author int64 658 755k | date stringlengths 19 19 | timezone int64 -46,800 43.2k | hash stringlengths 40 40 | message stringlengths 5 490 | mods list | language stringclasses 20 values | license stringclasses 3 values | repo stringlengths 5 68 | original_message stringlengths 12 491 |
|---|---|---|---|---|---|---|---|---|---|
260,335 | 30.06.2020 22:19:16 | 25,200 | 107689e91f0940327a807e2a9890da3071e6feac | improve vmap axis spec structure mismatch errors
* improve vmap axis spec structure mismatch errors
fixes
* deflake | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -867,10 +867,11 @@ def vmap(fun: Callable, in_axes=0, out_axes=0) -> Callable:\nargs_flat, in_tree = tree_flatten(args)\nf = lu.wrap_init(fun)\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\n- in_axes_flat = flatten_axes(in_tree, in_axes)\n+ in_axes_flat = flatten_axes(\"vmap in_axes\", in_tree, in_axes)\n_ = _mapped_axis_size(in_tree, args_flat, in_axes_flat, \"vmap\")\nout_flat = batching.batch(flat_fun, args_flat, in_axes_flat,\n- lambda: flatten_axes(out_tree(), out_axes))\n+ lambda: flatten_axes(\"vmap out_axes\", out_tree(),\n+ out_axes))\nreturn tree_unflatten(out_tree(), out_flat)\nreturn batched_fun\n@@ -1152,7 +1153,7 @@ def pmap(fun: Callable, axis_name: Optional[AxisName] = None, *, in_axes=0,\ndyn_args, dyn_in_axes = args, in_axes\nargs, in_tree = tree_flatten((dyn_args, kwargs))\ndonated_invars = donation_vector(donate_tuple, dyn_args, kwargs)\n- in_axes_flat = flatten_axes(in_tree, (dyn_in_axes, 0))\n+ in_axes_flat = flatten_axes(\"pmap in_axes\", in_tree, (dyn_in_axes, 0))\nlocal_axis_size = _mapped_axis_size(in_tree, args, in_axes_flat, \"pmap\")\nfor arg in args: _check_arg(arg)\nflat_fun, out_tree = flatten_fun(f, in_tree)\n@@ -1191,7 +1192,7 @@ def soft_pmap(fun: Callable, axis_name: Optional[AxisName] = None, *,\ndef f_pmapped(*args, **kwargs):\nf = lu.wrap_init(fun)\nargs_flat, in_tree = tree_flatten((args, kwargs))\n- in_axes_flat = flatten_axes(in_tree, (in_axes, 0))\n+ in_axes_flat = flatten_axes(\"soft_pmap in_axes\", in_tree, (in_axes, 0))\nmapped_invars = tuple(axis is not None for axis in in_axes_flat)\naxis_size = _mapped_axis_size(in_tree, args_flat, in_axes_flat, \"soft_pmap\")\nfor arg in args_flat: _check_arg(arg)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/api_util.py",
"new_path": "jax/api_util.py",
"diff": "@@ -143,7 +143,7 @@ def _argnums_partial(dyn_argnums, fixed_args, *dyn_args, **kwargs):\nans = yield args, kwargs\nyield ans\n-def flatten_axes(treedef, axis_tree):\n+def flatten_axes(name, treedef, axis_tree):\n# given an axis spec tree axis_tree (a pytree with integers and Nones at the\n# leaves, i.e. the Nones are to be considered leaves) that is a tree prefix of\n# the given treedef, build a complete axis spec tree with the same structure\n@@ -155,10 +155,10 @@ def flatten_axes(treedef, axis_tree):\nadd_leaves = lambda i, x: axes.extend([i] * len(tree_flatten(x)[0]))\ntry:\ntree_multimap(add_leaves, _replace_nones(proxy, axis_tree), dummy)\n- except ValueError as e:\n- msg = (\"axes specification must be a tree prefix of the corresponding \"\n- \"value, got specification {} for value {}.\")\n- raise ValueError(msg.format(axis_tree, treedef)) from e\n+ except ValueError:\n+ raise ValueError(f\"{name} specification must be a tree prefix of the \"\n+ f\"corresponding value, got specification {axis_tree} \"\n+ f\"for value tree {treedef}.\") from None\naxes = [None if a is proxy else a for a in axes]\nassert len(axes) == treedef.num_leaves\nreturn axes\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/sharded_jit.py",
"new_path": "jax/interpreters/sharded_jit.py",
"diff": "@@ -267,11 +267,13 @@ def sharded_jit(fun: Callable, in_parts, out_parts, num_partitions: int = None):\nraise NotImplementedError(\"sharded_jit over kwargs not yet supported\")\nf = lu.wrap_init(fun)\nargs_flat, in_tree = tree_flatten((args, kwargs))\n- in_parts_flat = tuple(flatten_axes(in_tree.children()[0], in_parts))\n+ in_parts_flat = tuple(flatten_axes(\"sharded_jit in_parts\",\n+ in_tree.children()[0], in_parts))\nflat_fun, out_tree = flatten_fun(f, in_tree)\n# TODO(skye): having a function-typed param in a primitive seems dicey, is\n# there a better way?\n- out_parts_thunk = lambda: tuple(flatten_axes(out_tree(), out_parts))\n+ out_parts_thunk = lambda: tuple(flatten_axes(\"sharded_jit out_parts\",\n+ out_tree(), out_parts))\nout = sharded_call(\nflat_fun,\n*args_flat,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1073,8 +1073,8 @@ class APITest(jtu.JaxTestCase):\n# https://github.com/google/jax/issues/795\nself.assertRaisesRegex(\nValueError,\n- \"axes specification must be a tree prefix of the corresponding \"\n- r\"value, got specification \\(0, 0\\) for value \"\n+ \"vmap in_axes specification must be a tree prefix of the corresponding \"\n+ r\"value, got specification \\(0, 0\\) for value tree \"\nr\"PyTreeDef\\(tuple, \\[\\*\\]\\).\",\nlambda: api.vmap(lambda x: x, in_axes=(0, 0))(jnp.ones(3))\n)\n@@ -1148,7 +1148,9 @@ class APITest(jtu.JaxTestCase):\n# Error is: TypeError: only integer scalar arrays can be converted to a scalar index\nwith self.assertRaisesRegex(\n- ValueError, \"axes specification must be a tree prefix of the corresponding value\"):\n+ ValueError,\n+ \"vmap out_axes specification must be a tree prefix of the \"\n+ \"corresponding value.*\"):\napi.vmap(lambda x: x, in_axes=0, out_axes=(2, 3))(jnp.array([1., 2.]))\nwith self.assertRaisesRegex(\n"
}
] | Python | Apache License 2.0 | google/jax | improve vmap axis spec structure mismatch errors (#3619)
* improve vmap axis spec structure mismatch errors
fixes #3613
* deflake |
260,335 | 01.07.2020 11:26:44 | 25,200 | ba1b5ce8de01985133ce0cf960c112ffb81dd7fb | skip some ode tests on gpu for speed | [
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -55,8 +55,7 @@ flags.DEFINE_integer(\nflags.DEFINE_bool(\n'jax_skip_slow_tests',\nbool_env('JAX_SKIP_SLOW_TESTS', False),\n- help=\n- 'Skip tests marked as slow (> 5 sec).'\n+ help='Skip tests marked as slow (> 5 sec).'\n)\nflags.DEFINE_string(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/ode_test.py",
"new_path": "tests/ode_test.py",
"diff": "@@ -123,7 +123,7 @@ class ODETest(jtu.JaxTestCase):\njtu.check_grads(integrate, (y0, ts, *args), modes=[\"rev\"], order=2,\nrtol=tol, atol=tol)\n- @jtu.skip_on_devices(\"tpu\")\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_swoop_bigger(self):\ndef swoop(_np, y, t, arg1, arg2):\nreturn _np.array(y - _np.sin(t) - _np.cos(t) * arg1 + arg2)\n@@ -139,6 +139,7 @@ class ODETest(jtu.JaxTestCase):\njtu.check_grads(integrate, (big_y0, ts, *args), modes=[\"rev\"], order=2,\nrtol=tol, atol=tol)\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_odeint_vmap_grad(self):\n# https://github.com/google/jax/issues/2531\n@@ -168,6 +169,7 @@ class ODETest(jtu.JaxTestCase):\nrtol = {jnp.float64: 2e-15}\nself.assertAllClose(ans, expected, check_dtypes=False, atol=atol, rtol=rtol)\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_disable_jit_odeint_with_vmap(self):\n# https://github.com/google/jax/issues/2598\nwith jax.disable_jit():\n@@ -176,7 +178,7 @@ class ODETest(jtu.JaxTestCase):\nf = lambda x0: odeint(lambda x, _t: x, x0, t)\njax.vmap(f)(x0_eval) # doesn't crash\n- @jtu.skip_on_devices(\"tpu\")\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_grad_closure(self):\n# simplification of https://github.com/google/jax/issues/2718\ndef experiment(x):\n@@ -186,7 +188,7 @@ class ODETest(jtu.JaxTestCase):\nreturn history[-1]\njtu.check_grads(experiment, (0.01,), modes=[\"rev\"], order=1)\n- @jtu.skip_on_devices(\"tpu\")\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_grad_closure_with_vmap(self):\n# https://github.com/google/jax/issues/2718\n@jax.jit\n@@ -207,6 +209,7 @@ class ODETest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False, atol=1e-2, rtol=1e-2)\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_forward_mode_error(self):\n# https://github.com/google/jax/issues/3558\n@@ -216,7 +219,7 @@ class ODETest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(TypeError, \"can't apply forward-mode.*\"):\njax.jacfwd(f)(3.)\n- @jtu.skip_on_devices(\"tpu\")\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_closure_nondiff(self):\n# https://github.com/google/jax/issues/3584\n"
}
] | Python | Apache License 2.0 | google/jax | skip some ode tests on gpu for speed (#3629) |
260,335 | 01.07.2020 12:22:39 | 25,200 | 1bd04e2d2f3ed0cbbe4dae8bfec09651930db66c | skip gamma tests on tpu for compilation speed | [
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -402,6 +402,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nnp.array([0.2, 1., 5.]),\n]\nfor dtype in [np.float32, np.float64]))\n+ @jtu.skip_on_devices(\"tpu\") # TODO(mattjj): slow compilation times\ndef testDirichlet(self, alpha, dtype):\nkey = random.PRNGKey(0)\nrand = lambda key, alpha: random.dirichlet(key, alpha, (10000,), dtype)\n@@ -437,6 +438,7 @@ class LaxRandomTest(jtu.JaxTestCase):\n\"a\": a, \"dtype\": np.dtype(dtype).name}\nfor a in [0.1, 1., 10.]\nfor dtype in [np.float32, np.float64]))\n+ @jtu.skip_on_devices(\"tpu\") # TODO(mattjj): slow compilation times\ndef testGamma(self, a, dtype):\nkey = random.PRNGKey(0)\nrand = lambda key, a: random.gamma(key, a, (10000,), dtype)\n"
}
] | Python | Apache License 2.0 | google/jax | skip gamma tests on tpu for compilation speed (#3631) |
260,335 | 01.07.2020 14:15:48 | 25,200 | 65c4d755def093ab9c4388d04b10a6ff0f3178f6 | fix bug in categorical test, disable on tpu
* fix bug in categorical test, disable on tpu
Disabling on TPU pending a TPU compilation bug.
* unskip a test | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -4363,6 +4363,10 @@ ad.defjvp_zero(argmin_p)\nxla.backend_specific_translations['gpu'][argmin_p] = xla.lower_fun(\npartial(_argminmax_gpu_translation_rule, _reduce_min),\nmultiple_results=False)\n+# TODO(mattjj,phawkins): remove this rule when TPU compile time issue resolved\n+xla.backend_specific_translations['tpu'][argmin_p] = xla.lower_fun(\n+ partial(_argminmax_gpu_translation_rule, _reduce_min),\n+ multiple_results=False)\nargmax_p = standard_primitive(_argminmax_shape_rule, _argminmax_dtype_rule,\n'argmax', _argmax_translation_rule)\n@@ -4371,6 +4375,10 @@ ad.defjvp_zero(argmax_p)\nxla.backend_specific_translations['gpu'][argmax_p] = xla.lower_fun(\npartial(_argminmax_gpu_translation_rule, _reduce_max),\nmultiple_results=False)\n+# TODO(mattjj,phawkins): remove this rule when TPU compile time issue resolved\n+xla.backend_specific_translations['tpu'][argmax_p] = xla.lower_fun(\n+ partial(_argminmax_gpu_translation_rule, _reduce_max),\n+ multiple_results=False)\ndef _reduce_logical_shape_rule(operand, *, axes):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -336,11 +336,11 @@ class LaxRandomTest(jtu.JaxTestCase):\nlogits = np.log(p) - 42 # test unnormalized\nout_shape = tuple(np.delete(logits.shape, axis))\nshape = sample_shape + out_shape\n- rand = lambda key, p: random.categorical(key, logits, shape=shape, axis=axis)\n+ rand = partial(random.categorical, shape=shape, axis=axis)\ncrand = api.jit(rand)\n- uncompiled_samples = rand(key, p)\n- compiled_samples = crand(key, p)\n+ uncompiled_samples = rand(key, logits)\n+ compiled_samples = crand(key, logits)\nif axis < 0:\naxis += len(logits.shape)\n@@ -438,7 +438,6 @@ class LaxRandomTest(jtu.JaxTestCase):\n\"a\": a, \"dtype\": np.dtype(dtype).name}\nfor a in [0.1, 1., 10.]\nfor dtype in [np.float32, np.float64]))\n- @jtu.skip_on_devices(\"tpu\") # TODO(mattjj): slow compilation times\ndef testGamma(self, a, dtype):\nkey = random.PRNGKey(0)\nrand = lambda key, a: random.gamma(key, a, (10000,), dtype)\n"
}
] | Python | Apache License 2.0 | google/jax | fix bug in categorical test, disable #3611 on tpu (#3633)
* fix bug in categorical test, disable #3611 on tpu
Disabling #3611 on TPU pending a TPU compilation bug.
* unskip a test |
260,411 | 02.07.2020 10:21:23 | -10,800 | 448c635a9ea00f32b2c20c277a49f62ea9029f3b | [jax2tf] Update the tf-nightly version to 2020-07-01 | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/ci-build.yaml",
"new_path": ".github/workflows/ci-build.yaml",
"diff": "@@ -52,6 +52,7 @@ jobs:\n- python-version: 3.6\nos: ubuntu-latest\nenable-x64: enable-x64\n+ # Test with numpy version that matches Google-internal version\npackage-overrides: \"numpy==1.16.4\"\nnum_generated_cases: 10\nsteps:\n"
},
{
"change_type": "MODIFY",
"old_path": "build/test-requirements.txt",
"new_path": "build/test-requirements.txt",
"diff": "@@ -4,6 +4,6 @@ msgpack\nmypy==0.770\npytest-benchmark\npytest-xdist\n-# jax2tf needs some fixes that are not in tensorflow==2.2.0\n-tf-nightly==2.3.0.dev20200624\n+# jax2tf needs some fixes that are not in latest tensorflow\n+tf-nightly==2.4.0.dev20200701\nwheel\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Update the tf-nightly version to 2020-07-01 (#3635) |
260,411 | 02.07.2020 10:33:00 | -10,800 | a5ed161550825f3b3c52b764b39db8e15b4c9f1e | Release jaxlib 0.1.51 | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -28,10 +28,10 @@ http_archive(\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"3e2387ae5d069de6fe1ccd4faa8d0dc1d63799d59df10f5bb93d03152ba9b158\",\n- strip_prefix = \"tensorflow-ed7033c7fc2787aa50fae345fc1be4030608b54f\",\n+ sha256 = \"ab1b8edb072269a4a513385fbf03a6dc2a22cda5f7cb833aa4962e692d3caf61\",\n+ strip_prefix = \"tensorflow-62b6c316d2a9a1fb06aefb086856e76241280c08\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/ed7033c7fc2787aa50fae345fc1be4030608b54f.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/62b6c316d2a9a1fb06aefb086856e76241280c08.tar.gz\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/CHANGELOG.rst",
"new_path": "docs/CHANGELOG.rst",
"diff": "@@ -8,6 +8,11 @@ Change Log\n.. PLEASE REMEMBER TO CHANGE THE '..master' WITH AN ACTUAL TAG in GITHUB LINK.\nThese are the release notes for JAX.\n+jaxlib 0.1.51 (July 2, 2020)\n+------------------------------\n+\n+* Update XLA.\n+* Add new runtime support for host_callback.\njax 0.1.72 (June 28, 2020)\n---------------------------\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/version.py",
"new_path": "jaxlib/version.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-__version__ = \"0.1.50\"\n+__version__ = \"0.1.51\"\n"
}
] | Python | Apache License 2.0 | google/jax | Release jaxlib 0.1.51 (#3636) |
260,411 | 02.07.2020 12:47:22 | -10,800 | bfe8f8732b9b90a3a0e7d79c40964b759833bdea | Change the version of tensorflow, the one in jaxlib 0.1.51 does not build | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -28,10 +28,10 @@ http_archive(\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"ab1b8edb072269a4a513385fbf03a6dc2a22cda5f7cb833aa4962e692d3caf61\",\n- strip_prefix = \"tensorflow-62b6c316d2a9a1fb06aefb086856e76241280c08\",\n+ sha256 = \"183e4a234507efb86afbd1c6c961efa6bc384e084b7cfd3b914cf21e33a31a82\",\n+ strip_prefix = \"tensorflow-daea038a3d0df3234385fc3a97fc8f35d1a307a8\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/62b6c316d2a9a1fb06aefb086856e76241280c08.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/daea038a3d0df3234385fc3a97fc8f35d1a307a8.tar.gz\",\n],\n)\n"
}
] | Python | Apache License 2.0 | google/jax | Change the version of tensorflow, the one in jaxlib 0.1.51 does not build (#3637) |
260,411 | 02.07.2020 18:53:58 | -10,800 | 166e795d638349530accacb1a48261203b29ae67 | Updated minimum jaxlib to 0.1.51 | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -410,7 +410,7 @@ PYTHON_VERSION=cp37 # alternatives: cp36, cp37, cp38\nCUDA_VERSION=cuda100 # alternatives: cuda100, cuda101, cuda102, cuda110\nPLATFORM=manylinux2010_x86_64 # alternatives: manylinux2010_x86_64\nBASE_URL='https://storage.googleapis.com/jax-releases'\n-pip install --upgrade $BASE_URL/$CUDA_VERSION/jaxlib-0.1.50-$PYTHON_VERSION-none-$PLATFORM.whl\n+pip install --upgrade $BASE_URL/$CUDA_VERSION/jaxlib-0.1.51-$PYTHON_VERSION-none-$PLATFORM.whl\npip install --upgrade jax # install jax\n```\n@@ -448,7 +448,7 @@ requires Python 3.6 or above. Jax does not support Python 2 any more.\nTo try automatic detection of the correct version for your system, you can run:\n```bash\n-pip install --upgrade https://storage.googleapis.com/jax-releases/`nvidia-smi | sed -En \"s/.* CUDA Version: ([0-9]*)\\.([0-9]*).*/cuda\\1\\2/p\"`/jaxlib-0.1.50-`python3 -V | sed -En \"s/Python ([0-9]*)\\.([0-9]*).*/cp\\1\\2/p\"`-none-manylinux2010_x86_64.whl jax\n+pip install --upgrade https://storage.googleapis.com/jax-releases/`nvidia-smi | sed -En \"s/.* CUDA Version: ([0-9]*)\\.([0-9]*).*/cuda\\1\\2/p\"`/jaxlib-0.1.51-`python3 -V | sed -En \"s/Python ([0-9]*)\\.([0-9]*).*/cp\\1\\2/p\"`-none-manylinux2010_x86_64.whl jax\n```\nPlease let us know on [the issue tracker](https://github.com/google/jax/issues)\n"
},
{
"change_type": "MODIFY",
"old_path": "build/test-requirements.txt",
"new_path": "build/test-requirements.txt",
"diff": "flake8\n-jaxlib==0.1.48\n+jaxlib==0.1.51\nmsgpack\nmypy==0.770\npytest-benchmark\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lib/__init__.py",
"new_path": "jax/lib/__init__.py",
"diff": "@@ -22,7 +22,7 @@ __all__ = [\nimport jaxlib\n-_minimum_jaxlib_version = (0, 1, 48)\n+_minimum_jaxlib_version = (0, 1, 51)\ntry:\nfrom jaxlib import version as jaxlib_version\nexcept Exception as err:\n"
}
] | Python | Apache License 2.0 | google/jax | Updated minimum jaxlib to 0.1.51 (#3642) |
260,335 | 02.07.2020 14:29:17 | 25,200 | d10cf0e38f9281e16e7e84fa4fe289f6c5ae2654 | fix prng key reuse in differential privacy example
fix prng key reuse in differential privacy example | [
{
"change_type": "MODIFY",
"old_path": "examples/differentially_private_sgd.py",
"new_path": "examples/differentially_private_sgd.py",
"diff": "@@ -64,7 +64,6 @@ Example invocations:\n--learning_rate=.25 \\\n\"\"\"\n-from functools import partial\nimport itertools\nimport time\nimport warnings\n@@ -75,18 +74,17 @@ from absl import flags\nfrom jax import grad\nfrom jax import jit\nfrom jax import random\n-from jax import tree_util\nfrom jax import vmap\nfrom jax.experimental import optimizers\nfrom jax.experimental import stax\n-from jax.lax import stop_gradient\n+from jax.tree_util import tree_flatten, tree_unflatten\nimport jax.numpy as jnp\nfrom examples import datasets\nimport numpy.random as npr\n# https://github.com/tensorflow/privacy\n-from privacy.analysis.rdp_accountant import compute_rdp\n-from privacy.analysis.rdp_accountant import get_privacy_spent\n+from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp\n+from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent\nFLAGS = flags.FLAGS\n@@ -134,33 +132,30 @@ def accuracy(params, batch):\nreturn jnp.mean(predicted_class == target_class)\n-def private_grad(params, batch, rng, l2_norm_clip, noise_multiplier,\n- batch_size):\n- \"\"\"Return differentially private gradients for params, evaluated on batch.\"\"\"\n-\n- def _clipped_grad(params, single_example_batch):\n+def clipped_grad(params, l2_norm_clip, single_example_batch):\n\"\"\"Evaluate gradient for a single-example batch and clip its grad norm.\"\"\"\ngrads = grad(loss)(params, single_example_batch)\n-\n- nonempty_grads, tree_def = tree_util.tree_flatten(grads)\n+ nonempty_grads, tree_def = tree_flatten(grads)\ntotal_grad_norm = jnp.linalg.norm(\n[jnp.linalg.norm(neg.ravel()) for neg in nonempty_grads])\n- divisor = stop_gradient(jnp.amax((total_grad_norm / l2_norm_clip, 1.)))\n+ divisor = jnp.max((total_grad_norm / l2_norm_clip, 1.))\nnormalized_nonempty_grads = [g / divisor for g in nonempty_grads]\n- return tree_util.tree_unflatten(tree_def, normalized_nonempty_grads)\n-\n- px_clipped_grad_fn = vmap(partial(_clipped_grad, params))\n- std_dev = l2_norm_clip * noise_multiplier\n- noise_ = lambda n: n + std_dev * random.normal(rng, n.shape)\n- normalize_ = lambda n: n / float(batch_size)\n- tree_map = tree_util.tree_map\n- sum_ = lambda n: jnp.sum(n, 0) # aggregate\n- aggregated_clipped_grads = tree_map(sum_, px_clipped_grad_fn(batch))\n- noised_aggregated_clipped_grads = tree_map(noise_, aggregated_clipped_grads)\n- normalized_noised_aggregated_clipped_grads = (\n- tree_map(normalize_, noised_aggregated_clipped_grads)\n- )\n- return normalized_noised_aggregated_clipped_grads\n+ return tree_unflatten(tree_def, normalized_nonempty_grads)\n+\n+\n+def private_grad(params, batch, rng, l2_norm_clip, noise_multiplier,\n+ batch_size):\n+ \"\"\"Return differentially private gradients for params, evaluated on batch.\"\"\"\n+ clipped_grads = vmap(clipped_grad, (None, None, 0))(params, l2_norm_clip, batch)\n+ clipped_grads_flat, grads_treedef = tree_flatten(clipped_grads)\n+ aggregated_clipped_grads = [g.sum(0) for g in clipped_grads_flat]\n+ rngs = random.split(rng, len(aggregated_clipped_grads))\n+ noised_aggregated_clipped_grads = [\n+ g + l2_norm_clip * noise_multiplier * random.normal(r, g.shape)\n+ for r, g in zip(rngs, aggregated_clipped_grads)]\n+ normalized_noised_aggregated_clipped_grads = [\n+ g / batch_size for g in noised_aggregated_clipped_grads]\n+ return tree_unflatten(grads_treedef, normalized_noised_aggregated_clipped_grads)\ndef shape_as_image(images, labels, dummy_dim=False):\n@@ -225,7 +220,6 @@ def main(_):\nprint('\\nStarting training...')\nfor epoch in range(1, FLAGS.epochs + 1):\nstart_time = time.time()\n- # pylint: disable=no-value-for-parameter\nfor _ in range(num_batches):\nif FLAGS.dpsgd:\nopt_state = \\\n@@ -235,7 +229,6 @@ def main(_):\nelse:\nopt_state = update(\nkey, next(itercount), opt_state, shape_as_image(*next(batches)))\n- # pylint: enable=no-value-for-parameter\nepoch_time = time.time() - start_time\nprint('Epoch {} in {:0.2f} sec'.format(epoch, epoch_time))\n"
}
] | Python | Apache License 2.0 | google/jax | fix prng key reuse in differential privacy example (#3646)
fix prng key reuse in differential privacy example |
260,335 | 03.07.2020 10:00:25 | 25,200 | 796df9c550618c15dfec157af306b08fe58eac13 | make psum transpose handle zero cotangents
make psum transpose handle zero cotangents
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -364,6 +364,12 @@ def _notuple_psum_translation_rule(c, *args, replica_groups):\nreturn psum(val)\nreturn xops.Tuple(c, list(map(_translate, args)))\n+def _psum_transpose_rule(cts, axis_name, axis_index_groups):\n+ nonzero_out_cts, treedef = tree_util.tree_flatten(cts)\n+ nonzero_in_cts = psum_p.bind(*nonzero_out_cts, axis_name=axis_name,\n+ axis_index_groups=axis_index_groups)\n+ return tree_util.tree_unflatten(treedef, nonzero_in_cts)\n+\npsum_p = standard_pmap_primitive('psum', multiple_results=True)\npsum_p.def_abstract_eval(\nlambda *args, **params: tuple(map(raise_to_shaped, args)))\n@@ -371,8 +377,7 @@ pxla.split_axis_rules[psum_p] = \\\npartial(_allreduce_split_axis_rule, psum_p, lax._reduce_sum)\nxla.parallel_translations[psum_p] = _psum_translation_rule\npxla.parallel_pure_rules[psum_p] = lambda *args, shape: (x * prod(shape) for x in args)\n-ad.deflinear(psum_p, lambda ts, axis_name, axis_index_groups: psum_p.bind(\n- *ts, axis_name=axis_name, axis_index_groups=axis_index_groups))\n+ad.deflinear(psum_p, _psum_transpose_rule)\npxla.multi_host_supported_collectives.add(psum_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -1290,6 +1290,30 @@ class PmapTest(jtu.JaxTestCase):\nself.assertIn(\"The jitted function foo includes a pmap\",\nstr(w[-1].message))\n+ def testPsumZeroCotangents(self):\n+ # https://github.com/google/jax/issues/3651\n+ def loss(params, meta_params):\n+ (net, mpo) = params\n+ return meta_params * mpo * net\n+\n+ def inner(meta_params, params):\n+ grads = jax.grad(loss)(params, meta_params)\n+ grads = lax.psum(grads, axis_name=\"i\")\n+ net_grads, mpo_grads = grads\n+ net = params[0] + net_grads\n+ mpo = params[1]\n+ return mpo * net\n+\n+ def outer(params):\n+ meta_params = jnp.array(4.0)\n+ return jax.grad(inner)(meta_params, params)\n+\n+ params = (jnp.array([2.0]), jnp.array([3.0]))\n+ jax.pmap(outer, axis_name='i')(params) # doesn't crash\n+\n+ f = jax.pmap(outer, axis_name='i')\n+ jtu.check_grads(f, (params,), 2, [\"fwd\", \"rev\"], 1e-3, 1e-3)\n+\nclass VmapOfPmapTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | make psum transpose handle zero cotangents (#3653)
make psum transpose handle zero cotangents
fixes #3651 |
260,335 | 03.07.2020 20:54:25 | 25,200 | 49cfe2687c9a23d355c799a01a931280e44e6018 | improve concreteness error message for nn.one_hot
* improve nn.one_hot and jax.numpy.arange errors
fixes
* deflake
* debug | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -831,17 +831,15 @@ def concretization_function_error(fun, context=\"\"):\nreturn error\n-def concrete_or_error(typ: Type, val: Any, context=\"\"):\n- \"\"\"Like typ(val), but gives the context in the error message.\n- Use with typ either `int`, or `bool`.\n- \"\"\"\n+def concrete_or_error(force: Any, val: Any, context=\"\"):\n+ \"\"\"Like force(val), but gives the context in the error message.\"\"\"\nif isinstance(val, Tracer):\nif isinstance(val.aval, ConcreteArray):\n- return typ(val.aval.val)\n+ return force(val.aval.val)\nelse:\nraise_concretization_error(val, context)\nelse:\n- return typ(val)\n+ return force(val)\nclass UnshapedArray(AbstractValue):\n__slots__ = ['dtype', 'weak_type']\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/nn/functions.py",
"new_path": "jax/nn/functions.py",
"diff": "@@ -20,6 +20,7 @@ import numpy as np\nfrom jax import custom_jvp\nfrom jax import dtypes\nfrom jax import lax\n+from jax import core\nfrom jax.scipy.special import expit\nimport jax.numpy as jnp\n@@ -263,6 +264,8 @@ def one_hot(x, num_classes, *, dtype=jnp.float64):\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n\"\"\"\n+ num_classes = core.concrete_or_error(int, num_classes,\n+ \"in jax.nn.one_hot argument `num_classes`\")\ndtype = dtypes.canonicalize_dtype(dtype)\nx = jnp.asarray(x)\nlhs = x[..., jnp.newaxis]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2282,10 +2282,16 @@ def identity(n, dtype=None):\n@_wraps(np.arange)\ndef arange(start, stop=None, step=None, dtype=None):\nlax._check_user_dtype_supported(dtype, \"arange\")\n+ require = partial(core.concrete_or_error, np.asarray)\n+ msg = \"in jax.numpy.arange argument `{}`\".format\nif stop is None and step is None:\n+ start = require(start, msg(\"stop\"))\ndtype = dtype or _dtype(start)\nreturn lax.iota(dtype, np.ceil(start)) # avoids materializing\nelse:\n+ start = None if start is None else require(start, msg(\"start\"))\n+ stop = None if stop is None else require(stop, msg(\"stop\"))\n+ step = None if step is None else require(step, msg(\"step\"))\nreturn array(np.arange(start, stop=stop, step=step, dtype=dtype))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -3826,6 +3826,17 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, r\"duplicate value in 'axis': \\(0, 0\\)\"):\njnp.sum(jnp.arange(3), (0, 0))\n+ def testArangeConcretizationError(self):\n+ msg = r\"Abstract tracer.*\\(in jax.numpy.arange argument `{}`\\).*\".format\n+ with self.assertRaisesRegex(jax.core.ConcretizationTypeError, msg('stop')):\n+ jax.jit(jnp.arange)(3)\n+\n+ with self.assertRaisesRegex(jax.core.ConcretizationTypeError, msg('start')):\n+ jax.jit(lambda start: jnp.arange(start, 3))(0)\n+\n+ with self.assertRaisesRegex(jax.core.ConcretizationTypeError, msg('stop')):\n+ jax.jit(lambda stop: jnp.arange(0, stop))(3)\n+\n# Most grad tests are at the lax level (see lax_test.py), but we add some here\n# as needed for e.g. particular compound ops of interest.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/nn_test.py",
"new_path": "tests/nn_test.py",
"diff": "@@ -148,6 +148,13 @@ class NNFunctionsTest(jtu.JaxTestCase):\n[False, False, True]])\nself.assertAllClose(actual, expected)\n+ def testOneHotConcretizationError(self):\n+ # https://github.com/google/jax/issues/3654\n+ msg = r\"Abstract tracer.*\\(in jax.nn.one_hot argument `num_classes`\\).*\"\n+ with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n+ jax.jit(nn.one_hot)(3, 5)\n+\n+\nInitializerRecord = collections.namedtuple(\n\"InitializerRecord\",\n[\"name\", \"initializer\", \"shapes\"])\n"
}
] | Python | Apache License 2.0 | google/jax | improve concreteness error message for nn.one_hot (#3656)
* improve nn.one_hot and jax.numpy.arange errors
fixes #3654
* deflake
* debug |
260,411 | 06.07.2020 09:04:02 | -10,800 | 8f93607330b36f1bfdb8e030657b6d73452d0cb3 | Fix broken links to deleted notebook
Fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/tree_util.py",
"new_path": "jax/tree_util.py",
"diff": "@@ -31,7 +31,7 @@ The primary purpose of this module is to enable the interoperability between\nuser defined data structures and JAX transformations (e.g. `jit`). This is not\nmeant to be a general purpose tree-like data structure handling library.\n-See the `JAX pytrees notebook <https://jax.readthedocs.io/en/latest/notebooks/JAX_pytrees.html>`_\n+See the `JAX pytrees note <pytrees.html>`_\nfor examples.\n\"\"\"\n@@ -112,7 +112,7 @@ def all_leaves(iterable):\ndef register_pytree_node(nodetype, flatten_func, unflatten_func):\n\"\"\"Extends the set of types that are considered internal nodes in pytrees.\n- See `example usage <https://jax.readthedocs.io/en/latest/notebooks/JAX_pytrees.html#Pytrees-are-extensible>`_.\n+ See `example usage <pytrees.html>`_.\nArgs:\nnodetype: a Python type to treat as an internal pytree node.\n"
}
] | Python | Apache License 2.0 | google/jax | Fix broken links to deleted notebook (#3663)
Fixes #3662. |
260,335 | 06.07.2020 15:11:01 | 25,200 | e5ba5f1e6707fde12b3d95de0bd71da8a2dd453b | support multiple_results and custom JVPs in jet | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -26,6 +26,7 @@ from jax.tree_util import (register_pytree_node, tree_structure,\ntreedef_is_leaf, tree_flatten, tree_unflatten)\nimport jax.linear_util as lu\nfrom jax.interpreters import xla\n+from jax.custom_derivatives import custom_jvp_call_jaxpr_p\nfrom jax.lax import lax\nfrom jax.lax import lax_fft\n@@ -113,7 +114,6 @@ class JetTrace(core.Trace):\nreturn JetTracer(self, val.primal, val.terms)\ndef process_primitive(self, primitive, tracers, params):\n- assert not primitive.multiple_results # TODO\norder = self.master.order # pytype: disable=attribute-error\nprimals_in, series_in = unzip2((t.primal, t.terms) for t in tracers)\nseries_in = [[zero_term] * order if s is zero_series else s\n@@ -124,7 +124,10 @@ class JetTrace(core.Trace):\nfor x, series in zip(primals_in, series_in)]\nrule = jet_rules[primitive]\nprimal_out, terms_out = rule(primals_in, series_in, **params)\n+ if not primitive.multiple_results:\nreturn JetTracer(self, primal_out, terms_out)\n+ else:\n+ return [JetTracer(self, p, ts) for p, ts in zip(primal_out, terms_out)]\ndef process_call(self, call_primitive, f, tracers, params):\nprimals_in, series_in = unzip2((t.primal, t.terms) for t in tracers)\n@@ -547,3 +550,10 @@ def _lax_min_taylor_rule(primal_in, series_in):\nseries_out = [select_min_and_avg_eq(*terms_in) for terms_in in zip(*series_in)]\nreturn primal_out, series_out\njet_rules[lax.min_p] = _lax_min_taylor_rule\n+\n+def _custom_jvp_call_jaxpr_rule(primals_in, series_in, *, fun_jaxpr,\n+ jvp_jaxpr_thunk):\n+ # TODO(mattjj): do something better than ignoring custom jvp rules for jet?\n+ del jvp_jaxpr_thunk\n+ return jet(core.jaxpr_as_fun(fun_jaxpr), primals_in, series_in)\n+jet_rules[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_rule\n"
}
] | Python | Apache License 2.0 | google/jax | support multiple_results and custom JVPs in jet (#3657) |
260,335 | 07.07.2020 00:30:08 | 25,200 | d2ebb6eb19b0a824303e22a492d4b72f15ba1d88 | fix ppermute test bugs found by | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -196,29 +196,26 @@ def ppermute(x, axis_name, perm):\npartial(ppermute_p.bind, axis_name=axis_name, perm=tuple(perm)), x)\ndef pshuffle(x, axis_name, perm):\n- \"\"\"Perform a collective shuffle according to the permutation ``perm``.\n+ \"\"\"Convenience wrapper of jax.lax.ppermute with alternate permutation encoding\nIf ``x`` is a pytree then the result is equivalent to mapping this function to\neach leaf in the tree.\n- This function is a simple wrapper around jax.lax.ppermute.\n-\nArgs:\nx: array(s) with a mapped axis named ``axis_name``.\naxis_name: hashable Python object used to name a pmapped axis (see the\n:func:`jax.pmap` documentation for more details).\n- perm: list of of ints, representing the new order of the source indices\n- that encode how the mapped axis named ``axis_name`` should be\n- shuffled. The integer values are treated as indices into the mapped axis\n- ``axis_name``. Every int between 0 and ``len(perm)-1`` should be included.\n+ perm: list of of ints encoding sources for the permutation to be applied to\n+ the axis named ``axis_name``, so that the output at axis index i\n+ comes from the input at axis index perm[i]. Every integer in [0, N) should\n+ be included exactly once for axis size N.\nReturns:\nArray(s) with the same shape as ``x`` with slices along the axis\n``axis_name`` gathered from ``x`` according to the permutation ``perm``.\n\"\"\"\nif set(perm) != set(range(len(perm))):\n- raise AssertionError(\n- \"Given `perm` does not represent a real permutation: {}\".format(perm))\n+ raise ValueError(f\"`perm` does not represent a permutation: {perm}\")\nreturn ppermute(x, axis_name, list(zip(perm, range(len(perm)))))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -563,17 +563,25 @@ class PmapTest(jtu.JaxTestCase):\ng = lambda x: jnp.sum(y * pmap(f, 'i')(x))\nx = np.arange(device_count, dtype=np.float32)\n- ans = grad(g)(x)\n+\n+ ans = g(x)\nexpected = np.roll(np.pi + np.arange(device_count), 1)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ ans = grad(g)(x)\n+ expected = np.roll(np.pi + np.arange(device_count), -1)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ jtu.check_grads(f, (x,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, eps=1.)\n+ jtu.check_grads(g, (x,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2)\n+\n@jtu.skip_on_devices(\"cpu\")\ndef testCollectivePermuteCyclicWithPShuffle(self):\ndevice_count = xla_bridge.device_count()\nvalues = np.arange(device_count)\nshift_right = [(i - 1) % device_count for i in range(device_count)]\nf = lambda x: lax.pshuffle(x, perm=shift_right, axis_name='i')\n- expected = np.roll(values, -1)\n+ expected = np.roll(values, 1)\nans = np.asarray(pmap(f, \"i\")(values))\nself.assertAllClose(ans, expected, check_dtypes=False)\n@@ -593,8 +601,7 @@ class PmapTest(jtu.JaxTestCase):\n# https://github.com/google/jax/issues/1703\nnum_devices = xla_bridge.device_count()\nperm = [num_devices - 1] + list(range(num_devices - 1))\n- f = pmap(\n- lambda x: lax.ppermute(x, \"i\", zip(range(num_devices), perm)), \"i\")\n+ f = pmap(lambda x: lax.ppermute(x, \"i\", zip(perm, range(num_devices))), \"i\")\nresult = f(jnp.arange(num_devices, dtype=jnp.float32))\nexpected = jnp.asarray(perm, dtype=jnp.float32)\nself.assertAllClose(result, expected)\n"
}
] | Python | Apache License 2.0 | google/jax | fix ppermute test bugs found by @jekbradbury (#3675) |
260,335 | 07.07.2020 14:48:54 | 25,200 | 1034f29de778b288c32271cd283fb44e9b5adaf4 | fix bad pmap tests from | [
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -564,15 +564,10 @@ class PmapTest(jtu.JaxTestCase):\nx = np.arange(device_count, dtype=np.float32)\n- ans = g(x)\n- expected = np.roll(np.pi + np.arange(device_count), 1)\n- self.assertAllClose(ans, expected, check_dtypes=False)\n-\nans = grad(g)(x)\nexpected = np.roll(np.pi + np.arange(device_count), -1)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- jtu.check_grads(f, (x,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, eps=1.)\njtu.check_grads(g, (x,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2)\n@jtu.skip_on_devices(\"cpu\")\n"
}
] | Python | Apache License 2.0 | google/jax | fix bad pmap tests from #3675 (#3685) |
260,411 | 08.07.2020 16:08:54 | -10,800 | fdd7f0c8574b1e0e4366ee428153d73bc1788510 | Added concurrent id_tap tests, disabled for GPU | [
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -336,6 +336,77 @@ where: 3\nhcb.barrier_wait() # Wait for receivers to be done\nself.assertEqual(3, tap_count)\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list(\n+ dict(\n+ testcase_name=f\"_concurrent_{concurrent}\",\n+ concurrent=concurrent)\n+ for concurrent in [True, False]))\n+ def test_multiple_tap(self, concurrent=False):\n+ \"\"\"Call id_tap multiple times, concurrently or in sequence. \"\"\"\n+ if concurrent and jtu.device_under_test() == \"gpu\":\n+ # TODO(necula): it seems that on GPU if multiple host threads run\n+ # a jit computation, the mutliple computations are interleaved on the\n+ # GPU. This can result in the outfeed trains being interleaved, which\n+ # will trigger an error. The solution is to fix on GPU the receiving\n+ # logic so that we can outfeed the train as one tuple, and receive it\n+ # one piece as a time. Then the trains should be atomic.\n+ # See also b/160692602.\n+ raise SkipTest(\"concurrent id_tap not supported on GPU\")\n+ received = set()\n+ count = 5\n+ def pause_tap(idx, **kwargs):\n+ received.add(int(idx))\n+ logging.info(f\"Starting do_tap {idx}. Sleeping 1sec ...\")\n+ time.sleep(0.3)\n+ logging.info(f\"Finish do_tap {idx}\")\n+\n+ def do_tap(idx):\n+ api.jit(lambda idx: hcb.id_tap(pause_tap, idx))(idx)\n+\n+ if concurrent:\n+ threads = [\n+ threading.Thread(\n+ name=f\"enqueue_tap_{idx}\", target=do_tap, args=(idx,))\n+ for idx in range(count)\n+ ]\n+ [t.start() for t in threads]\n+ [t.join() for t in threads]\n+ else:\n+ for idx in range(count):\n+ do_tap(idx)\n+\n+ hcb.barrier_wait()\n+ self.assertEqual(received, set(range(count)))\n+\n+ # TODO(necula): see comment for test_multiple_tap.\n+ @jtu.skip_on_devices(\"gpu\")\n+ def test_multiple_barriers(self):\n+ \"\"\"Call barrier_wait concurrently.\"\"\"\n+\n+ def pause_tap(*args, **kwargs):\n+ logging.info(\"pause_tap waiting\")\n+ time.sleep(0.3)\n+ logging.info(\"pause_tap done\")\n+\n+ def long_run(x):\n+ return hcb.id_tap(pause_tap, x)\n+\n+ api.jit(long_run)(5.)\n+\n+ def try_barrier(idx):\n+ logging.info(f\"Starting test barrier {idx}\")\n+ hcb.barrier_wait()\n+ logging.info(f\"Finished test barrier {idx}\")\n+\n+ threads = [\n+ threading.Thread(\n+ name=f\"barrier_{idx}\", target=try_barrier, args=(idx,))\n+ for idx in range(3)\n+ ]\n+ [t.start() for t in threads]\n+ [t.join() for t in threads]\n+\n@parameterized.named_parameters(\njtu.cases_from_list(\ndict(\n@@ -917,32 +988,6 @@ what: x times i\nself.assertMultiLineStrippedEqual(expected, testing_stream.output)\n- def test_multiple_barriers(self):\n- \"\"\"Call barrier_wait concurrently.\"\"\"\n-\n- def pause_tap(*args, **kwargs):\n- logging.info(\"pause_tap waiting\")\n- time.sleep(2)\n- logging.info(\"pause_tap done\")\n-\n- def long_run(x):\n- return hcb.id_tap(pause_tap, x)\n-\n- api.jit(long_run)(5.)\n-\n- def try_barrier(idx):\n- logging.info(f\"Starting test barrier {idx}\")\n- hcb.barrier_wait()\n- logging.info(f\"Finished test barrier {idx}\")\n-\n- threads = [\n- threading.Thread(\n- name=f\"barrier_{idx}\", target=try_barrier, args=(idx,))\n- for idx in range(3)\n- ]\n- [t.start() for t in threads]\n- [t.join() for t in threads]\n-\ndef test_error_bad_consumer_id(self):\n\"\"\"Try to use reserved consumer ID 0.\n"
}
] | Python | Apache License 2.0 | google/jax | Added concurrent id_tap tests, disabled for GPU (#3690) |
260,651 | 10.07.2020 20:34:59 | -10,800 | 412b9d5209619c6cc6f5af7c6926cab24b919c3e | hfft and ihfft implementation | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -312,6 +312,8 @@ jax.numpy.fft\nirfft2\nrfftn\nirfftn\n+ hfft\n+ ihfft\nfftfreq\nrfftfreq\nfftshift\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/fft.py",
"new_path": "jax/numpy/fft.py",
"diff": "@@ -92,13 +92,16 @@ def irfftn(a, s=None, axes=None, norm=None):\nreturn _fft_core('irfftn', xla_client.FftType.IRFFT, a, s, axes, norm)\n-def _fft_core_1d(func_name, fft_type, a, s, axis, norm):\n+def _axis_check_1d(func_name, axis):\nfull_name = \"jax.numpy.fft.\" + func_name\nif isinstance(axis, (list, tuple)):\nraise ValueError(\n\"%s does not support multiple axes. Please use %sn. \"\n\"Got axis = %r.\" % (full_name, full_name, axis)\n)\n+\n+def _fft_core_1d(func_name, fft_type, a, s, axis, norm):\n+ _axis_check_1d(func_name, axis)\naxes = None if axis is None else [axis]\nreturn _fft_core(func_name, fft_type, a, s, axes, norm)\n@@ -123,6 +126,22 @@ def irfft(a, n=None, axis=-1, norm=None):\nreturn _fft_core_1d('irfft', xla_client.FftType.IRFFT, a, s=n, axis=axis,\nnorm=norm)\n+@_wraps(np.fft.hfft)\n+def hfft(a, n=None, axis=-1, norm=None):\n+ conj_a = jnp.conj(a)\n+ _axis_check_1d('hfft', axis)\n+ nn = (a.shape[axis] - 1) * 2 if n is None else n\n+ return _fft_core_1d('hfft', xla_client.FftType.IRFFT, conj_a, s=n, axis=axis,\n+ norm=norm) * nn\n+\n+@_wraps(np.fft.ihfft)\n+def ihfft(a, n=None, axis=-1, norm=None):\n+ _axis_check_1d('ihfft', axis)\n+ nn = a.shape[axis] if n is None else n\n+ output = _fft_core_1d('ihfft', xla_client.FftType.RFFT, a, s=n, axis=axis,\n+ norm=norm)\n+ return jnp.conj(output) * (1 / nn)\n+\ndef _fft_core_2d(func_name, fft_type, a, s, axes, norm):\nfull_name = \"jax.numpy.fft.\" + func_name\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/fft_test.py",
"new_path": "tests/fft_test.py",
"diff": "@@ -148,22 +148,27 @@ class FftTest(jtu.JaxTestCase):\nValueError, lambda: func(rng([2, 3], dtype=np.float64), axes=[-3]))\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_inverse={}_real={}_shape={}_axis={}\".format(\n- inverse, real, jtu.format_shape_dtype_string(shape, dtype), axis),\n+ {\"testcase_name\": \"_inverse={}_real={}_hermitian={}_shape={}_axis={}\".format(\n+ inverse, real, hermitian, jtu.format_shape_dtype_string(shape, dtype), axis),\n\"axis\": axis, \"shape\": shape, \"dtype\": dtype,\n- \"rng_factory\": rng_factory, \"inverse\": inverse, \"real\": real}\n+ \"rng_factory\": rng_factory, \"inverse\": inverse, \"real\": real,\n+ \"hermitian\": hermitian}\nfor inverse in [False, True]\nfor real in [False, True]\n+ for hermitian in [False, True]\nfor rng_factory in [jtu.rand_default]\n- for dtype in (real_dtypes if real and not inverse else all_dtypes)\n+ for dtype in (real_dtypes if (real and not inverse) or (hermitian and inverse)\n+ else all_dtypes)\nfor shape in [(10,)]\nfor axis in [-1, 0]))\n- def testFft(self, inverse, real, shape, dtype, axis, rng_factory):\n+ def testFft(self, inverse, real, hermitian, shape, dtype, axis, rng_factory):\nrng = rng_factory(self.rng())\nargs_maker = lambda: (rng(shape, dtype),)\nname = 'fft'\nif real:\nname = 'r' + name\n+ elif hermitian:\n+ name = 'h' + name\nif inverse:\nname = 'i' + name\njnp_op = getattr(jnp.fft, name)\n@@ -176,15 +181,18 @@ class FftTest(jtu.JaxTestCase):\nself._CompileAndCheck(jnp_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_inverse={}_real={}\".format(inverse, real),\n- \"inverse\": inverse, \"real\": real}\n+ {\"testcase_name\": \"_inverse={}_real={}_hermitian={}\".format(inverse, real, hermitian),\n+ \"inverse\": inverse, \"real\": real, \"hermitian\": hermitian}\nfor inverse in [False, True]\n- for real in [False, True]))\n- def testFftErrors(self, inverse, real):\n+ for real in [False, True]\n+ for hermitian in [False, True]))\n+ def testFftErrors(self, inverse, real, hermitian):\nrng = jtu.rand_default(self.rng())\nname = 'fft'\nif real:\nname = 'r' + name\n+ elif hermitian:\n+ name = 'h' + name\nif inverse:\nname = 'i' + name\nfunc = getattr(jnp.fft, name)\n"
}
] | Python | Apache License 2.0 | google/jax | hfft and ihfft implementation (#3664) |
260,335 | 11.07.2020 20:47:22 | 25,200 | 51ca57d5fc02abe486cecc1f1a5478bd2bf6a100 | check matmul inputs aren't scalar
also dot_general shape rule should check dimension numbers are in range
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2657,6 +2657,20 @@ def _precision_config(precision):\ndef _dot_general_shape_rule(lhs, rhs, *, dimension_numbers, precision):\n(lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers\n+ if not all(onp.all(onp.greater_equal(d, 0)) and onp.all(onp.less(d, lhs.ndim))\n+ for d in (lhs_contracting, lhs_batch)):\n+ msg = (\"dot_general requires lhs dimension numbers to be nonnegative and \"\n+ \"less than the number of axes of the lhs value, got \"\n+ f\"lhs_batch of {lhs_batch} and lhs_contracting of {lhs_contracting} \"\n+ f\"for lhs of rank {lhs.ndim}\")\n+ raise TypeError(msg)\n+ if not all(onp.all(onp.greater_equal(d, 0)) and onp.all(onp.less(d, rhs.ndim))\n+ for d in (rhs_contracting, rhs_batch)):\n+ msg = (\"dot_general requires rhs dimension numbers to be nonnegative and \"\n+ \"less than the number of axes of the rhs value, got \"\n+ f\"rhs_batch of {rhs_batch} and rhs_contracting of {rhs_contracting} \"\n+ f\"for rhs of rank {rhs.ndim}\")\n+ raise TypeError(msg)\nif len(lhs_batch) != len(rhs_batch):\nmsg = (\"dot_general requires equal numbers of lhs_batch and rhs_batch \"\n\"dimensions, got lhs_batch {} and rhs_batch {}.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2783,6 +2783,12 @@ def dot(a, b, *, precision=None): # pylint: disable=missing-docstring\n@_wraps(np.matmul, lax_description=_PRECISION_DOC)\ndef matmul(a, b, *, precision=None): # pylint: disable=missing-docstring\n_check_arraylike(\"matmul\", a, b)\n+ for i, x in enumerate((a, b)):\n+ if ndim(x) < 1:\n+ msg = (f\"matmul input operand {i} must have ndim at least 1, \"\n+ f\"but it has ndim {ndim(x)}\")\n+ raise ValueError(msg)\n+\na_is_vec, b_is_vec = (ndim(a) == 1), (ndim(b) == 1)\na = expand_dims(a, axis=0) if a_is_vec else a\nb = expand_dims(b, axis=-1) if b_is_vec else b\n"
}
] | Python | Apache License 2.0 | google/jax | check matmul inputs aren't scalar (#3725)
also dot_general shape rule should check dimension numbers are in range
fixes #3718 |
260,651 | 14.07.2020 01:31:47 | -10,800 | a6ab742f3635ed7c6d8c499c4be8aeb2a4181922 | Improve np.intersect1d | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1249,10 +1249,9 @@ def _intersect1d_sorted_mask(ar1, ar2, return_indices=False):\nHelper function for intersect1d which is jit-able\n\"\"\"\nar = concatenate((ar1, ar2))\n-\nif return_indices:\n- indices = argsort(ar)\n- aux = ar[indices]\n+ iota = lax.broadcasted_iota(np.int64, shape(ar), dimension=0)\n+ aux, indices = lax.sort_key_val(ar, iota)\nelse:\naux = sort(ar)\n"
}
] | Python | Apache License 2.0 | google/jax | Improve np.intersect1d (#3739) |
260,500 | 14.07.2020 18:37:09 | -3,600 | f6f97554f9c9689caccae8ff383a51620f0151f8 | A jit-able version of np.repeat.
A new keyword argument has been added to np.repeat, total_repeat_length, that can optionally be supplied to make np.repeat jit-able. | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2505,72 +2505,61 @@ def indices(dimensions, dtype=int32, sparse=False):\nreturn stack(output, 0) if output else array([], dtype=dtype)\n-def _repeat_scalar(a, repeats, axis=None):\n- if not isscalar(repeats):\n- raise NotImplementedError(\n- \"_repeat_scalar implementation only supports scalar repeats\")\n- if axis is None or isscalar(a) or len(shape(a)) == 0:\n- a = ravel(a)\n- axis = 0\n- a_shape = list(shape(a))\n- num_dims = len(a_shape)\n- if axis < 0:\n- axis = axis + num_dims\n-\n- if axis < 0 or axis >= num_dims:\n- raise ValueError(\n- \"axis {} is out of bounds for array of dimension {}\".format(\n- axis, num_dims))\n+_TOTAL_REPEAT_LENGTH_DOC = \"\"\"\\\n+Jax adds the optional `total_repeat_length` parameter which specifies the total\n+number of repeat, and defaults to sum(repeats). It must be specified for repeat\n+to be compilable. If `sum(repeats)` is larger than the specified\n+`total_repeat_length` the remaining values will be discarded. In the case of\n+`sum(repeats)` being smaller than the specified target length, the final value\n+will be repeated.\n+\"\"\"\n- # Broadcasts to [..., X, repeats, ...] and reshapes to [..., X * repeats, ...]\n- broadcast_shape = list(a_shape)\n- broadcast_shape.insert(axis + 1, repeats)\n- broadcast_dims = np.concatenate((np.arange(0, axis + 1),\n- np.arange(axis + 2, num_dims + 1)))\n- a_shape[axis] *= repeats\n- return lax.reshape(\n- lax.broadcast_in_dim(a, broadcast_shape, broadcast_dims),\n- a_shape)\n-\n-@_wraps(np.repeat)\n-def repeat(a, repeats, axis=None):\n- # use `_repeat_scalar` when possible\n- if isscalar(repeats):\n- return _repeat_scalar(a, repeats, axis)\n- repeats_raveled = np.ravel(np.array(repeats))\n- if size(repeats_raveled) == 1:\n- return _repeat_scalar(a, repeats_raveled.item(), axis)\n- if axis is None or isscalar(a):\n+@_wraps(np.repeat, lax_description=_TOTAL_REPEAT_LENGTH_DOC)\n+def repeat(a, repeats, axis=None, *, total_repeat_length=None):\n+ if axis is None:\na = ravel(a)\naxis = 0\n- # repeats must match the dimension along the requested axis\n- if repeats_raveled.size != a.shape[axis]:\n- raise ValueError(f\"repeats shape {repeats_raveled.shape} does not match \"\n- f\"the dimension on axis {a.shape[axis]}\")\n+ repeats = array(repeats)\n+ repeats = ravel(repeats)\n+\n+ if ndim(a) != 0:\n+ repeats = broadcast_to(repeats, [a.shape[axis]])\n- # calculating the new shape\n- total = repeats_raveled.sum()\n+ # If total_repeat_length is not given, use a default.\n+ if total_repeat_length is None:\n+ total_repeat_length = sum(repeats)\n- new_shape = list(a.shape)\n- new_shape[axis] = total\n- a_flattened = ravel(a)\n+ # Special case when a is a scalar.\n+ if ndim(a) == 0:\n+ if repeats.shape == (1,):\n+ return full([total_repeat_length], a)\n+ else:\n+ raise ValueError('`repeat` with a scalar parameter `a` is only '\n+ 'implemented for scalar values of the parameter `repeats`.')\n+\n+ # Special case if total_repeat_length is zero.\n+ if total_repeat_length == 0:\n+ return reshape(array([], dtype=a.dtype), array(a.shape).at[axis].set(0))\n- # first break down raveled input array into list of chunks; each chunk is the\n- # unit of repeat. then tile the repeats to have same length as the list of\n- # chunks. finally repeat each unit x number of times according to the tiled\n- # repeat list.\n- chunks = _prod(a.shape[:axis+1])\n- a_splitted = split(a_flattened, chunks)\n- repeats_tiled = np.tile(repeats_raveled, chunks // len(repeats_raveled))\n+ # If repeats is on a zero sized axis, then return the array.\n+ if a.shape[axis] == 0:\n+ return a\n- ret = array([], dtype=a.dtype)\n- for i, repeat in enumerate(repeats_tiled):\n- if repeat != 0:\n- ret = concatenate((ret, tile(a_splitted[i], (repeat,))))\n+ # Modify repeats from e.g. [1,2,5] -> [0,1,2]\n+ exclusive_repeats = roll(repeats, shift=1).at[0].set(0)\n+ # Cumsum to get indices of new number in repeated tensor, e.g. [0, 1, 3]\n+ scatter_indices = cumsum(exclusive_repeats)\n+ # Scatter these onto a zero buffer, e.g. [1,1,0,1,0,0,0,0]\n+ block_split_indicators = ops.index_update(\n+ x=zeros([total_repeat_length], dtype=int32),\n+ idx=scatter_indices,\n+ y=1)\n+ # Cumsum again to get scatter indices for repeat, e.g. [0,1,1,2,2,2,2,2]\n+ gather_indices = cumsum(block_split_indicators) - 1\n+ return take(a, gather_indices, axis=axis)\n- return reshape(ret, new_shape)\n@_wraps(np.tri)\ndef tri(N, M=None, k=0, dtype=None):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1319,25 +1319,59 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+\n+ def _compute_total_repeat_length(self, shape, axis, repeats):\n+ # Calculate expected size of the repeated axis.\n+ if jnp.ndim(shape) == 0 :\n+ return repeats\n+ shape = jnp.array(shape)\n+ if shape.size == 0:\n+ return repeats\n+ if axis is None:\n+ axis = 0\n+ if jnp.ndim(shape) != 0:\n+ shape = jnp.array([jnp.product(shape)])\n+ # Broadcasting the repeats if a scalar value.\n+ expected_repeats = jnp.broadcast_to(jnp.ravel(repeats),\n+ [shape[axis]])\n+ # Total size will be num_repeats X axis length.\n+ total_repeat_length = jnp.sum(expected_repeats)\n+ return total_repeat_length\n+\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_shape=[{}]_axis={}_repeats={}\".format(\n- jtu.format_shape_dtype_string(shape, dtype), axis, repeats),\n+ {\"testcase_name\": \"_shape=[{}]_axis={}_repeats={}_fixed_size={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype),\n+ axis, repeats, fixed_size),\n\"axis\": axis, \"shape\": shape, \"dtype\": dtype, \"repeats\": repeats,\n- \"rng_factory\": jtu.rand_default}\n+ \"rng_factory\": jtu.rand_default, 'fixed_size': fixed_size}\nfor repeats in [0, 1, 2]\nfor shape, dtype in _shape_and_dtypes(all_shapes, default_dtypes)\n- for axis in [None] + list(range(-len(shape), max(1, len(shape))))))\n- def testRepeat(self, axis, shape, dtype, repeats, rng_factory):\n+ for axis in [None] + list(range(-len(shape), max(1, len(shape))))\n+ for fixed_size in [True, False]))\n+ def testRepeat(self, axis, shape, dtype, repeats, rng_factory, fixed_size):\nrng = rng_factory(self.rng())\nnp_fun = lambda arg: np.repeat(arg, repeats=repeats, axis=axis)\nnp_fun = _promote_like_jnp(np_fun)\n+ if fixed_size:\n+ total_repeat_length = self._compute_total_repeat_length(\n+ shape, axis, repeats)\n+ jnp_fun = lambda arg, rep: jnp.repeat(arg, repeats=rep, axis=axis,\n+ total_repeat_length=total_repeat_length)\n+ jnp_args_maker = lambda: [rng(shape, dtype), repeats]\n+ clo_fun = lambda arg: jnp.repeat(arg, repeats=repeats, axis=axis,\n+ total_repeat_length=total_repeat_length)\n+ clo_fun_args_maker = lambda: [rng(shape, dtype)]\n+ self._CompileAndCheck(jnp_fun, jnp_args_maker)\n+ self._CheckAgainstNumpy(np_fun, clo_fun, clo_fun_args_maker)\n+ else:\n+ # Now repeats is in a closure, so a constant.\njnp_fun = lambda arg: jnp.repeat(arg, repeats=repeats, axis=axis)\n-\nargs_maker = lambda: [rng(shape, dtype)]\n-\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_ind={}_inv={}_count={}\".format(\njtu.format_shape_dtype_string(shape, dtype),\n@@ -1357,7 +1391,11 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\njnp_fun = lambda x: jnp.unique(x, return_index, return_inverse, return_counts)\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n- def testIssue1233(self):\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_fixed_size={}\".format(fixed_size),\n+ \"fixed_size\": fixed_size}\n+ for fixed_size in [True, False]))\n+ def testNonScalarRepeats(self, fixed_size):\n'''\nFollowing numpy test suite from `test_repeat` at\nhttps://github.com/numpy/numpy/blob/master/numpy/core/tests/test_multiarray.py\n@@ -1369,17 +1407,29 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nnumpy_ans = np.repeat(m, repeats, axis)\nself.assertAllClose(lax_ans, numpy_ans, rtol=tol, atol=tol)\n+ if fixed_size:\n+ # Calculate expected size of the repeated axis.\n+ rep_length = self._compute_total_repeat_length(m.shape, axis, repeats)\n+ jnp_fun = lambda arg, rep: jnp.repeat(\n+ arg, repeats = rep, axis=axis, total_repeat_length=rep_length)\n+ else:\njnp_fun = lambda arg: jnp.repeat(arg, repeats = repeats, axis=axis)\nself._CompileAndCheck(jnp_fun, args_maker)\nm = jnp.array([1,2,3,4,5,6])\n+ if fixed_size:\n+ args_maker = lambda: [m, repeats]\n+ else:\nargs_maker = lambda: [m]\nfor repeats in [2, [1,3,2,1,1,2], [1,3,0,1,1,2], [2], jnp.array([1,3,2,1,1,2]), jnp.array([2])]:\ntest_single(m, args_maker, repeats, None)\nm_rect = m.reshape((2,3))\n+ if fixed_size:\n+ args_maker = lambda: [m_rect, repeats]\n+ else:\nargs_maker = lambda: [m_rect]\nfor repeats in [2, [2,1], [2], jnp.array([2,1]), jnp.array([2])]:\n"
}
] | Python | Apache License 2.0 | google/jax | A jit-able version of np.repeat. (#3670)
A new keyword argument has been added to np.repeat, total_repeat_length, that can optionally be supplied to make np.repeat jit-able. |
260,308 | 15.07.2020 00:45:49 | -7,200 | f02d5b4694ae62a5a05a193d89e825bda2b79737 | Support differentiation through jax.lax.all_to_all
* Support differentiation through jax.lax.all_to_all
Credit to for the solution.
* Test gradient of all_to_all
We are testing all_to_all through pswapaxes, since general all_to_all is problematic according to
* Removed trailing spaces | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -441,6 +441,9 @@ def _all_to_all_split_axis_rule(vals, which_mapped, split_axis, concat_axis,\nout = _moveaxis(1, concat_axis + 1, out)\nreturn out, True\n+def _all_to_all_transpose_rule(cts, axis_name, split_axis, concat_axis):\n+ return (all_to_all(cts, axis_name=axis_name, split_axis=concat_axis, concat_axis=split_axis),)\n+\ndef _moveaxis(src, dst, x):\nperm = [i for i in range(x.ndim) if i != src]\nperm.insert(dst, src)\n@@ -449,6 +452,7 @@ def _moveaxis(src, dst, x):\nall_to_all_p = standard_pmap_primitive('all_to_all')\nxla.parallel_translations[all_to_all_p] = _all_to_all_translation_rule\npxla.split_axis_rules[all_to_all_p] = _all_to_all_split_axis_rule\n+ad.deflinear(all_to_all_p, _all_to_all_transpose_rule)\n### papply rules\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -949,6 +949,25 @@ class PmapTest(jtu.JaxTestCase):\nexpected = np.swapaxes(x, 0, 2)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @jtu.skip_on_devices(\"gpu\")\n+ def testGradOfPswapaxes(self):\n+ device_count = xla_bridge.device_count()\n+ # TODO: AllToAll not yet implemented on XLA:CPU\n+ if jtu.device_under_test() == \"cpu\":\n+ device_count = 1\n+ shape = (device_count, 1, device_count)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ w = np.arange(device_count, dtype=np.float32)\n+\n+ @partial(pmap, axis_name='i')\n+ def f(x, w):\n+ g = lambda x: jnp.sum(lax.pswapaxes(x, 'i', 1) * w)\n+ return grad(g)(x)\n+\n+ ans = f(x, w)\n+ expected = np.tile(w, reps=device_count).reshape(shape)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef testReshardInput(self):\nif xla_bridge.device_count() < 6:\nraise SkipTest(\"testReshardInput requires 6 devices\")\n"
}
] | Python | Apache License 2.0 | google/jax | Support differentiation through jax.lax.all_to_all (#3733)
* Support differentiation through jax.lax.all_to_all
Credit to @levskaya for the solution.
* Test gradient of all_to_all
We are testing all_to_all through pswapaxes, since general all_to_all is problematic according to https://github.com/google/jax/issues/1332.
* Removed trailing spaces |
260,298 | 15.07.2020 06:56:19 | -7,200 | 68c8dc781e9623afa01f5d0ec9cdde93c7e2bc6d | Added installation note for jax2tf with GPU support. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -77,3 +77,10 @@ tf.saved_model.save(my_model, '/some/directory')\n# Restoring (note: the restored model does *not* require JAX to run, just XLA).\nrestored_model = tf.saved_model.load('/some/directory')\n```\n+\n+### Running on GPU\n+\n+To run jax2tf on GPU, both jaxlib and TensorFlow must be installed with support\n+for CUDA. One must be mindful to install a version of CUDA that is compatible\n+with both [jaxlib](../../../../../#pip-installation) and\n+[TensorFlow](https://www.tensorflow.org/install/source#tested_build_configurations).\n"
}
] | Python | Apache License 2.0 | google/jax | Added installation note for jax2tf with GPU support. (#3750) |
260,298 | 15.07.2020 14:12:42 | -7,200 | d55c47d2cfc031b1340cca776ece33faf54c8060 | [jax2tf] Fix error in sorting with TF graphs. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1104,9 +1104,9 @@ def _sort(*operand: TfVal, dimension: int, is_stable: bool, num_keys: int) -> Tu\nraise NotImplementedError(\"TODO: implement stable version of XlaSort\")\nif dimension == len(operand[0].shape) - 1:\nif len(operand) == 2:\n- return tfxla.key_value_sort(operand[0], operand[1])\n+ return tuple(tfxla.key_value_sort(operand[0], operand[1]))\nelse:\n- return tfxla.sort(operand)\n+ return (tfxla.sort(operand[0]),)\nelse:\nraise NotImplementedError(\"TODO: implement XlaSort for all axes\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -131,9 +131,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nnot harness.params[\"is_stable\"]):\n# TODO: fix the TF GPU test\nraise unittest.SkipTest(\"GPU tests are running TF on CPU\")\n- # TODO: if we enable this test, we get the error\n- # iterating over `tf.Tensor` is not allowed: AutoGraph is disabled in this function.\n- raise unittest.SkipTest(\"TODO: re-enable the sort test\")\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@primitive_harness.parameterized(primitive_harness.lax_unary_elementwise)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix error in sorting with TF graphs. (#3764) |
260,411 | 15.07.2020 18:19:22 | -10,800 | 23c279f033a4fc6b836f4c9f12d82a8bcc1dda17 | [jax2tf] Relax tolerance for JaxPrimitiveTest.test_unary_elementwise_lgamma_float32 | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -171,7 +171,12 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# non-special cases are equal\nself.assertAllClose(result_jax[~ special_cases],\nresult_tf[~ special_cases])\n- self.ConvertAndCompare(harness.dyn_fun, arg, custom_assert=custom_assert)\n+ atol = None\n+ if jtu.device_under_test() == \"gpu\":\n+ # TODO(necula): revisit once we fix the GPU tests\n+ atol = 1e-3\n+ self.ConvertAndCompare(harness.dyn_fun, arg, custom_assert=custom_assert,\n+ atol=atol)\n@primitive_harness.parameterized(primitive_harness.lax_bitwise_not)\ndef test_bitwise_not(self, harness):\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Relax tolerance for JaxPrimitiveTest.test_unary_elementwise_lgamma_float32 (#3767) |
260,266 | 15.07.2020 19:19:40 | -3,600 | 150d028d9d381b47ff58b9b71dc7167ef3f6dc7f | Update scipy.ndimage.map_coordinates docstring | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/ndimage.py",
"new_path": "jax/scipy/ndimage.py",
"diff": "@@ -111,10 +111,10 @@ def _map_coordinates(input, coordinates, order, mode, cval):\n@_wraps(scipy.ndimage.map_coordinates, lax_description=textwrap.dedent(\"\"\"\\\n- Only linear interpolation (``order=1``) and modes ``'constant'``,\n- ``'nearest'`` and ``'wrap'`` are currently supported. Note that\n- interpolation near boundaries differs from the scipy function, because we\n- fixed an outstanding bug (https://github.com/scipy/scipy/issues/2640);\n+ Only nearest neighbor (``order=0``), linear interpolation (``order=1``) and\n+ modes ``'constant'``, ``'nearest'`` and ``'wrap'`` are currently supported.\n+ Note that interpolation near boundaries differs from the scipy function,\n+ because we fixed an outstanding bug (https://github.com/scipy/scipy/issues/2640);\nthis function interprets the ``mode`` argument as documented by SciPy, but\nnot as implemented by SciPy.\n\"\"\"))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_ndimage_test.py",
"new_path": "tests/scipy_ndimage_test.py",
"diff": "@@ -114,7 +114,7 @@ class NdimageTest(jtu.JaxTestCase):\nlsp_ndimage.map_coordinates(x, [c, c], order=1)\ndef testMapCoordinateDocstring(self):\n- self.assertIn(\"Only linear interpolation\",\n+ self.assertIn(\"Only nearest neighbor\",\nlsp_ndimage.map_coordinates.__doc__)\n@parameterized.named_parameters(jtu.cases_from_list(\n"
}
] | Python | Apache License 2.0 | google/jax | Update scipy.ndimage.map_coordinates docstring (#3762) |
260,298 | 16.07.2020 15:44:20 | -7,200 | 7b18a4e857f0a11f6203fe8fff7a4d87f22ce107 | [jax2tf] Fix interface of ConvertAndCompare function. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"new_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"diff": "@@ -62,7 +62,6 @@ class JaxToTfTestCase(jtu.JaxTestCase):\ndef ConvertAndCompare(self, func_jax: Callable, *args,\ncustom_assert: Optional[Callable] = None,\nexpect_tf_exceptions: bool = False,\n- expect_exception: Optional[Any] = None,\natol=None,\nrtol=None) -> Tuple[Any, Any]:\n\"\"\"Compares jax_func(*args) with convert(jax_func)(*args).\n@@ -70,8 +69,8 @@ class JaxToTfTestCase(jtu.JaxTestCase):\nIt compares the result of JAX, TF (\"eager\" mode),\nTF with tf.function (\"graph\" mode), and TF with\ntf.function(experimental_compile=True) (\"compiled\" mode). In each mode,\n- either we expect an exception (see `expect_exception`) or the value should\n- match the value from the JAX execution.\n+ either we expect an exception (see `expect_tf_exceptions`) or the value\n+ should match the value from the JAX execution.\nArgs:\ncustom_assert: a function that will be called\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix interface of ConvertAndCompare function. (#3776) |
260,355 | 18.07.2020 21:36:23 | -3,600 | d43393405abe30b2da2561bd29b4d8b08a6063bf | Add a TypeVar to while_loop definition. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -22,7 +22,7 @@ import functools\nimport inspect\nimport itertools\nimport operator\n-from typing import Callable, Sequence\n+from typing import Callable, Sequence, TypeVar\nimport numpy as np\n@@ -55,6 +55,9 @@ _map = safe_map\nzip = safe_zip\n_reduce = functools.reduce\n+T = TypeVar('T')\n+\n+\n@cache()\ndef _initial_style_untyped_jaxpr(fun: Callable, in_tree, in_avals):\nin_pvals = [pe.PartialVal.unknown(aval) for aval in in_avals]\n@@ -211,7 +214,9 @@ def fori_loop(lower, upper, body_fun, init_val):\nreturn result\n-def while_loop(cond_fun, body_fun, init_val):\n+def while_loop(cond_fun: Callable[[T], bool],\n+ body_fun: Callable[[T], T],\n+ init_val: T) -> T:\n\"\"\"Call ``body_fun`` repeatedly in a loop while ``cond_fun`` is True.\nThe type signature in brief is\n"
}
] | Python | Apache License 2.0 | google/jax | Add a TypeVar to while_loop definition. (#3792) |
260,424 | 20.07.2020 14:59:13 | -7,200 | dd3cb8213507f5f57f23b554862f7e703abb7c6e | Enable buffer donation for GPU. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -795,7 +795,7 @@ def parallel_callable(fun, backend, axis_name, axis_size, global_axis_size,\nelse:\nout_tuple = build_out_tuple()\nbackend = xb.get_backend(backend)\n- if backend.platform == \"tpu\":\n+ if backend.platform in (\"gpu\", \"tpu\"):\ndonated_invars = xla.set_up_aliases(c, xla_args, out_tuple, donated_invars, tuple_args)\nbuilt = c.Build(out_tuple)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -648,7 +648,7 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\nextend_name_stack(wrap_name(name, 'jit')), *xla_args)\nout_tuple = xops.Tuple(c, out_nodes)\nbackend = xb.get_backend(backend)\n- if backend.platform == \"tpu\":\n+ if backend.platform in (\"gpu\", \"tpu\"):\ndonated_invars = set_up_aliases(c, xla_args, out_tuple, donated_invars, tuple_args)\nif any(donated_invars):\n# TODO(tomhennigan): At call time we should mark these buffers as deleted.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -3229,16 +3229,17 @@ class BufferDonationTest(jtu.JaxTestCase):\n\"Some donated buffers were not usable: f32[2]{0}, s32[2]{0}\",\nstr(w[-1].message))\n- @jtu.skip_on_devices(\"cpu\", \"gpu\") # In/out aliasing only supported on TPU.\n+ @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\ndef test_jit_donate_argnums_invalidates_input(self):\n- # We can't just use `lambda x: x` because JAX simplifies this away.\n+ # We can't just use `lambda x: x` because JAX simplifies this away to an\n+ # empty XLA computation.\nmove = jit(lambda x: x + x - x, donate_argnums=0)\nx = jnp.ones([])\ny = move(x)\nself.assertDeleted(x)\nself.assertEqual(y, 1.)\n- @jtu.skip_on_devices(\"cpu\", \"gpu\") # In/out aliasing only supported on TPU.\n+ @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\ndef test_jit_donate_argnums_static_argnums(self):\njit_fun = jit(lambda a, b, c, d: ((a + b + c), (a + b + d)),\nstatic_argnums=(0, 1), donate_argnums=(2, 3))\n@@ -3284,7 +3285,7 @@ class BufferDonationTest(jtu.JaxTestCase):\n# === pmap ===\n- @jtu.skip_on_devices(\"cpu\", \"gpu\") # In/out aliasing only supported on TPU.\n+ @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\ndef test_pmap_donate_argnums_invalidates_input(self):\nmove = api.pmap(lambda x: x + x - x, donate_argnums=0)\nn = jax.local_device_count()\n"
}
] | Python | Apache License 2.0 | google/jax | Enable buffer donation for GPU. (#3800) |
260,335 | 21.07.2020 06:48:55 | 25,200 | 3a3c8ea8f21332bce8bd44bdd62deec059e0fe62 | tweak jnp.repeat not to use jnp on shapes
tweak jnp.repeat not to use jnp on shapes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2543,16 +2543,18 @@ def repeat(a, repeats, axis=None, *, total_repeat_length=None):\na = ravel(a)\naxis = 0\n- repeats = array(repeats)\n+ # If total_repeat_length is not given, can't compile, use a default.\n+ if total_repeat_length is None:\n+ repeats = core.concrete_or_error(np.array, repeats, \"jax.numpy.repeat\")\n+ repeats = np.ravel(repeats)\n+ if ndim(a) != 0:\n+ repeats = np.broadcast_to(repeats, [a.shape[axis]])\n+ total_repeat_length = np.sum(repeats)\n+ else:\nrepeats = ravel(repeats)\n-\nif ndim(a) != 0:\nrepeats = broadcast_to(repeats, [a.shape[axis]])\n- # If total_repeat_length is not given, use a default.\n- if total_repeat_length is None:\n- total_repeat_length = sum(repeats)\n-\n# Special case when a is a scalar.\nif ndim(a) == 0:\nif repeats.shape == (1,):\n@@ -2563,7 +2565,9 @@ def repeat(a, repeats, axis=None, *, total_repeat_length=None):\n# Special case if total_repeat_length is zero.\nif total_repeat_length == 0:\n- return reshape(array([], dtype=a.dtype), array(a.shape).at[axis].set(0))\n+ result_shape = list(a.shape)\n+ result_shape[axis] = 0\n+ return reshape(array([], dtype=a.dtype), result_shape)\n# If repeats is on a zero sized axis, then return the array.\nif a.shape[axis] == 0:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1319,26 +1319,6 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n-\n- def _compute_total_repeat_length(self, shape, axis, repeats):\n- # Calculate expected size of the repeated axis.\n- if jnp.ndim(shape) == 0 :\n- return repeats\n- shape = jnp.array(shape)\n- if shape.size == 0:\n- return repeats\n- if axis is None:\n- axis = 0\n- if jnp.ndim(shape) != 0:\n- shape = jnp.array([jnp.product(shape)])\n- # Broadcasting the repeats if a scalar value.\n- expected_repeats = jnp.broadcast_to(jnp.ravel(repeats),\n- [shape[axis]])\n- # Total size will be num_repeats X axis length.\n- total_repeat_length = jnp.sum(expected_repeats)\n- return total_repeat_length\n-\n-\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape=[{}]_axis={}_repeats={}_fixed_size={}\".format(\njtu.format_shape_dtype_string(shape, dtype),\n@@ -1354,8 +1334,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nnp_fun = lambda arg: np.repeat(arg, repeats=repeats, axis=axis)\nnp_fun = _promote_like_jnp(np_fun)\nif fixed_size:\n- total_repeat_length = self._compute_total_repeat_length(\n- shape, axis, repeats)\n+ total_repeat_length = np.repeat(np.zeros(shape), repeats, axis).shape[axis or 0]\njnp_fun = lambda arg, rep: jnp.repeat(arg, repeats=rep, axis=axis,\ntotal_repeat_length=total_repeat_length)\njnp_args_maker = lambda: [rng(shape, dtype), repeats]\n@@ -1371,7 +1350,6 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n-\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_ind={}_inv={}_count={}\".format(\njtu.format_shape_dtype_string(shape, dtype),\n@@ -1410,7 +1388,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nif fixed_size:\n# Calculate expected size of the repeated axis.\n- rep_length = self._compute_total_repeat_length(m.shape, axis, repeats)\n+ rep_length = np.repeat(np.zeros_like(m), repeats, axis).shape[axis or 0]\njnp_fun = lambda arg, rep: jnp.repeat(\narg, repeats=rep, axis=axis, total_repeat_length=rep_length)\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | tweak jnp.repeat not to use jnp on shapes (#3810)
tweak jnp.repeat not to use jnp on shapes |
260,476 | 21.07.2020 15:41:08 | 14,400 | 74d363e552ca916d48eb116366eca3bb7eccf23f | fix extremely minor typo
"ijnputs" -> "inputs" | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -280,7 +280,7 @@ def fold_in(key, data):\ndata: a 32bit integer representing data to be folded in to the key.\nReturns:\n- A new PRNGKey that is a deterministic function of the ijnputs and is\n+ A new PRNGKey that is a deterministic function of the inputs and is\nstatistically safe for producing a stream of new pseudo-random values.\n\"\"\"\nreturn _fold_in(key, data)\n"
}
] | Python | Apache License 2.0 | google/jax | fix extremely minor typo (#3815)
"ijnputs" -> "inputs" |
260,335 | 23.07.2020 19:38:56 | 25,200 | 67ad5eb5a1bf4db3c61a28d7f7233f971e4c1263 | add result_shape option to xla_computation
add result_shape option to xla_computation | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -228,7 +228,8 @@ def xla_computation(fun: Callable,\naxis_env: Optional[Sequence[Tuple[AxisName, int]]] = None,\nbackend: Optional[str] = None,\ntuple_args: bool = False,\n- instantiate_const_outputs: bool = True) -> Callable:\n+ instantiate_const_outputs: bool = True,\n+ return_shape: bool = False) -> Callable:\n\"\"\"Creates a function that produces its XLA computation given example args.\nArgs:\n@@ -351,9 +352,8 @@ def xla_computation(fun: Callable,\njaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)\navals = map(abstractify, jax_args)\npvals = [pe.PartialVal.unknown(aval) for aval in avals]\n- jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals,\n- instantiate=instantiate_const_outputs,\n- stage_out=True)\n+ jaxpr, out_pvals, consts = pe.trace_to_jaxpr(\n+ jaxtree_fun, pvals, instantiate=instantiate_const_outputs, stage_out=True)\njaxpr = xla.apply_outfeed_rewriter(jaxpr)\naxis_env_ = make_axis_env(xla.jaxpr_replicas(jaxpr))\nc = xb.make_computation_builder('xla_computation_{}'.format(fun_name))\n@@ -362,7 +362,14 @@ def xla_computation(fun: Callable,\nouts = xla.jaxpr_subcomp(\nc, jaxpr, backend, axis_env_, xla_consts,\nextend_name_stack(wrap_name(fun_name, 'xla_computation')), *xla_args)\n- return c.build(xc.ops.Tuple(c, outs))\n+ built = c.build(xc.ops.Tuple(c, outs))\n+ if return_shape:\n+ out_avals = [raise_to_shaped(pval.get_aval()) for pval in out_pvals]\n+ out_shapes_flat = [ShapeDtypeStruct(a.shape, a.dtype) for a in out_avals]\n+ out_shape = tree_unflatten(out_tree(), out_shapes_flat)\n+ return built, out_shape\n+ else:\n+ return built\nreturn computation_maker\ndef grad(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -932,6 +932,13 @@ class APITest(jtu.JaxTestCase):\nxla_comp = api.xla_computation(f, static_argnums=(1,))(2, 3)\nself.assertIn('constant(3)', xla_comp.as_hlo_text())\n+ def test_xla_computation_return_shape(self):\n+ _, shape_tree = api.xla_computation(lambda x: (x + 1, jnp.zeros(2, jnp.float32)),\n+ return_shape=True)(np.int32(1))\n+ expected = (api.ShapeDtypeStruct(shape=(), dtype=jnp.int32),\n+ api.ShapeDtypeStruct(shape=(2,), dtype=jnp.float32))\n+ self.assertEqual(shape_tree, expected)\n+\ndef test_jit_device(self):\ndevice = xb.devices()[-1]\nx = api.jit(lambda x: x, device=device)(3.)\n"
}
] | Python | Apache License 2.0 | google/jax | add result_shape option to xla_computation (#3844)
add result_shape option to xla_computation |
260,335 | 23.07.2020 19:49:04 | 25,200 | cc9528d97dba5c88c15c089a4bac069d7407a61b | fix thread locality bug in custom_derivatives
* fix thread locality bug in custom_derivatives
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -635,6 +635,11 @@ class TraceState(threading.local):\nself.substack = [Sublevel(0)]\nself.initial_style = False\n+ def set_state(self, other: 'TraceState') -> None:\n+ self.trace_stack = other.trace_stack\n+ self.sustack = other.substack[:]\n+ self.initial_style = other.initial_style\n+\ndef copy(self):\nnew = TraceState()\nnew.trace_stack = self.trace_stack.copy()\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -58,11 +58,12 @@ def _memoize(thunk):\nsaved_state = core.trace_state.copy()\ndef memoized():\nif not cell:\n- prev_state, core.trace_state = core.trace_state, saved_state\n+ prev_state = core.trace_state.copy()\n+ core.trace_state.set_state(saved_state)\ntry:\ncell.append(thunk())\nfinally:\n- core.trace_state = prev_state\n+ core.trace_state.set_state(prev_state)\nreturn cell[0]\nreturn memoized\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2524,6 +2524,24 @@ class CustomJVPTest(jtu.JaxTestCase):\nexpected = 12.\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_concurrent_initial_style(self):\n+ # https://github.com/google/jax/issues/3843\n+ def unroll(param, sequence):\n+ def scan_f(prev_state, inputs):\n+ return prev_state, jax.nn.sigmoid(param * inputs)\n+ return jnp.sum(jax.lax.scan(scan_f, None, sequence)[1])\n+\n+ def run():\n+ return jax.grad(unroll)(jnp.array(1.0), jnp.array([1.0]))\n+\n+ # we just don't want this to crash\n+ n_workers = 20\n+ with concurrent.futures.ThreadPoolExecutor(max_workers=n_workers) as e:\n+ futures = []\n+ for _ in range(n_workers):\n+ futures.append(e.submit(run))\n+ _ = [f.result() for f in futures]\n+\nclass CustomVJPTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | fix thread locality bug in custom_derivatives (#3845)
* fix thread locality bug in custom_derivatives
fixes #3843 |
260,335 | 23.07.2020 20:59:12 | 25,200 | e2424e3b242a521dc02eaa11228861ddc354b41b | attempt to fix CI failure (from test?) | [
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2534,13 +2534,17 @@ class CustomJVPTest(jtu.JaxTestCase):\ndef run():\nreturn jax.grad(unroll)(jnp.array(1.0), jnp.array([1.0]))\n+ expected = run()\n+\n# we just don't want this to crash\nn_workers = 20\nwith concurrent.futures.ThreadPoolExecutor(max_workers=n_workers) as e:\nfutures = []\nfor _ in range(n_workers):\nfutures.append(e.submit(run))\n- _ = [f.result() for f in futures]\n+ results = [f.result() for f in futures]\n+ for ans in results:\n+ self.assertAllClose(ans, expected)\nclass CustomVJPTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | attempt to fix CI failure (from #3845 test?) (#3846) |
260,411 | 24.07.2020 10:14:08 | -10,800 | 86732620c9c996c60ffd2666e18e56b3142c437d | [jax2tf] Expand the support for jax.remat.
In the simplest forms, remat is already handled by the `process_call`.
But when the `remat` has outputs computed from values captured from
an outer environment, we need to also implement `post_process_call`. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -305,8 +305,17 @@ class TensorFlowTrace(core.Trace):\nvals_out: Sequence[TfValOrUnit] = f.call_wrapped(*vals)\nreturn [TensorFlowTracer(self, v) for v in vals_out]\n- def post_process_call(self, call_primitive, out_tracers, params):\n- raise NotImplementedError(\"post_process_call\")\n+ def post_process_call(self, call_primitive: core.Primitive,\n+ out_tracers: Sequence[TensorFlowTracer], params):\n+ # We encountered a call primitive, e.g., remat_call_p, whose result\n+ # (out_tracers) include TensorFlowTracer that were not passed through\n+ # its arguments (captured from the environment).\n+ vals = tuple(t.val for t in out_tracers)\n+ master = self.master\n+ def todo(vals: Sequence[TfValOrUnit]):\n+ trace = TensorFlowTrace(master, core.cur_sublevel())\n+ return map(functools.partial(TensorFlowTracer, trace), vals)\n+ return vals, todo\ndef process_map(self, map_primitive, f, tracers, params):\nraise NotImplementedError(\"process_map\")\n@@ -347,7 +356,8 @@ def _unexpected_primitive(p: core.Primitive, *args, **kwargs):\nfor unexpected in [\n- xla.xla_call_p]: # Not part of the public API\n+ # Call primitives are inlined\n+ xla.xla_call_p, pe.remat_call_p, core.call_p]:\ntf_impl[unexpected] = functools.partial(_unexpected_primitive, unexpected)\n@@ -369,8 +379,6 @@ tf_not_yet_impl = [\nlax.after_all_p, lax.all_to_all_p, lax.create_token_p, lax.cummax_p, lax.cummin_p,\nlax.infeed_p, lax.outfeed_p, lax.pmax_p, lax.pmin_p, lax.ppermute_p, lax.psum_p,\n- core.call_p,\n- pe.remat_call_p,\npxla.xla_pmap_p, pxla.axis_index_p,\n]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"new_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"diff": "@@ -275,6 +275,19 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\nself.TransformConvertAndCompare(g, arg, \"grad\")\nself.TransformConvertAndCompare(g, arg, \"grad_vmap\")\n+ def test_scan_remat(self):\n+ def f_jax(xs):\n+\n+ @jax.remat\n+ def body_fun(carry, x):\n+ return carry * x, xs # capture xs from the environment\n+ res1, res2 = lax.scan(body_fun, 0., xs + 1.)\n+ return jnp.sum(res1) + jnp.sum(res2)\n+\n+ arg = np.arange(10, dtype=np.float32) + 1.\n+ self.TransformConvertAndCompare(f_jax, arg, None)\n+ self.TransformConvertAndCompare(f_jax, arg, \"grad\")\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -311,6 +311,34 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.TransformConvertAndCompare(f, arg, \"grad\")\nself.TransformConvertAndCompare(f, arg, \"grad_vmap\")\n+ def test_remat1(self):\n+ @jax.remat\n+ def f(x1):\n+ x2 = jnp.sin(x1)\n+ x3 = jnp.sin(x2)\n+ x4 = jnp.sin(x3)\n+ return jnp.sum(x4)\n+\n+ # The computation of grad_f computes \"sin\" 5 times, 3 for the forward pass\n+ # and then to rematerialize \"x2\" and \"x3\" in the backward pass.\n+ arg = np.arange(3.)\n+ self.TransformConvertAndCompare(f, arg, \"grad\")\n+ # TODO: check that the TF code also computes \"sin\" 5 times\n+\n+\n+ def test_remat_free_var(self):\n+ def f(x):\n+ y = 2 * x\n+\n+ @jax.remat\n+ def g():\n+ return y\n+\n+ return g()\n+ arg = 3.\n+ self.TransformConvertAndCompare(f, arg, None)\n+ self.TransformConvertAndCompare(f, arg, \"grad\")\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Expand the support for jax.remat. (#3828)
In the simplest forms, remat is already handled by the `process_call`.
But when the `remat` has outputs computed from values captured from
an outer environment, we need to also implement `post_process_call`. |
260,411 | 24.07.2020 10:14:34 | -10,800 | 55cd8279c857456a0797639899259906dce570cf | [jax2tf] Selectively disable some primitive tests on TPU.
Currently, all primitive tests are disabled on TPU, but only some
cases fail. This PR simply disables the selected failing tests on
TPU, so that we can enable the rest by default. Future PRs will
address each failure individually. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -119,6 +119,9 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nelif harness.params[\"dtype\"] is dtypes.bfloat16:\nraise unittest.SkipTest(\"bfloat16 support not implemented\")\nelif harness.params[\"dtype\"] in jtu.dtypes.complex:\n+ # TODO(necula): fix top_k complex bug on TPU\n+ if jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"top_k complex on TPU raises different error\")\nwith self.assertRaisesRegex(RuntimeError, \"Unimplemented: complex comparison\"):\nharness.dyn_fun(*harness.dyn_args_maker(self.rng()))\n# TODO: TF and JAX sort [inf, nan] differently.\n@@ -158,6 +161,10 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\natol=1e-5, rtol=1e-5)\nelif harness.params[\"dtype\"] in [jnp.complex64, jnp.complex128]:\n+ if (jtu.device_under_test() == \"tpu\" and\n+ harness.params[\"dtype\"] in [jnp.complex64]):\n+ raise unittest.SkipTest(\"QR for c64 not implemented on TPU\")\n+\n# TODO: see https://github.com/google/jax/pull/3775#issuecomment-659407824.\n# - check_compiled=True breaks for complex types;\n# - for now, the performance of the HLO QR implementation called when\n@@ -166,6 +173,14 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\nexpect_tf_exceptions=True, atol=1e-5, rtol=1e-5)\nelse:\n+ # TODO(necula): fix QR bug on TPU\n+ if (jtu.device_under_test() == \"tpu\" and\n+ harness.params[\"dtype\"] in (jnp.bfloat16, jnp.int32, jnp.uint32)):\n+ raise unittest.SkipTest(\"QR bug on TPU for certain types: error not raised\")\n+ if (jtu.device_under_test() == \"tpu\" and\n+ harness.params[\"dtype\"] in (jnp.bool_,)):\n+ raise unittest.SkipTest(\"QR bug on TPU for certain types: invalid cast\")\n+\nexpected_error = ValueError if jtu.device_under_test() == \"gpu\" else NotImplementedError\nwith self.assertRaisesRegex(expected_error, \"Unsupported dtype\"):\nharness.dyn_fun(*harness.dyn_args_maker(self.rng()))\n@@ -178,6 +193,10 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\narg, = harness.dyn_args_maker(self.rng())\ncustom_assert = None\nif harness.params[\"lax_name\"] == \"digamma\":\n+ # TODO(necula): fix bug with digamma/f32 on TPU\n+ if harness.params[\"dtype\"] is np.float32 and jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"TODO: fix bug: nan vs not-nan\")\n+\n# digamma is not defined at 0 and -1\ndef custom_assert(result_jax, result_tf):\n# lax.digamma returns NaN and tf.math.digamma returns inf\n@@ -194,6 +213,9 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# TODO(necula): fix bug with erf_inv/f16\nif dtype is np.float16:\nraise unittest.SkipTest(\"TODO: fix bug\")\n+ # TODO(necula): fix erf_inv bug on TPU\n+ if jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"erf_inv bug on TPU: nan vs non-nan\")\n# erf_inf is not defined for arg <= -1 or arg >= 1\ndef custom_assert(result_jax, result_tf): # noqa: F811\n# for arg < -1 or arg > 1\n@@ -223,10 +245,13 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ndef test_binary_elementwise(self, harness):\nif harness.params[\"dtype\"] is dtypes.bfloat16:\nraise unittest.SkipTest(\"bfloat16 not implemented\")\n+ if harness.params[\"lax_name\"] in (\"igamma\", \"igammac\"):\n# TODO(necula): fix bug with igamma/f16\n- if (harness.params[\"lax_name\"] in (\"igamma\", \"igammac\") and\n- harness.params[\"dtype\"] is np.float16):\n+ if harness.params[\"dtype\"] is np.float16:\nraise unittest.SkipTest(\"TODO: fix bug\")\n+ # TODO(necula): fix bug with igamma/f32 on TPU\n+ if harness.params[\"dtype\"] is np.float32 and jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"TODO: fix bug: nan vs not-nan\")\n# TODO(necula): fix bug with nextafter/f16\nif (harness.params[\"lax_name\"] == \"nextafter\" and\nharness.params[\"dtype\"] is np.float16):\n@@ -305,6 +330,9 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_dynamic_slice)\ndef test_dynamic_slice(self, harness):\n# JAX.dynamic_slice rejects slice sizes too big; check this, and skip jax2tf\n+ # TODO(necula): fix dynamic_slice bug on TPU\n+ if jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"dynamic_slice bug on TPU: not compilable (for some shapes)\")\nargs = harness.dyn_args_maker(self.rng())\nexpect_tf_exceptions = False\nif any(li - si < 0 or li - si >= sh\n@@ -342,9 +370,15 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_gather)\ndef test_gather(self, harness: primitive_harness.Harness):\n+ # TODO(necula): fix gather bug on TPU\n+ if jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"TODO: fix bug: not compilable\")\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\ndef test_boolean_gather(self):\n+ # TODO(necula): fix boolean_gather bug on TPU\n+ if jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"TODO: fix bug: not compilable\")\nvalues = np.array([[True, True], [False, True], [False, False]],\ndtype=np.bool_)\nindices = np.array([0, 1], dtype=np.int32)\n@@ -354,6 +388,9 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(f_jax, values, indices)\ndef test_gather_rank_change(self):\n+ # TODO(necula): fix gather bug on TPU\n+ if jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"TODO: fix bug: not compilable\")\nparams = jnp.array([[1.0, 1.5, 2.0], [2.0, 2.5, 3.0], [3.0, 3.5, 4.0]])\nindices = jnp.array([[1, 1, 2], [0, 1, 0]])\nf_jax = jax.jit(lambda i: params[i])\n@@ -380,6 +417,9 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nop=op)\nfor op in INDEX))\ndef test_scatter_static(self, op):\n+ # TODO(necula): fix scatter bug on TPU\n+ if jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"scatter bug on TPU: not compilable\")\nvalues = np.ones((5, 6), dtype=np.float32)\nupdate = np.float32(6.)\nf_jax = jax.jit(lambda v, u: op(v, jax.ops.index[::2, 3:], u))\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Selectively disable some primitive tests on TPU. (#3835)
Currently, all primitive tests are disabled on TPU, but only some
cases fail. This PR simply disables the selected failing tests on
TPU, so that we can enable the rest by default. Future PRs will
address each failure individually. |
260,335 | 24.07.2020 12:52:52 | 25,200 | 57c2fcb0cdb58768790fed13e6dd171bba235d90 | tweak parallel collective translation rule api
also remove standard_parallel_primitive helper function, which wasn't
very helpful | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -944,7 +944,7 @@ def get_num_partitions(*partitions):\nreturn num_partitions_set.pop()\n-class ResultToPopulate(object): pass\n+class ResultToPopulate: pass\nresult_to_populate = ResultToPopulate()\ndef _pvals_to_results_handler(\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -410,17 +410,8 @@ def jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, name_stack, *args):\nans = rule(c, axis_env, extend_name_stack(name_stack, eqn.primitive.name),\nmap(aval, eqn.invars), backend, *in_nodes, **new_params)\nelif eqn.primitive in parallel_translations:\n- replica_groups = axis_groups(axis_env, eqn.params['axis_name'])\n- axis_index_groups = eqn.params.get('axis_index_groups', None)\n- if axis_index_groups is not None:\n- replica_groups = [[axis_group[i] for i in axis_index_group]\n- for axis_group in replica_groups\n- for axis_index_group in axis_index_groups]\n- new_params = {k: v for k, v in eqn.params.items()\n- if k not in ('axis_name', 'axis_index_groups')}\nrule = parallel_translations[eqn.primitive]\n- ans = rule(c, *in_nodes, replica_groups=replica_groups, platform=platform,\n- **new_params)\n+ ans = rule(c, *in_nodes, axis_env=axis_env, platform=platform, **eqn.params)\nelif eqn.primitive in call_translations:\nnew_params = check_backend_params(eqn.params, backend)\nrule = call_translations[eqn.primitive]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -301,19 +301,33 @@ def _allreduce_split_axis_rule(prim, reducer, vals, which_mapped, axis_name,\nif axis_index_groups is not None:\nraise NotImplementedError(\"soft_pmap does not yet support axis_index_groups\")\nvals = (reducer(x, [0]) for x in vals)\n- return prim.bind(*vals, axis_name=axis_name), False\n+ out = prim.bind(*vals, axis_name=axis_name, axis_index_groups=axis_index_groups)\n+ return out, False\n-def _allreduce_translation_rule(prim, c, val, replica_groups, platform=None):\n+def _allreduce_translation_rule(prim, c, val, *, axis_name, axis_index_groups,\n+ axis_env, platform):\n+ replica_groups = _replica_groups(axis_env, axis_name, axis_index_groups)\ndtype = c.get_shape(val).numpy_dtype()\nscalar = ShapedArray((), dtype)\ncomputation = xla.primitive_subcomputation(prim, scalar, scalar)\nreplica_groups_protos = xc.make_replica_groups(replica_groups)\nreturn xops.AllReduce(val, computation, replica_groups_protos, None, None)\n+def _replica_groups(axis_env, axis_name, axis_index_groups):\n+ replica_groups = xla.axis_groups(axis_env, axis_name)\n+ if axis_index_groups is not None:\n+ replica_groups = [[axis_group[i] for i in axis_index_group]\n+ for axis_group in replica_groups\n+ for axis_index_group in axis_index_groups]\n+ return replica_groups\n+\n# psum translation rule has special handling for complex dtypes\n-def _psum_translation_rule(c, *args, replica_groups=None, platform=None):\n+def _psum_translation_rule(c, *args, axis_name, axis_index_groups, axis_env,\n+ platform):\nif platform in (\"cpu\", \"tpu\"):\n- return _notuple_psum_translation_rule(c, *args, replica_groups=replica_groups)\n+ return _notuple_psum_translation_rule(c, *args, axis_name=axis_name,\n+ axis_index_groups=axis_index_groups,\n+ axis_env=axis_env, platform=platform)\n# XLA's tuple all-reduce doesn't support different dtypes in the same\n# allreduce. Instead, we perform once all-reduce for each argument input type.\n@@ -325,6 +339,7 @@ def _psum_translation_rule(c, *args, replica_groups=None, platform=None):\n# The outputs, in the original argument order.\nout = [None] * len(args)\n+ replica_groups = _replica_groups(axis_env, axis_name, axis_index_groups)\nreplica_groups_protos = xc.make_replica_groups(replica_groups)\nfor dtype, (indices, dtype_args) in sorted(args_by_type.items()):\nis_complex = dtypes.issubdtype(dtype, np.complexfloating)\n@@ -350,10 +365,12 @@ def _psum_translation_rule(c, *args, replica_groups=None, platform=None):\n# cross-task communication either.\n# TODO(b/155446630): An XLA:TPU optimization pass also doesn't support\n# tuple all-reduce yet. Meanwhile, rely on deterministic compiler behavior.\n-def _notuple_psum_translation_rule(c, *args, replica_groups):\n+def _notuple_psum_translation_rule(c, *args, axis_name, axis_env,\n+ axis_index_groups, platform):\ndef _translate(val):\npsum = partial(_allreduce_translation_rule, lax.add_p, c,\n- replica_groups=replica_groups)\n+ axis_name=axis_name, axis_env=axis_env,\n+ axis_index_groups=axis_index_groups, platform=platform)\ndtype = c.get_shape(val).numpy_dtype()\nif dtypes.issubdtype(dtype, np.complexfloating):\nreturn xops.Complex(psum(xops.Real(val)), psum(xops.Imag(val)))\n@@ -367,9 +384,10 @@ def _psum_transpose_rule(cts, axis_name, axis_index_groups):\naxis_index_groups=axis_index_groups)\nreturn tree_util.tree_unflatten(treedef, nonzero_in_cts)\n-psum_p = standard_pmap_primitive('psum', multiple_results=True)\n-psum_p.def_abstract_eval(\n- lambda *args, **params: tuple(map(raise_to_shaped, args)))\n+psum_p = core.Primitive('psum')\n+psum_p.multiple_results = True\n+psum_p.def_impl(partial(pxla.apply_parallel_primitive, psum_p))\n+psum_p.def_abstract_eval(lambda *args, **params: map(raise_to_shaped, args))\npxla.split_axis_rules[psum_p] = \\\npartial(_allreduce_split_axis_rule, psum_p, lax._reduce_sum)\nxla.parallel_translations[psum_p] = _psum_translation_rule\n@@ -378,21 +396,24 @@ ad.deflinear(psum_p, _psum_transpose_rule)\npxla.multi_host_supported_collectives.add(psum_p)\n-pmax_p = standard_pmap_primitive('pmax')\n+pmax_p = core.Primitive('pmax')\n+pmax_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nxla.parallel_translations[pmax_p] = \\\npartial(_allreduce_translation_rule, lax.max_p)\npxla.split_axis_rules[pmax_p] = \\\npartial(_allreduce_split_axis_rule, pmax_p, lax._reduce_max)\n-pmin_p = standard_pmap_primitive('pmin')\n+pmin_p = core.Primitive('pmin')\n+pmin_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nxla.parallel_translations[pmin_p] = \\\npartial(_allreduce_translation_rule, lax.min_p)\npxla.split_axis_rules[pmin_p] = \\\npartial(_allreduce_split_axis_rule, pmin_p, lax._reduce_min)\n-def _ppermute_translation_rule(c, x, replica_groups, perm, platform=None):\n+def _ppermute_translation_rule(c, x, *, axis_name, axis_env, perm, platform):\n+ replica_groups = _replica_groups(axis_env, axis_name, None)\ngroup_size = len(replica_groups[0])\nsrcs, dsts = unzip2((src % group_size, dst % group_size) for src, dst in perm)\nif not (len(srcs) == len(set(srcs)) and len(dsts) == len(set(dsts))):\n@@ -410,15 +431,17 @@ def _ppermute_transpose_rule(t, perm, axis_name):\ninverse_perm = list(zip(dsts, srcs))\nreturn [ppermute(t, axis_name=axis_name, perm=inverse_perm)]\n-ppermute_p = standard_pmap_primitive('ppermute')\n+ppermute_p = core.Primitive('ppermute')\n+ppermute_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nad.deflinear(ppermute_p, _ppermute_transpose_rule)\nxla.parallel_translations[ppermute_p] = _ppermute_translation_rule\npxla.multi_host_supported_collectives.add(ppermute_p)\n-def _all_to_all_translation_rule(c, x, split_axis, concat_axis, replica_groups,\n- platform=None):\n+def _all_to_all_translation_rule(c, x, *, split_axis, concat_axis, axis_name,\n+ axis_env, platform):\n# Workaround for AllToAll not being implemented on CPU.\n+ replica_groups = _replica_groups(axis_env, axis_name, None)\nif len(replica_groups[0]) == 1:\nreturn x\nelse:\n@@ -449,7 +472,8 @@ def _moveaxis(src, dst, x):\nperm.insert(dst, src)\nreturn lax.transpose(x, perm)\n-all_to_all_p = standard_pmap_primitive('all_to_all')\n+all_to_all_p = core.Primitive('all_to_all')\n+all_to_all_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nxla.parallel_translations[all_to_all_p] = _all_to_all_translation_rule\npxla.split_axis_rules[all_to_all_p] = _all_to_all_split_axis_rule\nad.deflinear(all_to_all_p, _all_to_all_transpose_rule)\n"
}
] | Python | Apache License 2.0 | google/jax | tweak parallel collective translation rule api (#3853)
also remove standard_parallel_primitive helper function, which wasn't
very helpful |
260,335 | 24.07.2020 15:54:21 | 25,200 | 5e91965723ac16dda361435d1bfcd4dc99201537 | delete standard_parallel_primitive helper
delete standard_parallel_primitive helper
meant to include this in it's even in the PR message! | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/__init__.py",
"new_path": "jax/lax/__init__.py",
"diff": "@@ -334,5 +334,4 @@ from .lax_parallel import (\npsum,\npsum_p,\npswapaxes,\n- standard_pmap_primitive,\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -287,14 +287,6 @@ def all_to_all(x, axis_name, split_axis, concat_axis):\n### parallel primitives\n-def standard_pmap_primitive(name, multiple_results=False):\n- prim = core.Primitive(name)\n- prim.multiple_results = multiple_results\n- prim.def_impl(partial(pxla.apply_parallel_primitive, prim))\n- prim.def_abstract_eval(lambda x, *args, **params: x)\n- return prim\n-\n-\ndef _allreduce_split_axis_rule(prim, reducer, vals, which_mapped, axis_name,\naxis_index_groups):\nassert tuple(which_mapped) == (True,)\n"
}
] | Python | Apache License 2.0 | google/jax | delete standard_parallel_primitive helper (#3858)
delete standard_parallel_primitive helper
meant to include this in #3853, it's even in the PR message! |
260,335 | 26.07.2020 22:38:14 | 25,200 | c9d8acd2e921efdbc01b2208fa9f790a9c312933 | put core trace state in a threading.local class
this is a refinement of the fix in so that we no longer need
TraceState.set_state (and so that is easier to adapt) | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -39,7 +39,7 @@ from .pprint_util import pp, vcat, PrettyPrint\n# TODO(dougalm): compilation cache breaks the leak detector. Consisder solving.\ncheck_leaks = False\n-\"\"\"Disables internal invariant checks.\"\"\"\n+# Disables internal invariant checks\nskip_checks = not FLAGS.jax_enable_checks # not __debug__ # google doesn't use -O\n@contextmanager\n@@ -116,6 +116,8 @@ class TypedJaxpr:\nassert len(literals) == len(jaxpr.constvars)\nassert len(in_avals) == len(jaxpr.invars)\n+ assert not any(isinstance(l, Tracer) for l in literals), literals\n+\nif not skip_checks:\nin_avals_raised = [raise_to_shaped(v) for v in in_avals]\nout_avals_raised = [raise_to_shaped(v) for v in out_avals]\n@@ -291,11 +293,11 @@ class Primitive:\nself.bind = bind\nreturn bind\n- def impl(self, *args, **kwargs):\n+ def impl(self, *args, **params):\nraise NotImplementedError(\"Evaluation rule for '{}' not implemented\"\n.format(self.name))\n- def abstract_eval(self, *args, **kwargs):\n+ def abstract_eval(self, *args, **params):\nraise NotImplementedError(\"Abstract evaluation for '{}' not implemented\"\n.format(self.name))\n@@ -622,10 +624,7 @@ class TraceStack:\nclass Sublevel(int): pass\n-# The global state of the tracer is accessed by a thread-local object.\n-# This allows concurrent tracing in separate threads; passing traced objects\n-# between threads is forbidden.\n-class TraceState(threading.local):\n+class TraceState:\ntrace_stack: TraceStack\nsubstack: List[Sublevel]\ninitial_style: bool\n@@ -635,58 +634,60 @@ class TraceState(threading.local):\nself.substack = [Sublevel(0)]\nself.initial_style = False\n- def set_state(self, other: 'TraceState') -> None:\n- self.trace_stack = other.trace_stack\n- self.sustack = other.substack[:]\n- self.initial_style = other.initial_style\n-\ndef copy(self):\nnew = TraceState()\nnew.trace_stack = self.trace_stack.copy()\nnew.substack = self.substack[:]\nnew.initial_style = self.initial_style\nreturn new\n-trace_state = TraceState()\n+\n+# The global state of the tracer is accessed by a thread-local object.\n+# This allows concurrent tracing in separate threads; passing traced objects\n+# between threads is forbidden.\n+class ThreadLocalState(threading.local):\n+ def __init__(self):\n+ self.trace_state = TraceState()\n+thread_local_state = ThreadLocalState()\ndef reset_trace_state() -> bool:\n\"Reset the global trace state and return True if it was already clean.\"\n- if (trace_state.substack != [Sublevel(0)] or\n- trace_state.trace_stack.downward or\n- trace_state.trace_stack.upward):\n- trace_state.__init__() # type: ignore\n+ if (thread_local_state.trace_state.substack != [Sublevel(0)] or\n+ thread_local_state.trace_state.trace_stack.downward or\n+ thread_local_state.trace_state.trace_stack.upward):\n+ thread_local_state.trace_state.__init__() # type: ignore\nreturn False\nelse:\nreturn True\ndef cur_sublevel() -> Sublevel:\n- return trace_state.substack[-1]\n+ return thread_local_state.trace_state.substack[-1]\n@contextmanager\ndef new_master(trace_type: Type[Trace], bottom=False) -> Generator[MasterTrace, None, None]:\n- level = trace_state.trace_stack.next_level(bottom)\n+ level = thread_local_state.trace_state.trace_stack.next_level(bottom)\nmaster = MasterTrace(level, trace_type)\n- trace_state.trace_stack.push(master, bottom)\n+ thread_local_state.trace_state.trace_stack.push(master, bottom)\ntry:\nyield master\nfinally:\n- trace_state.trace_stack.pop(bottom)\n+ thread_local_state.trace_state.trace_stack.pop(bottom)\nif check_leaks:\nt = ref(master)\ndel master\nif t() is not None:\n- print(trace_state.trace_stack)\n+ print(thread_local_state.trace_state.trace_stack)\nraise Exception('Leaked trace {}'.format(t()))\n@contextmanager\ndef new_sublevel() -> Generator[None, None, None]:\n- sublevel = Sublevel(len(trace_state.substack))\n- trace_state.substack.append(sublevel)\n+ sublevel = Sublevel(len(thread_local_state.trace_state.substack))\n+ thread_local_state.trace_state.substack.append(sublevel)\ntry:\nyield\nfinally:\n- trace_state.substack.pop()\n+ thread_local_state.trace_state.substack.pop()\nif check_leaks:\nt = ref(sublevel)\n@@ -707,6 +708,7 @@ def find_top_trace(xs) -> Optional[Trace]:\n@contextmanager\ndef initial_style_staging():\n+ trace_state = thread_local_state.trace_state\nprev, trace_state.initial_style = trace_state.initial_style, True\ntry:\nyield\n@@ -1095,7 +1097,8 @@ def call_bind(primitive: Union['CallPrimitive', 'MapPrimitive'],\nfun: lu.WrappedFun, *args, **params):\nparams_tuple = tuple(params.items())\ntop_trace = find_top_trace(args)\n- level = trace_state.trace_stack.next_level(True) if top_trace is None else top_trace.level\n+ level = (thread_local_state.trace_state.trace_stack.next_level(True)\n+ if top_trace is None else top_trace.level)\nparams_tuple = tuple(params.items())\nfun, env_trace_todo = process_env_traces(fun, primitive, level, params_tuple)\nif top_trace is None:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -55,15 +55,15 @@ def _add_args_(extra_args, left, *args, **kwargs):\ndef _memoize(thunk):\ncell = []\n- saved_state = core.trace_state.copy()\n+ saved_state = core.thread_local_state.trace_state.copy()\ndef memoized():\nif not cell:\n- prev_state = core.trace_state.copy()\n- core.trace_state.set_state(saved_state)\n+ prev_state = core.thread_local_state.trace_state\n+ core.thread_local_state.trace_state = saved_state\ntry:\ncell.append(thunk())\nfinally:\n- core.trace_state.set_state(prev_state)\n+ core.thread_local_state.trace_state = prev_state\nreturn cell[0]\nreturn memoized\n@@ -221,7 +221,7 @@ class custom_jvp:\nargs_flat, in_tree = tree_flatten(dyn_args)\nflat_fun, out_tree1 = flatten_fun_nokwargs(f_, in_tree)\nflat_jvp, out_tree2 = _flatten_jvp(jvp, in_tree)\n- if core.trace_state.initial_style:\n+ if core.thread_local_state.trace_state.initial_style:\nout_flat = custom_jvp_call_jaxpr(flat_fun, flat_jvp, *args_flat)\nout_tree = out_tree1()\nelse:\n@@ -464,7 +464,7 @@ class custom_vjp:\nflat_fun, out_tree = flatten_fun_nokwargs(f_, in_tree)\nflat_fwd, out_trees = _flatten_fwd(fwd, in_tree)\nflat_bwd = _flatten_bwd(bwd, in_tree, out_trees)\n- if core.trace_state.initial_style:\n+ if core.thread_local_state.trace_state.initial_style:\nout_flat = custom_vjp_call_jaxpr(flat_fun, flat_fwd, flat_bwd,\n*args_flat, out_trees=out_trees)\nout_tree = out_tree()\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/loops.py",
"new_path": "jax/experimental/loops.py",
"diff": "@@ -277,15 +277,15 @@ class Scope(object):\ndef start_subtrace(self):\n\"\"\"Starts a nested trace, returns the Trace object.\"\"\"\n# TODO: This follows the __enter__ part of core.new_master.\n- level = core.trace_state.trace_stack.next_level(False)\n+ level = core.thread_local_state.trace_state.trace_stack.next_level(False)\nmaster = core.MasterTrace(level, pe.JaxprTrace)\n- core.trace_state.trace_stack.push(master, False)\n+ core.thread_local_state.trace_state.trace_stack.push(master, False)\nself._count_subtraces += 1\nreturn pe.JaxprTrace(master, core.cur_sublevel())\ndef end_subtrace(self):\n# TODO: This follows the __exit__ part of core.new_master\n- core.trace_state.trace_stack.pop(False)\n+ core.thread_local_state.trace_state.trace_stack.pop(False)\nself._count_subtraces -= 1\n"
}
] | Python | Apache License 2.0 | google/jax | put core trace state in a threading.local class (#3869)
this is a refinement of the fix in #3845, so that we no longer need
TraceState.set_state (and so that #3370 is easier to adapt) |
260,326 | 28.07.2020 02:45:36 | -19,080 | 3aa37d3af4324f53c72270296ca905189ab6fd99 | Replicating sort_complex functionality from np.sort_complex to jax.numpy | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -255,6 +255,7 @@ Not every function in NumPy is implemented; contributions are welcome!\nsinh\nsometrue\nsort\n+ sort_complex\nsplit\nsqrt\nsquare\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -53,7 +53,7 @@ from .lax_numpy import (\nrad2deg, radians, ravel, real, reciprocal, remainder, repeat, reshape,\nresult_type, right_shift, rint, roll, rollaxis, rot90, round, row_stack,\nsave, savez, searchsorted, select, set_printoptions, shape, sign, signbit,\n- signedinteger, sin, sinc, single, sinh, size, sometrue, sort, split, sqrt,\n+ signedinteger, sin, sinc, single, sinh, size, sometrue, sort, sort_complex, split, sqrt,\nsquare, squeeze, stack, std, subtract, sum, swapaxes, take, take_along_axis,\ntan, tanh, tensordot, tile, trace, trapz, transpose, tri, tril, tril_indices, tril_indices_from,\ntriu, triu_indices, triu_indices_from, true_divide, trunc, uint16, uint32, uint64, uint8, unique,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -3237,6 +3237,11 @@ def sort(a, axis=-1, kind='quicksort', order=None):\nelse:\nreturn lax.sort(a, dimension=_canonicalize_axis(axis, ndim(a)))\n+@_wraps(np.sort_complex)\n+def sort_complex(a):\n+ a = lax.sort(a, dimension=0)\n+ return lax.convert_element_type(a, result_type(a, complex_))\n+\n@_wraps(np.lexsort)\ndef lexsort(keys, axis=-1):\nkeys = tuple(keys)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -2648,6 +2648,23 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(jnp_fun, np_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_axis={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), axis),\n+ \"shape\": shape, \"dtype\": dtype, \"axis\": axis}\n+ for dtype in all_dtypes\n+ for shape in one_dim_array_shapes\n+ for axis in [None]))\n+ def testSortComplex(self, dtype, shape, axis):\n+ # TODO(b/141131288): enable test once complex sort is supported on TPU.\n+ if (jnp.issubdtype(dtype, jnp.complexfloating)\n+ and jtu.device_under_test() == \"tpu\"):\n+ self.skipTest(\"complex sort not supported on TPU\")\n+ rng = jtu.rand_some_equal(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+ self._CheckAgainstNumpy(jnp.sort_complex, np.sort_complex, args_maker, check_dtypes=False)\n+ self._CompileAndCheck(jnp.sort_complex, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_input_type={}_axis={}\".format(\njtu.format_shape_dtype_string(shape, dtype),\n"
}
] | Python | Apache License 2.0 | google/jax | Replicating sort_complex functionality from np.sort_complex to jax.numpy (#3870) |
260,335 | 27.07.2020 21:51:12 | 25,200 | 616d63b19ae08c6d58f1de8d7c41fe78ebded157 | fix vmap error, fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -907,7 +907,7 @@ def _mapped_axis_size(tree, vals, dims, name):\n# TODO(mattjj,phawkins): add a way to inspect pytree kind more directly\nif tree == tree_flatten((core.unit,) * tree.num_leaves)[1]:\nlines1 = [\"arg {} has shape {} and axis {} is to be mapped\"\n- .format(i, x.shape, d) for i, (x, d) in enumerate(zip(vals, dims))]\n+ .format(i, np.shape(x), d) for i, (x, d) in enumerate(zip(vals, dims))]\nsizes = collections.defaultdict(list)\nfor i, (x, d) in enumerate(zip(vals, dims)):\nif d is not None:\n@@ -919,11 +919,11 @@ def _mapped_axis_size(tree, vals, dims, name):\n\"axes\" if len(idxs) > 1 else \"an axis\",\nsize)\nfor size, idxs in sizes.items()]\n- raise ValueError(msg.format(\"\\n\".join(lines1 + [\"so\"] + lines2))) from e\n+ raise ValueError(msg.format(\"\\n\".join(lines1 + [\"so\"] + lines2))) from None\nelse:\nsizes = [x.shape[d] if d is not None else None for x, d in zip(vals, dims)]\nsizes = tree_unflatten(tree, sizes)\n- raise ValueError(msg.format(\"the tree of axis sizes is:\\n{}\".format(sizes))) from e\n+ raise ValueError(msg.format(\"the tree of axis sizes is:\\n{}\".format(sizes))) from None\ndef pmap(fun: Callable, axis_name: Optional[AxisName] = None, *, in_axes=0,\nstatic_broadcasted_argnums: Union[int, Iterable[int]] = (),\n"
}
] | Python | Apache License 2.0 | google/jax | fix vmap error, fixes #3877 (#3879) |
260,299 | 28.07.2020 16:27:07 | -7,200 | 7506a3e5f0137f48415def878bea71c5977dfbd0 | Fix flaky generated_fun_test.py test | [
{
"change_type": "MODIFY",
"old_path": "tests/generated_fun_test.py",
"new_path": "tests/generated_fun_test.py",
"diff": "@@ -186,7 +186,7 @@ def inner_prod(xs, ys):\nreturn sum(jnp.sum(x * y) for x, y in xys)\ndef jvp_fd(fun, args, tangents):\n- EPS = 1e-4\n+ EPS = 1e-3\ndef eval_eps(eps):\nreturn fun(*[x if t is None else x + eps * t\nfor x, t in zip(args, tangents)])\n"
}
] | Python | Apache License 2.0 | google/jax | Fix flaky generated_fun_test.py test (#3885) |
260,335 | 28.07.2020 19:46:00 | 25,200 | 30980742c57f3b507d74b5ae79e9a75b5f57bc08 | refine population_count type check
* refine population_count type check
fixes
* allow signed/unsigned ints for population_count
https://cs.opensource.google/tensorflow/tensorflow/+/master:tensorflow/compiler/xla/service/shape_inference.cc;l=314?q=xla%20f:shape_inference.cc
* make lax_reference.population_count handle signed | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2242,7 +2242,7 @@ ad.defjvp_zero(or_p)\nxor_p = standard_naryop([_bool_or_int, _bool_or_int], 'xor')\nad.defjvp_zero(xor_p)\n-population_count_p = standard_unop(_bool_or_int, 'population_count')\n+population_count_p = standard_unop(_int, 'population_count')\ndef _add_transpose(t, x, y):\n# The following linearity assertion is morally true, but because in some cases we\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax_reference.py",
"new_path": "jax/lax_reference.py",
"diff": "@@ -119,9 +119,14 @@ shift_right_arithmetic = np.right_shift\n# TODO shift_right_logical\ndef population_count(x):\n+ assert np.issubdtype(x.dtype, np.integer)\ndtype = x.dtype\n- if x.dtype in (np.uint8, np.uint16):\n- x = x.astype(np.uint32)\n+ iinfo = np.iinfo(x.dtype)\n+ if np.iinfo(x.dtype).bits < 32:\n+ assert iinfo.kind in ('i', 'u')\n+ x = x.astype(np.uint32 if iinfo.kind == 'u' else np.int32)\n+ if iinfo.kind == 'i':\n+ x = x.view(f\"uint{np.iinfo(x.dtype).bits}\")\nassert x.dtype in (np.uint32, np.uint64)\nm = [\n0x5555555555555555, # binary: 0101...\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -137,7 +137,7 @@ LAX_OPS = [\nop_record(\"bitwise_not\", 1, bool_dtypes, jtu.rand_small),\nop_record(\"bitwise_or\", 2, bool_dtypes, jtu.rand_small),\nop_record(\"bitwise_xor\", 2, bool_dtypes, jtu.rand_small),\n- op_record(\"population_count\", 1, uint_dtypes, jtu.rand_int),\n+ op_record(\"population_count\", 1, int_dtypes + uint_dtypes, jtu.rand_int),\nop_record(\"add\", 2, default_dtypes + complex_dtypes, jtu.rand_small),\nop_record(\"sub\", 2, default_dtypes + complex_dtypes, jtu.rand_small),\n@@ -1786,6 +1786,12 @@ class LaxTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, \"duplicate value in 'axes' .*\"):\nlax.reduce(np.arange(3), 0, lax.add, (0, 0))\n+ def test_population_count_booleans_not_supported(self):\n+ # https://github.com/google/jax/issues/3886\n+ msg = \"population_count does not accept dtype bool\"\n+ with self.assertRaisesRegex(TypeError, msg):\n+ lax.population_count(True)\n+\nclass LazyConstantTest(jtu.JaxTestCase):\ndef _Check(self, make_const, expected):\n"
}
] | Python | Apache License 2.0 | google/jax | refine population_count type check (#3887)
* refine population_count type check
fixes #3886
* allow signed/unsigned ints for population_count
https://cs.opensource.google/tensorflow/tensorflow/+/master:tensorflow/compiler/xla/service/shape_inference.cc;l=314?q=xla%20f:shape_inference.cc
* make lax_reference.population_count handle signed |
260,335 | 30.07.2020 00:42:32 | 25,200 | b3806ce87438ecbeb52ffa5ee7755adaf21eef2b | add placeholder enable_omnistaging method | [
{
"change_type": "MODIFY",
"old_path": "jax/config.py",
"new_path": "jax/config.py",
"diff": "@@ -113,6 +113,8 @@ class Config(object):\nself.complete_absl_config(absl.flags)\nalready_configured_with_absl = True\n+ def enable_omnistaging(self):\n+ pass # placeholder\nclass NameSpace(object):\ndef __init__(self, getter):\n"
}
] | Python | Apache License 2.0 | google/jax | add placeholder enable_omnistaging method (#3907) |
260,335 | 30.07.2020 22:27:01 | 25,200 | 146cf49fa04ce8e476da6981f52688b63bef7f4e | delay backend check for xla_computation | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -369,7 +369,10 @@ def jaxpr_literals(jaxpr):\ndef jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, name_stack, *args):\n- platform = xb.get_backend(backend).platform\n+ if backend not in ('cpu', 'gpu', 'tpu'):\n+ platform = xb.get_backend(backend).platform # canonicalize\n+ else:\n+ platform = backend\ndef read(v):\nif type(v) is Literal:\n"
}
] | Python | Apache License 2.0 | google/jax | delay backend check for xla_computation (#3920) |
260,335 | 31.07.2020 15:11:01 | 25,200 | 843d710116138fba67728fafb53a4eb667cbf55c | allow mask to return output logical shape
When the `mask` argument `out_shape` is not provided, or when it has
value `None`, return the output logical shape to the user. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1241,7 +1241,7 @@ def _papply(fun):\nreturn papply_fun, axis_name\n-def mask(fun: Callable, in_shapes, out_shape) -> Callable:\n+def mask(fun: Callable, in_shapes, out_shape=None) -> Callable:\n_check_callable(fun)\nunique_ids = masking.UniqueIds()\n@@ -1249,6 +1249,7 @@ def mask(fun: Callable, in_shapes, out_shape) -> Callable:\nin_specs = map(masking.parse_spec, in_specs)\nin_specs = map(partial(masking.remap_ids, unique_ids), in_specs)\n+ if out_shape is not None:\nout_specs, out_spec_tree = tree_flatten(out_shape)\nout_specs = map(masking.parse_spec, out_specs)\nout_specs = map(partial(masking.remap_ids, unique_ids), out_specs)\n@@ -1266,6 +1267,13 @@ def mask(fun: Callable, in_shapes, out_shape) -> Callable:\nflat_fun, logical_env, padded_env, args_flat, in_shapes)\nout_tree = out_tree_thunk()\n+ if out_shape is None:\n+ def logical_shape(poly_shape, padded_val):\n+ shape = masking.eval_poly_shape(poly_shape, logical_env)\n+ return ShapeDtypeStruct(shape, core.get_aval(padded_val).dtype)\n+ out_logicals = map(logical_shape, out_shapes, outs)\n+ return tree_unflatten(out_tree, outs), tree_unflatten(out_tree, out_logicals)\n+ else:\nmasking.check_shapes(out_specs, out_spec_tree, list(out_shapes), out_tree)\ndef padded_spec(shape_spec):\nreturn tuple(dim if dim is masking._monomorphic_dim else\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -69,11 +69,11 @@ def extend_shape_envs(logical_env, padded_env):\ndef shape_as_value(shape):\nassert is_tracing() or not is_polymorphic(shape)\n- return eval_polymorphic_shape(shape, shape_envs.logical)\n+ return eval_poly_shape(shape, shape_envs.logical)\ndef padded_shape_as_value(shape):\nassert is_tracing() or not is_polymorphic(shape)\n- return eval_polymorphic_shape(shape, shape_envs.padded)\n+ return eval_poly_shape(shape, shape_envs.padded)\ndef mask_fun(fun, logical_env, padded_env, in_vals, polymorphic_shapes):\nenv_keys, padded_env_vals = unzip2(sorted(padded_env.items()))\n@@ -101,7 +101,7 @@ def mask_subtrace(master, shapes, padded_env, *in_vals):\nout_vals, out_shapes = unzip2((t.val, t.polymorphic_shape) for t in out_tracers)\nyield out_vals, out_shapes\n-def eval_polymorphic_shape(shape, values_dict):\n+def eval_poly_shape(shape, values_dict):\nreturn tuple(eval_poly(dim, values_dict) for dim in shape)\ndef eval_poly(poly, values_dict):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -32,7 +32,7 @@ from jax.scipy.special import expit\nfrom jax import mask, vmap, jit, grad, shapecheck, make_jaxpr\nfrom jax.interpreters.masking import (\nshape_as_value, ShapeError, parse_spec, Poly, Mon, finalize_spec,\n- eval_polymorphic_shape, remap_ids, UniqueIds)\n+ eval_poly_shape, remap_ids, UniqueIds)\nconfig.parse_flags_with_absl()\n@@ -153,14 +153,14 @@ class MaskingTest(jtu.JaxTestCase):\nout_specs, _ = tree_flatten(out_shape)\nout_specs = map(parse_spec, out_specs)\nout_specs = map(finalize_spec, out_specs, map(np.shape, padded_outs))\n- logical_out_shapes = [eval_polymorphic_shape(s, logical_env)\n+ logical_out_shapes = [eval_poly_shape(s, logical_env)\nfor s in out_specs]\nlogical_out_slices = [tuple(map(slice, s)) for s in logical_out_shapes]\nlogical_outs = [o[s] for o, s in zip(padded_outs, logical_out_slices)]\nin_specs = map(parse_spec, in_shapes)\nin_specs = map(finalize_spec, in_specs, padded_in_shapes)\n- logical_in_shapes = [eval_polymorphic_shape(s, logical_env)\n+ logical_in_shapes = [eval_poly_shape(s, logical_env)\nfor s in in_specs]\nlogical_in_slices = [tuple(map(slice, s)) for s in logical_in_shapes]\nlogical_args = [a[s] for a, s in zip(padded_args, logical_in_slices)]\n@@ -174,7 +174,6 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertAllClose(padded_outs_jit, padded_outs, check_dtypes=True,\natol=atol, rtol=rtol)\n-\ndef test_add(self):\nself.check(lax.add, ['n', ''], 'n', {'n': 3}, [(4,), ()], ['float_', 'float_'],\njtu.rand_default(self.rng()))\n@@ -733,6 +732,18 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertNotIn('mul', str(jaxpr))\nself.assertNotIn('add', str(jaxpr))\n+ def test_return_shape_to_user(self):\n+ @partial(mask, in_shapes=['n'])\n+ def foo(x):\n+ return [x, np.sum(x)]\n+\n+ out, out_shape = foo([np.arange(5)], dict(n=2))\n+ self.assertIsInstance(out_shape, list)\n+ self.assertLen(out_shape, 2)\n+ a, b = out_shape\n+ self.assertEqual(a.shape, (2,))\n+ self.assertEqual(b.shape, ())\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | allow mask to return output logical shape (#3929)
When the `mask` argument `out_shape` is not provided, or when it has
value `None`, return the output logical shape to the user. |
260,335 | 31.07.2020 22:20:58 | 25,200 | ff96de935b186609da473cf6f769901a17f77aa9 | add dummy eval context | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -733,6 +733,10 @@ def initial_style_staging():\nfinally:\ntrace_state.initial_style = prev\n+@contextmanager\n+def eval_context():\n+ yield # dummy implementation for forward compatibility\n+\n# -------------------- abstract values --------------------\n"
}
] | Python | Apache License 2.0 | google/jax | add dummy eval context (#3932) |
260,355 | 01.08.2020 21:33:11 | -3,600 | 8a8bb702d29c8036807d53b6110fc2fe2051559a | Catch invalid (negative) in/out axes in vmap.
Catch invalid (negative) in/out axes in vmap. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -869,16 +869,22 @@ def vmap(fun: Callable, in_axes=0, out_axes=0) -> Callable:\n# rather than raising an error. https://github.com/google/jax/issues/2367\nin_axes = tuple(in_axes)\n- if not all(isinstance(l, (type(None), int, batching._Last))\n- for l in tree_leaves(in_axes)):\n+ in_axes_, out_axes_ = tree_leaves(in_axes), tree_leaves(out_axes)\n+ if not all(isinstance(l, (type(None), int, batching._Last)) for l in in_axes_):\nmsg = (\"vmap in_axes must be an int, None, or (nested) container with \"\n\"those types as leaves, but got {}.\")\nraise TypeError(msg.format(in_axes))\n- if not all(isinstance(l, (type(None), int, batching._Last))\n- for l in tree_leaves(out_axes)):\n+ if not all(isinstance(l, (type(None), int, batching._Last)) for l in out_axes_):\nmsg = (\"vmap out_axes must be an int, None, or (nested) container with \"\n\"those types as leaves, but got {}.\")\nraise TypeError(msg.format(out_axes))\n+ if any(l < 0 for l in in_axes_ if l is not batching.last):\n+ msg = \"vmap in_axes leaves must be non-negative integers or None, but got {}.\"\n+ raise TypeError(msg.format(in_axes))\n+ if any(l < 0 for l in out_axes_ if l is not batching.last):\n+ msg = \"vmap in_axes leaves must be non-negative integers or None, but got {}.\"\n+ raise TypeError(msg.format(out_axes))\n+ del in_axes_, out_axes_\n@wraps(fun, docstr=docstr)\ndef batched_fun(*args):\n"
}
] | Python | Apache License 2.0 | google/jax | Catch invalid (negative) in/out axes in vmap. (#3926)
Catch invalid (negative) in/out axes in vmap. |
260,285 | 03.08.2020 17:17:48 | -7,200 | 7de784afbf719590583e362102a2bcc0fa5037a0 | Fix _CheckAgainstNumpy arg order | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -2582,7 +2582,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nargs_maker = lambda: [rng.randn(3, 4).astype(\"float32\")]\nnp_op = lambda x: np.asarray(x).astype(jnp.int32)\njnp_op = lambda x: jnp.asarray(x).astype(jnp.int32)\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2605,7 +2605,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\njnp_op = lambda x: jnp.asarray(x).view(dtype)\n# Above may produce signaling nans; ignore warnings from invalid values.\nwith np.errstate(invalid='ignore'):\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\ndef testPathologicalFloats(self):\n@@ -2625,7 +2625,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nnp_op = lambda x: np.asarray(x).view('float32').view('uint32')\njnp_op = lambda x: jnp.asarray(x).view('float32').view('uint32')\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\n# TODO(mattjj): test other ndarray-like method overrides\n@@ -2663,7 +2663,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nif axis is not None:\njnp_fun = partial(jnp_fun, axis=axis)\nnp_fun = partial(np_fun, axis=axis)\n- self._CheckAgainstNumpy(jnp_fun, np_fun, args_maker)\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2680,7 +2680,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself.skipTest(\"complex sort not supported on TPU\")\nrng = jtu.rand_some_equal(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\n- self._CheckAgainstNumpy(jnp.sort_complex, np.sort_complex, args_maker, check_dtypes=False)\n+ self._CheckAgainstNumpy(np.sort_complex, jnp.sort_complex, args_maker, check_dtypes=False)\nself._CompileAndCheck(jnp.sort_complex, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2701,7 +2701,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nargs_maker = lambda: [input_type(rng(shape, dtype))]\njnp_op = lambda x: jnp.lexsort(x, axis=axis)\nnp_op = lambda x: np.lexsort(x, axis=axis)\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2723,7 +2723,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nif axis is not None:\njnp_fun = partial(jnp_fun, axis=axis)\nnp_fun = partial(np_fun, axis=axis)\n- self._CheckAgainstNumpy(jnp_fun, np_fun, args_maker)\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2739,7 +2739,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself.skipTest(\"complex sort not supported on TPU\")\nrng = jtu.rand_some_equal(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\n- self._CheckAgainstNumpy(jnp.msort, np.msort, args_maker)\n+ self._CheckAgainstNumpy(np.msort, jnp.msort, args_maker)\nself._CompileAndCheck(jnp.msort, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2765,7 +2765,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype), np.array(shifts)]\njnp_op = partial(jnp.roll, axis=axis)\nnp_op = partial(np.roll, axis=axis)\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2784,7 +2784,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype)]\njnp_op = partial(jnp.rollaxis, axis=axis, start=start)\nnp_op = partial(np.rollaxis, axis=axis, start=start)\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2804,7 +2804,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype)]\njnp_op = partial(jnp.packbits, axis=axis, bitorder=bitorder)\nnp_op = partial(np.packbits, axis=axis, bitorder=bitorder)\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2824,7 +2824,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype)]\njnp_op = partial(jnp.unpackbits, axis=axis, bitorder=bitorder)\nnp_op = partial(np.unpackbits, axis=axis, bitorder=bitorder)\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2851,7 +2851,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nrng_indices = jtu.rand_int(self.rng(), -5, 5)\njnp_op = lambda x, i: jnp.take(x, i, axis=axis, mode=mode)\nnp_op = lambda x, i: np.take(x, i, axis=axis, mode=mode)\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\ndef testTakeEmpty(self):\n@@ -2892,7 +2892,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nif hasattr(np, \"take_along_axis\"):\nnp_op = lambda x, i: np.take_along_axis(x, i, axis=axis)\n- self._CheckAgainstNumpy(jnp_op, np_op, args_maker)\n+ self._CheckAgainstNumpy(np_op, jnp_op, args_maker)\nself._CompileAndCheck(jnp_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -195,7 +195,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype) for shape in shapes]\nop = getattr(lax, op_name)\nnumpy_op = getattr(lax_reference, op_name)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker, tol=tol)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker, tol=tol)\n# TODO test shift_left, shift_right_arithmetic, shift_right_logical\n@@ -224,7 +224,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng((2, 3), from_dtype)]\nop = lambda x: lax.convert_element_type(x, to_dtype)\nnumpy_op = lambda x: lax_reference.convert_element_type(x, to_dtype)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_from_dtype={}_to_dtype={}\"\n@@ -251,7 +251,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng((2, 3), from_dtype)]\nop = lambda x: lax.bitcast_convert_type(x, to_dtype)\nnumpy_op = lambda x: lax_reference.bitcast_convert_type(x, to_dtype)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_min_shape={}_operand_shape={}_max_shape={}\".format(\n@@ -294,7 +294,7 @@ class LaxTest(jtu.JaxTestCase):\nrng = rng_factory(self.rng())\nshapes = [min_shape, operand_shape, max_shape]\nargs_maker = lambda: [rng(shape, dtype) for shape in shapes]\n- self._CheckAgainstNumpy(lax.clamp, lax_reference.clamp, args_maker)\n+ self._CheckAgainstNumpy(lax_reference.clamp, lax.clamp, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_dim={}_baseshape=[{}]_dtype={}_narrs={}\".format(\n@@ -333,7 +333,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype) for shape in shapes]\nop = lambda *args: lax.concatenate(args, dim)\nnumpy_op = lambda *args: lax_reference.concatenate(args, dim)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -378,7 +378,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\nop = lambda lhs, rhs: lax.conv(lhs, rhs, strides, padding)\nnumpy_op = lambda lhs, rhs: lax_reference.conv(lhs, rhs, strides, padding)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\"\n@@ -501,7 +501,7 @@ class LaxTest(jtu.JaxTestCase):\njnp_fun = partial(lax.conv_general_dilated, window_strides=(),\npadding='VALID', dimension_numbers=('NC', 'IO', 'NC'))\nself._CompileAndCheck(jnp_fun, args_maker)\n- self._CheckAgainstNumpy(jnp_fun, np.dot, args_maker, tol=.1)\n+ self._CheckAgainstNumpy(np.dot, jnp_fun, args_maker, tol=.1)\n@staticmethod\n@@ -581,7 +581,7 @@ class LaxTest(jtu.JaxTestCase):\ndimension_numbers=dspec)\n# NB: below just checks for agreement, we're not calling numpy.\n- self._CheckAgainstNumpy(fun, fun_via_grad, args_maker)\n+ self._CheckAgainstNumpy(fun_via_grad, fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -619,7 +619,7 @@ class LaxTest(jtu.JaxTestCase):\ndimension_numbers=dspec)\n# NB: below just checks for agreement, we're not calling numpy.\n- self._CheckAgainstNumpy(fun, fun_via_grad, args_maker)\n+ self._CheckAgainstNumpy(fun_via_grad, fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -656,7 +656,7 @@ class LaxTest(jtu.JaxTestCase):\ndimension_numbers=dspec)\n# NB: below just checks for agreement, we're not calling numpy.\n- self._CheckAgainstNumpy(fun, fun_via_grad, args_maker)\n+ self._CheckAgainstNumpy(fun_via_grad, fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -693,7 +693,7 @@ class LaxTest(jtu.JaxTestCase):\ndimension_numbers=dspec)\n# NB: below just checks for agreement, we're not calling numpy.\n- self._CheckAgainstNumpy(fun, fun_via_grad, args_maker)\n+ self._CheckAgainstNumpy(fun_via_grad, fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_lhs_shape={}_rhs_shape={}_precision={}\".format(\n@@ -731,7 +731,7 @@ class LaxTest(jtu.JaxTestCase):\n1e-14)\n}\nlax_op = partial(lax.dot, precision=lax.Precision.HIGHEST)\n- self._CheckAgainstNumpy(lax_op, lax_reference.dot, args_maker, tol=tol)\n+ self._CheckAgainstNumpy(lax_reference.dot, lax_op, args_maker, tol=tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -813,7 +813,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\nop = lambda x, y: lax.dot_general(x, y, dimension_numbers)\nnumpy_op = lambda x, y: lax_reference.dot_general(x, y, dimension_numbers)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_dtype={}_broadcast_sizes={}\".format(\n@@ -844,7 +844,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype)]\nop = lambda x: lax.broadcast(x, broadcast_sizes)\nnumpy_op = lambda x: lax_reference.broadcast(x, broadcast_sizes)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_inshape={}_outshape={}_bcdims={}\".format(\n@@ -912,7 +912,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(inshape, dtype)]\nop = lambda x: lax.broadcast_in_dim(x, outshape, dimensions)\nnumpy_op = lambda x: lax_reference.broadcast_in_dim(x, outshape, dimensions)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_inshape={}_dimensions={}\".format(\n@@ -952,7 +952,7 @@ class LaxTest(jtu.JaxTestCase):\nop = lambda x: lax.squeeze(x, dimensions)\nnumpy_op = lambda x: lax_reference.squeeze(x, dimensions)\nself._CompileAndCheck(op, args_maker)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\ncheck_grads(op, args_maker(), 2, [\"fwd\", \"rev\"], eps=1.)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -988,7 +988,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(arg_shape, dtype)]\nop = lambda x: lax.reshape(x, out_shape)\nnumpy_op = lambda x: lax_reference.reshape(x, out_shape)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_inshape={}_pads={}\"\n@@ -1022,7 +1022,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype)]\nop = lambda x: lax.pad(x, np.array(0, dtype), pads)\nnumpy_op = lambda x: lax_reference.pad(x, np.array(0, dtype), pads)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\ndef testReverse(self):\nrev = api.jit(lambda operand: lax.rev(operand, dimensions))\n@@ -1072,7 +1072,7 @@ class LaxTest(jtu.JaxTestCase):\nreturn [rng(pred_shape, np.bool_), rng(arg_shape, arg_dtype),\nrng(arg_shape, arg_dtype)]\nrng = rng_factory(self.rng())\n- return self._CheckAgainstNumpy(lax.select, lax_reference.select, args_maker)\n+ return self._CheckAgainstNumpy(lax_reference.select, lax.select, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -1126,7 +1126,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype)]\nop = lambda x: lax.slice(x, starts, limits, strides)\nnumpy_op = lambda x: lax_reference.slice(x, starts, limits, strides)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_start_indices={}_size_indices={}\".format(\n@@ -1167,7 +1167,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype), np.array(start_indices)]\nop = lambda x, s: lax.dynamic_slice(x, s, size_indices)\nnumpy_op = lambda x, s: lax_reference.dynamic_slice(x, s, size_indices)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\ndef testDynamicSliceInDim(self):\n# Regression test for mixed type problem in dynamic_slice_in_dim.\n@@ -1219,8 +1219,8 @@ class LaxTest(jtu.JaxTestCase):\nreturn [rng(shape, dtype), rng(update_shape, dtype),\nnp.array(start_indices)]\n- self._CheckAgainstNumpy(lax.dynamic_update_slice,\n- lax_reference.dynamic_update_slice, args_maker)\n+ self._CheckAgainstNumpy(lax_reference.dynamic_update_slice,\n+ lax.dynamic_update_slice, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_perm={}\".format(\n@@ -1257,7 +1257,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype)]\nop = lambda x: lax.transpose(x, perm)\nnumpy_op = lambda x: lax_reference.transpose(x, perm)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_op={}_inshape={}_reducedims={}_initval={}\"\n@@ -1346,7 +1346,7 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype), init_val]\nself._CompileAndCheck(fun, args_maker)\nif all(d == 1 for d in window_dilation):\n- self._CheckAgainstNumpy(fun, reference_fun, args_maker)\n+ self._CheckAgainstNumpy(reference_fun, fun, args_maker)\n# we separately test the version that uses a concrete init_val because it\n# can hit different code paths\n@@ -1380,7 +1380,7 @@ class LaxTest(jtu.JaxTestCase):\nnp_fun = partial(np_op, axis=axis, dtype=dtype)\nargs_maker = lambda: [rng(shape, dtype)]\nself._CompileAndCheck(fun, args_maker)\n- self._CheckAgainstNumpy(fun, np_fun, args_maker)\n+ self._CheckAgainstNumpy(np_fun, fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_axis={}_isstable={}\".format(\n@@ -1423,7 +1423,7 @@ class LaxTest(jtu.JaxTestCase):\nreturn lax_reference.sort(x, axis, kind='stable')\nelse:\nreturn lax_reference.sort(x, axis)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_keyshape={}_valshape={}_axis={}_isstable={}\".format(\n@@ -1474,7 +1474,7 @@ class LaxTest(jtu.JaxTestCase):\nlax_fun = lambda x: lax.sort(tuple(x), num_keys=num_keys)\nnumpy_fun = lambda x: tuple(x[:, np.lexsort(x[:num_keys][::-1])])\n# self._CompileAndCheck(lax_fun, args_maker)\n- self._CheckAgainstNumpy(lax_fun, numpy_fun, args_maker)\n+ self._CheckAgainstNumpy(numpy_fun, lax_fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_keyshape={}_valshape={}_axis={}\".format(\n@@ -1505,7 +1505,7 @@ class LaxTest(jtu.JaxTestCase):\nop = lambda ks, vs: lax.sort_key_val(ks, vs, axis)\nnumpy_op = lambda ks, vs: lax_reference.sort_key_val(ks, vs, axis)\n- self._CheckAgainstNumpy(op, numpy_op, args_maker)\n+ self._CheckAgainstNumpy(numpy_op, op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_k={}\".format(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_ndimage_test.py",
"new_path": "tests/scipy_ndimage_test.py",
"diff": "@@ -98,9 +98,9 @@ class NdimageTest(jtu.JaxTestCase):\nif dtype in float_dtypes:\nepsilon = max([dtypes.finfo(dtypes.canonicalize_dtype(d)).eps\nfor d in [dtype, coords_dtype]])\n- self._CheckAgainstNumpy(lsp_op, osp_op, args_maker, tol=100*epsilon)\n+ self._CheckAgainstNumpy(osp_op, lsp_op, args_maker, tol=100*epsilon)\nelse:\n- self._CheckAgainstNumpy(lsp_op, osp_op, args_maker, tol=0)\n+ self._CheckAgainstNumpy(osp_op, lsp_op, args_maker, tol=0)\ndef testMapCoordinatesErrors(self):\nx = np.arange(5.0)\n@@ -130,7 +130,7 @@ class NdimageTest(jtu.JaxTestCase):\nlsp_op = lambda x, c: lsp_ndimage.map_coordinates(x, c, order=order)\nosp_op = lambda x, c: osp_ndimage.map_coordinates(x, c, order=order)\n- self._CheckAgainstNumpy(lsp_op, osp_op, args_maker)\n+ self._CheckAgainstNumpy(osp_op, lsp_op, args_maker)\ndef testContinuousGradients(self):\n# regression test for https://github.com/google/jax/issues/3024\n"
}
] | Python | Apache License 2.0 | google/jax | Fix _CheckAgainstNumpy arg order (#3935) |
260,298 | 04.08.2020 09:24:53 | -7,200 | ea6d1dafc2f698a831cfdbb7faf1f4dab47ed102 | [jax2tf] First draft of conversion of population_count.
tf.raw_ops.PopulationCount returns a Tensor with elements of type
uint8. In JAX, the type of the result is the same as the type of
the input, hence the need to use tf.cast in the conversion
function. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -364,7 +364,7 @@ for unexpected in [\n# Primitives that are not yet implemented must be explicitly declared here.\ntf_not_yet_impl = [\n- lax.population_count_p, lax.reduce_p, lax.reduce_window_p, lax.rng_uniform_p,\n+ lax.reduce_p, lax.reduce_window_p, lax.rng_uniform_p,\nlax.select_and_gather_add_p, lax.select_and_scatter_p,\nlax.linear_solve_p,\n@@ -399,6 +399,11 @@ tf_impl[lax.ceil_p] = tf.math.ceil\ntf_impl[lax.round_p] = tf.math.round\ntf_impl[lax.nextafter_p] = tf.math.nextafter\n+def _population_count(x):\n+ orig_dtype = x.dtype\n+ return tf.bitcast(tf.raw_ops.PopulationCount(x=x), orig_dtype)\n+\n+tf_impl[lax.population_count_p] = _population_count\ntf_impl[lax.is_finite_p] = tf.math.is_finite\ntf_impl[lax.abs_p] = tf.math.abs\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -193,6 +193,17 @@ lax_bitwise_not = tuple(\n]]\n)\n+lax_population_count = tuple(\n+ Harness(f\"{jtu.dtype_str(dtype)}\",\n+ lax.population_count,\n+ [arg],\n+ dtype=dtype)\n+ for dtype in jtu.dtypes.all_integer + jtu.dtypes.all_unsigned\n+ for arg in [\n+ np.array([-1, -2, 0, 1], dtype=dtype)\n+ ]\n+)\n+\n_LAX_BINARY_ELEMENTWISE = (\nlax.add, lax.atan2, lax.div, lax.igamma, lax.igammac, lax.max, lax.min,\nlax.nextafter, lax.rem, lax.sub)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -244,6 +244,11 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ndef test_bitwise_not(self, harness):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n+ @primitive_harness.parameterized(primitive_harness.lax_population_count)\n+ def test_population_count(self, harness: primitive_harness.Harness):\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ expect_tf_exceptions=True)\n+\n@primitive_harness.parameterized(primitive_harness.lax_binary_elementwise)\ndef test_binary_elementwise(self, harness):\nif harness.params[\"dtype\"] is dtypes.bfloat16:\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] First draft of conversion of population_count. (#3890)
tf.raw_ops.PopulationCount returns a Tensor with elements of type
uint8. In JAX, the type of the result is the same as the type of
the input, hence the need to use tf.cast in the conversion
function. |
260,287 | 04.08.2020 12:41:30 | 0 | 60db0a073747bd11d654e31a380f23ee9de95ab3 | Improve a comment and a docstring in partial_eval | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -605,6 +605,12 @@ def partial_eval_jaxpr(jaxpr: TypedJaxpr, unknowns: Sequence[bool],\n`jaxpr_known` = lambda ki, ui: let ka = ki + 2\nin (ki + 3, *, ka)\n'jaxpr_unknown` = lambda ki, ui, ka: (*, ui + ka)\n+\n+ Note that if instantiate is True for a given output, then jaxpr_known always returns a\n+ unit in its place. So when instantiate is True, the expectation is the one doesn't\n+ run `jaxpr_known` for any of its outputs, but only to generate residuals that will allow\n+ to obtain the full outputs once `jaxpr_unknown` is ran. Outputs known ahead of time will\n+ simply get passed as residual constants and returned immediately.\n\"\"\"\nf = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\n@@ -618,8 +624,9 @@ def partial_eval_jaxpr(jaxpr: TypedJaxpr, unknowns: Sequence[bool],\ncell.append((out_pvs_2, jaxpr_2, len(consts_2)))\nreturn out_consts_2 + consts_2\n- # For jaxpr_known we pass core.unit for the unknown inputs, and known PartialVal for the\n- # known inputs.\n+ # The abstract_unit here doesn't really matter, because trace_to_jaxpr completely ignores\n+ # the avals, and it will never actually reach any primitives, because the `fun` above will\n+ # execute the jaxpr with the right avals (it reconstructs `pvals` inside).\npvals = [PartialVal.unknown(abstract_unit) if uk else PartialVal.unknown(aval)\nfor aval, uk in zip(jaxpr.in_avals, unknowns)]\njaxpr_1, out_pvals, consts_1 = trace_to_jaxpr(lu.wrap_init(fun), pvals, instantiate=True)\n"
}
] | Python | Apache License 2.0 | google/jax | Improve a comment and a docstring in partial_eval |
260,285 | 06.08.2020 03:36:46 | -7,200 | 2e873b7d050a09dd99881d9339353a18042cf7b3 | Fix jnp.right_shift incorrect on unsigned ints | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -506,7 +506,9 @@ class Tracer:\ndef __rxor__(self, other): return self.aval._rxor(self, other)\ndef __invert__(self): return self.aval._invert(self)\ndef __lshift__(self, other): return self.aval._lshift(self, other)\n+ def __rlshift__(self, other): return self.aval._rlshift(self, other)\ndef __rshift__(self, other): return self.aval._rshift(self, other)\n+ def __rrshift__(self, other): return self.aval._rrshift(self, other)\ndef __getitem__(self, idx): return self.aval._getitem(self, idx)\ndef __nonzero__(self): return self.aval._nonzero(self)\ndef __bool__(self): return self.aval._bool(self)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -394,7 +394,6 @@ add = _maybe_bool_binop(np.add, lax.add, lax.bitwise_or)\nbitwise_and = _one_to_one_binop(np.bitwise_and, lax.bitwise_and)\nbitwise_or = _one_to_one_binop(np.bitwise_or, lax.bitwise_or)\nbitwise_xor = _one_to_one_binop(np.bitwise_xor, lax.bitwise_xor)\n-right_shift = _one_to_one_binop(np.right_shift, lax.shift_right_arithmetic)\nleft_shift = _one_to_one_binop(np.left_shift, lax.shift_left)\nequal = _one_to_one_binop(np.equal, lax.eq)\nmultiply = _maybe_bool_binop(np.multiply, lax.mul, lax.bitwise_and)\n@@ -441,6 +440,14 @@ logical_or = _logical_op(np.logical_or, lax.bitwise_or)\nlogical_xor = _logical_op(np.logical_xor, lax.bitwise_xor)\n+@_wraps(np.right_shift)\n+def right_shift(x1, x2):\n+ x1, x2 = _promote_args(np.right_shift.__name__, x1, x2)\n+ lax_fn = lax.shift_right_logical if \\\n+ np.issubdtype(x1.dtype, np.unsignedinteger) else lax.shift_right_arithmetic\n+ return lax_fn(x1, x2)\n+\n+\n@_wraps(np.absolute)\ndef absolute(x):\nreturn x if issubdtype(_dtype(x), unsignedinteger) else lax.abs(x)\n@@ -4492,6 +4499,8 @@ _operators = {\n\"invert\": bitwise_not,\n\"lshift\": _defer_to_unrecognized_arg(left_shift),\n\"rshift\": _defer_to_unrecognized_arg(right_shift),\n+ \"rlshift\": _defer_to_unrecognized_arg(_swap_args(left_shift)),\n+ \"rrshift\": _defer_to_unrecognized_arg(_swap_args(right_shift)),\n\"round\": _operator_round,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -69,6 +69,9 @@ all_dtypes = number_dtypes + bool_dtypes\npython_scalar_dtypes = [jnp.bool_, jnp.int_, jnp.float_, jnp.complex_]\n+# uint64 is problematic because with any uint type it promotes to float:\n+int_dtypes_no_uint64 = [d for d in int_dtypes + unsigned_dtypes if d != np.uint64]\n+\ndef _valid_dtypes_for_shape(shape, dtypes):\n# Not all (shape, dtype) pairs are valid. In particular, Python scalars only\n# have one type in each category (float, bool, etc.)\n@@ -351,7 +354,8 @@ JAX_OPERATOR_OVERLOADS = [\n# op_record(\"__and__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n# op_record(\"__xor__\", 2, number_dtypes, all_shapes, jtu.rand_bool, []),\n# op_record(\"__divmod__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero, []),\n- # TODO(mattjj): lshift, rshift\n+ op_record(\"__lshift__\", 2, int_dtypes_no_uint64, all_shapes, partial(jtu.rand_int, high=8), []),\n+ op_record(\"__rshift__\", 2, int_dtypes_no_uint64, all_shapes, partial(jtu.rand_int, high=8), []),\n]\nJAX_RIGHT_OPERATOR_OVERLOADS = [\n@@ -370,6 +374,8 @@ JAX_RIGHT_OPERATOR_OVERLOADS = [\n# op_record(\"__rand__\", 2, number_dtypes, all_shapes, jtu.rand_default, []),\n# op_record(\"__rxor__\", 2, number_dtypes, all_shapes, jtu.rand_bool, []),\n# op_record(\"__rdivmod__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero, []),\n+ op_record(\"__rlshift__\", 2, int_dtypes_no_uint64, all_shapes, partial(jtu.rand_int, high=8), []),\n+ op_record(\"__rrshift__\", 2, int_dtypes_no_uint64, all_shapes, partial(jtu.rand_int, high=8), [])\n]\nclass _OverrideEverything(object):\n@@ -392,11 +398,8 @@ if numpy_version >= (1, 15):\nJAX_COMPOUND_OP_RECORDS += [\nop_record(\"isclose\", 2, [t for t in all_dtypes if t != jnp.bfloat16],\nall_shapes, jtu.rand_small_positive, []),\n- # uint64 is problematic because with any other int type it promotes to float.\n- op_record(\"gcd\", 2, [d for d in int_dtypes + unsigned_dtypes if d != np.uint64],\n- all_shapes, jtu.rand_default, []),\n- op_record(\"lcm\", 2, [d for d in int_dtypes + unsigned_dtypes if d != np.uint64],\n- all_shapes, jtu.rand_default, []),\n+ op_record(\"gcd\", 2, int_dtypes_no_uint64, all_shapes, jtu.rand_default, []),\n+ op_record(\"lcm\", 2, int_dtypes_no_uint64, all_shapes, jtu.rand_default, []),\n]\nJAX_REDUCER_NO_DTYPE_RECORDS += [\nop_record(\"ptp\", 1, number_dtypes, nonempty_shapes, jtu.rand_default, []),\n@@ -594,6 +597,35 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ncheck_dtypes=jtu.PYTHON_SCALAR_SHAPE not in shapes)\nself._CompileAndCheck(jnp_op, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": jtu.format_test_name_suffix(op.__name__, shapes, dtypes),\n+ \"op\": op, \"dtypes\": dtypes, \"shapes\": shapes}\n+ for op in [jnp.left_shift, jnp.right_shift]\n+ for shapes in filter(\n+ _shapes_are_broadcast_compatible,\n+ # TODO numpy always promotes to shift dtype for zero-dim shapes:\n+ itertools.combinations_with_replacement(nonzerodim_shapes, 2))\n+ for dtypes in itertools.product(\n+ *(_valid_dtypes_for_shape(s, int_dtypes_no_uint64) for s in shapes))))\n+ def testShiftOpAgainstNumpy(self, op, dtypes, shapes):\n+ dtype, shift_dtype = dtypes\n+ signed_mix = np.issubdtype(dtype, np.signedinteger) != \\\n+ np.issubdtype(shift_dtype, np.signedinteger)\n+ has_32 = any(np.iinfo(d).bits == 32 for d in dtypes)\n+ promoting_to_64 = has_32 and signed_mix\n+ if promoting_to_64 and not FLAGS.jax_enable_x64:\n+ self.skipTest(\"np.right_shift/left_shift promoting to int64\"\n+ \"differs from jnp in 32 bit mode.\")\n+\n+ info, shift_info = map(np.iinfo, dtypes)\n+ x_rng = jtu.rand_int(self.rng(), low=info.min, high=info.max + 1)\n+ # NumPy requires shifts to be non-negative and below the bit width:\n+ shift_rng = jtu.rand_int(self.rng(), high=max(info.bits, shift_info.bits))\n+ args_maker = lambda: (x_rng(shapes[0], dtype), shift_rng(shapes[1], shift_dtype))\n+ self._CompileAndCheck(op, args_maker)\n+ np_op = getattr(np, op.__name__)\n+ self._CheckAgainstNumpy(np_op, op, args_maker)\n+\n@parameterized.named_parameters(itertools.chain.from_iterable(\njtu.cases_from_list(\n{\"testcase_name\": \"{}_inshape={}_axis={}_dtype={}_keepdims={}\".format(\n"
}
] | Python | Apache License 2.0 | google/jax | Fix jnp.right_shift incorrect on unsigned ints (#3958) |
260,299 | 06.08.2020 18:37:32 | -7,200 | 09f4339c165f3885583144644b8fa9d33788e3b3 | Rm two unused lines from lax_parallel.psum_bind | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -955,8 +955,6 @@ def omnistaging_enabler() -> None:\n# tracing time.\n@psum_p.def_custom_bind\ndef psum_bind(*args, axis_name, **params):\n- if len(args) == 1 and not isinstance(args[0], core.Tracer):\n- x, = args\nif all(not isinstance(x, core.Tracer) for x in args):\nif type(axis_name) is tuple:\nsize = prod([core.axis_frame(name).size for name in axis_name]) # type: ignore\n"
}
] | Python | Apache License 2.0 | google/jax | Rm two unused lines from lax_parallel.psum_bind (#3978) |
260,411 | 07.08.2020 13:30:26 | -10,800 | e39420b55d715a6e73aae0691936945975775451 | [jax2tf] Another attempt to work around the nested XLA compilation bug
* [jax2tf] Another attempt to work around the nested compilation bug for XLA
This time we abandon trying to force compilation, and instead we
use XlaDynamicSlice. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -92,36 +92,6 @@ with both [jaxlib](../../../../../#pip-installation) and\n## Known limitations\n-#### Errors due to nested invocations of XLA\n-\n-In some rare cases, running the converted function will result in compilation\n-errors of the form\n-`InvalidArgumentError: Function invoked by the following node is not compilable`.\n-This can be fixed by ensuring that the conversion happens in a compilation context, e.g.:\n-\n-```\n-tf.function(jax2tf.convert(func), experimental_compile=True)(*args)\n-```\n-\n-Explanation: some of the TF operations that are used in the conversion have the\n-correct (i.e., matching JAX) semantics only if they are compiled with XLA. An example\n-is `tf.gather` that for out-of-bounds index has different semantics when XLA\n-is used vs. when XLA is not used. Only the XLA semantics matches the JAX semantics.\n-To work around this problem, the conversion will wrap the use of these TF ops with a\n-`tf.xla.experimental.compile(tf.gather)`. However, there seems to be a problem where the\n-`tf.xla.experimental.compile` cannot be used if we are already in a compilation\n-context (results in the error mentioned above). (See b/162814494).\n-The converter watches for an\n-enclosing compilation context and will not use the compiler if we are already\n-in a compilation context. That is why the solution mentioned above works.\n-\n-One instance when you can still get this error is on TPU, when you use the\n-converted function in graph mode but without invoking the compiler:\n-`tf.function(jax2tf.convert(fun), experimental_compile=False)`. Since there\n-is no compilation context, the converter will apply the compiler internally,\n-but since we are on TPU, when executing the graph the compiler will be called\n-again, resulting in the error.\n-\n#### Converted functions cannot be differentiated when loaded from SavedModel\nTODO\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -48,8 +48,6 @@ import tensorflow as tf # type: ignore[import]\n# pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.compiler.tf2xla.python import xla as tfxla # type: ignore[import]\nfrom tensorflow.compiler.xla import xla_data_pb2 # type: ignore[import]\n-from tensorflow.python.ops import control_flow_util # type: ignore[import]\n-from tensorflow.python.framework import ops # type: ignore[import]\n# A value suitable in a TF tracing context: tf.Tensor, tf.Variable,\n# or Python scalar or numpy.ndarray. (A tf.EagerTensor is a tf.Tensor.)\n@@ -448,32 +446,6 @@ tf_impl[lax.add_p] = wrap_binary_op(tf.math.add)\ntf_impl[lax.sub_p] = wrap_binary_op(tf.math.subtract)\ntf_impl[lax.mul_p] = wrap_binary_op(tf.math.multiply)\n-def _xla_compile(func: Callable, *args: TfVal) -> TfVal:\n- \"\"\"Ensure that the function is compiled with XLA.\n-\n- We do this to ensure that XLA is used for certain operations, so that we\n- can match the JAX semantics. See comments at the callsites for this function.\n- \"\"\"\n- # In some cases, e.g., when we are already in an XLA context due to an outer\n- # tf.function(compile=True), the compilation fails. In those cases, however,\n- # the compilation should not be necessary.\n- in_xla_context = control_flow_util.GraphOrParentsInXlaContext(\n- ops.get_default_graph())\n- if in_xla_context:\n- return func(*args)\n- else:\n- # We don't seem to be in an XLA context, but on TPUs, even the eager\n- # execution is using XLA. Be prepared to catch an exception and\n- # fallback to no-compilation.\n- try:\n- res, = tf.xla.experimental.compile(func, args)\n- return res\n- except tf.errors.InvalidArgumentError as e:\n- if \"Function invoked by the following node is not compilable\" in e.message:\n- return func(*args)\n- else:\n- raise e\n-\ndef _div(lhs, rhs):\nif lhs.dtype.is_integer:\n@@ -752,28 +724,6 @@ tf_impl[lax.rev_p] = _rev\ntf_impl[lax.select_p] = tf.where\n-\n-def _slice(operand, start_indices, limit_indices, strides):\n- if strides is None:\n- strides = [1] * len(start_indices)\n- slices = tuple(map(slice, start_indices, limit_indices, strides))\n- return operand[slices]\n-tf_impl[lax.slice_p] = _slice\n-\n-\n-def _dynamic_slice(operand, *start_indices, slice_sizes=None):\n- # See out-of-bounds index clamping comment for tf.gather\n- return _xla_compile(lambda o, s: tf.slice(o, s, slice_sizes),\n- operand, tf.stack(start_indices))\n-tf_impl[lax.dynamic_slice_p] = _dynamic_slice\n-\n-\n-def _dynamic_update_slice(operand, update, *start_indices):\n- return tfxla.dynamic_update_slice(*promote_types(operand, update),\n- tf.stack(start_indices))\n-tf_impl[lax.dynamic_update_slice_p] = _dynamic_update_slice\n-\n-\ndef _transpose(operand, permutation):\nreturn tf.transpose(operand, permutation)\ntf_impl[lax.transpose_p] = _transpose\n@@ -956,10 +906,12 @@ def _gather_shape(operand, start_indices, dimension_numbers, slice_sizes):\ndef _try_tf_gather(operand, start_indices, dimension_numbers, slice_sizes):\n+ # TODO: this function is not used (see comment for dynamic_slice).\n+\n# Handle only the case when batch_dims=0.\n# Find axis to match the tf.gather semantics\n- # Let I = len(indices_shape)\n+ # Let I = len(start_indices_shape)\n# let O = len(op_shape)\n# slice_sizes == op_shape[:axis] + (1,) + op_shape[axis+1:]\n# collapsed_slice_dims == (axis,)\n@@ -993,27 +945,53 @@ def _try_tf_gather(operand, start_indices, dimension_numbers, slice_sizes):\n# We do not use tf.gather directly because in the non-compiled version it\n# rejects indices that are out of bounds, while JAX and XLA clamps them.\n# We fix this by ensuring that we always compile tf.gather, to use XLA.\n- return _xla_compile(lambda o, s: tf.gather(o, s, axis=axis, batch_dims=0),\n- operand, start_indices_reshaped)\n+ # TODO: see comment for dynamic_slice\n+ return tf.function(lambda o, s: tf.gather(o, s, axis=axis, batch_dims=0),\n+ experimental_compile=True)(operand, start_indices_reshaped)\n@functools.partial(bool_to_int8, argnums=0)\ndef _gather(operand, start_indices, dimension_numbers, slice_sizes):\n\"\"\"Tensorflow implementation of gather.\"\"\"\n- res = _try_tf_gather(operand, start_indices, dimension_numbers, slice_sizes)\n- if res is not None:\n- return res\n+ # TODO: see comment for dynamic_slice\n+ #res = _try_tf_gather(operand, start_indices, dimension_numbers, slice_sizes)\n+ #if res is not None:\n+ # return res\nout_shape = _gather_shape(\noperand, start_indices, dimension_numbers, slice_sizes)\nproto = _gather_dimensions_proto(start_indices.shape, dimension_numbers)\n# We compile because without it we run into a TF bug:\n# tfxla.gather fails on constant inputs with \"must be a compile-time constant\"\n# b/153556869\n- out = _xla_compile(lambda o, s: tfxla.gather(o, s, proto, slice_sizes, False),\n- operand, start_indices)\n+ out = tf.function(lambda o, s: tfxla.gather(o, s, proto, slice_sizes, False),\n+ experimental_compile=True)(operand, start_indices)\nout.set_shape(out_shape)\nreturn out\ntf_impl[lax.gather_p] = _gather\n+def _slice(operand, start_indices, limit_indices, strides):\n+ if strides is None:\n+ strides = [1] * len(start_indices)\n+ slices = tuple(map(slice, start_indices, limit_indices, strides))\n+ return operand[slices]\n+tf_impl[lax.slice_p] = _slice\n+\n+\n+def _dynamic_slice(operand, *start_indices, slice_sizes):\n+ # Here we could use tf.slice. Similarly, for lax.gather we can sometimes use\n+ # tf.gather. But those have different semantics for index-out-of-bounds than\n+ # JAX (and XLA). We have tried to force compilation, by wrapping into\n+ # tf.xla.experimental.compile, or tf.function(experimental_compile=True), but\n+ # those solutions are brittle because they do not work when nested into an\n+ # outer compilation (see b/162814494 and b/163006262). They also do not\n+ # survive well being put in a SavedModel. Hence, we now use TFXLA slicing\n+ # and gather ops.\n+ res = tfxla.dynamic_slice(operand, tf.stack(start_indices),\n+ size_indices=slice_sizes)\n+ # TODO: implement shape inference for XlaShape\n+ res.set_shape(tuple(slice_sizes))\n+ return res\n+\n+tf_impl[lax.dynamic_slice_p] = _dynamic_slice\ndef _scatter_dimensions_proto(indices_shape, dimension_numbers):\nproto = xla_data_pb2.ScatterDimensionNumbers()\n@@ -1046,10 +1024,9 @@ def _scatter(update_computation, operand, scatter_indices, updates,\nxla_update_computation = (\ntf.function(update_computation).get_concrete_function(o_spec, o_spec))\n# We compile due to TF bug, see comment on gather\n- out = _xla_compile(\n- lambda o, s, u: tfxla.scatter(o, s, u, xla_update_computation, proto,\n+ out = tf.function(lambda o, s, u: tfxla.scatter(o, s, u, xla_update_computation, proto,\nindices_are_sorted=indices_are_sorted),\n- operand, scatter_indices, updates)\n+ experimental_compile=True)(operand, scatter_indices, updates)\nout.set_shape(out_shape)\nreturn out\n@@ -1059,6 +1036,11 @@ tf_impl[lax.scatter_max_p] = functools.partial(_scatter, tf.math.maximum)\ntf_impl[lax.scatter_mul_p] = functools.partial(_scatter, tf.math.multiply)\ntf_impl[lax.scatter_add_p] = functools.partial(_scatter, tf.math.add)\n+def _dynamic_update_slice(operand, update, *start_indices):\n+ return tfxla.dynamic_update_slice(*promote_types(operand, update),\n+ tf.stack(start_indices))\n+tf_impl[lax.dynamic_update_slice_p] = _dynamic_update_slice\n+\ndef _cond(index: TfVal, *operands: TfValOrUnit,\nbranches: Sequence[core.TypedJaxpr],\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -496,6 +496,7 @@ lax_slice = tuple(\n[(5,), (5,), (6,), None],\n[(5,), (10,), (11,), None],\n[(5,), (0,), (100,), None],\n+ [(5,), (3,), (6,), None]\n]\nfor dtype in [np.float32]\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -423,9 +423,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# JAX.dynamic_slice rejects slice sizes too big; check this, and skip jax2tf\nargs = harness.dyn_args_maker(self.rng())\nexpect_tf_exceptions = False\n- if jtu.device_under_test() == \"tpu\":\n- # TODO(necula): TPU \"graph\" mode throws \"not compilable\". See README.md\n- expect_tf_exceptions = True\nif any(li - si < 0 or li - si >= sh\nfor sh, si, li in zip(harness.params[\"shape\"],\nharness.params[\"start_indices\"],\n@@ -461,36 +458,21 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_gather)\ndef test_gather(self, harness: primitive_harness.Harness):\n- expect_tf_exceptions = False\n- if jtu.device_under_test() == \"tpu\":\n- # TODO(necula): TPU \"graph\" mode throws \"not compilable\". See README.md\n- expect_tf_exceptions = True\n- self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n- expect_tf_exceptions=expect_tf_exceptions)\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\ndef test_boolean_gather(self):\n- expect_tf_exceptions = False\n- if jtu.device_under_test() == \"tpu\":\n- # TODO(necula): TPU \"graph\" mode throws \"not compilable\". See README.md\n- expect_tf_exceptions = True\nvalues = np.array([[True, True], [False, True], [False, False]],\ndtype=np.bool_)\nindices = np.array([0, 1], dtype=np.int32)\nfor axis in [0, 1]:\nf_jax = jax.jit(lambda v, i: jnp.take(v, i, axis=axis)) # pylint: disable=cell-var-from-loop\n- self.ConvertAndCompare(f_jax, values, indices,\n- expect_tf_exceptions=expect_tf_exceptions)\n+ self.ConvertAndCompare(f_jax, values, indices)\ndef test_gather_rank_change(self):\n- expect_tf_exceptions = False\n- if jtu.device_under_test() == \"tpu\":\n- # TODO(necula): TPU \"graph\" mode throws \"not compilable\". See README.md\n- expect_tf_exceptions = True\nparams = jnp.array([[1.0, 1.5, 2.0], [2.0, 2.5, 3.0], [3.0, 3.5, 4.0]])\nindices = jnp.array([[1, 1, 2], [0, 1, 0]])\nf_jax = jax.jit(lambda i: params[i])\n- self.ConvertAndCompare(f_jax, indices,\n- expect_tf_exceptions=expect_tf_exceptions)\n+ self.ConvertAndCompare(f_jax, indices)\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_{f_jax.__name__}\",\n@@ -513,15 +495,10 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nop=op)\nfor op in INDEX))\ndef test_scatter_static(self, op):\n- expect_tf_exceptions = False\n- if jtu.device_under_test() == \"tpu\":\n- # TODO(necula): TPU \"graph\" mode throws \"not compilable\". See README.md\n- expect_tf_exceptions = True\nvalues = np.ones((5, 6), dtype=np.float32)\nupdate = np.float32(6.)\nf_jax = jax.jit(lambda v, u: op(v, jax.ops.index[::2, 3:], u))\n- self.ConvertAndCompare(f_jax, values, update,\n- expect_tf_exceptions=expect_tf_exceptions)\n+ self.ConvertAndCompare(f_jax, values, update)\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_{f_jax.__name__}\",\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"new_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"diff": "@@ -101,27 +101,39 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(TypeError, \"An op outside of the function building code is being passed\"):\n_ = tape.gradient(y, xv)\n- # TODO: nested compilation bug on TPU. See README.md.\n- @jtu.skip_on_devices(\"tpu\")\n- def test_xla_context_preserved(self):\n+ def _compare_with_saved_model(self, f_jax, *args):\n# Certain ops are converted to ensure an XLA context, e.g.,\n# tf.gather, so that the index-out-of-bounds behavior matches that of\n# JAX. We check that this information is preserved through a savedmodel\n- nr_elements = 10\n- def f_jax(arr):\n- return lax.dynamic_slice(arr, [nr_elements + 1], [1]) # out of bounds, should return the last element\n- arr = np.arange(nr_elements, dtype=np.float32)\n- self.assertEqual(nr_elements - 1, f_jax(arr))\n-\n- f_tf = jax2tf.convert(f_jax) # Even in eager evaluation we get XLA behavior\n- self.assertEqual(nr_elements - 1, f_tf(arr))\n+ f_tf = jax2tf.convert(f_jax)\n+ res = f_tf(*args)\nmodel = tf.Module()\n- model.f = tf.function(jax2tf.convert(f_jax),\n+ input_signature = list(tf.TensorSpec(a.shape, a.dtype) for a in args)\n+ model.f = tf.function(f_tf,\nautograph=False,\n- input_signature=[tf.TensorSpec([nr_elements], tf.float32)])\n+ input_signature=input_signature)\nrestored_model = self.save_and_load_model(model)\n- self.assertEqual(nr_elements - 1, restored_model.f(arr))\n+ res_restored = restored_model.f(*args)\n+ self.assertAllClose(res, res_restored)\n+\n+ def test_xla_context_preserved_slice(self):\n+ arr = np.arange(10, dtype=np.float32)\n+ def f_jax(arr):\n+ return lax.dynamic_slice(arr, [100], [1]) # out of bounds, should return the last element\n+ self._compare_with_saved_model(f_jax, arr)\n+\n+ def test_xla_context_preserved_gather(self):\n+ def f_jax(arr):\n+ return arr[100] # out of bounds, should return the last element\n+ arr = np.arange(10, dtype=np.float32)\n+ if jtu.device_under_test() != \"tpu\":\n+ # TODO(b/153556869): the compilation attributes are not saved in savedmodel\n+ with self.assertRaisesRegex(BaseException, \"Input 2 to .* XlaGather must be a compile-time constant\"):\n+ self._compare_with_saved_model(f_jax, arr)\n+ else:\n+ self._compare_with_saved_model(f_jax, arr)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Another attempt to work around the nested XLA compilation bug (#3965)
* [jax2tf] Another attempt to work around the nested compilation bug for XLA
This time we abandon trying to force compilation, and instead we
use XlaDynamicSlice. |
260,298 | 07.08.2020 17:22:17 | -7,200 | b756f29457a717ab47b791538dc029681e8f5c80 | [jax2tf] implementation of select_and_gather_add conversion.
* [jax2tf] First draft of select_and_gather_add conversion.
The case where we need to reduce precision for packing is left
unimplemented, as packing is anyway a temporary hack until XLA
implements ReduceWindow on tuples (see b/73062247). | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -23,6 +23,7 @@ from jax import ad_util\nfrom jax import api\nfrom jax import core\nfrom jax import custom_derivatives\n+from jax import dtypes\nfrom jax import lax\nfrom jax import linear_util as lu\nfrom jax import numpy as jnp\n@@ -365,7 +366,7 @@ for unexpected in [\n# Primitives that are not yet implemented must be explicitly declared here.\ntf_not_yet_impl = [\nlax.reduce_p, lax.reduce_window_p, lax.rng_uniform_p,\n- lax.select_and_gather_add_p, lax.select_and_scatter_p,\n+ lax.select_and_scatter_p,\nlax.linear_solve_p,\nlax_linalg.cholesky_p, lax_linalg.eig_p, lax_linalg.eigh_p,\n@@ -759,6 +760,75 @@ _max_fn = tf.function(tf.math.maximum)\ntf_impl[lax.cumsum_p] = tf.math.cumsum\ntf_impl[lax.cumprod_p] = tf.math.cumprod\n+def _select_and_gather_add(tangents: TfVal,\n+ operand: TfVal,\n+ select_prim: core.Primitive,\n+ window_dimensions: Sequence[int],\n+ window_strides: Sequence[int],\n+ base_dilation: Sequence[int],\n+ window_dilation: Sequence[int],\n+ padding: Sequence[Tuple[int, int]]):\n+ # Note: this function follows the pattern in\n+ # jax.lax._select_and_gather_add_translation.\n+ dtype = to_jax_dtype(operand.dtype)\n+ nbits = dtypes.finfo(dtype).bits\n+\n+ # Specializing the function for 64 bits. Only up to 32 bits are supported on TPU,\n+ # we thus intend to let the code throw a different exception on this platform.\n+ max_bits = 64\n+\n+ assert nbits <= max_bits\n+ double_word_reduction = nbits * 2 <= max_bits\n+\n+ const = lambda dtype, x: tf.constant(np.array(x), dtype)\n+\n+ if double_word_reduction:\n+ word_dtype = lax.lax._UINT_DTYPES[nbits]\n+ double_word_dtype = lax.lax._UINT_DTYPES[nbits * 2]\n+\n+ # Packs two values into a tuple.\n+ def pack(a, b):\n+ a = _bitcast_convert_type(a, word_dtype)\n+ b = _bitcast_convert_type(b, word_dtype)\n+ a = _convert_element_type(a, double_word_dtype, word_dtype)\n+ b = _convert_element_type(b, double_word_dtype, word_dtype)\n+ a = tf.bitwise.left_shift(a, const(double_word_dtype, nbits))\n+ return tf.bitwise.bitwise_or(a, b)\n+\n+ # Unpacks the first element of a tuple.\n+ def fst(t):\n+ st = _shift_right_logical(t, const(double_word_dtype, nbits))\n+ return _bitcast_convert_type(\n+ _convert_element_type(st, word_dtype, double_word_dtype), dtype\n+ )\n+\n+ # Unpacks the second element of a tuple.\n+ def snd(t):\n+ return _bitcast_convert_type(\n+ _convert_element_type(t, word_dtype, double_word_dtype), dtype\n+ )\n+\n+ else:\n+ raise NotImplementedError(f\"TODO: need to pack {nbits * 2} bits but this platform can only go up to {max_bits} bits.\")\n+\n+ assert select_prim is lax.ge_p or select_prim is lax.le_p, select_prim\n+\n+ def reducer(x, y):\n+ which = tf_impl[select_prim]\n+ return tf_impl[lax.select_p](which(fst(x), fst(y)), x=x, y=y)\n+\n+ init = -np.inf if select_prim is lax.ge_p else np.inf\n+ jax_f = lax._reduce_window_max if select_prim is lax.ge_p else lax._reduce_window_min\n+\n+ out = _reduce_window(jax_f, tf.function(reducer),\n+ pack(const(dtype, init), const(dtype, 0)),\n+ pack(operand, tangents), window_dimensions, window_strides,\n+ padding, base_dilation, window_dilation)\n+\n+ return snd(out)\n+\n+tf_impl[lax.select_and_gather_add_p] = _select_and_gather_add\n+\ndef _reduce_window_shape(jax_f, operand, window_dimensions,\nwindow_strides, padding, base_dilation,\n@@ -793,9 +863,14 @@ def _reduce_window(jax_f, reducer, init_val, operand, window_dimensions,\nout_shape = _reduce_window_shape(jax_f, operand, window_dimensions,\nwindow_strides, padding, base_dilation,\nwindow_dilation)\n- a = tf.constant(0, operand.dtype)\n- reducer_fn = reducer.get_concrete_function(a, a)\n- out = tfxla.reduce_window(operand, tf.constant(init_val, operand.dtype),\n+\n+ o_spec = tf.TensorSpec(operand.shape, dtype=operand.dtype)\n+ reducer_fn = reducer.get_concrete_function(o_spec, o_spec)\n+\n+ if not isinstance(init_val, tf.Tensor):\n+ init_val = tf.constant(init_val, operand.dtype)\n+\n+ out = tfxla.reduce_window(operand, init_val,\nreducer_fn, window_dimensions,\nwindow_strides, base_dilations=base_dilation,\nwindow_dilations=window_dilation, padding=padding)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -586,3 +586,57 @@ lax_shift_right_arithmetic = tuple(\n[arg, StaticArg(np.array([shift_amount], dtype=dtype))])\nfor arg, dtype, shift_amount in shift_inputs\n)\n+\n+lax_select_and_gather_add = tuple(\n+ # Tests with 2d shapes (see tests.lax_autodiff_test.testReduceWindowGrad)\n+ Harness(f\"2d_shape={jtu.format_shape_dtype_string(shape, dtype)}_selectprim={select_prim}_windowdimensions={window_dimensions}_windowstrides={window_strides}_padding={padding}_basedilation={base_dilation}_windowdilation={window_dilation}\",\n+ lax._select_and_gather_add,\n+ [RandArg(shape, dtype), RandArg(shape, dtype), StaticArg(select_prim),\n+ StaticArg(window_dimensions), StaticArg(window_strides),\n+ StaticArg(padding), StaticArg(base_dilation),\n+ StaticArg(window_dilation)],\n+ shape=shape,\n+ dtype=dtype,\n+ window_dimensions=window_dimensions,\n+ window_strides=window_strides,\n+ padding=padding,\n+ base_dilation=base_dilation,\n+ window_dilation=window_dilation)\n+ for dtype in jtu.dtypes.all_floating\n+ for shape in [(4, 6)]\n+ for select_prim in [lax.le_p, lax.ge_p]\n+ for window_dimensions in [(2, 1), (1, 2)]\n+ for window_strides in [(1, 1), (2, 1), (1, 2)]\n+ for padding in tuple(set([tuple(lax.padtype_to_pads(shape, window_dimensions,\n+ window_strides, p))\n+ for p in ['VALID', 'SAME']] +\n+ [((0, 3), (1, 2))]))\n+ for base_dilation in [(1, 1)]\n+ for window_dilation in [(1, 1)]\n+) + tuple(\n+ # Tests with 4d shapes (see tests.lax_autodiff_test.testReduceWindowGrad)\n+ Harness(f\"4d_shape={jtu.format_shape_dtype_string(shape, dtype)}_selectprim={select_prim}_windowdimensions={window_dimensions}_windowstrides={window_strides}_padding={padding}_basedilation={base_dilation}_windowdilation={window_dilation}\",\n+ lax._select_and_gather_add,\n+ [RandArg(shape, dtype), RandArg(shape, dtype), StaticArg(select_prim),\n+ StaticArg(window_dimensions), StaticArg(window_strides),\n+ StaticArg(padding), StaticArg(base_dilation),\n+ StaticArg(window_dilation)],\n+ shape=shape,\n+ dtype=dtype,\n+ window_dimensions=window_dimensions,\n+ window_strides=window_strides,\n+ padding=padding,\n+ base_dilation=base_dilation,\n+ window_dilation=window_dilation)\n+ for dtype in jtu.dtypes.all_floating\n+ for shape in [(3, 2, 4, 6)]\n+ for select_prim in [lax.le_p, lax.ge_p]\n+ for window_dimensions in [(1, 1, 2, 1), (2, 1, 2, 1)]\n+ for window_strides in [(1, 2, 2, 1), (1, 1, 1, 1)]\n+ for padding in tuple(set([tuple(lax.padtype_to_pads(shape, window_dimensions,\n+ window_strides, p))\n+ for p in ['VALID', 'SAME']] +\n+ [((0, 1), (1, 0), (2, 3), (0, 2))]))\n+ for base_dilation in [(1, 1, 1, 1)]\n+ for window_dilation in [(1, 1, 1, 1)]\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -268,6 +268,22 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ncustom_assert=custom_assert,\nalways_custom_assert=True)\n+ @primitive_harness.parameterized(primitive_harness.lax_select_and_gather_add)\n+ def test_select_and_gather_add(self, harness: primitive_harness.Harness):\n+ dtype = harness.params[\"dtype\"]\n+\n+ if dtype is dtypes.bfloat16:\n+ raise unittest.SkipTest(\"bfloat16 not implemented\")\n+\n+ max_bits = 64\n+ if jtu.device_under_test() == \"tpu\":\n+ max_bits = 32\n+\n+ if dtypes.finfo(dtype).bits * 2 > max_bits:\n+ with self.assertRaisesRegex(BaseException, \"XLA encountered an HLO for which this rewriting is not implemented\"):\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n+ else:\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@primitive_harness.parameterized(primitive_harness.lax_unary_elementwise)\ndef test_unary_elementwise(self, harness: primitive_harness.Harness):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1260,6 +1260,29 @@ def _select_and_gather_add(tangents: Array, operand: Array,\npadding: Sequence[Tuple[int, int]],\nbase_dilation: Sequence[int],\nwindow_dilation: Sequence[int]) -> Array:\n+ \"\"\"Extracts the tangent corresponding to the minimum or maximum element in each\n+ window of the `operand` array.\n+\n+ Wraps XLA's `ReduceWindow\n+ <https://www.tensorflow.org/xla/operation_semantics#reducewindow>`_\n+ operator, which applies a reduction function to all elements in each window of the\n+ input multi-dimensional array. In this case, the input multi-dimensional array is\n+ built by packing each element in the `operand` array with its corresponding\n+ element in the `tangents` array.\n+\n+ Args:\n+ tangents: an array\n+ operand: an array with the same shape as `tangents`\n+ select_prim: a reduction function (restricted to `ge_p` and `le_p`)\n+ window_dimensions: an array of integers for window dimension values\n+ window_strides: an array of integers for window stride values\n+ base_dilation: an array of integers for base dilation values\n+ window_dilation: an array of integers for window dilation values\n+\n+ Returns:\n+ An array containing the elements in `tangents` corresponding to the output of the\n+ reduction of `operand` fin each window.\n+ \"\"\"\nreturn select_and_gather_add_p.bind(\ntangents, operand, select_prim=select_prim,\nwindow_dimensions=tuple(window_dimensions),\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] implementation of select_and_gather_add conversion. (#3987)
* [jax2tf] First draft of select_and_gather_add conversion.
The case where we need to reduce precision for packing is left
unimplemented, as packing is anyway a temporary hack until XLA
implements ReduceWindow on tuples (see b/73062247). |
260,355 | 08.08.2020 17:22:54 | -3,600 | 038c85dad0ca6d7b39ccee3f8838d29630f97e8f | Improve type annotations for `jit` and `vmap`. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -29,7 +29,7 @@ import functools\nimport inspect\nimport itertools as it\nimport threading\n-from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union\n+from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, TypeVar, Union\nfrom warnings import warn\nimport numpy as np\n@@ -68,6 +68,17 @@ from .config import flags, config, bool_env\nAxisName = Any\n+# This TypeVar is used below to express the fact that function call signatures\n+# are invariant under the jit, vmap, and pmap transformations.\n+# Specifically, we statically assert that the return type is invariant.\n+# Until PEP-612 is implemented, we cannot express the same invariance for\n+# function arguments.\n+# Note that the return type annotations will generally not strictly hold\n+# in JIT internals, as Tracer values are passed through the function.\n+# Should this raise any type errors for the tracing code in future, we can disable\n+# type checking in parts of the tracing code, or remove these annotations.\n+T = TypeVar(\"T\")\n+\nmap = safe_map\nzip = safe_zip\n@@ -89,9 +100,11 @@ class _ThreadLocalState(threading.local):\n_thread_local_state = _ThreadLocalState()\n-def jit(fun: Callable, static_argnums: Union[int, Iterable[int]] = (),\n- device=None, backend: Optional[str] = None,\n- donate_argnums: Union[int, Iterable[int]] = ()) -> Callable:\n+def jit(fun: Callable[..., T],\n+ static_argnums: Union[int, Iterable[int]] = (),\n+ device=None,\n+ backend: Optional[str] = None,\n+ donate_argnums: Union[int, Iterable[int]] = ()) -> Callable[..., T]:\n\"\"\"Sets up ``fun`` for just-in-time compilation with XLA.\nArgs:\n@@ -756,7 +769,7 @@ def _dtype(x):\nreturn dtypes.canonicalize_dtype(dtypes.result_type(x))\n-def vmap(fun: Callable, in_axes=0, out_axes=0) -> Callable:\n+def vmap(fun: Callable[..., T], in_axes=0, out_axes=0) -> Callable[..., T]:\n\"\"\"Vectorizing map. Creates a function which maps ``fun`` over argument axes.\nArgs:\n@@ -885,7 +898,7 @@ def vmap(fun: Callable, in_axes=0, out_axes=0) -> Callable:\nmsg = \"vmap in_axes leaves must be non-negative integers or None, but got {}.\"\nraise TypeError(msg.format(in_axes))\nif any(l < 0 for l in out_axes_ if l is not batching.last):\n- msg = \"vmap in_axes leaves must be non-negative integers or None, but got {}.\"\n+ msg = \"vmap out_axes leaves must be non-negative integers or None, but got {}.\"\nraise TypeError(msg.format(out_axes))\ndel in_axes_, out_axes_\n@@ -945,11 +958,12 @@ def _mapped_axis_size(tree, vals, dims, name):\nsizes = tree_unflatten(tree, sizes)\nraise ValueError(msg.format(\"the tree of axis sizes is:\\n{}\".format(sizes))) from None\n-def pmap(fun: Callable, axis_name: Optional[AxisName] = None, *, in_axes=0,\n+def pmap(fun: Callable[..., T],\n+ axis_name: Optional[AxisName] = None, *, in_axes=0,\nstatic_broadcasted_argnums: Union[int, Iterable[int]] = (),\ndevices=None, backend: Optional[str] = None,\naxis_size: Optional[int] = None,\n- donate_argnums: Union[int, Iterable[int]] = ()) -> Callable:\n+ donate_argnums: Union[int, Iterable[int]] = ()) -> Callable[..., T]:\n\"\"\"Parallel map with support for collectives.\nThe purpose of :py:func:`pmap` is to express single-program multiple-data (SPMD)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -264,10 +264,10 @@ def split(key: jnp.ndarray, num: int = 2) -> jnp.ndarray:\nReturns:\nAn array with shape (num, 2) and dtype uint32 representing `num` new keys.\n\"\"\"\n- return _split(key, int(num))\n+ return _split(key, int(num)) # type: ignore\n@partial(jit, static_argnums=(1,))\n-def _split(key, num):\n+def _split(key, num) -> jnp.ndarray:\ncounts = lax.iota(np.uint32, num * 2)\nreturn lax.reshape(threefry_2x32(key, counts), (num, 2))\n@@ -364,10 +364,10 @@ def uniform(key: jnp.ndarray,\nf\"got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\n- return _uniform(key, shape, dtype, minval, maxval)\n+ return _uniform(key, shape, dtype, minval, maxval) # type: ignore\n@partial(jit, static_argnums=(1, 2))\n-def _uniform(key, shape, dtype, minval, maxval):\n+def _uniform(key, shape, dtype, minval, maxval) -> jnp.ndarray:\n_check_shape(\"uniform\", shape)\nif not jnp.issubdtype(dtype, np.floating):\nraise TypeError(\"uniform only accepts floating point dtypes.\")\n@@ -473,7 +473,7 @@ def shuffle(key: jnp.ndarray, x: jnp.ndarray, axis: int = 0) -> jnp.ndarray:\nmsg = (\"jax.random.shuffle is deprecated and will be removed in a future release. \"\n\"Use jax.random.permutation\")\nwarnings.warn(msg, FutureWarning)\n- return _shuffle(key, x, axis)\n+ return _shuffle(key, x, axis) # type: ignore\ndef permutation(key, x):\n@@ -504,7 +504,7 @@ def permutation(key, x):\n@partial(jit, static_argnums=(2,))\n-def _shuffle(key, x, axis):\n+def _shuffle(key, x, axis) -> jnp.ndarray:\n# On parallel architectures, Fisher-Yates is more expensive than doing\n# multiple sorts. This algorithm is based on one developed and analyzed by\n# tjablin@. We sort according to randomly-generated 32bit keys, but those keys\n@@ -606,10 +606,10 @@ def normal(key: jnp.ndarray,\nf\"got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\n- return _normal(key, shape, dtype)\n+ return _normal(key, shape, dtype) # type: ignore\n@partial(jit, static_argnums=(1, 2))\n-def _normal(key, shape, dtype):\n+def _normal(key, shape, dtype) -> jnp.ndarray:\n_check_shape(\"normal\", shape)\nlo = np.nextafter(np.array(-1., dtype), 0., dtype=dtype)\nhi = np.array(1., dtype)\n@@ -648,10 +648,10 @@ def multivariate_normal(key: jnp.ndarray,\ndtype = dtypes.canonicalize_dtype(dtype)\nif shape is not None:\nshape = abstract_arrays.canonicalize_shape(shape)\n- return _multivariate_normal(key, mean, cov, shape, dtype)\n+ return _multivariate_normal(key, mean, cov, shape, dtype) # type: ignore\n@partial(jit, static_argnums=(3, 4))\n-def _multivariate_normal(key, mean, cov, shape, dtype):\n+def _multivariate_normal(key, mean, cov, shape, dtype) -> jnp.ndarray:\nif not np.ndim(mean) >= 1:\nmsg = \"multivariate_normal requires mean.ndim >= 1, got mean.ndim == {}\"\nraise ValueError(msg.format(np.ndim(mean)))\n@@ -704,10 +704,10 @@ def truncated_normal(key: jnp.ndarray,\ndtype = dtypes.canonicalize_dtype(dtype)\nif shape is not None:\nshape = abstract_arrays.canonicalize_shape(shape)\n- return _truncated_normal(key, lower, upper, shape, dtype)\n+ return _truncated_normal(key, lower, upper, shape, dtype) # type: ignore\n@partial(jit, static_argnums=(3, 4))\n-def _truncated_normal(key, lower, upper, shape, dtype):\n+def _truncated_normal(key, lower, upper, shape, dtype) -> jnp.ndarray:\nif shape is None:\nshape = lax.broadcast_shapes(np.shape(lower), np.shape(upper))\nelse:\n@@ -746,10 +746,10 @@ def bernoulli(key: jnp.ndarray,\nmsg = \"bernoulli probability `p` must have a floating dtype, got {}.\"\nraise TypeError(msg.format(dtype))\np = lax.convert_element_type(p, dtype)\n- return _bernoulli(key, p, shape)\n+ return _bernoulli(key, p, shape) # type: ignore\n@partial(jit, static_argnums=(2,))\n-def _bernoulli(key, p, shape):\n+def _bernoulli(key, p, shape) -> jnp.ndarray:\nif shape is None:\nshape = np.shape(p)\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | Improve type annotations for `jit` and `vmap`. (#3938) |
260,335 | 10.08.2020 07:20:09 | 25,200 | d46ea969533dbfe4451517ac9a5e51dbdeee6d5d | add helper for flax to be omnistaging-compatible | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1075,6 +1075,15 @@ def trace_to_jaxpr_final(fun: lu.WrappedFun, in_avals: Sequence[AbstractValue]):\ndel master\nreturn jaxpr, out_avals, consts\n+def partial_eval_to_jaxpr_dynamic(fun: lu.WrappedFun, in_pvals: Sequence[PartialVal]):\n+ # This function provides a partial evaluation behavior used by Flax. We can't\n+ # use trace_to_jaxpr directly because of an interaction with the curent\n+ # custom_derivatives.py, which we work around by adding the EvalTrace.\n+ # TODO(mattjj): alias to trace_to_jaxpr after revising custom_derivatives.py\n+ assert config.omnistaging_enabled\n+ with core.new_master(core.EvalTrace, dynamic=True) as _: # type: ignore\n+ return trace_to_jaxpr(fun, in_pvals)\n+\ndef fun_sourceinfo(fun):\nif isinstance(fun, functools.partial):\nfun = fun.func\n"
}
] | Python | Apache License 2.0 | google/jax | add helper for flax to be omnistaging-compatible (#4004) |
260,299 | 10.08.2020 19:09:34 | -7,200 | 89e8a0886b17385556074f1c31d5048981794bb8 | Fix warnings in pmap_test.py
Also add note to developer documentation re: testing pmap. | [
{
"change_type": "MODIFY",
"old_path": "docs/developer.rst",
"new_path": "docs/developer.rst",
"diff": "@@ -116,6 +116,14 @@ the tests of ``jax.numpy.pad`` using::\nThe Colab notebooks are tested for errors as part of the documentation build.\n+Note that to run the full pmap tests on a (multi-core) CPU only machine, you\n+can run::\n+\n+ pytest tests/pmap_tests.py\n+\n+I.e. don't use the `-n auto` option, since that effectively runs each test on a\n+single-core worker.\n+\nType checking\n=============\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -94,6 +94,9 @@ def tearDownModule():\nignore_soft_pmap_warning = partial(\njtu.ignore_warning, message=\"soft_pmap is an experimental.*\")\n+ignore_jit_of_pmap_warning = partial(\n+ jtu.ignore_warning, message=\".*jit-of-pmap.*\")\n+\nclass PmapTest(jtu.JaxTestCase):\ndef _getMeshShape(self, device_mesh_shape):\n@@ -1005,7 +1008,7 @@ class PmapTest(jtu.JaxTestCase):\n# Manually construct a ShardedDeviceArray with the wrong sharding for the\n# subsequent pmap\nshard_shape = (3,2)\n- shard = jnp.arange(jnp.prod(shard_shape)).reshape(shard_shape)\n+ shard = jnp.arange(jnp.prod(jnp.array(shard_shape))).reshape(shard_shape)\nbufs = [xla.device_put(shard, d) for d in xla_bridge.devices()[:4]]\naval = ShapedArray((6,4), shard.dtype)\nsharding_spec = pxla.ShardingSpec(\n@@ -1134,6 +1137,7 @@ class PmapTest(jtu.JaxTestCase):\nx = pmap(lambda x: x)(x)\nx.block_until_ready() # doesn't crash\n+ @ignore_jit_of_pmap_warning()\ndef testJitPmapComposition(self):\nf = lambda x: x - lax.psum(x, 'i')\n@@ -1166,6 +1170,7 @@ class PmapTest(jtu.JaxTestCase):\nf(np.arange(1.).reshape((1, 1))) # doesn't crash\n+ @ignore_jit_of_pmap_warning()\ndef testIssue1065(self):\n# from https://github.com/google/jax/issues/1065\ndevice_count = xla_bridge.device_count()\n@@ -1380,6 +1385,7 @@ class PmapTest(jtu.JaxTestCase):\nf = jax.pmap(outer, axis_name='i')\njtu.check_grads(f, (params,), 2, [\"fwd\", \"rev\"], 1e-3, 1e-3)\n+ @ignore_jit_of_pmap_warning()\ndef test_issue_1062(self):\n# code from https://github.com/google/jax/issues/1062 @shoyer\n# this tests, among other things, whether ShardedDeviceTuple constants work\n@@ -1530,6 +1536,7 @@ class PmapWithDevicesTest(jtu.JaxTestCase):\nexpected = np.ones((ndevices, 1), dtype=jnp.float_) * ndevices * 2\nself.assertAllClose(ans, expected)\n+ @ignore_jit_of_pmap_warning()\ndef testPmapInJit(self):\n@jit\ndef foo(x):\n@@ -1578,7 +1585,7 @@ class ShardedDeviceArrayTest(jtu.JaxTestCase):\nif jax.device_count() < shape[0]:\nraise SkipTest(f\"requires {shape[0]} devices\")\n- x = jnp.arange(jnp.prod(shape)).reshape(shape)\n+ x = jnp.arange(jnp.prod(jnp.array(shape))).reshape(shape)\nsharded_x = pmap(lambda x: x)(x)\nnum_threads = 10\n"
}
] | Python | Apache License 2.0 | google/jax | Fix warnings in pmap_test.py (#3977)
Also add note to developer documentation re: testing pmap. |
260,335 | 10.08.2020 18:11:57 | 25,200 | 6a3b920507dcae7a4e4dfa513155222fa0c6feb1 | make make_jaxpr work on tracer example args
(don't use xla.abstractify) | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1625,7 +1625,7 @@ def make_jaxpr(fun: Callable,\nwrapped, _ = argnums_partial(wrapped, dyn_argnums, args)\njax_args, in_tree = tree_flatten((args, kwargs))\njaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)\n- in_avals = map(xla.abstractify, jax_args)\n+ in_avals = [raise_to_shaped(core.get_aval(x)) for x in jax_args]\nif config.omnistaging_enabled:\njaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(jaxtree_fun, in_avals)\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | make make_jaxpr work on tracer example args (#4014)
(don't use xla.abstractify) |
260,335 | 10.08.2020 20:48:03 | 25,200 | 09d8ac14de8c9edc2c9a14becb4963bfdebda605 | use fewer internal APIs in custom interp notebook | [
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb",
"new_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb",
"diff": "{\n+ \"nbformat\": 4,\n+ \"nbformat_minor\": 0,\n+ \"metadata\": {\n+ \"colab\": {\n+ \"name\": \"Writing custom interpreters in Jax\",\n+ \"provenance\": [],\n+ \"collapsed_sections\": []\n+ },\n+ \"kernelspec\": {\n+ \"display_name\": \"Python 3\",\n+ \"language\": \"python\",\n+ \"name\": \"python3\"\n+ },\n+ \"language_info\": {\n+ \"codemirror_mode\": {\n+ \"name\": \"ipython\",\n+ \"version\": 3\n+ },\n+ \"file_extension\": \".py\",\n+ \"mimetype\": \"text/x-python\",\n+ \"name\": \"python\",\n+ \"nbconvert_exporter\": \"python\",\n+ \"pygments_lexer\": \"ipython3\",\n+ \"version\": \"3.7.3\"\n+ }\n+ },\n\"cells\": [\n{\n\"cell_type\": \"markdown\",\n\"JAX offers several composable function transformations (`jit`, `grad`, `vmap`,\\n\",\n\"etc.) that enable writing concise, accelerated code. \\n\",\n\"\\n\",\n- \"Here we show how to add your own function transformations to the system, by writing a custom Jaxpr interpreter. And we'll get composability with all the other transformations for free.\"\n+ \"Here we show how to add your own function transformations to the system, by writing a custom Jaxpr interpreter. And we'll get composability with all the other transformations for free.\\n\",\n+ \"\\n\",\n+ \"**This example uses internal JAX APIs, which may break at any time. Anything not in [the API Documentation](https://jax.readthedocs.io/en/latest/jax.html) should be assumed internal.**\"\n]\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 1,\n\"metadata\": {\n- \"colab\": {},\n\"colab_type\": \"code\",\n- \"id\": \"s27RDKvKXFL8\"\n+ \"id\": \"s27RDKvKXFL8\",\n+ \"colab\": {}\n},\n- \"outputs\": [],\n\"source\": [\n\"import numpy as np\\n\",\n\"import jax\\n\",\n\"import jax.numpy as jnp\\n\",\n\"from jax import jit, grad, vmap\\n\",\n\"from jax import random\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 2,\n\"metadata\": {\n- \"colab\": {\n- \"height\": 54\n- },\n\"colab_type\": \"code\",\n\"id\": \"HmlMcICOcSXR\",\n- \"outputId\": \"546bf21b-7d03-4364-a087-5802792abbb0\"\n+ \"colab\": {}\n},\n- \"outputs\": [\n- {\n- \"name\": \"stderr\",\n- \"output_type\": \"stream\",\n- \"text\": [\n- \"/usr/local/google/home/sharadmv/workspace/jax/jax/lib/xla_bridge.py:115: UserWarning: No GPU/TPU found, falling back to CPU.\\n\",\n- \" warnings.warn('No GPU/TPU found, falling back to CPU.')\\n\"\n- ]\n- }\n- ],\n\"source\": [\n\"x = random.normal(random.PRNGKey(0), (5000, 5000))\\n\",\n\"def f(w, b, x):\\n\",\n\" return jnp.tanh(jnp.dot(x, w) + b)\\n\",\n\"fast_f = jit(f)\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 3,\n\"metadata\": {\n- \"colab\": {\n- \"height\": 547\n- },\n\"colab_type\": \"code\",\n\"id\": \"RSxEiWi-EeYW\",\n- \"outputId\": \"ee3d4f5c-97d3-4db3-a012-20898920cadb\"\n- },\n- \"outputs\": [\n- {\n- \"name\": \"stdout\",\n- \"output_type\": \"stream\",\n- \"text\": [\n- \"foo\\n\",\n- \"=====\\n\",\n- \"invars: [a]\\n\",\n- \"outvars: [b]\\n\",\n- \"constvars: []\\n\",\n- \"equation: [a, 1] add [b] {}\\n\",\n- \"\\n\",\n- \"jaxpr: { lambda ; ; a.\\n\",\n- \" let b = add a 1\\n\",\n- \" in (b,) }\\n\",\n- \"\\n\",\n- \"\\n\",\n- \"bar\\n\",\n- \"=====\\n\",\n- \"invars: [a, b, c]\\n\",\n- \"outvars: [g, c]\\n\",\n- \"constvars: [f]\\n\",\n- \"equation: [a, c] dot_general [d] {'dimension_numbers': (((1,), (0,)), ((), ())), 'precision': None}\\n\",\n- \"equation: [d, b] add [e] {}\\n\",\n- \"equation: [e, f] add [g] {}\\n\",\n- \"\\n\",\n- \"jaxpr: { lambda f ; ; a b c.\\n\",\n- \" let d = dot_general[ dimension_numbers=(((1,), (0,)), ((), ()))\\n\",\n- \" precision=None ] a c\\n\",\n- \" e = add d b\\n\",\n- \" g = add e f\\n\",\n- \" in (g, c) }\\n\",\n- \"\\n\"\n- ]\n- }\n- ],\n+ \"colab\": {}\n+ },\n\"source\": [\n\"def examine_jaxpr(typed_jaxpr):\\n\",\n\" jaxpr = typed_jaxpr.jaxpr\\n\",\n\"print(\\\"bar\\\")\\n\",\n\"print(\\\"=====\\\")\\n\",\n\"examine_jaxpr(jax.make_jaxpr(bar)(jnp.ones((5, 10)), jnp.ones(5), jnp.ones(10)))\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 4,\n\"metadata\": {\n- \"colab\": {},\n\"colab_type\": \"code\",\n- \"id\": \"BHkg_3P1pXJj\"\n+ \"id\": \"BHkg_3P1pXJj\",\n+ \"colab\": {}\n},\n- \"outputs\": [],\n\"source\": [\n\"# Importing Jax functions useful for tracing/interpreting.\\n\",\n\"import numpy as np\\n\",\n\"from functools import wraps\\n\",\n\"\\n\",\n- \"from jax import api_util\\n\",\n\"from jax import core\\n\",\n\"from jax import lax\\n\",\n- \"from jax import linear_util as lu\\n\",\n- \"from jax import tree_util\\n\",\n- \"from jax.abstract_arrays import ShapedArray\\n\",\n- \"from jax.interpreters import partial_eval as pe\\n\",\n\"from jax.util import safe_map\"\n- ]\n- },\n- {\n- \"cell_type\": \"code\",\n- \"execution_count\": 5,\n- \"metadata\": {\n- \"colab\": {},\n- \"colab_type\": \"code\",\n- \"id\": \"aqHqPjuBqrl9\"\n- },\n- \"outputs\": [],\n- \"source\": [\n- \"def make_jaxpr2(fun):\\n\",\n- \" \\n\",\n- \" def pv_like(x):\\n\",\n- \" # ShapedArrays are abstract values that carry around\\n\",\n- \" # shape and dtype information\\n\",\n- \" aval = ShapedArray(np.shape(x), np.result_type(x))\\n\",\n- \" return pe.PartialVal.unknown(aval)\\n\",\n- \"\\n\",\n- \" @wraps(fun)\\n\",\n- \" def jaxpr_const_maker(*args, **kwargs):\\n\",\n- \" # Set up fun for transformation\\n\",\n- \" wrapped = lu.wrap_init(fun)\\n\",\n- \" # Flatten input args\\n\",\n- \" jax_args, in_tree = tree_util.tree_flatten((args, kwargs))\\n\",\n- \" # Transform fun to accept flat args\\n\",\n- \" # and return a flat list result\\n\",\n- \" jaxtree_fun, out_tree = api_util.flatten_fun(wrapped, in_tree) \\n\",\n- \" # Abstract and partial-val's flat args\\n\",\n- \" pvals = safe_map(pv_like, jax_args)\\n\",\n- \" # Trace function into Jaxpr\\n\",\n- \" jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals) \\n\",\n- \" return jaxpr, consts, (in_tree, out_tree())\\n\",\n- \" return jaxpr_const_maker\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 6,\n\"metadata\": {\n- \"colab\": {\n- \"height\": 119\n- },\n\"colab_type\": \"code\",\n\"id\": \"Tc1REN5aq_fH\",\n- \"outputId\": \"2e6f2833-5139-48ef-da3f-01ea9cd6a7d3\"\n+ \"colab\": {}\n},\n- \"outputs\": [\n- {\n- \"name\": \"stdout\",\n- \"output_type\": \"stream\",\n- \"text\": [\n- \"{ lambda ; ; a.\\n\",\n- \" let b = tanh a\\n\",\n- \" c = exp b\\n\",\n- \" in (c,) }\\n\",\n- \"\\n\",\n- \"()\\n\"\n- ]\n- }\n- ],\n\"source\": [\n\"def f(x):\\n\",\n\" return jnp.exp(jnp.tanh(x))\\n\",\n- \"jaxpr, consts, _ = make_jaxpr2(f)(jnp.ones(5))\\n\",\n- \"print(jaxpr)\\n\",\n- \"print(consts)\"\n- ]\n+ \"\\n\",\n+ \"closed_jaxpr = jax.make_jaxpr(f)(jnp.ones(5))\\n\",\n+ \"print(closed_jaxpr)\\n\",\n+ \"print(closed_jaxpr.literals)\"\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n\"id\": \"WmZ3BcmZsbfR\"\n},\n\"source\": [\n- \"This particular function doesn't have any example constants, but in general, this is how you both trace into a Jaxpr and extract the constants.\\n\",\n- \"\\n\",\n\"### 2. Evaluating a Jaxpr\\n\",\n\"\\n\",\n\"\\n\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 7,\n\"metadata\": {\n- \"colab\": {},\n\"colab_type\": \"code\",\n- \"id\": \"ACMxjIHStHwD\"\n+ \"id\": \"ACMxjIHStHwD\",\n+ \"colab\": {}\n},\n- \"outputs\": [],\n\"source\": [\n\"def eval_jaxpr(jaxpr, consts, *args):\\n\",\n\" # Mapping from variable -> value\\n\",\n\" safe_map(write, eqn.outvars, outvals) \\n\",\n\" # Read the final result of the Jaxpr from the environment\\n\",\n\" return safe_map(read, jaxpr.outvars) \"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 8,\n\"metadata\": {\n- \"colab\": {\n- \"height\": 51\n- },\n\"colab_type\": \"code\",\n\"id\": \"mGHPc3NruCFV\",\n- \"outputId\": \"3f459905-02ad-4f43-e70f-3db0a5ff58e4\"\n+ \"colab\": {}\n},\n- \"outputs\": [\n- {\n- \"data\": {\n- \"text/plain\": [\n- \"[DeviceArray([2.14168763, 2.14168763, 2.14168763, 2.14168763, 2.14168763],\\n\",\n- \" dtype=float32)]\"\n- ]\n- },\n- \"execution_count\": 8,\n- \"metadata\": {},\n- \"output_type\": \"execute_result\"\n- }\n- ],\n\"source\": [\n- \"jaxpr, consts, _ = make_jaxpr2(f)(jnp.ones(5))\\n\",\n- \"eval_jaxpr(jaxpr, consts, jnp.ones(5))\"\n- ]\n+ \"closed_jaxpr = jax.make_jaxpr(f)(jnp.ones(5))\\n\",\n+ \"eval_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.literals, jnp.ones(5))\"\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n\"id\": \"XhZhzbVBvAiT\"\n},\n\"source\": [\n- \"Notice that `eval_jaxpr` will always return a list even if the original function does not. To \\\"unflatten\\\" the list into what the function was originally supposed to return, we can use the `out_tree` object returned by `trace`. \\n\",\n+ \"Notice that `eval_jaxpr` will always return a flat list even if the original function does not.\\n\",\n\"\\n\",\n\"Furthermore, this interpreter does not handle `subjaxprs`, which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/master/jax/core.py#L185-L212)) to see the edge cases that this interpreter does not cover.\"\n]\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 9,\n\"metadata\": {\n- \"colab\": {},\n\"colab_type\": \"code\",\n- \"id\": \"gSMIT2z1vUpO\"\n+ \"id\": \"gSMIT2z1vUpO\",\n+ \"colab\": {}\n},\n- \"outputs\": [],\n\"source\": [\n\"inverse_registry = {}\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 10,\n\"metadata\": {\n- \"colab\": {},\n\"colab_type\": \"code\",\n- \"id\": \"fUerorGkCqhw\"\n+ \"id\": \"fUerorGkCqhw\",\n+ \"colab\": {}\n},\n- \"outputs\": [],\n\"source\": [\n\"inverse_registry[lax.exp_p] = jnp.log\\n\",\n\"inverse_registry[lax.tanh_p] = jnp.arctanh\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 11,\n\"metadata\": {\n- \"colab\": {},\n\"colab_type\": \"code\",\n- \"id\": \"jGNfV6JJC1B3\"\n+ \"id\": \"jGNfV6JJC1B3\",\n+ \"colab\": {}\n},\n- \"outputs\": [],\n\"source\": [\n\"def inverse(fun):\\n\",\n\" @wraps(fun)\\n\",\n\" # Since we assume unary functions, we won't\\n\",\n\" # worry about flattening and\\n\",\n\" # unflattening arguments\\n\",\n- \" jaxpr, consts, _ = make_jaxpr2(fun)(*args, **kwargs)\\n\",\n- \" out = inverse_jaxpr(jaxpr, consts, *args)\\n\",\n+ \" closed_jaxpr = jax.make_jaxpr(fun)(*args, **kwargs)\\n\",\n+ \" out = inverse_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.literals, *args)\\n\",\n\" return out[0]\\n\",\n\" return wrapped\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 12,\n\"metadata\": {\n- \"colab\": {},\n\"colab_type\": \"code\",\n- \"id\": \"uUAd-L-BDKT5\"\n+ \"id\": \"uUAd-L-BDKT5\",\n+ \"colab\": {}\n},\n- \"outputs\": [],\n\"source\": [\n\"def inverse_jaxpr(jaxpr, consts, *args):\\n\",\n\" env = {}\\n\",\n\" outval = inverse_registry[eqn.primitive](*invals)\\n\",\n\" safe_map(write, eqn.invars, [outval])\\n\",\n\" return safe_map(read, jaxpr.invars)\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 13,\n\"metadata\": {\n- \"colab\": {\n- \"height\": 71\n- },\n\"colab_type\": \"code\",\n\"id\": \"cjEKWso-D5Bu\",\n- \"outputId\": \"54e73a42-a908-448c-d6d5-e6d0fe9adbf9\"\n+ \"colab\": {}\n},\n- \"outputs\": [\n- {\n- \"name\": \"stderr\",\n- \"output_type\": \"stream\",\n- \"text\": [\n- \"/usr/local/google/home/sharadmv/workspace/jax/jax/numpy/lax_numpy.py:220: RuntimeWarning: divide by zero encountered in arctanh\\n\",\n- \" return _dtype(op(*args))\\n\"\n- ]\n- }\n- ],\n\"source\": [\n\"def f(x):\\n\",\n\" return jnp.exp(jnp.tanh(x))\\n\",\n+ \"\\n\",\n\"f_inv = inverse(f)\\n\",\n\"assert jnp.allclose(f_inv(f(1.0)), 1.0)\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 14,\n\"metadata\": {\n- \"colab\": {\n- \"height\": 238\n- },\n\"colab_type\": \"code\",\n\"id\": \"j6ov_rveHmTb\",\n- \"outputId\": \"a7a9b4be-f284-4e78-c469-d84e352d838d\"\n- },\n- \"outputs\": [\n- {\n- \"data\": {\n- \"text/plain\": [\n- \"{ lambda ; ; a.\\n\",\n- \" let b = log a\\n\",\n- \" c = abs b\\n\",\n- \" d = le c 1.0\\n\",\n- \" e = add b 1.0\\n\",\n- \" f = sub 1.0 b\\n\",\n- \" g = div e f\\n\",\n- \" h = log g\\n\",\n- \" i = mul h 0.5\\n\",\n- \" j = tie_in b nan\\n\",\n- \" k = broadcast[ sizes=() ] j\\n\",\n- \" l = select d i k\\n\",\n- \" in (l,) }\"\n- ]\n+ \"colab\": {}\n},\n- \"execution_count\": 14,\n- \"metadata\": {},\n- \"output_type\": \"execute_result\"\n- }\n- ],\n\"source\": [\n\"jax.make_jaxpr(inverse(f))(f(1.))\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n},\n{\n\"cell_type\": \"code\",\n- \"execution_count\": 15,\n\"metadata\": {\n- \"colab\": {\n- \"height\": 51\n- },\n\"colab_type\": \"code\",\n\"id\": \"3tjNk21CH4yZ\",\n- \"outputId\": \"4c6d2090-0558-4171-8dce-0ea681ef6e53\"\n+ \"colab\": {}\n},\n- \"outputs\": [\n- {\n- \"data\": {\n- \"text/plain\": [\n- \"DeviceArray([ 0. , 15.58493137, 2.25512528, 1.31550276,\\n\",\n- \" 1. ], dtype=float32)\"\n- ]\n- },\n- \"execution_count\": 15,\n- \"metadata\": {},\n- \"output_type\": \"execute_result\"\n- }\n- ],\n\"source\": [\n\"jit(vmap(grad(inverse(f))))((jnp.arange(5) + 1.) / 5.)\"\n- ]\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n\"* Handle `xla_call` and `xla_pmap` primitives, which will not work with both `eval_jaxpr` and `inverse_jaxpr` as written.\"\n]\n}\n- ],\n- \"metadata\": {\n- \"colab\": {\n- \"collapsed_sections\": [],\n- \"name\": \"Writing custom interpreters in Jax\",\n- \"provenance\": []\n- },\n- \"kernelspec\": {\n- \"display_name\": \"Python 3\",\n- \"language\": \"python\",\n- \"name\": \"python3\"\n- },\n- \"language_info\": {\n- \"codemirror_mode\": {\n- \"name\": \"ipython\",\n- \"version\": 3\n- },\n- \"file_extension\": \".py\",\n- \"mimetype\": \"text/x-python\",\n- \"name\": \"python\",\n- \"nbconvert_exporter\": \"python\",\n- \"pygments_lexer\": \"ipython3\",\n- \"version\": \"3.7.3\"\n- }\n- },\n- \"nbformat\": 4,\n- \"nbformat_minor\": 1\n+ ]\n}\n\\ No newline at end of file\n"
}
] | Python | Apache License 2.0 | google/jax | use fewer internal APIs in custom interp notebook (#4016) |
260,411 | 11.08.2020 12:39:54 | -10,800 | 0b99ca896d8cfecd737af71f1a140b9956143d4c | [jax2tf] Disable the CI tests for jax2tf.
We do this to see if this reduces the incidence of errors fetching
the tf-nightly package. These tests are being run when we import
the code in Google. | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/ci-build.yaml",
"new_path": ".github/workflows/ci-build.yaml",
"diff": "@@ -110,9 +110,6 @@ jobs:\necho \"JAX_NUM_GENERATED_CASES=$JAX_NUM_GENERATED_CASES\"\necho \"JAX_ENABLE_X64=$JAX_ENABLE_X64\"\necho \"JAX_OMNISTAGING=$JAX_OMNISTAGING\"\n- if [ $JAX_ENABLE_X64 = 0 -a $JAX_OMNISTAGING = 0 ]; then\n- pytest -n auto jax/experimental/jax2tf/tests\n- fi\npytest -n auto tests examples\n"
},
{
"change_type": "MODIFY",
"old_path": "build/test-requirements.txt",
"new_path": "build/test-requirements.txt",
"diff": "@@ -4,6 +4,4 @@ mypy==0.770\npillow\npytest-benchmark\npytest-xdist\n-# jax2tf needs some fixes that are not in latest tensorflow\n-tf-nightly==2.4.0.dev20200729\nwheel\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Disable the CI tests for jax2tf. (#4019)
We do this to see if this reduces the incidence of errors fetching
the tf-nightly package. These tests are being run when we import
the code in Google. |
260,287 | 11.08.2020 11:45:58 | -7,200 | cd54dd977897f868c3f55723604054d43db801e8 | Implement the invertible decorator in terms of custom_vjp
This simplifies the implementation significantly, as we can piggyback
off of all the logic for custom derivatives. For example, the previous
implementation didn't support differentiating with respect to a subset
of function parameters, but the new one does. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -2044,7 +2044,7 @@ def custom_gradient(fun):\ndef _ensure_tuple(x: Union[int, Iterable[int]]) -> Tuple[int, ...]:\nreturn (x,) if isinstance(x, int) else tuple(x)\n-def invertible(fun: Callable, concrete: bool = False) -> Callable:\n+def invertible(fun: Callable) -> Callable:\n\"\"\"Asserts that the decorated function is invertible.\nApplying reverse-mode AD to a decorated function will use a more memory efficient\n@@ -2054,13 +2054,5 @@ def invertible(fun: Callable, concrete: bool = False) -> Callable:\nArgs:\nfun: The function assumed to be invertible.\n- concrete: See the documentation of checkpoint.\n\"\"\"\n- @wraps(fun)\n- def fun_invertible(*args, **kwargs):\n- args_flat, in_tree = tree_flatten((args, kwargs))\n- flat_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n- out_flat = iad.invertible_call(flat_fun, *args_flat, name=flat_fun.__name__,\n- concrete=concrete)\n- return tree_unflatten(out_tree(), out_flat)\n- return fun_invertible\n+ return iad.invertible(fun)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/invertible_ad.py",
"new_path": "jax/interpreters/invertible_ad.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import warnings\nfrom functools import partial\nfrom typing import Dict, Any, Callable\n@@ -20,12 +21,10 @@ from jax import core\nfrom jax import linear_util as lu\nfrom . import ad\nfrom . import partial_eval as pe\n-from .partial_eval import PartialVal, new_eqn_recipe, _partition_knowns\nfrom ..core import raise_to_shaped, get_aval, Literal, Jaxpr\nfrom ..api_util import flatten_fun_nokwargs\n-from ..tree_util import tree_flatten, tree_unflatten\n-from ..util import safe_map, safe_zip, unzip2, split_list, cache\n-from .. import source_info_util\n+from ..tree_util import tree_flatten, tree_unflatten, register_pytree_node\n+from ..util import safe_map, safe_zip, unzip2, split_list\nfrom .. import custom_derivatives\nfrom ..config import config\n@@ -36,68 +35,45 @@ zip = safe_zip\n# Reverse call primitive\n################################################################################\n-invertible_call_p = core.CallPrimitive('invertible_call')\n-invertible_call = invertible_call_p.bind\n-invertible_call_p.def_impl(core.call_impl)\n-\n-def _invertible_call_make_output_tracers(trace, in_tracers, out_tracers, params):\n- uks = [not t.pval.is_known() for t in out_tracers]\n- out_tracers_known, out_tracers_unknown = _partition_knowns(out_tracers, uks)\n-\n- # Add dummy arguments representing the outputs to the jaxpr. Those should\n- # remain unused if the expression is evaluated, but they make it well-formed.\n- out_known_avals = [raise_to_shaped(t.pval.get_aval()) for t in out_tracers_known]\n- out_consts = [trace.instantiate_const(t) for t in out_tracers_known]\n- new_jaxpr = _append_invars(params['call_jaxpr'], tuple(out_known_avals))\n- new_in_tracers = (*in_tracers, *out_consts)\n-\n- # Append dummy outputs that correspond to known outputs left in the call_jaxpr\n- dummy_outputs = [trace.new_const(t.pval.get_known()) for t in out_tracers_known]\n- new_out_tracers = (*dummy_outputs, *out_tracers_unknown)\n-\n- eqn = new_eqn_recipe(new_in_tracers, new_out_tracers, invertible_call_p,\n- dict(params, call_jaxpr=new_jaxpr),\n- source_info_util.current())\n- for t in out_tracers_unknown: t.recipe = eqn\n- return new_out_tracers\n-\n-pe.call_partial_eval_rules[invertible_call_p] = partial(\n- pe._remat_partial_eval, _invertible_call_make_output_tracers)\n-\n-@cache()\n-def _append_invars(jaxpr, avals):\n- newvar = core.gensym([jaxpr])\n- return core.Jaxpr(jaxpr.constvars, jaxpr.invars + map(newvar, avals),\n- jaxpr.outvars, jaxpr.eqns)\n-\n-\n-def _invertible_call_transpose(params, call_jaxpr, args, ct, _):\n- # TODO: Is the vjp invertible too? In principle yes, because the derivative is\n- # a linear transform with coefficients derived from the primal, but do we\n- # want to preserve this annotation?\n-\n- # All this code is an awkward attempt to inverse engineer the structure of our\n- # arguments in a way that lets us separate primal arguments and constants from the\n- # primal outputs. We need to do that, because even though the jaxpr has arguments\n- # corresponding to the primal outputs, we need to fill them in in the primal environment\n- # under the names corresponding to the outvars of the jaxpr.\n- # The general idea here is that due to the way linearization works, all tangent\n- # arguments always come after all the primal args. Additionally, _inverse_partial_eval\n- # appends the constants corresponding to primal outputs as trailing arguments.\n- # In the end we expect is_tangent to be of the form:\n- # [False, ..., False, True, ..., True, False, ..., False]\n- # where the first primal block gives us the constants and regular primal args,\n- # while the second block gives us the saved primal outputs.\n- is_tangent = map(ad.is_undefined_primal, args)\n- first_tangent = is_tangent.index(True)\n- last_tangent = (len(is_tangent) - 1) - is_tangent[::-1].index(True)\n- # Make sure that there are some primals before and after the tangent segment\n- assert first_tangent > 0 and last_tangent < len(is_tangent)\n- # Make sure that the tangents form a contiguous range\n- assert all(is_tangent[first_tangent:last_tangent + 1])\n- outputs = args[last_tangent + 1:]\n- return inv_backward_pass(call_jaxpr, (), args, outputs, ct)\n-ad.primitive_transposes[invertible_call_p] = _invertible_call_transpose\n+class DontFlatten:\n+ def __init__(self, val):\n+ self.val = val\n+\n+register_pytree_node(DontFlatten,\n+ lambda x: ((), x.val),\n+ lambda val, _: DontFlatten(val))\n+\n+def get_concrete_array(aval):\n+ assert isinstance(aval, core.ConcreteArray), aval\n+ return aval.val\n+\n+def invertible(fun):\n+ # TODO: Avoid materializing zeros!\n+ ifun = custom_derivatives.custom_vjp(fun)\n+\n+ def fwd(*args):\n+ flat_args, in_tree = tree_flatten(args)\n+ in_pvals = tuple(pe.PartialVal.unknown(raise_to_shaped(get_aval(arg))) for arg in flat_args)\n+ fun_flat, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\n+ jaxpr, out_pvals, consts = pe.trace_to_jaxpr(fun_flat, in_pvals)\n+ # TODO: Don't warn if consts contain JVP tracers?\n+ if consts:\n+ warnings.warn(\"Values that an @invertible function closes over will not have their \" +\n+ \"gradients computed correctly (their uses inside this function will be ignored)!\")\n+ # TODO: This requires the body to be jittable, but this shouldn't be necessary.\n+ # Is there a way to trace a jaxpr while running it?\n+ outs = core.eval_jaxpr(jaxpr, consts, *flat_args)\n+ return tree_unflatten(out_tree(), outs), (args, outs, consts, DontFlatten((jaxpr, in_tree)))\n+\n+ def bwd(res, cts):\n+ args, outs, consts, aux = res\n+ jaxpr, in_tree = aux.val\n+ flat_cts, _ = tree_flatten(cts)\n+ return tree_unflatten(in_tree, inv_backward_pass(jaxpr, consts, args, outs, flat_cts))\n+\n+ ifun.defvjp(fwd, bwd)\n+\n+ return ifun\n################################################################################\n# Custom inverse\n@@ -114,7 +90,7 @@ class custom_ivjp:\ndef __call__(self, *args, **kwargs):\nif self.ivjp is None:\n- msg = \"No VJP defined for custom_vjp function {}. Did you forget to use defivjp?\"\n+ msg = \"No IVJP defined for custom_vjp function {}. Did you forget to use defivjp?\"\nraise AttributeError(msg.format(self.__name__))\nargs = custom_derivatives._resolve_kwargs(self.fun, args, kwargs)\n# TODO: Support nondiff_argnums\n@@ -176,7 +152,7 @@ ad.primitive_jvps[custom_ivjp_p] = _custom_ivjp_jvp\ndef inv_backward_pass(jaxpr: core.Jaxpr, consts, primals_in, primals_out, cotangents_in):\nif all(type(ct) is ad.Zero for ct in cotangents_in):\n- return zero_vars(jaxpr.invars)\n+ return map(lambda v: ad.Zero(v.aval), jaxpr.invars)\ndef write_cotangent(v, ct):\n# assert v not in primal_env\n@@ -197,34 +173,15 @@ def inv_backward_pass(jaxpr: core.Jaxpr, consts, primals_in, primals_out, cotang\nreturn\nprimal_env.setdefault(v, val)\n- # Structure of arguments is [primal_invars, tangent_invars, unused_primal_outvar_placeholders]\n- primal_invars, tangent_invars = split(jaxpr.invars[:-len(primals_out)], parts=2)\n- primal_outvars, tangent_outvars = split(jaxpr.outvars, parts=2)\n-\n- def is_tangent(var):\n- return type(var) is not Literal and var in tangent_vars\n-\n- tangent_vars = set(tangent_invars)\n- primal_eqns = []\n- tangent_eqns = []\n- for eqn in jaxpr.eqns:\n- if not eqn.primitive.call_primitive:\n- if any(map(is_tangent, eqn.invars)):\n- tangent_eqns.append(eqn)\n- tangent_vars.update(eqn.outvars)\n- else:\n- primal_eqns.append(eqn)\n- else:\n- assert False\n-\n- # Invert while computing the cotangents\n+ # Invert while computing cotangents\nct_env: Dict[Any, Any] = {}\nprimal_env: Dict[Any, Any] = {}\nwrite_primal(core.unitvar, core.unit)\nmap(write_primal, jaxpr.invars, primals_in)\n- map(write_primal, jaxpr.outvars[:len(primals_out)], primals_out)\n- map(write_cotangent, primal_outvars, split(cotangents_in, parts=2)[1])\n- for eqn in primal_eqns[::-1]:\n+ map(write_primal, jaxpr.outvars, primals_out)\n+ map(write_primal, jaxpr.constvars, consts)\n+ map(write_cotangent, jaxpr.outvars, cotangents_in)\n+ for eqn in jaxpr.eqns[::-1]:\nprimals_in = map(read_primal, eqn.invars)\nprimals_out = map(read_primal, eqn.outvars)\ncts_in = map(read_cotangent, eqn.outvars)\n@@ -256,11 +213,12 @@ def inv_backward_pass(jaxpr: core.Jaxpr, consts, primals_in, primals_out, cotang\nin_avals = map(abstract, primals_in + primals_out + primals_out)\nif config.omnistaging_enabled:\n+ # TODO: Actually we do know some of the inputs, because they might be literals!\nivjp_jaxpr, out_pvals, _ = pe.trace_to_jaxpr(\n- complete_ivjp_flat, map(PartialVal.unknown, in_avals), instantiate=True)\n+ complete_ivjp_flat, map(pe.PartialVal.unknown, in_avals), instantiate=True)\nelse:\nivjp_jaxpr, out_pvals, _ = pe.trace_to_jaxpr(\n- complete_ivjp_flat, map(PartialVal.unknown, in_avals),\n+ complete_ivjp_flat, map(pe.PartialVal.unknown, in_avals),\ninstantiate=True, stage_out=False)\nassert not ivjp_jaxpr.constvars # That might happen some time, but don't bother until then\nout_avals = map(raise_to_shaped, unzip2(out_pvals)[0])\n@@ -284,8 +242,9 @@ def inv_backward_pass(jaxpr: core.Jaxpr, consts, primals_in, primals_out, cotang\n# failing to compute cotangents later.\nassert not any(unknown_cotangents)\n# Remove residual outputs -- we won't be computing the unknown jaxpr anyway.\n- jaxpr_known.out_avals = jaxpr_known.out_avals[:num_inputs * 2]\n- jaxpr_known.jaxpr.outvars = jaxpr_known.jaxpr.outvars[:num_inputs * 2]\n+ num_outputs = len(jaxpr_unknown.jaxpr.outvars)\n+ jaxpr_known.out_avals = jaxpr_known.out_avals[:num_outputs]\n+ jaxpr_known.jaxpr.outvars = jaxpr_known.jaxpr.outvars[:num_outputs]\n# TODO: We could drop the outputs that correspond to primals that we already know.\n# This only matters in eager mode, so leaving it out for now...\nivjp = core.jaxpr_as_fun(jaxpr_known)\n@@ -297,15 +256,12 @@ def inv_backward_pass(jaxpr: core.Jaxpr, consts, primals_in, primals_out, cotang\nfor prev, rec, unknown\nin zip(primals_in, rec_primals_in, unknown_rec_primals_in)]\nmap(write_primal, eqn.invars, rec_primals_in)\n- map(write_cotangent, eqn.invars, cts_out)\n+ map(write_cotangent, [v for v in eqn.invars if type(v) is not Literal], cts_out)\n# NOTE: We keep the cotangents associated with primal variables, while the contract of a\n# transpose is to return them in positions associated with tangent variables, which\n# is what causes this whole confusion.\n- return zero_vars(primal_invars) + map(read_cotangent, primal_invars) + zero_vars(primals_out)\n-\n-def zero_vars(vs):\n- return map(lambda v: ad.Zero(v.aval), vs)\n+ return map(read_cotangent, jaxpr.invars)\nprimitive_ivjps: Dict[core.Primitive, Callable] = {}\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -663,12 +663,7 @@ remat_call_p = core.CallPrimitive('remat_call')\nremat_call = remat_call_p.bind\nremat_call_p.def_impl(core.call_impl)\n-# We reuse the _remat_partial_eval function both for remat_call and for\n-# invertible_call, both of which in a sense stage out operations to\n-# rematerialize values. The two usages differ only in details of what jaxpr eqn\n-# and output tracers are formed. As a result we parameterize _remat_partial_eval\n-# by a `process_out` function.\n-def _remat_partial_eval(process_out, trace, _, f, tracers, params):\n+def _remat_partial_eval(trace, _, f, tracers, params):\nconcrete = params['concrete']\n# Unlike JaxprTrace.process_call, we want to form a jaxpr for the entirety of\n@@ -744,29 +739,18 @@ def _remat_partial_eval(process_out, trace, _, f, tracers, params):\n# Unknown outputs get wrapped in tracers with the appropriate recipe\nunknown_output_tracers = [JaxprTracer(trace, out_pval, None)\nfor out_pval in out_unknown_pvals]\n- out_tracers = _zip_knowns(known_output_tracers, unknown_output_tracers, out_unknowns)\n- in_tracers = (*const_tracers, *env_tracers, *instantiated_tracers)\n- new_params = dict(params, call_jaxpr=convert_constvars_jaxpr(typed_jaxpr.jaxpr))\n- return process_out(trace, in_tracers, out_tracers, new_params)\n-\n-def _remat_make_output_tracers(_, in_tracers, out_tracers, params):\n# dce jaxpr outputs\n- jaxpr = params['call_jaxpr']\n- out_unknowns = [not t.pval.is_known() for t in out_tracers]\n- typed_jaxpr = core.TypedJaxpr(jaxpr, (), [v.aval for v in jaxpr.invars],\n- [v.aval for v in jaxpr.outvars])\nnew_jaxpr = _dce_jaxpr(typed_jaxpr, out_unknowns, drop_outputs=True).jaxpr\nnew_params = dict(params, call_jaxpr=new_jaxpr)\n# set up eqn for unknown outputs\n- unknown_out_tracers = [t for t in out_tracers if not t.pval.is_known()]\n- eqn = new_eqn_recipe(in_tracers, unknown_out_tracers, remat_call_p, new_params,\n+ in_tracers = (*const_tracers, *env_tracers, *instantiated_tracers)\n+ eqn = new_eqn_recipe(in_tracers, unknown_output_tracers, remat_call_p, new_params,\nsource_info_util.current())\n- for t in unknown_out_tracers: t.recipe = eqn\n- return out_tracers\n-call_partial_eval_rules[remat_call_p] = partial(\n- _remat_partial_eval, _remat_make_output_tracers)\n+ for t in unknown_output_tracers: t.recipe = eqn\n+ return _zip_knowns(known_output_tracers, unknown_output_tracers, out_unknowns)\n+call_partial_eval_rules[remat_call_p] = _remat_partial_eval\ndef _partition_knowns(pvals, unknowns: Sequence[bool]):\nreturn ([e for e, unknown in zip(pvals, unknowns) if not unknown],\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2982,13 +2982,7 @@ class InvertibleADTest(jtu.JaxTestCase):\nfinv = jax.invertible(f)\n- x = jnp.ones((1,))\n-\n- def primal_vjp_trace(fun, primals, cotangents):\n- def run(primals, cotangents):\n- out, fun_vjp = jax.vjp(fun, *primals)\n- return fun_vjp(cotangents)\n- return jax.make_jaxpr(run)(primals, cotangents)\n+ x = jnp.ones((5,))\nif config.omnistaging_enabled:\nexpected = \"\"\"\n@@ -3077,6 +3071,19 @@ class InvertibleADTest(jtu.JaxTestCase):\njax.value_and_grad(partial(reduce, g), argnums=(0, 1))(x, x + 2),\ncheck_dtypes=True)\n+ def test_invertible_partial_diff(self):\n+ # Check that we don't have to differentiate with respect to inputs\n+ # of the invertible function.\n+ def f(x, y):\n+ return (jnp.exp(x) * 4) * x, y + 4\n+\n+ finv = jax.invertible(f)\n+ o = np.ones((5,))\n+ self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x, o)[0]))(o),\n+ jax.value_and_grad(lambda x: np.sum(finv(x, o)[0]))(o),\n+ check_dtypes=True)\n+\n+\nclass DeprecatedCustomTransformsTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Implement the invertible decorator in terms of custom_vjp (#3957)
This simplifies the implementation significantly, as we can piggyback
off of all the logic for custom derivatives. For example, the previous
implementation didn't support differentiating with respect to a subset
of function parameters, but the new one does. |
260,299 | 11.08.2020 16:09:36 | -7,200 | 1e07712955939d6f8f461fc259b12a20808782b3 | Fix typos in api.py docstrings | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -118,7 +118,7 @@ def jit(fun: Callable[..., T],\nstatic_argnums: An int or collection of ints specifying which positional\narguments to treat as static (compile-time constant). Operations that only\ndepend on static arguments will be constant-folded in Python (during\n- tracing), and so the corrersponding argument values can be any Python\n+ tracing), and so the corresponding argument values can be any Python\nobject. Calling the jitted function with different values for these\nconstants will trigger recompilation. If the jitted function is called\nwith fewer positional arguments than indicated by ``static_argnums`` then\n@@ -134,10 +134,10 @@ def jit(fun: Callable[..., T],\ndonate_argnums: Specify which arguments are \"donated\" to the computation.\nIt is safe to donate arguments if you no longer need them once the\ncomputation has finished. In some cases XLA can make use of donated\n- buffers to reduce the amount of memory needed to perfom a computation, for\n- example recycling one of your input buffers to store a result. You should\n- not re-use buffers that you donate to a computation, JAX will raise an\n- error if you try to.\n+ buffers to reduce the amount of memory needed to perform a computation,\n+ for example recycling one of your input buffers to store a result. You\n+ should not re-use buffers that you donate to a computation, JAX will raise\n+ an error if you try to.\nReturns:\nA wrapped version of ``fun``, set up for just-in-time compilation.\n@@ -278,7 +278,7 @@ def xla_computation(fun: Callable,\nthe unoptimized XLA HLO computation can be extracted using methods like\n``as_hlo_text``, ``as_serialized_hlo_module_proto``, and\n``as_hlo_dot_graph``. If the argument ``return_shape`` is ``True``, then the\n- wrapped function eturns a pair where the first element is the XLA\n+ wrapped function returns a pair where the first element is the XLA\nComputation and the second element is a pytree representing the structure,\nshapes, and dtypes of the output of ``fun``.\n@@ -774,10 +774,10 @@ def vmap(fun: Callable[..., T], in_axes=0, out_axes=0) -> Callable[..., T]:\nArgs:\nfun: Function to be mapped over additional axes.\n- in_axes: A nonnegative integer, None, or (nested) standard Python container\n+ in_axes: A non-negative integer, None, or (nested) standard Python container\n(tuple/list/dict) thereof specifying which input array axes to map over.\nIf each positional argument to ``fun`` is an array, then ``in_axes`` can\n- be a nonnegative integer, a None, or a tuple of integers and Nones with\n+ be a non-negative integer, a None, or a tuple of integers and Nones with\nlength equal to the number of positional arguments to ``fun``. An integer\nor None indicates which array axis to map over for all arguments (with\nNone indicating not to map any axis), and a tuple indicates which axis to\n@@ -791,7 +791,7 @@ def vmap(fun: Callable[..., T], in_axes=0, out_axes=0) -> Callable[..., T]:\nof the mapped input axes for all mapped positional arguments must all\nbe equal.\n- out_axes: A nonnegative integer, None, or (nested) standard Python container\n+ out_axes: A non-negative integer, None, or (nested) standard Python container\n(tuple/list/dict) thereof indicating where the mapped axis should appear\nin the output. All outputs with a mapped axis must have a non-None\n``out_axes`` specification.\n@@ -1012,14 +1012,14 @@ def pmap(fun: Callable[..., T],\nhashable and have an equality operation defined.\naxis_name: Optional, a hashable Python object used to identify the mapped\naxis so that parallel collectives can be applied.\n- in_axes: A nonnegative integer, None, or nested Python container thereof\n+ in_axes: A non-negative integer, None, or nested Python container thereof\nthat specifies which axes in the input to map over (see :py:func:`vmap`).\nCurrently, only 0 and None are supported axes for pmap.\nstatic_broadcasted_argnums: An int or collection of ints specifying which\npositional arguments to treat as static (compile-time constant).\nOperations that only depend on static arguments will be constant-folded.\n- Calling the pmaped function with different values for these constants will\n- trigger recompilation. If the pmaped function is called with fewer\n+ Calling the pmapped function with different values for these constants will\n+ trigger recompilation. If the pmapped function is called with fewer\npositional arguments than indicated by ``static_argnums`` then an error is\nraised. Each of the static arguments will be broadcasted to all devices.\nArguments that are not arrays or containers thereof must be marked as\n@@ -1036,10 +1036,10 @@ def pmap(fun: Callable[..., T],\ndonate_argnums: Specify which arguments are \"donated\" to the computation.\nIt is safe to donate arguments if you no longer need them once the\ncomputation has finished. In some cases XLA can make use of donated\n- buffers to reduce the amount of memory needed to perfom a computation, for\n- example recycling one of your input buffers to store a result. You should\n- not re-use buffers that you donate to a computation, JAX will raise an\n- error if you try to.\n+ buffers to reduce the amount of memory needed to perform a computation,\n+ for example recycling one of your input buffers to store a result. You\n+ should not re-use buffers that you donate to a computation, JAX will raise\n+ an error if you try to.\nReturns:\nA parallelized version of ``fun`` with arguments that correspond to those of\n@@ -1128,8 +1128,8 @@ def pmap(fun: Callable[..., T],\n1.0\nOn multi-host platforms, collective operations operate over all devices,\n- including those those on other hosts. For example, assuming the following code\n- runs on two hosts with 4 XLA devices each:\n+ including those on other hosts. For example, assuming the following code runs\n+ on two hosts with 4 XLA devices each:\n>>> f = lambda x: x + jax.lax.psum(x, axis_name='i')\n>>> data = jnp.arange(4) if jax.host_id() == 0 else jnp.arange(4,8)\n@@ -1140,7 +1140,7 @@ def pmap(fun: Callable[..., T],\nEach host passes in a different length-4 array, corresponding to its 4 local\ndevices, and the psum operates over all 8 values. Conceptually, the two\n- length-4 arrays can be thought of as sharded length-8 array (in this example\n+ length-4 arrays can be thought of as a sharded length-8 array (in this example\nequivalent to jnp.arange(8)) that is mapped over, with the length-8 mapped axis\ngiven name 'i'. The pmap call on each host then returns the corresponding\nlength-4 output shard.\n@@ -1803,7 +1803,7 @@ def checkpoint(fun: Callable, concrete: bool = False) -> Callable:\nlinearization points (e.g. inputs to elementwise nonlinear primitive\noperations) are stored when evaluating the forward pass so that they can be\nreused on the backward pass. This evaluation strategy can lead to a high\n- memory cost, or even to poor performance on hardware acceleartors where memory\n+ memory cost, or even to poor performance on hardware accelerators where memory\naccess is much more expensive than FLOPs.\nAn alternative evaluation strategy is for some of the linearization points to\n"
}
] | Python | Apache License 2.0 | google/jax | Fix typos in api.py docstrings (#4021) |
260,335 | 11.08.2020 20:36:51 | 25,200 | c564aca77710df0599715d4231b7d5b7dd46984a | skip more ode tests on gpu, b/c slow to compile | [
{
"change_type": "MODIFY",
"old_path": "tests/ode_test.py",
"new_path": "tests/ode_test.py",
"diff": "@@ -59,7 +59,7 @@ class ODETest(jtu.JaxTestCase):\njtu.check_grads(integrate, (y0, ts, *args), modes=[\"rev\"], order=2,\natol=tol, rtol=tol)\n- @jtu.skip_on_devices(\"tpu\")\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_pytree_state(self):\n\"\"\"Test calling odeint with y(t) values that are pytrees.\"\"\"\ndef dynamics(y, _t):\n@@ -89,7 +89,7 @@ class ODETest(jtu.JaxTestCase):\njtu.check_grads(integrate, (y0, ts), modes=[\"rev\"], order=2,\nrtol=tol, atol=tol)\n- @jtu.skip_on_devices(\"tpu\")\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_decay(self):\ndef decay(_np, y, t, arg1, arg2):\nreturn -_np.sqrt(t) - y + arg1 - _np.mean((y + arg2)**2)\n@@ -107,7 +107,7 @@ class ODETest(jtu.JaxTestCase):\njtu.check_grads(integrate, (y0, ts, *args), modes=[\"rev\"], order=2,\nrtol=tol, atol=tol)\n- @jtu.skip_on_devices(\"tpu\")\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_swoop(self):\ndef swoop(_np, y, t, arg1, arg2):\nreturn _np.array(y - _np.sin(t) - _np.cos(t) * arg1 + arg2)\n"
}
] | Python | Apache License 2.0 | google/jax | skip more ode tests on gpu, b/c slow to compile (#4028) |
260,411 | 12.08.2020 09:20:26 | -10,800 | ece05d2813942594cc904c306ac485b4846882bd | [host_callback] Add support for custom gradients inside control-flow
* [host_callback] Add support for custom gradients inside control-flow
Specifically, add support for rewriting JAXPR that contains
custom_vjp_call_jaxpr_p and custom_jvp_call_jaxpr_p.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -136,6 +136,7 @@ import itertools\nfrom jax import api\nfrom jax import core\n+from jax import custom_derivatives\nfrom jax import lax\nfrom jax.lib import pytree\nfrom jax.interpreters import ad, xla, batching, masking\n@@ -654,6 +655,39 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\neqn.params,\ncall_jaxpr=_rewrite_jaxpr(call_jaxpr, True,\nTrue)), eqn.source_info))\n+ elif eqn.primitive is custom_derivatives.custom_jvp_call_jaxpr_p:\n+ fun_jaxpr = eqn.params[\"fun_jaxpr\"]\n+ new_invars = [*eqn.invars, input_token_var]\n+ def unreachable_thunk():\n+ assert False, \"Should not be reached\"\n+ eqns.append(\n+ core.new_jaxpr_eqn(\n+ new_invars, eqn.outvars + [output_token_var], eqn.primitive,\n+ dict(\n+ eqn.params,\n+ fun_jaxpr=_rewrite_typed_jaxpr(fun_jaxpr, True, True),\n+ jvp_jaxpr_thunk=unreachable_thunk\n+ ),\n+ eqn.source_info))\n+ elif eqn.primitive is custom_derivatives.custom_vjp_call_jaxpr_p:\n+ fun_jaxpr = eqn.params[\"fun_jaxpr\"]\n+ new_invars = [*eqn.invars, input_token_var]\n+ def unreachable_thunk():\n+ assert False, \"Should not be reached\"\n+ eqns.append(\n+ core.new_jaxpr_eqn(\n+ new_invars, eqn.outvars + [output_token_var], eqn.primitive,\n+ dict(\n+ eqn.params,\n+ fun_jaxpr=_rewrite_typed_jaxpr(fun_jaxpr, True, True),\n+ fwd_jaxpr_thunk=unreachable_thunk,\n+ # The following are illegal values for the parameters, they\n+ # should not be needed because this rewrite is just before\n+ # compilation to XLA, which does not use those parameters.\n+ bwd=\"illegal param\",\n+ out_trees=\"illegal param\"\n+ ),\n+ eqn.source_info))\nelse:\nraise NotImplementedError(f\"outfeed rewrite {eqn.primitive}\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -90,6 +90,10 @@ def assertMultiLineStrippedEqual(tst: jtu.JaxTestCase,\nwhat = re.sub(r\"\\-?\\d*\\.[\\-\\def]*\", repl_floats, what)\nwhat = re.sub(r\"output_stream=[^\\]\\n]*\", \"\", what)\nwhat = re.sub(r\"threshold=[^\\]\\n]*\", \"\", what)\n+ what = re.sub(r\"bwd=[^\\]\\n]*\", \"\", what)\n+ what = re.sub(r\"out_trees=[^\\]\\n]*\", \"\", what)\n+ what = re.sub(r\"fwd_jaxpr_thunk=[^\\]\\n]*\", \"\", what)\n+ what = re.sub(r\"jvp_jaxpr_thunk=[^\\]\\n]*\", \"\", what)\n# Empty lines\nwhat = re.sub(r\"^\\s*\\n\", \"\", what, flags=re.MULTILINE)\ndef repl_func(match_group):\n@@ -916,6 +920,94 @@ transforms: ({'name': 'batch', 'batch_dims': (0,)},) where: 3\nexpected_res = jnp.stack([fun1_equiv(2. + a) for a in range(api.local_device_count())])\nself.assertAllClose(expected_res, res, check_dtypes=False)\n+ def test_scan_custom_jvp(self):\n+ \"\"\"custom JVP, inside scan.\n+ This exercises the custom_jvp_call_jaxpr primitives.\"\"\"\n+ @api.custom_jvp\n+ def f(x):\n+ return x * hcb.id_print(x, output_stream=testing_stream, what=\"x\")\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ x_dot, = tangents\n+ primal_out = f(x)\n+ tangent_out = 3. * x * hcb.id_print(x_dot, output_stream=testing_stream, what=\"x_dot\")\n+ return primal_out, tangent_out\n+\n+ def g(x):\n+ # Sum f(x_i)\n+ return lax.scan(lambda carry, inp: (carry + f(inp), 0.),\n+ np.full(x.shape[1:], 0.), # Like x w/o leading dim\n+ x)[0]\n+\n+ arg = np.full((2,), 0.7)\n+ self.assertAllClose(0.7 * 0.7 * 2, g(arg))\n+ hcb.barrier_wait()\n+ self.assertMultiLineStrippedEqual(\"\"\"\n+ what: x\n+ 0.7\n+ what: x\n+ 0.7\"\"\", testing_stream.output)\n+ testing_stream.reset()\n+\n+ self.assertAllClose(np.array([2.1, 2.1]), api.grad(g)(arg), check_dtypes=False)\n+ hcb.barrier_wait()\n+ self.assertMultiLineStrippedEqual(\"\"\"\n+ what: x\n+ 0.7\n+ what: x\n+ 0.7\n+ transforms: ({'name': 'transpose'},) what: x_dot\n+ 2.1\n+ transforms: ({'name': 'transpose'},) what: x_dot\n+ 2.1\"\"\", testing_stream.output)\n+\n+ def test_scan_custom_vjp(self):\n+ \"\"\"custom VJP, inside scan.\n+ This exercises the custom_vjp_call_jaxpr primitives.\"\"\"\n+ @api.custom_vjp\n+ def f(x):\n+ return x * hcb.id_print(x, output_stream=testing_stream, what=\"x\")\n+\n+ # f_fwd: a -> (b, residual)\n+ def f_fwd(x):\n+ return f(x), 3. * x\n+ # f_bwd: (residual, CT b) -> [CT a]\n+ def f_bwd(residual, ct_b):\n+ return residual * hcb.id_print(ct_b, output_stream=testing_stream, what=\"ct_b\"),\n+\n+ f.defvjp(f_fwd, f_bwd)\n+\n+ def g(x):\n+ # Sum f(x_i)\n+ return lax.scan(lambda carry, inp: (carry + f(inp), 0.),\n+ np.full(x.shape[1:], 0.), # Like x w/o leading dim\n+ x)[0]\n+\n+ arg = np.full((2,), 0.7)\n+\n+ self.assertAllClose(0.7 * 0.7 * 2, g(arg))\n+ hcb.barrier_wait()\n+ self.assertMultiLineStrippedEqual(\"\"\"\n+ what: x\n+ 0.7\n+ what: x\n+ 0.7\"\"\", testing_stream.output)\n+ testing_stream.reset()\n+\n+ self.assertAllClose(np.array([2.1, 2.1]), api.grad(g)(arg), check_dtypes=False)\n+ hcb.barrier_wait()\n+ self.assertMultiLineStrippedEqual(\"\"\"\n+ what: x\n+ 0.7\n+ what: x\n+ 0.7\n+ what: ct_b\n+ 1.\n+ what: ct_b\n+ 1.\"\"\", testing_stream.output)\n+\ndef test_mask(self):\n# TODO(necula)\nraise SkipTest(\"masking has regressed\")\n@@ -1186,9 +1278,176 @@ class OutfeedRewriterTest(jtu.JaxTestCase):\nlinear=(False, False, False, False, False)\nnum_carry=3\nnum_consts=1\n- reverse=False ] b 1 2 f a\n+ reverse=False\n+ unroll=1 ] b 1 2 f a\nin (c, d, e, g) }\"\"\", func, [y])\n+ def test_scan_custom_jvp(self):\n+ \"\"\"custom JVP, inside scan.\n+ This exercises the custom_jvp_call_jaxpr primitives.\"\"\"\n+ @api.custom_jvp\n+ def f(x):\n+ return x * hcb.id_print(x)\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ x_dot, = tangents\n+ primal_out = f(x)\n+ tangent_out = 3. * x * hcb.id_print(x_dot)\n+ return primal_out, tangent_out\n+\n+ def g(x):\n+ # Sum f(x_i)\n+ return lax.scan(lambda carry, inp: (carry + f(inp), 0.),\n+ np.full(x.shape[1:], 0.), # Like x w/o leading dim\n+ x)[0]\n+\n+ arg = np.full((5,), 0.7)\n+ self.assertRewrite(\"\"\"\n+ { lambda ; a c.\n+ let b d _ = scan[ jaxpr={ lambda ; a e b.\n+ let c f = custom_jvp_call_jaxpr[ fun_jaxpr={ lambda ; a d.\n+ let b e = id_tap[ arg_treedef_=*\n+ has_token_=True\n+ nr_tapped_args_=1\n+ tap_func_=_print\n+ ] a d\n+ c = mul a b\n+ in (c, e) }\n+ ] b e\n+ d = add a c\n+ in (d, f, 0.00) }\n+ length=5\n+ linear=(False, False, False)\n+ num_carry=2\n+ num_consts=0\n+ reverse=False\n+ unroll=1 ] 0.00 c a\n+ in (b, d) }\"\"\", g, [arg])\n+ self.assertRewrite(\"\"\"\n+ { lambda ; a d.\n+ let _ _ e _ b =\n+ scan[ jaxpr={ lambda ; a b h c d.\n+ let e i = custom_jvp_call_jaxpr[ fun_jaxpr={ lambda ; a d.\n+ let b e = id_tap[ arg_treedef_=*\n+ has_token_=True\n+ nr_tapped_args_=1\n+ tap_func_=_print\n+ ] a d\n+ c = mul a b\n+ in (c, e) }\n+ ] c h\n+ f = add a e\n+ g = mul c 3.00\n+ in (f, *, i, 0.00, g) }\n+ length=5\n+ linear=(False, True, False, True, False)\n+ num_carry=3\n+ num_consts=0\n+ reverse=False\n+ unroll=1 ] 0.00 * d a *\n+ _ _ f _ c =\n+ scan[ jaxpr={ lambda ; a b g c d.\n+ let e = mul b d\n+ f h = id_tap[ arg_treedef_=*\n+ has_token_=True\n+ nr_tapped_args_=1\n+ tap_func_=_print\n+ transforms=(('transpose',),) ] e g\n+ in (*, b, h, *, f) }\n+ length=5\n+ linear=(True, True, True, False, False)\n+ num_carry=3\n+ num_consts=0\n+ reverse=True\n+ unroll=1 ] * 1.00 e * b\n+ in (c, f) }\"\"\", api.grad(g), [arg])\n+\n+ def test_scan_custom_vjp(self):\n+ \"\"\"custom VJP, inside scan.\n+ This exercises the custom_vjp_call_jaxpr primitives.\"\"\"\n+ @api.custom_vjp\n+ def f(x):\n+ return x * hcb.id_print(x)\n+\n+ # f_fwd: a -> (b, residual)\n+ def f_fwd(x):\n+ return f(x), 3. * x\n+ # f_bwd: (residual, CT b) -> [CT a]\n+ def f_bwd(residual, ct_b):\n+ return residual * hcb.id_print(ct_b),\n+\n+ f.defvjp(f_fwd, f_bwd)\n+\n+ def g(x):\n+ # Sum f(x_i)\n+ return lax.scan(lambda carry, inp: (carry + f(inp), 0.),\n+ np.full(x.shape[1:], 0.), # Like x w/o leading dim\n+ x)[0]\n+\n+ arg = np.full((2,), 0.7)\n+ self.assertRewrite(\"\"\"\n+ { lambda ; a c.\n+ let b d _ = scan[ jaxpr={ lambda ; a e b.\n+ let c f = custom_vjp_call_jaxpr[\n+ fun_jaxpr={ lambda ; a d.\n+ let b e = id_tap[ arg_treedef_=*\n+ has_token_=True\n+ nr_tapped_args_=1\n+ tap_func_=_print\n+ ] a d\n+ c = mul a b\n+ in (c, e) }\n+ ] b e\n+ d = add a c\n+ in (d, f, 0.00) }\n+ length=2\n+ linear=(False, False, False)\n+ num_carry=2\n+ num_consts=0\n+ reverse=False\n+ unroll=1 ] 0.00 c a\n+ in (b, d) }\"\"\", g, [arg])\n+ self.assertRewrite(\"\"\"\n+ { lambda ; a d.\n+ let _ _ e _ b =\n+ scan[ jaxpr={ lambda ; a b h c d.\n+ let e i = custom_vjp_call_jaxpr[\n+ fun_jaxpr={ lambda ; a d.\n+ let b e = id_tap[ arg_treedef_=*\n+ has_token_=True\n+ nr_tapped_args_=1\n+ tap_func_=_print\n+ ] a d\n+ c = mul a b\n+ in (c, e) }\n+ ] c h\n+ f = add a e\n+ g = mul c 3.00\n+ in (f, *, i, 0.00, g) }\n+ length=2\n+ linear=(False, True, False, True, False)\n+ num_carry=3\n+ num_consts=0\n+ reverse=False\n+ unroll=1 ] 0.00 * d a *\n+ _ _ f _ c =\n+ scan[ jaxpr={ lambda ; a b g c d.\n+ let e h = id_tap[ arg_treedef_=*\n+ has_token_=True\n+ nr_tapped_args_=1\n+ tap_func_=_print\n+ ] b g\n+ f = mul d e\n+ in (*, b, h, *, f) }\n+ length=2\n+ linear=(True, True, True, False, False)\n+ num_carry=3\n+ num_consts=0\n+ reverse=True\n+ unroll=1 ] * 1.00 e * b\n+ in (c, f) }\"\"\", api.grad(g), [arg])\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [host_callback] Add support for custom gradients inside control-flow (#4029)
* [host_callback] Add support for custom gradients inside control-flow
Specifically, add support for rewriting JAXPR that contains
custom_vjp_call_jaxpr_p and custom_jvp_call_jaxpr_p.
Fixes #4015. |
260,701 | 12.08.2020 19:52:42 | -3,600 | 6e4ec7cb81be0dc06dd0bf0ffe789abb8a2ae87a | Fix broadcasting in random.uniform and randint. | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -353,8 +353,8 @@ def uniform(key: jnp.ndarray,\nshape. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n- minval: optional, a minimum (inclusive) value for the range (default 0).\n- maxval: optional, a maximum (exclusive) value for the range (default 1).\n+ minval: optional, a minimum (inclusive) value broadcast-compatible with shape for the range (default 0).\n+ maxval: optional, a maximum (exclusive) value broadcast-compatible with shape for the range (default 1).\nReturns:\nA random array with the specified shape and dtype.\n@@ -374,6 +374,9 @@ def _uniform(key, shape, dtype, minval, maxval) -> jnp.ndarray:\nminval = lax.convert_element_type(minval, dtype)\nmaxval = lax.convert_element_type(maxval, dtype)\n+ minval = lax.broadcast_to_rank(minval, len(shape))\n+ maxval = lax.broadcast_to_rank(maxval, len(shape))\n+\nfinfo = jnp.finfo(dtype)\nnbits, nmant = finfo.bits, finfo.nmant\n@@ -427,6 +430,8 @@ def _randint(key, shape, minval, maxval, dtype):\nminval = lax.convert_element_type(minval, dtype)\nmaxval = lax.convert_element_type(maxval, dtype)\n+ minval = lax.broadcast_to_rank(minval, len(shape))\n+ maxval = lax.broadcast_to_rank(maxval, len(shape))\nnbits = jnp.iinfo(dtype).bits\nif nbits not in (8, 16, 32, 64):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -733,6 +733,16 @@ class LaxRandomTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, r\"dtype argument to.*\"):\nrandom.normal(random.PRNGKey(0), (), dtype=jnp.int32)\n+ def testRandomBroadcast(self):\n+ \"\"\"Issue 4033\"\"\"\n+ # test for broadcast issue in https://github.com/google/jax/issues/4033\n+ key = random.PRNGKey(0)\n+ shape = (10, 2)\n+ x = random.uniform(key, shape, minval=jnp.zeros(2), maxval=jnp.ones(2))\n+ assert x.shape == shape\n+ x = random.randint(key, shape, jnp.array([0, 1]), jnp.array([1, 2]))\n+ assert x.shape == shape\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Fix broadcasting in random.uniform and randint. (#4035) |
260,411 | 13.08.2020 13:02:22 | -10,800 | 206d2f9890dac4da6855933ae486f8a270d477dd | [host_callback] Fix handling of params[donated_invars]
There was some confusion when rewriting xla_call primitives and
the donated_invars was not set to be equal to the length of the
invars.
Fixes:
Fixes: | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -654,7 +654,10 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\ndict(\neqn.params,\ncall_jaxpr=_rewrite_jaxpr(call_jaxpr, True,\n- True)), eqn.source_info))\n+ True),\n+ donated_invars=eqn.params[\"donated_invars\"] + (False,)\n+ ),\n+ eqn.source_info))\nelif eqn.primitive is custom_derivatives.custom_jvp_call_jaxpr_p:\nfun_jaxpr = eqn.params[\"fun_jaxpr\"]\nnew_invars = [*eqn.invars, input_token_var]\n@@ -712,7 +715,7 @@ def _rewrite_while_outfeed_cond(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\ndict(\ncall_jaxpr=transformed_cond_jaxpr.jaxpr,\nname=\"cond_before\",\n- donated_invars=(False,) * (cond_nconsts + len(carry_invars) + 1)),\n+ donated_invars=(False,) * len(transformed_cond_jaxpr.in_avals)),\neqn.source_info))\n# Make a new cond \"lambda pred, carry, token: pred\"\nnew_cond_pred_invar = mk_new_var(cond_jaxpr.out_avals[0])\n@@ -751,9 +754,7 @@ def _rewrite_while_outfeed_cond(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\ndict(\ncall_jaxpr=transformed_body_jaxpr.jaxpr,\nname=\"body\",\n- donated_invars=(False,) *\n- (len(new_body_invars_body_constvars) +\n- len(new_body_invars_carry) + 1 + len(new_body_carry2) + 1)),\n+ donated_invars=(False,) * len(transformed_body_jaxpr.in_avals)),\neqn.source_info),\ncore.new_jaxpr_eqn(\nnew_body_invars_cond_constvars + new_body_carry2 + [new_body_token2],\n@@ -761,8 +762,7 @@ def _rewrite_while_outfeed_cond(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\ndict(\ncall_jaxpr=transformed_cond_jaxpr.jaxpr,\nname=\"cond_body\",\n- donated_invars=(False,) * (len(new_body_invars_cond_constvars) +\n- len(new_body_carry2) + 1 + 2)),\n+ donated_invars=(False,) * len(transformed_cond_jaxpr.in_avals)),\neqn.source_info)\n]\nnew_body_jaxpr = _mk_typed_jaxpr(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -1116,6 +1116,21 @@ what: x times i\ncomp, token, 123,\n[xla_bridge.constant(comp, np.zeros((2,), dtype=np.float32))])\n+ def test_odeint(self):\n+ # TODO: find a smaller repro for bug #4015\n+ # Seems to be xla_call(scan(xla_call)), all under grad.\n+ from jax.experimental.ode import odeint\n+\n+ def f(x, t, k):\n+ x = hcb.id_print(x)\n+ return -k * x\n+\n+ def loss(k=1.0):\n+ t = jnp.linspace(0, 0.001, num=2)\n+ xs = odeint(f, 1.0, t, k)\n+ return xs[-1]\n+\n+ api.grad(loss)(1.0) # should not fail\nclass OutfeedRewriterTest(jtu.JaxTestCase):\n@@ -1240,7 +1255,7 @@ class OutfeedRewriterTest(jtu.JaxTestCase):\n] b f\ne = add d 1\nin (c, e, g) }\n- donated_invars=(False, False, False, False, False, False, False)\n+ donated_invars=(False, False, False, False)\nname=body ] n p q r\nv w = xla_call[ call_jaxpr={ lambda ; c a b f.\nlet _ d g = id_tap[ arg_treedef_=*\n@@ -1250,7 +1265,7 @@ class OutfeedRewriterTest(jtu.JaxTestCase):\n] c b f\ne = lt d 5\nin (e, g) }\n- donated_invars=(False, False, False, False, False, False)\n+ donated_invars=(False, False, False, False)\nname=cond_body ] m s t u\nin (v, s, t, w) }\nbody_nconsts=2\n"
}
] | Python | Apache License 2.0 | google/jax | [host_callback] Fix handling of params[donated_invars] (#4040)
There was some confusion when rewriting xla_call primitives and
the donated_invars was not set to be equal to the length of the
invars.
Fixes: #4015
Fixes: #3863 |
260,298 | 13.08.2020 12:27:16 | -7,200 | 3458f1fc1643eb5b1f71c598a16baf7e6d739307 | [jax2tf] Change np.array dtype to jnp.float32 when target dtype is bfloat16.
* Change np.array dtype to jnp.float32 when target dtype is bfloat16.
This ensures that the conversion for tf.convert_to_tensor is well
defined without losing precision.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -57,11 +57,39 @@ def _is_tfval(v: TfVal) -> bool:\nif isinstance(v, (tf.Tensor, tf.Variable)):\nreturn True\ntry:\n- tf.convert_to_tensor(v)\n+ # Note: this conversion is overkill and just intended as a type check; this code\n+ # is in principle only run if core.skip_checks is False.\n+ _safe_convert_to_tensor(v)\nreturn True\nexcept ValueError:\nreturn False\n+def _safe_convert_to_tensor(val, dtype=None):\n+ \"\"\"Converts val to a Tensor.\n+\n+ This method wraps TensorFlow's `convert_to_tensor\n+ <https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor>`_ operator with\n+ special case handling for when `val` is an instance of `jnp.bfloat16` or has a\n+ `jnp.bfloat16` dtype. Because this type is not supported in numpy and different\n+ from `tf.bfloat16.as_numpy_dtype`, `tf.convert_to_tensor` runs into trouble when\n+ trying to convert it. In such a case, we solve the problem by viewing val as a\n+ `ndarray` with a `uint16` dtype, for which conversion is properly defined. Then, we\n+ simply bitcast it back to `bfloat16`.\n+ \"\"\"\n+ dtype = dtype if dtype else (val.dtype if hasattr(val, \"dtype\") else None)\n+ if (dtype == jnp.bfloat16 or isinstance(val, jnp.bfloat16)):\n+ if not isinstance(val, jnp.ndarray):\n+ val = np.array(val, jnp.bfloat16)\n+\n+ val = tf.bitcast(tf.convert_to_tensor(val.view(jnp.uint16),\n+ dtype=to_tf_dtype(jnp.uint16)),\n+ type=to_tf_dtype(jnp.bfloat16))\n+ else:\n+ conversion_type = to_tf_dtype(dtype) if dtype else None\n+ val = tf.convert_to_tensor(val, dtype=conversion_type)\n+\n+ return val\n+\n# During JAX transformations we sometimes produce a Jaxpr that has arguments\n# of abstract value core.abstract_unit and results equal to core.unit.\n# These are arguments and results that are not used in the computation.\n@@ -244,7 +272,9 @@ class TensorFlowTracer(core.Tracer):\nelse: # Must be a numeric value\nassert core.skip_checks or _is_tfval(val), f\"Non TfVal: {val}\"\naval = xla.abstractify(val) # type: ignore\n- self.val = tf.convert_to_tensor(np.array(val, aval.dtype), dtype=aval.dtype) # type: ignore\n+\n+ self.val = _safe_convert_to_tensor(val, dtype=aval.dtype)\n+\nassert core.skip_checks or aval.strip_weak_type() == self.aval.strip_weak_type(), (\nf\"Expected {aval}, got {self.aval}\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -88,7 +88,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ndef test_type_promotion(self, f_jax=jnp.add):\n# We only test a few types here, as tensorflow does not support many\n# types like uint* or bool in binary ops.\n- types = [np.int32, np.int64, np.float32]\n+ types = [dtypes.bfloat16, np.int32, np.int64, np.float32]\nfor x_dtype in types:\nfor y_dtype in types:\nx = np.array([1, 2], dtype=x_dtype)\n@@ -104,9 +104,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_pad)\ndef test_pad(self, harness: primitive_harness.Harness):\n- # TODO: figure out the bfloat16 story\n- if harness.params[\"dtype\"] is dtypes.bfloat16:\n- raise unittest.SkipTest(\"bfloat16 not implemented\")\n# TODO: fix pad with negative padding in XLA (fixed on 06/16/2020)\nif any([lo < 0 or hi < 0 for lo, hi, mid in harness.params[\"pads\"]]):\nraise unittest.SkipTest(\"pad with negative pad not supported\")\n@@ -118,9 +115,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nharness.params[\"k\"] < 0):\nwith self.assertRaisesRegex(ValueError, \"k argument to top_k must be\"):\nharness.dyn_fun(*harness.dyn_args_maker(self.rng()))\n- # TODO: figure out what's up with bfloat16\n- elif harness.params[\"dtype\"] is dtypes.bfloat16:\n- raise unittest.SkipTest(\"bfloat16 support not implemented\")\nelif harness.params[\"dtype\"] in jtu.dtypes.complex:\n# TODO(necula): fix top_k complex bug on TPU\nif jtu.device_under_test() == \"tpu\":\n@@ -135,9 +129,9 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_sort)\ndef test_sort(self, harness: primitive_harness.Harness):\n- if harness.params[\"dtype\"] is dtypes.bfloat16 or harness.params[\"dtype\"] in jtu.dtypes.complex:\n- # TODO: implement bfloat16/complex support in XlaSort\n- raise unittest.SkipTest(\"bfloat16/complex support not implemented\")\n+ if harness.params[\"dtype\"] in jtu.dtypes.complex:\n+ # TODO: implement complex support in XlaSort\n+ raise unittest.SkipTest(\"complex support not implemented\")\nif harness.params[\"dtype\"] is dtypes.bool_ and len(harness.arg_descriptors) == 4:\n# TODO: _sort uses tfxla.key_value_sort to handle 2 operandes, but the operation is not compatible with boolean keys.\nraise unittest.SkipTest(\"boolean key key value sort not implemented\")\n@@ -549,6 +543,25 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nf = jax2tf.convert(lax.stop_gradient)\nself.assertEqual(f(tf.ones([])), 1.)\n+ # test_bfloat16_constant checks that https://github.com/google/jax/issues/3942 is\n+ # fixed\n+ def test_bfloat16_constant(self):\n+ def jax_fn_scalar(x):\n+ x = x.astype(jnp.bfloat16)\n+ x *= 2.\n+ return x\n+\n+ def jax_fn_array(x):\n+ x = x.astype(jnp.bfloat16)\n+ x *= np.array([1.5, 2.5, 3.5], jnp.bfloat16)\n+ return x\n+\n+ tf_fn_scalar = jax2tf.convert(jax_fn_scalar)\n+ self.assertAllClose(tf_fn_scalar(1.375).numpy(), jnp.bfloat16(2.750))\n+\n+ tf_fn_array = jax2tf.convert(jax_fn_array)\n+ self.assertAllClose(tf_fn_array(np.array([3, 4, 5])),\n+ np.array([4.5, 10, 17.5], jnp.bfloat16))\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"new_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"diff": "@@ -91,14 +91,23 @@ class JaxToTfTestCase(jtu.JaxTestCase):\n# Run TF in all execution modes\nfunc_tf = jax2tf.convert(func_jax)\n+ def convert_if_bfloat16(v):\n+ if hasattr(v, \"dtype\"):\n+ return tf.convert_to_tensor(np.array(v, jnp.float32) if\n+ v.dtype == jnp.bfloat16 else v,\n+ jax2tf.jax2tf.to_tf_dtype(v.dtype))\n+ return v\n+\n+ tf_args = tuple(map(convert_if_bfloat16, args))\n+\ndef run_tf(mode):\nif mode == \"eager\":\n- return func_tf(*args)\n+ return func_tf(*tf_args)\nelif mode == \"graph\":\n- return tf.function(func_tf, autograph=False)(*args)\n+ return tf.function(func_tf, autograph=False)(*tf_args)\nelif mode == \"compiled\":\nreturn tf.function(func_tf, autograph=False,\n- experimental_compile=True)(*args)\n+ experimental_compile=True)(*tf_args)\nelse:\nassert False\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Change np.array dtype to jnp.float32 when target dtype is bfloat16. (#3959)
* Change np.array dtype to jnp.float32 when target dtype is bfloat16.
This ensures that the conversion for tf.convert_to_tensor is well
defined without losing precision.
Fixes #3942. |
260,411 | 13.08.2020 15:20:07 | -10,800 | 7cf236f83f0494f2ef0777f0ba450df20973dde2 | [jax2tf] Clean up test_qr and disable (temporarily) some tests for shirt_right
on TPU
This is a follow-up from that enabled some more integer types for TPU
for JAX.
There are still some silent errors to investigate for shift_right on TPU. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -413,7 +413,7 @@ lax_linalg_qr = tuple(\nshape=shape,\ndtype=dtype,\nfull_matrices=full_matrices)\n- for dtype in jtu.dtypes.all\n+ for dtype in jtu.dtypes.all_floating + jtu.dtypes.complex\nfor shape in [(1, 1), (3, 3), (3, 4), (2, 10, 5), (2, 200, 100)]\nfor full_matrices in [False, True]\n)\n@@ -576,14 +576,16 @@ lax_shift_left = tuple(\nlax_shift_right_logical = tuple(\nHarness(f\"_dtype={dtype.__name__}_shift_amount={shift_amount}\", # type: ignore\nlax.shift_right_logical,\n- [arg, StaticArg(np.array([shift_amount], dtype=dtype))])\n+ [arg, StaticArg(np.array([shift_amount], dtype=dtype))],\n+ dtype=dtype)\nfor arg, dtype, shift_amount in shift_inputs\n)\nlax_shift_right_arithmetic = tuple(\nHarness(f\"_dtype={dtype.__name__}_shift_amount={shift_amount}\", # type: ignore\nlax.shift_right_arithmetic,\n- [arg, StaticArg(np.array([shift_amount], dtype=dtype))])\n+ [arg, StaticArg(np.array([shift_amount], dtype=dtype))],\n+ dtype=dtype)\nfor arg, dtype, shift_amount in shift_inputs\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -175,41 +175,40 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_linalg_qr)\ndef test_qr(self, harness: primitive_harness.Harness):\n# See jax.lib.lapack.geqrf for the list of compatible types\n- if (harness.params[\"dtype\"] in [jnp.float32, jnp.float64] or\n- harness.params[\"dtype\"] == jnp.float16 and jtu.device_under_test() == \"tpu\"):\n- self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n- atol=1e-5, rtol=1e-5)\n- elif harness.params[\"dtype\"] in [jnp.complex64, jnp.complex128]:\n- if (jtu.device_under_test() == \"tpu\" and\n- harness.params[\"dtype\"] in [jnp.complex64]):\n- raise unittest.SkipTest(\"QR for c64 not implemented on TPU\")\n+ dtype = harness.params[\"dtype\"]\n+ dut = jtu.device_under_test()\n+ # These cases are not implemented in JAX\n+ if dtype in (jtu.dtypes.all_integer + [jnp.bfloat16]):\n+ unimplemented_jax = True\n+ elif dtype is np.complex64 and dut == \"tpu\":\n+ unimplemented_jax = True\n+ elif dtype is np.float16 and dut in (\"cpu\", \"gpu\"):\n+ unimplemented_jax = True\n+ else:\n+ unimplemented_jax = False\n+\n+ if unimplemented_jax:\n+ raise unittest.SkipTest(f\"QR not implemented in JAX for {dtype} on {dut}\")\n+\n+ expect_tf_exceptions = False\n+ if dtype in (np.complex64, np.complex128):\n+ expect_tf_exceptions = True\n# TODO: see https://github.com/google/jax/pull/3775#issuecomment-659407824.\n- # - check_compiled=True breaks for complex types;\n+ # - experimental_compile=True breaks for complex types;\n# - for now, the performance of the HLO QR implementation called when\n# compiling with TF is expected to have worse performance than the\n# custom calls made in JAX.\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n- expect_tf_exceptions=True, atol=1e-5, rtol=1e-5)\n- else:\n- # TODO(necula): fix QR bug on TPU\n- if (jtu.device_under_test() == \"tpu\" and\n- harness.params[\"dtype\"] in (jnp.bfloat16, jnp.int32, jnp.uint32)):\n- raise unittest.SkipTest(\"QR bug on TPU for certain types: error not raised\")\n- if (jtu.device_under_test() == \"tpu\" and\n- harness.params[\"dtype\"] in (jnp.bool_,)):\n- raise unittest.SkipTest(\"QR bug on TPU for certain types: invalid cast\")\n-\n- expected_error = ValueError if jtu.device_under_test() == \"gpu\" else NotImplementedError\n- with self.assertRaisesRegex(expected_error, \"Unsupported dtype\"):\n- harness.dyn_fun(*harness.dyn_args_maker(self.rng()))\n+ expect_tf_exceptions=expect_tf_exceptions,\n+ atol=1e-5, rtol=1e-5)\n@primitive_harness.parameterized(primitive_harness.lax_linalg_svd)\ndef test_svd(self, harness: primitive_harness.Harness):\nif jtu.device_under_test() == \"tpu\":\nraise unittest.SkipTest(\"TODO: test crashes the XLA compiler for some TPU variants\")\nexpect_tf_exceptions = False\n- if harness.params[\"dtype\"] in [jnp.float16, dtypes.bfloat16]:\n+ if harness.params[\"dtype\"] in [np.float16, dtypes.bfloat16]:\nif jtu.device_under_test() == \"tpu\":\n# TODO: SVD on TPU for bfloat16 seems to work for JAX but fails for TF\nexpect_tf_exceptions = True\n@@ -219,7 +218,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nharness.dyn_fun(*harness.dyn_args_maker(self.rng()))\nreturn\n- if harness.params[\"dtype\"] in [jnp.complex64, jnp.complex128]:\n+ if harness.params[\"dtype\"] in [np.complex64, np.complex128]:\nif jtu.device_under_test() == \"tpu\":\n# TODO: on JAX on TPU there is no SVD implementation for complex\nwith self.assertRaisesRegex(RuntimeError,\n@@ -416,10 +415,14 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_shift_right_logical)\ndef test_shift_right_logical(self, harness):\n+ if jtu.device_under_test() == \"tpu\" and harness.params[\"dtype\"] in [np.int8, np.int16]:\n+ raise unittest.SkipTest(\"TODO: silent error for negative inputs\")\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@primitive_harness.parameterized(primitive_harness.lax_shift_right_arithmetic)\ndef test_shift_right_arithmetic(self, harness):\n+ if jtu.device_under_test() == \"tpu\" and harness.params[\"dtype\"] in [np.uint8, np.uint16]:\n+ raise unittest.SkipTest(\"TODO: silent error for negative inputs\")\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@primitive_harness.parameterized(primitive_harness.lax_slice)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Clean up test_qr and disable (temporarily) some tests for shirt_right (#4044)
on TPU
This is a follow-up from #4032 that enabled some more integer types for TPU
for JAX.
There are still some silent errors to investigate for shift_right on TPU. |
260,298 | 14.08.2020 09:58:41 | -7,200 | 41f1eb412c2522be34795cd47148f3e39405088c | [jax2tf] Added note about nextafter support in TensorFlow.
The TF implementation of nextafter only supports float32/64 params. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -361,9 +361,11 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nif dtype is np.float32 and jtu.device_under_test() == \"tpu\":\nraise unittest.SkipTest(\"TODO: fix bug: nan vs not-nan\")\n# TODO(necula): fix bug with nextafter/f16\n+ # See https://www.tensorflow.org/api_docs/python/tf/math/nextafter, params to\n+ # nextafter can only be float32/float64.\nif (lax_name == \"nextafter\" and\ndtype in [np.float16, dtypes.bfloat16]):\n- raise unittest.SkipTest(\"TODO: understand unimplemented case\")\n+ raise unittest.SkipTest(\"TODO: nextafter not supported for (b)float16 in TF\")\narg1, arg2 = harness.dyn_args_maker(self.rng())\ncustom_assert = None\nif lax_name == \"igamma\":\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Added note about nextafter support in TensorFlow. (#4056)
The TF implementation of nextafter only supports float32/64 params. |
260,298 | 14.08.2020 12:24:57 | -7,200 | bd14f2343aece428df85808d23cace1ede0b2821 | [jax2tf] Fix bfloat16 failures on CPU/GPU with latest tf-nightly. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -282,8 +282,13 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ndef test_unary_elementwise(self, harness: primitive_harness.Harness):\ndtype = harness.params[\"dtype\"]\nlax_name = harness.params[\"lax_name\"]\n+ if (lax_name in (\"acosh\", \"asinh\", \"atanh\", \"bessel_i0e\", \"bessel_i1e\", \"digamma\",\n+ \"erf\", \"erf_inv\", \"erfc\", \"lgamma\", \"round\", \"rsqrt\") and\n+ dtype is dtypes.bfloat16 and\n+ jtu.device_under_test() in [\"cpu\", \"gpu\"]):\n+ raise unittest.SkipTest(f\"bfloat16 support is missing from '{lax_name}' TF kernel on {jtu.device_under_test()} devices.\")\n# TODO(bchetioui): do they have bfloat16 support, though?\n- if lax_name in (\"sinh\", \"cosh\", \"atanh\", \"asinh\", \"acosh\") and dtype is np.float16:\n+ if lax_name in (\"sinh\", \"cosh\", \"atanh\", \"asinh\", \"acosh\", \"erf_inv\") and dtype is np.float16:\nraise unittest.SkipTest(\"b/158006398: float16 support is missing from '%s' TF kernel\" % lax_name)\narg, = harness.dyn_args_maker(self.rng())\ncustom_assert = None\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix bfloat16 failures on CPU/GPU with latest tf-nightly. (#4060) |
260,272 | 14.08.2020 21:05:46 | -7,200 | b44a1bacaf14833f44907dbd13399bf04d162fee | Note flush-denormal-to-zero behavior in nextafter.
Since imports of functions from lax.py in lax_numpy.py previously
didn't copy docstrings, add option to extract docstring from the
lax function. To avoid duplication of the short description,
discard first line of the lax function's docstring, and pass
the rest as lax_description to _wraps. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -113,7 +113,18 @@ def sign(x: Array) -> Array:\nreturn sign_p.bind(x)\ndef nextafter(x1: Array, x2: Array) -> Array:\n- r\"\"\"Returns the next representable value after `x1` in the direction of `x2`.\"\"\"\n+ r\"\"\"Returns the next representable value after `x1` in the direction of `x2`.\n+\n+ Note that in some environments flush-denormal-to-zero semantics is used.\n+ This means that, around zero, this function returns strictly non-zero\n+ values which appear as zero in any operations. Consider this example::\n+ >>> jnp.nextafter(0, 1) # denormal numbers are representable\n+ DeviceArray(1.e-45, dtype=float32)\n+ >>> jnp.nextafter(0, 1) * 1 # but are flushed to zero\n+ DeviceArray(0., dtype=float32)\n+\n+ For the smallest usable (i.e. normal) float, use ``tiny`` of ``jnp.finfo``.\n+ \"\"\"\nreturn nextafter_p.bind(_brcast(x1, x2), _brcast(x2, x1))\ndef floor(x: Array) -> Array:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -30,6 +30,7 @@ import operator\nimport os\nimport types\nfrom typing import Sequence, Set, Tuple, Union\n+from textwrap import dedent as _dedent\nimport warnings\nimport numpy as np\n@@ -341,27 +342,40 @@ iterable = np.iterable\ndef result_type(*args):\nreturn dtypes.result_type(*args)\n-def _one_to_one_unop(numpy_fn, lax_fn, promote_to_inexact=False):\n+def _one_to_one_unop(numpy_fn, lax_fn, promote_to_inexact=False, lax_doc=False):\nif promote_to_inexact:\ndef fn(x):\nx = lax.convert_element_type(x, _to_inexact_dtype(_dtype(x)))\nreturn lax_fn(x)\nelse:\nfn = lambda x: lax_fn(x)\n+ if lax_doc:\n+ doc = _dedent('\\n\\n'.join(lax_fn.__doc__.split('\\n\\n')[1:])).strip()\n+ return _wraps(numpy_fn, lax_description=doc)(fn)\n+ else:\nreturn _wraps(numpy_fn)(fn)\n-def _one_to_one_binop(numpy_fn, lax_fn, promote_to_inexact=False):\n+def _one_to_one_binop(numpy_fn, lax_fn, promote_to_inexact=False, lax_doc=False):\nif promote_to_inexact:\nfn = lambda x1, x2: lax_fn(*_promote_args_inexact(numpy_fn.__name__, x1, x2))\nelse:\nfn = lambda x1, x2: lax_fn(*_promote_args(numpy_fn.__name__, x1, x2))\n+ if lax_doc:\n+ doc = _dedent('\\n\\n'.join(lax_fn.__doc__.split('\\n\\n')[1:])).strip()\n+ return _wraps(numpy_fn, lax_description=doc)(fn)\n+ else:\nreturn _wraps(numpy_fn)(fn)\n-def _maybe_bool_binop(numpy_fn, lax_fn, bool_lax_fn):\n+def _maybe_bool_binop(numpy_fn, lax_fn, bool_lax_fn, lax_doc=False):\ndef fn(x1, x2):\nx1, x2 = _promote_args(numpy_fn.__name__, x1, x2)\nreturn lax_fn(x1, x2) if x1.dtype != bool_ else bool_lax_fn(x1, x2)\nreturn _wraps(numpy_fn)(fn)\n+ if lax_doc:\n+ doc = _dedent('\\n\\n'.join(lax_fn.__doc__.split('\\n\\n')[1:])).strip()\n+ return _wraps(numpy_fn, lax_description=doc)(fn)\n+ else:\n+ return _wraps(numpy_fn)(fn)\nfabs = _one_to_one_unop(np.fabs, lax.abs, True)\nbitwise_not = _one_to_one_unop(np.bitwise_not, lax.bitwise_not)\n@@ -404,7 +418,7 @@ arctan2 = _one_to_one_binop(np.arctan2, lax.atan2, True)\nminimum = _one_to_one_binop(np.minimum, lax.min)\nmaximum = _one_to_one_binop(np.maximum, lax.max)\nfloat_power = _one_to_one_binop(np.float_power, lax.pow, True)\n-nextafter = _one_to_one_binop(np.nextafter, lax.nextafter, True)\n+nextafter = _one_to_one_binop(np.nextafter, lax.nextafter, True, True)\ndef _comparison_op(numpy_fn, lax_fn):\n"
}
] | Python | Apache License 2.0 | google/jax | Note flush-denormal-to-zero behavior in nextafter. (#4049)
Since imports of functions from lax.py in lax_numpy.py previously
didn't copy docstrings, add option to extract docstring from the
lax function. To avoid duplication of the short description,
discard first line of the lax function's docstring, and pass
the rest as lax_description to _wraps. |
260,588 | 15.08.2020 17:47:28 | -7,200 | 1316562b0b96eb4ce10b0661bb113e1be3b9406c | Canonicalize result dtype to fix double precision problem in ldexp | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -757,7 +757,7 @@ _INT_DTYPES = {\n@_wraps(np.ldexp)\n@jit\ndef ldexp(x1, x2):\n- dtype = _result_dtype(np.ldexp, x1, x2)\n+ dtype = dtypes.canonicalize_dtype(_result_dtype(np.ldexp, x1, x2))\nx1, x2 = _promote_shapes(\"ldexp\", x1, x2)\nx1 = lax.convert_element_type(x1, dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -120,6 +120,7 @@ JAX_ONE_TO_ONE_OP_RECORDS = [\njtu.rand_default, [], check_dtypes=False),\nop_record(\"greater\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),\nop_record(\"greater_equal\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),\n+ op_record(\"ldexp\", 2, int_dtypes, all_shapes, jtu.rand_default, [], check_dtypes=False),\nop_record(\"less\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),\nop_record(\"less_equal\", 2, all_dtypes, all_shapes, jtu.rand_some_equal, []),\nop_record(\"log\", 1, number_dtypes, all_shapes, jtu.rand_positive, [\"rev\"],\n"
}
] | Python | Apache License 2.0 | google/jax | Canonicalize result dtype to fix double precision problem in ldexp (#4069) |
260,335 | 15.08.2020 22:55:18 | 25,200 | 8232f2deee5d1e0c78496699f35225b2f5d6226b | adapt _TempAxisName for unhashable objs
adapt _TempAxisName for unhashable objs | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -364,7 +364,7 @@ def xla_computation(fun: Callable,\nreturn xla.AxisEnv(nreps, (), (), None)\nelse:\nnreps = nreps * prod(size for name, size in axis_env)\n- names, sizes = zip(*axis_env)\n+ names, sizes = unzip2(axis_env)\nreturn xla.AxisEnv(nreps, names, sizes, None)\ndef abstractify(x):\n@@ -1240,16 +1240,21 @@ def pmap(fun: Callable[..., T],\nreturn f_pmapped\n+# When a mapped function is given no axis name, we generate a name object based\n+# on the id of the function object. Collisions aren't important because this\n+# name can't be used in collectives, as user code never gets a ref to this\n+# object. We don't want to use the function object itself because that might\n+# persist references to the function object.\n+# TODO(mattjj): revisit this unique axis name strategy\nclass _TempAxisName:\ndef __init__(self, obj):\n- self.obj = id(obj)\n- self.hash = hash(obj)\n+ self.id = id(obj)\ndef __repr__(self):\n- return '<axis {}>'.format(hex(self.obj))\n+ return f'<axis {hex(self.id)}>'\ndef __hash__(self):\n- return self.hash\n+ return hash(self.id)\ndef __eq__(self, other):\n- return type(other) is _TempAxisName and self.obj == other.obj\n+ return type(other) is _TempAxisName and self.id == other.id\ndef soft_pmap(fun: Callable, axis_name: Optional[AxisName] = None, in_axes=0\n"
}
] | Python | Apache License 2.0 | google/jax | adapt _TempAxisName for unhashable objs (#4077)
adapt _TempAxisName for unhashable objs |
260,411 | 17.08.2020 09:50:47 | -10,800 | 22b92c5122ab5af6f5e4560f9be08f5649ae7653 | Increase tolerance for CPU test LaxBackedNumpyTests::testCorrCoef | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -3623,7 +3623,10 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(\nnp_fun, jnp_fun, args_maker, check_dtypes=False,\ntol=1e-2 if jtu.device_under_test() == \"tpu\" else None)\n- self._CompileAndCheck(jnp_fun, args_maker)\n+ # Use very high tolerance to prevent failure after LLVM change\n+ # See b/164924709\n+ rtol = 1e-1 if jtu.device_under_test() == \"cpu\" else None\n+ self._CompileAndCheck(jnp_fun, args_maker, rtol=rtol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_{}_{}\".format(jtu.format_shape_dtype_string(shape, dtype),\n"
}
] | Python | Apache License 2.0 | google/jax | Increase tolerance for CPU test LaxBackedNumpyTests::testCorrCoef (#4080) |
260,298 | 17.08.2020 12:57:41 | -7,200 | ec90c3587adb569491bf54c7b447844491925337 | [jax2tf] Fix bfloat16 bug in select_and_gather_add conversion.
* [jax2tf] Fix bfloat16 bug in select_and_gather_add conversion.
This fix makes it possible to run bfloat16 tests for the jax2tf
conversion of select_and_gather_add. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -799,8 +799,8 @@ def _select_and_gather_add(tangents: TfVal,\npadding: Sequence[Tuple[int, int]]):\n# Note: this function follows the pattern in\n# jax.lax._select_and_gather_add_translation.\n- dtype = to_jax_dtype(operand.dtype)\n- nbits = dtypes.finfo(dtype).bits\n+ dtype = operand.dtype\n+ nbits = dtypes.finfo(dtype.as_numpy_dtype).bits\n# Specializing the function for 64 bits. Only up to 32 bits are supported on TPU,\n# we thus intend to let the code throw a different exception on this platform.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -265,9 +265,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ndef test_select_and_gather_add(self, harness: primitive_harness.Harness):\ndtype = harness.params[\"dtype\"]\n- if dtype is dtypes.bfloat16:\n- raise unittest.SkipTest(\"bfloat16 not implemented\")\n-\nmax_bits = 64\nif jtu.device_under_test() == \"tpu\":\nmax_bits = 32\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix bfloat16 bug in select_and_gather_add conversion. (#4058)
* [jax2tf] Fix bfloat16 bug in select_and_gather_add conversion.
This fix makes it possible to run bfloat16 tests for the jax2tf
conversion of select_and_gather_add. |
260,298 | 17.08.2020 16:32:34 | -7,200 | 4c22e012d27ca865d429492f0e5956791907a981 | [jax2tf] Explictly raise an error when attempting to convert _select_and_scatter_add_p. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -395,7 +395,6 @@ for unexpected in [\n# Primitives that are not yet implemented must be explicitly declared here.\ntf_not_yet_impl = [\nlax.reduce_p, lax.reduce_window_p, lax.rng_uniform_p,\n- lax.select_and_scatter_p,\nlax.linear_solve_p,\nlax_linalg.cholesky_p, lax_linalg.eig_p, lax_linalg.eigh_p,\n@@ -914,6 +913,12 @@ tf_impl[lax.reduce_window_max_p] = (\nfunctools.partial(_reduce_window, lax._reduce_window_max, _max_fn, -np.inf))\n# pylint: enable=protected-access\n+def _select_and_scatter(\n+ operand, source, init_value, select_jaxpr, select_consts, scatter_jaxpr,\n+ scatter_consts, window_dimensions, window_strides, padding):\n+ raise NotImplementedError(\"TODO: jax2tf can not convert _select_and_scatter\")\n+\n+tf_impl[lax.select_and_scatter_p] = _select_and_scatter\ndef _select_and_scatter_add(\noperand, source, init_value, select_jaxpr, select_consts, scatter_jaxpr,\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Explictly raise an error when attempting to convert _select_and_scatter_add_p. (#4084) |
260,287 | 17.08.2020 20:11:43 | -7,200 | 1ba4e06c9101f5fcc3fa587e76b1247b72a5fa1b | Initial version of gmap
Co-autored-by: Matthew Johnson | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/general_map.py",
"diff": "+# Copyright 2020 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import enum\n+from collections import namedtuple\n+from typing import Callable\n+from warnings import warn\n+from functools import wraps\n+\n+import jax\n+from .. import core\n+from .. import linear_util as lu\n+from ..api import _TempAxisName, _mapped_axis_size, _check_callable, _check_arg\n+from ..tree_util import tree_flatten, tree_unflatten\n+from ..api_util import flatten_fun\n+from ..interpreters import partial_eval as pe\n+\n+\n+def gmap(fun: Callable, schedule, axis_name = None) -> Callable:\n+ warn(\"gmap is an experimental feature and probably has bugs!\")\n+ _check_callable(fun)\n+\n+ if axis_name is not None:\n+ raise ValueError(\"gmap doesn't support binding axis names yet\")\n+\n+ axis_name = _TempAxisName(fun) if axis_name is None else axis_name\n+\n+ @wraps(fun)\n+ def f_gmapped(*args, **kwargs):\n+ f = lu.wrap_init(fun)\n+ args_flat, in_tree = tree_flatten((args, kwargs))\n+ mapped_invars = (True,) * len(args_flat)\n+ axis_size = _mapped_axis_size(in_tree, args_flat, (0,) * len(args_flat), \"gmap\")\n+ for arg in args_flat: _check_arg(arg)\n+ flat_fun, out_tree = flatten_fun(f, in_tree)\n+ outs = gmap_p.bind(\n+ flat_fun, *args_flat,\n+ axis_name=axis_name,\n+ axis_size=axis_size,\n+ mapped_invars=mapped_invars,\n+ schedule=tuple(schedule))\n+ return tree_unflatten(out_tree(), outs)\n+ return f_gmapped\n+\n+\n+class LoopType(enum.Enum):\n+ vectorized = enum.auto()\n+ parallel = enum.auto()\n+ sequential = enum.auto()\n+\n+Loop = namedtuple('Loop', ['type', 'size'])\n+\n+\n+def gmap_impl(fun: lu.WrappedFun, *args, axis_size, axis_name, mapped_invars, schedule):\n+ avals = [core.raise_to_shaped(core.get_aval(arg)) for arg in args]\n+ scheduled_fun = _apply_schedule(fun, axis_size, mapped_invars, schedule, *avals)\n+ return scheduled_fun(*args)\n+\n+def _parse_name(name):\n+ if isinstance(name, LoopType):\n+ return name\n+ try:\n+ return LoopType[name]\n+ except KeyError as err:\n+ raise ValueError(f\"Unrecognized loop type: {name}\") from err\n+\n+def _normalize_schedule(schedule, axis_size):\n+ scheduled = 1\n+ seen_none = False\n+ for loop in schedule:\n+ if loop[1] is not None:\n+ scheduled *= loop[1]\n+ elif seen_none:\n+ raise ValueError(\"gmap schedule can only contain at most a single None size specification\")\n+ else:\n+ seen_none = True\n+ unscheduled = axis_size // scheduled\n+\n+ new_schedule = []\n+ for i, loop in enumerate(schedule):\n+ loop_type = _parse_name(loop[0])\n+ if loop_type is LoopType.vectorized and i < len(schedule) - 1:\n+ raise ValueError(\"vectorized loops can only appear as the last component of the schedule\")\n+ new_schedule.append(Loop(loop_type, loop[1] or unscheduled))\n+ return new_schedule\n+\n+@lu.cache\n+def _apply_schedule(fun: lu.WrappedFun, axis_size, mapped_invars, schedule, *avals):\n+ mapped_avals = [core.mapped_aval(axis_size, aval) if mapped else aval\n+ for mapped, aval in zip(mapped_invars, avals)]\n+ jaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, mapped_avals)\n+\n+ schedule = _normalize_schedule(schedule, axis_size)\n+ dim_sizes = tuple(loop.size for loop in schedule)\n+\n+ sched_fun = lambda *args: core.eval_jaxpr(jaxpr, consts, *args)\n+\n+ if schedule[-1].type is LoopType.vectorized:\n+ sched_fun = jax.vmap(sched_fun)\n+ nonvector_schedule = schedule[:-1]\n+ else:\n+ nonvector_schedule = schedule\n+ for (ltype, size) in nonvector_schedule[::-1]:\n+ if ltype is LoopType.parallel:\n+ sched_fun = jax.pmap(sched_fun)\n+ elif ltype is LoopType.sequential:\n+ sched_fun = lambda *args, sched_fun=sched_fun: jax.lax.map(lambda xs: sched_fun(*xs), args)\n+\n+ def sched_fun_wrapper(*args):\n+ split_args = [arg.reshape(dim_sizes + arg.shape[1:]) for arg in args]\n+ results = sched_fun(*split_args)\n+ return [res.reshape((axis_size,) + res.shape[len(dim_sizes):]) for res in results]\n+ return sched_fun_wrapper\n+\n+gmap_p = core.MapPrimitive('gmap')\n+gmap_p.def_impl(gmap_impl)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/gmap_test.py",
"diff": "+# Copyright 2020 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+# flake8: noqa\n+\n+import functools\n+import itertools\n+import unittest\n+from unittest import SkipTest, skip, skipIf\n+\n+import numpy as np\n+from absl.testing import absltest\n+from absl.testing import parameterized\n+\n+import jax.numpy as jnp\n+from jax import test_util as jtu\n+from jax import vmap\n+from jax.experimental.general_map import gmap\n+from jax.lib import xla_bridge\n+\n+from jax.config import config\n+config.parse_flags_with_absl()\n+\n+from pmap_test import setUpModule, tearDownModule\n+\n+ignore_gmap_warning = functools.partial(\n+ jtu.ignore_warning, message=\"gmap is an experimental.*\")\n+\n+class GmapTest(jtu.JaxTestCase):\n+\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_\" + name, \"schedule\": schedule}\n+ for name, schedule in [\n+ ('seq', [('sequential', None)]),\n+ ('vec', [('vectorized', None)]),\n+ ('par', [('parallel', None)]),\n+ ('lim_vmap', [('sequential', None), ('vectorized', 2)]),\n+ ('soft_pmap', [('parallel', 2), ('vectorized', None)])\n+ ])\n+ @ignore_gmap_warning()\n+ @skipIf(not config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testBasicSchedules(self, schedule):\n+ def f(x):\n+ return jnp.dot(jnp.sin(x), x.T) * 4 + x\n+\n+ x = jnp.arange(800).reshape((8, 10, 10))\n+\n+ for loop, n in schedule:\n+ approx_n = x.shape[0] if n is None else n\n+ if loop == 'parallel' and approx_n > xla_bridge.device_count():\n+ raise SkipTest(\"this test requires more XLA devices\")\n+\n+ self.assertAllClose(vmap(f)(x), gmap(f, schedule)(x))\n+\n+if __name__ == '__main__':\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Initial version of gmap (#4006)
Co-autored-by: Matthew Johnson <mattjj@google.com> |
260,287 | 18.08.2020 12:02:28 | -7,200 | 36f3a369c73f9d293b600dc97cbd3be4e31bf708 | Separate axis splitting from collective handling
This makes the vmap collective handling a bit more flexible and allowed
me to add ppermute support. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -133,23 +133,20 @@ class BatchTrace(Trace):\nif all(bdim is not_mapped for bdim in dims_in):\nreturn primitive.bind(*vals_in, **params)\nelif config.omnistaging_enabled and primitive in collective_rules:\n- axes_names = params['axis_name']\n- if not isinstance(axes_names, (tuple, list)):\n- axes_names = (axes_names,)\n- for i, axis_name in enumerate(axes_names):\n+ axis_names = params['axis_name']\n+ if not isinstance(axis_names, (tuple, list)):\n+ axis_names = (axis_names,)\n+ for i, axis_name in enumerate(axis_names):\nframe = core.axis_frame(axis_name)\n- if frame.tag is self.master:\n- if params['axis_index_groups'] is not None:\n- raise NotImplementedError(\"axis_index_groups not supported in vmap collectives\")\n- result = collective_rules[primitive](vals_in, dims_in, frame.size, **params)\n- remaining_axes = axes_names[:i] + axes_names[(i+1):]\n- # TODO: This assumes that the collective always returns the same result for each\n- # array element, which is not true for the ones that are not reductions!\n- if remaining_axes:\n- new_params = dict(params, axis_name=remaining_axes)\n- return primitive.bind(*result, **new_params)\n- else:\n- return result\n+ if frame.tag is not self.master:\n+ continue\n+ # We run the split_axis rule with tracers, which is supposed to never\n+ # mix this axis name with another one. We will handle any invocations\n+ # of collectives over the vmapped axis in a recursive call from a tracer.\n+ if len(axis_names) > 1:\n+ return split_axis(primitive, axis_name, tracers, params)\n+ vals_out, dims_out = collective_rules[primitive](vals_in, dims_in, frame.size, **params)\n+ return map(partial(BatchTracer, self), vals_out, dims_out)\n# TODO(mattjj,phawkins): if no rule implemented, could vmap-via-map here\nbatched_primitive = get_primitive_batcher(primitive)\nval_out, dim_out = batched_primitive(vals_in, dims_in, **params)\n@@ -444,9 +441,10 @@ def omnistaging_enabler() -> None:\nreturn jaxpr_out, batched_out()\n-# It is assumed that all collectives specified below are commutative\n-# and associative over axis names if they support tuples. That is,\n-# they have to satisfy:\n-# collective(x, ('i', 'j')) == collective(x, ('j', 'i'))\n-# == collective(collective(x, 'j'), 'i')\n+# collective_rules can assume that the collective is only carried out throughout\n+# the vmapped axis (i.e. no tuples in axis_name).\ncollective_rules: Dict[core.Primitive, Callable] = {}\n+split_axis_rules: Dict[core.Primitive, Callable] = {}\n+\n+def split_axis(primitive, split_name, args, params):\n+ return split_axis_rules[primitive](split_name, args, params)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -31,6 +31,7 @@ from jax.interpreters import batching\nfrom jax.util import partial, unzip2, prod\nfrom jax.lib import xla_client as xc\nfrom jax.config import config\n+from jax.numpy import lax_numpy\nfrom jax.interpreters.pxla import axis_index\n@@ -305,6 +306,41 @@ def _allreduce_translation_rule(prim, c, val, *, axis_name, axis_index_groups,\nreplica_groups_protos = xc.make_replica_groups(replica_groups)\nreturn xops.AllReduce(val, computation, replica_groups_protos, None, None)\n+# It is assumed that all collectives that use this rule are commutative\n+# and associative over axis names if they support tuples. That is,\n+# they have to satisfy:\n+# collective(x, ('i', 'j')) == collective(x, ('j', 'i'))\n+# == collective(collective(x, 'j'), 'i')\n+def _split_axis_comm_assoc(primitive, split_name, args, params):\n+ axis_names = params['axis_name']\n+ assert isinstance(axis_names, tuple)\n+ if params['axis_index_groups'] is not None:\n+ raise NotImplementedError(\"axis_index_groups not supported in axis splitting. \"\n+ \"Please open a feature request!\")\n+ remaining_axes = list(axis_names)\n+ remaining_axes.remove(split_name)\n+ remaining_axes = tuple(remaining_axes)\n+ split_params = dict(params, axis_name=split_name)\n+ remain_params = dict(params, axis_name=remaining_axes)\n+ split_result = primitive.bind(*args, **split_params)\n+ return primitive.bind(*split_result, **remain_params)\n+\n+# NB: This is only used for collectives that do not include the vmapped axis name,\n+# which is why the rule is so simple. All other collectives go through split_axis.\n+def _collective_batcher(prim, args, dims, **params):\n+ return prim.bind(*args, **params), dims\n+\n+def _batched_reduction_collective(prim, if_mapped, if_unmapped,\n+ vals_in, dims_in, axis_size,\n+ axis_name, axis_index_groups):\n+ if axis_index_groups is not None:\n+ raise NotImplementedError(\"axis_index_groups not implemented in vmap collectives. \"\n+ \"Please open a feature request!\")\n+ vals_out = [if_mapped(v, d) if d is not batching.not_mapped else if_unmapped(v, axis_size)\n+ for v, d in zip(vals_in, dims_in)]\n+ dims_out = [batching.not_mapped] * len(vals_in)\n+ return vals_out, dims_out\n+\ndef _replica_groups(axis_env, axis_name, axis_index_groups):\nreplica_groups = xla.axis_groups(axis_env, axis_name)\nif axis_index_groups is not None:\n@@ -386,32 +422,39 @@ xla.parallel_translations[psum_p] = _psum_translation_rule\npxla.parallel_pure_rules[psum_p] = lambda *args, shape: (x * prod(shape) for x in args)\nad.deflinear(psum_p, _psum_transpose_rule)\npxla.multi_host_supported_collectives.add(psum_p)\n+batching.split_axis_rules[psum_p] = partial(_split_axis_comm_assoc, psum_p)\n+batching.primitive_batchers[psum_p] = partial(_collective_batcher, psum_p)\nbatching.collective_rules[psum_p] = \\\n- lambda vals, dims, axis_size, **_: [v.sum(d) if d is not batching.not_mapped else\n- axis_size * v\n- for v, d in zip(vals, dims)]\n+ partial(_batched_reduction_collective,\n+ psum_p,\n+ lambda v, d: v.sum(d),\n+ lambda v, axis_size: axis_size * v)\npmax_p = core.Primitive('pmax')\npmax_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nxla.parallel_translations[pmax_p] = \\\npartial(_allreduce_translation_rule, lax.max_p)\n+batching.split_axis_rules[pmax_p] = partial(_split_axis_comm_assoc, pmax_p)\n+batching.primitive_batchers[pmax_p] = partial(_collective_batcher, pmax_p)\nbatching.collective_rules[pmax_p] = \\\n- lambda vals, dims, axis_size, **_: [v.max(d) if d is not batching.not_mapped else v\n- for v, d in zip(vals, dims)]\n-# pxla.split_axis_rules[pmax_p] = \\\n-# partial(_allreduce_split_axis_rule, pmax_p, lax._reduce_max)\n+ partial(_batched_reduction_collective,\n+ pmax_p,\n+ lambda v, d: v.max(d),\n+ lambda v, axis_size: v)\npmin_p = core.Primitive('pmin')\npmin_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nxla.parallel_translations[pmin_p] = \\\npartial(_allreduce_translation_rule, lax.min_p)\n+batching.split_axis_rules[pmin_p] = partial(_split_axis_comm_assoc, pmin_p)\n+batching.primitive_batchers[pmin_p] = partial(_collective_batcher, pmin_p)\nbatching.collective_rules[pmin_p] = \\\n- lambda vals, dims, axis_size, **_: [v.min(d) if d is not batching.not_mapped else v\n- for v, d in zip(vals, dims)]\n-# pxla.split_axis_rules[pmin_p] = \\\n-# partial(_allreduce_split_axis_rule, pmin_p, lax._reduce_min)\n+ partial(_batched_reduction_collective,\n+ pmin_p,\n+ lambda v, d: v.min(d),\n+ lambda v, axis_size: v)\ndef _ppermute_translation_rule(c, x, *, axis_name, axis_env, perm, platform):\n@@ -433,11 +476,22 @@ def _ppermute_transpose_rule(t, perm, axis_name):\ninverse_perm = list(zip(dsts, srcs))\nreturn [ppermute(t, axis_name=axis_name, perm=inverse_perm)]\n+def _ppermute_batcher(vals_in, dims_in, axis_size, axis_name, perm):\n+ assert len(perm) == axis_size, \"Permutation doesn't match the axis size!\"\n+ perm_indices = np.full((axis_size,), -1, dtype=np.int32)\n+ for s, d in perm:\n+ perm_indices[s] = d\n+ vals_out = [lax_numpy.take(v, perm_indices, d) if d is not batching.not_mapped else v\n+ for v, d in zip(vals_in, dims_in)]\n+ return vals_out, dims_in\n+\nppermute_p = core.Primitive('ppermute')\nppermute_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nad.deflinear(ppermute_p, _ppermute_transpose_rule)\nxla.parallel_translations[ppermute_p] = _ppermute_translation_rule\npxla.multi_host_supported_collectives.add(ppermute_p)\n+batching.primitive_batchers[ppermute_p] = partial(_collective_batcher, pmin_p)\n+batching.collective_rules[ppermute_p] = _ppermute_batcher\ndef _all_to_all_translation_rule(c, x, *, split_axis, concat_axis, axis_name,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -1002,5 +1002,21 @@ class BatchingTest(jtu.JaxTestCase):\nvmap(vmap(lambda x: x - collective(x, ('i', 'j')), axis_name='i'), axis_name='j')(x),\nx - seq(x, axis=(1, 0)))\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testPpermute(self):\n+ nelem = 10\n+ ntests = 10\n+ x = np.arange(nelem)\n+ rng = np.random.RandomState(1)\n+ for i in range(ntests):\n+ perm = np.arange(nelem)\n+ rng.shuffle(perm)\n+ perm_pairs = np.stack([np.arange(nelem), perm], axis=-1)\n+ rng.shuffle(perm_pairs)\n+ self.assertAllClose(\n+ vmap(lambda x: x - lax.ppermute(x, 'i', perm_pairs)[0], axis_name='i')(x),\n+ x - x[perm])\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Separate axis splitting from collective handling (#4082)
This makes the vmap collective handling a bit more flexible and allowed
me to add ppermute support. |
260,485 | 18.08.2020 16:40:45 | 14,400 | 29f7fa753a24225800a7d7ba64db6441ca6a4dac | Add implementation of jax.numpy.trim_zeros | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -342,6 +342,7 @@ Not every function in NumPy is implemented; contributions are welcome!\ntril\ntril_indices\ntril_indices_from\n+ trim_zeros\ntriu\ntriu_indices\ntriu_indices_from\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -58,7 +58,7 @@ from .lax_numpy import (\nsignedinteger, sin, sinc, single, sinh, size, sometrue, sort, sort_complex, split, sqrt,\nsquare, squeeze, stack, std, subtract, sum, swapaxes, take, take_along_axis,\ntan, tanh, tensordot, tile, trace, trapz, transpose, tri, tril, tril_indices, tril_indices_from,\n- triu, triu_indices, triu_indices_from, true_divide, trunc, uint16, uint32, uint64, uint8, unique,\n+ trim_zeros, triu, triu_indices, triu_indices_from, true_divide, trunc, uint16, uint32, uint64, uint8, unique,\nunpackbits, unravel_index, unsignedinteger, unwrap, vander, var, vdot, vsplit,\nvstack, where, zeros, zeros_like, _NOT_IMPLEMENTED)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2860,11 +2860,14 @@ def polyder(p, m=1):\ncoeff = (arange(len(p), m, -1) - 1 - arange(m)[:, newaxis]).prod(0)\nreturn p[:-m] * coeff\n-def _trim_zeros(a):\n- for i, v in enumerate(a):\n- if v != 0:\n- return a[i:]\n- return a[:0]\n+@_wraps(np.trim_zeros)\n+def trim_zeros(filt, trim='fb'):\n+ nz = asarray(filt) == 0\n+ if all(nz):\n+ return empty(0, _dtype(filt))\n+ start = argmin(nz) if 'f' in trim.lower() else 0\n+ end = argmin(nz[::-1]) if 'b' in trim.lower() else 0\n+ return filt[start:len(filt) - end]\n_LEADING_ZEROS_DOC=\"\"\"\\\nSetting trim_leading_zeros=True makes the output match that of numpy.\n@@ -2878,7 +2881,7 @@ def polymul(a1, a2, *, trim_leading_zeros=False):\nif isinstance(a2, np.poly1d):\na2 = asarray(a2)\nif trim_leading_zeros and (len(a1) > 1 or len(a2) > 1):\n- a1, a2 = _trim_zeros(a1), _trim_zeros(a2)\n+ a1, a2 = trim_zeros(a1, trim='f'), trim_zeros(a2, trim='f')\nif len(a1) == 0:\na1 = asarray([0.])\nif len(a2) == 0:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1253,6 +1253,21 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"{}_trim={}\".format(\n+ jtu.format_shape_dtype_string(a_shape, dtype), trim),\n+ \"dtype\": dtype, \"a_shape\": a_shape, \"trim\": trim}\n+ for dtype in default_dtypes\n+ for a_shape in one_dim_array_shapes\n+ for trim in [\"f\", \"b\", \"fb\"]))\n+ def testTrimZeros(self, a_shape, dtype, trim):\n+ rng = jtu.rand_some_zero(self.rng())\n+ args_maker = lambda: [rng(a_shape, dtype)]\n+ np_fun = lambda arg1: np.trim_zeros(arg1, trim)\n+ jnp_fun = lambda arg1: jnp.trim_zeros(arg1, trim)\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=True)\n+\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"a_shape={} , b_shape={}\".format(\njtu.format_shape_dtype_string(a_shape, dtype),\n"
}
] | Python | Apache License 2.0 | google/jax | Add implementation of jax.numpy.trim_zeros (#4027) |
260,268 | 18.08.2020 18:49:29 | 14,400 | afeefa6f1fb8c5fdd296e5bedf4d4e1c1df70b45 | Add typing and namedtuple to `optimizers.py`, improve documentation. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optimizers.py",
"new_path": "jax/experimental/optimizers.py",
"diff": "@@ -64,8 +64,21 @@ Notice that an optimizer implementation has a lot of flexibility in the form of\nopt_state: it just has to be a pytree of JaxTypes (so that it can be passed to\nthe JAX transforms defined in api.py) and it has to be consumable by update_fun\nand get_params.\n+\n+Example Usage:\n+ opt = optimizers.sgd(learning_rate)\n+ opt_state = opt.init(params)\n+\n+ def step(step, opt_state):\n+ value, grads = jax.value_and_grad(loss_fn)(opt.get_params(state))\n+ opt_state = opt.update(step, grads, opt_state)\n+ return value, opt_state\n+\n+ for step in range(num_steps):\n+ value, opt_state = step(step, opt_state)\n\"\"\"\n+from typing import Any, Callable, NamedTuple, Tuple, Union\nfrom collections import namedtuple\nimport functools\n@@ -94,7 +107,28 @@ register_pytree_node(\nlambda xs: ((xs.packed_state,), (xs.tree_def, xs.subtree_defs)),\nlambda data, xs: OptimizerState(xs[0], data[0], data[1]))\n-def optimizer(opt_maker):\n+\n+Array = Any\n+Params = Any # Parameters are arbitrary nests of `jnp.ndarrays`.\n+State = Any # internal State\n+Updates = Params # Gradient updates are of the same type as parameters.\n+\n+InitFn = Callable[[Params], OptimizerState]\n+Step = int\n+UpdateFn = Callable[[Step, Updates, OptimizerState], OptimizerState]\n+ParamsFn = Callable[[OptimizerState], Params]\n+\n+class Optimizer(NamedTuple):\n+ init_fn: InitFn\n+ update_fn: UpdateFn\n+ params_fn: ParamsFn\n+\n+Schedule = Callable[[Step], float]\n+\n+def optimizer(opt_maker: Callable[...,\n+ Tuple[Callable[[Params], State],\n+ Callable[[Step, Updates, Params], Params],\n+ Callable[[State], Params]]]) -> Callable[..., Optimizer]:\n\"\"\"Decorator to make an optimizer defined for arrays generalize to containers.\nWith this decorator, you can write init, update, and get_params functions that\n@@ -164,7 +198,7 @@ def optimizer(opt_maker):\nparams = map(get_params, states)\nreturn tree_unflatten(tree, params)\n- return tree_init, tree_update, tree_get_params\n+ return Optimizer(tree_init, tree_update, tree_get_params)\nreturn tree_opt_maker\n@@ -188,10 +222,10 @@ def sgd(step_size):\nreturn x - step_size(i) * g\ndef get_params(x):\nreturn x\n- return init, update, get_params\n+ return Optimizer(init, update, get_params)\n@optimizer\n-def momentum(step_size, mass):\n+def momentum(step_size: Schedule, mass: float):\n\"\"\"Construct optimizer triple for SGD with momentum.\nArgs:\n@@ -218,7 +252,7 @@ def momentum(step_size, mass):\n@optimizer\n-def nesterov(step_size, mass):\n+def nesterov(step_size: Schedule, mass: float):\n\"\"\"Construct optimizer triple for SGD with Nesterov momentum.\nArgs:\n@@ -374,7 +408,7 @@ def adam(step_size, b1=0.9, b2=0.999, eps=1e-8):\nx = x - step_size(i) * mhat / (jnp.sqrt(vhat) + eps)\nreturn x, m, v\ndef get_params(state):\n- x, m, v = state\n+ x, _, _ = state\nreturn x\nreturn init, update, get_params\n@@ -408,7 +442,7 @@ def adamax(step_size, b1=0.9, b2=0.999, eps=1e-8):\nx = x - (step_size(i) / (1 - b1 ** (i + 1))) * m / (u + eps)\nreturn x, m, u\ndef get_params(state):\n- x, m, u = state\n+ x, _, _ = state\nreturn x\nreturn init, update, get_params\n@@ -462,7 +496,7 @@ def sm3(step_size, momentum=0.9):\n### learning rate schedules\n-def constant(step_size):\n+def constant(step_size) -> Schedule:\ndef schedule(i):\nreturn step_size\nreturn schedule\n@@ -489,7 +523,7 @@ def polynomial_decay(step_size, decay_steps, final_step_size, power=1.0):\nreturn schedule\n-def piecewise_constant(boundaries, values):\n+def piecewise_constant(boundaries: Any, values: Any):\nboundaries = jnp.array(boundaries)\nvalues = jnp.array(values)\nif not boundaries.ndim == values.ndim == 1:\n@@ -501,7 +535,7 @@ def piecewise_constant(boundaries, values):\nreturn values[jnp.sum(i > boundaries)]\nreturn schedule\n-def make_schedule(scalar_or_schedule):\n+def make_schedule(scalar_or_schedule: Union[float, Schedule]) -> Schedule:\nif callable(scalar_or_schedule):\nreturn scalar_or_schedule\nelif jnp.ndim(scalar_or_schedule) == 0:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optix.py",
"new_path": "jax/experimental/optix.py",
"diff": "@@ -19,8 +19,9 @@ typically used in the context of optimizing neural nets.\nEach transformation defines:\n-* ``init_fn``, to initialize (possibly empty) sets of statistics (aka ``state``)\n-* ``update_fn`` to transform a parameter update or gradient and update the state\n+* ``init_fn``: Params -> OptState, to initialize (possibly empty) sets of statistics (aka ``state``)\n+* ``update_fn``: (Updates, OptState, Optional[Params]) -> (Updates, OptState)\n+ to transform a parameter update or gradient and update the state\nAn (optional) ``chain`` utility can be used to build custom optimizers by\nchaining arbitrary sequences of transformations. For any sequence of\n@@ -36,10 +37,26 @@ different tasks may benefit from different sets of gradient transformations).\nMany popular optimizers can be implemented using ``optix`` as one-liners, and,\nfor convenience, we provide aliases for some of the most popular ones.\n+\n+Example Usage:\n+\n+ opt = optix.sgd(learning_rate)\n+ OptData = collections.namedtuple('OptData', 'step state params')\n+ data = OptData(0, opt.init(params), params)\n+\n+ def step(opt_data):\n+ step, state, params = opt_data\n+ value, grads = jax.value_and_grad(loss_fn)(params)\n+ updates, state = opt.update(grads, state, params)\n+ params = optix.apply_updates(updates, params)\n+ return value, OptData(step+1, state, params)\n+\n+ for step in range(steps):\n+ value, opt_data = step(opt_data)\n\"\"\"\n-from typing import Any, Callable, NamedTuple, Sequence, Tuple, Union\n+from typing import Any, Callable, NamedTuple, Optional, Sequence, Tuple, Union\nfrom jax import numpy as jnp\nfrom jax import random as jrandom\n@@ -60,7 +77,8 @@ Params = Any # Parameters are arbitrary nests of `jnp.ndarrays`.\nUpdates = Params # Gradient updates are of the same type as parameters.\nInitFn = Callable[[Params], Union[OptState, Sequence[OptState]]]\n-UpdateFn = Callable[[Updates, OptState], Tuple[Updates, OptState]]\n+UpdateFn = Callable[[Updates, OptState, Optional[Params]],\n+ Tuple[Updates, Union[OptState, Sequence[OptState]]]]\n###\n@@ -435,12 +453,13 @@ def chain(*args: GradientTransformation) -> GradientTransformation:\ninit_fns, update_fns = zip(*args)\n- def init_fn(params):\n+ def init_fn(params: Params) -> Sequence[OptState]:\nreturn [fn(params) for fn in init_fns]\n- def update_fn(updates, state, params=None):\n+ def update_fn(updates: Updates, state: OptState, params: Params = None\n+ ) -> Tuple[Updates, Sequence[OptState]]:\nnew_state = []\n- for s, fn in zip(state, update_fns):\n+ for s, fn in zip(state, update_fns): # pytype: disable=wrong-arg-types\nupdates, new_s = fn(updates, s, params)\nnew_state.append(new_s)\nreturn updates, new_state\n"
}
] | Python | Apache License 2.0 | google/jax | Add typing and namedtuple to `optimizers.py`, improve documentation. (#3570) |
260,321 | 19.08.2020 19:36:28 | -3,600 | b4efb31f1a9c38b6e635b1b096adc496866fb235 | Docs: Fix broken link in quickstart | [
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/quickstart.ipynb",
"new_path": "docs/notebooks/quickstart.ipynb",
"diff": "\"id\": \"Xpy1dSgNqCP4\"\n},\n\"source\": [\n- \"We'll be generating random data in the following examples. One big difference between NumPy and JAX is how you generate random numbers. For more details, see the [README](../../README.md).\"\n+ \"We'll be generating random data in the following examples. One big difference between NumPy and JAX is how you generate random numbers. For more details, see [Common Gotchas in JAX].\\n\",\n+ \"\\n\",\n+ \"[Common Gotchas in JAX]: https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#%F0%9F%94%AA-Random-Numbers\"\n]\n},\n{\n"
}
] | Python | Apache License 2.0 | google/jax | Docs: Fix broken link in quickstart (#4102) |
260,335 | 19.08.2020 15:51:40 | 25,200 | 9ba282f321c7b68d0a3f5b70c3c352bcd43a4b91 | add axis_index to supported multi-host collectives
also make the error message less confusing | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -726,8 +726,9 @@ def parallel_callable(fun, backend, axis_name, axis_size, global_axis_size,\nif is_multi_host_pmap:\nused_collectives = set(xla.jaxpr_collectives(jaxpr))\nif not used_collectives.issubset(multi_host_supported_collectives):\n+ bad_collectives = used_collectives - multi_host_supported_collectives\nmsg = \"using collectives that aren't supported for multi-host: {}\"\n- raise TypeError(msg.format(\", \".join(map(str, used_collectives))))\n+ raise TypeError(msg.format(\", \".join(map(str, bad_collectives))))\nif not config.omnistaging_enabled:\nif all(pv is None for pv in out_pvs):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -37,6 +37,9 @@ from jax.interpreters.pxla import axis_index\nxops = xc.ops\n+pxla.multi_host_supported_collectives.add(pxla.axis_index_p)\n+\n+\n### parallel traceables\ndef psum(x, axis_name, *, axis_index_groups=None):\n"
}
] | Python | Apache License 2.0 | google/jax | add axis_index to supported multi-host collectives (#4107)
also make the error message less confusing |
260,298 | 20.08.2020 09:05:30 | -7,200 | 22b593b6b9888dafb5308bc8e689d2d272ab623e | [jax2tf] General conversion of reduce_window.
* [jax2tf] General conversion of reduce_window.
Much like scatter_p, the conversion works as well as the underlying
reduction function (e.g. reduce_window_max is not properly converted
for the int8 dtype, because tf.math.maximum is not defined for int8
tensors). | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -781,9 +781,6 @@ tf_impl[lax.argmax_p] = functools.partial(_argminmax, tf.math.argmax)\n_add_fn = tf.function(tf.math.add)\n_ge_fn = tf.function(tf.math.greater_equal)\n-_min_fn = tf.function(tf.math.minimum)\n-_max_fn = tf.function(tf.math.maximum)\n-\ntf_impl[lax.cumsum_p] = tf.math.cumsum\ntf_impl[lax.cumprod_p] = tf.math.cumprod\n@@ -846,12 +843,12 @@ def _select_and_gather_add(tangents: TfVal,\nreturn tf_impl[lax.select_p](which(fst(x), fst(y)), x=x, y=y)\ninit = -np.inf if select_prim is lax.ge_p else np.inf\n- jax_f = lax._reduce_window_max if select_prim is lax.ge_p else lax._reduce_window_min\n+ init_identity = lambda x: pack(const(dtype, init), const(dtype, 0))\n- out = _reduce_window(jax_f, tf.function(reducer),\n- pack(const(dtype, init), const(dtype, 0)),\n- pack(operand, tangents), window_dimensions, window_strides,\n- padding, base_dilation, window_dilation)\n+ out = _specialized_reduce_window(reducer, init_identity,\n+ pack(operand, tangents), window_dimensions,\n+ window_strides, padding, base_dilation,\n+ window_dilation)\nreturn snd(out)\n@@ -881,21 +878,19 @@ def _get_shape_from_tensor_or_array(x):\nreturn tuple(x.shape.as_list())\nreturn tuple(x.shape)\n-\n-def _reduce_window(jax_f, reducer, init_val, operand, window_dimensions,\n- window_strides, padding, base_dilation, window_dilation,\n- input_shape=None):\n- \"\"\"TensorFlow implementation of reduce_window_{sum,min,max}.\"\"\"\n- del input_shape\n+def _common_reduce_window(operand, init_val, reducer, window_dimensions,\n+ window_strides, padding, base_dilation,\n+ window_dilation):\n# TODO(tomhennigan): tf2xla should have a shape inference function.\n- out_shape = _reduce_window_shape(jax_f, operand, window_dimensions,\n+ out_shape = _reduce_window_shape(lax._reduce_window_sum, operand, window_dimensions,\nwindow_strides, padding, base_dilation,\nwindow_dilation)\no_spec = tf.TensorSpec(operand.shape, dtype=operand.dtype)\n- reducer_fn = reducer.get_concrete_function(o_spec, o_spec)\n+ reducer_fn = tf.function(reducer).get_concrete_function(o_spec, o_spec)\nif not isinstance(init_val, tf.Tensor):\n+ assert core.skip_checks or _is_tfval(init_val), f\"Non TfVal: {init_val}\"\ninit_val = tf.constant(init_val, operand.dtype)\nout = tfxla.reduce_window(operand, init_val,\n@@ -904,13 +899,97 @@ def _reduce_window(jax_f, reducer, init_val, operand, window_dimensions,\nwindow_dilations=window_dilation, padding=padding)\nout.set_shape(out_shape)\nreturn out\n+\n+def _reduce_window(operand, init_value, *, jaxpr, consts, window_dimensions,\n+ window_strides, padding, base_dilation, window_dilation):\n+ \"\"\"TensorFlow implementation of reduce_window.\n+\n+ Args:\n+ operand: N dimensional array containing elements of type T\n+ init_value: starting value of the reduction\n+ jaxpr: the jaxpr corresponding to the reduction function\n+ consts: the constants associated with jaxpr.\n+ window_dimensions: array of integers for window dimension values\n+ window_strides: array of integers for window stride values\n+ padding: array of pairs of integers for padding values\n+ base_dilation: array of integers for base dilation values\n+ window_dilation: array of integers for window dilation values\n+\n+ Returns:\n+ The reduced operand.\n+ \"\"\"\n+ assert len(consts) == 0, \"Reduction computation cannot have constants\"\n+\n+ def reducer(arg1: TfVal, arg2: TfVal) -> TfVal:\n+ typed_jaxpr = _mk_typed_jaxpr(jaxpr, consts)\n+ res, = _interpret_jaxpr(typed_jaxpr, arg1, arg2)\n+ return res\n+\n+ return _common_reduce_window(\n+ operand, init_value, reducer, window_dimensions, window_strides, padding,\n+ base_dilation, window_dilation\n+ )\n+\n+def _specialized_reduce_window(reducer, identity, operand, window_dimensions,\n+ window_strides, padding, base_dilation,\n+ window_dilation):\n+ \"\"\"Wraps the TensorFlow reduce window operation based on a reducer and an identity\n+ function defining the initial value of the reduction depending on the dtype of the\n+ operand.\n+\n+ Args:\n+ reducer: reduction function of type TfVal -> TfVal -> TfVal\n+ identity: function that takes a TensorFlow dtype as a parameter and returns the\n+ starting value of the reduction.\n+ operand: N dimensional array containing elements of type T\n+ window_dimensions: array of integers for window dimension values\n+ window_strides: array of integers for window stride values\n+ padding: array of pairs of integers for padding values\n+ base_dilation: array of integers for base dilation values\n+ window_dilation: array of integers for window dilation values\n+\n+ Returns:\n+ The reduced operand.\n+ \"\"\"\n+\n+ return _common_reduce_window(\n+ operand, identity(operand.dtype), reducer, window_dimensions,\n+ window_strides, padding, base_dilation, window_dilation\n+ )\n+\n+def _get_max_identity(tf_dtype):\n+ numpy_tf_dtype = tf_dtype.as_numpy_dtype\n+ if tf_dtype == tf.bfloat16 or dtypes.issubdtype(numpy_tf_dtype, np.inexact):\n+ return numpy_tf_dtype(-np.inf)\n+ elif dtypes.issubdtype(numpy_tf_dtype, np.integer):\n+ return dtypes.iinfo(numpy_tf_dtype).min\n+ else:\n+ assert dtypes.issubdtype(numpy_tf_dtype, np.bool_), (\n+ f\"{tf_dtype} has no defined max identity\"\n+ )\n+ return False\n+\n+def _get_min_identity(tf_dtype):\n+ numpy_tf_dtype = tf_dtype.as_numpy_dtype\n+ if tf_dtype == tf.bfloat16 or dtypes.issubdtype(numpy_tf_dtype, np.inexact):\n+ return numpy_tf_dtype(np.inf)\n+ elif dtypes.issubdtype(numpy_tf_dtype, np.integer):\n+ return dtypes.iinfo(numpy_tf_dtype).max\n+ else:\n+ assert dtypes.issubdtype(numpy_tf_dtype, np.bool_), (\n+ f\"{tf_dtype} has no defined min identity\"\n+ )\n+ return True\n+\n# pylint: disable=protected-access\ntf_impl[lax.reduce_window_sum_p] = (\n- functools.partial(_reduce_window, lax._reduce_window_sum, _add_fn, 0))\n+ functools.partial(_specialized_reduce_window, tf.math.add, lambda x: 0))\ntf_impl[lax.reduce_window_min_p] = (\n- functools.partial(_reduce_window, lax._reduce_window_min, _min_fn, np.inf))\n+ functools.partial(_specialized_reduce_window, tf.math.minimum,\n+ _get_min_identity))\ntf_impl[lax.reduce_window_max_p] = (\n- functools.partial(_reduce_window, lax._reduce_window_max, _max_fn, -np.inf))\n+ functools.partial(_specialized_reduce_window, tf.math.maximum,\n+ _get_max_identity))\ntf_impl[lax.reduce_window_p] = _reduce_window\n# pylint: enable=protected-access\n@@ -1120,6 +1199,10 @@ def _scatter_shape(operand, scatter_indices, updates, dimension_numbers):\ndimension_numbers=dimension_numbers)\nreturn out.shape\n+def _mk_typed_jaxpr(jaxpr: core.Jaxpr, literals: Sequence) -> core.TypedJaxpr:\n+ return core.TypedJaxpr(jaxpr, literals,\n+ tuple(map(lambda v: v.aval, jaxpr.invars)),\n+ tuple(map(lambda v: v.aval, jaxpr.outvars)))\n@functools.partial(bool_to_int8, argnums=(1, 3))\ndef _scatter(update_computation, operand, scatter_indices, updates,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -645,7 +645,7 @@ lax_select_and_gather_add = tuple(\nlax_reduce_window = tuple(\n# Tests with 2d shapes (see tests.lax_test.testReduceWindow)\n- Harness(f\"2d_shape={jtu.format_shape_dtype_string(shape, dtype)}_initvalue={init_value}_computation={computation.__name__}_windowdimensions={window_dimensions}_windowstrides={window_strides}_padding={padding}_basedilation={base_dilation}_windowdilation={window_dilation}\",\n+ Harness(f\"2d_shape={jtu.format_shape_dtype_string(shape, dtype)}_initvalue={init_value}_computation={computation.__name__}_windowdimensions={window_dimensions}_windowstrides={window_strides}_padding={padding}_basedilation={base_dilation}_windowdilation={window_dilation}\".replace(' ', ''),\nlax.reduce_window,\n[RandArg(shape, dtype), StaticArg(init_value), StaticArg(computation),\nStaticArg(window_dimensions), StaticArg(window_strides),\n@@ -659,21 +659,34 @@ lax_reduce_window = tuple(\npadding=padding,\nbase_dilation=base_dilation,\nwindow_dilation=window_dilation)\n- for dtype in jtu.dtypes.all\n- for shape in [(4, 6)]\n- for init_value in map(dtype, [0, 1] if not dtype in jtu.dtypes.all_floating else [0, -np.inf, np.inf, 1])\nfor computation in [lax.add, lax.max, lax.min, lax.mul]\n- for window_dimensions in [(2, 1), (1, 2)]\n- for window_strides in [(1, 1), (2, 1), (1, 2)]\n+ for dtype in { lax.add: filter(lambda t: t != np.bool_, jtu.dtypes.all)\n+ , lax.mul: filter(lambda t: t != np.bool_, jtu.dtypes.all)\n+ , lax.max: jtu.dtypes.all\n+ , lax.min: jtu.dtypes.all\n+ }[computation]\n+ for init_value in map(\n+ dtype,\n+ (lambda ts: ts[0] if not dtype in jtu.dtypes.all_floating else ts[1])(\n+ { lax.add: ([0, 1], [0, 1])\n+ , lax.mul: ([1], [1])\n+ , lax.max: ([1], [-np.inf, 1])\n+ , lax.min: ([0], [np.inf, 0])\n+ }[computation]\n+ )\n+ )\n+ for shape in [(4, 6)]\n+ for window_dimensions in [(1, 2)]\n+ for window_strides in [(2, 1)]\nfor padding in tuple(set([tuple(lax.padtype_to_pads(shape, window_dimensions,\nwindow_strides, p))\nfor p in ['VALID', 'SAME']] +\n[((0, 3), (1, 2))]))\n- for base_dilation in [(1, 1), (2, 3)]\n- for window_dilation in [(1, 1), (1, 2)]\n+ for base_dilation in [(2, 3)]\n+ for window_dilation in [(1, 2)]\n) + tuple(\n# Tests with 4d shapes (see tests.lax_test.testReduceWindow)\n- Harness(f\"4d_shape={jtu.format_shape_dtype_string(shape, dtype)}_initvalue={init_value}_computation={computation.__name__}_windowdimensions={window_dimensions}_windowstrides={window_strides}_padding={padding}_basedilation={base_dilation}_windowdilation={window_dilation}\",\n+ Harness(f\"4d_shape={jtu.format_shape_dtype_string(shape, dtype)}_initvalue={init_value}_computation={computation.__name__}_windowdimensions={window_dimensions}_windowstrides={window_strides}_padding={padding}_basedilation={base_dilation}_windowdilation={window_dilation}\".replace(' ', ''),\nlax.reduce_window,\n[RandArg(shape, dtype), StaticArg(init_value), StaticArg(computation),\nStaticArg(window_dimensions), StaticArg(window_strides),\n@@ -687,16 +700,29 @@ lax_reduce_window = tuple(\npadding=padding,\nbase_dilation=base_dilation,\nwindow_dilation=window_dilation)\n- for dtype in jtu.dtypes.all_floating\n- for shape in [(3, 2, 4, 6)]\n- for init_value in map(dtype, [0, 1] if not dtype in jtu.dtypes.all_floating else [0, -np.inf, np.inf, 1])\nfor computation in [lax.add, lax.max, lax.min, lax.mul]\n- for window_dimensions in [(1, 1, 2, 1), (2, 1, 2, 1)]\n- for window_strides in [(1, 2, 2, 1), (1, 1, 1, 1)]\n+ for dtype in { lax.add: filter(lambda t: t != np.bool_, jtu.dtypes.all)\n+ , lax.mul: filter(lambda t: t != np.bool_, jtu.dtypes.all)\n+ , lax.max: jtu.dtypes.all\n+ , lax.min: jtu.dtypes.all\n+ }[computation]\n+ for init_value in map(\n+ dtype,\n+ (lambda ts: ts[0] if not dtype in jtu.dtypes.all_floating else ts[1])(\n+ { lax.add: ([0, 1], [0, 1])\n+ , lax.mul: ([1], [1])\n+ , lax.max: ([1], [-np.inf, 1])\n+ , lax.min: ([0], [np.inf, 0])\n+ }[computation]\n+ )\n+ )\n+ for shape in [(3, 2, 4, 6)]\n+ for window_dimensions in [(1, 1, 2, 1)]\n+ for window_strides in [(1, 2, 2, 1)]\nfor padding in tuple(set([tuple(lax.padtype_to_pads(shape, window_dimensions,\nwindow_strides, p))\nfor p in ['VALID', 'SAME']] +\n[((0, 1), (1, 0), (2, 3), (0, 2))]))\n- for base_dilation in [(1, 1, 1, 1), (2, 1, 3, 2)]\n- for window_dilation in [(1, 1, 1, 1), (1, 2, 2, 1)]\n+ for base_dilation in [(2, 1, 3, 2)]\n+ for window_dilation in [(1, 2, 2, 1)]\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -279,20 +279,39 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_reduce_window)\ndef test_reduce_window(self, harness: primitive_harness.Harness):\n- computation = harness.params['computation'].__name__\n- init_value = harness.params['init_value']\n+ f_name = harness.params['computation'].__name__\ndtype = harness.params['dtype']\n- safe_computations = [('sum', dtype(0))]\n+ expect_tf_exceptions = False\n- if dtype in jtu.dtypes.all_floating:\n- # Only in this case, np.inf can be casted safely to a meaningful value.\n- safe_computations += [('max', dtype(-np.inf)), ('min', dtype(np.inf))]\n+ if (jtu.device_under_test() == 'tpu' and dtype is np.complex64):\n+ raise unittest.SkipTest(\n+ 'TODO: JAX reduce_window on TPU does not handle complex64'\n+ )\n- if (computation, init_value) not in safe_computations:\n- raise unittest.SkipTest('TODO: only specific instances of max/min/sum are supported for now.')\n+ if ((f_name == 'min' or f_name == 'max') and\n+ dtype not in [dtypes.bfloat16, np.float16, np.float32, np.float64, np.uint8,\n+ np.int16, np.int32, np.int64]):\n+ # See https://www.tensorflow.org/api_docs/python/tf/math/minimum for a list of\n+ # the types supported by tf.math.minimum/tf.math.maximum.\n+ expect_tf_exceptions = True\n+ elif (f_name == 'add' and\n+ dtype not in [dtypes.bfloat16, np.float16, np.float32, np.float64, np.uint8,\n+ np.int8, np.int16, np.int32, np.int64, np.complex64,\n+ np.complex128]):\n+ # See https://www.tensorflow.org/api_docs/python/tf/math/add for a list of the\n+ # types supported by tf.math.add.\n+ expect_tf_exceptions = True\n+ elif (f_name == 'mul' and\n+ dtype not in [dtypes.bfloat16, np.float16, np.float32, np.float64, np.uint8,\n+ np.int8, np.uint16, np.int16, np.int32, np.int64,\n+ np.complex64, np.complex128]):\n+ # See https://www.tensorflow.org/api_docs/python/tf/math/multiply for a list of\n+ # the types supported by tf.math.multiply.\n+ expect_tf_exceptions = True\n- self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ expect_tf_exceptions=expect_tf_exceptions)\n@primitive_harness.parameterized(primitive_harness.lax_unary_elementwise)\ndef test_unary_elementwise(self, harness: primitive_harness.Harness):\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] General conversion of reduce_window. (#4093)
* [jax2tf] General conversion of reduce_window.
Much like scatter_p, the conversion works as well as the underlying
reduction function (e.g. reduce_window_max is not properly converted
for the int8 dtype, because tf.math.maximum is not defined for int8
tensors). |
260,441 | 20.08.2020 16:46:55 | -7,200 | 1e8ac248635a14249dd17269f8e165698603d6ea | Add rademacher, maxwell, double_sided_maxwell and weibull_min to jax.random. | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -1349,3 +1349,132 @@ def _t(key, df, shape, dtype):\nhalf_df = lax.div(df, two)\ng = gamma(key_n, half_df, shape, dtype)\nreturn n * jnp.sqrt(half_df / g)\n+\n+\n+def rademacher(key, shape, dtype=dtypes.int_):\n+ \"\"\"Sample from a Rademacher distribution.\n+\n+ Args:\n+ key: a PRNGKey key.\n+ shape: The shape of the returned samples.\n+ dtype: The type used for samples.\n+\n+ Returns:\n+ A jnp.array of samples, of shape `shape`. Each element in the output has\n+ a 50% change of being 1 or -1.\n+\n+ \"\"\"\n+ dtype = dtypes.canonicalize_dtype(dtype)\n+ shape = abstract_arrays.canonicalize_shape(shape)\n+ return _rademacher(key, shape, dtype)\n+\n+\n+@partial(jit, static_argnums=(1, 2))\n+def _rademacher(key, shape, dtype):\n+ bernoulli_samples = bernoulli(key=key, p=0.5, shape=shape)\n+ return (2 * bernoulli_samples - 1).astype(dtype)\n+\n+\n+def maxwell(key, shape=(), dtype=dtypes.float_):\n+ \"\"\"Sample from a one sided Maxwell distribution.\n+\n+ The scipy counterpart is `scipy.stats.maxwell`.\n+\n+ Args:\n+ key: a PRNGKey key.\n+ shape: The shape of the returned samples.\n+ dtype: The type used for samples.\n+\n+ Returns:\n+ A jnp.array of samples, of shape `shape`.\n+\n+ \"\"\"\n+ # Generate samples using:\n+ # sqrt(X^2 + Y^2 + Z^2), X,Y,Z ~N(0,1)\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `maxwell` must be a float \"\n+ f\"dtype, got {dtype}\")\n+ dtype = dtypes.canonicalize_dtype(dtype)\n+ shape = abstract_arrays.canonicalize_shape(shape)\n+ return _maxwell(key, shape, dtype)\n+\n+\n+@partial(jit, static_argnums=(1, 2))\n+def _maxwell(key, shape, dtype):\n+ shape = shape + (3,)\n+ norm_rvs = normal(key=key, shape=shape, dtype=dtype)\n+ return jnp.linalg.norm(norm_rvs, axis=-1)\n+\n+\n+def double_sided_maxwell(key, loc, scale, shape=(), dtype=dtypes.float_):\n+ \"\"\"Sample from a double sided Maxwell distribution.\n+\n+ Samples using:\n+ loc + scale* sgn(U-0.5)* one_sided_maxwell U~Unif;\n+\n+ Args:\n+ key: a PRNGKey key.\n+ loc: The location parameter of the distribution.\n+ scale: The scale parameter of the distribution.\n+ shape: The shape added to the parameters loc and scale broadcastable shape.\n+ dtype: The type used for samples.\n+\n+ Returns:\n+ A jnp.array of samples.\n+\n+ \"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `double_sided_maxwell` must be a float\"\n+ f\" dtype, got {dtype}\")\n+ dtype = dtypes.canonicalize_dtype(dtype)\n+ shape = abstract_arrays.canonicalize_shape(shape)\n+ return _double_sided_maxwell(key, loc, scale, shape, dtype)\n+\n+\n+@partial(jit, static_argnums=(1, 2, 3, 4))\n+def _double_sided_maxwell(key, loc, scale, shape, dtype):\n+ params_shapes = lax.broadcast_shapes(np.shape(loc), np.shape(scale))\n+ if not shape:\n+ shape = params_shapes\n+\n+ shape = shape + params_shapes\n+ maxwell_key, rademacher_key = split(key)\n+ maxwell_rvs = maxwell(maxwell_key, shape=shape, dtype=dtype)\n+ # Generate random signs for the symmetric variates.\n+ random_sign = rademacher(rademacher_key, shape=shape, dtype=dtype)\n+ assert random_sign.shape == maxwell_rvs.shape\n+\n+ return random_sign * maxwell_rvs * scale + loc\n+\n+\n+def weibull_min(key, scale, concentration, shape=(), dtype=dtypes.float_):\n+ \"\"\"Sample from a Weibull distribution.\n+\n+ The scipy counterpart is `scipy.stats.weibull_min`.\n+\n+ Args:\n+ key: a PRNGKey key.\n+ scale: The scale parameter of the distribution.\n+ concentration: The concentration parameter of the distribution.\n+ shape: The shape added to the parameters loc and scale broadcastable shape.\n+ dtype: The type used for samples.\n+\n+ Returns:\n+ A jnp.array of samples.\n+\n+ \"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `weibull_min` must be a float \"\n+ f\"dtype, got {dtype}\")\n+ dtype = dtypes.canonicalize_dtype(dtype)\n+ shape = abstract_arrays.canonicalize_shape(shape)\n+ return _weibull_min(key, scale, concentration, shape, dtype)\n+\n+\n+@partial(jit, static_argnums=(1, 2, 3, 4))\n+def _weibull_min(key, scale, concentration, shape, dtype):\n+ random_uniform = uniform(\n+ key=key, shape=shape, minval=0, maxval=1, dtype=dtype)\n+\n+ # Inverse weibull CDF.\n+ return jnp.power(-jnp.log1p(-random_uniform), 1.0/concentration) * scale\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -743,6 +743,111 @@ class LaxRandomTest(jtu.JaxTestCase):\nx = random.randint(key, shape, jnp.array([0, 1]), jnp.array([1, 2]))\nassert x.shape == shape\n+ def testMaxwellSample(self):\n+ num_samples = 10**5\n+ rng = random.PRNGKey(0)\n+\n+ rand = lambda x: random.maxwell(x, (num_samples, ))\n+ crand = api.jit(rand)\n+\n+ loc = scipy.stats.maxwell.mean()\n+ std = scipy.stats.maxwell.std()\n+\n+ uncompiled_samples = rand(rng)\n+ compiled_samples = crand(rng)\n+\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ # Check first and second moments.\n+ self.assertEqual((num_samples,), samples.shape)\n+ self.assertAllClose(np.mean(samples), loc, atol=0., rtol=0.1)\n+ self.assertAllClose(np.std(samples), std, atol=0., rtol=0.1)\n+ self._CheckKolmogorovSmirnovCDF(samples, scipy.stats.maxwell().cdf)\n+\n+ @parameterized.named_parameters(\n+ ('test1', 4.0, 1.0),\n+ ('test2', 2.0, 3.0))\n+ def testWeibullSample(self, concentration, scale):\n+ num_samples = 10**5\n+ rng = random.PRNGKey(0)\n+\n+ rand = lambda x: random.weibull_min(x, scale, concentration, (num_samples,))\n+ crand = api.jit(rand)\n+\n+ loc = scipy.stats.weibull_min.mean(c=concentration, scale=scale)\n+ std = scipy.stats.weibull_min.std(c=concentration, scale=scale)\n+\n+ uncompiled_samples = rand(rng)\n+ compiled_samples = crand(rng)\n+\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ # Check first and second moments.\n+ self.assertEqual((num_samples,), samples.shape)\n+ self.assertAllClose(np.mean(samples), loc, atol=0., rtol=0.1)\n+ self.assertAllClose(np.std(samples), std, atol=0., rtol=0.1)\n+ self._CheckKolmogorovSmirnovCDF(samples, scipy.stats.weibull_min(\n+ c=concentration, scale=scale).cdf)\n+\n+ @parameterized.named_parameters(\n+ ('test1', 4.0, 1.0),\n+ ('test2', 2.0, 3.0))\n+ def testDoublesidedMaxwellSample(self, loc, scale):\n+ num_samples = 10**5\n+ rng = random.PRNGKey(0)\n+\n+ rand = lambda key: random.double_sided_maxwell(\n+ rng, loc, scale, (num_samples,))\n+ crand = api.jit(rand)\n+\n+ mean = loc\n+ std = np.sqrt(3.) * scale\n+\n+ uncompiled_samples = rand(rng)\n+ compiled_samples = crand(rng)\n+\n+ # Compute the double sided maxwell CDF through the one sided maxwell cdf.\n+ # This is done as follows:\n+ # P(DSM <= x) = P (loc + scale * radamacher_sample * one_sided_sample <=x) =\n+ # P (radamacher_sample * one_sided_sample <= (x - loc) / scale) =\n+ # 1/2 P(one_sided_sample <= (x - loc) / scale)\n+ # + 1/2 P( - one_sided_sample <= (x - loc) / scale) =\n+ # 1/2 P(one_sided_sample <= (x - loc) / scale)\n+ # + 1/2 P(one_sided_sample >= - (x - loc) / scale) =\n+ # 1/2 CDF_one_maxwell((x - loc) / scale))\n+ # + 1/2 (1 - CDF_one_maxwell(- (x - loc) / scale)))\n+ def double_sided_maxwell_cdf(x, loc, scale):\n+ pos = scipy.stats.maxwell().cdf((x - loc)/ scale)\n+ neg = (1 - scipy.stats.maxwell().cdf((-x + loc)/ scale))\n+ return (pos + neg) / 2\n+\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ # Check first and second moments.\n+ self.assertEqual((num_samples,), samples.shape)\n+ self.assertAllClose(np.mean(samples), mean, atol=0., rtol=0.1)\n+ self.assertAllClose(np.std(samples), std, atol=0., rtol=0.1)\n+\n+ self._CheckKolmogorovSmirnovCDF(\n+ samples, lambda x: double_sided_maxwell_cdf(x, loc, scale))\n+\n+ def testRadamacher(self):\n+ rng = random.PRNGKey(0)\n+ num_samples = 10**5\n+\n+ rand = lambda x: random.rademacher(x, (num_samples,))\n+ crand = api.jit(rand)\n+\n+ uncompiled_samples = rand(rng)\n+ compiled_samples = crand(rng)\n+\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ unique_values, counts = np.unique(samples, return_counts=True)\n+ assert len(unique_values) == 2\n+ assert len(counts) == 2\n+\n+ self.assertAllClose(\n+ counts[0]/ num_samples, 0.5, rtol=1e-02, atol=1e-02)\n+ self.assertAllClose(\n+ counts[1]/ num_samples, 0.5, rtol=1e-02, atol=1e-02)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add rademacher, maxwell, double_sided_maxwell and weibull_min to jax.random. (#4104) |
260,335 | 20.08.2020 14:44:26 | 25,200 | 306314590e0c4565178320b13acac40adaee1f8d | use xla.backend_compile function in pxla.py
* use xla.backend_compile function in pxla.py
Not only is this useful for profiling, it also helps us do google-internal logging for the XLA team. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -302,12 +302,9 @@ def _cpp_jit(\noptions.parameter_is_tupled_arguments = True\nreturn (\n- # We call xla._backend_compile to ensure the XLA computation appears\n+ # We call xla.backend_compile to ensure the XLA computation appears\n# separately in Python profiling results.\n- xla._backend_compile(\n- backend,\n- xla_result.xla_computation,\n- options=options),\n+ xla.backend_compile(backend, xla_result.xla_computation, options),\nxla_result.out_pytree_def,\nxla_result.shaped_arrays,\nxla_result.lazy_expressions)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -853,7 +853,7 @@ def parallel_callable(fun, backend, axis_name, axis_size, global_axis_size,\nuse_spmd_partitioning=use_spmd_partitioning,\n)\ncompile_options.parameter_is_tupled_arguments = tuple_args\n- compiled = backend.compile(built, compile_options=compile_options)\n+ compiled = xla.backend_compile(backend, built, compile_options)\narg_parts_ = arg_parts or [None] * len(avals)\ninput_sharding_specs = [\n@@ -1243,7 +1243,7 @@ def _soft_pmap_callable(fun, axis_name, axis_size, mapped_invars, *avals):\nnum_replicas=num_devices, num_partitions=1, device_assignment=None)\ncompile_options.tuple_arguments = tuple_args\nbackend = xb.get_backend(None)\n- compiled = backend.compile(built, compile_options=compile_options)\n+ compiled = xla.backend_compile(backend, built, compile_options)\ninput_specs = [\nShardingSpec(shards_per_axis=(num_devices,) + (1,) * (aval.ndim - 1),\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/sharded_jit.py",
"new_path": "jax/interpreters/sharded_jit.py",
"diff": "@@ -121,9 +121,9 @@ def _sharded_callable(\ndevice_assignment = np.reshape(device_assignment, (-1, num_partitions))\n# device_assignment = None # TODO(skye): replace with default device assignment?\n- compiled = xb.get_backend().compile(\n- built, compile_options=xb.get_compile_options(\n- nrep, num_partitions, device_assignment))\n+ compiled = xla.backend_compile(\n+ xb.get_backend(), built,\n+ xb.get_compile_options(nrep, num_partitions, device_assignment))\ninput_specs = [\npxla.partitioned_sharding_spec(num_partitions, parts, aval)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -34,7 +34,7 @@ from ..abstract_arrays import (ConcreteArray, ShapedArray, AbstractToken,\nabstract_token)\nfrom ..core import Literal, pp_eqn_compact\nfrom ..pprint_util import pp\n-from ..util import (partial, partialmethod, cache, prod, unzip2, memoize,\n+from ..util import (partial, partialmethod, cache, prod, unzip2,\nextend_name_stack, wrap_name, safe_zip, safe_map)\nfrom ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\n@@ -261,7 +261,7 @@ def xla_primitive_callable(prim, *arg_specs: Tuple[core.AbstractValue,\nnum_partitions=1,\ndevice_assignment=device and (device.id,))\noptions.parameter_is_tupled_arguments = tuple_args\n- compiled = _backend_compile(backend, built_c, options)\n+ compiled = backend_compile(backend, built_c, options)\nif nreps == 1:\nreturn partial(_execute_compiled_primitive, prim, compiled, handle_result)\nelse:\n@@ -319,7 +319,7 @@ def primitive_subcomputation(prim, *avals, **params):\naxis_env = AxisEnv(1, (), (), None)\nreturn primitive_computation(prim, axis_env, None, False, *avals, **params)\n-def _backend_compile(backend, built_c, options):\n+def backend_compile(backend, built_c, options):\n# we use a separate function call to ensure that XLA compilation appears\n# separately in Python profiling results\nreturn backend.compile(built_c, compile_options=options)\n@@ -662,7 +662,7 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\nnum_partitions=1,\ndevice_assignment=(device.id,) if device else None)\noptions.parameter_is_tupled_arguments = tuple_args\n- compiled = _backend_compile(backend, built, options)\n+ compiled = backend_compile(backend, built, options)\nif nreps == 1:\nreturn partial(_execute_compiled, compiled, result_handlers)\nelse:\n@@ -780,20 +780,6 @@ def _execute_trivial(jaxpr, device: Optional[Device], consts, handlers, *args):\nreturn [_copy_device_array_to_device(x, device) if type(x) is DeviceArray\nelse h(device_put(x, device)) for h, x in zip(handlers, outs)]\n-@memoize\n-def _get_device(device, backend):\n- # TODO(mattjj): after jaxlib update, avoid compile here, just to get device\n- c = xb.make_computation_builder(\"get_device\")\n- built = c.build(_make_unit(c))\n- options = xb.get_compile_options(\n- num_replicas=1,\n- num_partitions=1,\n- device_assignment=(device.id,) if device else None)\n- backend = xb.get_backend(backend)\n- compiled = backend.compile(built, compile_options=options)\n- out, = compiled.local_devices()\n- return out\n-\nxla_call_p = core.CallPrimitive('xla_call')\nxla_call = xla_call_p.bind\nxla_call_p.def_impl(_xla_call_impl)\n@@ -1208,8 +1194,7 @@ def _lazy_force_computation(aval: core.ShapedArray,\nnum_replicas=1,\nnum_partitions=1,\ndevice_assignment=device and (device.id,))\n- backend = xb.get_device_backend(device)\n- compiled = backend.compile(built_c, compile_options=options)\n+ compiled = backend_compile(xb.get_device_backend(device), built_c, options)\nforce_fun: Callable[[DeviceArray], DeviceArray]\nif lazy.is_constant(lexpr):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/gmap_test.py",
"new_path": "tests/gmap_test.py",
"diff": "import functools\nimport itertools\n+import os\nimport unittest\nfrom unittest import SkipTest, skip, skipIf\n@@ -32,11 +33,31 @@ from jax.lib import xla_bridge\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n-from pmap_test import setUpModule, tearDownModule\n-\nignore_gmap_warning = functools.partial(\njtu.ignore_warning, message=\"gmap is an experimental.*\")\n+# TODO(mattjj): de-duplicate setUpModule and tearDownModule with pmap_test.py\n+# Run all tests with 8 CPU devices.\n+def setUpModule():\n+ global prev_xla_flags\n+ prev_xla_flags = os.getenv(\"XLA_FLAGS\")\n+ flags_str = prev_xla_flags or \"\"\n+ # Don't override user-specified device count, or other XLA flags.\n+ if \"xla_force_host_platform_device_count\" not in flags_str:\n+ os.environ[\"XLA_FLAGS\"] = (flags_str +\n+ \" --xla_force_host_platform_device_count=8\")\n+ # Clear any cached backends so new CPU backend will pick up the env var.\n+ xla_bridge.get_backend.cache_clear()\n+\n+# Reset to previous configuration in case other test modules will be run.\n+def tearDownModule():\n+ if prev_xla_flags is None:\n+ del os.environ[\"XLA_FLAGS\"]\n+ else:\n+ os.environ[\"XLA_FLAGS\"] = prev_xla_flags\n+ xla_bridge.get_backend.cache_clear()\n+\n+\nclass GmapTest(jtu.JaxTestCase):\n@parameterized.named_parameters(\n"
}
] | Python | Apache License 2.0 | google/jax | use xla.backend_compile function in pxla.py (#4113)
* use xla.backend_compile function in pxla.py
Not only is this useful for profiling, it also helps us do google-internal logging for the XLA team. |
260,335 | 21.08.2020 11:10:53 | 25,200 | b2a239ca9e7ffa9008e5b1db6adcac66f2bf02f2 | don't force backend creation in xla_computation | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -611,17 +611,13 @@ def _xla_computation(\nelse:\nout_tuple = build_out_tuple()\n- backend_ = xb.get_backend(backend)\n- if backend_.platform in (\"gpu\", \"tpu\"):\n- donated_invars = xla.set_up_aliases(c, xla_args, out_tuple,\n- donated_invars, tuple_args)\nif any(donated_invars):\n# TODO(tomhennigan): At call time we should mark these buffers as deleted.\n- unused_donations = [\n- str(c.GetShape(a)) for a, d in zip(xla_args, donated_invars) if d\n- ]\n- warn(\"Some donated buffers were not usable: {}\".format(\n- \", \".join(unused_donations)))\n+ unused = xla.set_up_aliases(c, xla_args, out_tuple,\n+ donated_invars, tuple_args)\n+ if any(unused):\n+ shapes = [str(c.GetShape(a)) for a, d in zip(xla_args, unused) if d]\n+ warn(\"Some donated buffers were not usable: {}\".format(\", \".join(shapes)))\nbuilt = c.build(out_tuple)\nout_shapes_flat = [ShapeDtypeStruct(a.shape, a.dtype) for a in out_avals]\nout_shape = tree_unflatten(out_tree(), out_shapes_flat)\n"
}
] | Python | Apache License 2.0 | google/jax | don't force backend creation in xla_computation |
260,644 | 21.08.2020 20:19:51 | -7,200 | 9d733dd7d7edb3660493654c7aa807e996f99a37 | Doc: change suggested way of starting the profiler | [
{
"change_type": "MODIFY",
"old_path": "docs/profiling.md",
"new_path": "docs/profiling.md",
"diff": "@@ -37,11 +37,13 @@ from a running program.\n```python\nimport jax.profiler\n- jax.profiler.start_server(9999)\n+ server = jax.profiler.start_server(9999)\n```\nThis starts the profiler server that TensorBoard connects to. The profiler\n- server must be running before you move on to the next step.\n+ server must be running before you move on to the next step. It will remain\n+ alive and listening until the object returned by `start_server()` is\n+ destroyed.\nIf you'd like to profile a snippet of a long-running program (e.g. a long\ntraining loop), you can put this at the beginning of the program and start\n"
}
] | Python | Apache License 2.0 | google/jax | Doc: change suggested way of starting the profiler (#4120) |
260,335 | 21.08.2020 17:43:15 | 25,200 | 66a02b69713a773a837b7f9160dacb6c9a6d397f | only construct one axis_index_p primitive
Before this change, there were two versions, one used with omnistaging
and one without. But that made bookkeeping hard and buggy. This change
defines the axis_index_p primitive in core.py. Some of its rules are
still changed when omnistaging is enabled. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1436,7 +1436,7 @@ axis_frame = None\ndef omnistaging_enabler() -> None:\nglobal thread_local_state, call_bind, find_top_trace, initial_style_staging, \\\nnew_master, reset_trace_state, extend_axis_env, axis_frame, \\\n- axis_index, axis_index_p, new_base_master, eval_context, \\\n+ axis_index, new_base_master, eval_context, \\\nTraceStack, TraceState\ndel initial_style_staging\n@@ -1629,5 +1629,5 @@ def omnistaging_enabler() -> None:\n\"\"\"\nreturn axis_index_p.bind(axis_name=axis_name)\n+\naxis_index_p = Primitive('axis_index')\n- axis_index_p.def_abstract_eval(lambda *, axis_name: ShapedArray((), np.int32))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -45,7 +45,7 @@ from .. import linear_util as lu\nfrom .. import lazy\nfrom .. import source_info_util\nfrom ..abstract_arrays import ConcreteArray, ShapedArray, array_types\n-from ..core import Var, Literal\n+from ..core import Var, Literal, axis_index_p\nfrom ..util import (partial, unzip2, unzip3, prod, safe_map, safe_zip,\nextend_name_stack, wrap_name)\nfrom ..lib import xla_bridge as xb\n@@ -483,7 +483,6 @@ def _axis_index_translation_rule(c, nreps, sizes, axis_name):\nunsigned_index = xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)\nreturn xops.ConvertElementType(unsigned_index, xb.dtype_to_etype(np.int32))\n-axis_index_p = core.Primitive('axis_index')\naxis_index_p.def_custom_bind(_axis_index_bind)\naxis_index_p.def_abstract_eval(\nlambda *args, **params: ShapedArray((), np.int32))\n@@ -1363,13 +1362,13 @@ def omnistaging_enable() -> None:\nglobal DynamicAxisEnvFrame, DynamicAxisEnv, _ThreadLocalState, \\\n_thread_local_state, extend_dynamic_axis_env, unmapped_device_count, \\\naxis_index, _axis_index_bind, _axis_index_translation_rule, \\\n- axis_index_p, apply_parallel_primitive, parallel_pure_rules, \\\n+ apply_parallel_primitive, parallel_pure_rules, \\\n_pvals_to_results_handler, _pval_to_result_handler, replicate, \\\navals_to_results_handler, axis_index\ndel DynamicAxisEnvFrame, DynamicAxisEnv, _ThreadLocalState, \\\n_thread_local_state, extend_dynamic_axis_env, unmapped_device_count, \\\naxis_index, _axis_index_bind, _axis_index_translation_rule, \\\n- axis_index_p, apply_parallel_primitive, parallel_pure_rules, \\\n+ apply_parallel_primitive, parallel_pure_rules, \\\n_pvals_to_results_handler, _pval_to_result_handler, replicate\ndef avals_to_results_handler(size, nrep, npart, out_parts, out_avals):\n@@ -1398,6 +1397,10 @@ def omnistaging_enable() -> None:\nreturn [h(bufs) for h, bufs in zip(handlers, buffers)]\nreturn handler\n- soft_pmap_rules[core.axis_index_p] = _axis_index_soft_pmap_rule # type: ignore\n+ soft_pmap_rules[axis_index_p] = _axis_index_soft_pmap_rule # type: ignore\n- from ..core import axis_index, axis_index_p # type: ignore # noqa: F401\n+ axis_index_p.bind = partial(core.Primitive.bind, axis_index_p)\n+ axis_index_p.def_abstract_eval(lambda *, axis_name: ShapedArray((), np.int32))\n+ del xla.translations[axis_index_p]\n+\n+ from ..core import axis_index # type: ignore # noqa: F401\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -37,7 +37,7 @@ from jax.interpreters.pxla import axis_index\nxops = xc.ops\n-pxla.multi_host_supported_collectives.add(pxla.axis_index_p)\n+pxla.multi_host_supported_collectives.add(core.axis_index_p)\n### parallel traceables\n"
}
] | Python | Apache License 2.0 | google/jax | only construct one axis_index_p primitive
Before this change, there were two versions, one used with omnistaging
and one without. But that made bookkeeping hard and buggy. This change
defines the axis_index_p primitive in core.py. Some of its rules are
still changed when omnistaging is enabled. |
260,335 | 21.08.2020 19:58:06 | 25,200 | 56b3688db90cc6c943a15eda4ca7e7c673c17e14 | make random.choice error when shape isn't sequence
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -556,6 +556,9 @@ def choice(key, a, shape=(), replace=True, p=None):\nReturns:\nAn array of shape `shape` containing samples from `a`.\n\"\"\"\n+ if not isinstance(shape, Sequence):\n+ raise TypeError(\"shape argument of jax.random.choice must be a sequence, \"\n+ f\"got {shape}\")\na = jnp.asarray(a)\nif a.ndim not in [0, 1]:\nraise ValueError(\"a must be an integer or 1-dimensional\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -848,6 +848,13 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertAllClose(\ncounts[1]/ num_samples, 0.5, rtol=1e-02, atol=1e-02)\n+ def testChoiceShapeIsNotSequenceError(self):\n+ key = random.PRNGKey(0)\n+ with self.assertRaises(TypeError):\n+ random.choice(key, 5, 2, replace=False)\n+ with self.assertRaises(TypeError):\n+ random.choice(key, 5, 2, replace=True)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | make random.choice error when shape isn't sequence
fixes #4124 |
260,298 | 24.08.2020 21:29:22 | -7,200 | 0cc3802b0453efa85b45d98099590302608936a9 | Fix documentation of scatter_* operations.
* Fix documentation of scatter_* operations.
This commit changes the documentation of the `unique_indices`
parameter to scatter to better capture its intended meaning in
XLA. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -868,8 +868,9 @@ def scatter_add(operand: Array, scatter_indices: Array, updates: Array,\nrelate.\nindices_are_sorted: whether `scatter_indices` is known to be sorted. If\ntrue, may improve performance on some backends.\n- unique_indices: whether `scatter_indices` is known to be free of duplicates.\n- If true, may improve performance on some backends.\n+ unique_indices: whether the indices to be updated in ``operand`` are\n+ guaranteed to not overlap with each other. If true, may improve performance on\n+ some backends.\nReturns:\nAn array containing the sum of `operand` and the scattered updates.\n@@ -902,8 +903,9 @@ def scatter_mul(operand: Array, scatter_indices: Array, updates: Array,\nrelate.\nindices_are_sorted: whether `scatter_indices` is known to be sorted. If\ntrue, may improve performance on some backends.\n- unique_indices: whether `scatter_indices` is known to be free of duplicates.\n- If true, may improve performance on some backends.\n+ unique_indices: whether the indices to be updated in ``operand`` are\n+ guaranteed to not overlap with each other. If true, may improve performance on\n+ some backends.\nReturns:\nAn array containing the sum of `operand` and the scattered updates.\n@@ -936,8 +938,9 @@ def scatter_min(operand: Array, scatter_indices: Array, updates: Array,\nrelate.\nindices_are_sorted: whether `scatter_indices` is known to be sorted. If\ntrue, may improve performance on some backends.\n- unique_indices: whether `scatter_indices` is known to be free of duplicates.\n- If true, may improve performance on some backends.\n+ unique_indices: whether the indices to be updated in ``operand`` are\n+ guaranteed to not overlap with each other. If true, may improve performance on\n+ some backends.\nReturns:\nAn array containing the sum of `operand` and the scattered updates.\n@@ -970,8 +973,9 @@ def scatter_max(operand: Array, scatter_indices: Array, updates: Array,\nrelate.\nindices_are_sorted: whether `scatter_indices` is known to be sorted. If\ntrue, may improve performance on some backends.\n- unique_indices: whether `scatter_indices` is known to be free of duplicates.\n- If true, may improve performance on some backends.\n+ unique_indices: whether the indices to be updated in ``operand`` are\n+ guaranteed to not overlap with each other. If true, may improve performance on\n+ some backends.\nReturns:\nAn array containing the sum of `operand` and the scattered updates.\n@@ -1010,8 +1014,9 @@ def scatter(operand: Array, scatter_indices: Array, updates: Array,\nrelate.\nindices_are_sorted: whether `scatter_indices` is known to be sorted. If\ntrue, may improve performance on some backends.\n- unique_indices: whether `scatter_indices` is known to be free of duplicates.\n- If true, may improve performance on some backends.\n+ unique_indices: whether the indices to be updated in ``operand`` are\n+ guaranteed to not overlap with each other. If true, may improve performance on\n+ some backends.\nReturns:\nAn array containing the sum of `operand` and the scattered updates.\n"
}
] | Python | Apache License 2.0 | google/jax | Fix documentation of scatter_* operations. (#4138)
* Fix documentation of scatter_* operations.
This commit changes the documentation of the `unique_indices`
parameter to scatter to better capture its intended meaning in
XLA. |
260,510 | 24.08.2020 21:08:23 | 25,200 | 774b5f688e69a33396309a1d0dadb58783fbba86 | Remove frame check assertion in `extend_axis_env`. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1579,8 +1579,7 @@ def omnistaging_enabler() -> None:\ntry:\nyield\nfinally:\n- frame_ = thread_local_state.trace_state.axis_env.pop()\n- assert frame is frame_\n+ thread_local_state.trace_state.axis_env.pop()\ndef axis_frame(axis_name):\nframes = thread_local_state.trace_state.axis_env\n"
}
] | Python | Apache License 2.0 | google/jax | Remove frame check assertion in `extend_axis_env`. |
260,335 | 25.08.2020 05:38:41 | 25,200 | f4b05bc9ea18bda3dfab1cab77b2e0a36379a1c7 | make pe.abstract_eval_fun use omnistaging | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -315,11 +315,10 @@ call_param_updaters: Dict[core.Primitive, Callable] = {}\ndef abstract_eval_fun(fun, *avals, **params):\n- pvals_in = [PartialVal.unknown(a) for a in avals]\nif config.omnistaging_enabled:\n- _, pvals_out, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvals_in,\n- instantiate=True)\n+ _, avals_out, _ = trace_to_jaxpr_dynamic(lu.wrap_init(fun, params), avals)\nelse:\n+ pvals_in = [PartialVal.unknown(a) for a in avals]\n_, pvals_out, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvals_in,\ninstantiate=True, stage_out=True)\navals_out, _ = unzip2(pvals_out)\n"
}
] | Python | Apache License 2.0 | google/jax | make pe.abstract_eval_fun use omnistaging (#4139) |
260,335 | 26.08.2020 10:21:56 | 25,200 | 1d93991003cba20235c21a51e313efa5e06a218e | allow random.choice to accept ndarray input
* allow random.choice to accept ndarray `a`
follow-up to to allow ndarray inputs to be passed
* add jax.random.choice tests to cover ndarray input
* don't use callables in test params
it can mess with pytest-xdist because of hashing by id | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -98,6 +98,14 @@ def _is_prng_key(key: jnp.ndarray) -> bool:\n### utilities\n+# TODO(mattjj,jakevdp): add more info to error message, use this utility more\n+def _asarray(x):\n+ \"\"\"A more restrictive jnp.asarray, only accepts JAX arrays and np.ndarrays.\"\"\"\n+ if not isinstance(x, (np.ndarray, jnp.ndarray)):\n+ raise TypeError(f\"Function requires array input, got {x} of type {type(x)}.\")\n+ return jnp.asarray(x)\n+\n+\ndef _make_rotate_left(dtype):\nif not jnp.issubdtype(dtype, np.integer):\nraise TypeError(\"_rotate_left only accepts integer dtypes.\")\n@@ -561,7 +569,11 @@ def choice(key, a, shape=(), replace=True, p=None):\nf\"got {shape}\")\nif np.ndim(a) not in [0, 1]:\nraise ValueError(\"a must be an integer or 1-dimensional\")\n- n_inputs = int(a) if np.ndim(a) == 0 else len(a)\n+ if np.ndim(a) == 0:\n+ a = int(a)\n+ else:\n+ a = _asarray(a)\n+ n_inputs = a if np.ndim(a) == 0 else len(a)\nn_draws = prod(shape)\nif n_draws == 0:\nreturn jnp.zeros(shape, dtype=lax.dtype(a))\n@@ -577,7 +589,7 @@ def choice(key, a, shape=(), replace=True, p=None):\nelse:\nresult = permutation(key, a)[:n_draws]\nelse:\n- if np.shape(p) != (n_inputs,):\n+ if p.shape != (n_inputs,):\nraise ValueError(\"p must be None or match the shape of a\")\nif replace:\np_cuml = jnp.cumsum(p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -228,11 +228,13 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor shape in [(), (5,), (4, 5)]\nfor replace in [True, False]\nfor weighted in [True, False]\n- for array_input in [True, False]))\n+ for array_input in [False, 'jnp', 'np']))\ndef testChoice(self, dtype, shape, replace, weighted, array_input):\nN = 100\nkey = random.PRNGKey(0)\n- x = N if not array_input else jnp.arange(N, dtype=dtype)\n+ x = (N if not array_input else\n+ jnp.arange(N, dtype=dtype) if array_input == 'jnp' else\n+ np.arange(N, dtype=dtype))\np = None if not weighted else jnp.arange(N)\nrand = lambda key: random.choice(key, x, shape, p=p, replace=replace)\ncrand = api.jit(rand)\n@@ -241,7 +243,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nsample2 = crand(key)\nself.assertEqual(shape, sample1.shape)\n- if array_input:\n+ if array_input == 'jnp':\nself.assertEqual(x.dtype, sample1.dtype)\nif not replace:\nassert len(np.unique(sample1)) == len(np.ravel(sample1))\n"
}
] | Python | Apache License 2.0 | google/jax | allow random.choice to accept ndarray input (#4145)
* allow random.choice to accept ndarray `a`
follow-up to #4137 to allow ndarray inputs to be passed
* add jax.random.choice tests to cover ndarray input
* don't use callables in test params
it can mess with pytest-xdist because of hashing by id |
260,298 | 27.08.2020 09:46:32 | -7,200 | 1dc71b2f41bc17ef6d0854661fb64e9a668babea | [jax2tf] Add testing for add/mul/min/max conversion.
* [jax2tf] Add testing for add/mul/min/max conversion.
Only certain types are supported for each of the operations above.
This commit adds previously missing tests to make this explicit. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -22,6 +22,7 @@ from typing import Any, Callable, Dict, Iterable, Optional, NamedTuple, Sequence\nfrom absl import testing\nfrom jax import config\n+from jax import dtypes\nfrom jax import test_util as jtu\nfrom jax import lax\nfrom jax import lax_linalg\n@@ -206,6 +207,72 @@ lax_population_count = tuple(\n]\n)\n+def _get_max_identity(dtype):\n+ if dtypes.issubdtype(dtype, np.inexact):\n+ return np.array(-np.inf, dtype)\n+ elif dtypes.issubdtype(dtype, np.integer):\n+ return np.array(dtypes.iinfo(dtype).min, dtype)\n+ elif dtypes.issubdtype(dtype, np.bool_):\n+ return np.array(False, np.bool_)\n+\n+def _get_min_identity(dtype):\n+ if dtypes.issubdtype(dtype, np.inexact):\n+ return np.array(np.inf, dtype)\n+ elif dtypes.issubdtype(dtype, np.integer):\n+ return np.array(dtypes.iinfo(dtype).max, dtype)\n+ elif dtypes.issubdtype(dtype, np.bool_):\n+ return np.array(True, np.bool_)\n+\n+lax_add_mul = tuple(\n+ Harness(f\"fun={f_jax.__name__}_{jtu.dtype_str(dtype)}\",\n+ f_jax,\n+ [lhs, rhs],\n+ f_jax=f_jax,\n+ dtype=dtype)\n+ for f_jax in [lax.add, lax.mul]\n+ for dtype in filter(lambda t: t != np.bool_, jtu.dtypes.all)\n+ for lhs, rhs in [\n+ (np.array([1, 2], dtype=dtype), np.array([3, 4], dtype=dtype))\n+ ]\n+) + tuple(\n+ Harness(f\"fun={f_jax.__name__}_bounds_{jtu.dtype_str(dtype)}\",\n+ f_jax,\n+ [StaticArg(lhs), StaticArg(rhs)],\n+ f_jax=f_jax,\n+ dtype=dtype)\n+ for f_jax in [lax.add, lax.mul]\n+ for dtype in filter(lambda t: t != np.bool_, jtu.dtypes.all)\n+ for lhs, rhs in [\n+ (np.array([3, 3], dtype=dtype),\n+ np.array([_get_max_identity(dtype), _get_min_identity(dtype)], dtype=dtype))\n+ ]\n+)\n+\n+lax_min_max = tuple(\n+ Harness(f\"fun={f_jax.__name__}_{jtu.dtype_str(dtype)}\",\n+ f_jax,\n+ [lhs, rhs],\n+ f_jax=f_jax,\n+ dtype=dtype)\n+ for f_jax in [lax.min, lax.max]\n+ for dtype in jtu.dtypes.all\n+ for lhs, rhs in [\n+ (np.array([1, 2], dtype=dtype), np.array([3, 4], dtype=dtype))\n+ ]\n+) + tuple(\n+ Harness(f\"fun={f_jax.__name__}_inf_nan_{jtu.dtype_str(dtype)}_{lhs[0]}_{rhs[0]}\",\n+ f_jax,\n+ [StaticArg(lhs), StaticArg(rhs)],\n+ f_jax=f_jax,\n+ dtype=dtype)\n+ for f_jax in [lax.min, lax.max]\n+ for dtype in jtu.dtypes.all_floating + jtu.dtypes.complex\n+ for lhs, rhs in [\n+ (np.array([np.inf], dtype=dtype), np.array([np.nan], dtype=dtype)),\n+ (np.array([-np.inf], dtype=dtype), np.array([np.nan], dtype=dtype))\n+ ]\n+)\n+\n_LAX_BINARY_ELEMENTWISE = (\nlax.add, lax.atan2, lax.div, lax.igamma, lax.igammac, lax.max, lax.min,\nlax.nextafter, lax.rem, lax.sub)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -383,6 +383,36 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\nexpect_tf_exceptions=True)\n+ @primitive_harness.parameterized(primitive_harness.lax_add_mul)\n+ def test_add_mul(self, harness: primitive_harness.Harness):\n+ expect_tf_exceptions = False\n+ dtype = harness.params[\"dtype\"]\n+ f_name = harness.params[\"f_jax\"].__name__\n+\n+ if dtype in [np.uint32, np.uint64]:\n+ # TODO(bchetioui): tf.math.multiply is not defined for the above types.\n+ expect_tf_exceptions = True\n+ elif dtype is np.uint16 and f_name == \"add\":\n+ # TODO(bchetioui): tf.math.add is defined for the same types as multiply,\n+ # except uint16.\n+ expect_tf_exceptions = True\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ expect_tf_exceptions=expect_tf_exceptions)\n+\n+ @primitive_harness.parameterized(primitive_harness.lax_min_max)\n+ def test_min_max(self, harness: primitive_harness.Harness):\n+ expect_tf_exceptions = False\n+ dtype = harness.params[\"dtype\"]\n+\n+ if dtype in [np.bool_, np.int8, np.uint16, np.uint32, np.uint64,\n+ np.complex64, np.complex128]:\n+ # TODO(bchetioui): tf.math.maximum and tf.math.minimum are not defined for\n+ # the above types.\n+ expect_tf_exceptions = True\n+\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ expect_tf_exceptions=expect_tf_exceptions)\n+\n@primitive_harness.parameterized(primitive_harness.lax_binary_elementwise)\ndef test_binary_elementwise(self, harness):\nlax_name, dtype = harness.params[\"lax_name\"], harness.params[\"dtype\"]\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Add testing for add/mul/min/max conversion. (#4142)
* [jax2tf] Add testing for add/mul/min/max conversion.
Only certain types are supported for each of the operations above.
This commit adds previously missing tests to make this explicit. |
260,298 | 27.08.2020 09:47:19 | -7,200 | 80114e51d643e945f14b66bd576208cd30d8e691 | Add a boolean to _check_shapelike to accept or reject shapes
* Add a boolean to _check_shapelike to accept or reject shapes
corresponding to arrays of 0 elements. (Fixes google/jax#3972).
* Added test for failures referenced in issue 3972. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -4748,8 +4748,10 @@ def _reduce_window_chooser_jvp_rule(prim, g, operand, *, window_dimensions,\ndef _common_reduce_window_shape_rule(operand, window_dimensions,\nwindow_strides, padding, base_dilation,\nwindow_dilation):\n- _check_shapelike(\"reduce_window\", \"window_dimensions\", window_dimensions)\n- _check_shapelike(\"reduce_window\", \"window_strides\", window_strides)\n+ _check_shapelike(\"reduce_window\", \"window_dimensions\", window_dimensions,\n+ non_zero_shape=True)\n+ _check_shapelike(\"reduce_window\", \"window_strides\", window_strides,\n+ non_zero_shape=True)\n_check_shapelike(\"reduce_window\", \"base_dilation\", base_dilation)\n_check_shapelike(\"reduce_window\", \"window_dilation\", window_dilation)\nif operand.ndim != len(window_dimensions):\n@@ -5730,7 +5732,7 @@ def conv_transpose_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\nreturn tuple(np.take(out_trans, np.argsort(out_perm)))\n-def _check_shapelike(fun_name, arg_name, obj):\n+def _check_shapelike(fun_name, arg_name, obj, non_zero_shape=False):\n\"\"\"Check that `obj` is a shape-like value (e.g. tuple of nonnegative ints).\"\"\"\nif not isinstance(obj, (tuple, list, np.ndarray)):\nmsg = \"{} {} must be of type tuple/list/ndarray, got {}.\"\n@@ -5747,9 +5749,11 @@ def _check_shapelike(fun_name, arg_name, obj):\nexcept TypeError:\nmsg = \"{} {} must have every element be an integer type, got {}.\"\nraise TypeError(msg.format(fun_name, arg_name, tuple(map(type, obj))))\n- if not (obj_arr >= 0).all():\n- msg = \"{} {} must have every element be nonnegative, got {}.\"\n- raise TypeError(msg.format(fun_name, arg_name, obj))\n+ lower_bound, bound_error = (\n+ (1, \"strictly positive\") if non_zero_shape else (0, \"nonnegative\"))\n+ if not (obj_arr >= lower_bound).all():\n+ msg = \"{} {} must have every element be {}, got {}.\"\n+ raise TypeError(msg.format(fun_name, arg_name, bound_error, obj))\ndef _dynamic_slice_indices(operand, start_indices):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1358,6 +1358,19 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype)]\nself._CompileAndCheck(fun, args_maker)\n+ def testReduceWindowFailures(self):\n+ def empty_window_test():\n+ return lax.reduce_window(np.ones((1,)), 0., lax.add, padding='VALID',\n+ window_dimensions=(0,), window_strides=(1,))\n+\n+ def zero_stride_test():\n+ return lax.reduce_window(np.ones((1,)), 0., lax.add, padding='VALID',\n+ window_dimensions=(1,), window_strides=(0,))\n+\n+ for failure_fun in [empty_window_test, zero_stride_test]:\n+ with self.assertRaisesRegex(TypeError, \"must have every element be\"):\n+ failure_fun()\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": (f\"_shape={shape}_windowdimensions={window_dimensions}\"\nf\"_basedilation={base_dilation}_windowdilation=\"\n"
}
] | Python | Apache License 2.0 | google/jax | Add a boolean to _check_shapelike to accept or reject shapes (#4108)
* Add a boolean to _check_shapelike to accept or reject shapes
corresponding to arrays of 0 elements. (Fixes google/jax#3972).
* Added test for failures referenced in issue 3972. |
260,298 | 27.08.2020 11:04:32 | -7,200 | 4d7396aa02f1d8f739b60e18ed75de4efcb4a427 | Implement a proper shape checking rule for scatter.
The implementation is based on the corresponding shape inference
code in `tensorflow/compiler/xla/service/shape_inference.cc`. The
tests added in `tests/lax_test.py` are similarly mirroring the
corresponding tests in tensorflow, with slight adaptations for
the particular setting of JAX. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3952,7 +3952,131 @@ def _scatter_dtype_rule(operand, scatter_indices, updates, **kwargs):\n_check_same_dtypes(\"scatter\", False, operand.dtype, updates.dtype)\nreturn dtypes.canonicalize_dtype(operand.dtype)\n-def _scatter_shape_rule(operand, scatter_indices, updates, **kwargs):\n+def _scatter_shape_rule(operand, scatter_indices, updates, *, update_jaxpr,\n+ update_consts, dimension_numbers, indices_are_sorted,\n+ unique_indices):\n+ \"\"\"Validates the well-formedness of the ``dimension_numbers`` argument to\n+ Scatter.\n+\n+ The code implements the checks based on the detailed operation semantics of\n+ XLA's `Scatter <https://www.tensorflow.org/xla/operation_semantics#scatter>`_\n+ operator and following the outline of the implementation of\n+ ShapeInference::InferScatterShape in TensorFlow.\n+ \"\"\"\n+ rank = lambda arr: len(arr.shape)\n+\n+ def _is_sorted(dims, name):\n+ for i in range(1, len(dims)):\n+ if dims[i] < dims[i - 1]:\n+ raise TypeError(f\"{name} in scatter op must be sorted; got {dims}\")\n+\n+ def _sorted_dims_in_range(dims, rank, name):\n+ if len(dims) == 0:\n+ return\n+ invalid_dim = None\n+ if dims[0] < 0:\n+ invalid_dim = dims[0]\n+ elif dims[-1] >= rank:\n+ invalid_dim = dims[-1]\n+ if invalid_dim:\n+ raise TypeError(f\"Invalid {name} set in scatter op; valid range is \"\n+ f\"[0, {rank}); got: {invalid_dim}.\")\n+\n+ def _no_duplicate_dims(dims, name):\n+ if len(set(dims)) != len(dims):\n+ raise TypeError(f\"{name} in scatter op must not repeat; got: {dims}.\")\n+\n+ update_window_dims = dimension_numbers.update_window_dims\n+ inserted_window_dims = dimension_numbers.inserted_window_dims\n+ scatter_dims_to_operand_dims = dimension_numbers.scatter_dims_to_operand_dims\n+ # Note: in JAX, index_vector_dim is always computed as below, cf. the\n+ # documentation of the ScatterDimensionNumbers class.\n+ index_vector_dim = rank(scatter_indices) - 1\n+\n+ # This case should never happen in JAX, due to the implicit construction of\n+ # index_vector_dim, but is included for completeness.\n+ if rank(scatter_indices) < index_vector_dim or index_vector_dim < 0:\n+ raise TypeError(f\"Scatter index leaf dimension must be within [0, \"\n+ f\"rank(scatter_indices) + 1). rank(scatter_indices) is \"\n+ f\"{rank(scatter_indices)} and scatter index leaf \"\n+ f\"dimension is {index_vector_dim}.\")\n+\n+ expanded_scatter_indices_shape = list(scatter_indices.shape)\n+ # This case should never happen in JAX, due to the implicit construction of\n+ # index_vector_dim, but is included for completeness.\n+ if len(expanded_scatter_indices_shape) == index_vector_dim:\n+ expanded_scatter_indices_shape.append(1)\n+\n+ expected_updates_rank = (len(expanded_scatter_indices_shape) - 1 +\n+ len(update_window_dims))\n+\n+ if rank(updates) != expected_updates_rank:\n+ raise TypeError(f\"Updates tensor must be of rank {expected_updates_rank}; \"\n+ f\"got {rank(updates)}.\")\n+\n+ # Validate update_window_dims\n+ _is_sorted(update_window_dims, \"update_window_dims\")\n+ _no_duplicate_dims(update_window_dims, \"update_window_dims\")\n+ _sorted_dims_in_range(update_window_dims, rank(updates), \"update_window_dims\")\n+\n+ # Validate inserted_window_dims\n+ _is_sorted(inserted_window_dims, \"inserted_window_dims\")\n+ _no_duplicate_dims(inserted_window_dims, \"inserted_window_dims\")\n+ _sorted_dims_in_range(inserted_window_dims, rank(operand),\n+ \"inserted_window_dims\")\n+\n+ # Validate window_size\n+ window_size = len(update_window_dims) + len(inserted_window_dims)\n+ if rank(operand) != window_size:\n+ raise TypeError(f\"Scatter op has window of size {window_size}; doesn't \"\n+ f\"match operand of rank {rank(operand)}.\")\n+\n+ # Validate scatter_dims_to_operand_dims\n+ if (len(scatter_dims_to_operand_dims) !=\n+ scatter_indices.shape[index_vector_dim]):\n+ raise TypeError(f\"Scatter op has {len(scatter_dims_to_operand_dims)} \"\n+ f\"elements in scatter_dims_to_operand_dims and the bound \"\n+ f\"of dimension index_vector_dim={index_vector_dim} of \"\n+ f\"scatter_indices is \"\n+ f\"{scatter_indices.shape[index_vector_dim]}. These two \"\n+ f\"numbers must be equal\")\n+\n+ for i in range(len(scatter_dims_to_operand_dims)):\n+ dim = scatter_dims_to_operand_dims[i]\n+ if dim < 0 or dim >= rank(operand):\n+ raise TypeError(f\"Invalid scatter_dims_to_operand_dims mapping; domain \"\n+ f\"is [0, {rank(operand)}), got: {i}->{dim}.\")\n+\n+ _no_duplicate_dims(scatter_dims_to_operand_dims,\n+ \"scatter_dims_to_operand_dims\")\n+\n+ max_update_slice_sizes = [operand.shape[i] for i in range(len(operand.shape))\n+ if not i in set(inserted_window_dims)]\n+\n+ for i in range(len(update_window_dims)):\n+ update_window_dim = update_window_dims[i]\n+ if updates.shape[update_window_dim] > max_update_slice_sizes[i]:\n+ raise TypeError(f\"Bounds of the window dimensions of updates must not \"\n+ f\"exceed the bounds of the corresponding dimensions of \"\n+ f\"operand. For dimension {update_window_dim}, updates \"\n+ f\"bound is {updates.shape[update_window_dim]}, operand \"\n+ f\"bound is {max_update_slice_sizes[i]}.\")\n+\n+ update_scatter_dims = [dim for dim in range(rank(updates)) if dim not in\n+ set(update_window_dims)]\n+\n+ scatter_dims_seen = 0\n+ for i in update_scatter_dims:\n+ if scatter_dims_seen == index_vector_dim:\n+ scatter_dims_seen += 1\n+ if updates.shape[i] != expanded_scatter_indices_shape[scatter_dims_seen]:\n+ raise TypeError(f\"Bounds of the scatter dimensions of updates must be \"\n+ f\"the same as the bounds of the corresponding dimensions \"\n+ f\"of scatter indices. For scatter dimension {i}, updates \"\n+ f\"bound is {updates.shape[i]}, scatter_indices bound is \"\n+ f\"{expanded_scatter_indices_shape[scatter_dims_seen]}.\")\n+ scatter_dims_seen += 1\n+\nreturn operand.shape\ndef _scatter_translation_rule(c, operand, scatter_indices, updates, *,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1774,6 +1774,95 @@ class LaxTest(jtu.JaxTestCase):\nfun = partial(lax.scatter, dimension_numbers=dnums)\nself._CompileAndCheck(fun, args_maker)\n+ # These tests are adapted from the corresponding tests in\n+ # tensorflow/compiler/xla/service/shape_inference_test.cc with slight\n+ # variations to account for the implicit setting of index_vector_dim in JAX.\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": f\"_{testcase_name}\", \"operand_shape\": operand_shape,\n+ \"scatter_indices\": scatter_indices, \"update_shape\": update_shape,\n+ \"dimension_numbers\": lax.ScatterDimensionNumbers(\n+ update_window_dims=update_window_dims,\n+ inserted_window_dims=inserted_window_dims,\n+ scatter_dims_to_operand_dims=scatter_dims_to_operand_dims),\n+ \"msg\": msg}\n+ for (testcase_name, operand_shape, scatter_indices, update_shape,\n+ update_window_dims, inserted_window_dims,\n+ scatter_dims_to_operand_dims, msg) in [\n+ (\"ScatterWithUpdatesBiggerThanInput\", (64, 48), np.zeros((32, 1)),\n+ (65, 32), (0,), (1,), (1,), \"Bounds of the window dimensions\"),\n+ (\"ScatterWithUpdatesBiggerThanInputV2\", (64, 48),\n+ np.zeros((32, 1)), (32, 49), (1,), (0,), (1,),\n+ \"Bounds of the window dimensions\"),\n+ (\"ScatterWithUpdatesNotMatchingIndices\", (64, 48),\n+ np.zeros((32, 1)), (64, 31), (0,), (1,), (1,),\n+ \"Bounds of the scatter dimensions\"),\n+ (\"ScatterWithUpdatesNotMatchingIndicesV2\", (64, 48),\n+ np.zeros((32, 1)), (31, 48), (1,), (0,), (1,),\n+ \"Bounds of the scatter dimensions\"),\n+ (\"ScatterNdWithUpdatesBiggerThanInput\", (64, 48),\n+ np.zeros((10, 9, 8, 7, 1)), (10, 9, 8, 7, 65), (4,), (1,),\n+ (0,), \"Bounds of the window dimensions\"),\n+ (\"ScatterNdWithUpdatesNotMatchingIndices\", (64, 48),\n+ np.zeros((10, 9, 8, 7, 1)), (9, 9, 8, 7, 64), (4,), (1,), (0,),\n+ \"Bounds of the scatter dimensions\"),\n+ (\"InvalidUpdates\", (50, 49, 48, 47, 46),\n+ np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4, 1),\n+ (4, 5, 6), (1, 2), (0, 1, 2, 3, 4),\n+ \"Updates tensor must be of rank 7; got 8.\"),\n+ (\"NonAscendingUpdateWindowDims\", (6, 5, 4, 3, 2),\n+ np.zeros((5, 4, 3, 2, 1)), (10, 9, 8, 7, 6, 5, 4, 3, 2),\n+ (4, 5, 6, 8, 7), (), (0, 1, 2, 3, 4),\n+ \"update_window_dims in scatter op must be sorted\"),\n+ (\"RepeatedUpdateWindowDims\", (6, 5, 4, 3, 2),\n+ np.zeros((5, 4, 3, 2, 1)), (10, 9, 8, 7, 6, 5, 4, 3, 2),\n+ (4, 5, 6, 7, 7), (), (0, 1, 2, 3, 4),\n+ \"update_window_dims in scatter op must not repeat\"),\n+ (\"OutOfBoundsUpdateWindowDims\", (6, 5, 4, 3, 2),\n+ np.zeros((5, 4, 3, 2, 1)), (10, 9, 8, 7, 6, 5, 4, 3, 2),\n+ (4, 5, 6, 7, 9), (), (0, 1, 2, 3, 4),\n+ \"Invalid update_window_dims set in scatter op\"),\n+ (\"NonAscendingInsertedWindowDims\", (50, 49, 48, 47, 46),\n+ np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n+ (4, 5, 6), (2, 1), (0, 1, 2, 3, 4),\n+ \"inserted_window_dims in scatter op must be sorted\"),\n+ (\"RepeatedInsertedWindowDims\", (50, 49, 48, 47, 46),\n+ np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n+ (4, 5, 6), (1, 1), (0, 1, 2, 3, 4),\n+ \"inserted_window_dims in scatter op must not repeat\"),\n+ (\"OutOfBoundsInsertedWindowDims\", (50, 49, 48, 47, 46),\n+ np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n+ (4, 5, 6), (1, 5), (0, 1, 2, 3, 4),\n+ \"Invalid inserted_window_dims set in scatter op\"),\n+ (\"MismatchingScatterDimsToOperandDims\", (50, 49, 48, 47, 46),\n+ np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n+ (4, 5, 6), (1, 2), (0, 1, 2, 3),\n+ \"Scatter op has 4 elements in scatter_dims_to_operand_dims and \"\n+ \"the bound of dimension index_vector_dim=4 of scatter_indices \"\n+ \"is 5. These two numbers must be equal\"),\n+ (\"OutOfBoundsScatterDimsToOperandDims\", (50, 49, 48, 47, 46),\n+ np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n+ (4, 5, 6), (1, 2), (0, 1, 2, 3, 10),\n+ \"Invalid scatter_dims_to_operand_dims mapping\"),\n+ (\"RepeatedValuesInScatterDimsToOperandDims\", (50, 49, 48, 47, 46),\n+ np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n+ (4, 5, 6), (1, 2), (0, 1, 2, 2, 3),\n+ \"scatter_dims_to_operand_dims in scatter op must not repeat\"),\n+ (\"InsufficientWindowDims\", (50, 49, 48, 47, 46),\n+ np.zeros((10, 9, 8, 7, 5)), (10, 9, 8, 7, 3, 2, 4),\n+ (4, 5, 6), (1,), (0, 1, 2, 3),\n+ \"Scatter op has window of size 4; doesn't match operand of \"\n+ \"rank 5.\")\n+ ]\n+ ))\n+ def testScatterShapeCheckingRule(self, operand_shape, scatter_indices,\n+ update_shape, dimension_numbers, msg):\n+\n+ operand = np.ones(operand_shape, dtype=np.int32)\n+ updates = np.ones(update_shape, dtype=np.int32)\n+\n+ with self.assertRaisesRegex(TypeError, msg):\n+ lax.scatter(operand, scatter_indices, updates, dimension_numbers)\n+\ndef testIssue831(self):\n# Tests the DeviceTuple constant handler\ndef f(x):\n"
}
] | Python | Apache License 2.0 | google/jax | Implement a proper shape checking rule for scatter. (#4144)
The implementation is based on the corresponding shape inference
code in `tensorflow/compiler/xla/service/shape_inference.cc`. The
tests added in `tests/lax_test.py` are similarly mirroring the
corresponding tests in tensorflow, with slight adaptations for
the particular setting of JAX. |
260,287 | 18.08.2020 09:14:38 | 0 | 7210d6f5d01ba7c64c7552628f37d66523feac9b | Add support for binding axis_name in gmap
This allows executing collectives over the gmapped axes. This requires
some extra manipulation of the gmapped jaxpr, since gmap exposes a
single logical axis name, but evaluates the program using multiple
"physical" axes.
This also fixes some bugs around handling `multiple_returns` in
vmap collective implementation. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1579,7 +1579,8 @@ def omnistaging_enabler() -> None:\ntry:\nyield\nfinally:\n- thread_local_state.trace_state.axis_env.pop()\n+ frame_ = thread_local_state.trace_state.axis_env.pop()\n+ assert frame is frame_ # Only runs if there was was no exception\ndef axis_frame(axis_name):\nframes = thread_local_state.trace_state.axis_env\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/general_map.py",
"new_path": "jax/experimental/general_map.py",
"diff": "@@ -30,10 +30,7 @@ from ..interpreters import partial_eval as pe\ndef gmap(fun: Callable, schedule, axis_name = None) -> Callable:\nwarn(\"gmap is an experimental feature and probably has bugs!\")\n_check_callable(fun)\n-\n- if axis_name is not None:\n- raise ValueError(\"gmap doesn't support binding axis names yet\")\n-\n+ binds_axis_name = axis_name is not None\naxis_name = _TempAxisName(fun) if axis_name is None else axis_name\n@wraps(fun)\n@@ -42,6 +39,7 @@ def gmap(fun: Callable, schedule, axis_name = None) -> Callable:\nargs_flat, in_tree = tree_flatten((args, kwargs))\nmapped_invars = (True,) * len(args_flat)\naxis_size = _mapped_axis_size(in_tree, args_flat, (0,) * len(args_flat), \"gmap\")\n+ parsed_schedule = _normalize_schedule(schedule, axis_size, binds_axis_name)\nfor arg in args_flat: _check_arg(arg)\nflat_fun, out_tree = flatten_fun(f, in_tree)\nouts = gmap_p.bind(\n@@ -49,7 +47,8 @@ def gmap(fun: Callable, schedule, axis_name = None) -> Callable:\naxis_name=axis_name,\naxis_size=axis_size,\nmapped_invars=mapped_invars,\n- schedule=tuple(schedule))\n+ schedule=parsed_schedule,\n+ binds_axis_name=binds_axis_name)\nreturn tree_unflatten(out_tree(), outs)\nreturn f_gmapped\n@@ -62,20 +61,10 @@ class LoopType(enum.Enum):\nLoop = namedtuple('Loop', ['type', 'size'])\n-def gmap_impl(fun: lu.WrappedFun, *args, axis_size, axis_name, mapped_invars, schedule):\n- avals = [core.raise_to_shaped(core.get_aval(arg)) for arg in args]\n- scheduled_fun = _apply_schedule(fun, axis_size, mapped_invars, schedule, *avals)\n- return scheduled_fun(*args)\n+def _normalize_schedule(schedule, axis_size, binds_axis_name):\n+ if not schedule:\n+ raise ValueError(\"gmap expects a non-empty schedule\")\n-def _parse_name(name):\n- if isinstance(name, LoopType):\n- return name\n- try:\n- return LoopType[name]\n- except KeyError as err:\n- raise ValueError(f\"Unrecognized loop type: {name}\") from err\n-\n-def _normalize_schedule(schedule, axis_size):\nscheduled = 1\nseen_none = False\nfor loop in schedule:\n@@ -92,31 +81,69 @@ def _normalize_schedule(schedule, axis_size):\nloop_type = _parse_name(loop[0])\nif loop_type is LoopType.vectorized and i < len(schedule) - 1:\nraise ValueError(\"vectorized loops can only appear as the last component of the schedule\")\n+ if loop_type is LoopType.sequential and binds_axis_name:\n+ raise ValueError(\"gmaps that bind a new axis name cannot have sequential components in the schedule\")\nnew_schedule.append(Loop(loop_type, loop[1] or unscheduled))\n- return new_schedule\n+ return tuple(new_schedule)\n+\n+def _parse_name(name):\n+ if isinstance(name, LoopType):\n+ return name\n+ try:\n+ return LoopType[name]\n+ except KeyError as err:\n+ raise ValueError(f\"Unrecognized loop type: {name}\") from err\n+\n+\n+def gmap_impl(fun: lu.WrappedFun, *args, axis_size, axis_name, binds_axis_name, mapped_invars, schedule):\n+ avals = [core.raise_to_shaped(core.get_aval(arg)) for arg in args]\n+ scheduled_fun = _apply_schedule(fun, axis_size, axis_name, binds_axis_name,\n+ mapped_invars, schedule, *avals)\n+ return scheduled_fun(*args)\n+\n+class _GMapSubaxis:\n+ def __init__(self, axis_name, index):\n+ self.axis_name = axis_name\n+ self.index = index\n+ def __repr__(self):\n+ return f'<subaxis {self.index} of {self.axis_name}>'\n+ def __hash__(self):\n+ return hash((self.axis_name, self.index))\n+ def __eq__(self, other):\n+ return (isinstance(other, _GMapSubaxis) and\n+ self.axis_name == other.axis_name and\n+ self.index == other.index)\n@lu.cache\n-def _apply_schedule(fun: lu.WrappedFun, axis_size, mapped_invars, schedule, *avals):\n+def _apply_schedule(fun: lu.WrappedFun,\n+ axis_size, full_axis_name, binds_axis_name,\n+ mapped_invars,\n+ schedule,\n+ *avals):\n+ assert all(mapped_invars)\nmapped_avals = [core.mapped_aval(axis_size, aval) if mapped else aval\nfor mapped, aval in zip(mapped_invars, avals)]\n+ with core.extend_axis_env(full_axis_name, axis_size, None):\njaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, mapped_avals)\n- schedule = _normalize_schedule(schedule, axis_size)\n- dim_sizes = tuple(loop.size for loop in schedule)\n+ axis_names = tuple(_GMapSubaxis(full_axis_name, i) for i in range(len(schedule)))\n+ if binds_axis_name:\n+ jaxpr = subst_axis_names(jaxpr, full_axis_name, axis_names)\nsched_fun = lambda *args: core.eval_jaxpr(jaxpr, consts, *args)\n-\n- if schedule[-1].type is LoopType.vectorized:\n- sched_fun = jax.vmap(sched_fun)\n- nonvector_schedule = schedule[:-1]\n- else:\n- nonvector_schedule = schedule\n- for (ltype, size) in nonvector_schedule[::-1]:\n- if ltype is LoopType.parallel:\n- sched_fun = jax.pmap(sched_fun)\n+ for (ltype, size), axis_name in list(zip(schedule, axis_names))[::-1]:\n+ if ltype is LoopType.vectorized:\n+ sched_fun = jax.vmap(sched_fun, axis_name=axis_name)\n+ elif ltype is LoopType.parallel:\n+ sched_fun = jax.pmap(sched_fun, axis_name=axis_name)\nelif ltype is LoopType.sequential:\n+ if binds_axis_name:\n+ raise NotImplementedError(\"gmaps with sequential components of the schedule don't support \"\n+ \"collectives yet. Please open a feature request!\")\n+ assert not binds_axis_name\nsched_fun = lambda *args, sched_fun=sched_fun: jax.lax.map(lambda xs: sched_fun(*xs), args)\n+ dim_sizes = tuple(loop.size for loop in schedule)\ndef sched_fun_wrapper(*args):\nsplit_args = [arg.reshape(dim_sizes + arg.shape[1:]) for arg in args]\nresults = sched_fun(*split_args)\n@@ -125,3 +152,19 @@ def _apply_schedule(fun: lu.WrappedFun, axis_size, mapped_invars, schedule, *ava\ngmap_p = core.MapPrimitive('gmap')\ngmap_p.def_impl(gmap_impl)\n+\n+\n+def subst_axis_names(jaxpr, replaced_name, axis_names):\n+ eqns = [subst_eqn_axis_names(eqn, replaced_name, axis_names) for eqn in jaxpr.eqns]\n+ return core.Jaxpr(jaxpr.constvars, jaxpr.invars, jaxpr.outvars, eqns)\n+\n+def subst_eqn_axis_names(eqn, replaced_name, axis_names):\n+ if isinstance(eqn.primitive, (core.CallPrimitive, core.MapPrimitive)):\n+ if eqn.params.get('axis_name', None) == replaced_name: # Check for shadowing\n+ return eqn\n+ new_call_jaxpr = subst_axis_names(eqn.params['call_jaxpr'], replaced_name, axis_names)\n+ return eqn._replace(params=dict(eqn.params, call_jaxpr=new_call_jaxpr))\n+ elif eqn.params.get('axis_name', None) == replaced_name:\n+ return eqn._replace(params=dict(eqn.params, axis_name=axis_names))\n+ else:\n+ return eqn\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -150,7 +150,9 @@ class BatchTrace(Trace):\nif len(axis_names) > 1:\nreturn split_axis(primitive, axis_name, tracers, params)\nvals_out, dims_out = collective_rules[primitive](vals_in, dims_in, frame.size, **params)\n- return map(partial(BatchTracer, self), vals_out, dims_out)\n+ results = map(partial(BatchTracer, self), vals_out, dims_out)\n+ print(results)\n+ return results if primitive.multiple_results else results[0]\n# TODO(mattjj,phawkins): if no rule implemented, could vmap-via-map here\nbatched_primitive = get_primitive_batcher(primitive)\nval_out, dim_out = batched_primitive(vals_in, dims_in, **params)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -326,12 +326,14 @@ def _split_axis_comm_assoc(primitive, split_name, args, params):\nsplit_params = dict(params, axis_name=split_name)\nremain_params = dict(params, axis_name=remaining_axes)\nsplit_result = primitive.bind(*args, **split_params)\n+ if not primitive.multiple_results:\n+ split_result = (split_result,)\nreturn primitive.bind(*split_result, **remain_params)\n# NB: This is only used for collectives that do not include the vmapped axis name,\n# which is why the rule is so simple. All other collectives go through split_axis.\ndef _collective_batcher(prim, args, dims, **params):\n- return prim.bind(*args, **params), dims\n+ return prim.bind(*args, **params), dims if prim.multiple_results else dims[0]\ndef _batched_reduction_collective(prim, if_mapped, if_unmapped,\nvals_in, dims_in, axis_size,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -984,12 +984,12 @@ class BatchingTest(jtu.JaxTestCase):\n\"seq\": seq}\nfor collective, seq in [(lax.psum, jnp.sum),\n(lax.pmean, jnp.mean),\n- (lambda x, n: lax.pmax(x, n)[0], jnp.max),\n- (lambda x, n: lax.pmin(x, n)[0], jnp.min)])\n+ (lambda x, n: lax.pmax(x, n), jnp.max),\n+ (lambda x, n: lax.pmin(x, n), jnp.min)])\n@skipIf(not jax.config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\ndef testCollective(self, collective, seq):\n- x = jnp.arange(1000).reshape((10, 10, 10))\n+ x = jnp.arange(64).reshape((4, 4, 4))\nself.assertAllClose(\nvmap(lambda x: x - collective(x, 'i'), axis_name='i')(x),\nx - seq(x, axis=0))\n@@ -1015,7 +1015,7 @@ class BatchingTest(jtu.JaxTestCase):\nperm_pairs = np.stack([np.arange(nelem), perm], axis=-1)\nrng.shuffle(perm_pairs)\nself.assertAllClose(\n- vmap(lambda x: x - lax.ppermute(x, 'i', perm_pairs)[0], axis_name='i')(x),\n+ vmap(lambda x: x - lax.ppermute(x, 'i', perm_pairs), axis_name='i')(x),\nx - x[perm])\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/gmap_test.py",
"new_path": "tests/gmap_test.py",
"diff": "@@ -27,8 +27,10 @@ from absl.testing import parameterized\nimport jax.numpy as jnp\nfrom jax import test_util as jtu\nfrom jax import vmap\n+from jax import lax\nfrom jax.experimental.general_map import gmap\nfrom jax.lib import xla_bridge\n+from jax.util import curry\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -58,17 +60,36 @@ def tearDownModule():\nxla_bridge.get_backend.cache_clear()\n-class GmapTest(jtu.JaxTestCase):\n+@curry\n+def skip_insufficient_devices(axis_size, fun):\n+ @functools.wraps(fun)\n+ def wrapper(*args, schedule, **kwargs):\n+ for loop, n in schedule:\n+ approx_n = axis_size if n is None else n\n+ if loop == 'parallel' and approx_n > xla_bridge.device_count():\n+ raise SkipTest(\"this test requires more XLA devices\")\n+ return fun(*args, schedule=schedule, **kwargs)\n+ return wrapper\n- @parameterized.named_parameters(\n- {\"testcase_name\": \"_\" + name, \"schedule\": schedule}\n- for name, schedule in [\n+@curry\n+def check_default_schedules(cond, fun):\n+ schedules = [\n('seq', [('sequential', None)]),\n('vec', [('vectorized', None)]),\n('par', [('parallel', None)]),\n('lim_vmap', [('sequential', None), ('vectorized', 2)]),\n('soft_pmap', [('parallel', 2), ('vectorized', None)])\n- ])\n+ ]\n+ schedules = [s for s in schedules if cond(s[1])]\n+ return parameterized.named_parameters(\n+ {\"testcase_name\": \"_\" + name, \"schedule\": schedule}\n+ for name, schedule in schedules)(fun)\n+\n+\n+class GmapTest(jtu.JaxTestCase):\n+\n+ @check_default_schedules(lambda _: True)\n+ @skip_insufficient_devices(8)\n@ignore_gmap_warning()\n@skipIf(not config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\n@@ -78,12 +99,30 @@ class GmapTest(jtu.JaxTestCase):\nx = jnp.arange(800).reshape((8, 10, 10))\n- for loop, n in schedule:\n- approx_n = x.shape[0] if n is None else n\n- if loop == 'parallel' and approx_n > xla_bridge.device_count():\n- raise SkipTest(\"this test requires more XLA devices\")\n+ self.assertAllClose(gmap(f, schedule)(x), vmap(f)(x))\n- self.assertAllClose(vmap(f)(x), gmap(f, schedule)(x))\n+ @check_default_schedules(lambda s: not any(c[0] == 'sequential' for c in s))\n+ @skip_insufficient_devices(8)\n+ @ignore_gmap_warning()\n+ @skipIf(not config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testAxisName(self, schedule):\n+ def f(x):\n+ return x - lax.psum(x, 'i')\n+ x = jnp.arange(8)\n+ self.assertAllClose(gmap(f, schedule, axis_name='i')(x),\n+ vmap(f, axis_name='i')(x))\n+\n+ @ignore_gmap_warning()\n+ @skipIf(not config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testAxisName2d(self):\n+ def f(x):\n+ return x - lax.psum(x, 'i') + lax.pmax(x, 'j')\n+ x = jnp.arange(8 * 8).reshape((8, 8))\n+ s = [('vectorized', None)]\n+ self.assertAllClose(gmap(gmap(f, s, axis_name='i'), s, axis_name='j')(x),\n+ vmap(vmap(f, axis_name='i'), axis_name='j')(x))\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add support for binding axis_name in gmap
This allows executing collectives over the gmapped axes. This requires
some extra manipulation of the gmapped jaxpr, since gmap exposes a
single logical axis name, but evaluates the program using multiple
"physical" axes.
This also fixes some bugs around handling `multiple_returns` in
vmap collective implementation. |
260,298 | 28.08.2020 16:27:32 | -7,200 | 04f9ff7ff4ddb08649e94542900cd2c14755ca06 | Addition of one more conclusive polynomial comparison case.
* Addition of one more conclusive polynomial comparison case.
In the case when the difference between two polynomials is a
constant, it is possible to conclusively compare them. This commit
adds such a case to masking.Poly.__ge__.
* Added a few relevant tests in tests.masking_test.test_Poly_compare. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -200,6 +200,10 @@ class Poly(dict):\nreturn False # See above.\nelif self == other:\nreturn True\n+ else:\n+ diff = self - other\n+ if diff.is_constant:\n+ return int(diff) >= 0\nraise ValueError('Polynomials comparison \"{} >= {}\" is inconclusive.'\n.format(self, other))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -106,6 +106,10 @@ class PolyTest(jtu.JaxTestCase):\nassert 0 < poly\nassert constant_poly(3) >= 1\nassert constant_poly(3) > 1\n+ assert poly >= poly\n+ assert poly >= poly - 1\n+ assert poly < poly + 1\n+\nself.assertRaisesRegex(ValueError, \"\", lambda: poly >= 2)\nself.assertRaisesRegex(ValueError, \"\", lambda: poly > 1)\n"
}
] | Python | Apache License 2.0 | google/jax | Addition of one more conclusive polynomial comparison case. (#4167)
* Addition of one more conclusive polynomial comparison case.
In the case when the difference between two polynomials is a
constant, it is possible to conclusively compare them. This commit
adds such a case to masking.Poly.__ge__.
* Added a few relevant tests in tests.masking_test.test_Poly_compare. |
260,287 | 28.08.2020 20:03:39 | -7,200 | a33f4dd8c8853a988e97b57542627869533a2ee7 | Add support for axis_index inside vmap
Also, reorganize the code to put all `axis_index` related functions in
`lax_parallel.py`, next to all other parallel collectives. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -645,7 +645,7 @@ class TraceStack:\nreturn new\nclass Sublevel(int): pass\n-AxisEnvFrame = namedtuple('AxisEnvFrame', ['name', 'size', 'tag'])\n+AxisEnvFrame = namedtuple('AxisEnvFrame', ['name', 'size', 'master_trace'])\nclass TraceState:\n@@ -1436,7 +1436,7 @@ axis_frame = None\ndef omnistaging_enabler() -> None:\nglobal thread_local_state, call_bind, find_top_trace, initial_style_staging, \\\nnew_master, reset_trace_state, extend_axis_env, axis_frame, \\\n- axis_index, new_base_master, eval_context, \\\n+ new_base_master, eval_context, \\\nTraceStack, TraceState\ndel initial_style_staging\n@@ -1573,8 +1573,8 @@ def omnistaging_enabler() -> None:\nPrimitive.bind = bind\n@contextmanager\n- def extend_axis_env(axis_name, size: int, tag: Any):\n- frame = AxisEnvFrame(axis_name, size, tag)\n+ def extend_axis_env(axis_name, size: int, master_trace: Optional[MasterTrace]):\n+ frame = AxisEnvFrame(axis_name, size, master_trace)\nthread_local_state.trace_state.axis_env.append(frame)\ntry:\nyield\n@@ -1589,45 +1589,3 @@ def omnistaging_enabler() -> None:\nreturn frame\nelse:\nraise NameError(\"unbound axis name: {}\".format(axis_name))\n-\n- def axis_index(axis_name):\n- \"\"\"Return the index along the mapped axis ``axis_name``.\n-\n- Args:\n- axis_name: hashable Python object used to name the mapped axis.\n-\n- Returns:\n- An integer representing the index.\n-\n- For example, with 8 XLA devices available:\n-\n- >>> from functools import partial\n- >>> @partial(jax.pmap, axis_name='i')\n- ... def f(_):\n- ... return lax.axis_index('i')\n- ...\n- >>> f(np.zeros(4))\n- ShardedDeviceArray([0, 1, 2, 3], dtype=int32)\n- >>> f(np.zeros(8))\n- ShardedDeviceArray([0, 1, 2, 3, 4, 5, 6, 7], dtype=int32)\n- >>> @partial(jax.pmap, axis_name='i')\n- ... @partial(jax.pmap, axis_name='j')\n- ... def f(_):\n- ... return lax.axis_index('i'), lax.axis_index('j')\n- ...\n- >>> x, y = f(np.zeros((4, 2)))\n- >>> print(x)\n- [[0 0]\n- [1 1]\n- [2 2]\n- [3 3]]\n- >>> print(y)\n- [[0 1]\n- [0 1]\n- [0 1]\n- [0 1]]\n- \"\"\"\n- return axis_index_p.bind(axis_name=axis_name)\n-\n-\n-axis_index_p = Primitive('axis_index')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -408,8 +408,9 @@ tf_not_yet_impl = [\n# Not high priority?\nlax.after_all_p, lax.all_to_all_p, lax.create_token_p, lax.cummax_p, lax.cummin_p,\nlax.infeed_p, lax.outfeed_p, lax.pmax_p, lax.pmin_p, lax.ppermute_p, lax.psum_p,\n+ lax.axis_index_p,\n- pxla.xla_pmap_p, pxla.axis_index_p,\n+ pxla.xla_pmap_p,\n]\ntry:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -142,7 +142,7 @@ class BatchTrace(Trace):\naxis_names = (axis_names,)\nfor i, axis_name in enumerate(axis_names):\nframe = core.axis_frame(axis_name)\n- if frame.tag is not self.master:\n+ if frame.master_trace is not self.master:\ncontinue\n# We run the split_axis rule with tracers, which is supposed to never\n# mix this axis name with another one. We will handle any invocations\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -43,9 +43,8 @@ from ..config import flags, config\nfrom .. import core\nfrom .. import linear_util as lu\nfrom .. import lazy\n-from .. import source_info_util\nfrom ..abstract_arrays import ConcreteArray, ShapedArray, array_types\n-from ..core import Var, Literal, axis_index_p\n+from ..core import Var, Literal\nfrom ..util import (partial, unzip2, unzip3, prod, safe_map, safe_zip,\nextend_name_stack, wrap_name)\nfrom ..lib import xla_bridge as xb\n@@ -416,79 +415,6 @@ def apply_parallel_primitive(prim, *args, **params):\nparallel_pure_rules: Dict[core.Primitive, Callable] = {}\n-def axis_index(axis_name):\n- \"\"\"Return the index along the pmapped axis ``axis_name``.\n-\n- On multi-host platforms, returns unique indices on each host, in line with the\n- conceptual model of a multi-host pmap running over a single array sharded\n- across hosts. See the \"Multi-host platforms\" section of the :func:`jax.pmap`\n- documentation.\n-\n- Args:\n- axis_name: hashable Python object used to name the pmapped axis (see the\n- :func:`jax.pmap` documentation for more details).\n-\n- Returns:\n- An integer representing the index.\n-\n- For example, with 8 XLA devices available:\n-\n- >>> from functools import partial\n- >>> @partial(pmap, axis_name='i')\n- ... def f(_):\n- ... return lax.axis_index('i')\n- ...\n- >>> f(np.zeros(4))\n- ShardedDeviceArray([0, 1, 2, 3], dtype=int32)\n- >>> f(np.zeros(8))\n- ShardedDeviceArray([0, 1, 2, 3, 4, 5, 6, 7], dtype=int32)\n- >>> @partial(pmap, axis_name='i')\n- ... @partial(pmap, axis_name='j')\n- ... def f(_):\n- ... return lax.axis_index('i'), lax.axis_index('j')\n- ...\n- >>> x, y = f(np.zeros((4, 2)))\n- >>> print(x)\n- [[0 0]\n- [1 1]\n- [2 2]\n- [3 3]]\n- >>> print(y)\n- [[0 1]\n- [0 1]\n- [0 1]\n- [0 1]]\n- \"\"\"\n- return axis_index_p.bind(axis_name=axis_name)\n-\n-def _axis_index_bind(*, axis_name):\n- dynamic_axis_env = _thread_local_state.dynamic_axis_env\n- frame = dynamic_axis_env[axis_name]\n- sizes = dynamic_axis_env.sizes[:dynamic_axis_env.index(frame)+1]\n- nreps = dynamic_axis_env.nreps\n- trace = frame.pmap_trace\n-\n- out_aval = ShapedArray((), np.int32)\n- out_tracer = pe.JaxprTracer(trace, pe.PartialVal.unknown(out_aval), None)\n- eqn = pe.new_eqn_recipe([], [out_tracer], axis_index_p,\n- dict(nreps=nreps, sizes=sizes, axis_name=axis_name),\n- source_info_util.current())\n- out_tracer.recipe = eqn\n-\n- return out_tracer\n-\n-def _axis_index_translation_rule(c, nreps, sizes, axis_name):\n- div = xb.constant(c, np.array(nreps // prod(sizes), dtype=np.uint32))\n- mod = xb.constant(c, np.array(sizes[-1], dtype=np.uint32))\n- unsigned_index = xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)\n- return xops.ConvertElementType(unsigned_index, xb.dtype_to_etype(np.int32))\n-\n-axis_index_p.def_custom_bind(_axis_index_bind)\n-axis_index_p.def_abstract_eval(\n- lambda *args, **params: ShapedArray((), np.int32))\n-xla.translations[axis_index_p] = _axis_index_translation_rule\n-\n-\n### lazy device-memory persistence and result handling\nclass ShardedDeviceArray(xla.DeviceArray):\n@@ -1222,7 +1148,7 @@ def _soft_pmap_callable(fun, axis_name, axis_size, mapped_invars, *avals):\nraise NotImplementedError(msg)\njaxpr, _, consts = _soft_pmap_jaxpr(jaxpr, consts, mapped_invars,\n- axis_name, chunk_size)\n+ axis_name, axis_size, chunk_size)\njaxpr_replicas = xla.jaxpr_replicas(jaxpr)\nif jaxpr_replicas != 1: raise NotImplementedError\n@@ -1260,10 +1186,11 @@ def _soft_pmap_callable(fun, axis_name, axis_size, mapped_invars, *avals):\nreturn partial(execute_replicated, compiled, backend, handle_args, handle_outs)\n-def _soft_pmap_jaxpr(jaxpr, consts, mapped_invars, axis_name, chunk_size):\n+def _soft_pmap_jaxpr(jaxpr, consts, mapped_invars, axis_name, axis_size, chunk_size):\nfun = partial(_soft_pmap_interp, chunk_size, jaxpr, consts, mapped_invars)\nin_avals = [core.unmapped_aval(chunk_size, v.aval) if m else v.aval\nfor v, m in zip(jaxpr.invars, mapped_invars)]\n+ with core.extend_axis_env(axis_name, axis_size, None):\nreturn pe.trace_to_jaxpr_dynamic(lu.wrap_init(fun), in_avals)\ndef _soft_pmap_interp(chunk_size, jaxpr, consts, mapped_invars, *args):\n@@ -1351,11 +1278,6 @@ soft_pmap_p.def_impl(soft_pmap_impl)\nsoft_pmap_rules: Dict[core.Primitive, Callable] = {}\n-def _axis_index_soft_pmap_rule(vals, mapped, chunk_size, *, axis_name):\n- assert not vals and not mapped\n- idx = core.axis_index(axis_name) # type: ignore\n- return idx * chunk_size + np.arange(chunk_size), True\n-\ndef deleted_with_omnistaging(*a, **k):\nassert False, \"Should be deleted\"\n@@ -1363,13 +1285,11 @@ def deleted_with_omnistaging(*a, **k):\ndef omnistaging_enable() -> None:\nglobal DynamicAxisEnvFrame, DynamicAxisEnv, _ThreadLocalState, \\\n_thread_local_state, extend_dynamic_axis_env, unmapped_device_count, \\\n- axis_index, _axis_index_bind, _axis_index_translation_rule, \\\napply_parallel_primitive, parallel_pure_rules, \\\n_pvals_to_results_handler, _pval_to_result_handler, replicate, \\\n- avals_to_results_handler, axis_index\n+ avals_to_results_handler\ndel DynamicAxisEnvFrame, DynamicAxisEnv, _ThreadLocalState, \\\n_thread_local_state, extend_dynamic_axis_env, unmapped_device_count, \\\n- axis_index, _axis_index_bind, _axis_index_translation_rule, \\\n_pvals_to_results_handler, _pval_to_result_handler, replicate\napply_parallel_primitive = deleted_with_omnistaging\n@@ -1400,11 +1320,3 @@ def omnistaging_enable() -> None:\nfor buf in bufs)\nreturn [h(bufs) for h, bufs in zip(handlers, buffers)]\nreturn handler\n-\n- soft_pmap_rules[axis_index_p] = _axis_index_soft_pmap_rule # type: ignore\n-\n- axis_index_p.bind = partial(core.Primitive.bind, axis_index_p) # type: ignore\n- axis_index_p.def_abstract_eval(lambda *, axis_name: ShapedArray((), np.int32))\n- del xla.translations[axis_index_p]\n-\n- from ..core import axis_index # type: ignore # noqa: F401\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1293,11 +1293,3 @@ pe.staged_out_calls.add(xla_call_p)\ndef omnistaging_enabler() -> None:\nglobal _pval_to_result_handler\ndel _pval_to_result_handler\n-\n- def _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\n- div = xb.constant(c, np.array(axis_env.nreps // prod(axis_env.sizes),\n- dtype=np.uint32))\n- mod = xb.constant(c, np.array(axis_env.sizes[-1], dtype=np.uint32))\n- unsigned_index = xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)\n- return xops.ConvertElementType(unsigned_index, xb.dtype_to_etype(np.int32))\n- parallel_translations[core.axis_index_p] = _axis_index_translation_rule # type: ignore\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/__init__.py",
"new_path": "jax/lax/__init__.py",
"diff": "@@ -322,6 +322,7 @@ from .lax_parallel import (\nall_to_all,\nall_to_all_p,\naxis_index,\n+ axis_index_p,\npmax,\npmax_p,\npmean,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -22,23 +22,22 @@ import numpy as np\nfrom jax import core\nfrom jax import dtypes\nfrom jax import tree_util\n+from jax import source_info_util\nfrom jax.lax import lax\nfrom jax.abstract_arrays import ShapedArray, raise_to_shaped\nfrom jax.interpreters import ad\nfrom jax.interpreters import xla\nfrom jax.interpreters import pxla\nfrom jax.interpreters import batching\n+from jax.interpreters import partial_eval as pe\nfrom jax.util import partial, unzip2, prod\nfrom jax.lib import xla_client as xc\n+from jax.lib import xla_bridge as xb\nfrom jax.config import config\nfrom jax.numpy import lax_numpy\n-from jax.interpreters.pxla import axis_index\n-\nxops = xc.ops\n-pxla.multi_host_supported_collectives.add(core.axis_index_p)\n-\n### parallel traceables\n@@ -289,6 +288,46 @@ def all_to_all(x, axis_name, split_axis, concat_axis):\naxis_name=axis_name)\nreturn tree_util.tree_map(bind, x)\n+def axis_index(axis_name):\n+ \"\"\"Return the index along the mapped axis ``axis_name``.\n+\n+ Args:\n+ axis_name: hashable Python object used to name the mapped axis.\n+\n+ Returns:\n+ An integer representing the index.\n+\n+ For example, with 8 XLA devices available:\n+\n+ >>> from functools import partial\n+ >>> @partial(jax.pmap, axis_name='i')\n+ ... def f(_):\n+ ... return lax.axis_index('i')\n+ ...\n+ >>> f(np.zeros(4))\n+ ShardedDeviceArray([0, 1, 2, 3], dtype=int32)\n+ >>> f(np.zeros(8))\n+ ShardedDeviceArray([0, 1, 2, 3, 4, 5, 6, 7], dtype=int32)\n+ >>> @partial(jax.pmap, axis_name='i')\n+ ... @partial(jax.pmap, axis_name='j')\n+ ... def f(_):\n+ ... return lax.axis_index('i'), lax.axis_index('j')\n+ ...\n+ >>> x, y = f(np.zeros((4, 2)))\n+ >>> print(x)\n+ [[0 0]\n+ [1 1]\n+ [2 2]\n+ [3 3]]\n+ >>> print(y)\n+ [[0 1]\n+ [0 1]\n+ [0 1]\n+ [0 1]]\n+ \"\"\"\n+ return axis_index_p.bind(axis_name=axis_name)\n+\n+\n### parallel primitives\ndef _allreduce_soft_pmap_rule(prim, reducer, vals, mapped, chunk_size,\n@@ -581,6 +620,41 @@ def all_gather(x, axis_name):\nreturn _allgather(x, 0, psum(1, axis_name), axis_name)\n+def _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\n+ div = xb.constant(c, np.array(axis_env.nreps // prod(axis_env.sizes),\n+ dtype=np.uint32))\n+ mod = xb.constant(c, np.array(axis_env.sizes[-1], dtype=np.uint32))\n+ unsigned_index = xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)\n+ return xops.ConvertElementType(unsigned_index, xb.dtype_to_etype(np.int32))\n+\n+def _axis_index_bind(*, axis_name):\n+ dynamic_axis_env = pxla._thread_local_state.dynamic_axis_env\n+ frame = dynamic_axis_env[axis_name]\n+ trace = frame.pmap_trace\n+\n+ out_aval = ShapedArray((), np.int32)\n+ out_tracer = pe.JaxprTracer(trace, pe.PartialVal.unknown(out_aval), None)\n+ eqn = pe.new_eqn_recipe([], [out_tracer], axis_index_p,\n+ dict(axis_name=axis_name),\n+ source_info_util.current())\n+ out_tracer.recipe = eqn\n+\n+ return out_tracer\n+\n+def _axis_index_soft_pmap_rule(vals, mapped, chunk_size, *, axis_name):\n+ assert not vals and not mapped\n+ idx = axis_index(axis_name) # type: ignore\n+ return idx * chunk_size + np.arange(chunk_size), True\n+\n+axis_index_p = core.Primitive('axis_index')\n+xla.parallel_translations[axis_index_p] = _axis_index_translation_rule\n+pxla.soft_pmap_rules[axis_index_p] = _axis_index_soft_pmap_rule # type: ignore\n+axis_index_p.def_custom_bind(_axis_index_bind)\n+axis_index_p.def_abstract_eval(\n+ lambda *args, **params: ShapedArray((), np.int32))\n+pxla.multi_host_supported_collectives.add(axis_index_p)\n+\n+\n@config.register_omnistaging_enabler\ndef omnistaging_enabler() -> None:\n# We set a special bind rule for psum so that psum(1, 'i') can be evaluated at\n@@ -600,3 +674,21 @@ def omnistaging_enabler() -> None:\nif psum_p in pxla.parallel_pure_rules:\ndel pxla.parallel_pure_rules[psum_p]\n+\n+ # Axis index doesn't get any arguments, so that the default bind would have no\n+ # way to call into a data-dependency based trace such as vmap. Each trace that\n+ # wants to bind an axis name has to additionally implement `process_axis_index`\n+ # and put its master trace on the axis env stack.\n+ def _axis_index_bind(*, axis_name):\n+ frame = core.axis_frame(axis_name)\n+ if frame.master_trace is not None:\n+ trace = frame.master_trace.trace_type(frame.master_trace, core.cur_sublevel())\n+ return trace.process_axis_index(frame)\n+ return core.Primitive.bind(axis_index_p, axis_name=axis_name)\n+\n+ axis_index_p.def_custom_bind(_axis_index_bind)\n+\n+ def process_axis_index(self, frame):\n+ return batching.BatchTracer(self, lax_numpy.arange(frame.size, dtype=np.int32), 0)\n+\n+ batching.BatchTrace.process_axis_index = process_axis_index\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -1004,7 +1004,7 @@ class BatchingTest(jtu.JaxTestCase):\n@skipIf(not jax.config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\n- def testPpermute(self):\n+ def testPPermute(self):\nnelem = 10\nntests = 10\nx = np.arange(nelem)\n@@ -1018,7 +1018,6 @@ class BatchingTest(jtu.JaxTestCase):\nvmap(lambda x: x - lax.ppermute(x, 'i', perm_pairs), axis_name='i')(x),\nx - x[perm])\n-\ndef testNegativeAxes(self):\nx = np.arange(3*4*5).reshape(3, 4, 5)\nself.assertAllClose(jax.vmap(jnp.sum, in_axes=-3)(x),\n@@ -1050,6 +1049,14 @@ class BatchingTest(jtu.JaxTestCase):\njax.vmap(lambda *xs: xs, in_axes=(0, None), out_axes=(0, -2))(\nnp.arange(5), 7)\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testAxisIndex(self):\n+ x = np.arange(10)\n+ self.assertAllClose(\n+ vmap(lambda x: x - lax.axis_index('i'), axis_name='i')(x),\n+ x - np.arange(x.shape[0]))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add support for axis_index inside vmap (#4168)
Also, reorganize the code to put all `axis_index` related functions in
`lax_parallel.py`, next to all other parallel collectives. |
260,411 | 30.08.2020 12:38:14 | -10,800 | 634c6259df26484a7e716db47105c589057d3580 | More renaming of master to main in JAX internals | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -645,7 +645,7 @@ class TraceStack:\nreturn new\nclass Sublevel(int): pass\n-AxisEnvFrame = namedtuple('AxisEnvFrame', ['name', 'size', 'master_trace'])\n+AxisEnvFrame = namedtuple('AxisEnvFrame', ['name', 'size', 'main_trace'])\nclass TraceState:\n@@ -1435,7 +1435,7 @@ axis_frame = None\n@no_type_check\ndef omnistaging_enabler() -> None:\nglobal thread_local_state, call_bind, find_top_trace, initial_style_staging, \\\n- new_master, reset_trace_state, extend_axis_env, axis_frame, \\\n+ new_main, reset_trace_state, extend_axis_env, axis_frame, \\\nnew_base_main, eval_context, \\\nTraceStack, TraceState\ndel initial_style_staging\n@@ -1573,8 +1573,8 @@ def omnistaging_enabler() -> None:\nPrimitive.bind = bind\n@contextmanager\n- def extend_axis_env(axis_name, size: int, master_trace: Optional[MasterTrace]):\n- frame = AxisEnvFrame(axis_name, size, master_trace)\n+ def extend_axis_env(axis_name, size: int, main_trace: Optional[MainTrace]):\n+ frame = AxisEnvFrame(axis_name, size, main_trace)\nthread_local_state.trace_state.axis_env.append(frame)\ntry:\nyield\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/callback.py",
"new_path": "jax/experimental/callback.py",
"diff": "@@ -93,8 +93,8 @@ def callback_fun(fun : lu.WrappedFun, in_vals, callback, strip_calls):\nreturn fun.call_wrapped(*in_vals)\n@lu.transformation\n-def callback_subtrace(master, *in_vals, **params):\n- trace = CallbackTrace(master, core.cur_sublevel())\n+def callback_subtrace(main, *in_vals, **params):\n+ trace = CallbackTrace(main, core.cur_sublevel())\nin_tracers = [CallbackTracer(trace, val) for val in in_vals]\nouts = yield in_tracers, params\nout_tracers = map(trace.full_raise, outs)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/doubledouble.py",
"new_path": "jax/experimental/doubledouble.py",
"diff": "@@ -87,8 +87,8 @@ class DoublingTrace(core.Trace):\n@lu.transformation\n-def doubling_subtrace(master, heads, tails):\n- trace = DoublingTrace(master, core.cur_sublevel())\n+def doubling_subtrace(main, heads, tails):\n+ trace = DoublingTrace(main, core.cur_sublevel())\nin_tracers = [DoublingTracer(trace, h, t) if t is not None else h\nfor h, t in zip(heads, tails)]\nans = yield in_tracers, {}\n@@ -109,8 +109,8 @@ def screen_nones(num_heads, in_tree_def, *heads_and_tails):\n@lu.transformation\ndef doubling_transform(*args):\n- with core.new_main(DoublingTrace) as master:\n- trace = DoublingTrace(master, core.cur_sublevel())\n+ with core.new_main(DoublingTrace) as main:\n+ trace = DoublingTrace(main, core.cur_sublevel())\nin_tracers = [DoublingTracer(trace, head, tail) for head, tail in args]\noutputs = yield in_tracers, {}\nif isinstance(outputs, Sequence):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -212,16 +212,16 @@ def convert(fun, with_gradient=False):\ndef _interpret_fun(fun: lu.WrappedFun,\nin_vals: Sequence[TfValOrUnit]) -> Sequence[TfValOrUnit]:\n- with core.new_main(TensorFlowTrace) as master:\n- fun = _interpret_subtrace(fun, master)\n+ with core.new_main(TensorFlowTrace) as main:\n+ fun = _interpret_subtrace(fun, main)\nout_vals: Sequence[TfValOrUnit] = fun.call_wrapped(*in_vals)\n- del master\n+ del main\nreturn out_vals\n@lu.transformation\n-def _interpret_subtrace(master: core.MainTrace, *in_vals: TfValOrUnit):\n- trace = TensorFlowTrace(master, core.cur_sublevel())\n+def _interpret_subtrace(main: core.MainTrace, *in_vals: TfValOrUnit):\n+ trace = TensorFlowTrace(main, core.cur_sublevel())\nin_tracers = tuple(TensorFlowTracer(trace, val) for val in in_vals)\nouts = yield in_tracers, {} # type: Sequence[TfValOrUnit]\nout_tracers: Iterable[TensorFlowTracer] = map(trace.full_raise, outs) # type: ignore\n@@ -295,7 +295,7 @@ class TensorFlowTrace(core.Trace):\nreturn TensorFlowTracer(self, val)\ndef lift(self, val: core.Tracer):\n- \"\"\"Lifts a core.Tracer from a lower-level master into the TensorFlowTrace.\"\"\"\n+ \"\"\"Lifts a core.Tracer from a lower-level main into the TensorFlowTrace.\"\"\"\n# TODO(necula): this should never be needed\nreturn TensorFlowTracer(self, val)\n@@ -342,9 +342,9 @@ class TensorFlowTrace(core.Trace):\n# (out_tracers) include TensorFlowTracer that were not passed through\n# its arguments (captured from the environment).\nvals = tuple(t.val for t in out_tracers)\n- master = self.main\n+ main = self.main\ndef todo(vals: Sequence[TfValOrUnit]):\n- trace = TensorFlowTrace(master, core.cur_sublevel())\n+ trace = TensorFlowTrace(main, core.cur_sublevel())\nreturn map(functools.partial(TensorFlowTracer, trace), vals)\nreturn vals, todo\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -68,8 +68,8 @@ def jet_fun(order, primals, series):\nyield out_primals, out_terms\n@lu.transformation\n-def jet_subtrace(master, primals, series):\n- trace = JetTrace(master, core.cur_sublevel())\n+def jet_subtrace(main, primals, series):\n+ trace = JetTrace(main, core.cur_sublevel())\nin_tracers = map(partial(JetTracer, trace), primals, series)\nans = yield in_tracers, {}\nout_tracers = map(trace.full_raise, ans)\n@@ -145,10 +145,10 @@ class JetTrace(core.Trace):\nprimals, series = unzip2((t.primal, t.terms) for t in out_tracers)\nout, treedef = tree_flatten((primals, series))\ndel primals, series\n- master = self.main\n+ main = self.main\ndef todo(x):\nprimals, series = tree_unflatten(treedef, x)\n- trace = JetTrace(master, core.cur_sublevel())\n+ trace = JetTrace(main, core.cur_sublevel())\nreturn map(partial(JetTracer, trace), primals, series)\nreturn out, todo\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/loops.py",
"new_path": "jax/experimental/loops.py",
"diff": "@@ -280,16 +280,16 @@ class Scope(object):\n# TODO: This follows the __enter__ part of core.new_main.\nif config.omnistaging_enabled:\nlevel = core.thread_local_state.trace_state.trace_stack.next_level()\n- master = core.MainTrace(level, pe.JaxprTrace)\n- core.thread_local_state.trace_state.trace_stack.push(master)\n+ main = core.MainTrace(level, pe.JaxprTrace)\n+ core.thread_local_state.trace_state.trace_stack.push(main)\nself._count_subtraces += 1\n- return pe.JaxprTrace(master, core.cur_sublevel())\n+ return pe.JaxprTrace(main, core.cur_sublevel())\nelse:\nlevel = core.thread_local_state.trace_state.trace_stack.next_level(False)\n- master = core.MainTrace(level, pe.JaxprTrace)\n- core.thread_local_state.trace_state.trace_stack.push(master, False)\n+ main = core.MainTrace(level, pe.JaxprTrace)\n+ core.thread_local_state.trace_state.trace_stack.push(main, False)\nself._count_subtraces += 1\n- return pe.JaxprTrace(master, core.cur_sublevel())\n+ return pe.JaxprTrace(main, core.cur_sublevel())\ndef end_subtrace(self):\n# TODO: This follows the __exit__ part of core.new_main\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -46,9 +46,9 @@ def jvp(fun: lu.WrappedFun, has_aux=False, instantiate=True) -> Any:\n@lu.transformation\ndef jvpfun(instantiate, primals, tangents):\n- with core.new_main(JVPTrace) as master:\n- out_primals, out_tangents = yield (master, primals, tangents), {}\n- del master\n+ with core.new_main(JVPTrace) as main:\n+ out_primals, out_tangents = yield (main, primals, tangents), {}\n+ del main\nif type(instantiate) is bool:\ninstantiate = [instantiate] * len(out_tangents)\nout_tangents = [instantiate_zeros(t) if inst else t for t, inst\n@@ -56,8 +56,8 @@ def jvpfun(instantiate, primals, tangents):\nyield out_primals, out_tangents\n@lu.transformation\n-def jvp_subtrace(master, primals, tangents):\n- trace = JVPTrace(master, core.cur_sublevel())\n+def jvp_subtrace(main, primals, tangents):\n+ trace = JVPTrace(main, core.cur_sublevel())\nfor x in list(primals) + list(tangents):\nif isinstance(x, Tracer):\nassert x._trace.level < trace.level\n@@ -69,8 +69,8 @@ def jvp_subtrace(master, primals, tangents):\nfor out_tracer in out_tracers])\n@lu.transformation_with_aux\n-def jvp_subtrace_aux(master, primals, tangents):\n- trace = JVPTrace(master, core.cur_sublevel())\n+def jvp_subtrace_aux(main, primals, tangents):\n+ trace = JVPTrace(main, core.cur_sublevel())\nfor x in list(primals) + list(tangents):\nif isinstance(x, Tracer):\nassert x._trace.level < trace.level\n@@ -280,10 +280,10 @@ class JVPTrace(Trace):\nprimals, tangents = unzip2((t.primal, t.tangent) for t in out_tracers)\nout, treedef = tree_flatten((primals, tangents))\ndel primals, tangents\n- master = self.main\n+ main = self.main\ndef todo(x):\nprimals, tangents = tree_unflatten(treedef, x)\n- trace = JVPTrace(master, core.cur_sublevel())\n+ trace = JVPTrace(main, core.cur_sublevel())\nreturn map(partial(JVPTracer, trace), primals, tangents)\nreturn out, todo\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -36,8 +36,8 @@ def batch(fun: lu.WrappedFun, in_vals, in_dims, out_dim_dests, axis_name):\nreturn batched_fun.call_wrapped(*in_vals)\n@lu.transformation_with_aux\n-def batch_subtrace(master, in_dims, *in_vals, **params):\n- trace = BatchTrace(master, core.cur_sublevel())\n+def batch_subtrace(main, in_dims, *in_vals, **params):\n+ trace = BatchTrace(main, core.cur_sublevel())\nin_tracers = [BatchTracer(trace, val, dim) if dim is not None else val\nfor val, dim in zip(in_vals, in_dims)]\nouts = yield in_tracers, params\n@@ -60,10 +60,10 @@ def _batch_fun(axis_name, sum_match, in_dims, out_dims_thunk, out_dim_dests,\ncanonicalize_axis(dim, np.ndim(val)) if isinstance(dim, int) else dim\nfor val, dim in zip(in_vals, in_dims)]\nsize, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\n- with core.new_main(BatchTrace) as master:\n- with core.extend_axis_env(axis_name, size, master):\n- out_vals = yield (master, in_dims,) + in_vals, params\n- del master\n+ with core.new_main(BatchTrace) as main:\n+ with core.extend_axis_env(axis_name, size, main):\n+ out_vals = yield (main, in_dims,) + in_vals, params\n+ del main\nout_dim_dests = out_dim_dests() if callable(out_dim_dests) else out_dim_dests\nout_dims = out_dims_thunk()\nfor od, od_dest in zip(out_dims, out_dim_dests):\n@@ -80,9 +80,9 @@ def batch_fun2(fun : lu.WrappedFun, in_dims):\n@lu.transformation\ndef _batch_fun2(in_dims, *in_vals, **params):\n- with core.new_main(BatchTrace) as master:\n- out_vals = yield (master, in_dims,) + in_vals, params\n- del master\n+ with core.new_main(BatchTrace) as main:\n+ out_vals = yield (main, in_dims,) + in_vals, params\n+ del main\nyield out_vals\n@@ -174,9 +174,9 @@ class BatchTrace(Trace):\ndef post_process_call(self, call_primitive, out_tracers, params):\nvals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n- master = self.main\n+ main = self.main\ndef todo(vals):\n- trace = BatchTrace(master, core.cur_sublevel())\n+ trace = BatchTrace(main, core.cur_sublevel())\nreturn map(partial(BatchTracer, trace), vals, dims)\nreturn vals, todo\n@@ -198,9 +198,9 @@ class BatchTrace(Trace):\ndef post_process_map(self, call_primitive, out_tracers, params):\nvals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n- master = self.main\n+ main = self.main\ndef todo(vals):\n- trace = BatchTrace(master, core.cur_sublevel())\n+ trace = BatchTrace(main, core.cur_sublevel())\nreturn [BatchTracer(trace, v, d + 1 if d is not not_mapped else d)\nfor v, d in zip(vals, dims)]\nreturn vals, todo\n@@ -392,12 +392,12 @@ def batch_jaxpr(jaxpr, size, batched, instantiate):\n@lu.transformation_with_aux\ndef batched_traceable(size, batched, instantiate, *vals):\nin_dims = [0 if b else None for b in batched]\n- with core.new_main(BatchTrace) as master:\n- trace = BatchTrace(master, core.cur_sublevel())\n+ with core.new_main(BatchTrace) as main:\n+ trace = BatchTrace(main, core.cur_sublevel())\nans = yield map(partial(BatchTracer, trace), vals, in_dims), {}\nout_tracers = map(trace.full_raise, ans)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n- del master, out_tracers\n+ del main, out_tracers\nif type(instantiate) is bool:\ninstantiate = [instantiate] * len(out_vals)\nout_vals = [moveaxis(x, d, 0) if d is not not_mapped and d != 0\n@@ -409,9 +409,9 @@ def batched_traceable(size, batched, instantiate, *vals):\n@lu.transformation_with_aux\n-def batch_custom_jvp_subtrace(master, in_dims, *in_vals):\n+def batch_custom_jvp_subtrace(main, in_dims, *in_vals):\nsize, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\n- trace = BatchTrace(master, core.cur_sublevel())\n+ trace = BatchTrace(main, core.cur_sublevel())\nin_tracers = [BatchTracer(trace, val, dim) if dim is not None else val\nfor val, dim in zip(in_vals, in_dims * 2)]\nouts = yield in_tracers, {}\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -80,19 +80,19 @@ def mask_fun(fun, logical_env, padded_env, in_vals, polymorphic_shapes):\nlogical_env_vals = [logical_env[k] for k in env_keys]\n# Make padded_env hashable\npadded_env = (env_keys, padded_env_vals)\n- with core.new_main(MaskTrace) as master:\n- fun, out_shapes = mask_subtrace(fun, master, polymorphic_shapes, padded_env)\n+ with core.new_main(MaskTrace) as main:\n+ fun, out_shapes = mask_subtrace(fun, main, polymorphic_shapes, padded_env)\nout_vals = fun.call_wrapped(*(logical_env_vals + in_vals))\n- del master\n+ del main\nreturn out_vals, out_shapes()\n@lu.transformation_with_aux\n-def mask_subtrace(master, shapes, padded_env, *in_vals):\n+def mask_subtrace(main, shapes, padded_env, *in_vals):\nenv_keys, _ = padded_env\nlogical_env_vals, in_vals = in_vals[:len(env_keys)], in_vals[len(env_keys):]\nlogical_env = dict(zip(env_keys, logical_env_vals))\npadded_env = dict(zip(*padded_env))\n- trace = MaskTrace(master, core.cur_sublevel())\n+ trace = MaskTrace(main, core.cur_sublevel())\nin_tracers = [MaskTracer(trace, x, s).full_lower()\nfor x, s in zip(in_vals, shapes)]\nwith extend_shape_envs(logical_env, padded_env):\n@@ -430,9 +430,9 @@ class MaskTrace(Trace):\ndef post_process_call(self, call_primitive, out_tracers, params):\nvals, shapes = unzip2((t.val, t.polymorphic_shape) for t in out_tracers)\n- master = self.main\n+ main = self.main\ndef todo(vals):\n- trace = MaskTrace(master, core.cur_sublevel())\n+ trace = MaskTrace(main, core.cur_sublevel())\nreturn map(partial(MaskTracer, trace), vals, shapes)\nreturn vals, todo\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -239,7 +239,7 @@ class JaxprTrace(Trace):\nout_pvs, out_pv_consts = unzip2(t.pval for t in out_tracers)\nout = out_pv_consts + consts\ndel consts, out_pv_consts\n- master = self.main\n+ main = self.main\nif primitive.map_primitive:\nsz = params['axis_size']\n@@ -249,7 +249,7 @@ class JaxprTrace(Trace):\ndef todo(x):\nn = len(jaxpr.outvars)\nout_pv_consts, consts = x[:n], x[n:]\n- trace = JaxprTrace(master, core.cur_sublevel())\n+ trace = JaxprTrace(main, core.cur_sublevel())\nconst_tracers = map(trace.new_instantiated_const, consts)\nout_tracers = [JaxprTracer(trace, PartialVal((out_pv, out_pv_const)), None)\nfor out_pv, out_pv_const in zip(out_pvs, out_pv_consts)]\n@@ -417,20 +417,20 @@ def trace_to_jaxpr(fun: lu.WrappedFun, pvals: Sequence[PartialVal],\nconsts = [3, 6] # values for `ka` and `kb` constvars\n\"\"\"\ntrace_type = trace_type or (StagingJaxprTrace if stage_out else JaxprTrace)\n- with core.new_main(trace_type, bottom=bottom) as master:\n- fun = trace_to_subjaxpr(fun, master, instantiate)\n+ with core.new_main(trace_type, bottom=bottom) as main:\n+ fun = trace_to_subjaxpr(fun, main, instantiate)\njaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)\nassert not env\n- del master\n+ del main\nreturn jaxpr, out_pvals, consts\n@lu.transformation\n-def trace_to_subjaxpr(master: core.MainTrace, instantiate: Union[bool, Sequence[bool]],\n+def trace_to_subjaxpr(main: core.MainTrace, instantiate: Union[bool, Sequence[bool]],\npvals: Sequence[PartialVal]):\nassert all([isinstance(pv, PartialVal) for pv in pvals]), pvals\n- trace = JaxprTrace(master, core.cur_sublevel())\n+ trace = JaxprTrace(main, core.cur_sublevel())\nin_tracers = map(trace.new_arg, pvals)\nans = yield in_tracers, {}\ninstantiate = [instantiate] * len(ans) if isinstance(instantiate, bool) else instantiate\n@@ -869,8 +869,8 @@ class JaxprStackFrame:\nself.tracer_to_var = {}\nself.constid_to_var = {}\nself.constvar_to_val = {}\n- self.tracers = [] # circ refs, frame->tracer->trace->master->frame,\n- self.eqns = [] # cleared when we pop frame from master\n+ self.tracers = [] # circ refs, frame->tracer->trace->main->frame,\n+ self.eqns = [] # cleared when we pop frame from main\ndef to_jaxpr(self, in_tracers, out_tracers):\ninvars = [self.tracer_to_var[id(t)] for t in in_tracers]\n@@ -1090,11 +1090,11 @@ def omnistaging_enabler() -> None:\ndef trace_to_jaxpr(fun: lu.WrappedFun, pvals: Sequence[PartialVal],\ninstantiate: Union[bool, Sequence[bool]] = False,\n) -> Tuple[Jaxpr, Tuple[PartialVal, ...], Tuple[core.Value, ...]]:\n- with core.new_main(JaxprTrace) as master:\n- fun = trace_to_subjaxpr(fun, master, instantiate)\n+ with core.new_main(JaxprTrace) as main:\n+ fun = trace_to_subjaxpr(fun, main, instantiate)\njaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)\nassert not env\n- del master\n+ del main\nreturn jaxpr, out_pvals, consts\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -678,11 +678,11 @@ def omnistaging_enabler() -> None:\n# Axis index doesn't get any arguments, so that the default bind would have no\n# way to call into a data-dependency based trace such as vmap. Each trace that\n# wants to bind an axis name has to additionally implement `process_axis_index`\n- # and put its master trace on the axis env stack.\n+ # and put its main trace on the axis env stack.\ndef _axis_index_bind(*, axis_name):\nframe = core.axis_frame(axis_name)\n- if frame.master_trace is not None:\n- trace = frame.master_trace.trace_type(frame.master_trace, core.cur_sublevel())\n+ if frame.main_trace is not None:\n+ trace = frame.main_trace.trace_type(frame.main_trace, core.cur_sublevel())\nreturn trace.process_axis_index(frame)\nreturn core.Primitive.bind(axis_index_p, axis_name=axis_name)\n"
}
] | Python | Apache License 2.0 | google/jax | More renaming of master to main in JAX internals (#4179) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.