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,578
13.08.2021 09:03:08
25,200
3a99d18df845566af1b41a24dd65551610ddcfed
Add nocuda jaxlib wheels to the index as well
[ { "change_type": "MODIFY", "old_path": "build/generate_release_indexes.py", "new_path": "build/generate_release_indexes.py", "diff": "@@ -41,7 +41,7 @@ def get_entries(gcs_uri, whl_filter=\".whl\"):\nls_output = subprocess.check_output([\"gsutil\", \"ls\", gcs_uri])\nfor line in ls_output.decode(\"utf-8\").split(\"\\n\"):\n# Skip incorrectly formatted wheel filenames and other gsutil output\n- if not whl_filter in line: continue\n+ if whl_filter not in line: continue\n# Example lines:\n# gs://jax-releases/cuda101/jaxlib-0.1.52+cuda101-cp38-none-manylinux2010_x86_64.whl\n# gs://cloud-tpu-tpuvm-artifacts/wheels/libtpu-nightly/libtpu_nightly-0.1.dev20210615-py3-none-any.whl\n@@ -66,7 +66,9 @@ def write_release_index(filename, entries):\nprint(\"Done.\")\njaxlib_cuda_entries = get_entries(\"gs://jax-releases/cuda*\", whl_filter=\"+cuda\")\n+jaxlib_nocuda_entries = get_entries(\"gs://jax-releases/nocuda\")\nlibtpu_entries = get_entries(\"gs://cloud-tpu-tpuvm-artifacts/wheels/libtpu-nightly/\")\n-write_release_index(JAXLIB_INDEX_FILENAME, jaxlib_cuda_entries)\n+write_release_index(JAXLIB_INDEX_FILENAME,\n+ jaxlib_cuda_entries + jaxlib_nocuda_entries)\nwrite_release_index(LIBTPU_INDEX_FILENAME, libtpu_entries)\n" } ]
Python
Apache License 2.0
google/jax
Add nocuda jaxlib wheels to the index as well
260,578
13.08.2021 11:11:50
25,200
2ab264dc8543d2d734e406228811f1f6b2302d6c
Update workspace org_tensorflow commit
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -7,10 +7,10 @@ load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"0f13410284b9186e436350e9617b3bed2d65f1dc1a220fd37ad9ef43c2035663\",\n- strip_prefix = \"tensorflow-4039feeb743bc42cd0a3d8146ce63fc05d23eb8d\",\n+ sha256 = \"8e1b21a456b8d1f245910e561007317e2a7a4894cc420336cda621e8df08a630\",\n+ strip_prefix = \"tensorflow-3d2e2c88fc805ca5a0dd523ce23182e3173ad887\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/4039feeb743bc42cd0a3d8146ce63fc05d23eb8d.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/3d2e2c88fc805ca5a0dd523ce23182e3173ad887.tar.gz\",\n],\n)\n" } ]
Python
Apache License 2.0
google/jax
Update workspace org_tensorflow commit
260,335
13.08.2021 14:47:45
25,200
2e6a30a595b358c06afcd183621ce5af23dda625
always use same object for vmap temp axis name
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -1256,8 +1256,6 @@ def vmap(fun: F, in_axes=0, out_axes=0, axis_name=None) -> F:\ndocstr += \"\\n\\nOriginal documentation:\\n\\n\"\ndocstr += fun.__doc__\n- axis_name = core._TempAxisName(fun) if axis_name is None else axis_name\n-\nif isinstance(in_axes, list):\n# To be a tree prefix of the positional args tuple, in_axes can never be a\n# list: if in_axes is not a leaf, it must be a tuple of trees. However,\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -66,7 +66,7 @@ def _match_axes(axis_size, axis_name, in_dims, out_dims_thunk, out_dim_dests,\nout_dims = out_dims_thunk()\nfor od, od_dest in zip(out_dims, out_dim_dests):\nif od is not None and not isinstance(od_dest, int):\n- if not isinstance(axis_name, core._TempAxisName):\n+ if not isinstance(axis_name, core._TempAxisName) and axis_name is not None:\nmsg = f\"vmap has mapped output (axis_name={axis_name}) but out_axes is {od_dest}\"\nelse:\nmsg = f\"vmap has mapped output but out_axes is {od_dest}\"\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2949,6 +2949,20 @@ class APITest(jtu.JaxTestCase):\nwith jax.checking_leaks():\n_ = jax.grad(loss)(A, x) # doesn't crash\n+ def test_vmap_caching(self):\n+ # https://github.com/google/jax/issues/7621\n+\n+ f = lambda x: jnp.square(x).mean()\n+ jf = jax.jit(f)\n+ x = jax.random.uniform(jax.random.PRNGKey(0), shape=(8, 4))\n+\n+ with jtu.count_jit_and_pmap_compiles() as count: # noqa: F841\n+ jax.hessian(jf)(x).block_until_ready()\n+ jax.hessian(jf)(x).block_until_ready()\n+ jax.hessian(jf)(x).block_until_ready()\n+\n+ self.assertEqual(count[0], 2)\n+\nclass RematTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
always use same object for vmap temp axis name
260,456
16.08.2021 04:37:18
0
16a110e4ff7342aaac8c93d5c5204576c6e794f7
fix custom_call_status for rocm
[ { "change_type": "MODIFY", "old_path": "jaxlib/rocm_gpu_kernel_helpers.cc", "new_path": "jaxlib/rocm_gpu_kernel_helpers.cc", "diff": "@@ -42,6 +42,6 @@ absl::StatusOr<std::unique_ptr<void* []>> MakeBatchPointers(\nJAX_RETURN_IF_ERROR(\nAsStatus(hipMemcpyAsync(dev_ptrs, host_ptrs.get(), sizeof(void*) * batch,\nhipMemcpyHostToDevice, stream)));\n- return host_ptrs;\n+ return std::move(host_ptrs);\n}\n} // namespace jax\n" } ]
Python
Apache License 2.0
google/jax
fix custom_call_status for rocm
260,411
17.08.2021 14:37:54
-7,200
663ba16694b5f2f1b3541bcc1b2b3055351d4d45
[jax2tf] Update conversion of scatter for shape polymorphism It turns out that the XlaScatter inference rule is enough, we don't need the `.set_shape` workaround.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -2519,8 +2519,6 @@ def _scatter(operand, scatter_indices, updates, *, update_jaxpr, update_consts,\nxla_update_computation,\nproto,\nindices_are_sorted=indices_are_sorted)\n- # TODO: implement shape analysis for XlaScatter\n- out.set_shape(_aval_to_tf_shape(_out_aval))\nreturn out\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Update conversion of scatter for shape polymorphism It turns out that the XlaScatter inference rule is enough, we don't need the `.set_shape` workaround.
260,285
17.08.2021 15:20:13
-7,200
6d83027b69b21f8c3df6ec49feaa3ed9017ada9b
Support scipy.fft.dct/dctn type=2
[ { "change_type": "MODIFY", "old_path": "docs/jax.scipy.rst", "new_path": "docs/jax.scipy.rst", "diff": "jax.scipy package\n=================\n+jax.scipy.fft\n+-------------\n+\n+.. automodule:: jax.scipy.fft\n+\n+.. autosummary::\n+ :toctree: _autosummary\n+\n+ dct\n+ dctn\n+\njax.scipy.linalg\n----------------\n" }, { "change_type": "MODIFY", "old_path": "docs/sphinxext/jax_extensions.py", "new_path": "docs/sphinxext/jax_extensions.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-from docutils import nodes\n+from docutils import nodes, utils\n+\n+from sphinx.util.nodes import split_explicit_title\ndef jax_issue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):\n\"\"\"Generate links to jax issues or PRs in sphinx.\n@@ -32,5 +34,15 @@ def jax_issue_role(name, rawtext, text, lineno, inliner, options={}, content=[])\nnode = nodes.reference(rawtext, '#' + text, refuri=url, **options)\nreturn [node], []\n+def doi_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):\n+ text = utils.unescape(text)\n+ has_explicit_title, title, part = split_explicit_title(text)\n+ full_url = 'https://doi.org/' + part\n+ if not has_explicit_title:\n+ title = 'DOI:' + part\n+ pnode = nodes.reference(title, title, internal=False, refuri=full_url)\n+ return [pnode], []\n+\ndef setup(app):\napp.add_role('jax-issue', jax_issue_role)\n+ app.add_role('doi', doi_role)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/scipy/fft.py", "diff": "+# Copyright 2021 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 scipy.fftpack as osp_fft # TODO use scipy.fft once scipy>=1.4.0 is used\n+from jax import lax, numpy as jnp, partial\n+from jax._src.lax.lax import _canonicalize_axis\n+from jax._src.numpy.util import _wraps\n+\n+def _W4(N, k):\n+ return jnp.exp(-.5j * jnp.pi * k / N)\n+\n+def _dct_interleave(x, axis):\n+ v0 = lax.slice_in_dim(x, None, None, 2, axis)\n+ v1 = lax.rev(lax.slice_in_dim(x, 1, None, 2, axis), (axis,))\n+ return lax.concatenate([v0, v1], axis)\n+\n+def _dct_ortho_norm(out, axis):\n+ factor = lax.concatenate([lax.full((1,), 4, out.dtype), lax.full((out.shape[axis] - 1,), 2, out.dtype)], 0)\n+ factor = lax.expand_dims(factor, [a for a in range(out.ndim) if a != axis])\n+ return out / lax.sqrt(factor * out.shape[axis])\n+\n+# Implementation based on\n+# John Makhoul: A Fast Cosine Transform in One and Two Dimensions (1980)\n+\n+@_wraps(osp_fft.dct)\n+def dct(x, type=2, n=None, axis=-1, norm=None):\n+ if type != 2:\n+ raise NotImplementedError('Only DCT type 2 is implemented.')\n+\n+ axis = _canonicalize_axis(axis, x.ndim)\n+ if n is not None:\n+ x = lax.pad(x, jnp.array(0, x.dtype),\n+ [(0, n - x.shape[axis] if a == axis else 0, 0)\n+ for a in range(x.ndim)])\n+\n+ N = x.shape[axis]\n+ v = _dct_interleave(x, axis)\n+ V = jnp.fft.fft(v, axis=axis)\n+ k = lax.expand_dims(jnp.arange(N), [a for a in range(x.ndim) if a != axis])\n+ out = V * _W4(N, k)\n+ out = 2 * out.real\n+ if norm == 'ortho':\n+ out = _dct_ortho_norm(out, axis)\n+ return out\n+\n+\n+def _dct2(x, axes, norm):\n+ axis1, axis2 = map(partial(_canonicalize_axis, num_dims=x.ndim), axes)\n+ N1, N2 = x.shape[axis1], x.shape[axis2]\n+ v = _dct_interleave(_dct_interleave(x, axis1), axis2)\n+ V = jnp.fft.fftn(v, axes=axes)\n+ k1 = lax.expand_dims(jnp.arange(N1), [a for a in range(x.ndim) if a != axis1])\n+ k2 = lax.expand_dims(jnp.arange(N2), [a for a in range(x.ndim) if a != axis2])\n+ out = _W4(N1, k1) * (_W4(N2, k2) * V + _W4(N2, -k2) * jnp.roll(jnp.flip(V, axis=axis2), shift=1, axis=axis2))\n+ out = 2 * out.real\n+ if norm == 'ortho':\n+ return _dct_ortho_norm(_dct_ortho_norm(out, axis1), axis2)\n+ return out\n+\n+\n+@_wraps(osp_fft.dctn)\n+def dctn(x, type=2, s=None, axes=None, norm=None):\n+ if type != 2:\n+ raise NotImplementedError('Only DCT type 2 is implemented.')\n+\n+ if axes is None:\n+ axes = range(x.ndim)\n+\n+ if len(axes) == 1:\n+ return dct(x, n=s[0] if s is not None else None, axis=axes[0], norm=norm)\n+\n+ if s is not None:\n+ ns = {a: n for a, n in zip(axes, s)}\n+ pads = [(0, ns[a] - x.shape[a] if a in ns else 0, 0) for a in range(x.ndim)]\n+ x = lax.pad(x, jnp.array(0, x.dtype), pads)\n+\n+ if len(axes) == 2:\n+ return _dct2(x, axes=axes, norm=norm)\n+\n+ # compose high-D DCTs from 2D and 1D DCTs:\n+ for axes_block in [axes[i:i+2] for i in range(0, len(axes), 2)]:\n+ x = dctn(x, axes=axes_block, norm=norm)\n+ return x\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/__init__.py", "new_path": "jax/scipy/__init__.py", "diff": "@@ -19,3 +19,4 @@ from . import signal\nfrom . import sparse\nfrom . import special\nfrom . import stats\n+from . import fft\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/scipy/fft.py", "diff": "+# Copyright 2021 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: F401\n+\n+from jax._src.scipy.fft import (\n+ dct,\n+ dctn\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/scipy_fft_test.py", "diff": "+# Copyright 2021 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+import itertools\n+\n+from absl.testing import absltest, parameterized\n+\n+from jax import test_util as jtu\n+import jax.scipy.fft as jsp_fft\n+import scipy.fftpack as osp_fft # TODO use scipy.fft once scipy>=1.4.0 is used\n+\n+from jax.config import config\n+\n+config.parse_flags_with_absl()\n+\n+float_dtypes = jtu.dtypes.floating\n+real_dtypes = float_dtypes + jtu.dtypes.integer + jtu.dtypes.boolean\n+\n+def _get_dctn_test_axes(shape):\n+ axes = [[]]\n+ ndims = len(shape)\n+ axes.append(None)\n+ for naxes in range(1, min(ndims, 3) + 1):\n+ axes.extend(itertools.combinations(range(ndims), naxes))\n+ for index in range(1, ndims + 1):\n+ axes.append((-index,))\n+ return axes\n+\n+def _get_dctn_test_s(shape, axes):\n+ s_list = [None]\n+ if axes is not None:\n+ s_list.extend(itertools.product(*[[shape[ax]+i for i in range(-shape[ax]+1, shape[ax]+1)] for ax in axes]))\n+ return s_list\n+\n+class LaxBackedScipyFftTests(jtu.JaxTestCase):\n+ \"\"\"Tests for LAX-backed scipy.fft implementations\"\"\"\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"_shape={jtu.format_shape_dtype_string(shape, dtype)}_n={n}_axis={axis}_norm={norm}\",\n+ shape=shape, dtype=dtype, n=n, axis=axis, norm=norm)\n+ for dtype in real_dtypes\n+ for shape in [(10,), (2, 5)]\n+ for n in [None, 1, 7, 13, 20]\n+ for axis in [-1, 0]\n+ for norm in [None, 'ortho']))\n+ @jtu.skip_on_devices(\"rocm\")\n+ def testDct(self, shape, dtype, n, axis, norm):\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: (rng(shape, dtype),)\n+ jnp_fn = lambda a: jsp_fft.dct(a, n=n, axis=axis, norm=norm)\n+ np_fn = lambda a: osp_fft.dct(a, n=n, axis=axis, norm=norm)\n+ self._CheckAgainstNumpy(np_fn, jnp_fn, args_maker, check_dtypes=False,\n+ tol=1e-4)\n+ self._CompileAndCheck(jnp_fn, args_maker, atol=1e-4)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"_shape={jtu.format_shape_dtype_string(shape, dtype)}_axes={axes}_s={s}_norm={norm}\",\n+ shape=shape, dtype=dtype, s=s, axes=axes, norm=norm)\n+ for dtype in real_dtypes\n+ for shape in [(10,), (10, 10), (9,), (2, 3, 4), (2, 3, 4, 5)]\n+ for axes in _get_dctn_test_axes(shape)\n+ for s in _get_dctn_test_s(shape, axes)\n+ for norm in [None, 'ortho']))\n+ @jtu.skip_on_devices(\"rocm\")\n+ def testDctn(self, shape, dtype, s, axes, norm):\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: (rng(shape, dtype),)\n+ jnp_fn = lambda a: jsp_fft.dctn(a, s=s, axes=axes, norm=norm)\n+ np_fn = lambda a: osp_fft.dctn(a, shape=s, axes=axes, norm=norm)\n+ self._CheckAgainstNumpy(np_fn, jnp_fn, args_maker, check_dtypes=False,\n+ tol=1e-4)\n+ self._CompileAndCheck(jnp_fn, args_maker, atol=1e-4)\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Support scipy.fft.dct/dctn type=2
260,456
17.08.2021 20:42:02
0
f454f6b7b8db328f7fd6a23f693bbbddf434ca85
fix rocm_amdgpu_targets for rocm
[ { "change_type": "MODIFY", "old_path": ".bazelrc", "new_path": ".bazelrc", "diff": "@@ -46,7 +46,7 @@ build:native_arch_posix --host_copt=-march=native\nbuild:mkl_open_source_only --define=tensorflow_mkldnn_contraction_kernel=1\nbuild:cuda --repo_env TF_NEED_CUDA=1\n-build:cuda --action_env=TF_CUDA_COMPUTE_CAPABILITIES=\"3.5,5.2,6.0,6.1,7.0\"\n+build:cuda --action_env TF_CUDA_COMPUTE_CAPABILITIES=\"3.5,5.2,6.0,6.1,7.0\"\nbuild:cuda --crosstool_top=@local_config_cuda//crosstool:toolchain\nbuild:cuda --@local_config_cuda//:enable_cuda\nbuild:cuda --define=xla_python_enable_gpu=true\n@@ -55,7 +55,7 @@ build:rocm --crosstool_top=@local_config_rocm//crosstool:toolchain\nbuild:rocm --define=using_rocm=true --define=using_rocm_hipcc=true\nbuild:rocm --define=xla_python_enable_gpu=true\nbuild:rocm --repo_env TF_NEED_ROCM=1\n-build:rocm --action_env=TF_ROCM_AMDGPU_TARGETS=\"gfx803,gfx900,gfx906,gfx1010\"\n+build:rocm --action_env TF_ROCM_AMDGPU_TARGETS=\"gfx900,gfx906,gfx908\"\nbuild:nonccl --define=no_nccl_support=true\n" }, { "change_type": "MODIFY", "old_path": "build/build.py", "new_path": "build/build.py", "diff": "@@ -374,18 +374,10 @@ def main():\n\"--cudnn_version\",\ndefault=None,\nhelp=\"CUDNN version, e.g., 8\")\n- parser.add_argument(\n- \"--cuda_compute_capabilities\",\n- default=\"3.5,5.2,6.0,6.1,7.0\",\n- help=\"A comma-separated list of CUDA compute capabilities to support.\")\nparser.add_argument(\n\"--rocm_path\",\ndefault=None,\nhelp=\"Path to the ROCm toolkit.\")\n- parser.add_argument(\n- \"--rocm_amdgpu_targets\",\n- default=\"gfx803,gfx900,gfx906,gfx1010\",\n- help=\"A comma-separated list of ROCm amdgpu targets to support.\")\nparser.add_argument(\n\"--bazel_startup_options\",\naction=\"append\", default=[],\n@@ -457,7 +449,6 @@ def main():\nprint(\"CUDA toolkit path: {}\".format(cuda_toolkit_path))\nif cudnn_install_path:\nprint(\"CUDNN library path: {}\".format(cudnn_install_path))\n- print(\"CUDA compute capabilities: {}\".format(args.cuda_compute_capabilities))\nif args.cuda_version:\nprint(\"CUDA version: {}\".format(args.cuda_version))\nif args.cudnn_version:\n@@ -470,7 +461,6 @@ def main():\nif args.enable_rocm:\nif rocm_toolkit_path:\nprint(\"ROCm toolkit path: {}\".format(rocm_toolkit_path))\n- print(\"ROCm amdgpu targets: {}\".format(args.rocm_amdgpu_targets))\nwrite_bazelrc(\npython_bin_path=python_bin_path,\n" } ]
Python
Apache License 2.0
google/jax
fix rocm_amdgpu_targets for rocm
260,335
17.08.2021 16:18:57
25,200
b90daf9cdad16c13bf31b9947d762e1430912162
custom_vjp: automatically handle float0 cotangents
[ { "change_type": "MODIFY", "old_path": "jax/_src/custom_derivatives.py", "new_path": "jax/_src/custom_derivatives.py", "diff": "@@ -553,8 +553,10 @@ def _flatten_bwd(in_tree, in_avals, out_trees, *args):\n\"number of arguments to the primal function, but got VJP output \"\n\"structure {} for primal input structure {}.\")\nraise TypeError(msg.format(in_tree2, in_tree)) from None\n- yield [zeros_like_aval(aval.at_least_vspace()) if ct is zero else ct\n- for aval, ct in zip(in_avals, cts_in_flat)]\n+ # Ignore any None cotangents, and any corresponding to inputs for which the\n+ # type doesn't equal the tangent type (i.e. float0s)\n+ yield [zeros_like_aval(a.at_least_vspace()) if ct is zero or a != a.at_least_vspace()\n+ else ct for a, ct in zip(in_avals, cts_in_flat)]\nclass CustomVJPCallPrimitive(core.CallPrimitive):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -5351,6 +5351,21 @@ class CustomVJPTest(jtu.JaxTestCase):\nself.assertAllClose(g_c, 42. * c, check_dtypes=False)\nself.assertAllClose(g_x, 17. * x, check_dtypes=False)\n+ def test_float0_cotangents_automatically_handled(self):\n+ @jax.custom_vjp\n+ def f(x, y):\n+ return x\n+\n+ def f_fwd(x, y):\n+ return x, None\n+\n+ def f_bwd(_, zbar):\n+ return (0., 1)\n+\n+ f.defvjp(f_fwd, f_bwd)\n+\n+ jax.jit(lambda x: jax.vjp(f, 0., x)[1](1.))(1) # doesn't crash\n+\nclass CustomTransposeTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
custom_vjp: automatically handle float0 cotangents
260,335
17.08.2021 17:06:19
25,200
83f95a5dae19124b0f396ba7608c7701a617ccbd
custom_jvp/vjp tweaks and fixes
[ { "change_type": "MODIFY", "old_path": "jax/_src/custom_derivatives.py", "new_path": "jax/_src/custom_derivatives.py", "diff": "@@ -242,6 +242,7 @@ def _flatten_jvp(in_tree, *args):\nmsg = (\"Custom JVP rule must produce primal and tangent outputs with equal \"\n\"container (pytree) structures, but got {} and {} respectively.\")\nraise TypeError(msg.format(out_tree, out_tree2))\n+ # TODO(mattjj): compare primals' tangent types to tangent objects' types\nprimal_avals_out = [\nraise_to_shaped(core.get_aval(x), weak_type=False).strip_named_shape()\nfor x in primals_out]\n@@ -555,7 +556,8 @@ def _flatten_bwd(in_tree, in_avals, out_trees, *args):\nraise TypeError(msg.format(in_tree2, in_tree)) from None\n# Ignore any None cotangents, and any corresponding to inputs for which the\n# type doesn't equal the tangent type (i.e. float0s)\n- yield [zeros_like_aval(a.at_least_vspace()) if ct is zero or a != a.at_least_vspace()\n+ # TODO(mattjj): change this to check if tangent type represents 0dim vspace\n+ yield [Zero(a.at_least_vspace()) if ct is zero or a != a.at_least_vspace()\nelse ct for a, ct in zip(in_avals, cts_in_flat)]\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -2076,9 +2076,3 @@ def pp_kv_pairs(kv_pairs):\nreturn pp('[ ') >> vcat([pp_kv_pair(k, v) for k, v in kv_pairs]) >> pp(' ]')\nelse:\nreturn pp('')\n-\n-# Casting float0 array to a float-valued zero array.\n-def zeros_like_float0(array, dtype=None):\n- if not dtype:\n- dtype = np.float\n- return np.zeros(array.shape, dtype)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -150,7 +150,7 @@ def unpair_pval(pval):\ndef replace_float0s(primal, tangent):\nif dtype(tangent) is float0:\n- return core.zeros_like_float0(tangent, dtype(primal))\n+ return zeros_like_jaxval(primal)\nelse:\nreturn tangent\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -19,7 +19,8 @@ import jax\nfrom ..config import config\nfrom .. import core\nfrom ..core import raise_to_shaped, Trace, Tracer\n-from jax._src.ad_util import add_jaxvals, add_jaxvals_p, zeros_like_jaxval, zeros_like_p\n+from jax._src.ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval,\n+ zeros_like_p, Zero)\nfrom .. import linear_util as lu\nfrom .._src.util import (unzip2, partial, safe_map, safe_zip, wrap_name, split_list,\ncanonicalize_axis, moveaxis, as_hashable_function, curry)\n@@ -275,9 +276,26 @@ def batch_custom_vjp_bwd(bwd, axis_name, axis_size, in_dims, out_dim_dests, main\ndef _match_axes_and_sum(axis_size, out_dims_thunk, out_dim_dests, *in_vals):\n# this is like _match_axes, but we do reduce-sums as needed\nout_vals = yield in_vals, {}\n- yield map(partial(matchaxis, axis_size, sum_match=True),\n+ yield map(partial(_matchaxis_symbolic_zeros, axis_size, sum_match=True),\nout_dims_thunk(), out_dim_dests, out_vals)\n+def _matchaxis_symbolic_zeros(sz, src, dst, x, sum_match=False):\n+ # Just like `matchaxis`, but handles symbolic zeros using ad_util.py\n+ if isinstance(x, Zero):\n+ if src == dst:\n+ return x\n+ elif type(src) == type(dst) == int:\n+ aval = core.mapped_aval(sz, src, x.aval)\n+ return Zero(core.unmapped_aval(sz, dst, aval))\n+ elif src is not_mapped and dst is not not_mapped:\n+ return Zero(core.unmapped_aval(sz, dst, x.aval))\n+ elif dst is not_mapped and sum_match:\n+ return Zero(core.mapped_aval(sz, src, x.aval))\n+ else:\n+ raise ValueError((x, src, dst))\n+ else:\n+ return matchaxis(sz, src, dst, x, sum_match=sum_match)\n+\n### API\nAxesSpec = Union[Callable[[], BatchDims], BatchDims]\n@@ -437,9 +455,8 @@ def matchaxis(sz, src, dst, x, sum_match=False):\nelif type(src) == type(dst) == int:\nreturn moveaxis(x, src, dst)\nelif src is not_mapped and dst is not not_mapped:\n- return broadcast(\n- x, sz, canonicalize_axis(dst, np.ndim(x) + 1))\n- elif dst is None and sum_match:\n+ return broadcast(x, sz, canonicalize_axis(dst, np.ndim(x) + 1))\n+ elif dst is not_mapped and sum_match:\nreturn x.sum(src)\nelse:\nraise ValueError((src, dst))\n" } ]
Python
Apache License 2.0
google/jax
custom_jvp/vjp tweaks and fixes
260,296
17.08.2021 20:41:02
25,200
b65f39ca7ade1d50bf8fa22f4ec282ab5163c1ca
Default to `jnp.float_` type in `nn.initializers`.
[ { "change_type": "MODIFY", "old_path": "jax/_src/nn/initializers.py", "new_path": "jax/_src/nn/initializers.py", "diff": "@@ -28,17 +28,20 @@ from jax import ops\nfrom jax import random\nfrom jax import core\nfrom jax._src.util import prod\n+from jax import dtypes\n-def zeros(key, shape, dtype=jnp.float32): return jnp.zeros(shape, dtype)\n-def ones(key, shape, dtype=jnp.float32): return jnp.ones(shape, dtype)\n+def zeros(key, shape, dtype=jnp.float_): return jnp.zeros(shape, dtypes.canonicalize_dtype(dtype))\n+def ones(key, shape, dtype=jnp.float_): return jnp.ones(shape, dtypes.canonicalize_dtype(dtype))\n-def uniform(scale=1e-2, dtype=jnp.float32):\n+def uniform(scale=1e-2, dtype=jnp.float_):\ndef init(key, shape, dtype=dtype):\n+ dtype = dtypes.canonicalize_dtype(dtype)\nreturn random.uniform(key, shape, dtype) * scale\nreturn init\n-def normal(stddev=1e-2, dtype=jnp.float32):\n+def normal(stddev=1e-2, dtype=jnp.float_):\ndef init(key, shape, dtype=dtype):\n+ dtype = dtypes.canonicalize_dtype(dtype)\nreturn random.normal(key, shape, dtype) * stddev\nreturn init\n@@ -48,8 +51,9 @@ def _compute_fans(shape: core.NamedShape, in_axis=-2, out_axis=-1):\nfan_out = shape[out_axis] * receptive_field_size\nreturn fan_in, fan_out\n-def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1, dtype=jnp.float32):\n+def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1, dtype=jnp.float_):\ndef init(key, shape, dtype=dtype):\n+ dtype = dtypes.canonicalize_dtype(dtype)\nshape = core.as_named_shape(shape)\nfan_in, fan_out = _compute_fans(shape, in_axis, out_axis)\nif mode == \"fan_in\": denominator = fan_in\n@@ -78,7 +82,7 @@ lecun_normal = partial(variance_scaling, 1.0, \"fan_in\", \"truncated_normal\")\nkaiming_uniform = he_uniform = partial(variance_scaling, 2.0, \"fan_in\", \"uniform\")\nkaiming_normal = he_normal = partial(variance_scaling, 2.0, \"fan_in\", \"truncated_normal\")\n-def orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float32):\n+def orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float_):\n\"\"\"\nConstruct an initializer for uniformly distributed orthogonal matrices.\n@@ -86,6 +90,7 @@ def orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float32):\ndepending on which side is smaller.\n\"\"\"\ndef init(key, shape, dtype=dtype):\n+ dtype = dtypes.canonicalize_dtype(dtype)\nif len(shape) < 2:\nraise ValueError(\"orthogonal initializer requires at least a 2D shape\")\nn_rows, n_cols = prod(shape) // shape[column_axis], shape[column_axis]\n@@ -101,13 +106,14 @@ def orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float32):\nreturn init\n-def delta_orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float32):\n+def delta_orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float_):\n\"\"\"\nConstruct an initializer for delta orthogonal kernels; see arXiv:1806.05393.\nThe shape must be 3D, 4D or 5D.\n\"\"\"\ndef init(key, shape, dtype=dtype):\n+ dtype = dtypes.canonicalize_dtype(dtype)\nif len(shape) not in [3, 4, 5]:\nraise ValueError(\"Delta orthogonal initializer requires a 3D, 4D or 5D \"\n\"shape.\")\n" }, { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -111,12 +111,12 @@ class JetTest(jtu.JaxTestCase):\nrng = np.random.RandomState(0)\n- x = rng.randn(*input_shape).astype(\"float32\")\n+ x = rng.randn(*input_shape)\nprimals = (W, b, x)\n- series_in1 = [rng.randn(*W.shape).astype(\"float32\") for _ in range(order)]\n- series_in2 = [rng.randn(*b.shape).astype(\"float32\") for _ in range(order)]\n- series_in3 = [rng.randn(*x.shape).astype(\"float32\") for _ in range(order)]\n+ series_in1 = [rng.randn(*W.shape) for _ in range(order)]\n+ series_in2 = [rng.randn(*b.shape) for _ in range(order)]\n+ series_in3 = [rng.randn(*x.shape) for _ in range(order)]\nseries_in = (series_in1, series_in2, series_in3)\n" }, { "change_type": "MODIFY", "old_path": "tests/stax_test.py", "new_path": "tests/stax_test.py", "diff": "@@ -22,6 +22,7 @@ import numpy as np\nfrom jax import test_util as jtu\nfrom jax import random\nfrom jax.experimental import stax\n+from jax import dtypes\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -29,7 +30,7 @@ config.parse_flags_with_absl()\ndef random_inputs(rng, input_shape):\nif type(input_shape) is tuple:\n- return rng.randn(*input_shape).astype(np.float32)\n+ return rng.randn(*input_shape).astype(dtypes.canonicalize_dtype(np.float_))\nelif type(input_shape) is list:\nreturn [random_inputs(rng, shape) for shape in input_shape]\nelse:\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -734,7 +734,7 @@ class NamedNNTest(XMapTestCase):\nshape = (80, 50, 7)\nfan_in, fan_out = jax._src.nn.initializers._compute_fans(\nNamedShape(*shape), 0, 1)\n- key = jax.random.PRNGKey(0)\n+ key = jax.random.PRNGKey(1)\nbase_scaling = partial(jax.nn.initializers.variance_scaling, 100, fan, distr)\nref_sampler = lambda: base_scaling(in_axis=0, out_axis=1)(key, shape)\nif map_in and map_out:\n" } ]
Python
Apache License 2.0
google/jax
Default to `jnp.float_` type in `nn.initializers`.
260,411
18.08.2021 16:31:09
-7,200
bc1e41438b5a5ea72ba819684c5b67f29cbedc13
[jax2tf] Added support for conversion of padding with enable_xla=False
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -230,9 +230,12 @@ def convert(fun: Callable,\nin a SavedModel, the custom gradients are currently lost and an error will\nbe raised if a gradient computation is attempted. This is due to a current\nbug in TensorFlow.\n- enable_xla: if unset, the converter will try harder to use pure TF ops to\n- convert the function, and raise an error if it can not be converted\n- without resorting to XLA ops (default: True).\n+ enable_xla: if set (default), the converter will use the simplest conversion\n+ and use XLA TF ops when necessary. These ops are known to create issues\n+ for the TFLite and TFjs converters. For those cases, unset this parameter\n+ so the converter tries harder to use non-XLA TF ops to convert the function,\n+ and raises an error if it can not be converted\n+ without resorting to XLA ops.\nReturns:\nA version of `fun` that expects TfVals as arguments (or\n@@ -1739,22 +1742,60 @@ tf_impl_with_avals[lax.squeeze_p] = _squeeze\ndef _pad(operand, padding_value, *, padding_config,\n_in_avals: Sequence[core.ShapedArray],\n_out_aval: core.ShapedArray):\n- del _in_avals\nlow, high, interior = util.unzip3(padding_config)\nif _thread_local_state.enable_xla:\nout = tfxla.pad(operand, padding_value, low, high, interior)\nreturn out\n- if all(lo >= 0 and hi >= 0 and i == 0 for lo, hi, i in padding_config):\n- return tf.pad(\n- operand,\n- zip(low, high),\n+ # Do only the interior padding first. This is rarely needed.\n+ if any(i != 0 for _, _, i in padding_config):\n+ operand = _interior_padding(operand, padding_value, padding_config,\n+ _eval_shape(_in_avals[0].shape))\n+\n+ # Now do the non-negative edge padding. This is the common case, use tf.pad.\n+ non_negative_padding = [((lo if lo >= 0 else 0), (hi if hi >= 0 else 0))\n+ for lo, hi, _ in padding_config]\n+ operand = tf.pad(operand, non_negative_padding,\nmode=\"CONSTANT\",\nconstant_values=padding_value)\n- raise _xla_disabled_error(\"pad\", \"Only use cases without interior or negative padding can be converted without XLA.\")\n+ # Now the negative edge padding (this is also rare)\n+ if any(lo < 0 or hi < 0 for lo, hi, _ in padding_config):\n+ output_shape = _eval_shape(_out_aval.shape)\n+ begins = [(-lo if lo < 0 else 0) for lo, _, _ in padding_config]\n+ operand = tf.slice(operand, begins, output_shape)\n+\n+ return operand\ntf_impl_with_avals[lax.pad_p] = _pad\n+def _interior_padding(operand, padding_value, padding_config, operand_shape):\n+ # Used only when enable_xla=False\n+ # Applies only the interior padding from the padding_config.\n+ # We do this somewhat inefficiently, as as a scatter.\n+ # For each dimension we compute the indices_by_dim as [0, f, 2f, 3f, ...] where\n+ # f is the dilation factor for the dimension, i.e., 1 + interior_padding.\n+ # Then we compute the cartesian production of the indices (using broadcast\n+ # and concat).\n+\n+ # We could make this code more complex and do all the padding at once, but\n+ # we prefer to keep it simple.\n+ indices_by_dim = []\n+ indices_shape = operand_shape + (1,)\n+ output_shape = [] # considering only interior padding\n+ for d, (dsz, (_, _, i)) in enumerate(zip(operand_shape, padding_config)):\n+ dilation_factor = i + 1\n+ output_shape.append(dsz * dilation_factor - i)\n+ indices = tf.range(dsz) * dilation_factor\n+ expansion = [None] * (1 + len(operand_shape))\n+ expansion[d] = slice(None, None, None)\n+ indices_by_dim.append(tf.broadcast_to(indices[expansion], indices_shape))\n+\n+ indices_cartesian = tf.concat(indices_by_dim, axis=len(operand_shape))\n+ scattered = tf.scatter_nd(indices_cartesian, operand, output_shape)\n+ # What elements from the output array we use from\n+ mask = tf.scatter_nd(indices_cartesian, tf.ones_like(operand, dtype=np.bool_), output_shape)\n+ return tf.where(mask, scattered, padding_value)\n+\ndef _rev(operand, *, dimensions):\nreturn tf.reverse(operand, dimensions)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -793,8 +793,8 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ndef test_enable_xla(self):\n# Tests that enable_xla flag is properly scoped to a conversion.\ndef fun(x):\n- # Can be converted only if enable_xla is on, due to negative padding.\n- return lax.pad(x, np.float32(0), [(-1, 0, 0), (0, 0, 0)])\n+ # lax.reduce is unlikely to ever be convertible with enable_xla=False\n+ return lax.reduce(x, np.float32(0), lambda v, acc: v + acc, dimensions=(0, 1))\ntf_fun_with_xla = jax2tf.convert(fun, enable_xla=True)\ntf_fun_without_xla = jax2tf.convert(fun, enable_xla=False)\n@@ -802,19 +802,15 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(fun(x), tf_fun_with_xla(x))\nwith self.assertRaisesRegex(NotImplementedError,\n- \"Call to pad cannot be converted with enable_xla=False\"):\n+ \"Call to reduce cannot be converted with enable_xla=False\"):\ntf_fun_without_xla(x)\n- # Now in reverse order\n- def fun2(x):\n- # Can be converted only if enable_xla is on, due to negative padding.\n- return lax.pad(x, np.float32(0), [(-1, 0, 0), (0, 0, 0)])\n-\n- tf_fun2_without_xla = jax2tf.convert(fun2, enable_xla=False)\n- tf_fun2_with_xla = jax2tf.convert(fun2, enable_xla=True)\n+ # Now in reverse order (we had bugs with the management of enable_xla global)\n+ tf_fun2_without_xla = jax2tf.convert(lambda x: fun(x), enable_xla=False)\n+ tf_fun2_with_xla = jax2tf.convert(lambda x: fun(x), enable_xla=True)\nwith self.assertRaisesRegex(NotImplementedError,\n- \"Call to pad cannot be converted with enable_xla=False\"):\n+ \"Call to reduce cannot be converted with enable_xla=False\"):\ntf_fun2_without_xla(x)\nself.assertAllClose(fun(x), tf_fun2_with_xla(x))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -1273,8 +1273,7 @@ for dtype in jtu.dtypes.all:\n[(0, 0, 0), (-2, -2, 4)], # add big dilation then remove from edges\n[(0, 0, 0), (-2, -3, 1)], # remove everything in one dimension\n]:\n- works_without_xla = all(lo >= 0 and hi >= 0 and i == 0 for lo, hi, i in pads)\n- for enable_xla in ([True, False] if works_without_xla else [True]):\n+ for enable_xla in [True, False]:\ndefine(\nlax.pad_p,\nf\"inshape={jtu.format_shape_dtype_string(arg_shape, dtype)}_pads={pads}_enable_xla={enable_xla}\",\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitives_test.py", "new_path": "jax/experimental/jax2tf/tests/primitives_test.py", "diff": "@@ -100,7 +100,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# `one_containing=\"foo\"` to parameterized below.\n@primitive_harness.parameterized(\nprimitive_harness.all_harnesses, include_jax_unimpl=False,\n- #one_containing=\"random_uniform_shape=float32[5,4]\"\n+ #one_containing=\"pad_inshape=uint8[2,3]_pads=[(0, 0, 0), (-1, -1, 0)]_enable_xla=False\"\n)\n@jtu.ignore_warning(\ncategory=UserWarning, message=\"Using reduced precision for gradient.*\")\n@@ -256,16 +256,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ntf1_res = sess.run(jax2tf.convert(jnp.floor_divide)(x, y))\nself.assertAllClose(expected, tf1_res)\n- def test_disable_xla(self):\n-\n- def fun(x):\n- return lax.pad(x, np.float32(0), [(-1, 0, 0), (0, 0, 0)])\n-\n- with self.assertRaisesRegex(\n- NotImplementedError, \"Call to pad cannot be converted with enable_xla=False.\"):\n- self.ConvertAndCompare(\n- fun, np.ones((2, 3), dtype=np.float32), enable_xla=False)\n-\ndef test_boolean_gather(self):\nvalues = np.array([[True, True], [False, True], [False, False]],\ndtype=np.bool_)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Added support for conversion of padding with enable_xla=False
260,635
31.07.2021 19:26:53
-7,200
5138743e8e15d2a565f7cecb23a91e5a0dd11d93
Implement variance scaling initializers with complex dtype
[ { "change_type": "MODIFY", "old_path": "jax/_src/nn/initializers.py", "new_path": "jax/_src/nn/initializers.py", "diff": "@@ -48,7 +48,59 @@ def _compute_fans(shape: core.NamedShape, in_axis=-2, out_axis=-1):\nfan_out = shape[out_axis] * receptive_field_size\nreturn fan_in, fan_out\n+def _complex_uniform(key, shape, dtype):\n+ \"\"\"\n+ Sample uniform random values within a disk on the complex plane,\n+ with zero mean and unit variance.\n+ \"\"\"\n+ key_r, key_theta = random.split(key)\n+ dtype = np.array(0, dtype).real.dtype\n+ r = jnp.sqrt(2 * random.uniform(key_r, shape, dtype))\n+ theta = 2 * jnp.pi * random.uniform(key_theta, shape, dtype)\n+ return r * jnp.exp(1j * theta)\n+\n+def _complex_truncated_normal(key, upper, shape, dtype):\n+ \"\"\"\n+ Sample random values from a centered normal distribution on the complex plane,\n+ whose modulus is truncated to `upper`, and the variance before the truncation is one.\n+ \"\"\"\n+ key_r, key_theta = random.split(key)\n+ dtype = np.array(0, dtype).real.dtype\n+ t = (1 - jnp.exp(jnp.array(-(upper ** 2), dtype))) * random.uniform(key_r, shape, dtype)\n+ r = jnp.sqrt(-jnp.log(1 - t))\n+ theta = 2 * jnp.pi * random.uniform(key_theta, shape, dtype)\n+ return r * jnp.exp(1j * theta)\n+\ndef variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1, dtype=jnp.float32):\n+ \"\"\"\n+ Initializer capable of adapting its scale to the shape of the weights tensor.\n+\n+ With `distribution=\"truncated_normal\" or \"normal\"`, samples are\n+ drawn from a truncated/untruncated normal distribution with a mean of zero and\n+ a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)`,\n+ where `n` is:\n+ - number of input units in the weights tensor, if `mode=\"fan_in\"`\n+ - number of output units, if `mode=\"fan_out\"`\n+ - average of the numbers of input and output units, if `mode=\"fan_avg\"`\n+\n+ With `distribution=\"truncated_normal\"`, the absolute values of the samples are\n+ truncated below 2 standard deviations before truncation.\n+\n+ With `distribution=\"uniform\"`, samples are drawn from:\n+ - a uniform interval, if `dtype` is real\n+ - a uniform disk, if `dtype` is complex\n+ with a mean of zero and a standard deviation of `stddev`.\n+\n+ Args:\n+ scale: scaling factor (positive float).\n+ mode: one of \"fan_in\", \"fan_out\", and \"fan_avg\".\n+ distribution: random distribution to use. One of \"truncated_normal\",\n+ \"normal\" and \"uniform\".\n+ in_axis: axis of the input dimension in the weights tensor.\n+ out_axis: axis of the output dimension in the weights tensor.\n+ dtype: the dtype of the weights.\n+ \"\"\"\n+\ndef init(key, shape, dtype=dtype):\nshape = core.as_named_shape(shape)\nfan_in, fan_out = _compute_fans(shape, in_axis, out_axis)\n@@ -59,16 +111,26 @@ def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1, dtype=j\nraise ValueError(\n\"invalid mode for variance scaling initializer: {}\".format(mode))\nvariance = jnp.array(scale / denominator, dtype=dtype)\n+\nif distribution == \"truncated_normal\":\n+ if jnp.issubdtype(dtype, jnp.floating):\n# constant is stddev of standard normal truncated to (-2, 2)\nstddev = jnp.sqrt(variance) / jnp.array(.87962566103423978, dtype)\nreturn random.truncated_normal(key, -2, 2, shape, dtype) * stddev\n+ else:\n+ # constant is stddev of complex standard normal truncated to 2\n+ stddev = jnp.sqrt(variance) / jnp.array(.95311164380491208, dtype)\n+ return _complex_truncated_normal(key, 2, shape, dtype) * stddev\nelif distribution == \"normal\":\nreturn random.normal(key, shape, dtype) * jnp.sqrt(variance)\nelif distribution == \"uniform\":\n+ if jnp.issubdtype(dtype, jnp.floating):\nreturn random.uniform(key, shape, dtype, -1) * jnp.sqrt(3 * variance)\nelse:\n- raise ValueError(\"invalid distribution for variance scaling initializer\")\n+ return _complex_uniform(key, shape, dtype) * jnp.sqrt(variance)\n+ else:\n+ raise ValueError(\"invalid distribution for variance scaling initializer: {}\".format(distribution))\n+\nreturn init\nxavier_uniform = glorot_uniform = partial(variance_scaling, 1.0, \"fan_avg\", \"uniform\")\n" }, { "change_type": "MODIFY", "old_path": "tests/nn_test.py", "new_path": "tests/nn_test.py", "diff": "@@ -178,26 +178,26 @@ class NNFunctionsTest(jtu.JaxTestCase):\nInitializerRecord = collections.namedtuple(\n\"InitializerRecord\",\n- [\"name\", \"initializer\", \"shapes\"])\n+ [\"name\", \"initializer\", \"shapes\", \"dtypes\"])\nALL_SHAPES = [(2,), (2, 2), (2, 3), (3, 2), (2, 3, 4), (4, 3, 2), (2, 3, 4, 5)]\n-def initializer_record(name, initializer, min_dims=2, max_dims=4):\n+def initializer_record(name, initializer, dtypes, min_dims=2, max_dims=4):\nshapes = [shape for shape in ALL_SHAPES\nif min_dims <= len(shape) <= max_dims]\n- return InitializerRecord(name, initializer, shapes)\n+ return InitializerRecord(name, initializer, shapes, dtypes)\nINITIALIZER_RECS = [\n- initializer_record(\"uniform\", nn.initializers.uniform, 1),\n- initializer_record(\"normal\", nn.initializers.normal, 1),\n- initializer_record(\"he_normal\", nn.initializers.he_normal),\n- initializer_record(\"he_uniform\", nn.initializers.he_uniform),\n- initializer_record(\"glorot_normal\", nn.initializers.glorot_normal),\n- initializer_record(\"glorot_uniform\", nn.initializers.glorot_uniform),\n- initializer_record(\"lecun_normal\", nn.initializers.lecun_normal),\n- initializer_record(\"lecun_uniform\", nn.initializers.lecun_uniform),\n- initializer_record(\"orthogonal\", nn.initializers.orthogonal, 2, 2),\n- initializer_record(\"delta_orthogonal\", nn.initializers.delta_orthogonal, 4, 4)\n+ initializer_record(\"uniform\", nn.initializers.uniform, jtu.dtypes.floating, 1),\n+ initializer_record(\"normal\", nn.initializers.normal, jtu.dtypes.inexact, 1),\n+ initializer_record(\"he_normal\", nn.initializers.he_normal, jtu.dtypes.inexact),\n+ initializer_record(\"he_uniform\", nn.initializers.he_uniform, jtu.dtypes.inexact),\n+ initializer_record(\"glorot_normal\", nn.initializers.glorot_normal, jtu.dtypes.inexact),\n+ initializer_record(\"glorot_uniform\", nn.initializers.glorot_uniform, jtu.dtypes.inexact),\n+ initializer_record(\"lecun_normal\", nn.initializers.lecun_normal, jtu.dtypes.inexact),\n+ initializer_record(\"lecun_uniform\", nn.initializers.lecun_uniform, jtu.dtypes.inexact),\n+ initializer_record(\"orthogonal\", nn.initializers.orthogonal, jtu.dtypes.floating, 2, 2),\n+ initializer_record(\"delta_orthogonal\", nn.initializers.delta_orthogonal, jtu.dtypes.floating, 4, 4)\n]\nclass NNInitializersTest(jtu.JaxTestCase):\n@@ -219,10 +219,11 @@ class NNInitializersTest(jtu.JaxTestCase):\n\"shape\": shape, \"dtype\": dtype}\nfor rec in INITIALIZER_RECS\nfor shape in rec.shapes\n- for dtype in jtu.dtypes.floating))\n+ for dtype in rec.dtypes))\ndef testInitializer(self, initializer, shape, dtype):\nrng = random.PRNGKey(0)\nval = initializer(rng, shape, dtype)\n+\nself.assertEqual(shape, jnp.shape(val))\nself.assertEqual(jax.dtypes.canonicalize_dtype(dtype), jnp.dtype(val))\n@@ -235,7 +236,7 @@ class NNInitializersTest(jtu.JaxTestCase):\n\"shape\": shape, \"dtype\": dtype}\nfor rec in INITIALIZER_RECS\nfor shape in rec.shapes\n- for dtype in jtu.dtypes.floating))\n+ for dtype in rec.dtypes))\ndef testInitializerProvider(self, initializer_provider, shape, dtype):\nrng = random.PRNGKey(0)\ninitializer = initializer_provider(dtype=dtype)\n" } ]
Python
Apache License 2.0
google/jax
Implement variance scaling initializers with complex dtype
260,688
19.08.2021 16:54:53
25,200
6b00b4480727d7d4877f279d6cf2d58cfad42b94
Move all Abseil dependencies out of jaxlib CUDA libraries These were breaking the build with CUDA 10.2
[ { "change_type": "MODIFY", "old_path": "jaxlib/BUILD", "new_path": "jaxlib/BUILD", "diff": "@@ -247,10 +247,6 @@ cuda_library(\nsrcs = [\"cuda_lu_pivot_kernels.cu.cc\"],\nhdrs = [\"cuda_lu_pivot_kernels.h\"],\ndeps = [\n- \":cuda_gpu_kernel_helpers\",\n- \":kernel_helpers\",\n- \"@org_tensorflow//tensorflow/compiler/xla/service:custom_call_status\",\n- \"@com_google_absl//absl/status\",\n\"@local_config_cuda//cuda:cuda_headers\",\n],\n)\n@@ -265,8 +261,10 @@ pybind_extension(\nfeatures = [\"-use_header_modules\"],\nmodule_name = \"cuda_lu_pivot_kernels\",\ndeps = [\n+ \":cuda_gpu_kernel_helpers\",\n\":cuda_lu_pivot_kernels_lib\",\n\":kernel_pybind11_helpers\",\n+ \"@org_tensorflow//tensorflow/compiler/xla/service:custom_call_status\",\n\"@org_tensorflow//tensorflow/stream_executor/cuda:cudart_stub\",\n\"@local_config_cuda//cuda:cuda_headers\",\n\"@pybind11\",\n@@ -278,10 +276,6 @@ cuda_library(\nsrcs = [\"cuda_prng_kernels.cu.cc\"],\nhdrs = [\"cuda_prng_kernels.h\"],\ndeps = [\n- \":cuda_gpu_kernel_helpers\",\n- \":kernel_helpers\",\n- \"@org_tensorflow//tensorflow/compiler/xla/service:custom_call_status\",\n- \"@com_google_absl//absl/status\",\n\"@local_config_cuda//cuda:cuda_headers\",\n],\n)\n@@ -296,8 +290,10 @@ pybind_extension(\nfeatures = [\"-use_header_modules\"],\nmodule_name = \"cuda_prng_kernels\",\ndeps = [\n+ \":cuda_gpu_kernel_helpers\",\n\":cuda_prng_kernels_lib\",\n\":kernel_pybind11_helpers\",\n+ \"@org_tensorflow//tensorflow/compiler/xla/service:custom_call_status\",\n\"@org_tensorflow//tensorflow/stream_executor/cuda:cudart_stub\",\n\"@local_config_cuda//cuda:cuda_headers\",\n\"@pybind11\",\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/cuda_lu_pivot_kernels.cc", "new_path": "jaxlib/cuda_lu_pivot_kernels.cc", "diff": "@@ -15,12 +15,42 @@ limitations under the License.\n#include \"jaxlib/cuda_lu_pivot_kernels.h\"\n+#include \"jaxlib/cuda_gpu_kernel_helpers.h\"\n#include \"jaxlib/kernel_pybind11_helpers.h\"\n#include \"include/pybind11/pybind11.h\"\n+#include \"tensorflow/compiler/xla/service/custom_call_status.h\"\nnamespace jax {\nnamespace {\n+std::string BuildCudaLuPivotsToPermutationDescriptor(\n+ std::int64_t batch_size, std::int32_t pivot_size,\n+ std::int32_t permutation_size) {\n+ return PackDescriptorAsString(LuPivotsToPermutationDescriptor{\n+ batch_size, pivot_size, permutation_size});\n+}\n+\n+absl::Status CudaLuPivotsToPermutation_(cudaStream_t stream, void** buffers,\n+ const char* opaque,\n+ std::size_t opaque_len) {\n+ auto s =\n+ UnpackDescriptor<LuPivotsToPermutationDescriptor>(opaque, opaque_len);\n+ JAX_RETURN_IF_ERROR(s.status());\n+ LaunchLuPivotsToPermutationKernel(stream, buffers, **s);\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cudaGetLastError()));\n+ return absl::OkStatus();\n+}\n+\n+void CudaLuPivotsToPermutation(cudaStream_t stream, void** buffers,\n+ const char* opaque, size_t opaque_len,\n+ XlaCustomCallStatus* status) {\n+ auto s = CudaLuPivotsToPermutation_(stream, buffers, opaque, opaque_len);\n+ if (!s.ok()) {\n+ absl::string_view message = s.message();\n+ XlaCustomCallStatusSetFailure(status, message.data(), message.length());\n+ }\n+}\n+\npybind11::dict Registrations() {\npybind11::dict dict;\ndict[\"cuda_lu_pivots_to_permutation\"] =\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/cuda_lu_pivot_kernels.cu.cc", "new_path": "jaxlib/cuda_lu_pivot_kernels.cu.cc", "diff": "@@ -18,10 +18,6 @@ limitations under the License.\n#include <array>\n#include <iostream>\n-#include \"jaxlib/cuda_gpu_kernel_helpers.h\"\n-#include \"jaxlib/kernel_helpers.h\"\n-#include \"tensorflow/compiler/xla/service/custom_call_status.h\"\n-\nnamespace jax {\nnamespace {\n@@ -61,29 +57,12 @@ __global__ void LuPivotsToPermutationKernel(\n} // namespace\n-struct LuPivotsToPermutationDescriptor {\n- std::int64_t batch_size;\n- std::int32_t pivot_size;\n- std::int32_t permutation_size;\n-};\n-\n-std::string BuildCudaLuPivotsToPermutationDescriptor(\n- std::int64_t batch_size, std::int32_t pivot_size,\n- std::int32_t permutation_size) {\n- return PackDescriptorAsString(LuPivotsToPermutationDescriptor{\n- batch_size, pivot_size, permutation_size});\n-}\n-\n-absl::Status CudaLuPivotsToPermutation_(cudaStream_t stream, void** buffers,\n- const char* opaque,\n- std::size_t opaque_len) {\n+void LaunchLuPivotsToPermutationKernel(\n+ cudaStream_t stream, void** buffers,\n+ LuPivotsToPermutationDescriptor descriptor) {\nconst std::int32_t* pivots =\nreinterpret_cast<const std::int32_t*>(buffers[0]);\nstd::int32_t* permutation_out = reinterpret_cast<std::int32_t*>(buffers[1]);\n- auto s =\n- UnpackDescriptor<LuPivotsToPermutationDescriptor>(opaque, opaque_len);\n- JAX_RETURN_IF_ERROR(s.status());\n- const auto& descriptor = **s;\nconst int block_dim = 128;\nconst std::int64_t grid_dim = std::min<std::int64_t>(\n@@ -93,18 +72,6 @@ absl::Status CudaLuPivotsToPermutation_(cudaStream_t stream, void** buffers,\n/*dynamic_shared_mem_bytes=*/0, stream>>>(\npivots, permutation_out, descriptor.batch_size, descriptor.pivot_size,\ndescriptor.permutation_size);\n- JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cudaGetLastError()));\n- return absl::OkStatus();\n-}\n-\n-void CudaLuPivotsToPermutation(cudaStream_t stream, void** buffers,\n- const char* opaque, size_t opaque_len,\n- XlaCustomCallStatus* status) {\n- auto s = CudaLuPivotsToPermutation_(stream, buffers, opaque, opaque_len);\n- if (!s.ok()) {\n- XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),\n- s.message().length());\n- }\n}\n} // namespace jax\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/cuda_lu_pivot_kernels.h", "new_path": "jaxlib/cuda_lu_pivot_kernels.h", "diff": "@@ -20,17 +20,18 @@ limitations under the License.\n#include <string>\n#include \"third_party/gpus/cuda/include/cuda_runtime_api.h\"\n-#include \"tensorflow/compiler/xla/service/custom_call_status.h\"\nnamespace jax {\n-std::string BuildCudaLuPivotsToPermutationDescriptor(\n- std::int64_t batch_size, std::int32_t pivot_size,\n- std::int32_t permutation_size);\n+struct LuPivotsToPermutationDescriptor {\n+ std::int64_t batch_size;\n+ std::int32_t pivot_size;\n+ std::int32_t permutation_size;\n+};\n-void CudaLuPivotsToPermutation(cudaStream_t stream, void** buffers,\n- const char* opaque, std::size_t opaque_len,\n- XlaCustomCallStatus* status);\n+void LaunchLuPivotsToPermutationKernel(\n+ cudaStream_t stream, void** buffers,\n+ LuPivotsToPermutationDescriptor descriptor);\n} // namespace jax\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/cuda_prng_kernels.cc", "new_path": "jaxlib/cuda_prng_kernels.cc", "diff": "@@ -15,12 +15,36 @@ limitations under the License.\n#include \"jaxlib/cuda_prng_kernels.h\"\n+#include \"jaxlib/cuda_gpu_kernel_helpers.h\"\n#include \"jaxlib/kernel_pybind11_helpers.h\"\n#include \"include/pybind11/pybind11.h\"\n+#include \"tensorflow/compiler/xla/service/custom_call_status.h\"\nnamespace jax {\nnamespace {\n+std::string BuildCudaThreeFry2x32Descriptor(std::int64_t n) {\n+ return PackDescriptorAsString(ThreeFry2x32Descriptor{n});\n+}\n+\n+absl::Status CudaThreeFry2x32_(cudaStream_t stream, void** buffers,\n+ const char* opaque, std::size_t opaque_len) {\n+ auto s = UnpackDescriptor<ThreeFry2x32Descriptor>(opaque, opaque_len);\n+ JAX_RETURN_IF_ERROR(s.status());\n+ LaunchThreeFry2x32Kernel(stream, buffers, **s);\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cudaGetLastError()));\n+ return absl::OkStatus();\n+}\n+\n+void CudaThreeFry2x32(cudaStream_t stream, void** buffers, const char* opaque,\n+ size_t opaque_len, XlaCustomCallStatus* status) {\n+ auto s = CudaThreeFry2x32_(stream, buffers, opaque, opaque_len);\n+ if (!s.ok()) {\n+ absl::string_view message = s.message();\n+ XlaCustomCallStatusSetFailure(status, message.data(), message.length());\n+ }\n+}\n+\npybind11::dict Registrations() {\npybind11::dict dict;\ndict[\"cuda_threefry2x32\"] = EncapsulateFunction(CudaThreeFry2x32);\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/cuda_prng_kernels.cu.cc", "new_path": "jaxlib/cuda_prng_kernels.cu.cc", "diff": "@@ -18,10 +18,6 @@ limitations under the License.\n#include <array>\n#include <cstddef>\n-#include \"jaxlib/cuda_gpu_kernel_helpers.h\"\n-#include \"jaxlib/kernel_helpers.h\"\n-#include \"tensorflow/compiler/xla/service/custom_call_status.h\"\n-\nnamespace jax {\nnamespace {\n@@ -100,16 +96,8 @@ __global__ void ThreeFry2x32Kernel(const std::uint32_t* key0,\n} // namespace\n-struct ThreeFry2x32Descriptor {\n- std::int64_t n;\n-};\n-\n-std::string BuildCudaThreeFry2x32Descriptor(std::int64_t n) {\n- return PackDescriptorAsString(ThreeFry2x32Descriptor{n});\n-}\n-\n-absl::Status CudaThreeFry2x32_(cudaStream_t stream, void** buffers,\n- const char* opaque, std::size_t opaque_len) {\n+void LaunchThreeFry2x32Kernel(cudaStream_t stream, void** buffers,\n+ ThreeFry2x32Descriptor descriptor) {\nstd::array<const std::uint32_t*, 2> keys;\nkeys[0] = reinterpret_cast<const std::uint32_t*>(buffers[0]);\nkeys[1] = reinterpret_cast<const std::uint32_t*>(buffers[1]);\n@@ -119,26 +107,12 @@ absl::Status CudaThreeFry2x32_(cudaStream_t stream, void** buffers,\nstd::array<std::uint32_t*, 2> out;\nout[0] = reinterpret_cast<std::uint32_t*>(buffers[4]);\nout[1] = reinterpret_cast<std::uint32_t*>(buffers[5]);\n- auto s = UnpackDescriptor<ThreeFry2x32Descriptor>(opaque, opaque_len);\n- JAX_RETURN_IF_ERROR(s.status());\n- const auto& descriptor = **s;\nconst int block_dim = 128;\nconst std::int64_t grid_dim =\nstd::min<std::int64_t>(1024, (descriptor.n + block_dim - 1) / block_dim);\nThreeFry2x32Kernel<<<grid_dim, block_dim, /*dynamic_shared_mem_bytes=*/0,\nstream>>>(keys[0], keys[1], data[0], data[1], out[0],\nout[1], descriptor.n);\n- JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cudaGetLastError()));\n- return absl::OkStatus();\n-}\n-\n-void CudaThreeFry2x32(cudaStream_t stream, void** buffers, const char* opaque,\n- size_t opaque_len, XlaCustomCallStatus* status) {\n- auto s = CudaThreeFry2x32_(stream, buffers, opaque, opaque_len);\n- if (!s.ok()) {\n- XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),\n- s.message().length());\n- }\n}\n} // namespace jax\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/cuda_prng_kernels.h", "new_path": "jaxlib/cuda_prng_kernels.h", "diff": "@@ -20,14 +20,15 @@ limitations under the License.\n#include <string>\n#include \"third_party/gpus/cuda/include/cuda_runtime_api.h\"\n-#include \"tensorflow/compiler/xla/service/custom_call_status.h\"\nnamespace jax {\n-std::string BuildCudaThreeFry2x32Descriptor(std::int64_t n);\n+struct ThreeFry2x32Descriptor {\n+ std::int64_t n;\n+};\n-void CudaThreeFry2x32(cudaStream_t stream, void** buffers, const char* opaque,\n- std::size_t opaque_len, XlaCustomCallStatus* status);\n+void LaunchThreeFry2x32Kernel(cudaStream_t stream, void** buffers,\n+ ThreeFry2x32Descriptor descriptor);\n} // namespace jax\n" } ]
Python
Apache License 2.0
google/jax
Move all Abseil dependencies out of jaxlib CUDA libraries These were breaking the build with CUDA 10.2 PiperOrigin-RevId: 391875083
260,335
20.08.2021 13:43:38
25,200
e416e8730165bb2308dd0a69fbeeb5a32ca09eb8
inline jit-decorated jax.random calls
[ { "change_type": "MODIFY", "old_path": "jax/_src/prng.py", "new_path": "jax/_src/prng.py", "diff": "@@ -371,7 +371,7 @@ if cuda_prng:\n_threefry2x32_gpu_translation_rule\n-@jit\n+@partial(jit, inline=True)\ndef threefry_2x32(keypair, count):\n\"\"\"Apply the Threefry 2x32 hash.\n@@ -408,7 +408,7 @@ def threefry_2x32(keypair, count):\ndef threefry_split(key: jnp.ndarray, num: int) -> jnp.ndarray:\nreturn _threefry_split(key, int(num)) # type: ignore\n-@partial(jit, static_argnums=(1,))\n+@partial(jit, static_argnums=(1,), inline=True)\ndef _threefry_split(key, num) -> jnp.ndarray:\ncounts = lax.iota(np.uint32, num * 2)\nreturn lax.reshape(threefry_2x32(key, counts), (num, 2))\n@@ -417,12 +417,12 @@ def _threefry_split(key, num) -> jnp.ndarray:\ndef threefry_fold_in(key: jnp.ndarray, data: int) -> jnp.ndarray:\nreturn _threefry_fold_in(key, jnp.uint32(data))\n-@jit\n+@partial(jit, inline=True)\ndef _threefry_fold_in(key, data):\nreturn threefry_2x32(key, threefry_seed(data))\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef threefry_random_bits(key: jnp.ndarray, bit_width, shape):\n\"\"\"Sample uniform random bits of given width and shape using PRNG key.\"\"\"\nif not _is_threefry_prng_key(key):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/random.py", "new_path": "jax/_src/random.py", "diff": "@@ -185,7 +185,7 @@ def uniform(key: KeyArray,\nshape = core.as_named_shape(shape)\nreturn _uniform(key, shape, dtype, minval, maxval) # type: ignore\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _uniform(key, shape, dtype, minval, maxval) -> jnp.ndarray:\n_check_shape(\"uniform\", shape)\nif not jnp.issubdtype(dtype, np.floating):\n@@ -242,7 +242,7 @@ def randint(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _randint(key, shape, minval, maxval, dtype)\n-@partial(jit, static_argnums=(1, 4))\n+@partial(jit, static_argnums=(1, 4), inline=True)\ndef _randint(key, shape, minval, maxval, dtype):\n_check_shape(\"randint\", shape, np.shape(minval), np.shape(maxval))\nif not jnp.issubdtype(dtype, np.integer):\n@@ -352,7 +352,7 @@ def permutation(key: KeyArray, x: Array) -> jnp.ndarray:\nreturn x[ind]\n-@partial(jit, static_argnums=(2,))\n+@partial(jit, static_argnums=(2,), inline=True)\ndef _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@@ -469,7 +469,7 @@ def normal(key: KeyArray,\nshape = core.as_named_shape(shape)\nreturn _normal(key, shape, dtype) # type: ignore\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _normal(key, shape, dtype) -> jnp.ndarray:\nif dtypes.issubdtype(dtype, np.complexfloating):\nsqrt2 = np.array(np.sqrt(2), dtype)\n@@ -482,7 +482,7 @@ def _normal(key, shape, dtype) -> jnp.ndarray:\nelse:\nreturn _normal_real(key, shape, dtype) # type: ignore\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _normal_real(key, shape, dtype) -> jnp.ndarray:\n_check_shape(\"normal\", shape)\nlo = np.nextafter(np.array(-1., dtype), np.array(0., dtype), dtype=dtype)\n@@ -529,7 +529,7 @@ def multivariate_normal(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _multivariate_normal(key, mean, cov, shape, dtype, method) # type: ignore\n-@partial(jit, static_argnums=(3, 4, 5))\n+@partial(jit, static_argnums=(3, 4, 5), inline=True)\ndef _multivariate_normal(key, mean, cov, shape, dtype, method) -> jnp.ndarray:\nif not np.ndim(mean) >= 1:\nmsg = \"multivariate_normal requires mean.ndim >= 1, got mean.ndim == {}\"\n@@ -594,7 +594,7 @@ def truncated_normal(key: KeyArray,\nshape = core.as_named_shape(shape)\nreturn _truncated_normal(key, lower, upper, shape, dtype) # type: ignore\n-@partial(jit, static_argnums=(3, 4))\n+@partial(jit, static_argnums=(3, 4), inline=True)\ndef _truncated_normal(key, lower, upper, shape, dtype) -> jnp.ndarray:\nif shape is None:\nshape = lax.broadcast_shapes(np.shape(lower), np.shape(upper))\n@@ -645,7 +645,7 @@ def bernoulli(key: KeyArray,\np = lax.convert_element_type(p, dtype)\nreturn _bernoulli(key, p, shape) # type: ignore\n-@partial(jit, static_argnums=(2,))\n+@partial(jit, static_argnums=(2,), inline=True)\ndef _bernoulli(key, p, shape) -> jnp.ndarray:\nif shape is None:\n# TODO: Use the named part of `p` as well\n@@ -727,7 +727,7 @@ def cauchy(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _cauchy(key, shape, dtype)\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _cauchy(key, shape, dtype):\n_check_shape(\"cauchy\", shape)\nu = uniform(key, shape, dtype, minval=jnp.finfo(dtype).eps, maxval=1.)\n@@ -767,7 +767,7 @@ def dirichlet(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _dirichlet(key, alpha, shape, dtype)\n-@partial(jit, static_argnums=(2, 3))\n+@partial(jit, static_argnums=(2, 3), inline=True)\ndef _dirichlet(key, alpha, shape, dtype):\nif not np.ndim(alpha) >= 1:\nmsg = \"dirichlet requires alpha.ndim >= 1, got alpha.ndim == {}\"\n@@ -806,7 +806,7 @@ def exponential(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _exponential(key, shape, dtype)\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _exponential(key, shape, dtype):\n_check_shape(\"exponential\", shape)\nu = uniform(key, shape, dtype)\n@@ -954,7 +954,7 @@ def gamma_threefry2x32(key: jnp.ndarray, # raw ndarray form of a 2x32 key\nshape = core.canonicalize_shape(shape)\nreturn _gamma(key, a, shape, dtype)\n-@partial(jit, static_argnums=(2, 3))\n+@partial(jit, static_argnums=(2, 3), inline=True)\ndef _gamma(key, a, shape, dtype):\nif shape is None:\nshape = np.shape(a)\n@@ -967,7 +967,7 @@ def _gamma(key, a, shape, dtype):\nreturn random_gamma_p.bind(key, a)\n-@partial(jit, static_argnums=(2, 3, 4))\n+@partial(jit, static_argnums=(2, 3, 4), inline=True)\ndef _poisson_knuth(key, lam, shape, dtype, max_iters):\n# Knuth's algorithm for generating Poisson random variates.\n# Reference:\n@@ -990,7 +990,7 @@ def _poisson_knuth(key, lam, shape, dtype, max_iters):\nreturn (k - 1).astype(dtype)\n-@partial(jit, static_argnums=(2, 3, 4))\n+@partial(jit, static_argnums=(2, 3, 4), inline=True)\ndef _poisson_rejection(key, lam, shape, dtype, max_iters):\n# Transformed rejection due to Hormann.\n# Reference:\n@@ -1033,7 +1033,7 @@ def _poisson_rejection(key, lam, shape, dtype, max_iters):\nreturn k.astype(dtype)\n-@partial(jit, static_argnums=(2, 3))\n+@partial(jit, static_argnums=(2, 3), inline=True)\ndef _poisson(key, lam, shape, dtype):\n# The implementation matches TensorFlow and NumPy:\n# https://github.com/tensorflow/tensorflow/blob/v2.2.0-rc3/tensorflow/core/kernels/random_poisson_op.cc\n@@ -1106,7 +1106,7 @@ def gumbel(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _gumbel(key, shape, dtype)\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _gumbel(key, shape, dtype):\n_check_shape(\"gumbel\", shape)\nreturn -jnp.log(-jnp.log(\n@@ -1174,7 +1174,7 @@ def laplace(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _laplace(key, shape, dtype)\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _laplace(key, shape, dtype):\n_check_shape(\"laplace\", shape)\nu = uniform(\n@@ -1205,7 +1205,7 @@ def logistic(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _logistic(key, shape, dtype)\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _logistic(key, shape, dtype):\n_check_shape(\"logistic\", shape)\nx = uniform(key, shape, dtype, minval=jnp.finfo(dtype).eps, maxval=1.)\n@@ -1241,7 +1241,7 @@ def pareto(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _pareto(key, b, shape, dtype)\n-@partial(jit, static_argnums=(2, 3))\n+@partial(jit, static_argnums=(2, 3), inline=True)\ndef _pareto(key, b, shape, dtype):\nif shape is None:\nshape = np.shape(b)\n@@ -1281,7 +1281,7 @@ def t(key: KeyArray,\nshape = core.canonicalize_shape(shape)\nreturn _t(key, df, shape, dtype)\n-@partial(jit, static_argnums=(2, 3))\n+@partial(jit, static_argnums=(2, 3), inline=True)\ndef _t(key, df, shape, dtype):\nif shape is None:\nshape = np.shape(df)\n@@ -1318,7 +1318,7 @@ def rademacher(key: KeyArray,\nreturn _rademacher(key, shape, dtype)\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _rademacher(key, shape, dtype):\nbernoulli_samples = bernoulli(key=key, p=0.5, shape=shape)\nreturn (2 * bernoulli_samples - 1).astype(dtype)\n@@ -1351,7 +1351,7 @@ def maxwell(key: KeyArray,\nreturn _maxwell(key, shape, dtype)\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=(1, 2), inline=True)\ndef _maxwell(key, shape, dtype):\nshape = shape + (3,)\nnorm_rvs = normal(key=key, shape=shape, dtype=dtype)\n@@ -1388,7 +1388,7 @@ def double_sided_maxwell(key: KeyArray,\nreturn _double_sided_maxwell(key, loc, scale, shape, dtype)\n-@partial(jit, static_argnums=(3, 4))\n+@partial(jit, static_argnums=(3, 4), inline=True)\ndef _double_sided_maxwell(key, loc, scale, shape, dtype):\nparams_shapes = lax.broadcast_shapes(np.shape(loc), np.shape(scale))\nif not shape:\n@@ -1433,7 +1433,7 @@ def weibull_min(key: KeyArray,\nreturn _weibull_min(key, scale, concentration, shape, dtype)\n-@partial(jit, static_argnums=(3, 4))\n+@partial(jit, static_argnums=(3, 4), inline=True)\ndef _weibull_min(key, scale, concentration, shape, dtype):\nrandom_uniform = uniform(\nkey=key, shape=shape, minval=0, maxval=1, dtype=dtype)\n" } ]
Python
Apache License 2.0
google/jax
inline jit-decorated jax.random calls
260,282
04.07.2021 19:55:45
-28,800
85367804552c149c96b09986ccfd9a96c20a5735
Add documentation for jax.device_get
[ { "change_type": "MODIFY", "old_path": "docs/jax.rst", "new_path": "docs/jax.rst", "diff": "@@ -36,6 +36,7 @@ Just-in-time compilation (:code:`jit`)\ndevice_put\ndevice_put_replicated\ndevice_put_sharded\n+ device_get\ndefault_backend\nnamed_call\n@@ -91,6 +92,7 @@ Parallelization (:code:`pmap`)\n.. autofunction:: device_put\n.. autofunction:: device_put_replicated\n.. autofunction:: device_put_sharded\n+.. autofunction:: device_get\n.. autofunction:: default_backend\n.. autofunction:: named_call\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -2328,7 +2328,35 @@ def _device_get(x):\nelse:\nreturn copy()\n-def device_get(x):\n+def device_get(x: Any):\n+ \"\"\"Transfer ``x`` to host.\n+\n+ Args:\n+ x: An array, scalar, DeviceArray or (nested) standard Python container thereof\n+ representing the array to be transferred to host.\n+\n+ Returns:\n+ An array or (nested) Python container thereof representing the\n+ value of ``x``.\n+\n+ Examples:\n+ Passing a DeviceArray:\n+\n+ >>> import jax\n+ >>> x = jax.numpy.array([1., 2., 3.])\n+ >>> jax.device_get(x)\n+ array([1., 2., 3.], dtype=float32)\n+\n+ Passing a scalar (has no effect):\n+\n+ >>> jax.device_get(1)\n+ 1\n+\n+ See Also:\n+ - device_put\n+ - device_put_sharded\n+ - device_put_replicated\n+ \"\"\"\nfor y in tree_leaves(x):\ntry:\ny.copy_to_host_async()\n" } ]
Python
Apache License 2.0
google/jax
Add documentation for jax.device_get
260,628
21.08.2021 16:03:43
14,400
fec72e1852cc09ddf499b3b3d388300e87d4f116
add support for scipy.special.{expn,expi,exp1}
[ { "change_type": "MODIFY", "old_path": "docs/jax.scipy.rst", "new_path": "docs/jax.scipy.rst", "diff": "@@ -99,7 +99,10 @@ jax.scipy.special\nerf\nerfc\nerfinv\n+ exp1\n+ expi\nexpit\n+ expn\ngammainc\ngammaincc\ngammaln\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/special.py", "new_path": "jax/_src/scipy/special.py", "diff": "@@ -1089,3 +1089,376 @@ def sph_harm(m: jnp.ndarray,\n'be statically specified to use `sph_harm` within JAX transformations.')\nreturn _sph_harm(m, n, theta, phi, n_max)\n+\n+\n+# exponential integrals\n+# these algorithms are ported over from the files ei.c and expn.c in the Cephes mathematical library.\n+# https://fossies.org/dox/cephes-math-28/ei_8c_source.html\n+# https://fossies.org/dox/cephes-math-28/expn_8c_source.html\n+\n+\n+def _expint1(x):\n+ # 0 < x <= 2\n+ A = [\n+ -5.350447357812542947283e0,\n+ 2.185049168816613393830e2,\n+ -4.176572384826693777058e3,\n+ 5.541176756393557601232e4,\n+ -3.313381331178144034309e5,\n+ 1.592627163384945414220e6,\n+ ]\n+ B = [\n+ 1.0,\n+ -5.250547959112862969197e1,\n+ 1.259616186786790571525e3,\n+ -1.756549581973534652631e4,\n+ 1.493062117002725991967e5,\n+ -7.294949239640527645655e5,\n+ 1.592627163384945429726e6,\n+ ]\n+ A, B = [jnp.array(U, dtype=x.dtype) for U in [A, B]]\n+ f = jnp.polyval(A, x) / jnp.polyval(B, x)\n+ return x * f + jnp.euler_gamma + jnp.log(x)\n+\n+\n+def _eval_expint_k(A, B, x):\n+ # helper function for all subsequent intervals\n+ A, B = [jnp.array(U, dtype=x.dtype) for U in [A, B]]\n+ one = _constant_like(x, 1.0)\n+ w = one / x\n+ f = jnp.polyval(A, w) / jnp.polyval(B, w)\n+ f = w * f + one\n+ return jnp.exp(x) * w * f\n+\n+\n+def _expint2(x):\n+ # 2 <= x < 4\n+ A = [\n+ 1.981808503259689673238e-2,\n+ -1.271645625984917501326e0,\n+ -2.088160335681228318920e0,\n+ 2.755544509187936721172e0,\n+ -4.409507048701600257171e-1,\n+ 4.665623805935891391017e-2,\n+ -1.545042679673485262580e-3,\n+ 7.059980605299617478514e-5,\n+ ]\n+ B = [\n+ 1.0,\n+ 1.476498670914921440652e0,\n+ 5.629177174822436244827e-1,\n+ 1.699017897879307263248e-1,\n+ 2.291647179034212017463e-2,\n+ 4.450150439728752875043e-3,\n+ 1.727439612206521482874e-4,\n+ 3.953167195549672482304e-5,\n+ ]\n+ return _eval_expint_k(A, B, x)\n+\n+\n+def _expint3(x):\n+ # 4 <= x <= 8\n+ A = [\n+ -1.373215375871208729803e0,\n+ -7.084559133740838761406e-1,\n+ 1.580806855547941010501e0,\n+ -2.601500427425622944234e-1,\n+ 2.994674694113713763365e-2,\n+ -1.038086040188744005513e-3,\n+ 4.371064420753005429514e-5,\n+ 2.141783679522602903795e-6,\n+ ]\n+ B = [\n+ 1.0,\n+ 8.585231423622028380768e-1,\n+ 4.483285822873995129957e-1,\n+ 7.687932158124475434091e-2,\n+ 2.449868241021887685904e-2,\n+ 8.832165941927796567926e-4,\n+ 4.590952299511353531215e-4,\n+ -4.729848351866523044863e-6,\n+ 2.665195537390710170105e-6,\n+ ]\n+ return _eval_expint_k(A, B, x)\n+\n+\n+def _expint4(x):\n+ # 8 <= x <= 16\n+ A = [\n+ -2.106934601691916512584e0,\n+ 1.732733869664688041885e0,\n+ -2.423619178935841904839e-1,\n+ 2.322724180937565842585e-2,\n+ 2.372880440493179832059e-4,\n+ -8.343219561192552752335e-5,\n+ 1.363408795605250394881e-5,\n+ -3.655412321999253963714e-7,\n+ 1.464941733975961318456e-8,\n+ 6.176407863710360207074e-10,\n+ ]\n+ B = [\n+ 1.0,\n+ -2.298062239901678075778e-1,\n+ 1.105077041474037862347e-1,\n+ -1.566542966630792353556e-2,\n+ 2.761106850817352773874e-3,\n+ -2.089148012284048449115e-4,\n+ 1.708528938807675304186e-5,\n+ -4.459311796356686423199e-7,\n+ 1.394634930353847498145e-8,\n+ 6.150865933977338354138e-10,\n+ ]\n+ return _eval_expint_k(A, B, x)\n+\n+\n+def _expint5(x):\n+ # 16 <= x <= 32\n+ A = [\n+ -2.458119367674020323359e-1,\n+ -1.483382253322077687183e-1,\n+ 7.248291795735551591813e-2,\n+ -1.348315687380940523823e-2,\n+ 1.342775069788636972294e-3,\n+ -7.942465637159712264564e-5,\n+ 2.644179518984235952241e-6,\n+ -4.239473659313765177195e-8,\n+ ]\n+ B = [\n+ 1.0,\n+ -1.044225908443871106315e-1,\n+ -2.676453128101402655055e-1,\n+ 9.695000254621984627876e-2,\n+ -1.601745692712991078208e-2,\n+ 1.496414899205908021882e-3,\n+ -8.462452563778485013756e-5,\n+ 2.728938403476726394024e-6,\n+ -4.239462431819542051337e-8,\n+ ]\n+ return _eval_expint_k(A, B, x)\n+\n+\n+def _expint6(x):\n+ # 32 <= x <= 64\n+ A = [\n+ 1.212561118105456670844e-1,\n+ -5.823133179043894485122e-1,\n+ 2.348887314557016779211e-1,\n+ -3.040034318113248237280e-2,\n+ 1.510082146865190661777e-3,\n+ -2.523137095499571377122e-5,\n+ ]\n+ B = [\n+ 1.0,\n+ -1.002252150365854016662e0,\n+ 2.928709694872224144953e-1,\n+ -3.337004338674007801307e-2,\n+ 1.560544881127388842819e-3,\n+ -2.523137093603234562648e-5,\n+ ]\n+ return _eval_expint_k(A, B, x)\n+\n+\n+def _expint7(x):\n+ # x > 64\n+ A = [\n+ -7.657847078286127362028e-1,\n+ 6.886192415566705051750e-1,\n+ -2.132598113545206124553e-1,\n+ 3.346107552384193813594e-2,\n+ -3.076541477344756050249e-3,\n+ 1.747119316454907477380e-4,\n+ -6.103711682274170530369e-6,\n+ 1.218032765428652199087e-7,\n+ -1.086076102793290233007e-9,\n+ ]\n+ B = [\n+ 1.0,\n+ -1.888802868662308731041e0,\n+ 1.066691687211408896850e0,\n+ -2.751915982306380647738e-1,\n+ 3.930852688233823569726e-2,\n+ -3.414684558602365085394e-3,\n+ 1.866844370703555398195e-4,\n+ -6.345146083130515357861e-6,\n+ 1.239754287483206878024e-7,\n+ -1.086076102793126632978e-9,\n+ ]\n+ return _eval_expint_k(A, B, x)\n+\n+\n+def _expi_pos(x):\n+ # x > 0\n+ _c = _constant_like\n+ conds = [(_c(x, 0) < x) & (x <= _c(x, 2))] + [\n+ (_c(x, 2 ** i) < x) & (x <= _c(x, 2 ** (i + 1))) for i in range(1, 6)\n+ ]\n+ return jnp.piecewise(\n+ x,\n+ conds,\n+ [_expint1, _expint2, _expint3, _expint4, _expint5, _expint6, _expint7],\n+ )\n+\n+\n+@_wraps(osp_special.expi)\n+@api.custom_jvp\n+@jit\n+def expi(x):\n+ (x,) = _promote_args_inexact(\"expi\", x)\n+ ret = jnp.piecewise(x, [x < 0], [lambda x: -exp1(-x), _expi_pos])\n+ return ret\n+\n+\n+@expi.defjvp\n+@jit\n+def expi_jvp(primals, tangents):\n+ (x,) = primals\n+ (x_dot,) = tangents\n+ return expi(x), jnp.exp(x) / x * x_dot\n+\n+\n+def _expn1(n, x):\n+ # exponential integral En\n+ _c = _constant_like\n+ x = jnp.array(x)\n+ MACHEP = jnp.finfo(x.dtype).eps\n+\n+ zero = _c(x, 0.0)\n+ one = _c(x, 1.0)\n+ psi = -jnp.euler_gamma - jnp.log(x)\n+ psi = lax.fori_loop(_c(n, 1), n, lambda i, psi: psi + one / i, psi)\n+ n1 = jnp.where(n == _c(n, 1), one + one, n)\n+ init = dict(\n+ x=x,\n+ z=-x,\n+ xk=zero,\n+ yk=one,\n+ pk=one - n,\n+ ans=jnp.where(n == _c(n, 1), zero, one / (one - n1)),\n+ t=jnp.inf,\n+ )\n+\n+ def body(d):\n+ d[\"xk\"] += one\n+ d[\"yk\"] *= d[\"z\"] / d[\"xk\"]\n+ d[\"pk\"] += one\n+ d[\"ans\"] += jnp.where(d[\"pk\"] != zero, d[\"yk\"] / d[\"pk\"], zero)\n+ d[\"t\"] = jnp.where(d[\"ans\"] != zero, abs(d[\"yk\"] / d[\"ans\"]), one)\n+ return d\n+\n+ def cond(d):\n+ return (d[\"x\"] > _c(d[\"x\"], 0.0)) & (d[\"t\"] > MACHEP)\n+\n+ d = lax.while_loop(cond, body, init)\n+ t = n\n+ r = n - _c(n, 1)\n+ return d[\"z\"] ** r * psi / jnp.exp(gammaln(t)) - d[\"ans\"]\n+\n+\n+def _expn2(n, x):\n+ # x > 1.\n+ _c = _constant_like\n+ BIG = _c(x, 1.44115188075855872e17)\n+ MACHEP = jnp.finfo(BIG.dtype).eps # ?\n+ zero = _c(x, 0.0)\n+ one = _c(x, 1.0)\n+\n+ init = dict(\n+ k=_c(n, 1),\n+ pkm2=one,\n+ qkm2=x,\n+ pkm1=one,\n+ qkm1=x + n,\n+ ans=one / (x + n),\n+ t=_c(x, jnp.inf),\n+ r=zero,\n+ x=x,\n+ )\n+\n+ def body(d):\n+ x = d[\"x\"]\n+ d[\"k\"] += _c(d[\"k\"], 1)\n+ k = d[\"k\"]\n+ odd = k % _c(k, 2) == _c(k, 1)\n+ yk = jnp.where(odd, one, x)\n+ xk = jnp.where(odd, n + (k - _c(k, 1)) / _c(k, 2), k / _c(k, 2))\n+ pk = d[\"pkm1\"] * yk + d[\"pkm2\"] * xk\n+ qk = d[\"qkm1\"] * yk + d[\"qkm2\"] * xk\n+ nz = qk != zero\n+ d[\"r\"] = r = jnp.where(nz, pk / qk, d[\"r\"])\n+ d[\"t\"] = jnp.where(nz, abs((d[\"ans\"] - r) / r), one)\n+ d[\"ans\"] = jnp.where(nz, r, d[\"ans\"])\n+ d[\"pkm2\"] = d[\"pkm1\"]\n+ d[\"pkm1\"] = pk\n+ d[\"qkm2\"] = d[\"qkm1\"]\n+ d[\"qkm1\"] = qk\n+ is_big = abs(pk) > BIG\n+ for s in \"pq\":\n+ for i in \"12\":\n+ key = s + \"km\" + i\n+ d[key] = jnp.where(is_big, d[key] / BIG, d[key])\n+ return d\n+\n+ def cond(d):\n+ return (d[\"x\"] > _c(d[\"k\"], 0)) & (d[\"t\"] > MACHEP)\n+\n+ d = lax.while_loop(cond, body, init)\n+ return d[\"ans\"] * jnp.exp(-x)\n+\n+\n+def _expn3(n, x):\n+ # n >= 5000\n+ _c = _constant_like\n+ one = _c(x, 1.0)\n+ xk = x + n\n+ yk = one / (xk * xk)\n+ t = n\n+ ans = yk * t * (_c(x, 6) * x * x - _c(x, 8) * t * x + t * t)\n+ ans = yk * (ans + t * (t - _c(x, 2) * x))\n+ ans = yk * (ans + t)\n+ return (ans + one) * jnp.exp(-x) / xk\n+\n+\n+@_wraps(osp_special.expn)\n+@partial(api.custom_jvp, nondiff_argnums=(0,))\n+@jnp.vectorize\n+@jit\n+def expn(n, x):\n+ n, x = _promote_args_inexact(\"expn\", n, x)\n+ _c = _constant_like\n+ zero = _c(x, 0)\n+ one = _c(x, 1)\n+ conds = [\n+ (n < _c(n, 0)) | (x < zero),\n+ (x == zero) & (n < _c(n, 2)),\n+ (x == zero) & (n >= _c(n, 2)),\n+ (n == _c(n, 0)) & (x >= zero),\n+ (n >= _c(n, 5000)),\n+ (x > one),\n+ ]\n+ n1 = jnp.where(n == _c(n, 1), n + n, n)\n+ vals = [\n+ jnp.nan,\n+ jnp.inf,\n+ one / n1, # prevent div by zero\n+ jnp.exp(-x) / x,\n+ partial(_expn3, n),\n+ partial(_expn2, n),\n+ partial(_expn1, n),\n+ ]\n+ ret = jnp.piecewise(x, conds, vals)\n+ return ret\n+\n+\n+@expn.defjvp\n+@jit\n+def expn_jvp(n, primals, tangents):\n+ (x,), (x_dot,) = primals, tangents\n+ return expn(n, x), lax.mul(\n+ lax.neg(x_dot), expn(lax.sub(n, _constant_like(n, 1)), x)\n+ )\n+\n+\n+@_wraps(osp_special.exp1)\n+def exp1(x):\n+ (x,) = _promote_args_inexact(\"exp1\", x)\n+ return expn(1, x)\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/special.py", "new_path": "jax/scipy/special.py", "diff": "@@ -22,7 +22,10 @@ from jax._src.scipy.special import (\nerf,\nerfc,\nerfinv,\n+ exp1,\n+ expi,\nexpit,\n+ expn,\ngammainc,\ngammaincc,\ngammaln,\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -138,6 +138,10 @@ JAX_SPECIAL_FUNCTION_RECORDS = [\n# TODO: enable gradient test for zeta by restricting the domain of\n# of inputs to some reasonable intervals\nop_record(\"zeta\", 2, float_dtypes, jtu.rand_positive, False),\n+ # TODO: float64 produces aborts on gpu, potentially related to use of jnp.piecewise\n+ op_record(\"expi\", 1, [np.float32], jtu.rand_default, True),\n+ op_record(\"exp1\", 1, [np.float32], jtu.rand_positive, True),\n+ op_record(\"expn\", 2, (int_dtypes, [np.float32]), jtu.rand_positive, True, (0,)),\n]\n" } ]
Python
Apache License 2.0
google/jax
add support for scipy.special.{expn,expi,exp1}
260,510
24.08.2021 17:46:34
25,200
0fa70084a395ddd5ec2bd18250a73f9e3f7a6188
Pass `x` into transpose in autodidax
[ { "change_type": "MODIFY", "old_path": "docs/autodidax.ipynb", "new_path": "docs/autodidax.ipynb", "diff": "\"def reduce_sum(x, axis=None): return bind1(reduce_sum_p, x, axis=axis)\\n\",\n\"def greater(x, y): return bind1(greater_p, x, y)\\n\",\n\"def less(x, y): return bind1(less_p, x, y)\\n\",\n- \"def transpose(x, perm): return bind1(transpose_p, perm=perm)\\n\",\n+ \"def transpose(x, perm): return bind1(transpose_p, x, perm=perm)\\n\",\n\"def broadcast(x, shape, axes): return bind1(broadcast_p, x, shape=shape, axes=axes)\\n\",\n\"\\n\",\n\"def bind1(prim, *args, **params):\\n\",\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.md", "new_path": "docs/autodidax.md", "diff": "@@ -107,7 +107,7 @@ def cos(x): return bind1(cos_p, x)\ndef reduce_sum(x, axis=None): return bind1(reduce_sum_p, x, axis=axis)\ndef greater(x, y): return bind1(greater_p, x, y)\ndef less(x, y): return bind1(less_p, x, y)\n-def transpose(x, perm): return bind1(transpose_p, perm=perm)\n+def transpose(x, perm): return bind1(transpose_p, x, perm=perm)\ndef broadcast(x, shape, axes): return bind1(broadcast_p, x, shape=shape, axes=axes)\ndef bind1(prim, *args, **params):\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.py", "new_path": "docs/autodidax.py", "diff": "@@ -97,7 +97,7 @@ def cos(x): return bind1(cos_p, x)\ndef reduce_sum(x, axis=None): return bind1(reduce_sum_p, x, axis=axis)\ndef greater(x, y): return bind1(greater_p, x, y)\ndef less(x, y): return bind1(less_p, x, y)\n-def transpose(x, perm): return bind1(transpose_p, perm=perm)\n+def transpose(x, perm): return bind1(transpose_p, x, perm=perm)\ndef broadcast(x, shape, axes): return bind1(broadcast_p, x, shape=shape, axes=axes)\ndef bind1(prim, *args, **params):\n" } ]
Python
Apache License 2.0
google/jax
Pass `x` into transpose in autodidax
260,296
25.08.2021 12:50:28
25,200
00435bd9002e8840064640c9641150c0714635fc
Make `input_shape` explicitly integer-typed in `_reduce_jvp` to avoid accidental float shapes when primal shape is `()`. Example where this fails: `grad(jnp.prod)(jnp.ones(()))`. Add a test.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -5353,7 +5353,7 @@ def _reduction_computation(c, jaxpr, consts, init_values, singleton=True):\nreturn subc.build(out_nodes)\ndef _reduce_jvp(reducer, init_values, primals, tangents, axes):\n- input_shape = np.array(primals[0].shape)\n+ input_shape = np.array(primals[0].shape, dtype=np.int_)\nn = np.prod(input_shape[list(axes)])\nnon_axes = np.delete(np.arange(len(input_shape)), axes)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_autodiff_test.py", "new_path": "tests/lax_autodiff_test.py", "diff": "@@ -643,6 +643,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n]\nfor dtype in dtypes\nfor shape, dims in [\n+ [(), ()],\n[(3, 4, 5), ()],\n[(3, 4, 5), (0,)],\n[(3, 4, 5), (1, 2)],\n" } ]
Python
Apache License 2.0
google/jax
Make `input_shape` explicitly integer-typed in `_reduce_jvp` to avoid accidental float shapes when primal shape is `()`. Example where this fails: `grad(jnp.prod)(jnp.ones(()))`. Add a test.
260,335
25.08.2021 20:46:11
25,200
2d28951ba4705f41d0f18d9657dbc82b759240f8
address comments form
[ { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -45,6 +45,7 @@ from ._src.config import (\nfrom ._src.api import (\nad, # TODO(phawkins): update users to avoid this.\ncheckpoint,\n+ checkpoint_policies,\nclosure_convert,\ncurry, # TODO(phawkins): update users to avoid this.\ncustom_ivjp,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -29,6 +29,7 @@ import itertools as it\nimport sys\nimport threading\nimport weakref\n+import types\nfrom typing import (Any, Callable, Iterable, NamedTuple, Mapping, Optional,\nSequence, Tuple, TypeVar, Union, overload)\nfrom warnings import warn\n@@ -36,6 +37,7 @@ from warnings import warn\nimport numpy as np\nfrom contextlib import contextmanager, ExitStack\n+import jax\nfrom .. import core\nfrom .. import lib\nfrom .. import linear_util as lu\n@@ -2686,11 +2688,12 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\n``pmap``, CSE can defeat the purpose of this decorator. But in some\nsettings, like when used inside a ``scan``, this CSE prevention mechanism\nis unnecessary, in which case ``prevent_cse`` can be set to False.\n- policy: Optional, callable which takes as input a type-level specification\n- of a first-order primitive application and returns a boolean indicating\n- whether the corresponding output value(s) can be saved as a residual (or,\n- if not, instead must be recomputed in the (co)tangent computation).\n- Experimental.\n+ policy: This is an experimental feature and the API is likely to change.\n+ Optional callable, one of the attributes of ``jax.checkpoint_policies``,\n+ which takes as input a type-level specification of a first-order primitive\n+ application and returns a boolean indicating whether the corresponding\n+ output value(s) can be saved as a residual (or, if not, instead must be\n+ recomputed in the (co)tangent computation).\nReturns:\nA function (callable) with the same input/output behavior as ``fun`` but\n@@ -2748,6 +2751,12 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\nreturn fun_remat\nremat = checkpoint\n+checkpoint_policies = types.SimpleNamespace(\n+ checkpoint_dots=\n+ lambda prim, *_, **__: prim in {jax._src.lax.lax.dot_general_p,\n+ jax._src.lax.lax.conv_general_dilated_p},\n+)\n+\ndef named_call(\nfun: Callable[..., Any],\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/custom_derivatives.py", "new_path": "jax/_src/custom_derivatives.py", "diff": "@@ -393,7 +393,7 @@ def custom_jvp_jaxpr_custom_partial_eval_rule(\ninst_out = [True] * len(eqn.outvars)\nreturn eqn, eqn, unks_out, inst_out, new_inst\npe.partial_eval_jaxpr_custom_rules[custom_jvp_call_jaxpr_p] = \\\n- custom_jvp_jaxpr_custom_partial_eval_rule\n+ custom_jvp_jaxpr_custom_partial_eval_rule # type: ignore\n### VJPs\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/util.py", "new_path": "jax/_src/util.py", "diff": "@@ -17,7 +17,8 @@ import functools\nimport itertools as it\nimport operator\nimport types\n-from typing import Any, Callable, List, Tuple\n+from typing import (Any, Callable, List, Tuple, Generic, TypeVar, Set, Iterator,\n+ Sequence)\nfrom absl import logging\nimport numpy as np\n@@ -25,6 +26,7 @@ import numpy as np\nfrom jax.config import config\npartial = functools.partial\n+Seq = Sequence\ndef safe_zip(*args):\n@@ -74,12 +76,12 @@ def split_list(args, ns):\nlists.append(args)\nreturn lists\n-def partition_list(bs: List[bool], l: List[Any]) -> Tuple[List[Any], List[Any]]:\n+def partition_list(bs: Seq[bool], l: Seq[Any]) -> Tuple[List[Any], List[Any]]:\nassert len(bs) == len(l)\n- lists = lst1, lst2 = [], [] # type: ignore\n+ lists = [], [] # type: ignore\nfor b, x in zip(bs, l):\nlists[b].append(x)\n- return lst1, lst2\n+ return lists\ndef split_dict(dct, names):\ndct = dict(dct)\n@@ -415,3 +417,31 @@ def distributed_debug_log(*pairs):\nlines.append(f\"{e}\")\nlines.append(\"DISTRIBUTED_DEBUG_END\")\nlogging.warning(\"\\n\".join(lines))\n+\n+T = TypeVar('T')\n+\n+class OrderedSet(Generic[T]):\n+ elts_set: Set[T]\n+ elts_list: List[T]\n+\n+ def __init__(self):\n+ self.elts_set = set()\n+ self.elts_list = []\n+\n+ def add(self, elt: T) -> None:\n+ if elt not in self.elts_set:\n+ self.elts_set.add(elt)\n+ self.elts_list.append(elt)\n+\n+ def update(self, elts: Seq[T]) -> None:\n+ for e in elts:\n+ self.add(e)\n+\n+ def __iter__(self) -> Iterator[T]:\n+ return iter(self.elts_list)\n+\n+ def __len__(self) -> int:\n+ return len(self.elts_list)\n+\n+ def __contains__(self, elt: T) -> bool:\n+ return elt in self.elts_set\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -18,7 +18,7 @@ from collections import namedtuple\nimport contextlib\nimport functools\nfrom typing import (Any, Callable, Dict, NamedTuple, Optional, Sequence, Tuple,\n- List, Union, cast, Set)\n+ List, Union, cast)\nfrom weakref import ref\nimport numpy as np\n@@ -30,7 +30,8 @@ from jax._src.ad_util import Zero\nfrom ..api_util import flattened_fun_in_tree\nfrom .._src.tree_util import PyTreeDef, tree_unflatten, tree_leaves\nfrom .._src.util import (unzip2, safe_zip, safe_map, toposort, partial,\n- split_list, partition_list, cache, as_hashable_function)\n+ split_list, partition_list, cache, OrderedSet,\n+ as_hashable_function)\nfrom ..core import (Trace, Tracer, Jaxpr, Literal, get_aval, AbstractValue,\nunit, unitvar, abstract_unit, ClosedJaxpr, new_jaxpr_eqn,\ndropvar, ConcreteArray, raise_to_shaped, Var, Atom,\n@@ -780,19 +781,19 @@ def _remat_partial_eval(trace, _, f, tracers, params):\nin_unknowns = ([False] * len(consts) +\n[not t.is_known() for t in it.chain(env_tracers, tracers)])\nif params['policy']:\n- # unzip into jaxpr1 and jaxpr2\n- jaxpr1_, jaxpr2_, out_unknowns, out_inst, _ = _partial_eval_jaxpr_custom(\n+ # unzip into known and jaxpr_unknown\n+ jaxpr_known, jaxpr_unknown, out_unknowns, out_inst, _ = _partial_eval_jaxpr_custom(\njaxpr, in_unknowns, params['policy'])\n- jaxpr1, in_used1 = dce_jaxpr(jaxpr1_, [True] * len(jaxpr1_.outvars))\n- _, used_outs2 = partition_list(out_inst, out_unknowns)\n- jaxpr2, in_used2 = dce_jaxpr(jaxpr2_, used_outs2)\n+ jaxpr_known, in_used_known = dce_jaxpr(jaxpr_known, [True] * len(jaxpr_known.outvars))\n+ _, used_outs_unknown = partition_list(out_inst, out_unknowns)\n+ jaxpr_unknown, in_used_unknown = dce_jaxpr(jaxpr_unknown, used_outs_unknown)\n# compute known outputs and residuals (hoisted out of a remat_call)\nif concrete: raise NotImplementedError # TODO(mattjj)\n_, in_consts_ = unzip2(t.pval for t in it.chain(env_tracers, tracers)\nif t.pval.is_known())\n- _, in_consts = partition_list(in_used1, [*consts, *in_consts_])\n- out_consts = core.eval_jaxpr(jaxpr1, (), *in_consts)\n+ _, in_consts = partition_list(in_used_known, [*consts, *in_consts_])\n+ out_consts = core.eval_jaxpr(jaxpr_known, (), *in_consts)\nout_consts_ = iter(out_consts)\n# reconstruct known outs, inserting units\nouts1 = [unit if x.aval is abstract_unit else next(out_consts_)\n@@ -807,10 +808,10 @@ def _remat_partial_eval(trace, _, f, tracers, params):\nconst_tracers = map(trace.new_instantiated_const, consts)\nin_jaxpr_tracers = [*res_tracers, *const_tracers, *env_tracers,\n*instantiated_tracers]\n- _, in_jaxpr_tracers = partition_list(in_used2, in_jaxpr_tracers)\n+ _, in_jaxpr_tracers = partition_list(in_used_unknown, in_jaxpr_tracers)\nout_jaxpr_tracers = [JaxprTracer(trace, PartialVal.unknown(x.aval), None)\n- for x in jaxpr2.outvars]\n- new_params = dict(params, call_jaxpr=jaxpr2, differentiated=True)\n+ for x in jaxpr_unknown.outvars]\n+ new_params = dict(params, call_jaxpr=jaxpr_unknown, differentiated=True)\nrecipe = new_eqn_recipe(in_jaxpr_tracers, out_jaxpr_tracers, remat_call_p,\nnew_params, source_info_util.current())\nfor t in out_jaxpr_tracers: t.recipe = recipe\n@@ -875,11 +876,11 @@ def _zip_knowns(known_list, unknown_list, which_unknown: Sequence[bool]):\ndef _partial_eval_jaxpr_custom(\n- jaxpr: Jaxpr, in_unknowns: List[bool], saveable: Callable[..., bool],\n- ) -> Tuple[Jaxpr, Jaxpr, List[bool], List[bool], int]:\n+ jaxpr: Jaxpr, in_unknowns: Sequence[bool], saveable: Callable[..., bool],\n+ ) -> Tuple[Jaxpr, Jaxpr, Sequence[bool], Sequence[bool], int]:\nif jaxpr.constvars: raise NotImplementedError # TODO\nenv: Dict[Var, Tuple[bool, bool]] = {}\n- residuals: Set[Var] = set()\n+ residuals: OrderedSet[Var] = OrderedSet()\ndef read(x: Atom) -> Tuple[bool, bool]:\nif type(x) is Var:\n@@ -895,7 +896,7 @@ def _partial_eval_jaxpr_custom(\nresiduals.add(x)\nreturn x\n- eqns1, eqns2 = [], []\n+ known_eqns, staged_eqns = [], []\nwrite(False, True, unitvar)\nmap(write, in_unknowns, [True] * len(in_unknowns), jaxpr.invars)\nfor eqn in jaxpr.eqns:\n@@ -903,37 +904,37 @@ def _partial_eval_jaxpr_custom(\nrule = partial_eval_jaxpr_custom_rules.get(eqn.primitive)\nif rule:\neqn1, eqn2, unks_out, inst_out, res = rule(saveable, unks_in, inst_in, eqn)\n- eqn1 and eqns1.append(eqn1); eqn2 and eqns2.append(eqn2) # type: ignore\n+ eqn1 and known_eqns.append(eqn1); eqn2 and staged_eqns.append(eqn2) # type: ignore\nresiduals.update(res)\nmap(write, unks_out, inst_out, eqn.outvars)\nelif any(unks_in):\ninputs = map(ensure_instantiated, inst_in, eqn.invars)\n- eqns2.append(new_jaxpr_eqn(inputs, eqn.outvars, eqn.primitive,\n+ staged_eqns.append(new_jaxpr_eqn(inputs, eqn.outvars, eqn.primitive,\neqn.params, eqn.source_info))\nmap(partial(write, True, True), eqn.outvars)\nelse:\n- eqns1.append(eqn)\n+ known_eqns.append(eqn)\nif saveable(eqn.primitive, *[x.aval for x in eqn.invars], **eqn.params):\nmap(partial(write, False, False), eqn.outvars)\nelse:\ninputs = map(ensure_instantiated, inst_in, eqn.invars)\n- eqns2.append(new_jaxpr_eqn(inputs, eqn.outvars, eqn.primitive,\n+ staged_eqns.append(new_jaxpr_eqn(inputs, eqn.outvars, eqn.primitive,\neqn.params, eqn.source_info))\nmap(partial(write, False, True), eqn.outvars)\nout_unknowns, out_inst = unzip2(map(read, jaxpr.outvars))\nassert all(type(v) is Var for v in residuals), residuals\n- ins1, _ = partition_list(in_unknowns, jaxpr.invars)\n- outs1_, _ = partition_list(out_unknowns, jaxpr.outvars)\n- outs1 = [x for x in outs1_ if x.aval is not abstract_unit]\n- jaxpr1 = Jaxpr((), ins1, [*outs1, *residuals], eqns1)\n- config.jax_enable_checks and core.check_jaxpr(jaxpr1)\n+ ins_known, _ = partition_list(in_unknowns, jaxpr.invars)\n+ outs_known_, _ = partition_list(out_unknowns, jaxpr.outvars)\n+ outs_known = [x for x in outs_known_ if x.aval is not abstract_unit]\n+ jaxpr_known = Jaxpr((), ins_known, [*outs_known, *residuals], known_eqns)\n+ config.jax_enable_checks and core.check_jaxpr(jaxpr_known)\n- _, outs2 = partition_list(out_inst, jaxpr.outvars)\n- jaxpr2 = Jaxpr((), [*residuals, *jaxpr.invars], outs2, eqns2)\n- config.jax_enable_checks and core.check_jaxpr(jaxpr2)\n+ _, outs_staged = partition_list(out_inst, jaxpr.outvars)\n+ jaxpr_staged = Jaxpr((), [*residuals, *jaxpr.invars], outs_staged, staged_eqns)\n+ config.jax_enable_checks and core.check_jaxpr(jaxpr_staged)\n- return jaxpr1, jaxpr2, out_unknowns, out_inst, len(residuals)\n+ return jaxpr_known, jaxpr_staged, out_unknowns, out_inst, len(residuals)\n# A primitive rule for policy-driven partial evaluation returns a 5-tuple\n# with the components representing, respectively:\n@@ -946,14 +947,14 @@ def _partial_eval_jaxpr_custom(\n# plumbed as outputs of the 'known' side jaxpr and added as input binders to\n# the 'unknown' jaxpr).\nPartialEvalCustomResult = Tuple[Optional[JaxprEqn], Optional[JaxprEqn],\n- List[bool], List[bool], List[Var]]\n+ Sequence[bool], Sequence[bool], List[Var]]\nPartialEvalCustomRule = Callable[\n- [Callable[..., bool], List[bool], List[bool], JaxprEqn],\n+ [Callable[..., bool], Sequence[bool], Sequence[bool], JaxprEqn],\nPartialEvalCustomResult]\npartial_eval_jaxpr_custom_rules: Dict[Primitive, PartialEvalCustomRule] = {}\ndef partial_eval_jaxpr_custom_rule_not_implemented(\n- saveable: Callable[..., bool], unks_in: List[bool], inst_in: List[bool],\n+ saveable: Callable[..., bool], unks_in: Sequence[bool], inst_in: Sequence[bool],\neqn: JaxprEqn) -> PartialEvalCustomResult:\nraise NotImplementedError\n@@ -963,25 +964,25 @@ ParamsUpdater = Callable[[List[bool], int, dict, dict], Tuple[dict, dict]]\ndef call_partial_eval_custom_rule(\nparams_updater: ParamsUpdater, saveable: Callable[..., bool],\nunks_in: List[bool], inst_in: List[bool], eqn: JaxprEqn\n- ) -> Tuple[JaxprEqn, JaxprEqn, List[bool], List[bool], List[Var]]:\n- jaxpr1, jaxpr2, unks_out, inst_out, num_res = _partial_eval_jaxpr_custom(\n+ ) -> Tuple[JaxprEqn, JaxprEqn, Sequence[bool], Sequence[bool], List[Var]]:\n+ jaxpr_known, jaxpr_staged, unks_out, inst_out, num_res = _partial_eval_jaxpr_custom(\neqn.params['call_jaxpr'], unks_in, saveable)\n- ins1, _ = partition_list(unks_in, eqn.invars)\n- out_binders1, _ = partition_list(unks_out, eqn.outvars)\n- _, out_binders2 = partition_list(inst_out, eqn.outvars)\n- newvar = core.gensym([jaxpr1, jaxpr2])\n- residuals = [newvar(v.aval) for v in jaxpr2.invars[:num_res]]\n- params1 = dict(eqn.params, call_jaxpr=jaxpr1)\n- params2 = dict(eqn.params, call_jaxpr=jaxpr2)\n- params1, params2 = params_updater(unks_in, num_res, params1, params2)\n- eqn1 = JaxprEqn(ins1, [*out_binders1, *residuals], eqn.primitive,\n- params1, eqn.source_info)\n- eqn2 = JaxprEqn([*residuals, *eqn.invars], out_binders2, eqn.primitive,\n- params2, eqn.source_info)\n- assert len(eqn2.invars) == len(jaxpr2.invars)\n+ ins_known, _ = partition_list(unks_in, eqn.invars)\n+ out_binders_known, _ = partition_list(unks_out, eqn.outvars)\n+ _, out_binders_staged = partition_list(inst_out, eqn.outvars)\n+ newvar = core.gensym([jaxpr_known, jaxpr_staged])\n+ residuals = [newvar(v.aval) for v in jaxpr_staged.invars[:num_res]]\n+ params_known = dict(eqn.params, call_jaxpr=jaxpr_known)\n+ params_staged = dict(eqn.params, call_jaxpr=jaxpr_staged)\n+ params_known, params_staged = params_updater(unks_in, num_res, params_known, params_staged)\n+ eqn_known = JaxprEqn(ins_known, [*out_binders_known, *residuals],\n+ eqn.primitive, params_known, eqn.source_info)\n+ eqn_staged = JaxprEqn([*residuals, *eqn.invars], out_binders_staged,\n+ eqn.primitive, params_staged, eqn.source_info)\n+ assert len(eqn_staged.invars) == len(jaxpr_staged.invars)\nnew_inst = [x for x, inst in zip(eqn.invars, inst_in)\nif type(x) is Var and not inst]\n- return eqn1, eqn2, unks_out, inst_out, new_inst + residuals\n+ return eqn_known, eqn_staged, unks_out, inst_out, new_inst + residuals\npartial_eval_jaxpr_custom_rules[core.call_p] = \\\npartial(call_partial_eval_custom_rule, lambda _, __, x, y: (x, y))\npartial_eval_jaxpr_custom_rules[remat_call_p] = \\\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -990,15 +990,15 @@ ad.primitive_transposes[xla_call_p] = partial(ad.call_transpose, xla_call_p)\ndef _xla_call_partial_eval_custom_params_updater(\n- unks_in: List[bool], num_res: int, params1: dict, params2: dict\n+ unks_in: List[bool], num_res: int, params_known: dict, params_staged: dict\n) -> Tuple[dict, dict]:\n- # pruned inputs to jaxpr1 according to unks_in, so prune donated_invars1\n- donated_invars1, _ = partition_list(unks_in, params1['donated_invars'])\n- new_params1 = dict(params1, donated_invars=tuple(donated_invars1))\n- # added num_res new inputs to jaxpr2, so extend donated_invars2\n- donated_invars2 = [*([False] * num_res), *params2['donated_invars']]\n- new_params2 = dict(params2, donated_invars=tuple(donated_invars2))\n- return new_params1, new_params2\n+ # pruned inputs to jaxpr_known according to unks_in, so prune donated_invars\n+ donated_invars_known, _ = partition_list(unks_in, params_known['donated_invars'])\n+ new_params_known = dict(params_known, donated_invars=tuple(donated_invars_known))\n+ # added num_res new inputs to jaxpr_staged, so extend donated_invars\n+ donated_invars_staged = [*([False] * num_res), *params_staged['donated_invars']]\n+ new_params_staged = dict(params_staged, donated_invars=tuple(donated_invars_staged))\n+ return new_params_known, new_params_staged\npe.partial_eval_jaxpr_custom_rules[xla_call_p] = \\\npartial(pe.call_partial_eval_custom_rule,\n_xla_call_partial_eval_custom_params_updater)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3501,9 +3501,7 @@ class RematTest(jtu.JaxTestCase):\njtu.check_grads(f, (3.,), order=2, modes=['fwd', 'rev'])\ndef test_remat_checkpoint_dots(self):\n- checkpoint_dots = lambda prim, *_, **__: str(prim) == 'dot_general'\n-\n- @partial(api.remat, policy=checkpoint_dots)\n+ @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\ndef f(x):\nx = jnp.dot(x, x)\nx = jnp.sin(x)\n@@ -3520,12 +3518,10 @@ class RematTest(jtu.JaxTestCase):\njtu.check_grads(f, (jnp.ones((2, 2)),), order=2, modes=['fwd', 'rev'])\ndef test_remat_checkpoint_dots_inside_scan(self):\n- checkpoint_dots = lambda prim, *_, **__: str(prim) == 'dot_general'\n-\nx = jnp.ones((5,))\ndef f(W):\n- @partial(api.remat, policy=checkpoint_dots)\n+ @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\ndef f(x):\nx = jnp.sin(jnp.dot(x, W))\nx = jnp.sin(jnp.dot(x, W))\n" } ]
Python
Apache License 2.0
google/jax
address comments form @apaszke
260,335
27.08.2021 16:59:54
25,200
a56a1679ab88dd2340429a5bcd0d91bd2186e6aa
fix constants problem
[ { "change_type": "MODIFY", "old_path": "jax/_src/traceback_util.py", "new_path": "jax/_src/traceback_util.py", "diff": "@@ -23,6 +23,7 @@ from jax._src import util\n_exclude_paths = [__file__, util.__file__]\ndef register_exclusion(path):\n+ return\n_exclude_paths.append(path)\n_jax_message_append = (\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -771,7 +771,7 @@ def _remat_partial_eval(trace, _, f, tracers, params):\ninstantiated_tracers = map(trace.instantiate_const_abstracted, tracers)\n# Using the instantiated tracers, run call_bind like JaxprTrace.process_call.\n- in_pvals = [t.pval for t in instantiated_tracers]\n+ in_pvals = [PartialVal.unknown(t.pval[0]) for t in instantiated_tracers]\njaxpr, eval_out_pvals, consts, env_tracers = trace.partial_eval(\nf, in_pvals, partial(remat_call_p.bind, **params), instantiate=False)\njaxpr = convert_constvars_jaxpr(jaxpr)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3517,6 +3517,24 @@ class RematTest(jtu.JaxTestCase):\nself.assertEqual(jaxpr_text.count(' dot_'), 6)\njtu.check_grads(f, (jnp.ones((2, 2)),), order=2, modes=['fwd', 'rev'])\n+ def test_remat_checkpoint_dots_jit(self):\n+ @api.jit\n+ @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n+ def f(x):\n+ x = jnp.dot(x, x)\n+ x = jnp.sin(x * 1e-3)\n+ x = jnp.dot(x, x)\n+ x = jnp.sin(x * 1e-3)\n+ x = jnp.dot(x, x)\n+ x = jnp.sin(x * 1e-3)\n+ return x\n+\n+ _, f_lin = api.linearize(f, jnp.ones((2, 2)))\n+ jaxpr_text = str(f_lin.func.args[0])\n+ self.assertEqual(jaxpr_text.count(' sin '), 2)\n+ self.assertEqual(jaxpr_text.count(' dot_'), 6)\n+ jtu.check_grads(f, (jnp.ones((2, 2)),), order=2, modes=['fwd', 'rev'])\n+\ndef test_remat_checkpoint_dots_inside_scan(self):\nx = jnp.ones((5,))\n" } ]
Python
Apache License 2.0
google/jax
fix constants problem
260,335
27.08.2021 17:42:42
25,200
9f919c69e43d6b967a040b16678814bd8dd78c32
fix custom_vjp issue?
[ { "change_type": "MODIFY", "old_path": "jax/_src/custom_derivatives.py", "new_path": "jax/_src/custom_derivatives.py", "diff": "@@ -681,6 +681,9 @@ xla.initial_style_translations[custom_vjp_call_jaxpr_p] = \\\nbatching.primitive_batchers[ad.custom_lin_p] = ad._raise_custom_vjp_error_on_jvp\nxla.translations[ad.custom_lin_p] = ad._raise_custom_vjp_error_on_jvp\n+pe.partial_eval_jaxpr_custom_rules[custom_vjp_call_jaxpr_p] = \\\n+ custom_jvp_jaxpr_custom_partial_eval_rule # type: ignore\n+\ndef custom_gradient(fun):\n\"\"\"Convenience function for defining custom VJP rules (aka custom gradients).\n@@ -706,7 +709,9 @@ def custom_gradient(fun):\nover intermediate values computed when evaluating the function to be\ndifferentiated. That is, use lexical closure to share work between the forward\npass and the backward pass of reverse-mode automatic differentiation. However,\n- it cannot support Python control flow.\n+ it cannot perform Python control flow which depends on the values of the\n+ closed-over intermediate values or its cotangent arguments; if the function\n+ includes such control flow, an error is raised.\nArgs:\nfun: a Python callable specifying both the mathematical function to be\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/traceback_util.py", "new_path": "jax/_src/traceback_util.py", "diff": "@@ -23,7 +23,6 @@ from jax._src import util\n_exclude_paths = [__file__, util.__file__]\ndef register_exclusion(path):\n- return\n_exclude_paths.append(path)\n_jax_message_append = (\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -878,7 +878,7 @@ def _zip_knowns(known_list, unknown_list, which_unknown: Sequence[bool]):\ndef _partial_eval_jaxpr_custom(\njaxpr: Jaxpr, in_unknowns: Sequence[bool], saveable: Callable[..., bool],\n) -> Tuple[Jaxpr, Jaxpr, Sequence[bool], Sequence[bool], int]:\n- if jaxpr.constvars: raise NotImplementedError # TODO\n+ if jaxpr.constvars: raise NotImplementedError # TODO(mattjj)\nenv: Dict[Var, Tuple[bool, bool]] = {}\nresiduals: OrderedSet[Var] = OrderedSet()\n@@ -985,15 +985,17 @@ def call_partial_eval_custom_rule(\nreturn eqn_known, eqn_staged, unks_out, inst_out, new_inst + residuals\npartial_eval_jaxpr_custom_rules[core.call_p] = \\\npartial(call_partial_eval_custom_rule, lambda _, __, x, y: (x, y))\n+partial_eval_jaxpr_custom_rules[core.named_call_p] = \\\n+ partial(call_partial_eval_custom_rule, lambda _, __, x, y: (x, y))\npartial_eval_jaxpr_custom_rules[remat_call_p] = \\\npartial(call_partial_eval_custom_rule,\nlambda _, __, p1, p2: (p1, dict(p2, differentiated=True)))\n-# TODO unify with dce code below\n+# TODO(mattjj): unify with dce code below\ndef dce_jaxpr(jaxpr: Jaxpr, used_outputs: List[bool]\n) -> Tuple[Jaxpr, List[bool]]:\n- if jaxpr.constvars: raise NotImplementedError # TODO\n+ if jaxpr.constvars: raise NotImplementedError # TODO(mattjj)\nenv: Dict[Var, bool] = {}\ndef read(v: Var) -> bool:\n@@ -1041,6 +1043,8 @@ def dce_jaxpr_call_rule(used_outputs: List[bool], eqn: JaxprEqn\neqn.primitive, new_params, eqn.source_info)\nreturn used_inputs, new_eqn\ndce_rules[core.call_p] = dce_jaxpr_call_rule\n+dce_rules[core.named_call_p] = dce_jaxpr_call_rule\n+dce_rules[remat_call_p] = dce_jaxpr_call_rule\ndef _dce_jaxpr(closed_jaxpr: ClosedJaxpr, outputs: Sequence[bool], drop_outputs=False) -> ClosedJaxpr:\n@@ -1051,7 +1055,7 @@ def _dce_jaxpr(closed_jaxpr: ClosedJaxpr, outputs: Sequence[bool], drop_outputs=\ndef _dce_open_jaxpr(jaxpr: Jaxpr, outputs: Tuple[bool, ...], drop_outputs=False) -> Jaxpr:\n# This dead-code elimination is pretty rudimentary, and in particular doesn't\n# nontrivially DCE through scan, call, or other higher-order primitives.\n- # TODO(mattjj): better DCE\n+ # TODO(mattjj): better DCE (i.e. use above dce_jaxpr)\nif drop_outputs:\nnew_outvars = [var for var, output in zip(jaxpr.outvars, outputs) if output]\nelse:\n" }, { "change_type": "MODIFY", "old_path": "jax/test_util.py", "new_path": "jax/test_util.py", "diff": "@@ -169,6 +169,7 @@ def join_tolerance(tol1, tol2):\nreturn out\ndef _assert_numpy_close(a, b, atol=None, rtol=None, err_msg=''):\n+ a, b = np.asarray(a), np.asarray(b)\nassert a.shape == b.shape\natol = max(tolerance(a.dtype, atol), tolerance(b.dtype, atol))\nrtol = max(tolerance(a.dtype, rtol), tolerance(b.dtype, rtol))\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3503,11 +3503,11 @@ class RematTest(jtu.JaxTestCase):\ndef test_remat_checkpoint_dots(self):\n@partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\ndef f(x):\n- x = jnp.dot(x, x)\n+ x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\nx = jnp.sin(x)\n- x = jnp.dot(x, x)\n+ x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\nx = jnp.sin(x)\n- x = jnp.dot(x, x)\n+ x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\nx = jnp.sin(x)\nreturn x\n@@ -3521,11 +3521,11 @@ class RematTest(jtu.JaxTestCase):\n@api.jit\n@partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\ndef f(x):\n- x = jnp.dot(x, x)\n+ x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\nx = jnp.sin(x * 1e-3)\n- x = jnp.dot(x, x)\n+ x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\nx = jnp.sin(x * 1e-3)\n- x = jnp.dot(x, x)\n+ x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\nx = jnp.sin(x * 1e-3)\nreturn x\n@@ -3541,9 +3541,9 @@ class RematTest(jtu.JaxTestCase):\ndef f(W):\n@partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\ndef f(x):\n- x = jnp.sin(jnp.dot(x, W))\n- x = jnp.sin(jnp.dot(x, W))\n- x = jnp.sin(jnp.dot(x, W))\n+ x = jnp.sin(jnp.dot(x, W, precision=lax.Precision.HIGHEST))\n+ x = jnp.sin(jnp.dot(x, W, precision=lax.Precision.HIGHEST))\n+ x = jnp.sin(jnp.dot(x, W, precision=lax.Precision.HIGHEST))\nreturn x\ndef body(x, _): return f(x), None\n@@ -3565,8 +3565,6 @@ class RematTest(jtu.JaxTestCase):\nmodes=['fwd', 'rev'])\ndef test_remat_custom_jvp_policy(self):\n- save_sin = lambda prim, *_, **__: str(prim) == 'sin'\n-\n@api.custom_jvp\ndef sin(x):\nreturn jnp.sin(x)\n@@ -3576,9 +3574,15 @@ class RematTest(jtu.JaxTestCase):\nreturn sin(x), jnp.cos(x) * g\nsin.defjvp(sin_jvp)\n- @partial(api.remat, policy=save_sin)\n+ @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\ndef f(x):\n- return sin(sin(x))\n+ x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n+ x = sin(x * 1e-3)\n+ x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n+ x = sin(x * 1e-3)\n+ x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n+ x = sin(x * 1e-3)\n+ return x\njtu.check_grads(f, (3.,), order=2, modes=['fwd', 'rev'])\n@@ -3586,6 +3590,38 @@ class RematTest(jtu.JaxTestCase):\nreturn lax.scan(lambda x, _: (f(x), None), x, None, length=2)[0]\njtu.check_grads(g, (3.,), order=2, modes=['fwd', 'rev'])\n+ def test_remat_custom_vjp_policy(self):\n+ @api.custom_vjp\n+ def sin(x):\n+ return jnp.sin(x)\n+ def sin_fwd(x):\n+ return sin(x), x\n+ def sin_bwd(x, y_bar):\n+ return (jnp.cos(x) * y_bar,)\n+ sin.defvjp(sin_fwd, sin_bwd)\n+\n+ @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n+ def f(x):\n+ @partial(api.named_call, name=\"dot\")\n+ def dot2(y, z):\n+ return jnp.dot(x, jnp.dot(y, z, precision=lax.Precision.HIGHEST),\n+ precision=lax.Precision.HIGHEST)\n+\n+ x = dot2(x, x)\n+ x = sin(x * 1e-3)\n+ x = dot2(x, x)\n+ x = sin(x * 1e-3)\n+ x = dot2(x, x)\n+ x = sin(x * 1e-3)\n+ return x\n+\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+\n+ def g(x):\n+ return lax.scan(lambda x, _: (f(x), None), x, None, length=2)[0]\n+ jtu.check_grads(g, (3.,), order=2, modes=['rev'])\n+\n+\nclass JaxprTest(jtu.JaxTestCase):\ndef test_scalar_literals(self):\n" } ]
Python
Apache License 2.0
google/jax
fix custom_vjp issue?
260,335
30.08.2021 19:22:43
25,200
d69f57e1ed3a8fdd05bd2e844524cc612cff0a53
raise NotImplementedError for pjit partial eval
[ { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -519,6 +519,13 @@ def _pjit_jvp(primals_in, tangents_in,\nad.primitive_jvps[pjit_p] = _pjit_jvp\n+def _pjit_partial_eval(trace, *in_tracers, jaxpr, in_axis_resources,\n+ out_axis_resources, resource_env, donated_invars, name):\n+ raise NotImplementedError(\"linearize, vjp, and grad of pjit not supported, \"\n+ \"see https://github.com/google/jax/pull/6876\")\n+pe.custom_partial_eval_rules[pjit_p] = _pjit_partial_eval\n+\n+\ndef _check_resources_against_named_axes(what, aval, pos_axis_resources, named_axis_resources):\npjit_resources = set(it.chain.from_iterable(pos_axis_resources))\naval_resources = set(it.chain.from_iterable(\n" }, { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "@@ -643,6 +643,22 @@ class PJitErrorTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(RuntimeError, error):\npjit(lambda x: x, in_axis_resources=None, out_axis_resources=None)(jnp.arange(4))\n+ @jtu.with_mesh([('x', 2), ('y', 2)])\n+ def testLinearizeNotImplemented(self):\n+ # pending https://github.com/google/jax/pull/6876\n+ @partial(pjit,\n+ in_axis_resources=(P(None, 'x', 'y'), P('y')),\n+ out_axis_resources=P('x'))\n+ def f(x, y):\n+ return x @ y\n+\n+ x_shape = (8, 6, 4)\n+ y_shape = (4, 2)\n+ x = jnp.arange(np.prod(x_shape)).reshape(x_shape)\n+ y = jnp.arange(np.prod(y_shape)).reshape(y_shape)\n+ with self.assertRaisesRegex(NotImplementedError, \"6876\"):\n+ jax.linearize(f, x, y)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
raise NotImplementedError for pjit partial eval
260,289
29.08.2021 16:36:45
-19,080
c4d300c4caa860c6c0ee61842e60194c49959880
Implement np.polyfit
[ { "change_type": "MODIFY", "old_path": "docs/jax.numpy.rst", "new_path": "docs/jax.numpy.rst", "diff": "@@ -294,6 +294,7 @@ Not every function in NumPy is implemented; contributions are welcome!\npoly\npolyadd\npolyder\n+ polyfit\npolyint\npolymul\npolysub\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1368,6 +1368,76 @@ def gradient(f, *varargs, axis: Optional[Union[int, Tuple[int, ...]]] = None,\ndef isrealobj(x):\nreturn not iscomplexobj(x)\n+_POLYFIT_DOC = \"\"\"\\\n+Unlike NumPy's implementation of polyfit, :py:func:`jax.numpy.polyfit` will not warn on rank reduction, which indicates an ill conditioned matrix\n+Also, it works best on rcond <= 10e-3 values.\n+\"\"\"\n+@_wraps(np.polyfit, lax_description=_POLYFIT_DOC )\n+def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):\n+ _check_arraylike(\"polyfit\", x, y)\n+ deg = core.concrete_or_error(int, deg, \"deg must be int\")\n+ order = deg + 1\n+ # check arguments\n+ if deg < 0:\n+ raise ValueError(\"expected deg >= 0\")\n+ if x.ndim != 1:\n+ raise TypeError(\"expected 1D vector for x\")\n+ if x.size == 0:\n+ raise TypeError(\"expected non-empty vector for x\")\n+ if y.ndim < 1 or y.ndim > 2:\n+ raise TypeError(\"expected 1D or 2D array for y\")\n+ if x.shape[0] != y.shape[0]:\n+ raise TypeError(\"expected x and y to have same length\")\n+\n+ # set rcond\n+ if rcond is None:\n+ rcond = len(x)*finfo(x.dtype).eps\n+ rcond = core.concrete_or_error(float, rcond, \"rcond must be float\")\n+ # set up least squares equation for powers of x\n+ lhs = vander(x, order)\n+ rhs = y\n+\n+ # apply weighting\n+ if w is not None:\n+ _check_arraylike(\"polyfit\", w)\n+ w, = _promote_dtypes_inexact(w)\n+ if w.ndim != 1:\n+ raise TypeError(\"expected a 1-d array for weights\")\n+ if w.shape[0] != y.shape[0]:\n+ raise TypeError(\"expected w and y to have the same length\")\n+ lhs *= w[:, newaxis]\n+ if rhs.ndim == 2:\n+ rhs *= w[:, newaxis]\n+ else:\n+ rhs *= w\n+\n+ # scale lhs to improve condition number and solve\n+ scale = sqrt((lhs*lhs).sum(axis=0))\n+ lhs /= scale[newaxis,:]\n+ from . import linalg\n+ c, resids, rank, s = linalg.lstsq(lhs, rhs, rcond)\n+ c = (c.T/scale).T # broadcast scale coefficients\n+\n+ if full:\n+ return c, resids, rank, s, rcond\n+ elif cov:\n+ Vbase = linalg.inv(dot(lhs.T, lhs))\n+ Vbase /= outer(scale, scale)\n+ if cov == \"unscaled\":\n+ fac = 1\n+ else:\n+ if len(x) <= order:\n+ raise ValueError(\"the number of data points must exceed order \"\n+ \"to scale the covariance matrix\")\n+ fac = resids / (len(x) - order)\n+ fac = fac[0] #making np.array() of shape (1,) to int\n+ if y.ndim == 1:\n+ return c, Vbase * fac\n+ else:\n+ return c, Vbase[:,:, newaxis] * fac\n+ else:\n+ return c\n+\n@_wraps(np.reshape, lax_description=_ARRAY_VIEW_DOC)\ndef reshape(a, newshape, order=\"C\"):\n" }, { "change_type": "MODIFY", "old_path": "jax/numpy/__init__.py", "new_path": "jax/numpy/__init__.py", "diff": "@@ -51,7 +51,7 @@ from jax._src.numpy.lax_numpy import (\nnanmax, nanmean, nanmin, nanprod, nanstd, nansum, nanvar, ndarray, ndim,\nnegative, newaxis, nextafter, nonzero, not_equal, number,\nobject_, ogrid, ones, ones_like, outer, packbits, pad, percentile,\n- pi, piecewise, poly, polyadd, polyder, polyint, polymul, polysub, polyval, positive, power,\n+ pi, piecewise, poly, polyadd, polyder, polyfit, polyint, polymul, polysub, polyval, positive, power,\nprod, product, promote_types, ptp, quantile,\nr_, rad2deg, radians, ravel, ravel_multi_index, real, reciprocal, remainder, repeat, reshape,\nresize, result_type, right_shift, rint, roll, rollaxis, rot90, round, round_, row_stack,\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1379,10 +1379,41 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ntol = max(jtu.tolerance(lhs_dtype, tol_spec),\njtu.tolerance(rhs_dtype, tol_spec))\n# TODO(phawkins): there are float32/float64 disagreements for some inputs.\n- self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False,\n- tol=tol)\n- self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=False, atol=tol,\n- rtol=tol)\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False, tol=tol)\n+ self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=False, atol=tol, rtol=tol)\n+\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_deg={}_rcond={}_full={}_w={}_cov={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype),\n+ deg,\n+ rcond,\n+ full,\n+ w,\n+ cov),\n+ \"shape\": shape, \"dtype\": dtype, \"deg\": deg,\n+ \"rcond\": rcond, \"full\": full, \"w\":w, \"cov\":cov}\n+ for dtype in [dt for dt in float_dtypes if dt not in [jnp.float16, jnp.bfloat16]]\n+ for shape in [shape for shape in one_dim_array_shapes if shape != (1,)]\n+ for deg in [1, 2, 3]\n+ for rcond in [None, -1, 10e-3, 10e-5, 10e-10]\n+ for full in [False, True]\n+ for w in [False, True]\n+ for cov in [False, True, \"unscaled\"]))\n+ def testPolyfit(self, shape, dtype, deg, rcond, full, w, cov):\n+ rng = jtu.rand_default(self.rng())\n+ tol_spec = {np.float32: 1e-4, np.float64: 1e-13, np.complex64: 1e-5}\n+ if jtu.device_under_test() == \"tpu\":\n+ tol_spec[np.float32] = tol_spec[np.complex64] = 2e-1\n+ tol = jtu.tolerance(dtype, tol_spec)\n+ _w = lambda a: abs(a) if w else None\n+ args_maker = lambda: [rng(shape, dtype), rng(shape, dtype), rng(shape, dtype)]\n+ jnp_fun = lambda x, y, a: jnp.polyfit(x, y, deg=deg, rcond=rcond, full=full, w=_w(a), cov=cov)\n+ np_fun = jtu.ignore_warning(\n+ message=\"Polyfit may be poorly conditioned*\")(lambda x, y, a: np.polyfit(x, y, deg=deg, rcond=rcond, full=full, w=_w(a), cov=cov))\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False, tol=tol)\n+ self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=False, atol=tol, rtol=tol)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_amin={}_amax={}\".format(\n" } ]
Python
Apache License 2.0
google/jax
Implement np.polyfit
260,578
01.09.2021 07:14:48
25,200
67bea579abcaf222739788a3bb4827d82323f693
Update org_tensorflow commit for jaxlib release
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -7,10 +7,10 @@ load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"8e1b21a456b8d1f245910e561007317e2a7a4894cc420336cda621e8df08a630\",\n- strip_prefix = \"tensorflow-3d2e2c88fc805ca5a0dd523ce23182e3173ad887\",\n+ sha256 = \"6b14b66a74728736359afcb491820fa3e713ea4a74bff0defe920f3453a3a0f0\",\n+ strip_prefix = \"tensorflow-b5b1ff47ad250c3e38dcadef5f6bc414b0a533ee\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/3d2e2c88fc805ca5a0dd523ce23182e3173ad887.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/b5b1ff47ad250c3e38dcadef5f6bc414b0a533ee.tar.gz\",\n],\n)\n" } ]
Python
Apache License 2.0
google/jax
Update org_tensorflow commit for jaxlib release
260,578
01.09.2021 10:43:20
25,200
be824a792edeb1908f21264b5d50dd3dbfefe5b3
Update files after new jaxlib release 0.1.71
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -16,6 +16,11 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* `jnp.unique` and other set-like operations now require array-like inputs\n({jax-issue}`#7662`)\n+## jaxlib 0.1.71 (Sep 1, 2021)\n+* Breaking changes:\n+ * Support for CUDA 11.0 and CUDA 10.1 has been dropped. Jaxlib now supports\n+ CUDA 10.2 and CUDA 11.1+.\n+\n## jax 0.2.19 (Aug 12, 2021)\n* [GitHub\ncommits](https://github.com/google/jax/compare/jax-v0.2.18...jax-v0.2.19).\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/version.py", "new_path": "jaxlib/version.py", "diff": "# reflect the most recent available binaries.\n# __version__ should be increased after releasing the current version\n# (i.e. on main, this is always the next version to be released).\n-__version__ = \"0.1.71\"\n+__version__ = \"0.1.72\"\n" }, { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "from setuptools import setup, find_packages\n# The following should be updated with each new jaxlib release.\n-_current_jaxlib_version = '0.1.70'\n-_available_cuda_versions = ['101', '102', '110', '111']\n+_current_jaxlib_version = '0.1.71'\n+_available_cuda_versions = ['102', '111']\n_dct = {}\nwith open('jax/version.py') as f:\n" } ]
Python
Apache License 2.0
google/jax
Update files after new jaxlib release 0.1.71
260,578
01.09.2021 10:56:54
25,200
84edde2f9b611d4323257faddd284e3692a20d36
Add new features section
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -20,6 +20,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Breaking changes:\n* Support for CUDA 11.0 and CUDA 10.1 has been dropped. Jaxlib now supports\nCUDA 10.2 and CUDA 11.1+.\n+* New features:\n+ * Experimental multi-host GPU support.\n## jax 0.2.19 (Aug 12, 2021)\n* [GitHub\n" } ]
Python
Apache License 2.0
google/jax
Add new features section
260,578
01.09.2021 11:26:41
25,200
14a02c68800f67e8d0762767a6e6152054353b8a
Remove new features
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -20,8 +20,6 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Breaking changes:\n* Support for CUDA 11.0 and CUDA 10.1 has been dropped. Jaxlib now supports\nCUDA 10.2 and CUDA 11.1+.\n-* New features:\n- * Experimental multi-host GPU support.\n## jax 0.2.19 (Aug 12, 2021)\n* [GitHub\n" } ]
Python
Apache License 2.0
google/jax
Remove new features
260,439
01.09.2021 13:08:10
25,200
f38d3e8735bb3b0afb5f49d3cc49672cedc4d554
Allow axis index groups to have different sizes for AllReduce.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -57,7 +57,7 @@ def psum(x, axis_name, *, axis_index_groups=None):\naxis_index_groups: optional list of lists containing axis indices (e.g. for\nan axis of size 4, [[0, 1], [2, 3]] would perform psums over the first\ntwo and last two replicas). Groups must cover all axis indices exactly\n- once, and all groups must be the same size.\n+ once.\nReturns:\n@@ -78,7 +78,7 @@ def psum(x, axis_name, *, axis_index_groups=None):\naxis_name = (axis_name,)\nif any(isinstance(axis, int) for axis in axis_name) and axis_index_groups is not None:\nraise ValueError(\"axis_index_groups only supported for sums over just named axes\")\n- _validate_axis_index_groups(axis_index_groups)\n+ _validate_reduce_axis_index_groups(axis_index_groups)\nleaves, treedef = tree_util.tree_flatten(x)\nleaves = [lax.convert_element_type(l, np.int32)\nif dtypes.dtype(l) == np.bool_ else l for l in leaves]\n@@ -99,7 +99,7 @@ def pmean(x, axis_name, *, axis_index_groups=None):\naxis_index_groups: optional list of lists containing axis indices (e.g. for\nan axis of size 4, [[0, 1], [2, 3]] would perform pmeans over the first\ntwo and last two replicas). Groups must cover all axis indices exactly\n- once, and all groups must be the same size.\n+ once, and on TPUs all groups must be the same size.\nReturns:\nArray(s) with the same shape as ``x`` representing the result of an\n@@ -132,7 +132,7 @@ def pmax(x, axis_name, *, axis_index_groups=None):\naxis_index_groups: optional list of lists containing axis indices (e.g. for\nan axis of size 4, [[0, 1], [2, 3]] would perform pmaxes over the first\ntwo and last two replicas). Groups must cover all axis indices exactly\n- once, and all groups must be the same size.\n+ once, and on TPUs all groups must be the same size.\nReturns:\nArray(s) with the same shape as ``x`` representing the result of an\n@@ -142,7 +142,7 @@ def pmax(x, axis_name, *, axis_index_groups=None):\naxis_name = (axis_name,)\nif any(isinstance(axis, int) for axis in axis_name) and axis_index_groups is not None:\nraise ValueError(\"axis_index_groups only supported for sums over just named axes\")\n- _validate_axis_index_groups(axis_index_groups)\n+ _validate_reduce_axis_index_groups(axis_index_groups)\nleaves, treedef = tree_util.tree_flatten(x)\nout_flat = pmax_p.bind(*leaves, axes=axis_name,\naxis_index_groups=axis_index_groups)\n@@ -161,7 +161,7 @@ def pmin(x, axis_name, *, axis_index_groups=None):\naxis_index_groups: optional list of lists containing axis indices (e.g. for\nan axis of size 4, [[0, 1], [2, 3]] would perform pmins over the first\ntwo and last two replicas). Groups must cover all axis indices exactly\n- once, and all groups must be the same size.\n+ once, and on TPUs all groups must be the same size.\nReturns:\nArray(s) with the same shape as ``x`` representing the result of an\n@@ -171,7 +171,7 @@ def pmin(x, axis_name, *, axis_index_groups=None):\naxis_name = (axis_name,)\nif any(isinstance(axis, int) for axis in axis_name) and axis_index_groups is not None:\nraise ValueError(\"axis_index_groups only supported for sums over just named axes\")\n- _validate_axis_index_groups(axis_index_groups)\n+ _validate_reduce_axis_index_groups(axis_index_groups)\nleaves, treedef = tree_util.tree_flatten(x)\nout_flat = pmin_p.bind(*leaves, axes=axis_name,\naxis_index_groups=axis_index_groups)\n@@ -194,13 +194,10 @@ def _axis_index_of_val(x, val, axis_name):\nvalidx = lax_numpy.where(val == x, idx, dtypes.iinfo(dtypes.dtype(idx)).max)\nreturn pmin(validx, axis_name)\n-def _validate_axis_index_groups(axis_index_groups):\n+def _validate_reduce_axis_index_groups(axis_index_groups):\nif axis_index_groups is None:\nreturn\n- len_0 = len(axis_index_groups[0])\n- if any(len(g) != len_0 for g in axis_index_groups):\n- raise ValueError(\"axis_index_groups must all be the same size\")\n- axis_space = range(len_0 * len(axis_index_groups))\n+ axis_space = range(sum(len(group) for group in axis_index_groups))\nif {i for g in axis_index_groups for i in g} != set(axis_space):\nraise ValueError(\"axis_index_groups must cover all indices exactly once\")\n@@ -645,6 +642,10 @@ def _allreduce_abstract_eval(*args, axes, axis_index_groups):\ndef _allreduce_translation_rule(prim, pos_prim, c, *args, axes, axis_index_groups,\naxis_env, platform):\n+ if axis_index_groups is not None and platform == \"tpu\":\n+ len_0 = len(axis_index_groups[0])\n+ if any(len(g) != len_0 for g in axis_index_groups):\n+ raise ValueError(\"axis_index_groups must all be the same size\")\nnamed_axes, positional_axes = axes_partition = [], []\nfor axis in axes:\naxes_partition[isinstance(axis, int)].append(axis)\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -602,6 +602,28 @@ class PythonPmapTest(jtu.JaxTestCase):\nans = f(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def testPsumUnevenReplicaGroups(self):\n+ replicas = xla_bridge.device_count()\n+ if replicas <= 2:\n+ raise SkipTest(\"Test expected devices greater than 2.\")\n+ axis_index_groups = [[0,1], np.arange(2,replicas)]\n+ f = lambda x: x - lax.psum(x, 'i', axis_index_groups=axis_index_groups)\n+ f = self.pmap(f, 'i')\n+\n+ shape = (replicas, 4)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ def sum_helper(a):\n+ return np.broadcast_to(a.sum(0, keepdims=True),\n+ (len(a), x.shape[1]))\n+ expected_psum_1 = sum_helper(x[0:2])\n+ expected_psum_2 = sum_helper(x[2:])\n+ expected_psum = np.concatenate([expected_psum_1, expected_psum_2], 0)\n+ expected = x - expected_psum\n+\n+ ans = f(x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef testPsumReplicaGroups(self):\nreplicas = xla_bridge.device_count()\nif replicas % 2 != 0:\n" } ]
Python
Apache License 2.0
google/jax
Allow axis index groups to have different sizes for AllReduce. PiperOrigin-RevId: 394297426
260,335
01.09.2021 22:38:17
25,200
ffa4ec05007ba2bf03bc36ce961603898647e803
[remat] fix two unit bugs, add test for one
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -798,8 +798,9 @@ def _remat_partial_eval(trace, _, f, tracers, params):\nout_consts = core.eval_jaxpr(jaxpr_known, (), *in_consts)\nout_consts_ = iter(out_consts)\n# reconstruct known outs, inserting units\n- outs1 = [unit if x.aval is abstract_unit else next(out_consts_)\n- for uk, x in zip(out_unknowns, jaxpr.outvars) if not uk]\n+ outs1 = [pval.get_known() if x.aval is abstract_unit else next(out_consts_)\n+ for uk, pval, x in zip(out_unknowns, eval_out_pvals, jaxpr.outvars)\n+ if not uk]\n# form known outputs and collect residual tracers\nout_known_tracers = [JaxprTracer(trace, PartialVal.known(c), None)\nfor c in outs1]\n@@ -971,15 +972,16 @@ def call_partial_eval_custom_rule(\neqn.params['call_jaxpr'], unks_in, saveable)\nins_known, _ = partition_list(unks_in, eqn.invars)\nout_binders_known, _ = partition_list(unks_out, eqn.outvars)\n+ out_binders_known = [v for v in out_binders_known if v is not dropvar]\n_, out_binders_staged = partition_list(inst_out, eqn.outvars)\nnewvar = core.gensym([jaxpr_known, jaxpr_staged])\nresiduals = [newvar(v.aval) for v in jaxpr_staged.invars[:num_res]]\nparams_known = dict(eqn.params, call_jaxpr=jaxpr_known)\nparams_staged = dict(eqn.params, call_jaxpr=jaxpr_staged)\nparams_known, params_staged = params_updater(unks_in, num_res, params_known, params_staged)\n- eqn_known = JaxprEqn(ins_known, [*out_binders_known, *residuals],\n+ eqn_known = new_jaxpr_eqn(ins_known, [*out_binders_known, *residuals],\neqn.primitive, params_known, eqn.source_info)\n- eqn_staged = JaxprEqn([*residuals, *eqn.invars], out_binders_staged,\n+ eqn_staged = new_jaxpr_eqn([*residuals, *eqn.invars], out_binders_staged,\neqn.primitive, params_staged, eqn.source_info)\nassert len(eqn_staged.invars) == len(jaxpr_staged.invars)\nnew_inst = [x for x, inst in zip(eqn.invars, inst_in)\n@@ -1040,7 +1042,7 @@ def dce_jaxpr_call_rule(used_outputs: List[bool], eqn: JaxprEqn\nupdate_params = call_param_updaters.get(eqn.primitive)\nif update_params:\nnew_params = update_params(new_params, used_inputs)\n- new_eqn = JaxprEqn([v for v, used in zip(eqn.invars, used_inputs) if used],\n+ new_eqn = new_jaxpr_eqn([v for v, used in zip(eqn.invars, used_inputs) if used],\n[v for v, used in zip(eqn.outvars, used_outputs) if used],\neqn.primitive, new_params, eqn.source_info)\nreturn used_inputs, new_eqn\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3642,6 +3642,17 @@ class RematTest(jtu.JaxTestCase):\nreturn lax.scan(lambda x, _: (f(x), None), x, None, length=2)[0]\njtu.check_grads(g, (3.,), order=2, modes=['rev'])\n+ def test_remat_dropvar_policy(self):\n+ def f(x):\n+ return x, x\n+\n+ @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n+ def g(x):\n+ x = api.grad(lambda x: f(x)[0])(x)\n+ return x\n+\n+ api.grad(g)(3.)\n+\nclass JaxprTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
[remat] fix two unit bugs, add test for one
260,335
02.09.2021 15:41:39
25,200
9955e44653a734affc4f2e4818be621486bba8b5
fix dce logic for nullary primitives
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1015,9 +1015,11 @@ def dce_jaxpr(jaxpr: Jaxpr, used_outputs: List[bool]\nif rule:\nused_ins, new_eqn = rule(used_outs, eqn)\nif any(used_ins): new_eqns.append(new_eqn)\n+ elif any(used_outs):\n+ new_eqns.append(eqn)\n+ used_ins = [True] * len(eqn.invars)\nelse:\n- used_ins = [any(used_outs)] * len(eqn.invars)\n- if any(used_ins): new_eqns.append(eqn)\n+ used_ins = [False] * len(eqn.invars)\nmap(write, eqn.invars, used_ins)\nused_inputs = map(read, jaxpr.invars)\n" } ]
Python
Apache License 2.0
google/jax
fix dce logic for nullary primitives
260,510
07.07.2021 11:03:59
25,200
d693324dabc1af2b323bd489078e23b360a885b8
change while loop batching fixed point condition Fixes
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -373,7 +373,7 @@ def _pred_bcast_select(c, pred, x, y, x_y_aval: core.AbstractValue):\nelif x_y_aval is core.abstract_token:\nreturn xops.AfterAll(c, [x, y])\nelse:\n- assert pred_shape == x_shape[:len(pred_shape)] == y_shape[:len(pred_shape)]\n+ assert pred_shape == x_shape[:len(pred_shape)] == y_shape[:len(pred_shape)], (pred_shape, x_shape, y_shape)\nbcast_pred = xops.BroadcastInDim(pred, x_shape, list(range(len(pred_shape))))\nreturn xops.Select(bcast_pred, x, y)\n@@ -383,43 +383,76 @@ def _while_loop_batching_rule(args, dims, axis_name, main_type,\nsize, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}\norig_batched = [d is not batching.not_mapped for d in dims]\ncconst_bat, bconst_bat, init_bat = split_list(orig_batched, [cond_nconsts, body_nconsts])\n+ cconsts, bconsts, init = split_list(args, [cond_nconsts, body_nconsts])\n+ cconst_dims, bconst_dims, init_dims = split_list(dims, [cond_nconsts, body_nconsts])\n+ carry_bat = init_bat\n# Fixpoint computation of which carry are batched: either\n# batched from init, or the carry out is batched. Each iteration promotes\n- # at least one carry to batched. We need at most len(carry) iterations,\n- # but we need one last iteration to prepare the jaxpr based on the final\n- # carry_bat.\n- carry_bat = init_bat\n+ # at least one carry to batched. We need at most len(carry) iterations to\n+ # reach a fixpoint.\nfor _ in range(1 + len(carry_bat)):\n- batched = bconst_bat + carry_bat\n- body_jaxpr_batched, carry_bat_out = batching.batch_jaxpr(\n- body_jaxpr, size, batched, instantiate=carry_bat,\n+ _, carry_bat_out = batching.batch_jaxpr(\n+ body_jaxpr, size, bconst_bat + carry_bat, instantiate=False,\naxis_name=axis_name, main_type=main_type)\n- cond_jaxpr_batched, (pred_bat,) = batching.batch_jaxpr(\n- cond_jaxpr, size, cconst_bat + carry_bat,\n- instantiate=bool(cond_jaxpr.out_avals[0].shape),\n- axis_name=axis_name, main_type=main_type)\n- carry_bat_out = _map(partial(operator.or_, pred_bat), carry_bat_out)\n- if carry_bat_out == carry_bat:\n+ if carry_bat == carry_bat_out:\nbreak\n- else:\n- carry_bat = _map(operator.or_, carry_bat, carry_bat_out)\n+ carry_bat = safe_map(operator.or_, carry_bat, carry_bat_out)\nelse:\nassert False, \"Fixpoint not reached\"\n- consts, init = split_list(args, [cond_nconsts + body_nconsts])\n- const_dims, init_dims = split_list(dims, [cond_nconsts + body_nconsts])\n- new_consts = [batching.moveaxis(x, d, 0) if d is not batching.not_mapped and d != 0\n- else x for x, d in zip(consts, const_dims)]\n- new_init = [batching.broadcast(x, size, 0) if now_bat and not was_bat\n- else batching.moveaxis(x, d, 0) if now_bat and d != 0 else x\n- for x, d, was_bat, now_bat in zip(init, init_dims, init_bat, carry_bat)]\n+ # Knowing how the carry is batched now, we can determine if the predicate is\n+ # batched.\n+ _, (pred_bat,) = batching.batch_jaxpr(\n+ cond_jaxpr, size, cconst_bat + carry_bat, instantiate=False,\n+ axis_name=axis_name, main_type=main_type)\n+\n+ if pred_bat:\n+ # If the predicate is batched, we have to batch *all* of the carry\n+ # regardless of if the body needs it.\n+ carry_bat = [True] * len(carry_bat)\n+ carry_dims = [0] * len(carry_bat)\n+ body_jaxpr_batched, _ = batching.batch_jaxpr_axes(\n+ body_jaxpr, size, bconst_dims + carry_dims,\n+ carry_dims, axis_name=axis_name, main_type=main_type)\n+ cond_jaxpr_batched, _ = batching.batch_jaxpr_axes(\n+ cond_jaxpr, size, cconst_dims + carry_dims, [0],\n+ axis_name=axis_name, main_type=main_type)\n+ else:\n+ # If the predicate is not batched, we can look at the `cond_jaxpr`'s out\n+ # shape to determine the rank of the predicate. From this rank\n+ # we pick the dims of the carry to be batched to ensure that the predicate\n+ # shape is a prefix of the carry in and out shapes. We can then batch\n+ # the `body_jaxpr` according to these new batch dims.\n+ cond_rank = len(cond_jaxpr.out_avals[0].shape)\n+ carry_dims = [cond_rank if b else None for b in carry_bat]\n+ body_jaxpr_batched, _ = batching.batch_jaxpr_axes(\n+ body_jaxpr, size, bconst_dims + carry_dims, carry_dims,\n+ axis_name=axis_name, main_type=main_type)\n+ # Now we need to rebatch the `cond_jaxpr` according to the new dims of the\n+ # carry.\n+ cond_jaxpr_batched, _ = batching.batch_jaxpr_axes(\n+ cond_jaxpr, size, cconst_dims + carry_dims, (None,),\n+ axis_name=axis_name, main_type=main_type)\n+\n+ # To prepare the `init` to the `while_p`, we broadcast values if they are\n+ # unbatched and need to have an out axis. If their current batch axis does not\n+ # match the one it needs to be for the translation rule to work, we move it\n+ # into place.\n+ new_init = []\n+ for x, old_axis, new_axis in zip(init, init_dims, carry_dims):\n+ if old_axis is batching.not_mapped and new_axis is not batching.not_mapped:\n+ new_init.append(batching.broadcast(x, size, new_axis))\n+ elif old_axis is batching.not_mapped and new_axis is batching.not_mapped:\n+ new_init.append(x)\n+ else:\n+ assert new_axis is not batching.not_mapped\n+ new_init.append(batching.moveaxis(x, old_axis, new_axis))\n- outs = while_p.bind(*(new_consts + new_init),\n+ outs = while_p.bind(*(cconsts + bconsts + new_init),\ncond_nconsts=cond_nconsts, cond_jaxpr=cond_jaxpr_batched,\nbody_nconsts=body_nconsts, body_jaxpr=body_jaxpr_batched)\n- out_bdims = [0 if b else batching.not_mapped for b in carry_bat]\n- return outs, out_bdims\n+ return outs, carry_dims\ndef _while_loop_jvp(primals, tangents, cond_nconsts, cond_jaxpr, body_nconsts,\nbody_jaxpr):\n@@ -551,7 +584,7 @@ def _while_transpose_error(*_, **kwargs):\n\"lax.while_loop or lax.fori_loop. \"\n\"Try using lax.scan instead.\")\n-while_p = lax.Primitive('while')\n+while_p = core.Primitive('while')\nwhile_p.multiple_results = True\nwhile_p.def_impl(partial(xla.apply_primitive, while_p))\nwhile_p.def_abstract_eval(_while_loop_abstract_eval)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -470,17 +470,31 @@ def bdim_at_front(x, bdim, size):\nreturn moveaxis(x, bdim, 0)\n+zero_if_mapped = object()\n+\ndef batch_jaxpr(closed_jaxpr, axis_size, in_batched, instantiate, axis_name, main_type):\n+ if instantiate is None:\n+ instantiate = False\n+ if isinstance(instantiate, bool):\n+ instantiate = [instantiate] * len(closed_jaxpr.out_avals)\n+ out_axes = [0 if inst else zero_if_mapped for inst in instantiate]\n+ return batch_jaxpr_axes(\n+ closed_jaxpr, axis_size,\n+ [0 if b else not_mapped for b in in_batched],\n+ out_axes,\n+ axis_name, main_type)\n+\n+def batch_jaxpr_axes(closed_jaxpr, axis_size, in_axes, out_axes, axis_name, main_type):\nf = lu.wrap_init(core.jaxpr_as_fun(closed_jaxpr))\n- f, out_batched = batch_subtrace_instantiate(f, instantiate, axis_size)\n- f = batchfun(f, axis_name, axis_size, [0 if b else None for b in in_batched], main_type)\n- avals_in = [core.unmapped_aval(axis_size, 0, aval) if b else aval\n- for aval, b in zip(closed_jaxpr.in_avals, in_batched)]\n+ f, out_batched = batch_subtrace_instantiate(f, axis_size, out_axes)\n+ f = batchfun(f, axis_name, axis_size, in_axes, main_type)\n+ avals_in = [core.unmapped_aval(axis_size, b, aval) if b is not not_mapped\n+ else aval for aval, b in zip(closed_jaxpr.in_avals, in_axes)]\njaxpr_out, _, consts = pe.trace_to_jaxpr_dynamic(f, avals_in)\nreturn core.ClosedJaxpr(jaxpr_out, consts), out_batched()\n@lu.transformation_with_aux\n-def batch_subtrace_instantiate(instantiate, axis_size, main, in_dims, *in_vals):\n+def batch_subtrace_instantiate(axis_size, out_axes, main, in_dims, *in_vals):\n# this is like `batch_subtrace` but we take an extra `instantiate` arg\n# analogue of `jvp_subtrace` in ad.py\ntrace = main.with_cur_sublevel()\n@@ -490,13 +504,12 @@ def batch_subtrace_instantiate(instantiate, axis_size, main, in_dims, *in_vals):\nout_tracers = map(trace.full_raise, outs)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n- if type(instantiate) is bool:\n- instantiate = [instantiate] * len(out_vals)\n- out_vals = [moveaxis(x, d, 0) if d is not not_mapped and d != 0\n- else broadcast(x, axis_size, 0) if d is not_mapped and inst else x\n- for x, d, inst in zip(out_vals, out_dims, instantiate)]\n- out_batched = [d is not not_mapped or inst\n- for d, inst in zip(out_dims, instantiate)]\n+ out_axes = [(None if od is not_mapped else 0) if out_axis is zero_if_mapped else out_axis\n+ for od, out_axis in zip(out_dims, out_axes)]\n+ out_vals = [moveaxis(x, d, od) if d is not not_mapped\n+ else broadcast(x, axis_size, od) if od is not None else x\n+ for x, d, od in zip(out_vals, out_dims, out_axes)]\n+ out_batched = [od is not None for od in out_axes]\nyield out_vals, out_batched\n@lu.transformation_with_aux\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -36,6 +36,7 @@ from jax import random\nfrom jax import test_util as jtu\nfrom jax import tree_util\nfrom jax._src.util import unzip2\n+from jax.experimental import maps\nfrom jax.lib import xla_bridge\nfrom jax.interpreters import xla\nimport jax.numpy as jnp # scan tests use numpy\n@@ -2739,5 +2740,30 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nlax.scan(side_effecting_scan, None, jnp.ones((2, 2)))\nlst[0] += 1\n+ def test_while_loop_fixed_point_with_nested_named_axes(self):\n+ def f(x):\n+ z = x + lax.axis_index('a')\n+ y = x + lax.axis_index('b')\n+ def cond(carry):\n+ i, x = carry\n+ return x < 5\n+ def body(carry):\n+ i, x = carry\n+ return i + 1, x + lax.psum(y, 'b')\n+ return lax.while_loop(cond, body, (0, z))[1]\n+ maps.xmap(f, axis_sizes=dict(a=2, b=10), out_axes=(['a']), in_axes={})(1.)\n+\n+ def test_while_loop_fixed_point_with_batched_pred_and_consts(self):\n+ def f(i, x):\n+ def cond(carry):\n+ i, x = carry\n+ return i < 5\n+ def body(carry):\n+ i, z = carry\n+ # Close over const with batch dim = 1\n+ return i + 1, z + x\n+ return lax.while_loop(cond, body, (i, jnp.ones(3)))[1]\n+ jax.vmap(f, in_axes=(0, 1))(jnp.arange(4), jnp.ones((3, 4)))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
change while loop batching fixed point condition Fixes #7063 Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com> Co-authored-by: Adam Paszke <apaszke@google.com>
260,528
06.09.2021 17:55:22
-7,200
cdbbefa00af1af3623f525c1f78d50e976f6f9d2
Fix argument names for jnp.ndarray.clip and deprecate the old ones
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -5946,6 +5946,20 @@ def _nbytes(arr):\nreturn size(arr) * _dtype(arr).itemsize\n+def _clip(number, min=None, max=None, out=None, *, a_min=None, a_max=None):\n+ # ndarray.clip has a slightly different API from clip (min -> a_min, max -> a_max)\n+ # TODO: remove after deprecation window\n+ if a_min is not None or a_max is not None:\n+ warnings.warn('`a_min` and `a_max` keyword arguments to ndarray.clip are deprecated '\n+ 'in favor of `min` and `max` for compatibility with numpy. '\n+ 'They will be removed in JAX 0.22.2', FutureWarning)\n+ if min is None and a_min is not None:\n+ min = a_min\n+ if max is None and a_max is not None:\n+ max = a_max\n+ return clip(number, a_min=min, a_max=max, out=out)\n+\n+\ndef _view(arr, dtype=None, type=None):\nlax._check_user_dtype_supported(dtype, \"view\")\nif type is not None:\n@@ -6082,7 +6096,7 @@ _operators = {\n# These numpy.ndarray methods are just refs to an equivalent numpy function\n_nondiff_methods = [\"all\", \"any\", \"argmax\", \"argmin\", \"argpartition\", \"argsort\",\n\"nonzero\", \"searchsorted\", \"round\"]\n-_diff_methods = [\"choose\", \"clip\", \"conj\", \"conjugate\", \"cumprod\", \"cumsum\",\n+_diff_methods = [\"choose\", \"conj\", \"conjugate\", \"cumprod\", \"cumsum\",\n\"diagonal\", \"dot\", \"max\", \"mean\", \"min\", \"prod\", \"ptp\",\n\"ravel\", \"repeat\", \"sort\", \"squeeze\", \"std\", \"sum\",\n\"swapaxes\", \"take\", \"tile\", \"trace\", \"var\"]\n@@ -6313,6 +6327,7 @@ def _set_shaped_array_attributes(shaped_array):\nsetattr(shaped_array, \"astype\", core.aval_method(_astype))\nsetattr(shaped_array, \"view\", core.aval_method(_view))\nsetattr(shaped_array, \"nbytes\", core.aval_property(_nbytes))\n+ setattr(shaped_array, \"clip\", core.aval_method(_clip))\nsetattr(shaped_array, \"_array_module\", staticmethod(__array_module__))\nsetattr(shaped_array, \"broadcast\", core.aval_method(lax.broadcast))\n@@ -6340,6 +6355,7 @@ def _set_device_array_base_attributes(device_array):\nsetattr(device_array, \"astype\", _astype)\nsetattr(device_array, \"view\", _view)\nsetattr(device_array, \"nbytes\", property(_nbytes))\n+ setattr(device_array, \"clip\", _clip)\n_set_device_array_base_attributes(DeviceArray)\n" } ]
Python
Apache License 2.0
google/jax
Fix argument names for jnp.ndarray.clip and deprecate the old ones
260,287
07.09.2021 03:25:54
25,200
0636f490f34d4a3c90cd6f2e3d83973643676934
Ensure that named axes consistently refer to global axis sizes in xmap Fixes
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1654,10 +1654,12 @@ def _map_unit(size: int, axis: int, aval: AbstractUnit) -> AbstractUnit:\ndef _map_shaped_array(size: int, axis: int, aval: ShapedArray) -> ShapedArray:\nassert aval.shape[axis] == size\n- return ShapedArray(tuple_delete(aval.shape, axis), aval.dtype)\n+ return ShapedArray(tuple_delete(aval.shape, axis), aval.dtype,\n+ named_shape=aval.named_shape)\ndef _unmap_shaped_array(size: int, axis: int, aval: ShapedArray) -> ShapedArray:\n- return ShapedArray(tuple_insert(aval.shape, axis, size), aval.dtype)\n+ return ShapedArray(tuple_insert(aval.shape, axis, size), aval.dtype,\n+ named_shape=aval.named_shape)\nAvalMapHandlerPair = Tuple[Callable, Callable]\naval_mapping_handlers: Dict[Type, AvalMapHandlerPair] = {\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -663,7 +663,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\n# TODO: Making axis substitution final style would allow us to avoid\n# tracing to jaxpr here\n- mapped_in_avals = [_delete_aval_axes(aval, in_axes)\n+ mapped_in_avals = [_delete_aval_axes(aval, in_axes, global_axis_sizes)\nfor aval, in_axes in zip(in_avals, in_axes)]\nwith core.extend_axis_env_nd(global_axis_sizes.items()):\njaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, mapped_in_avals)\n@@ -890,20 +890,23 @@ def _typecheck_xmap(\n*in_avals, call_jaxpr, name, in_axes, out_axes, donated_invars,\nglobal_axis_sizes, axis_resources, resource_env, backend,\nspmd_in_axes, spmd_out_axes):\n- binder_in_avals = [_insert_aval_axes(v.aval, a_in_axes, global_axis_sizes)\n+ axis_resource_count = _get_axis_resource_count(axis_resources, resource_env)\n+ local_axis_sizes = {axis: axis_resource_count[axis].to_local(global_size)\n+ for axis, global_size in global_axis_sizes.items()}\n+ binder_in_avals = [_insert_aval_axes(v.aval, a_in_axes, local_axis_sizes)\nfor v, a_in_axes in zip(call_jaxpr.invars, in_axes)]\nfor binder_in_aval, in_aval in zip(binder_in_avals, in_avals):\ncore.typecheck_assert(\ncore.typecompat(binder_in_aval, in_aval),\nf\"xmap passes operand {in_aval} to jaxpr expecting {binder_in_aval}\")\n- mapped_in_avals = [_delete_aval_axes(a, a_in_axes)\n+ mapped_in_avals = [_delete_aval_axes(a, a_in_axes, global_axis_sizes)\nfor a, a_in_axes in zip(in_avals, in_axes)]\nwith core.extend_axis_env_nd(global_axis_sizes.items()):\ncore._check_jaxpr(call_jaxpr, mapped_in_avals)\nmapped_out_avals = [v.aval for v in call_jaxpr.outvars]\n- out_avals = [_insert_aval_axes(a, a_out_axes, global_axis_sizes)\n+ out_avals = [_insert_aval_axes(a, a_out_axes, local_axis_sizes)\nfor a, a_out_axes in zip(mapped_out_avals, out_axes)]\nreturn out_avals\ncore.custom_typechecks[xmap_p] = _typecheck_xmap\n@@ -962,7 +965,7 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nassert primitive is xmap_p\nin_avals = [t.aval for t in tracers]\nglobal_axis_sizes = params['global_axis_sizes']\n- mapped_in_avals = [_delete_aval_axes(a, a_in_axes)\n+ mapped_in_avals = [_delete_aval_axes(a, a_in_axes, global_axis_sizes)\nfor a, a_in_axes in zip(in_avals, params['in_axes'])]\nwith core.extend_axis_env_nd(global_axis_sizes.items()):\njaxpr, mapped_out_avals, consts = trace_to_subjaxpr_dynamic(\n@@ -1043,7 +1046,7 @@ def _jaxpr_trace_process_xmap(self, primitive, f: lu.WrappedFun, tracers, params\nin_pvals = [t.pval for t in tracers]\nin_pvals = [pval if pval.is_known()\n- else PartialVal.unknown(_delete_aval_axes(pval[0], axes))\n+ else PartialVal.unknown(_delete_aval_axes(pval[0], axes, global_axis_sizes))\nfor pval, axes in zip(in_pvals, in_axes)]\nconst_axes_s = lu.Store()\n@@ -1434,21 +1437,21 @@ def _xmap_translation_rule_spmd(c, axis_env,\n# -------- helper functions --------\n-def _delete_aval_axes(aval, axes: AxisNamePos):\n+def _delete_aval_axes(aval, axes: AxisNamePos, global_axis_sizes):\nassert isinstance(aval, core.ShapedArray)\nshape = list(aval.shape)\nnamed_shape = dict(aval.named_shape)\n- for name, axis in sorted(axes.items(), key=lambda x: x[1], reverse=True):\n- named_shape[name] = shape[axis]\n- del shape[axis]\n+ for name, dim in sorted(axes.items(), key=lambda x: x[1], reverse=True):\n+ named_shape[name] = global_axis_sizes[name]\n+ del shape[dim]\nreturn aval.update(shape=tuple(shape), named_shape=named_shape)\n-def _insert_aval_axes(aval, axes: AxisNamePos, axis_sizes):\n+def _insert_aval_axes(aval, axes: AxisNamePos, local_axis_sizes):\nassert isinstance(aval, core.ShapedArray)\nshape = list(aval.shape)\nnamed_shape = dict(aval.named_shape)\n- for name, axis in sorted(axes.items(), key=lambda x: x[1]):\n- shape.insert(axis, axis_sizes[name])\n+ for name, dim in sorted(axes.items(), key=lambda x: x[1]):\n+ shape.insert(dim, local_axis_sizes[name])\nnamed_shape.pop(name, None) # The name might be missing --- it's a broadcast.\nreturn aval.update(shape=tuple(shape), named_shape=named_shape)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -456,6 +456,10 @@ def _pjit_translation_rule(c, axis_env, in_nodes, name_stack, backend, name,\nxla.call_translations[pjit_p] = _pjit_translation_rule\n+def remove_axis(axis_to_remove, axis):\n+ if axis == axis_to_remove: return ()\n+ return (axis,)\n+\ndef _pjit_batcher(insert_axis,\nvals_in, dims_in,\naxis_name, main_type,\n@@ -469,6 +473,8 @@ def _pjit_batcher(insert_axis,\nnew_jaxpr, is_mapped_out = batching.batch_jaxpr(\njaxpr, axis_size, is_mapped_in,\ninstantiate=False, axis_name=axis_name, main_type=main_type)\n+ # TODO(apaszke): Make batching remove axis names!\n+ new_jaxpr = core.subst_axis_names_jaxpr(new_jaxpr, partial(remove_axis, axis_name))\nnew_parts = (axis_name,) if insert_axis else ()\nin_axis_resources = tuple(\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1473,17 +1473,19 @@ class Mesh:\ntile_aval_nd(self.shape, axes, aval))\n-def tile_aval_nd(axis_sizes, in_axes: ArrayMapping, aval):\n+def tile_aval_nd(axis_sizes, in_axes: ArrayMapping, aval, tiling_sizes=None):\n+ if tiling_sizes is None:\n+ tiling_sizes = axis_sizes\nif aval is core.abstract_unit:\nreturn aval\nassert isinstance(aval, ShapedArray)\nshape = list(aval.shape)\nnamed_shape = dict(aval.named_shape)\nfor name, axis in in_axes.items():\n- assert shape[axis] % axis_sizes[name] == 0\n+ assert shape[axis] % tiling_sizes[name] == 0\nassert name not in named_shape\nnamed_shape[name] = axis_sizes[name]\n- shape[axis] //= axis_sizes[name]\n+ shape[axis] //= tiling_sizes[name]\nreturn aval.update(shape=tuple(shape), named_shape=named_shape)\ndef untile_aval_nd(axis_sizes, out_axes: ArrayMapping, aval):\n@@ -1548,7 +1550,9 @@ def mesh_callable(fun: lu.WrappedFun,\nf\"mesh with args {local_in_untiled_avals}. Argument mapping: {in_axes}.\")\n# 1. Trace to jaxpr and preprocess/verify it\n- in_tiled_avals = [tile_aval_nd(local_axis_sizes, aval_in_axes, aval)\n+ # Note that we tile by the local axis sizes, but use global axis sizes for named_shape\n+ in_tiled_avals = [tile_aval_nd(global_axis_sizes, aval_in_axes, aval,\n+ tiling_sizes=local_axis_sizes)\nfor aval, aval_in_axes in safe_zip(local_in_untiled_avals, in_axes)]\nif spmd_lowering:\n# TODO: Consider handling xmap's 'vectorize' in here. We can vmap once instead of vtile twice!\n" } ]
Python
Apache License 2.0
google/jax
Ensure that named axes consistently refer to global axis sizes in xmap Fixes #6959. PiperOrigin-RevId: 395210686
260,528
07.09.2021 15:37:04
-7,200
5ed619afbb47c382bc3edca2862abf7b2d92bb8a
Implement 'reflect' and 'mirror' padding modes for scipy.ndimage.map_coordinates
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/ndimage.py", "new_path": "jax/_src/scipy/ndimage.py", "diff": "@@ -30,10 +30,22 @@ from jax._src.util import safe_zip as zip\n_nonempty_prod = functools.partial(functools.reduce, operator.mul)\n_nonempty_sum = functools.partial(functools.reduce, operator.add)\n+\n+def _mirror_index_fixer(index, size):\n+ s = size - 1 # Half-wavelength of triangular wave\n+ # Scaled, integer-valued version of the triangular wave |x - round(x)|\n+ return jnp.abs((index + s) % (2 * s) - s)\n+\n+\n+def _reflect_index_fixer(index, size):\n+ return jnp.floor_divide(_mirror_index_fixer(2*index+1, 2*size+1) - 1, 2)\n+\n_INDEX_FIXERS = {\n'constant': lambda index, size: index,\n'nearest': lambda index, size: jnp.clip(index, 0, size - 1),\n'wrap': lambda index, size: index % size,\n+ 'mirror': _mirror_index_fixer,\n+ 'reflect': _reflect_index_fixer,\n}\n@@ -112,7 +124,7 @@ def _map_coordinates(input, coordinates, order, mode, cval):\n@_wraps(scipy.ndimage.map_coordinates, lax_description=textwrap.dedent(\"\"\"\\\nOnly nearest neighbor (``order=0``), linear interpolation (``order=1``) and\n- modes ``'constant'``, ``'nearest'`` and ``'wrap'`` are currently supported.\n+ modes ``'constant'``, ``'nearest'``, ``'wrap'`` ``'mirror'`` and ``'reflect'`` are currently supported.\nNote that interpolation near boundaries differs from the scipy function,\nbecause we fixed an outstanding bug (https://github.com/scipy/scipy/issues/2640);\nthis function interprets the ``mode`` argument as documented by SciPy, but\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_ndimage_test.py", "new_path": "tests/scipy_ndimage_test.py", "diff": "@@ -74,7 +74,7 @@ class NdimageTest(jtu.JaxTestCase):\nfor dtype in float_dtypes + int_dtypes\nfor coords_dtype in float_dtypes\nfor order in [0, 1]\n- for mode in ['wrap', 'constant', 'nearest']\n+ for mode in ['wrap', 'constant', 'nearest', 'mirror', 'reflect']\nfor cval in ([0, -1] if mode == 'constant' else [0])\nfor impl, rng_factory in [\n(\"original\", partial(jtu.rand_uniform, low=0, high=1)),\n@@ -111,7 +111,7 @@ class NdimageTest(jtu.JaxTestCase):\nlsp_ndimage.map_coordinates(x, c, order=2)\nwith self.assertRaisesRegex(\nNotImplementedError, 'does not yet support mode'):\n- lsp_ndimage.map_coordinates(x, c, order=1, mode='reflect')\n+ lsp_ndimage.map_coordinates(x, c, order=1, mode='grid-wrap')\nwith self.assertRaisesRegex(ValueError, 'sequence of length'):\nlsp_ndimage.map_coordinates(x, [c, c], order=1)\n" } ]
Python
Apache License 2.0
google/jax
Implement 'reflect' and 'mirror' padding modes for scipy.ndimage.map_coordinates
260,287
07.09.2021 07:53:42
25,200
0c03e9804688c4fd3b27e851b6928c4563b7842b
Don't cast out_axis_resources to a tuple automatically It's confusing and makes it impossible to specify non-trivial pytrees of out_axis_resources for functions that return lists. Also extend the error messages to be less confusing and hint at potential fixes.
[ { "change_type": "MODIFY", "old_path": "jax/api_util.py", "new_path": "jax/api_util.py", "diff": "@@ -255,12 +255,13 @@ def wrap_hashably(arg):\nelse:\nreturn Hashable(arg)\n-def flatten_axes(name, treedef, axis_tree, *, kws=False):\n+def flatten_axes(name, treedef, axis_tree, *, kws=False, tupled_args=False):\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# and return the flattened result\n# TODO(mattjj,phawkins): improve this implementation\n+\nproxy = object()\ndummy = tree_unflatten(treedef, [object()] * treedef.num_leaves)\naxes = []\n@@ -274,9 +275,22 @@ def flatten_axes(name, treedef, axis_tree, *, kws=False):\ntreedef, leaf = treedef_children(treedef)\nassert treedef_is_leaf(leaf)\naxis_tree, _ = axis_tree\n+ hint = \"\"\n+ if tupled_args:\n+ hint += (f\" Note that {name} that are non-trivial pytrees should always be \"\n+ f\"wrapped in a tuple representing the argument list.\")\n+ if len(treedef.children()) == 1:\n+ try:\n+ flatten_axes(name, treedef, (axis_tree,))\n+ except ValueError:\n+ pass # That's not the issue.\n+ else:\n+ hint += (f\" In particular, you're passing in a single argument which \"\n+ f\"means that {name} might need to be wrapped in \"\n+ f\"a singleton tuple.\")\nraise ValueError(f\"{name} specification must be a tree prefix of the \"\nf\"corresponding value, got specification {axis_tree} \"\n- f\"for value tree {treedef}.\") from None\n+ f\"for value tree {treedef}.{hint}\") 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/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -292,7 +292,8 @@ def _parse_entry(arg_name, entry):\nif entry and entry[-1] == ...:\nconstr = AxisNamePos\nentry = entry[:-1]\n- user_repr = str(entry + [DotDotDotRepr()])\n+ tail = [DotDotDotRepr()] if isinstance(entry, list) else (DotDotDotRepr(),)\n+ user_repr = str(entry + tail)\nelse:\nconstr = partial(AxisNamePosWithRank, expected_rank=len(entry))\nuser_repr = str(entry)\n@@ -498,15 +499,13 @@ def xmap(fun: Callable,\nwarn(\"xmap is an experimental feature and probably has bugs!\")\n_check_callable(fun)\n+ if isinstance(in_axes, list) and not _is_axes_leaf(in_axes):\n# To be a tree prefix of the positional args tuple, in_axes can never be a\n# list: if in_axes is not a leaf, it must be a tuple of trees. However,\n# in cases like these users expect tuples and lists to be treated\n# essentially interchangeably, so we canonicalize lists to tuples here\n# rather than raising an error. https://github.com/google/jax/issues/2367\n- if isinstance(in_axes, list) and not _is_axes_leaf(in_axes):\nin_axes = tuple(in_axes)\n- if isinstance(out_axes, list) and not _is_axes_leaf(out_axes):\n- out_axes = tuple(out_axes)\nif in_axes == (): # Allow empty argument lists\nin_axes, in_axes_entries = (), []\n@@ -578,12 +577,12 @@ def xmap(fun: Callable,\ndonated_invars = donation_vector(donate_argnums, args, ())\nelse:\ndonated_invars = (False,) * len(args_flat)\n- in_axes_flat = flatten_axes(\"xmap in_axes\", in_tree, in_axes)\n+ in_axes_flat = _flatten_axes(\"xmap in_axes\", in_tree, in_axes, tupled_args=True)\n# Some pytree containers might be unhashable, so we flatten the out_axes\n# pytree into a treedef and entries which are guaranteed to be hashable.\nout_axes_thunk = HashableFunction(\n- lambda: tuple(flatten_axes(\"xmap out_axes\", out_tree(), out_axes)),\n+ lambda: tuple(_flatten_axes(\"xmap out_axes\", out_tree(), out_axes, tupled_args=False)),\nclosure=(out_axes_entries, out_axes_treedef))\naxis_resource_count = _get_axis_resource_count(normalized_axis_resources, resource_env)\n@@ -1675,6 +1674,19 @@ def _fix_inferred_spmd_sharding(jaxpr, resource_env, gen_fresh_name = None):\neqn.source_info))\nreturn core.Jaxpr(jaxpr.constvars, jaxpr.invars, jaxpr.outvars, new_eqns)\n+def _flatten_axes(what, tree, axes, tupled_args):\n+ try:\n+ return tuple(flatten_axes(what, tree, axes, tupled_args=tupled_args))\n+ except ValueError:\n+ pass\n+ # Replace axis_resources with unparsed versions to avoid revealing internal details\n+ flatten_axes(what, tree, tree_map(lambda parsed: NoQuotesStr(parsed.user_repr), axes),\n+ tupled_args=tupled_args)\n+ raise AssertionError(\"Please open a bug request!\") # This should be unreachable\n+\n+class NoQuotesStr(str):\n+ __repr__ = str.__str__\n+\n# -------- soft_pmap --------\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -37,7 +37,7 @@ from ..interpreters import partial_eval as pe\nfrom ..interpreters.sharded_jit import PartitionSpec\nfrom ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\n-from ..tree_util import tree_flatten, tree_unflatten\n+from ..tree_util import tree_map, tree_flatten, tree_unflatten\nfrom .._src.util import (extend_name_stack, HashableFunction, safe_zip,\nwrap_name, wraps, distributed_debug_log,\nsplit_list, cache, tuple_insert)\n@@ -160,15 +160,13 @@ def pjit(fun: Callable,\nwarn(\"pjit is an experimental feature and probably has bugs!\")\n_check_callable(fun)\n+ if isinstance(in_axis_resources, list):\n# To be a tree prefix of the positional args tuple, in_axes can never be a\n# list: if in_axes is not a leaf, it must be a tuple of trees. However,\n# in cases like these users expect tuples and lists to be treated\n# essentially interchangeably, so we canonicalize lists to tuples here\n# rather than raising an error. https://github.com/google/jax/issues/2367\n- if isinstance(in_axis_resources, list):\nin_axis_resources = tuple(in_axis_resources)\n- if isinstance(out_axis_resources, list):\n- out_axis_resources = tuple(out_axis_resources)\nin_axis_resources, in_axis_resources_entries, _ = \\\n_prepare_axis_resources(in_axis_resources, \"in_axis_resources\")\n@@ -238,12 +236,23 @@ def hashable_pytree(pytree):\nreturn HashableFunction(lambda: tree_unflatten(treedef, vals),\nclosure=(treedef, vals))\n+def flatten_axis_resources(what, tree, axis_resources, tupled_args):\n+ try:\n+ return tuple(flatten_axes(what, tree, axis_resources, tupled_args=tupled_args))\n+ except ValueError:\n+ pass\n+ # Replace axis_resources with unparsed versions to avoid revealing internal details\n+ flatten_axes(what, tree, tree_map(lambda parsed: parsed.user_spec, axis_resources),\n+ tupled_args=tupled_args)\n+ raise AssertionError(\"Please open a bug request!\") # This should be unreachable\n+\n@lu.cache\ndef _pjit_jaxpr(fun, mesh, local_in_avals,\nin_tree, in_axis_resources_thunk,\nout_tree, out_axis_resources_thunk):\n- in_axis_resources_flat = tuple(flatten_axes(\"pjit in_axis_resources\",\n- in_tree, in_axis_resources_thunk()))\n+ in_axis_resources_flat = flatten_axis_resources(\n+ \"pjit in_axis_resources\", in_tree,\n+ in_axis_resources_thunk(), tupled_args=True)\n_check_shapes_against_resources(\"pjit arguments\", False, mesh.local_mesh.shape,\nlocal_in_avals, in_axis_resources_flat)\nglobal_in_avals = local_to_global(mesh, local_in_avals, in_axis_resources_flat)\n@@ -251,8 +260,9 @@ def _pjit_jaxpr(fun, mesh, local_in_avals,\njaxpr, global_out_avals, consts = pe.trace_to_jaxpr_dynamic(fun, global_in_avals)\njaxpr = core.ClosedJaxpr(jaxpr, consts)\n- out_axis_resources_flat = tuple(flatten_axes(\"pjit out_axis_resources\",\n- out_tree(), out_axis_resources_thunk()))\n+ out_axis_resources_flat = flatten_axis_resources(\n+ \"pjit out_axis_resources\", out_tree(),\n+ out_axis_resources_thunk(), tupled_args=False)\n_check_shapes_against_resources(\"pjit outputs\", mesh.is_multi_process, mesh.shape,\nglobal_out_avals, out_axis_resources_flat)\n# lu.cache needs to be able to create weakrefs to outputs, so we can't return a plain tuple\n" }, { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import re\nfrom functools import partial\nimport logging\nimport threading\n@@ -659,6 +660,37 @@ class PJitErrorTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(NotImplementedError, \"6876\"):\njax.linearize(f, x, y)\n+ @jtu.with_mesh([('x', 2)])\n+ def testAxisResourcesMismatch(self):\n+ x = jnp.ones([])\n+ p = [None, None, None]\n+ pjit(lambda x: x, (p,), p)([x, x, x]) # OK\n+ error = re.escape(\n+ r\"pjit in_axis_resources specification must be a tree prefix of the \"\n+ r\"corresponding value, got specification (None, None, None) for value \"\n+ r\"tree PyTreeDef((*, *)). Note that pjit in_axis_resources that are \"\n+ r\"non-trivial pytrees should always be wrapped in a tuple representing \"\n+ r\"the argument list.\")\n+ with self.assertRaisesRegex(ValueError, error):\n+ pjit(lambda x, y: x, p, p)(x, x) # Error, but make sure we hint at tupling\n+ # TODO(apaszke): Disable implicit list casts and enable this\n+ # error = re.escape(\n+ # r\"pjit in_axis_resources specification must be a tree prefix of the \"\n+ # r\"corresponding value, got specification (None, None, None) for value \"\n+ # r\"tree PyTreeDef(([*, *, *],)). Note that pjit in_axis_resources that \"\n+ # r\"are non-trivial pytrees should always be wrapped in a tuple representing \"\n+ # r\"the argument list. In particular, you're passing in a single argument \"\n+ # r\"which means that pjit in_axis_resources might need to be wrapped in a \"\n+ # r\"singleton tuple.\")\n+ # with self.assertRaisesRegex(ValueError, error):\n+ # pjit(lambda x: x, p, p)([x, x, x]) # Error, but make sure we hint at singleton tuple\n+ error = re.escape(\n+ r\"pjit out_axis_resources specification must be a tree prefix of the \"\n+ r\"corresponding value, got specification [[None, None, None], None] for \"\n+ r\"value tree PyTreeDef([*, *, *]).\")\n+ with self.assertRaisesRegex(ValueError, error):\n+ pjit(lambda x: x, (p,), [p, None])([x, x, x]) # Error, we raise a generic tree mismatch message\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -233,8 +233,8 @@ class XMapTest(XMapTestCase):\ndevices = np.array(local_devices[:4]).reshape((2, 2))\nwith mesh(devices, ('x', 'y')):\nfm = xmap(f,\n- in_axes=[{0: 'a', 1: 'b'}, ['c', ...]],\n- out_axes=[{0: 'a', 1: 'b'}, ['c', ...]],\n+ in_axes=({0: 'a', 1: 'b'}, ['c', ...]),\n+ out_axes=({0: 'a', 1: 'b'}, ['c', ...]),\naxis_resources={'a': 'x', 'b': 'y', 'c': 'x'})\nashape = (16, 8, 5)\na = jnp.arange(np.prod(ashape)).reshape(ashape)\n@@ -247,8 +247,8 @@ class XMapTest(XMapTestCase):\n@jtu.with_mesh([('x', 2), ('y', 2)])\ndef testCollectiveReduce(self):\nfm = xmap(lambda a, b: (lax.psum(a * 2, 'a'), b * 4),\n- in_axes=[['a', 'b', ...], {0: 'c'}],\n- out_axes=[['b', ...], {0: 'c'}],\n+ in_axes=(['a', 'b', ...], {0: 'c'}),\n+ out_axes=(['b', ...], {0: 'c'}),\naxis_resources={'a': 'x', 'b': 'y', 'c': 'x'})\nashape = (16, 8, 5)\na = jnp.arange(np.prod(ashape)).reshape(ashape)\n@@ -286,7 +286,7 @@ class XMapTest(XMapTestCase):\ndef testOneLogicalTwoMeshAxesBasic(self):\ndef f(v):\nreturn lax.psum(v * 2, 'a'), v * 4\n- fm = xmap(f, in_axes=['a', ...], out_axes=[{}, {1: 'a'}],\n+ fm = xmap(f, in_axes=['a', ...], out_axes=({}, {1: 'a'}),\naxis_resources={'a': ('x', 'y')})\nvshape = (4, 5)\nv = jnp.arange(np.prod(vshape)).reshape(vshape)\n@@ -515,7 +515,7 @@ class XMapTest(XMapTestCase):\ndef testAutodiffBroadcast(self):\nf = xmap(lambda x, y: jnp.cos(lax.dot(x, jnp.sin(y),\nprecision=lax.Precision.HIGHEST)),\n- in_axes=[['i', ...], {}], out_axes=['i', ...])\n+ in_axes=(['i', ...], {}), out_axes=['i', ...])\nx = jnp.arange(12, dtype=jnp.float32).reshape((3, 4)) / 100\ny = jnp.arange(20, dtype=jnp.float32).reshape((4, 5)) / 100\njtu.check_grads(f, (x, y), order=2, modes=['fwd'])\n@@ -528,7 +528,7 @@ class XMapTest(XMapTestCase):\ndef testAutodiffNoBroadcast(self):\nf = xmap(lambda x, y: jnp.cos(lax.dot(x, jnp.sin(y),\nprecision=lax.Precision.HIGHEST)),\n- in_axes=[['i', ...], [None, 'i']], out_axes=['i'])\n+ in_axes=(['i', ...], [None, 'i']), out_axes=['i'])\nx = jnp.arange(12, dtype=jnp.float32).reshape((3, 4)) / 100\ny = jnp.arange(12, dtype=jnp.float32).reshape((4, 3)) / 100\njtu.check_grads(f, (x, y), order=2)\n@@ -891,7 +891,7 @@ class PDotTests(XMapTestCase):\nreturn lax.pdot(x, y, 'i')\nf_mapped = xmap(f,\n- in_axes=[{1: 'i'}, {0: 'i'}],\n+ in_axes=({1: 'i'}, {0: 'i'}),\nout_axes={},\naxis_resources={'i': 'r1'})\n@@ -913,7 +913,7 @@ class PDotTests(XMapTestCase):\ny = rng.randn(2, 8, 5)\nf_mapped = xmap(f,\n- in_axes=[{0: 'j', 2: 'i'}, {0: 'j', 1: 'i'}],\n+ in_axes=({0: 'j', 2: 'i'}, {0: 'j', 1: 'i'}),\nout_axes=['j', ...],\naxis_resources={'i': 'r1'})\n@@ -931,7 +931,7 @@ class PDotTests(XMapTestCase):\ny = rng.randn(2, 8, 5)\nf_mapped = xmap(f,\n- in_axes=[{0: 'j', 2: 'i'}, {0: 'j', 1: 'i'}],\n+ in_axes=({0: 'j', 2: 'i'}, {0: 'j', 1: 'i'}),\nout_axes=['j', ...],\naxis_resources={'j': 'r1'})\n@@ -964,7 +964,7 @@ class PDotTests(XMapTestCase):\npos_batch=pdot_spec.pos_batch_after_mapping,\npos_contract=pdot_spec.pos_contract_after_mapping)\n- fun = xmap(pdot_fun, in_axes=[pdot_spec.lhs_in_axes, pdot_spec.rhs_in_axes],\n+ fun = xmap(pdot_fun, in_axes=(pdot_spec.lhs_in_axes, pdot_spec.rhs_in_axes),\nout_axes=[*pdot_spec.batch_names, ...],\naxis_resources=axis_resources)\n@@ -1007,8 +1007,8 @@ class PDotTests(XMapTestCase):\nreturn pdot_vjp(out_bar)\nfun = xmap(pdot_fun,\n- in_axes=[pdot_spec.lhs_in_axes, pdot_spec.rhs_in_axes,\n- [*pdot_spec.batch_names, ...]],\n+ in_axes=(pdot_spec.lhs_in_axes, pdot_spec.rhs_in_axes,\n+ [*pdot_spec.batch_names, ...]),\nout_axes=(pdot_spec.lhs_in_axes, pdot_spec.rhs_in_axes),\naxis_resources=axis_resources)\n@@ -1273,6 +1273,37 @@ class XMapErrorTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(RuntimeError, error):\nfm(x)\n+ def testAxesMismatch(self):\n+ x = jnp.ones((4,))\n+ p = [['x'], ['x'], ['x']]\n+ xmap(lambda x: x, (p,), p)([x, x, x]) # OK\n+ xmap(lambda x: x, [p], p)([x, x, x]) # OK\n+ error = re.escape(\n+ r\"xmap in_axes specification must be a tree prefix of the \"\n+ r\"corresponding value, got specification (['x'], ['x'], ['x']) for value \"\n+ r\"tree PyTreeDef((*, *)). Note that xmap in_axes that are \"\n+ r\"non-trivial pytrees should always be wrapped in a tuple representing \"\n+ r\"the argument list.\")\n+ with self.assertRaisesRegex(ValueError, error):\n+ xmap(lambda x, y: x, p, p)(x, x) # Error, but make sure we hint at tupling\n+ # TODO(apaszke): Disable implicit list casts and enable this\n+ # error = re.escape(\n+ # r\"xmap in_axes specification must be a tree prefix of the \"\n+ # r\"corresponding value, got specification (['x'], ['x'], ['x']) for value \"\n+ # r\"tree PyTreeDef(([*, *, *],)). Note that xmap in_axes that \"\n+ # r\"are non-trivial pytrees should always be wrapped in a tuple representing \"\n+ # r\"the argument list. In particular, you're passing in a single argument \"\n+ # r\"which means that xmap in_axes might need to be wrapped in a \"\n+ # r\"singleton tuple.\")\n+ # with self.assertRaisesRegex(ValueError, error):\n+ # xmap(lambda x: x, p, p)([x, x, x]) # Error, but make sure we hint at singleton tuple\n+ error = re.escape(\n+ r\"xmap out_axes specification must be a tree prefix of the \"\n+ r\"corresponding value, got specification ([['x'], ['x'], ['x']], ['x']) for \"\n+ r\"value tree PyTreeDef([*, *, *]).\")\n+ with self.assertRaisesRegex(ValueError, error):\n+ xmap(lambda x: x, (p,), (p, ['x']))([x, x, x]) # Error, we raise a generic tree mismatch message\n+\nclass NamedAutodiffTests(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Don't cast out_axis_resources to a tuple automatically It's confusing and makes it impossible to specify non-trivial pytrees of out_axis_resources for functions that return lists. Also extend the error messages to be less confusing and hint at potential fixes. PiperOrigin-RevId: 395246450
260,287
08.09.2021 01:41:38
25,200
1158530faa390bf6f4cddb8655f26b0503e938a6
Remove axis name from named_shape when unmapping avals Even though `vmap` and `pmap` don't use avals with names, the batching infrastructure is used to implement xmap and pjit. So while we keep the introduction of names carefully scoped, forgetting to remove them at the right points leads to extremely confusing errors.
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -2460,7 +2460,7 @@ def device_put_replicated(x: Any, devices: Sequence[xc.Device]):\nraise ValueError(\"`devices` argument to `device_put_replicated must be \"\n\"a non-empty sequence.\")\ndef _device_put_replicated(x):\n- aval = core.unmapped_aval(len(devices), 0,\n+ aval = core.unmapped_aval(len(devices), None, 0,\ncore.raise_to_shaped(core.get_aval(x)))\nassert isinstance(aval, core.ShapedArray) and aval._num_buffers == 1\nbuf, = xla.device_put(x, devices[0])\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -1643,7 +1643,7 @@ def _scan_partial_eval(trace, *tracers, reverse, length, num_consts, num_carry,\n# outputs from the jaxpr here, and updating out_flat below.\nextensive_invars = jaxpr_1_opt.jaxpr.invars[num_consts_1 + num_carry:]\nextensive_outvars = jaxpr_1_opt.jaxpr.outvars[num_carry:]\n- extensive_avals = [core.unmapped_aval(length, 0, core.raise_to_shaped(v.aval))\n+ extensive_avals = [core.unmapped_aval(length, None, 0, core.raise_to_shaped(v.aval))\nfor v in extensive_outvars]\nfwd_extensive = [num_consts + num_carry + extensive_invars.index(v)\nif v in extensive_invars else None for v in extensive_outvars]\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1642,24 +1642,28 @@ def mapped_aval(size: int, axis: int, aval: AbstractValue) -> AbstractValue:\nelse:\nraise TypeError(f\"no mapping handler for {aval} of type {type(aval)}\")\n-def unmapped_aval(size: int, axis: int, aval: AbstractValue) -> AbstractValue:\n+def unmapped_aval(size: int, axis_name, axis: int, aval: AbstractValue) -> AbstractValue:\n_, handler = aval_mapping_handlers.get(type(aval), (None, None))\nif handler is not None:\n- return handler(size, axis, aval)\n+ return handler(size, axis_name, axis, aval)\nelse:\nraise TypeError(f\"no unmapping handler for {aval} of type {type(aval)}\")\n-def _map_unit(size: int, axis: int, aval: AbstractUnit) -> AbstractUnit:\n- return aval\n+def _map_unit(*_) -> AbstractUnit:\n+ return abstract_unit\ndef _map_shaped_array(size: int, axis: int, aval: ShapedArray) -> ShapedArray:\nassert aval.shape[axis] == size\n+ # TODO: Extend the named shape\nreturn ShapedArray(tuple_delete(aval.shape, axis), aval.dtype,\nnamed_shape=aval.named_shape)\n-def _unmap_shaped_array(size: int, axis: int, aval: ShapedArray) -> ShapedArray:\n+def _unmap_shaped_array(size: int, axis_name, axis: int, aval: ShapedArray) -> ShapedArray:\n+ named_shape = dict(aval.named_shape)\n+ # TODO: Make this mandatory\n+ named_shape.pop(axis_name, None)\nreturn ShapedArray(tuple_insert(aval.shape, axis, size), aval.dtype,\n- named_shape=aval.named_shape)\n+ named_shape=named_shape)\nAvalMapHandlerPair = Tuple[Callable, Callable]\naval_mapping_handlers: Dict[Type, AvalMapHandlerPair] = {\n@@ -1974,6 +1978,9 @@ def check_map(prim, in_avals, params):\ntypecheck_assert(\"axis_size\" in params,\nf\"Map primitive {prim} missing 'axis_size' parameter\")\naxis_size = params[\"axis_size\"]\n+ typecheck_assert(\"axis_name\" in params,\n+ f\"Map primitive {prim} missing 'axis_name' parameter\")\n+ axis_name = params[\"axis_name\"]\ntypecheck_assert(\"in_axes\" in params,\nf\"Map primitive {prim} missing 'in_axes' parameter\")\nin_axes = params[\"in_axes\"]\n@@ -1981,7 +1988,7 @@ def check_map(prim, in_avals, params):\nf\"Map primitive {prim} missing 'out_axes' parameter\")\nout_axes = params[\"out_axes\"]\n- binder_avals = [unmapped_aval(axis_size, in_axis, v.aval)\n+ binder_avals = [unmapped_aval(axis_size, axis_name, in_axis, v.aval)\nif in_axis is not None else v.aval\nfor v, in_axis in zip(call_jaxpr.invars, in_axes)]\nfor binder_aval, in_aval in zip(binder_avals, in_avals):\n@@ -1996,7 +2003,7 @@ def check_map(prim, in_avals, params):\n_check_jaxpr(call_jaxpr, mapped_avals)\nmapped_out_avals = [v.aval for v in call_jaxpr.outvars]\n- out_avals = [unmapped_aval(axis_size, out_axis, aval) if out_axis is not None else aval\n+ out_avals = [unmapped_aval(axis_size, axis_name, out_axis, aval) if out_axis is not None else aval\nfor aval, out_axis in zip(mapped_out_avals, out_axes)]\nreturn out_avals\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/djax.py", "new_path": "jax/experimental/djax.py", "diff": "@@ -988,7 +988,7 @@ def batch_jaxpr(jaxpr, axis_size, in_dims):\ndimvars = dict((v, v.aval) for v in jaxpr.in_dim_binders)\nin_avals = [_replace_vars_with_avals(dimvars, v.aval) for v in jaxpr.in_binders]\n- in_avals = [core.unmapped_aval(axis_size, d, aval)\n+ in_avals = [core.unmapped_aval(axis_size, None, d, aval)\nif d is not batching.not_mapped else aval\nfor d, aval in zip(in_dims, in_avals)]\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -466,10 +466,6 @@ def _pjit_translation_rule(c, axis_env, in_nodes, name_stack, backend, name,\nxla.call_translations[pjit_p] = _pjit_translation_rule\n-def remove_axis(axis_to_remove, axis):\n- if axis == axis_to_remove: return ()\n- return (axis,)\n-\ndef _pjit_batcher(insert_axis,\nvals_in, dims_in,\naxis_name, main_type,\n@@ -483,8 +479,6 @@ def _pjit_batcher(insert_axis,\nnew_jaxpr, is_mapped_out = batching.batch_jaxpr(\njaxpr, axis_size, is_mapped_in,\ninstantiate=False, axis_name=axis_name, main_type=main_type)\n- # TODO(apaszke): Make batching remove axis names!\n- new_jaxpr = core.subst_axis_names_jaxpr(new_jaxpr, partial(remove_axis, axis_name))\nnew_parts = (axis_name,) if insert_axis else ()\nin_axis_resources = tuple(\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -622,7 +622,7 @@ def map_transpose(primitive, params, call_jaxpr, args, ct, _, reduce_axes):\nassert len(in_axes) == len(arg_cts)\ndef unmap_zero(zero, in_axis):\nreturn (zero if in_axis is None else\n- Zero(core.unmapped_aval(params['axis_size'], in_axis, zero.aval)))\n+ Zero(core.unmapped_aval(params['axis_size'], params['axis_name'], in_axis, zero.aval)))\narg_cts = (unmap_zero(arg_ct, in_axis) if type(arg_ct) is Zero else\narg_ct if in_axis is not None else\narg_ct.sum(0)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -270,25 +270,25 @@ def _main_trace_for_axis_names(main_trace: core.MainTrace,\ndef batch_custom_vjp_bwd(bwd, axis_name, axis_size, in_dims, out_dim_dests, main_type):\nbwd, out_dims_thunk = batch_subtrace(bwd)\nreturn _match_axes_and_sum(batchfun(bwd, axis_name, axis_size, in_dims, main_type),\n- axis_size, out_dims_thunk, out_dim_dests)\n+ axis_size, axis_name, out_dims_thunk, out_dim_dests)\n@lu.transformation\n-def _match_axes_and_sum(axis_size, out_dims_thunk, out_dim_dests, *in_vals):\n+def _match_axes_and_sum(axis_size, axis_name, out_dims_thunk, out_dim_dests, *in_vals):\n# this is like _match_axes, but we do reduce-sums as needed\nout_vals = yield in_vals, {}\n- yield map(partial(_matchaxis_symbolic_zeros, axis_size, sum_match=True),\n+ yield map(partial(_matchaxis_symbolic_zeros, axis_size, axis_name, sum_match=True),\nout_dims_thunk(), out_dim_dests, out_vals)\n-def _matchaxis_symbolic_zeros(sz, src, dst, x, sum_match=False):\n+def _matchaxis_symbolic_zeros(sz, name, src, dst, x, sum_match=False):\n# Just like `matchaxis`, but handles symbolic zeros using ad_util.py\nif isinstance(x, Zero):\nif src == dst:\nreturn x\nelif type(src) == type(dst) == int:\naval = core.mapped_aval(sz, src, x.aval)\n- return Zero(core.unmapped_aval(sz, dst, aval))\n+ return Zero(core.unmapped_aval(sz, name, dst, aval))\nelif src is not_mapped and dst is not not_mapped:\n- return Zero(core.unmapped_aval(sz, dst, x.aval))\n+ return Zero(core.unmapped_aval(sz, name, dst, x.aval))\nelif dst is not_mapped and sum_match:\nreturn Zero(core.mapped_aval(sz, src, x.aval))\nelse:\n@@ -488,7 +488,7 @@ def batch_jaxpr_axes(closed_jaxpr, axis_size, in_axes, out_axes, axis_name, main\nf = lu.wrap_init(core.jaxpr_as_fun(closed_jaxpr))\nf, out_batched = batch_subtrace_instantiate(f, axis_size, out_axes)\nf = batchfun(f, axis_name, axis_size, in_axes, main_type)\n- avals_in = [core.unmapped_aval(axis_size, b, aval) if b is not not_mapped\n+ avals_in = [core.unmapped_aval(axis_size, axis_name, b, aval) if b is not not_mapped\nelse aval for aval, b in zip(closed_jaxpr.in_avals, in_axes)]\njaxpr_out, _, consts = pe.trace_to_jaxpr_dynamic(f, avals_in)\nreturn core.ClosedJaxpr(jaxpr_out, consts), out_batched()\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -196,7 +196,7 @@ class JaxprTrace(Trace):\njaxpr, out_pvals, consts, env_tracers = self.partial_eval(\nf, in_pvals, app, instantiate=False)\nif primitive.map_primitive:\n- unmapped_aval = partial(core.unmapped_aval, params['axis_size'])\n+ unmapped_aval = partial(core.unmapped_aval, params['axis_size'], params['axis_name'])\nout_axes = params['out_axes_thunk']()\nout_pvals = [pval if pval.is_known() else\nPartialVal.unknown(unmapped_aval(out_axis, pval[0])) if out_axis is not None else\n@@ -258,7 +258,7 @@ class JaxprTrace(Trace):\nif primitive.map_primitive:\nout_axes = params['out_axes_thunk']()\nsz = params['axis_size']\n- out_pvs = [None if pv is None else core.unmapped_aval(sz, ax, pv)\n+ out_pvs = [None if pv is None else core.unmapped_aval(sz, params['axis_name'], ax, pv)\nfor pv, ax in zip(out_pvs, out_axes)]\ndef todo(x):\n@@ -1319,7 +1319,7 @@ class DynamicJaxprTrace(core.Trace):\njaxpr, reduced_out_avals, consts = trace_to_subjaxpr_dynamic(\nf, self.main, reduced_in_avals)\nout_axes = params['out_axes_thunk']()\n- out_avals = [core.unmapped_aval(params['axis_size'], out_axis, a)\n+ out_avals = [core.unmapped_aval(axis_size, axis_name, out_axis, a)\nif out_axis is not None else a\nfor a, out_axis in zip(reduced_out_avals, out_axes)]\nsource_info = source_info_util.current()\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -975,7 +975,7 @@ def parallel_callable(fun: lu.WrappedFun,\nlocal_out_avals = [get_local_aval(aval, parts, lparts)\nfor aval, parts, lparts\nin safe_zip(out_sharded_avals, out_parts, local_out_parts)]\n- local_unmapped_avals = [core.unmapped_aval(axis_size, out_axis, aval)\n+ local_unmapped_avals = [core.unmapped_aval(axis_size, axis_name, out_axis, aval)\nif out_axis is not None else aval\nfor aval, out_axis in safe_zip(local_out_avals, out_axes)]\n" } ]
Python
Apache License 2.0
google/jax
Remove axis name from named_shape when unmapping avals Even though `vmap` and `pmap` don't use avals with names, the batching infrastructure is used to implement xmap and pjit. So while we keep the introduction of names carefully scoped, forgetting to remove them at the right points leads to extremely confusing errors. PiperOrigin-RevId: 395423006
260,287
08.09.2021 10:54:09
25,200
5b4757d234ad52f56a32caad450dc0ae2ea02bf6
New lowering APIs for pjit This is the first in a series of refactoring patches that add the new AOT APIs to all JIT-like transforms in JAX. I'm sending this early, because I expect that it will come in handy when adding reverse-mode AD support for pjit.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -560,7 +560,7 @@ def xmap(fun: Callable,\nhas_input_rank_assertions = any(spec.expected_rank is not None for spec in in_axes_entries)\nhas_output_rank_assertions = any(spec.expected_rank is not None for spec in out_axes_entries)\n- def fun_mapped(*args):\n+ def infer_params(*args):\n# Putting this outside of fun_mapped would make resources lexically scoped\nresource_env = thread_resources.env\navailable_resources = set(resource_env.shape.keys())\n@@ -609,8 +609,7 @@ def xmap(fun: Callable,\nraise ValueError(f\"xmap argument has an in_axes specification of {spec.user_repr}, \"\nf\"which asserts that it should be of rank {spec.expected_rank}, \"\nf\"but the argument has rank {arg.ndim} (and shape {arg.shape})\")\n- out_flat = xmap_p.bind(\n- fun_flat, *args_flat,\n+ params = dict(\nname=getattr(fun, '__name__', '<unnamed function>'),\nin_axes=tuple(in_axes_flat),\nout_axes_thunk=out_axes_thunk,\n@@ -621,14 +620,22 @@ def xmap(fun: Callable,\nbackend=backend,\nspmd_in_axes=None,\nspmd_out_axes_thunk=None)\n+ return fun_flat, args_flat, params, out_tree\n+\n+ def verify_outputs(out_flat, out_tree, params):\nif has_output_rank_assertions:\n- for out, spec in zip(out_flat, out_axes_thunk()):\n+ for out, spec in zip(out_flat, params['out_axes_thunk']()):\nif spec.expected_rank is not None and spec.expected_rank != out.ndim:\nraise ValueError(f\"xmap output has an out_axes specification of {spec.user_repr}, \"\nf\"which asserts that it should be of rank {spec.expected_rank}, \"\nf\"but the output has rank {out.ndim} (and shape {out.shape})\")\nreturn tree_unflatten(out_tree(), out_flat)\n+ def fun_mapped(*args):\n+ fun_flat, args_flat, params, out_tree = infer_params(*args)\n+ out_flat = xmap_p.bind(fun_flat, *args_flat, **params)\n+ return verify_outputs(out_flat, out_tree, params)\n+\n# Decorate fun_mapped\nfor loop_params in reversed(anon_serial_loops):\nfun_mapped = serial_loop(*loop_params)(fun_mapped)\n@@ -689,17 +696,11 @@ def make_xmap_callable(fun: lu.WrappedFun,\nif used_mesh_axes:\nassert spmd_in_axes is None and spmd_out_axes_thunk is None # No outer xmaps, so should be None\nmesh_in_axes, mesh_out_axes = plan.to_mesh_axes(in_axes, out_axes)\n- return pxla.mesh_callable(f,\n- name,\n- backend,\n- resource_env.physical_mesh,\n- mesh_in_axes,\n- mesh_out_axes,\n- donated_invars,\n- use_spmd_lowering,\n- *in_avals,\n- tile_by_mesh_axes=True,\n- do_resource_typecheck=None)\n+ return pxla.lower_mesh_computation(\n+ f, name, resource_env.physical_mesh,\n+ mesh_in_axes, mesh_out_axes, donated_invars,\n+ use_spmd_lowering, in_avals,\n+ tile_by_mesh_axes=True, do_resource_typecheck=None).compile().unsafe_call\nelse:\nreturn xla._xla_callable(f, None, backend, name, donated_invars,\n*((a, None) for a in in_avals))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -178,10 +178,9 @@ def pjit(fun: Callable,\ndonate_argnums = _ensure_index_tuple(donate_argnums)\ndonate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)\n- @wraps(fun)\n- def wrapped(*args, **kwargs):\n+ def infer_params(*args, **kwargs):\nif kwargs:\n- raise NotImplementedError(\"pjit over kwargs not yet supported\")\n+ raise NotImplementedError(\"pjit does not support kwargs\")\nif max(static_argnums + donate_argnums, default=-1) >= len(args):\nraise ValueError(f\"jitted function has static_argnums={static_argnums}, \"\nf\"donate_argnums={donate_argnums} but \"\n@@ -214,16 +213,28 @@ def pjit(fun: Callable,\n_pjit_jaxpr(flat_fun, mesh, local_in_avals,\nin_tree, hashable_pytree(in_axis_resources),\nHashableFunction(out_tree, closure=()), hashable_pytree(out_axis_resources))\n-\n- out = pjit_p.bind(\n- *args_flat,\n+ params = dict(\njaxpr=jaxpr,\nin_axis_resources=in_axis_resources_flat,\nout_axis_resources=out_axis_resources_flat,\nresource_env=resource_env,\ndonated_invars=donated_invars,\nname=flat_fun.__name__)\n- return tree_unflatten(out_tree(), out)\n+ return args_flat, params, out_tree()\n+\n+ @wraps(fun)\n+ def wrapped(*args, **kwargs):\n+ args_flat, params, out_tree = infer_params(*args, **kwargs)\n+ out = pjit_p.bind(*args_flat, **params)\n+ return tree_unflatten(out_tree, out)\n+\n+ def lower(*args, **kwargs):\n+ args_flat, params, out_tree = infer_params(*args, **kwargs)\n+ return _pjit_lower(\n+ params['jaxpr'], params['in_axis_resources'],\n+ params['out_axis_resources'], params['resource_env'],\n+ params['donated_invars'], params['name'])\n+ wrapped.lower = lower\nreturn wrapped\n@@ -399,23 +410,22 @@ pjit_p.multiple_results = True\ndef _pjit_call_impl(*args, jaxpr,\nin_axis_resources, out_axis_resources,\nresource_env, donated_invars, name):\n- compiled = pjit_callable(\n+ compiled = _pjit_lower(\njaxpr, in_axis_resources, out_axis_resources,\n- resource_env, donated_invars, name)\n+ resource_env, donated_invars, name).compile()\ndistributed_debug_log((\"Running pjit'd function\", name),\n(\"mesh\", resource_env.physical_mesh))\n- return compiled(*args)\n+ return compiled.unsafe_call(*args)\npjit_p.def_impl(_pjit_call_impl)\n@cache()\n-def pjit_callable(\n+def _pjit_lower(\njaxpr: core.ClosedJaxpr,\nin_axis_resources: Tuple[ParsedPartitionSpec, ...],\nout_axis_resources: Tuple[ParsedPartitionSpec, ...],\nresource_env,\ndonated_invars,\nname: str):\n-\nin_axes = [get_array_mapping(axes) for axes in in_axis_resources]\nout_axes = [get_array_mapping(axes) for axes in out_axis_resources]\nf = core.jaxpr_as_fun(jaxpr)\n@@ -423,14 +433,13 @@ def pjit_callable(\nfun = lu.wrap_init(f)\nlocal_in_avals = global_to_local(resource_env.physical_mesh,\njaxpr.in_avals, in_axis_resources)\n- # TODO(skye): allow for using a submesh of physical_mesh\n- return pxla.mesh_callable(fun, name, None, resource_env.physical_mesh,\n+ return pxla.lower_mesh_computation(\n+ fun, name, resource_env.physical_mesh,\nin_axes, out_axes, donated_invars,\n- True, *local_in_avals, tile_by_mesh_axes=False,\n+ True, local_in_avals, tile_by_mesh_axes=False,\ndo_resource_typecheck=\"pjit\")\n-\ndef _pjit_abstract_eval(*args, jaxpr, out_axis_resources, resource_env, **_):\nreturn global_to_local(resource_env.physical_mesh,\njaxpr.out_avals, out_axis_resources)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -36,7 +36,6 @@ import operator as op\nimport threading\nfrom typing import (TYPE_CHECKING, Any, Callable, Dict, List, Optional,\nSequence, Set, Tuple, Type, Union, Iterable)\n-\nfrom absl import logging\nimport numpy as np\n@@ -1529,17 +1528,20 @@ def vtile_by_mesh(fun: lu.WrappedFun,\nmain_type=SPMDBatchTrace)\nreturn fun\n-def mesh_callable(fun: lu.WrappedFun,\n+def lower_mesh_computation(\n+ fun: lu.WrappedFun,\ntransformed_name: str,\n- backend_name: Optional[str],\nmesh: Mesh,\nin_axes: Sequence[ArrayMapping],\nout_axes: Union[Sequence[ArrayMapping], Callable[[], Sequence[ArrayMapping]]],\ndonated_invars: Sequence[bool],\nspmd_lowering: bool,\n- *local_in_untiled_avals,\n+ local_in_untiled_avals: Sequence[core.ShapedArray],\ntile_by_mesh_axes: bool,\ndo_resource_typecheck: Optional[str]):\n+ assert not mesh.empty\n+ backend = xb.get_device_backend(mesh.devices.flat[0])\n+\nlocal_mesh = mesh.local_mesh\nglobal_axis_sizes = mesh.shape\nlocal_axis_sizes = local_mesh.shape\n@@ -1615,34 +1617,49 @@ def mesh_callable(fun: lu.WrappedFun,\ndonated_invars=donated_invars)\nwith core.extend_axis_env_nd(mesh.shape.items()):\nout_nodes = xla.jaxpr_subcomp(\n- c, jaxpr, backend_name, axis_env, xla_consts,\n+ c, jaxpr, backend.platform, axis_env, xla_consts,\nextend_name_stack(wrap_name(transformed_name, 'xmap')), *xla_args)\n- if backend_name is None:\n- backend = xb.get_device_backend(mesh.devices.flat[0])\n- else:\n- backend = xb.get_backend(backend_name)\nif spmd_lowering:\nout_partitions_t = xb.tuple_sharding_proto(out_partitions)\nout_tuple = xb.with_sharding_proto(c, out_partitions_t, xops.Tuple, c, out_nodes)\nelse:\nout_tuple = xops.Tuple(c, out_nodes)\n+\nif backend.platform in (\"gpu\", \"tpu\"):\nxla.set_up_aliases(c, xla_args, out_tuple, donated_invars, tuple_args)\n# TODO: Warn about unused donations?\n- built = c.Build(out_tuple)\n- return compile_and_wrap_mesh_hlo(built, backend, mesh, local_in_untiled_avals,\n+ built = c.Build(out_tuple)\n+ return MeshComputation(\n+ built, mesh, local_in_untiled_avals,\nlocal_out_untiled_avals, in_axes, out_axes,\nspmd_lowering, tuple_args)\n-def compile_and_wrap_mesh_hlo(computation: xc.XlaComputation, backend,\n+class MeshComputation:\n+ def __init__(self, hlo, *compile_args):\n+ self._executable = None\n+ self.hlo = hlo\n+ self.compile_args = compile_args\n+\n+ def compile(self):\n+ if self._executable is None:\n+ self._executable = MeshExecutable(self.hlo, *self.compile_args)\n+ return self._executable\n+\n+\n+class MeshExecutable:\n+ def __init__(self,\n+ computation: xc.XlaComputation,\nmesh: Mesh,\nlocal_in_untiled_avals: Sequence[ShapedArray],\nlocal_out_untiled_avals: Sequence[ShapedArray],\nin_axes: Sequence[ArrayMapping],\nout_axes: Sequence[ArrayMapping],\nspmd_lowering: bool, tuple_args: bool):\n+ assert not mesh.empty\n+ backend = xb.get_device_backend(mesh.devices.flat[0])\n+\nlocal_mesh = mesh.local_mesh\nlocal_axis_sizes = local_mesh.shape\nif spmd_lowering:\n@@ -1674,13 +1691,20 @@ def compile_and_wrap_mesh_hlo(computation: xc.XlaComputation, backend,\nlocal_output_specs, local_out_untiled_avals)\nif hasattr(backend, \"compile_replicated\"):\n- return backend.compile_replicated(computation, compile_options,\n+ self.unsafe_call = backend.compile_replicated(\n+ computation, compile_options,\ninput_indices, local_input_specs,\nhandle_outs)\n+ else:\ncompiled = xla.compile_or_get_cached(backend, computation, compile_options)\nhandle_args = InputsHandler(compiled.local_devices(), local_input_specs,\ninput_indices)\n- return partial(execute_replicated, compiled, backend, handle_args, handle_outs)\n+ self.unsafe_call = partial(execute_replicated, compiled, backend, handle_args, handle_outs)\n+\n+ def __call__(self, *args):\n+ # TODO(apaszke): Validate arguments\n+ return self.unsafe_call(*args)\n+\n_forbidden_primitives = {\n'xla_pmap': 'pmap',\n" } ]
Python
Apache License 2.0
google/jax
New lowering APIs for pjit This is the first in a series of refactoring patches that add the new AOT APIs to all JIT-like transforms in JAX. I'm sending this early, because I expect that it will come in handy when adding reverse-mode AD support for pjit. PiperOrigin-RevId: 395510449
260,682
08.09.2021 23:29:20
0
add830037246983e6bd911d02e52f911a7d69a59
added images for pjit tutorial
[ { "change_type": "ADD", "old_path": "docs/_static/mesh.jpg", "new_path": "docs/_static/mesh.jpg", "diff": "Binary files /dev/null and b/docs/_static/mesh.jpg differ\n" }, { "change_type": "ADD", "old_path": "docs/_static/multi_host.jpg", "new_path": "docs/_static/multi_host.jpg", "diff": "Binary files /dev/null and b/docs/_static/multi_host.jpg differ\n" }, { "change_type": "ADD", "old_path": "docs/_static/partition_spec_none_y.png", "new_path": "docs/_static/partition_spec_none_y.png", "diff": "Binary files /dev/null and b/docs/_static/partition_spec_none_y.png differ\n" }, { "change_type": "ADD", "old_path": "docs/_static/partition_spec_x_none.png", "new_path": "docs/_static/partition_spec_x_none.png", "diff": "Binary files /dev/null and b/docs/_static/partition_spec_x_none.png differ\n" }, { "change_type": "ADD", "old_path": "docs/_static/partition_spec_x_y.png", "new_path": "docs/_static/partition_spec_x_y.png", "diff": "Binary files /dev/null and b/docs/_static/partition_spec_x_y.png differ\n" }, { "change_type": "ADD", "old_path": "docs/_static/partition_spec_xy.png", "new_path": "docs/_static/partition_spec_xy.png", "diff": "Binary files /dev/null and b/docs/_static/partition_spec_xy.png differ\n" }, { "change_type": "ADD", "old_path": "docs/_static/partition_spec_y_none.png", "new_path": "docs/_static/partition_spec_y_none.png", "diff": "Binary files /dev/null and b/docs/_static/partition_spec_y_none.png differ\n" }, { "change_type": "ADD", "old_path": "docs/_static/xla_spmd.jpg", "new_path": "docs/_static/xla_spmd.jpg", "diff": "Binary files /dev/null and b/docs/_static/xla_spmd.jpg differ\n" } ]
Python
Apache License 2.0
google/jax
added images for pjit tutorial
260,287
09.09.2021 13:50:41
25,200
00528a42e530a7a04e82bdffd6e6f98d3558b5d3
Add new lowering APIs for jit
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -689,6 +689,9 @@ def _xla_consts(c, consts):\n@lu.cache\ndef _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *arg_specs):\n+ return lower_xla_callable(fun, device, backend, name, donated_invars, *arg_specs).compile().unsafe_call\n+\n+def lower_xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *arg_specs):\nif device is not None and backend is not None:\nraise ValueError(\"can't specify both a device and a backend for jit, \"\n\"got device={} and backend={}\".format(device, backend))\n@@ -712,14 +715,12 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\ndevice = _xla_callable_device(nreps, backend, device, arg_devices)\nbackend = xb.get_device_backend(device) if device else (\nxb.get_backend(backend) if backend is not None else None)\n- result_handlers = map(partial(aval_to_result_handler, device), out_avals)\n# Computations that only produce constants and/or only rearrange their inputs,\n# which are often produced from partial evaluation, don't need compilation,\n# and don't need to evaluate their arguments.\nif not jaxpr.eqns:\n- return partial(_execute_trivial, jaxpr, device, consts, out_avals,\n- result_handlers, kept_var_idx)\n+ return XlaComputation(None, True, jaxpr, consts, device, out_avals, kept_var_idx)\nif not _on_exit:\nlog_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG\n@@ -764,19 +765,63 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\nfor a, d in zip(xla_args, donated_invars) if d]\nwarn(\"Some donated buffers were not usable: {}\".format(\", \".join(unused_donations)))\nbuilt = c.build(out_tuple)\n+ return XlaComputation(\n+ built, False, nreps, device, backend, tuple_args, out_avals, kept_var_idx)\n+\n+class XlaComputation:\n+ def __init__(self, hlo, is_trivial, *compile_args):\n+ self.hlo = hlo\n+ self._is_trivial = is_trivial\n+ self._executable = None\n+ self.compile_args = compile_args\n+\n+ def compile(self):\n+ if self._executable is None:\n+ if self._is_trivial:\n+ self._executable = XlaCompiledComputation.from_trivial_jaxpr(*self.compile_args)\n+ else:\n+ self._executable = XlaCompiledComputation.from_xla_computation(self.hlo, *self.compile_args)\n+ return self._executable\n+\n+\n+class XlaCompiledComputation:\n+ def __init__(self, unsafe_call):\n+ self.unsafe_call = unsafe_call\n+\n+ @staticmethod\n+ def from_xla_computation(\n+ xla_computation,\n+ nreps: int,\n+ device,\n+ backend,\n+ tuple_args: bool,\n+ out_avals,\n+ kept_var_idx):\n+ result_handlers = map(partial(aval_to_result_handler, device), out_avals)\noptions = xb.get_compile_options(\nnum_replicas=nreps,\nnum_partitions=1,\ndevice_assignment=(device.id,) if device else None)\noptions.parameter_is_tupled_arguments = tuple_args\n- compiled = compile_or_get_cached(backend, built, options)\n+ compiled = compile_or_get_cached(backend, xla_computation, options)\nif nreps == 1:\n- return partial(_execute_compiled, compiled, out_avals, result_handlers,\n- kept_var_idx)\n+ return XlaCompiledComputation(partial(\n+ _execute_compiled, compiled, out_avals, result_handlers, kept_var_idx))\nelse:\n- return partial(_execute_replicated, compiled, out_avals, result_handlers,\n- kept_var_idx)\n+ return XlaCompiledComputation(partial(\n+ _execute_replicated, compiled, out_avals, result_handlers, kept_var_idx))\n+\n+ @staticmethod\n+ def from_trivial_jaxpr(jaxpr, consts, device, out_avals, kept_var_idx):\n+ result_handlers = map(partial(aval_to_result_handler, device), out_avals)\n+ return XlaCompiledComputation(partial(\n+ _execute_trivial, jaxpr, device, consts, out_avals,\n+ result_handlers, kept_var_idx))\n+\n+ def __call__(self, *args):\n+ # TODO(apaszke,frostig): Check that args are compatible with input avals!\n+ return self.unsafe_call(*args)\ndef set_up_aliases(c, xla_args, out_tuple, donated_args, tuple_args):\n" } ]
Python
Apache License 2.0
google/jax
Add new lowering APIs for jit PiperOrigin-RevId: 395779305
260,682
09.09.2021 15:24:04
25,200
e7e8183a40e46377abd4e696887c942c2c579fdc
not exclude 08-pjit.md
[ { "change_type": "MODIFY", "old_path": "docs/conf.py", "new_path": "docs/conf.py", "diff": "@@ -115,7 +115,15 @@ exclude_patterns = [\n# Ignore markdown source for notebooks; myst-nb builds from the ipynb\n# These are kept in sync using the jupytext pre-commit hook.\n'notebooks/*.md',\n- 'jax-101/*.md',\n+ # TODO: revert to jax-101/*.md once 08-pjit has a notebook\n+ 'jax-101/01-jax-basics.md',\n+ 'jax-101/02-jitting.md',\n+ 'jax-101/03-vectorization.md',\n+ 'jax-101/04-advanced-autodiff.md',\n+ 'jax-101/05-random-numbers.md',\n+ 'jax-101/05.1-pytrees.md',\n+ 'jax-101/06-parallelism.md',\n+ 'jax-101/07-state.md',\n'autodidax.md',\n# Attempt to fix RTD build failure\n'transformations.md',\n" } ]
Python
Apache License 2.0
google/jax
not exclude 08-pjit.md
260,287
10.09.2021 07:09:26
25,200
c845d15b3ad2fd7526c044eca62de8f0a94875ef
Cache used_axis_names calls for jaxprs All control-flow primitives are `AxisPrimitive`s now, which means that we're doing lots of those used-names traversals during dispatch and they can be expensive! This adds caching to try to lower the cost of that change.
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -38,7 +38,7 @@ from . import linear_util as lu\nfrom jax._src import source_info_util\nfrom ._src.util import (safe_zip, safe_map, partial, curry, prod, partialmethod,\n- tuple_insert, tuple_delete, as_hashable_function,\n+ tuple_insert, tuple_delete, cache, as_hashable_function,\nHashableFunction)\nfrom ._src.pprint_util import pp, vcat, PrettyPrint\n@@ -1749,13 +1749,17 @@ def axis_frame(axis_name):\nParamDict = Dict[str, Any]\nAxisSubst = Callable[[AxisName], Tuple[AxisName, ...]]\n-def used_axis_names(primitive: Primitive, params: ParamDict) -> Set[AxisName]:\n- axis_names = set()\n- def register_name(axis_name):\n- axis_names.add(axis_name)\n+class NameGatheringSubst:\n+ def __init__(self):\n+ self.axis_names = set()\n+ def __call__(self, axis_name):\n+ self.axis_names.add(axis_name)\nreturn (axis_name,)\n- subst_axis_names(primitive, params, register_name)\n- return axis_names\n+\n+def used_axis_names(primitive: Primitive, params: ParamDict) -> Set[AxisName]:\n+ subst = NameGatheringSubst()\n+ subst_axis_names(primitive, params, subst)\n+ return subst.axis_names\ndef subst_axis_names(primitive: Primitive, params: ParamDict, subst: AxisSubst, traverse: bool = True) -> ParamDict:\nif primitive in axis_substitution_rules:\n@@ -1807,7 +1811,7 @@ def subst_axis_names_eqn(eqn: JaxprEqn, subst: AxisSubst, var_map: Dict[Var, Var\nparams = subst_axis_names(eqn.primitive, eqn.params, subst)\nreturn new_jaxpr_eqn(invars, outvars, eqn.primitive, params, eqn.source_info)\n-def subst_axis_names_jaxpr(jaxpr: Union[Jaxpr, ClosedJaxpr], subst: AxisSubst):\n+def do_subst_axis_names_jaxpr(jaxpr: Union[Jaxpr, ClosedJaxpr], subst: AxisSubst):\nconsts = None\nif isinstance(jaxpr, ClosedJaxpr):\nconsts = jaxpr.consts\n@@ -1822,6 +1826,19 @@ def subst_axis_names_jaxpr(jaxpr: Union[Jaxpr, ClosedJaxpr], subst: AxisSubst):\nreturn ClosedJaxpr(new_jaxpr, consts)\nreturn new_jaxpr\n+@cache()\n+def used_axis_names_jaxpr(jaxpr: Union[Jaxpr, ClosedJaxpr]):\n+ subst = NameGatheringSubst()\n+ do_subst_axis_names_jaxpr(jaxpr, subst)\n+ return frozenset(subst.axis_names)\n+\n+def subst_axis_names_jaxpr(jaxpr: Union[Jaxpr, ClosedJaxpr], subst: AxisSubst):\n+ if isinstance(subst, NameGatheringSubst): # This is a common case, so we optimize it!\n+ subst.axis_names |= used_axis_names_jaxpr(jaxpr)\n+ return jaxpr\n+ return do_subst_axis_names_jaxpr(jaxpr, subst)\n+\n+\naxis_substitution_rules: Dict[Primitive, Callable[[ParamDict, AxisSubst, bool], ParamDict]] = {}\n# ------------------- AxisPrimitive -------------------\n" } ]
Python
Apache License 2.0
google/jax
Cache used_axis_names calls for jaxprs All control-flow primitives are `AxisPrimitive`s now, which means that we're doing lots of those used-names traversals during dispatch and they can be expensive! This adds caching to try to lower the cost of that change. PiperOrigin-RevId: 395921887
260,287
10.09.2021 10:02:07
25,200
cc2efbf03240e89609289daf963b2f0f4e187179
Add new lowering APIs for xmap
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -636,10 +636,22 @@ def xmap(fun: Callable,\nout_flat = xmap_p.bind(fun_flat, *args_flat, **params)\nreturn verify_outputs(out_flat, out_tree, params)\n- # Decorate fun_mapped\n+ def decorate_serial(f):\nfor loop_params in reversed(anon_serial_loops):\n- fun_mapped = serial_loop(*loop_params)(fun_mapped)\n- fun_mapped = wraps(fun)(fun_mapped)\n+ f = serial_loop(*loop_params)(f)\n+ return f\n+\n+ def lower(*args):\n+ fun_flat, args_flat, params, out_tree = infer_params(*args)\n+ avals_flat = [core.raise_to_shaped(core.get_aval(arg)) for arg in args_flat]\n+ return make_xmap_callable(\n+ fun_flat, params['name'], params['in_axes'], params['out_axes_thunk'],\n+ params['donated_invars'], params['global_axis_sizes'], params['axis_resources'],\n+ params['resource_env'], params['backend'], params['spmd_in_axes'],\n+ params['spmd_out_axes_thunk'], *avals_flat)\n+\n+ fun_mapped = wraps(fun)(decorate_serial(fun_mapped))\n+ fun_mapped.lower = decorate_serial(lower)\nreturn fun_mapped\n@@ -651,7 +663,7 @@ def xmap_impl(fun: lu.WrappedFun, *args, name, in_axes, out_axes_thunk, donated_\nfun, name, in_axes, out_axes_thunk, donated_invars, global_axis_sizes,\naxis_resources, resource_env, backend,\nspmd_in_axes, spmd_out_axes_thunk,\n- *in_avals)\n+ *in_avals).compile().unsafe_call\ndistributed_debug_log((\"Running xmapped function\", name),\n(\"python function\", fun.f),\n(\"mesh\", resource_env.physical_mesh),\n@@ -700,10 +712,10 @@ def make_xmap_callable(fun: lu.WrappedFun,\nf, name, resource_env.physical_mesh,\nmesh_in_axes, mesh_out_axes, donated_invars,\nuse_spmd_lowering, in_avals,\n- tile_by_mesh_axes=True, do_resource_typecheck=None).compile().unsafe_call\n+ tile_by_mesh_axes=True, do_resource_typecheck=None)\nelse:\n- return xla._xla_callable(f, None, backend, name, donated_invars,\n- *((a, None) for a in in_avals))\n+ return xla.lower_xla_callable(\n+ f, None, backend, name, donated_invars, *((a, None) for a in in_avals))\nclass EvaluationPlan(NamedTuple):\n\"\"\"Encapsulates preprocessing common to top-level xmap invocations and its translation rule.\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
Add new lowering APIs for xmap PiperOrigin-RevId: 395950859
260,411
12.09.2021 18:54:32
-10,800
b59db5b181c374291f5a72cf9e3ca518fd61b50d
[jax2tf] Fix stale comments
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "diff": "@@ -43,8 +43,9 @@ def convert_and_save_model(\nsaved_model_options: Optional[tf.saved_model.SaveOptions] = None):\n\"\"\"Convert a JAX function and saves a SavedModel.\n- This is an example, for serious uses you will likely want to copy and\n- expand it as needed (see note at the top of the model).\n+ This is an example, we do not promise backwards compatibility for this code.\n+ For serious uses, please copy and and expand it as needed (see note at the top\n+ of the module).\nUse this function if you have a trained ML model that has both a prediction\nfunction and trained parameters, which you want to save separately from the\n@@ -74,14 +75,10 @@ def convert_and_save_model(\nthe default serving signature. The additional signatures will be used\nonly to ensure that the `jax_fn` is traced and converted to TF for the\ncorresponding input shapes.\n- with_gradient: whether the SavedModel should support gradients. If True,\n- then a custom gradient is saved. If False, then a\n- tf.raw_ops.PreventGradient is saved to error if a gradient is attempted.\n- (At the moment due to a bug in SavedModel, custom gradients are not\n- supported.)\n- enable_xla: whether the jax2tf converter is allowed to use TFXLA ops. If\n- False, the conversion tries harder to use purely TF ops and raises an\n- exception if it is not possible. (default: True)\n+ with_gradient: the value to use for the `with_gradient` parameter for\n+ `jax2tf.convert`.\n+ enable_xla: the value to use for the `enable_xla` parameter for\n+ `jax2tf.convert`.\ncompile_model: use TensorFlow jit_compiler on the SavedModel. This\nis needed if the SavedModel will be used for TensorFlow serving.\npolymorphic_shapes: if given then it will be used as the\n@@ -105,10 +102,6 @@ def convert_and_save_model(\n# Create tf.Variables for the parameters. If you want more useful variable\n# names, you can use `tree.map_structure_with_path` from the `dm-tree` package\nparam_vars = tf.nest.map_structure(\n- # Due to a bug in SavedModel it is not possible to use tf.GradientTape on\n- # a function converted with jax2tf and loaded from SavedModel. Thus, we\n- # mark the variables as non-trainable to ensure that users of the\n- # SavedModel will not try to fine tune them.\nlambda param: tf.Variable(param, trainable=with_gradient),\nparams)\ntf_graph = tf.function(lambda inputs: tf_fn(param_vars, inputs),\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -226,22 +226,20 @@ def convert(fun: Callable,\nfor more details.\nin_shapes: DEPRECATED in favor of `polymorphic_shapes`.\n- with_gradient: if set, will add a tf.custom_gradient to the converted\n- function, by converting the ``jax.vjp(fun)``. Only first-order\n- differentiation is supported for now. If the converted function is saved\n- in a SavedModel, the custom gradients are currently lost and an error will\n- be raised if a gradient computation is attempted. This is due to a current\n- bug in TensorFlow.\n+ with_gradient: if set (default), add a tf.custom_gradient to the converted\n+ function, by converting the ``jax.vjp(fun)``. This means that reverse-mode\n+ TensorFlow AD is supported for the output TensorFlow function, and the\n+ value of the gradient will be JAX-accurate.\nenable_xla: if set (default), the converter will use the simplest conversion\nand use XLA TF ops when necessary. These ops are known to create issues\nfor the TFLite and TFjs converters. For those cases, unset this parameter\n- so the converter tries harder to use non-XLA TF ops to convert the function,\n- and raises an error if it can not be converted\n- without resorting to XLA ops.\n+ so the converter tries harder to use non-XLA TF ops to convert the\n+ function and aborts if this is not possible.\nReturns:\nA version of `fun` that expects TfVals as arguments (or\n- tuple/lists/dicts) thereof, and returns TfVals as outputs.\n+ tuple/lists/dicts) thereof, and returns TfVals as outputs, and uses\n+ only TensorFlow ops.\n\"\"\"\napi._check_callable(fun)\nfun_name = getattr(fun, \"__name__\", \"unknown\")\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix stale comments
260,510
13.09.2021 15:39:02
25,200
ebd8d95847e90ee673d476a1b26947dd7ba340a1
Add precision param for pdot
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -633,7 +633,7 @@ def conv_general_dilated(\nfeature_group_count=feature_group_count,\nbatch_group_count=batch_group_count,\nlhs_shape=lhs.shape, rhs_shape=rhs.shape,\n- precision=_canonicalize_precision(precision),\n+ precision=canonicalize_precision(precision),\npreferred_element_type=preferred_element_type)\ndef dot(lhs: Array, rhs: Array, precision: PrecisionLike = None,\n@@ -702,7 +702,7 @@ def dot_general(lhs: Array, rhs: Array, dimension_numbers: DotDimensionNumbers,\nbatch_dims = tuple(map(tuple, batch_dims_seq)) # type: ignore\nreturn dot_general_p.bind(lhs, rhs,\ndimension_numbers=(contract_dims, batch_dims),\n- precision=_canonicalize_precision(precision),\n+ precision=canonicalize_precision(precision),\npreferred_element_type=preferred_element_type)\ndef broadcast(operand: Array, sizes: Sequence[int]) -> Array:\n@@ -6826,7 +6826,7 @@ def remaining(original, *removed_lists):\nreturn [i for i in original if i not in removed]\n-def _canonicalize_precision(precision: PrecisionLike) -> Optional[Tuple[PrecisionType, PrecisionType]]:\n+def canonicalize_precision(precision: PrecisionLike) -> Optional[Tuple[PrecisionType, PrecisionType]]:\n\"\"\"Turns an API precision specification, into a pair of enumeration values.\nThe API can take the precision as a string, or int, and either as a single\n@@ -6854,7 +6854,7 @@ def _canonicalize_precision(precision: PrecisionLike) -> Optional[Tuple[Precisio\nelif (isinstance(precision, (list, tuple)) and len(precision) == 2 and\nall(isinstance(s, str) for s in precision)):\ns1, s2 = precision\n- return (_canonicalize_precision(s1)[0], _canonicalize_precision(s2)[0]) # type: ignore\n+ return (canonicalize_precision(s1)[0], canonicalize_precision(s2)[0]) # type: ignore\nelse:\nraise ValueError(\nf\"Precision argument must be None, a string in {_precision_strings}, \"\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -395,11 +395,13 @@ def axis_index(axis_name):\nreturn axis_index_p.bind(axis_name=axis_name)\n-def pdot(x, y, axis_name, pos_contract=((), ()), pos_batch=((), ())):\n+def pdot(x, y, axis_name, pos_contract=((), ()), pos_batch=((), ()),\n+ precision=None):\nif not isinstance(axis_name, (list, tuple)):\naxis_name = (axis_name,)\nreturn pdot_p.bind(x, y, axis_name=axis_name,\n- pos_contract=pos_contract, pos_batch=pos_batch)\n+ pos_contract=pos_contract, pos_batch=pos_batch,\n+ precision=lax.canonicalize_precision(precision))\ndef xeinsum(spec: str, x, y):\n@@ -1347,17 +1349,17 @@ pdot_p = core.AxisPrimitive('pdot')\ncore.axis_substitution_rules[pdot_p] = partial(_subst_all_names_in_param, 'axis_name')\n@pdot_p.def_impl\n-def _pdot_impl(x, y, *, axis_name, pos_contract, pos_batch):\n+def _pdot_impl(x, y, *, axis_name, pos_contract, pos_batch, precision):\nif axis_name: raise NameError(f\"unbound axis name: {axis_name[0]}\")\n- return lax.dot_general(x, y, [pos_contract, pos_batch])\n+ return lax.dot_general(x, y, [pos_contract, pos_batch], precision=precision)\n@pdot_p.def_abstract_eval\n-def _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch):\n+def _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch, precision):\n# TODO(frostig,mattjj,jekbradbury): check inputs have given axis names?\nif not len(set(axis_name)) == len(axis_name): raise ValueError\npos_aval = lax.dot_general_p.abstract_eval(\nx, y, dimension_numbers=[pos_contract, pos_batch],\n- precision=None, preferred_element_type=None)\n+ precision=precision, preferred_element_type=None)\ncommon_named_shape = core.join_named_shapes(x.named_shape, y.named_shape)\nnamed_shape = {name: size\nfor name, size in common_named_shape.items()\n@@ -1365,7 +1367,7 @@ def _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch):\nreturn pos_aval.update(named_shape=named_shape)\ndef _pdot_vmap_collective_rule(axis_size, frame_name, _, vals_in, dims_in, *, axis_name,\n- pos_contract, pos_batch):\n+ pos_contract, pos_batch, precision):\nx, y = vals_in\nx_dim, y_dim = dims_in\nx_pos_contract, y_pos_contract = pos_contract\n@@ -1377,24 +1379,25 @@ def _pdot_vmap_collective_rule(axis_size, frame_name, _, vals_in, dims_in, *, ax\nremaining_axis_names = tuple(n for n in axis_name if n != frame_name)\nout = pdot_p.bind(x, y, axis_name=remaining_axis_names,\npos_contract=[x_pos_contract, y_pos_contract],\n- pos_batch=[x_pos_batch, y_pos_batch])\n+ pos_batch=[x_pos_batch, y_pos_batch],\n+ precision=precision)\nreturn out, None\nbatching.axis_primitive_batchers[pdot_p] = _pdot_vmap_collective_rule\ndef _pdot_vmap_batching_rule(vals_in, dims_in, *, axis_name, pos_contract,\n- pos_batch):\n+ pos_batch, precision):\nx, y = vals_in\n(pos_contract, pos_batch), result_batch_dim = lax._dot_general_batch_dim_nums(\n(x.ndim, y.ndim), dims_in, [pos_contract, pos_batch])\nout = pdot_p.bind(x, y, axis_name=axis_name, pos_contract=pos_contract,\n- pos_batch=pos_batch)\n+ pos_batch=pos_batch, precision=precision)\nreturn out, result_batch_dim\nbatching.primitive_batchers[pdot_p] = _pdot_vmap_batching_rule\n-def _pdot_translation_rule(c, x, y, *, axis_name, pos_contract, pos_batch,\n+def _pdot_translation_rule(c, x, y, *, axis_name, pos_contract, pos_batch, precision,\naxis_env, platform):\nlocal_out = lax._dot_general_translation_rule(\n- c, x, y, dimension_numbers=[pos_contract, pos_batch], precision=None,\n+ c, x, y, dimension_numbers=[pos_contract, pos_batch], precision=precision,\npreferred_element_type=None)\nif axis_name:\nout_tup = xla.parallel_translations[psum_p](\n@@ -1406,15 +1409,15 @@ def _pdot_translation_rule(c, x, y, *, axis_name, pos_contract, pos_batch,\nreturn out\nxla.parallel_translations[pdot_p] = _pdot_translation_rule\n-def _pdot_transpose_lhs(g, y, *, axis_name, pos_contract, pos_batch):\n+def _pdot_transpose_lhs(g, y, *, axis_name, pos_contract, pos_batch, precision):\n# TODO: avals with names, call pbroadcast with axis_name\nreturn lax._dot_general_transpose_lhs(\n- g, y, dimension_numbers=[pos_contract, pos_batch], precision=None,\n+ g, y, dimension_numbers=[pos_contract, pos_batch], precision=precision,\npreferred_element_type=None)\n-def _pdot_transpose_rhs(g, x, *, axis_name, pos_contract, pos_batch):\n+def _pdot_transpose_rhs(g, x, *, axis_name, pos_contract, pos_batch, precision):\n# TODO: avals with names, call pbroadcast with axis_name\nreturn lax._dot_general_transpose_rhs(\n- g, x, dimension_numbers=[pos_contract, pos_batch], precision=None,\n+ g, x, dimension_numbers=[pos_contract, pos_batch], precision=precision,\npreferred_element_type=None)\nad.defbilinear(pdot_p, _pdot_transpose_lhs, _pdot_transpose_rhs)\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -1117,6 +1117,19 @@ class BatchingTest(jtu.JaxTestCase):\nzs = vmap(vmap(f, axis_name='i', in_axes=(1, 0), out_axes=None))(xs, ys)\nself.assertAllClose(zs, jnp.einsum('nij,njk->nik', xs, ys))\n+ def testPdotPrecision(self):\n+ def f(x, y):\n+ return lax.pdot(x, y, 'i', precision=lax.Precision.HIGHEST)\n+\n+ f_jaxpr = make_jaxpr(f, axis_env=(('i', 4),))(jnp.ones(4), jnp.ones(4))\n+ self.assertIn('HIGHEST', str(f_jaxpr))\n+\n+ vmap_jaxpr = make_jaxpr(jax.vmap(f, axis_name='i'))(jnp.ones((3, 4)),\n+ jnp.ones((3, 4)))\n+ self.assertIn('HIGHEST', str(vmap_jaxpr))\n+\n+\n+\ndef testPdotJvp(self):\ndef f(x, y):\nreturn lax.pdot(x, y, 'i')\n" } ]
Python
Apache License 2.0
google/jax
Add precision param for pdot
260,335
03.09.2021 16:43:57
25,200
36154fac346be78ba0ee6298c19d04fa1e4fc0d6
handle linear custom_jvp functions
[ { "change_type": "MODIFY", "old_path": "jax/_src/custom_derivatives.py", "new_path": "jax/_src/custom_derivatives.py", "diff": "@@ -381,16 +381,24 @@ ad.reducing_transposes[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_transpo\ndef custom_jvp_jaxpr_custom_partial_eval_rule(\nsaveable: Callable[..., bool], unks_in: List[bool], inst_in: List[bool],\neqn: core.JaxprEqn\n- ) -> Tuple[core.JaxprEqn, core.JaxprEqn, List[bool], List[bool], List[core.Var]]:\n+ ) -> Tuple[Optional[core.JaxprEqn], core.JaxprEqn, List[bool], List[bool], List[core.Var]]:\n# It doesn't make sense to unzip (i.e. break up) a custom_jvp function into\n# constituent parts, so we always perform full remat. An alternative would be\n# to allow the policy function to decide whether the value of a\n# custom_jvp-decorated function's application should be saved or not.\n- if any(unks_in): raise NotImplementedError # TODO(mattjj): linear fn\n- unks_out = [False] * len(eqn.outvars)\n+ # TODO(mattjj,jekbradbury): the user writing the custom_jvp-decorated function\n+ # probably has a better idea for what to do under remat (e.g. if the function\n+ # contains dots or not), so we should allow for more expressive interaction\n+ # (e.g. allow the policy to depend on which custom_jvp-decorated function is\n+ # being applied, or annotating the behavior where custom_vjp is called.)\n+ inst_out = [True] * len(eqn.outvars)\nnew_inst = [x for x, inst in zip(eqn.invars, inst_in)\nif type(x) is core.Var and not inst]\n- inst_out = [True] * len(eqn.outvars)\n+ if any(unks_in):\n+ unks_out = [True] * len(eqn.outvars)\n+ return None, eqn, unks_out, inst_out, new_inst\n+ else:\n+ unks_out = [False] * len(eqn.outvars)\nreturn eqn, eqn, unks_out, inst_out, new_inst\npe.partial_eval_jaxpr_custom_rules[custom_jvp_call_jaxpr_p] = \\\ncustom_jvp_jaxpr_custom_partial_eval_rule # type: ignore\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3660,6 +3660,24 @@ class RematTest(jtu.JaxTestCase):\napi.grad(g)(3.)\n+ def test_remat_custom_jvp_linear_policy(self):\n+ @api.custom_jvp\n+ def sum(x):\n+ return jnp.sum(x, axis=0)\n+ @sum.defjvp\n+ def sum_jvp(primals, tangents):\n+ (x,), (xdot,) = primals, tangents\n+ return sum(x), sum(xdot)\n+\n+ @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n+ def f(x):\n+ return sum(x)\n+ jtu.check_grads(f, (jnp.ones(3),), order=2, modes=['fwd', 'rev'])\n+\n+ def g(x):\n+ return lax.scan(lambda _, x: (None, f(x)), None, x)[1]\n+ jtu.check_grads(g, (jnp.ones((2, 3)),), order=2, modes=['fwd', 'rev'])\n+\nclass JaxprTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
handle linear custom_jvp functions
260,632
12.09.2021 09:00:11
-28,800
507cc99c8476fb841db7bab0162023d5c23bbc0b
Add a note about Google Colab setup User must run `jax.tools.colab_tpu.setup_tpu()`
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -466,6 +466,11 @@ the following in your cloud TPU VM:\npip install --upgrade pip\npip install \"jax[tpu]>=0.2.16\" -f https://storage.googleapis.com/jax-releases/libtpu_releases.html\n```\n+Colab TPU runtimes come with JAX pre-installed, but before importing JAX you must run the following code to initialize the TPU:\n+```python\n+import jax.tools.colab_tpu\n+jax.tools.colab_tpu.setup_tpu()\n+```\n### Building JAX from source\nSee [Building JAX from\n" } ]
Python
Apache License 2.0
google/jax
Add a note about Google Colab setup User must run `jax.tools.colab_tpu.setup_tpu()`
260,411
14.09.2021 14:15:40
-7,200
805e359f43f65a9368bed566b04ea6f70b16bf3c
[call_tf] Fix bug when calling TF functions with variables in a jit context. The code was assuming that the `.captured_inputs` of a function are variables in the same order as `.variables`. This seems to not be true. Lookup variables now by handle.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/call_tf.py", "new_path": "jax/experimental/jax2tf/call_tf.py", "diff": "@@ -302,14 +302,11 @@ def _code_generator_and_avals(\n\"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion. \"\nf\"The following captures were found {concrete_function_flat_tf.captured_inputs}\")\nlogging.warning(msg)\n- next_var_idx = 0\nfor inp in concrete_function_flat_tf.captured_inputs:\n- if inp.dtype == tf.resource: # A variable; assume the next variable\n- assert next_var_idx < len(concrete_function_flat_tf.variables)\n- var = concrete_function_flat_tf.variables[next_var_idx]\n- next_var_idx += 1\n- assert inp is var.handle # For extra safety\n- captured_inputs.append(var)\n+ if inp.dtype == tf.resource: # A variable; lookup by handle\n+ inp_vars = [v for v in concrete_function_flat_tf.variables if inp is v.handle]\n+ assert len(inp_vars) == 1, f\"Found {inp_vars}\"\n+ captured_inputs.append(inp_vars[0])\nelse:\ncaptured_inputs.append(inp)\n" } ]
Python
Apache License 2.0
google/jax
[call_tf] Fix bug when calling TF functions with variables in a jit context. The code was assuming that the `.captured_inputs` of a function are variables in the same order as `.variables`. This seems to not be true. Lookup variables now by handle.
260,411
15.09.2021 09:19:55
-7,200
d417e31d91cc7c8cc852d80c62d1713fa5a673e6
[jax2tf] Document an expected error when saving converted functions If the JAX function is not reverse-mode differentiable (e.g., lax.while_loop) then it should be converted without gradients, or saved without gradients.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -119,6 +119,16 @@ tf.saved_model.save(my_model, '/some/directory',\noptions=tf.saved_model.SaveOptions(experimental_custom_gradients=True))\n```\n+Note that if the JAX function is not reverse-mode differentiable, e.g., uses `lax.while_loop` then\n+attempting to save its conversion to a SavedModel will fail with\n+```\n+ValueError: Error when tracing gradients for SavedModel\n+```\n+\n+You have two options, either pass `enable_gradients=False` to `jax2tf.convert`, or\n+set `tf.saved_model.SaveOption(experimental_custom_gradients=False)`. In either case,\n+you will not be able to compute the gradients of the function loaded from the SavedModel.\n+\nSome special care is needed to ensure that the model parameters are not embedded\nas constants in the graph and are instead saved separately as variables.\nThis is useful for two reasons:\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Document an expected error when saving converted functions If the JAX function is not reverse-mode differentiable (e.g., lax.while_loop) then it should be converted without gradients, or saved without gradients.
260,437
09.09.2021 18:18:13
14,400
af22aae1e02308b7bc5120b4913537f4a314c104
fix html formatting of markdown
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb", "new_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb", "diff": "\"\\\\hline\\n\",\n\"\\\\end{array}\\n\",\n\"$$\\n\",\n- \"<center>$\\\\ast$ = argument-__value__-independent loop condition - unrolls the loop </center>\"\n+ \"\\n\",\n+ \"<center>\\n\",\n+ \"\\n\",\n+ \"$\\\\ast$ = argument-<b>value</b>-independent loop condition - unrolls the loop\\n\",\n+ \"\\n\",\n+ \"</center>\"\n]\n},\n{\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/Common_Gotchas_in_JAX.md", "new_path": "docs/notebooks/Common_Gotchas_in_JAX.md", "diff": "@@ -810,7 +810,12 @@ $$\n\\hline\n\\end{array}\n$$\n-<center>$\\ast$ = argument-__value__-independent loop condition - unrolls the loop </center>\n+\n+<center>\n+\n+$\\ast$ = argument-<b>value</b>-independent loop condition - unrolls the loop\n+\n+</center>\n+++ {\"id\": \"DKTMw6tRZyK2\"}\n" } ]
Python
Apache License 2.0
google/jax
fix html formatting of markdown
260,510
16.09.2021 12:28:39
25,200
8ae58be90ae53e06fac657a4ac409c1b774a6f0c
Fix for singleton axis name in `axis_index_translation_rule`
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -1297,6 +1297,12 @@ def psum_scatter(x, axis_name, *, scatter_dimension=0, axis_index_groups=None, t\ndef _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\n+ if isinstance(axis_name, tuple):\n+ assert axis_name, 'empty axis name'\n+ if len(axis_name) > 1:\n+ raise NotImplementedError(\n+ '`axis_index` translation rule does not support multiple axis names.')\n+ axis_name, = axis_name\naxis_pos = list(axis_env.names).index(axis_name)\nnreplicas = axis_env.nreps // prod(axis_env.sizes)\ndiv = xb.constant(c, np.array(nreplicas * prod(axis_env.sizes[axis_pos+1:]),\n" } ]
Python
Apache License 2.0
google/jax
Fix for singleton axis name in `axis_index_translation_rule`
260,303
16.09.2021 21:49:57
25,200
2cee42cf6fd6b3e57baf84a3fe9fa17a1d8ad8bd
Check presence of __jax_array__ in _arraylike before calling it in isscalar
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -301,7 +301,7 @@ def _result_dtype(op, *args):\ndef _arraylike(x):\n- return isinstance(x, ndarray) or isscalar(x) or hasattr(x, '__jax_array__')\n+ return isinstance(x, ndarray) or hasattr(x, '__jax_array__') or isscalar(x)\ndef _check_arraylike(fun_name, *args):\n\"\"\"Check if all args fit JAX's definition of arraylike.\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
Check presence of __jax_array__ in _arraylike before calling it in isscalar
260,411
17.09.2021 16:42:31
-7,200
d172ba7b7e152c644c0b39231523091a45380d0e
[host_callback] Fix an assertion failure for grad(remat(host_callback)) Fixes:
[ { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -1215,28 +1215,31 @@ ad.primitive_jvps[outside_call_p] = _outside_call_jvp_rule\ndef _outside_call_partial_eval_rule(trace, *args, **params):\n- # The args have been prepared by the id_tap_jvp_rule: primals, tangents\n+ # partial eval is used after jvp and before transpose.\ntransforms = params.get(\"transforms\", ())\nif not transforms or transforms[-1] != (\"jvp\",):\n# We are not in the process of computing VJP\nreturn trace.default_process_primitive(outside_call_p, args, params)\n+ # The args have been prepared by the id_tap_jvp_rule: primals, tangents. The\n+ # result is a pair of the primal outputs and output tangents.\n+ # One invariant that JAX requires is that if the primals arguments are known\n+ # then the primal outputs must be known. So, if the primal arguments are known\n+ # and some of the tangents are unknown, then we must split the tap into\n+ # one for the primals (thus the output will be considered known), and a\n+ # separate tap for the tangents.\nassert \"has_token\" not in params\nif not params[\"identity\"]:\nraise NotImplementedError(\"differentiation rules are implemented only for id_tap, not for call.\")\nassert len(args) % 2 == 0\nnr_primals = len(args) // 2\n+ primals, tangents = util.split_list(args, [nr_primals])\n+ all_primals_known = all(p.is_known() for p in primals)\n+ some_tangents_unknown = any(not t.is_known() for t in tangents)\n- consts = [t.pval.get_known() for t in args]\n- if all(c is not None for c in consts):\n+ if not (all_primals_known and some_tangents_unknown):\nreturn trace.default_process_primitive(outside_call_p, args, params)\n- # Split into two taps, one for the knowns and one for the unknowns\n- # We implement here only the case when primals are known, and we make a tap\n- # with just the primals.\n- primals, tangents = util.split_list(args, [nr_primals])\n- c_primals_tapped, _ = util.split_list(consts, [nr_primals])\n- assert all([c is not None for c in c_primals_tapped])\nprims, _ = params[\"arg_treedef\"].unflatten(args)\n_, primals_treedef = api.tree_flatten(prims)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -147,7 +147,7 @@ class JaxprTrace(Trace):\ndef default_process_primitive(self, primitive, tracers, params):\n\"\"\"By default, if all the input tracers are known, then execute the primitive\n- and all the ouputs are known. Otherwise, all the outputs are unknown.\"\"\"\n+ and all the outputs are known. Otherwise, all the outputs are unknown.\"\"\"\nconsts = [t.pval.get_known() for t in tracers]\nif all(c is not None for c in consts):\nreturn primitive.bind(*consts, **params)\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -1841,7 +1841,7 @@ class HostCallbackTapTest(jtu.JaxTestCase):\njax.grad(loss)(1.0) # should not fail\n- def test_tap_remat(self):\n+ def test_tap_remat_0(self):\ndef f(i, k):\nx = hcb.id_print(k + i, output_stream=testing_stream)\nreturn k * x\n@@ -1856,6 +1856,47 @@ class HostCallbackTapTest(jtu.JaxTestCase):\n10\"\"\"\nself.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list(\n+ dict(testcase_name=f\"_use_remat={use_remat}_{grad_func}_use_result={use_result}\",\n+ use_result=use_result, use_remat=use_remat, grad_func=grad_func)\n+ for use_result in [True, False]\n+ for grad_func in [\"grad\", \"value_and_grad\"]\n+ for use_remat in [True, False]))\n+ def test_tap_remat(self, use_result=False, grad_func=\"grad\", use_remat=False):\n+ def f(x):\n+ id_print_result = hcb.id_print(x, output_stream=testing_stream)\n+ if use_result:\n+ x = id_print_result\n+ return 3. * x\n+ grad_f = jax.grad if grad_func == \"grad\" else jax.value_and_grad\n+ trans_f = jax.remat(f) if use_remat else f\n+ print(jax.make_jaxpr(grad_f(trans_f))(2.))\n+ grad_f(trans_f)(2.)\n+\n+ hcb.barrier_wait()\n+\n+ if not use_result:\n+ if use_remat:\n+ expected = \"\"\n+ else:\n+ # TODO: if not use_result then we should only see the primal when\n+ # computing value_and_grad.\n+ expected = \"2.\"\n+ elif use_remat:\n+ expected = \"\"\"\n+ 2.\n+ 2.\n+ transforms: ['jvp', 'transpose']\n+ 3.\"\"\"\n+ else:\n+ expected = \"\"\"\n+ 2.\n+ transforms: ['jvp', 'transpose']\n+ 3.\"\"\"\n+ self.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+ testing_stream.reset()\n+\ndef test_tap_named_call(self):\ndef tap_scalar(init, do_print=False):\n@partial(jax.named_call, name=\"step\")\n" } ]
Python
Apache License 2.0
google/jax
[host_callback] Fix an assertion failure for grad(remat(host_callback)) Fixes: #5878
260,578
17.09.2021 08:43:25
25,200
d0acd9f3435a7eff924c9be937dc2abb1716e79a
Add flags to configure the cuda_compute_capability and rocm_amd_targets
[ { "change_type": "MODIFY", "old_path": "build/build.py", "new_path": "build/build.py", "diff": "@@ -214,7 +214,8 @@ def check_bazel_version(bazel_path):\ndef write_bazelrc(python_bin_path=None, remote_build=None,\ncuda_toolkit_path=None, cudnn_install_path=None,\ncuda_version=None, cudnn_version=None, rocm_toolkit_path=None,\n- cpu=None):\n+ cpu=None, cuda_compute_capabilities=None,\n+ rocm_amdgpu_targets=None):\ntf_cuda_paths = []\nwith open(\"../.jax_configure.bazelrc\", \"w\") as f:\n@@ -245,9 +246,15 @@ def write_bazelrc(python_bin_path=None, remote_build=None,\nif cudnn_version:\nf.write(\"build --action_env TF_CUDNN_VERSION=\\\"{cudnn_version}\\\"\\n\"\n.format(cudnn_version=cudnn_version))\n+ if cuda_compute_capabilities:\n+ f.write(\n+ f'build:cuda --action_env TF_CUDA_COMPUTE_CAPABILITIES=\"{cuda_compute_capabilities}\"')\nif rocm_toolkit_path:\nf.write(\"build --action_env ROCM_PATH=\\\"{rocm_toolkit_path}\\\"\\n\"\n.format(rocm_toolkit_path=rocm_toolkit_path))\n+ if rocm_amdgpu_targets:\n+ f.write(\n+ f'build:rocm --action_env TF_ROCM_AMDGPU_TARGETS=\"{rocm_amdgpu_targets}\"')\nif cpu is not None:\nf.write(\"build --distinct_host_configuration=true\\n\")\nf.write(f\"build --cpu={cpu}\\n\")\n@@ -366,6 +373,14 @@ def main():\n\"--cudnn_version\",\ndefault=None,\nhelp=\"CUDNN version, e.g., 8\")\n+ parser.add_argument(\n+ \"--cuda_compute_capabilities\",\n+ default=\"3.5,5.2,6.0,6.1,7.0\",\n+ help=\"A comma-separated list of CUDA compute capabilities to support.\")\n+ parser.add_argument(\n+ \"--rocm_amdgpu_targets\",\n+ default=\"gfx900,gfx906,gfx90\",\n+ help=\"A comma-separated list of ROCm amdgpu targets to support.\")\nparser.add_argument(\n\"--rocm_path\",\ndefault=None,\n@@ -439,6 +454,7 @@ def main():\nprint(\"CUDA toolkit path: {}\".format(cuda_toolkit_path))\nif cudnn_install_path:\nprint(\"CUDNN library path: {}\".format(cudnn_install_path))\n+ print(\"CUDA compute capabilities: {}\".format(args.cuda_compute_capabilities))\nif args.cuda_version:\nprint(\"CUDA version: {}\".format(args.cuda_version))\nif args.cudnn_version:\n@@ -451,6 +467,7 @@ def main():\nif args.enable_rocm:\nif rocm_toolkit_path:\nprint(\"ROCm toolkit path: {}\".format(rocm_toolkit_path))\n+ print(\"ROCm amdgpu targets: {}\".format(args.rocm_amdgpu_targets))\nwrite_bazelrc(\npython_bin_path=python_bin_path,\n@@ -461,6 +478,8 @@ def main():\ncudnn_version=args.cudnn_version,\nrocm_toolkit_path=rocm_toolkit_path,\ncpu=args.target_cpu,\n+ cuda_compute_capabilities=args.cuda_compute_capabilities,\n+ rocm_amdgpu_targets=args.rocm_amdgpu_targets,\n)\nprint(\"\\nBuilding XLA and installing it in the jaxlib source tree...\")\n" } ]
Python
Apache License 2.0
google/jax
Add flags to configure the cuda_compute_capability and rocm_amd_targets
260,664
18.09.2021 14:40:29
-32,400
8b489134c818364577f630ada6aa63beefd7376a
Reflected the opinions from the reviewer.
[ { "change_type": "MODIFY", "old_path": "docs/developer.md", "new_path": "docs/developer.md", "diff": "@@ -94,7 +94,7 @@ for more details. Install the following packages:\n```\npacman -S patch coreutils\n```\n-`realpath` command should be found in shell command line.\n+Once coreutils is installed, the realpath command should be present in your shell's path.\nOnce everything is installed. Open PowerShell, and make sure MSYS2 is in the\npath of the current session. Ensure `bazel`, `patch` and `realpath` are\n@@ -106,11 +106,9 @@ python .\\build\\build.py `\n--enable_cuda `\n--cuda_path='C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v10.1' `\n--cudnn_path='C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v10.1' `\n- --cuda_compute_capabilities='6.1' `\n--cuda_version='10.1' `\n--cudnn_version='7.6.5'\n```\n-Discard `--cuda_compute_capabilities` flag in case of argument exception.\nTo build with debug information, add the flag `--bazel_options='--copt=/Z7'`.\n" } ]
Python
Apache License 2.0
google/jax
Reflected the opinions from the reviewer.
260,287
20.09.2021 08:58:09
25,200
45c1a1b0600773f089a112c939cd4b838c8e608a
Make sure that xmap raises a clear error when using an undefined resource name
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -565,7 +565,7 @@ def xmap(fun: Callable,\nresource_env = thread_resources.env\navailable_resources = set(resource_env.shape.keys())\n- if necessary_resources > available_resources:\n+ if necessary_resources - available_resources:\nraise ValueError(f\"In-scope resources are insufficient to execute the \"\nf\"xmapped function. The missing resources are: \"\nf\"{necessary_resources - available_resources}\")\n@@ -585,14 +585,14 @@ def xmap(fun: Callable,\nlambda: tuple(_flatten_axes(\"xmap out_axes\", out_tree(), out_axes, tupled_args=False)),\nclosure=(out_axes_entries, out_axes_treedef))\n- axis_resource_count = _get_axis_resource_count(normalized_axis_resources, resource_env)\n+ axis_resource_count = _get_axis_resource_count(frozen_axis_resources, resource_env)\nfor axis, size in axis_sizes.items():\nresources = axis_resource_count[axis]\nif size % resources.nglobal != 0:\nglobal_size = \"Global size\" if resources.distributed else \"Size\"\nraise ValueError(f\"{global_size} of axis {axis} ({size}) is not divisible \"\nf\"by the total number of resources assigned to this axis \"\n- f\"({normalized_axis_resources[axis]}, {resources.nglobal} in total)\")\n+ f\"({frozen_axis_resources[axis]}, {resources.nglobal} in total)\")\nfrozen_global_axis_sizes = _get_axis_sizes(args_flat, in_axes_flat,\naxis_sizes, axis_resource_count)\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -1093,6 +1093,15 @@ class XMapErrorTest(jtu.JaxTestCase):\nfxy = xmap(f, in_axes=['a', ...], out_axes=['a', ...],\naxis_resources={'a': ('x', 'x')})\n+ @jtu.with_mesh([('y', 2)])\n+ def testUndefinedAxisResource(self):\n+ error = re.escape(\n+ r\"In-scope resources are insufficient to execute the xmapped function. \"\n+ r\"The missing resources are: {'x'}\")\n+ with self.assertRaisesRegex(ValueError, error):\n+ xmap(lambda x: x, in_axes=['a', ...], out_axes=['a', ...],\n+ axis_resources={'a': 'x'})(jnp.zeros((4,)))\n+\n@jtu.with_mesh([('x', 2)])\ndef testNestedDifferentResources(self):\n@partial(xmap, in_axes={0: 'a'}, out_axes={0: 'a'}, axis_resources={'a': 'x'})\n" } ]
Python
Apache License 2.0
google/jax
Make sure that xmap raises a clear error when using an undefined resource name PiperOrigin-RevId: 397762568
260,411
22.09.2021 11:18:43
-10,800
60d0b0829166c1d3f800ea85b10bf029f6f19c05
[jax2tf] Minor updates to the jax2tf examples documentation
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/README.md", "new_path": "jax/experimental/jax2tf/examples/README.md", "diff": "@@ -11,6 +11,10 @@ This directory contains a number of examples of using the\nin a larger TensorFlow Keras model.\n* use Flax models with TensorFlow Serving, TensorFlow JavaScript, and TensorFlow Lite.\n+You can also find usage examples in other projects:\n+\n+ * A [Vision Transformer model converted to TensorFlow](https://git.io/Jz8pj) and integrated with TensorFlow Hub.\n+\n# Generating TensorFlow SavedModel\nThe functions generated by `jax2tf.convert` are standard TensorFlow functions\n@@ -104,10 +108,8 @@ If you are using Haiku, then the recipe is along these lines:\npredict_fn = hk.without_apply_rng(net).apply\n```\n-\n# Preparing the model for jax2tf\n-\nOnce you have the model in this form, you can use the\n`saved_model_lib.save_model` function from\n[saved_model_lib.py](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/saved_model_lib.py)\n@@ -174,9 +176,16 @@ At the moment, the open-source TensorFlow model server is missing XLA support,\nbut the Google version can be used, as shown in the\n[serving examples](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/serving/README.md).\n-# Using jax2tf with TensorFlow JavaScript\n+# Using jax2tf with TensorFlow Lite and TensorFlow JavaScript\nA jax2tf-generated SavedModel can also be converted to a format usable with\n-TensorFlow.js in some cases where the conversion does not require XLA support,\n-as shown in the [Quickdraw TensorFlow.js example](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/tf_js/quickdraw/README.md). Note\n-that this is highly experimental.\n+TensorFlow Lite or TensorFlow.js, by using the appropriate converters from SavedModel.\n+At the moment, these converters may reject some jax2tf-generated SavedModels due to\n+some ops not yet implemented in the converters. As a partial workaround, one\n+can pass the `enable_xla=False` parameter to `jax2tf.convert` to direct\n+`jax2tf` to avoid problematic ops. This will increase the coverage, and in fact\n+most, but not all, Flax examples can be converted this way.\n+\n+Check out the [MNIST TensorFlow Lite](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/tflite/mnist/README.md)\n+and the\n+[Quickdraw TensorFlow.js example](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/tf_js/quickdraw/README.md).\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Minor updates to the jax2tf examples documentation
260,411
23.09.2021 11:14:19
-10,800
f03baaec517da39de7fbcc3c423cf74cbcbaf9a0
Expand the docstring for jax.checkpoint. I found the old docstring to be a bit inaccurate, but mostly not explanatory enough. I think that this feature deserves a tutorial, in addition to an expanded docstring.
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -2708,15 +2708,33 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\n... z = jnp.sin(y)\n... return z\n...\n- >>> jax.grad(g)(2.0)\n- DeviceArray(-0.25563914, dtype=float32)\n+ >>> jax.value_and_grad(g)(2.0)\n+ (DeviceArray(0.78907233, dtype=float32, weak_type=True), DeviceArray(-0.2556391, dtype=float32))\nHere, the same value is produced whether or not the :func:`jax.checkpoint`\n- decorator is present. But when using :func:`jax.checkpoint`, the value\n- ``jnp.sin(2.0)`` is computed twice: once on the forward pass, and once on the\n- backward pass. The values ``jnp.cos(2.0)`` and ``jnp.cos(jnp.sin(2.0))`` are\n- also computed twice. Without using the decorator, both ``jnp.cos(2.0)`` and\n- ``jnp.cos(jnp.sin(2.0))`` would be stored and reused.\n+ decorator is present. When the decorator is not present, the values\n+ ``jnp.cos(2.0)`` and ``jnp.cos(jnp.sin(2.0))`` are computed on the forward\n+ pass and are stored for use in the backward pass, because they are needed\n+ on the backward pass and depend only on the primal inputs. When using\n+ :func:`jax.checkpoint`, the forward pass will compute only the primal outputs\n+ and only the primal inputs (``2.0``) will be stored for the backward pass.\n+ At that time, the value ``jnp.sin(2.0)`` is recomputed, along with the values\n+ ``jnp.cos(2.0)`` and ``jnp.cos(jnp.sin(2.0))``.\n+\n+ Note that in some cases the XLA compiler may do its optimization that affect\n+ the meory usage, e.g., common-subexpression optimization, fusion, or\n+ even rematerialization. For example, if the code uses only element-wise\n+ operations, like in our example, XLA may fuse both the forward and backward\n+ pass, or may rematerialize aggressively, resulting in low memory usage even\n+ without ``jax.checkpoint``. In fact, in some such cases ``jax.checkpoint`` may\n+ hinder the compiler and you may see larger memory usage. For complex examples,\n+ the effect of ``jax.checkpoint`` is likely to be more significant than the\n+ XLA optimizations.\n+\n+ The best way to use ``jax.checkpoint`` is to experiment with its placement\n+ on sub-computations. For example, ``lambda x: f(jax.checkpoint(g)(x))`` is\n+ likely to have lower memory usage under ``jax.grad`` than when not using\n+ ``jax.checkpoint``, or than when using it on ``f`` or the whole function.\nThe :func:`jax.checkpoint` decorator can be applied recursively to express\nsophisticated autodiff rematerialization strategies. For example:\n" } ]
Python
Apache License 2.0
google/jax
Expand the docstring for jax.checkpoint. I found the old docstring to be a bit inaccurate, but mostly not explanatory enough. I think that this feature deserves a tutorial, in addition to an expanded docstring.
260,411
23.09.2021 17:45:57
-10,800
b1ad9e32a78eec55467f2ec0cfb3158653bddac1
[jax2tf] Ensure that shared constants in JAX are shared also in the converted function Fixes:
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -148,6 +148,13 @@ class _ThreadLocalState(threading.local):\n# Whether to actually include XLA op metadata in the generated TF ops\nself.include_xla_op_metadata = True\n+ # A cache for the tf.convert_to_tensor for constants. We try to preserve\n+ # sharing for constants, to enable tf.Graph to take advantage of it.\n+ # See https://github.com/google/jax/issues/7992.\n+ self.constant_cache = None # None means that we don't use a cache. We\n+ # may be outside a conversion scope.\n+\n+\n_thread_local_state = _ThreadLocalState()\ndef _get_current_name_stack():\n@@ -465,6 +472,12 @@ def _interpret_fun(\nin_avals: Sequence[core.ShapedArray],\nextra_name_stack: Optional[str]\n) -> Sequence[Tuple[TfVal, core.ShapedArray]]:\n+ try:\n+ prev_constant_cache = _thread_local_state.constant_cache\n+ _thread_local_state.constant_cache = {} # Start a new cache, so that we\n+ # don't share constants across\n+ # tf.function boundaries.\n+\nwith core.new_base_main(TensorFlowTrace) as main: # type: ignore\nfun = _interpret_subtrace(fun, main, in_avals)\nwith _extended_name_stack(extra_name_stack):\n@@ -472,6 +485,9 @@ def _interpret_fun(\nout_vals: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\nfun.call_wrapped(*in_vals)\ndel main\n+ finally:\n+ _thread_local_state.constant_cache = prev_constant_cache\n+\nreturn tuple(out_vals)\n@@ -563,7 +579,8 @@ def _to_jax_dtype(tf_dtype):\ndef _tfval_to_tensor_jax_dtype(val: TfVal,\n- jax_dtype: Optional[DType] = None) -> Tuple[TfVal, DType]:\n+ jax_dtype: Optional[DType] = None,\n+ memoize_constants=False) -> Tuple[TfVal, DType]:\n\"\"\"Converts a scalar, ndarray, or tf.Tensor to a tf.Tensor with proper type.\nIf `jax_dtype` is missing, uses JAX typing rules.\n@@ -573,6 +590,8 @@ def _tfval_to_tensor_jax_dtype(val: TfVal,\nval: a scalar, ndarray, tf.Tensor, or tf.Variable\njax_dtype: an optional dtype to use. If missing, uses JAX type inference\nrules for constants.\n+ memoize_constants: whether to memoize TF constants. We can't do this\n+ everywhere, we may be outside of a conversion scope.\nReturns:\na tuple with a tf.Tensor with the type as needed by JAX, and the JAX type.\n@@ -586,11 +605,28 @@ def _tfval_to_tensor_jax_dtype(val: TfVal,\nreturn val, jax_dtype\nelse: # A constant\njax_dtype = jax_dtype or xla.abstractify(val).dtype\n+ # TODO(document): We assume that the value of a constant does not\n+ # change through the scope of the function. But it may be an ndarray, ...\n+ # JAX has the same problem when generating HLO.\n+ const_key = (id(val), jax_dtype)\n+ # Since we use id(val) as a cache key, we have to make sure that we keep\n+ # the previous `val` alive. Otherwise, for an ndarray, it can get garbage\n+ # collected and reused for a different value, which would create correctness\n+ # issues. We keep the `val` alive by storing in the cache the pair\n+ # `(val, tf_val)`.\n+ if memoize_constants and _thread_local_state.constant_cache is not None:\n+ _, tf_val = _thread_local_state.constant_cache.get(const_key, (None, None))\n+ else:\n+ tf_val = None\n+ if tf_val is None:\nconversion_dtype = _to_tf_dtype(jax_dtype)\n# The float0 type is not known to TF.\nif jax_dtype == dtypes.float0:\nval = np.zeros(np.shape(val), conversion_dtype.as_numpy_dtype)\n- return tf.convert_to_tensor(val, dtype=conversion_dtype), jax_dtype\n+ tf_val = tf.convert_to_tensor(val, dtype=conversion_dtype)\n+ if memoize_constants and _thread_local_state.constant_cache is not None:\n+ _thread_local_state.constant_cache[const_key] = (val, tf_val)\n+ return tf_val, jax_dtype\ndef _args_to_avals_and_env(\nargs: Sequence[TfVal],\n@@ -696,7 +732,8 @@ class TensorFlowTracer(core.Tracer):\nassert aval_int == val_dim, f\"expected {self._aval.shape} == {val_shape}. Found {aval_int} != {val_dim}.\" # type: ignore\nself.val = _tfval_to_tensor_jax_dtype(val,\n- self._aval.dtype)[0] # type: ignore[attr-defined]\n+ self._aval.dtype,\n+ memoize_constants=True)[0] # type: ignore[attr-defined]\n@property\ndef aval(self):\n@@ -743,7 +780,7 @@ class TensorFlowTrace(core.Trace):\nreturn TensorFlowTracer(self, tf.constant(np.nan, tf.float32),\ncore.abstract_unit)\nelse:\n- tf_val, jax_dtype = _tfval_to_tensor_jax_dtype(val)\n+ tf_val, jax_dtype = _tfval_to_tensor_jax_dtype(val, memoize_constants=True)\nreturn TensorFlowTracer(\nself, val, core.ShapedArray(tf_val.shape, jax_dtype,\nweak_type=dtypes.is_weakly_typed(val)))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "Specific JAX primitive conversion tests are in primitives_test.\"\"\"\n+import re\nfrom typing import Dict, Tuple\nfrom absl.testing import absltest\n@@ -327,7 +328,6 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ngrad_g = jax.grad(g)\nself.ConvertAndCompare(grad_g, x)\n-\ndef test_gradient_with_float0_result(self):\n# Gradient over integer-argument functions, with float0 result\ndef f(x, y): # x is an int, y is a float\n@@ -400,10 +400,10 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(g_jax2tf[2].numpy(), np.float32(2.))\nself.assertAllClose(g_jax2tf[3].numpy(), np.int32(0))\n- # @parameterized.named_parameters(jtu.cases_from_list(\n- # dict(testcase_name=f\"function={with_function}\",\n- # with_function=with_function)\n- # for with_function in [False, True]))\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\ndef test_gradients_int_argument(self, with_function=True):\n# https://github.com/google/jax/issues/6975\n# Also issue #6975.\n@@ -745,6 +745,19 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ntf_fn_array(np.array([3, 4, 5])), np.array([4.5, 10, 17.5],\njnp.bfloat16))\n+ def test_shared_constants(self):\n+ # Check that the constants are shared properly in converted functions\n+ # See https://github.com/google/jax/issues/7992.\n+ const = np.ones((16, 16))\n+ def f(x):\n+ return x + const + const + const + const\n+\n+ f_tf_graph = tf.function(jax2tf.convert(f), autograph=False).get_concrete_function(const).graph.as_graph_def()\n+ f_tf_graph_nr_consts = len(re.findall(r'op:\\s*\"Const\"', str(f_tf_graph)))\n+ # It seems that there is already a shape constant in the graph, we want to\n+ # make sure our 4 instances of \"const\" are shared.\n+ self.assertEqual(f_tf_graph_nr_consts, 2)\n+\ndef test_weak_types(self):\nmul = jax.jit(jnp.multiply)\n# The value `2` here should be weakly typed, and should not lead to\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Ensure that shared constants in JAX are shared also in the converted function Fixes: #7992
260,411
24.09.2021 07:21:05
-10,800
afe57bee69b24e493943bf8780b9c67bb259c39c
[jax2tf] Fix workaround for get_compiler_ir error
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/call_tf.py", "new_path": "jax/experimental/jax2tf/call_tf.py", "diff": "@@ -318,9 +318,12 @@ def _code_generator_and_avals(\nfunc_tf_hlo = function_flat_tf.experimental_get_compiler_ir(*args_tf_flat)(\nstage=\"hlo_serialized\", device_name=tf_device_name)\nexcept Exception as e:\n- # TODO(xjun): Use a more robust mechanism instead of replying on error\n+ # TODO(xjun): Use a more robust mechanism instead of relying on error\n# message.\n- if type(e) is TypeError and \"external symbolic tensor\" in str(e):\n+ # Check two different error messages, to ensure the code works internally\n+ # (with \"external symbolic tensor\") and also in OSS (with \"An op outside ...\").\n+ if type(e) is TypeError and (\"external symbolic tensor\" in str(e) or\n+ \"An op outside of the function building code\" in str(e)):\n# TODO(b/193754660): this may happen if we are in a function context\n# Try to salvage the situation if we are just doing abstract_eval, maybe\n# for jax2tf.convert. We can do that if all the output_shapes are known.\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix workaround for get_compiler_ir error
260,424
24.09.2021 12:13:24
-3,600
327e00a668de2475bdb7e9ebdccb95885a2c0820
PRNGKeys can have dtype float0 if they are a tangent.
[ { "change_type": "MODIFY", "old_path": "jax/_src/prng.py", "new_path": "jax/_src/prng.py", "diff": "@@ -24,6 +24,7 @@ from jax import core\nfrom jax import numpy as jnp\nfrom jax import tree_util\nfrom jax.config import config\n+from jax.dtypes import float0\nfrom jax.interpreters import batching\nfrom jax.interpreters import xla\nfrom jax._src.api import jit, vmap\n@@ -75,7 +76,7 @@ def _is_prng_key_data(impl, keys: jnp.ndarray) -> bool:\ntry:\nreturn (keys.ndim >= 1 and\nkeys.shape[-ndim:] == impl.key_shape and\n- keys.dtype == np.uint32)\n+ (keys.dtype == np.uint32 or keys.dtype == float0))\nexcept AttributeError:\nreturn False\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -1113,6 +1113,13 @@ class LaxRandomWithCustomPRNGTest(LaxRandomTest):\nTypeError, r'unsupported operand type\\(s\\) for \\+*',\nlambda: key + 47)\n+ @skipIf(np.__version__ == \"1.21.0\",\n+ \"https://github.com/numpy/numpy/issues/19305\")\n+ def test_grad_of_prng_key(self):\n+ key = self.seed_prng(73)\n+ jax.grad(lambda x: 1., allow_int=True)(key) # does not crash\n+\n+\ndef _sampler_unimplemented_with_custom_prng(*args, **kwargs):\nraise SkipTest('sampler only implemented for default RNG')\n" } ]
Python
Apache License 2.0
google/jax
PRNGKeys can have dtype float0 if they are a tangent.
260,287
27.09.2021 05:31:48
25,200
484c7e0915522377320ec17aa57d910a90b00302
Use shaped_abstractify to allow abstract arguments in .lower methods
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -30,7 +30,8 @@ from ..tree_util import (tree_flatten, tree_unflatten, all_leaves, tree_map,\ntree_leaves)\nfrom .._src.tree_util import _replace_nones\nfrom .._src.api_util import (flatten_fun_nokwargs, flatten_axes,\n- _ensure_index_tuple, donation_vector)\n+ _ensure_index_tuple, donation_vector,\n+ shaped_abstractify)\nfrom .._src import source_info_util\nfrom .._src.config import config\nfrom ..errors import JAXTypeError\n@@ -571,7 +572,6 @@ def xmap(fun: Callable,\nf\"{necessary_resources - available_resources}\")\nargs_flat, in_tree = tree_flatten(args)\n- for arg in args_flat: _check_arg(arg)\nfun_flat, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\nif donate_argnums:\ndonated_invars = donation_vector(donate_argnums, args, ())\n@@ -632,6 +632,7 @@ def xmap(fun: Callable,\nreturn tree_unflatten(out_tree(), out_flat)\ndef fun_mapped(*args):\n+ tree_map(_check_arg, args)\nfun_flat, args_flat, params, out_tree = infer_params(*args)\nout_flat = xmap_p.bind(fun_flat, *args_flat, **params)\nreturn verify_outputs(out_flat, out_tree, params)\n@@ -643,7 +644,7 @@ def xmap(fun: Callable,\ndef lower(*args):\nfun_flat, args_flat, params, out_tree = infer_params(*args)\n- avals_flat = [core.raise_to_shaped(core.get_aval(arg)) for arg in args_flat]\n+ avals_flat = [shaped_abstractify(arg) for arg in args_flat]\nreturn make_xmap_callable(\nfun_flat, params['name'], params['in_axes'], params['out_axes_thunk'],\nparams['donated_invars'], params['global_axis_sizes'], params['axis_resources'],\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -27,7 +27,8 @@ from .._src.api import _check_callable, _check_arg\nfrom .._src import source_info_util\nfrom .._src.api_util import (argnums_partial_except, flatten_axes,\nflatten_fun_nokwargs, _ensure_index_tuple,\n- donation_vector, rebase_donate_argnums)\n+ donation_vector, rebase_donate_argnums,\n+ shaped_abstractify)\nfrom ..errors import JAXTypeError\nfrom ..interpreters import ad\nfrom ..interpreters import pxla\n@@ -201,14 +202,13 @@ def pjit(fun: Callable,\ndyn_args = args\nargs_flat, in_tree = tree_flatten(args)\n- for arg in args_flat: _check_arg(arg)\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\nif donate_argnums:\ndonated_invars = donation_vector(donate_argnums, dyn_args, ())\nelse:\ndonated_invars = (False,) * len(args_flat)\n- local_in_avals = tuple(core.raise_to_shaped(core.get_aval(a)) for a in args_flat)\n+ local_in_avals = tuple(shaped_abstractify(a) for a in args_flat)\njaxpr, in_axis_resources_flat, out_axis_resources_flat = \\\n_pjit_jaxpr(flat_fun, mesh, local_in_avals,\nin_tree, hashable_pytree(in_axis_resources),\n@@ -224,6 +224,7 @@ def pjit(fun: Callable,\n@wraps(fun)\ndef wrapped(*args, **kwargs):\n+ tree_map(_check_arg, args)\nargs_flat, params, out_tree = infer_params(*args, **kwargs)\nout = pjit_p.bind(*args_flat, **params)\nreturn tree_unflatten(out_tree, out)\n" }, { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "@@ -352,6 +352,12 @@ class PJitTest(jtu.BufferDonationTestCase):\nfinally:\nxla.call_translations[pjit_p] = rule\n+ @jtu.with_mesh([('x', 2)])\n+ def testLowerWithAbstractArgs(self):\n+ x = jax.ShapeDtypeStruct((2, 2), jnp.float32)\n+ # Make sure this doesn't crash\n+ pjit(lambda x: x + 4, in_axis_resources=P('x'), out_axis_resources=P('x')).lower(x)\n+\ndef testInfeed(self):\ndevices = np.array(jax.local_devices())\nnr_devices = len(devices)\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -586,6 +586,11 @@ class XMapTest(XMapTestCase):\naxis_resources={'i': ('x', SerialLoop(4))})(x)\nself.assertAllClose(y, x + 4)\n+ def testLowerWithAbstractArgs(self):\n+ x = jax.ShapeDtypeStruct((2, 2), jnp.float32)\n+ # Make sure this doesn't crash\n+ xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...]).lower(x)\n+\nclass XMapTestSPMD(SPMDTestMixin, XMapTest):\n\"\"\"Re-executes all basic tests with the SPMD partitioner enabled\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
Use shaped_abstractify to allow abstract arguments in .lower methods PiperOrigin-RevId: 399166736
260,563
28.09.2021 18:42:44
-7,200
8a68f7761ba89c19ad33c8969f1f0f7deee3f519
Change absl flag documentation to mention `re.search` The absl help texts for test target discovery mention that targets will be discovered by `re.match` use. However, in the subsequent implementation, actually `re.search` is used. This commit changes the help texts for the `test_targets` and `exclude_test_targets` flags to correctly mention `re.search` as the discovery algorithm.
[ { "change_type": "MODIFY", "old_path": "jax/_src/test_util.py", "new_path": "jax/_src/test_util.py", "diff": "@@ -71,12 +71,12 @@ flags.DEFINE_bool(\nflags.DEFINE_string(\n'test_targets', '',\n- 'Regular expression specifying which tests to run, called via re.match on '\n+ 'Regular expression specifying which tests to run, called via re.search on '\n'the test name. If empty or unspecified, run all tests.'\n)\nflags.DEFINE_string(\n'exclude_test_targets', '',\n- 'Regular expression specifying which tests NOT to run, called via re.match '\n+ 'Regular expression specifying which tests NOT to run, called via re.search '\n'on the test name. If empty or unspecified, run all tests.'\n)\n" } ]
Python
Apache License 2.0
google/jax
Change absl flag documentation to mention `re.search` The absl help texts for test target discovery mention that targets will be discovered by `re.match` use. However, in the subsequent implementation, actually `re.search` is used. This commit changes the help texts for the `test_targets` and `exclude_test_targets` flags to correctly mention `re.search` as the discovery algorithm.
260,397
28.09.2021 20:34:35
-7,200
f9a246ac19c3e1d399b355b6cd739fd01170347e
schur lapack wrapper
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/linalg.py", "new_path": "jax/_src/lax/linalg.py", "diff": "@@ -42,6 +42,7 @@ from jax._src.lib import rocsolver\nfrom jax._src.lib import xla_client\nfrom jax._src.lib import xla_bridge as xb\n+from jax._src.lib import version as jaxlib_version\nxops = xla_client.ops\n@@ -1441,3 +1442,119 @@ def tridiagonal_solve(dl, d, du, b):\nraise ValueError(f'Only f32/f64 are supported, got {t}')\nreturn tridiagonal_solve_p.bind(dl, d, du, b, m=m, n=n, ldb=ldb, t=t)\n+\n+\n+# Schur Decomposition\n+\n+\n+def schur(x,\n+ compute_schur_vectors=True,\n+ sort_eig_vals=False,\n+ select_callable=None):\n+ return schur_p.bind(\n+ x,\n+ compute_schur_vectors=compute_schur_vectors,\n+ sort_eig_vals=sort_eig_vals,\n+ select_callable=select_callable)\n+\n+\n+def _schur_impl(operand, *, compute_schur_vectors, sort_eig_vals,\n+ select_callable):\n+ return xla.apply_primitive(\n+ schur_p,\n+ operand,\n+ compute_schur_vectors=compute_schur_vectors,\n+ sort_eig_vals=sort_eig_vals,\n+ select_callable=select_callable)\n+\n+\n+def _schur_translation_rule(c, operand, *, compute_schur_vectors,\n+ sort_eig_vals):\n+ raise NotImplementedError(\n+ \"Schur decomposition is only implemented on the CPU backend.\")\n+\n+\n+def _schur_abstract_eval(operand, *, compute_schur_vectors, sort_eig_vals,\n+ select_callable):\n+\n+ if operand.ndim < 2 or operand.shape[-2] != operand.shape[-1]:\n+ raise ValueError(\"Argument to Schur decomposition must have \"\n+ \"shape [..., n, n], got shape {}\".format(operand.shape))\n+\n+ batch_dims = operand.shape[:-2]\n+ n = operand.shape[-1]\n+ dtype = operand.dtype\n+ dtype = dtypes.canonicalize_dtype(dtype)\n+ T = operand.update(shape=batch_dims + (n, n), dtype=dtype)\n+ vs = operand.update(shape=batch_dims + (n, n), dtype=dtype)\n+\n+ return (T, vs) if compute_schur_vectors else (T,)\n+\n+\n+def _schur_cpu_translation_rule(c, operand, *, compute_schur_vectors,\n+ sort_eig_vals, select_callable):\n+ shape = c.get_shape(operand)\n+ batch_dims = shape.dimensions()[:-2]\n+\n+ if jaxlib_version < (0, 1, 72):\n+ raise NotImplementedError(\n+ \"The Schur primitive is only implemented for jaxlib versions >= 0.1.72\"\n+ )\n+\n+ _cpu_gees = lapack.gees\n+\n+ if sort_eig_vals:\n+ T, vs, sdim, info = _cpu_gees(\n+ c,\n+ operand,\n+ jobvs=compute_schur_vectors,\n+ sort=sort_eig_vals,\n+ select=select_callable)\n+ else:\n+ T, vs, info = _cpu_gees(\n+ c,\n+ operand,\n+ jobvs=compute_schur_vectors,\n+ sort=sort_eig_vals,\n+ select=select_callable)\n+\n+ ok = xops.Eq(info, xops.ConstantLiteral(c, np.array(0, np.int32)))\n+ T = _broadcasting_select(c, xops.Reshape(ok, batch_dims + (1, 1)), T,\n+ _nan_like(c, T))\n+ output = [T]\n+ if compute_schur_vectors:\n+ vs = _broadcasting_select(c, xops.Reshape(ok, batch_dims + (1, 1)), vs,\n+ _nan_like(c, vs))\n+\n+ output.append(vs)\n+\n+ return xops.Tuple(c, output)\n+\n+\n+def _schur_batching_rule(batched_args, batch_dims, *, compute_schur_vectors,\n+ sort_eig_vals, select_callable):\n+ x, = batched_args\n+ bd, = batch_dims\n+ x = batching.moveaxis(x, bd, 0)\n+\n+ return schur_p.bind(\n+ x,\n+ compute_schur_vectors=compute_schur_vectors,\n+ sort_eig_vals=sort_eig_vals,\n+ select_callable=select_callable), (0,) * (1 + compute_schur_vectors)\n+\n+\n+def _schur_jvp_rule(primals, tangents, *, compute_schur_vectors, sort_eig_vals):\n+ raise NotImplementedError(\n+ 'The differentiation rules for the Schur factorization have not been implemented.'\n+ )\n+\n+\n+schur_p = Primitive('schur')\n+schur_p.multiple_results = True\n+schur_p.def_impl(_schur_impl)\n+schur_p.def_abstract_eval(_schur_abstract_eval)\n+xla.translations[schur_p] = _schur_translation_rule\n+xla.backend_specific_translations['cpu'][schur_p] = _schur_cpu_translation_rule\n+batching.primitive_batchers[schur_p] = _schur_batching_rule\n+ad.primitive_jvps[schur_p] = _schur_jvp_rule\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/linalg.py", "new_path": "jax/lax/linalg.py", "diff": "@@ -31,4 +31,6 @@ from jax._src.lax.linalg import (\ntriangular_solve_p,\ntridiagonal_solve,\ntridiagonal_solve_p,\n+ schur,\n+ schur_p\n)\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/cpu_kernels.cc", "new_path": "jaxlib/cpu_kernels.cc", "diff": "@@ -97,8 +97,14 @@ XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\n\"lapack_cgeev\", ComplexGeev<std::complex<float>>::Kernel, \"Host\");\nXLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\n\"lapack_zgeev\", ComplexGeev<std::complex<double>>::Kernel, \"Host\");\n-\n-\n+XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"lapack_sgees\",\n+ RealGees<float>::Kernel, \"Host\");\n+XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"lapack_dgees\",\n+ RealGees<double>::Kernel, \"Host\");\n+XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\n+ \"lapack_cgees\", ComplexGees<std::complex<float>>::Kernel, \"Host\");\n+XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\n+ \"lapack_zgees\", ComplexGees<std::complex<double>>::Kernel, \"Host\");\nXLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"pocketfft\", PocketFft, \"Host\");\n} // namespace\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/lapack.cc", "new_path": "jaxlib/lapack.cc", "diff": "@@ -115,6 +115,16 @@ void GetLapackKernelsFromScipy() {\nComplexGeev<std::complex<double>>::fn =\nreinterpret_cast<ComplexGeev<std::complex<double>>::FnType*>(\nlapack_ptr(\"zgeev\"));\n+ RealGees<float>::fn =\n+ reinterpret_cast<RealGees<float>::FnType*>(lapack_ptr(\"sgees\"));\n+ RealGees<double>::fn =\n+ reinterpret_cast<RealGees<double>::FnType*>(lapack_ptr(\"dgees\"));\n+ ComplexGees<std::complex<float>>::fn =\n+ reinterpret_cast<ComplexGees<std::complex<float>>::FnType*>(\n+ lapack_ptr(\"cgees\"));\n+ ComplexGees<std::complex<double>>::fn =\n+ reinterpret_cast<ComplexGees<std::complex<double>>::FnType*>(\n+ lapack_ptr(\"zgees\"));\n}\npy::dict Registrations() {\n@@ -165,6 +175,11 @@ py::dict Registrations() {\nEncapsulateFunction(ComplexGeev<std::complex<float>>::Kernel);\ndict[\"lapack_zgeev\"] =\nEncapsulateFunction(ComplexGeev<std::complex<double>>::Kernel);\n+\n+ dict[\"lapack_sgees\"] = EncapsulateFunction(RealGees<float>::Kernel);\n+ dict[\"lapack_dgees\"] = EncapsulateFunction(RealGees<double>::Kernel);\n+ dict[\"lapack_cgees\"] = EncapsulateFunction(ComplexGees<std::complex<float>>::Kernel);\n+ dict[\"lapack_zgees\"] = EncapsulateFunction(ComplexGees<std::complex<double>>::Kernel);\nreturn dict;\n}\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/lapack.py", "new_path": "jaxlib/lapack.py", "diff": "@@ -584,3 +584,79 @@ def geev(c, a, jobvl=True, jobvr=True):\nelse:\nreturn (_ops.GetTupleElement(out, 2), _ops.GetTupleElement(out, 3),\n_ops.GetTupleElement(out, 4), _ops.GetTupleElement(out, 5))\n+\n+# # gees : Schur factorization\n+\n+def gees(c, a, jobvs=True, sort=False, select=None):\n+ a_shape = c.get_shape(a)\n+ dtype = a_shape.element_type()\n+ dims = a_shape.dimensions()\n+ assert len(dims) >= 2\n+ m, n = dims[-2:]\n+ assert m == n\n+ batch_dims = tuple(dims[:-2])\n+ num_bd = len(batch_dims)\n+ b = 1\n+ for d in batch_dims:\n+ b *= d\n+ layout = (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))\n+\n+ if sort:\n+ raise NotImplementedError(\n+ \"The sort feature of LAPACK's gees routine is not implemented.\")\n+\n+ jobvs = ord('V' if jobvs else 'N')\n+ sort = ord('S' if sort else 'N')\n+\n+ if dtype == np.float32 or dtype == np.float64:\n+ fn = b\"lapack_sgees\" if dtype == np.float32 else b\"lapack_dgees\"\n+ schurvecs_type = dtype\n+ workspaces = (Shape.array_shape(np.dtype(schurvecs_type), dims, layout),)\n+ eigvals = (Shape.array_shape(\n+ np.dtype(dtype), batch_dims + (n,), tuple(range(num_bd, -1, -1))),\n+ Shape.array_shape(\n+ np.dtype(dtype), batch_dims + (n,),\n+ tuple(range(num_bd, -1, -1))))\n+ elif dtype == np.complex64 or dtype == np.complex128:\n+ fn = b\"lapack_cgees\" if dtype == np.complex64 else b\"lapack_zgees\"\n+ schurvecs_type = dtype\n+ workspaces = (\n+ Shape.array_shape(np.dtype(schurvecs_type), dims, layout),\n+ Shape.array_shape(\n+ np.dtype(np.float32 if dtype == np.complex64 else np.float64),\n+ (n,), (0,)))\n+ eigvals = (Shape.array_shape(\n+ np.dtype(dtype), batch_dims + (n,), tuple(range(num_bd, -1, -1))),)\n+ else:\n+ raise NotImplementedError(\"Unsupported dtype {}\".format(dtype))\n+\n+ out = _ops.CustomCallWithLayout(\n+ c,\n+ fn,\n+ operands=(\n+ _constant_s32_scalar(c, b),\n+ _constant_s32_scalar(c, n),\n+ _ops.Constant(c, np.uint8(jobvs)),\n+ _ops.Constant(c, np.uint8(sort)),\n+ #figure out how to put the callable select function here\n+ a),\n+ shape_with_layout=Shape.tuple_shape(workspaces + eigvals + (\n+ Shape.array_shape(np.dtype(schurvecs_type), dims, layout),\n+ Shape.array_shape(\n+ np.dtype(np.int32), batch_dims, tuple(range(num_bd - 1, -1, -1))),\n+ Shape.array_shape(\n+ np.dtype(np.int32), batch_dims, tuple(range(num_bd -\n+ 1, -1, -1))))),\n+ operand_shapes_with_layout=(\n+ Shape.array_shape(np.dtype(np.int32), (), ()),\n+ Shape.array_shape(np.dtype(np.int32), (), ()),\n+ Shape.array_shape(np.dtype(np.uint8), (), ()),\n+ Shape.array_shape(np.dtype(np.uint8), (), ()),\n+ Shape.array_shape(dtype, dims, layout),\n+ ))\n+ if sort == ord('S'):\n+ return (_ops.GetTupleElement(out, 0), _ops.GetTupleElement(out, 3),\n+ _ops.GetTupleElement(out, 4), _ops.GetTupleElement(out, 5))\n+ else:\n+ return (_ops.GetTupleElement(out, 0), _ops.GetTupleElement(out, 3),\n+ _ops.GetTupleElement(out, 5))\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/lapack_kernels.cc", "new_path": "jaxlib/lapack_kernels.cc", "diff": "@@ -628,6 +628,120 @@ template struct RealGeev<double>;\ntemplate struct ComplexGeev<std::complex<float>>;\ntemplate struct ComplexGeev<std::complex<double>>;\n+// Gees\n+\n+template <typename T>\n+typename RealGees<T>::FnType* RealGees<T>::fn = nullptr;\n+\n+template <typename T>\n+void RealGees<T>::Kernel(void* out_tuple, void** data) {\n+ int b = *(reinterpret_cast<int32_t*>(data[0]));\n+ int n = *(reinterpret_cast<int32_t*>(data[1]));\n+ char jobvs = *(reinterpret_cast<uint8_t*>(data[2]));\n+ char sort = *(reinterpret_cast<uint8_t*>(data[3]));\n+\n+ const T* a_in = reinterpret_cast<T*>(data[4]);\n+\n+ // bool* select (T, T) = reinterpret_cast<bool* (T, T)>(data[5]);\n+ bool (*select)(T, T);\n+\n+ void** out = reinterpret_cast<void**>(out_tuple);\n+ T* a_work = reinterpret_cast<T*>(out[0]);\n+\n+\n+ T* wr_out = reinterpret_cast<T*>(out[1]);\n+ T* wi_out = reinterpret_cast<T*>(out[2]);\n+ T* vs_out = reinterpret_cast<T*>(out[3]);\n+ int* sdim_out = reinterpret_cast<int*>(out[4]);\n+ int* info_out = reinterpret_cast<int*>(out[5]);\n+\n+ bool* b_work;\n+ if (sort == 'N')\n+ b_work = new bool[n];\n+\n+ T work_query;\n+ int lwork = -1;\n+ fn(&jobvs, &sort, select, &n, a_work, &n, sdim_out, wr_out, wi_out, vs_out, &n,\n+ &work_query, &lwork, b_work, info_out);\n+ lwork = static_cast<int>(work_query);\n+ T* work = new T[lwork];\n+\n+ for (int i = 0; i < b; ++i) {\n+ std::memcpy(a_work, a_in,\n+ static_cast<int64_t>(n) * static_cast<int64_t>(n) * sizeof(T));\n+ fn(&jobvs, &sort, select, &n, a_work, &n, sdim_out, wr_out, wi_out, vs_out, &n,\n+ work, &lwork, b_work, info_out);\n+\n+ a_in += static_cast<int64_t>(n) * n;\n+ a_work += static_cast<int64_t>(n) * n;\n+ wr_out += n;\n+ wi_out += n;\n+ vs_out += static_cast<int64_t>(n) * n;\n+ ++sdim_out;\n+ ++info_out;\n+ }\n+ delete[] work;\n+ delete[] b_work;\n+}\n+\n+template <typename T>\n+typename ComplexGees<T>::FnType* ComplexGees<T>::fn = nullptr;\n+\n+template <typename T>\n+void ComplexGees<T>::Kernel(void* out_tuple, void** data) {\n+ int b = *(reinterpret_cast<int32_t*>(data[0]));\n+ int n = *(reinterpret_cast<int32_t*>(data[1]));\n+ char jobvs = *(reinterpret_cast<uint8_t*>(data[2]));\n+ char sort = *(reinterpret_cast<uint8_t*>(data[3]));\n+\n+ const T* a_in = reinterpret_cast<T*>(data[4]);\n+\n+ // bool* select (T, T) = reinterpret_cast<bool* (T, T)>(data[5]);\n+ bool (*select)(T);\n+\n+ void** out = reinterpret_cast<void**>(out_tuple);\n+ T* a_work = reinterpret_cast<T*>(out[0]);\n+ typename T::value_type* r_work =\n+ reinterpret_cast<typename T::value_type*>(out[1]);\n+ T* w_out = reinterpret_cast<T*>(out[2]);\n+ T* vs_out = reinterpret_cast<T*>(out[3]);\n+ int* sdim_out = reinterpret_cast<int*>(out[4]);\n+ int* info_out = reinterpret_cast<int*>(out[5]);\n+\n+ bool* b_work;\n+ if (sort == 'N')\n+ b_work = new bool[n];\n+\n+ T work_query;\n+ int lwork = -1;\n+ fn(&jobvs, &sort, select, &n, a_work, &n, sdim_out, w_out, vs_out, &n,\n+ &work_query, &lwork, r_work, b_work, info_out);\n+ lwork = static_cast<int>(work_query.real());\n+ T* work = new T[lwork];\n+\n+\n+ for (int i = 0; i < b; ++i) {\n+ std::memcpy(a_work, a_in,\n+ static_cast<int64_t>(n) * static_cast<int64_t>(n) * sizeof(T));\n+ fn(&jobvs, &sort, select, &n, a_work, &n, sdim_out, w_out, vs_out, &n,\n+ work, &lwork, r_work, b_work, info_out);\n+\n+ a_in += static_cast<int64_t>(n) * n;\n+ a_work += static_cast<int64_t>(n) * n;\n+ w_out += n;\n+ vs_out += static_cast<int64_t>(n) * n;\n+ ++info_out;\n+ ++sdim_out;\n+ }\n+ delete[] work;\n+ delete[] b_work;\n+}\n+\n+template struct RealGees<float>;\n+template struct RealGees<double>;\n+template struct ComplexGees<std::complex<float>>;\n+template struct ComplexGees<std::complex<double>>;\n+\n// Normally JAX obtains its LAPACK/BLAS kernels via Scipy, but optionally\n// allow the user to link against LAPACK directly. This is useful when using\n// JAX-generated HLO from C++.\n@@ -678,6 +792,11 @@ jax::RealGeev<double>::FnType dgeev_ ABSL_ATTRIBUTE_WEAK;\njax::ComplexGeev<std::complex<float>>::FnType cgeev_ ABSL_ATTRIBUTE_WEAK;\njax::ComplexGeev<std::complex<double>>::FnType zgeev_ ABSL_ATTRIBUTE_WEAK;\n+jax::RealGees<float>::FnType sgees_ ABSL_ATTRIBUTE_WEAK;\n+jax::RealGees<double>::FnType dgees_ ABSL_ATTRIBUTE_WEAK;\n+jax::ComplexGees<std::complex<float>>::FnType cgees_ ABSL_ATTRIBUTE_WEAK;\n+jax::ComplexGees<std::complex<double>>::FnType zgees_ ABSL_ATTRIBUTE_WEAK;\n+\n} // extern \"C\"\nnamespace jax {\n@@ -715,6 +834,10 @@ static auto init = []() -> int {\nRealGeev<double>::fn = dgeev_;\nComplexGeev<std::complex<float>>::fn = cgeev_;\nComplexGeev<std::complex<double>>::fn = zgeev_;\n+ RealGees<float>::fn = sgees_;\n+ RealGees<double>::fn = dgees_;\n+ ComplexGees<std::complex<float>>::fn = cgees_;\n+ ComplexGees<std::complex<double>>::fn = zgees_;\nreturn 0;\n}();\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/lapack_kernels.h", "new_path": "jaxlib/lapack_kernels.h", "diff": "@@ -149,6 +149,26 @@ struct ComplexGeev {\nstatic void Kernel(void* out, void** data);\n};\n+template <typename T>\n+struct RealGees {\n+ using FnType = void(char* jobvs, char* sort, bool (*select)(T, T), lapack_int* n, T* a,\n+ lapack_int* lda, lapack_int* sdim, T* wr, T* wi, T* vs, lapack_int* ldvs,\n+ T* work, lapack_int* lwork, bool* bwork,\n+ lapack_int* info);\n+ static FnType* fn;\n+ static void Kernel(void* out, void** data);\n+};\n+\n+template <typename T>\n+struct ComplexGees {\n+ using FnType = void(char* jobvs, char* sort, bool (*select)(T), lapack_int* n, T* a,\n+ lapack_int* lda, lapack_int* sdim, T* w, T* vs, lapack_int* ldvs,\n+ T* work, lapack_int* lwork, typename T::value_type* rwork, bool* bwork,\n+ lapack_int* info);\n+ static FnType* fn;\n+ static void Kernel(void* out, void** data);\n+};\n+\n} // namespace jax\n#endif // JAXLIB_LAPACK_KERNELS_H_\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -1440,5 +1440,42 @@ class LaxLinalgTest(jtu.JaxTestCase):\nA[[0, 1], [1, 2]] = du[:-1]\nnp.testing.assert_allclose(A @ X, B, rtol=1e-6, atol=1e-6)\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n+ \"shape\": shape, \"dtype\": dtype\n+ } for shape in [(4, 4), (15, 15), (50, 50), (100, 100)]\n+ for dtype in float_types + complex_types))\n+ @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ def testSchur(self, shape, dtype):\n+ if jax._src.lib.version < (0, 1, 72):\n+ self.skipTest(\"Schur LAPACK wrapper only implemented for jaxlib versions >= 0.1.72\")\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+\n+ self._CheckAgainstNumpy(osp.linalg.schur, lax.linalg.schur, args_maker)\n+ self._CompileAndCheck(lax.linalg.schur, args_maker)\n+\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n+ \"shape\": shape, \"dtype\": dtype\n+ } for shape in [(2, 2), (4, 4), (15, 15), (50, 50), (100, 100)]\n+ for dtype in float_types + complex_types))\n+ @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ def testSchurBatching(self, shape, dtype):\n+ if jax._src.lib.version < (0, 1, 72):\n+ self.skipTest(\"Schur LAPACK wrapper only implemented for jaxlib versions >= 0.1.72\")\n+ rng = jtu.rand_default(self.rng())\n+ batch_size = 10\n+ shape = (batch_size, ) + shape\n+ args = rng(shape, dtype)\n+ reconstruct = vmap(lambda S, T: S @ T @ jnp.conj(S.T))\n+\n+ Ts, Ss = vmap(lax.linalg.schur)(args)\n+ self.assertAllClose(reconstruct(Ss, Ts), args, atol=1e-4)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
schur lapack wrapper
260,287
29.09.2021 07:40:13
25,200
2a4648b08c382cfad69d022f98eb70c81e7cdc13
Improve the error message raised when local mesh is not a continuous subcube We need this restriction for now to make the stacking of per-device chunks into process-local SDAs to make sense. Once we have GSDA we can revisit this restriction.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1452,7 +1452,9 @@ class Mesh:\n# subcube of the full array. This is because we were biased towards taking a\n# \"hull\" spanned by the devices, and in case the local devices don't form a\n# subcube that hull will contain non-local devices.\n- assert is_local_device[subcube_indices].all()\n+ if not is_local_device[subcube_indices].all():\n+ raise ValueError(\"Devices connected to a single host must form a contiguous \"\n+ \"subcube of the global device mesh\")\nreturn Mesh(self.devices[subcube_indices], self.axis_names)\n@property\n" } ]
Python
Apache License 2.0
google/jax
Improve the error message raised when local mesh is not a continuous subcube We need this restriction for now to make the stacking of per-device chunks into process-local SDAs to make sense. Once we have GSDA we can revisit this restriction. PiperOrigin-RevId: 399683607
260,287
30.09.2021 07:26:46
25,200
004d8558d39113a207e401074f4a67d3ff0c5af8
Raise a clear error message when pjit is used with CPU devices
[ { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -193,6 +193,8 @@ def pjit(fun: Callable,\nif mesh.empty:\nraise RuntimeError(\"pjit requires a non-empty mesh! Are you sure that \"\n\"it's defined at the call site?\")\n+ if any(d.platform not in {'gpu', 'tpu'} for d in mesh.devices.flat):\n+ raise RuntimeError(\"pjit only supports GPU and TPU devices\")\nf = lu.wrap_init(fun)\nif static_argnums:\n" } ]
Python
Apache License 2.0
google/jax
Raise a clear error message when pjit is used with CPU devices PiperOrigin-RevId: 399927116
260,287
01.10.2021 11:12:14
0
08685efb22c8b6651dc4896526c9c09382f01e42
Keep axis_env initialized during jaxpr_subcomp ``jaxpr_subcomp`` likes to lower control-flow primitives by tracing them again as JAX callables, but they're all axis primitives now and so they do require a properly initialized axis env.
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1860,6 +1860,16 @@ class APITest(jtu.JaxTestCase):\naxis_env = [(axis_name, api.local_device_count())]\n_ = api.xla_computation(fn, axis_env=axis_env, backend='cpu')(input_x)\n+ def test_xla_computation_axis_env(self):\n+ def fn(x):\n+ z = x * jax.lax.axis_index('i').astype(jnp.float32)\n+ def inner_fn(carry, a):\n+ return carry + a, ()\n+ return jax.lax.scan(inner_fn, jnp.zeros_like(z[0]), z)\n+\n+ x = jnp.ones((5, 6, 4))\n+ _ = jax.xla_computation(fn, axis_env=(('i', 8),), backend='cpu')(x)\n+\ndef test_concurrent_device_get_and_put(self):\ndef f(x):\nfor _ in range(100):\n" } ]
Python
Apache License 2.0
google/jax
Keep axis_env initialized during jaxpr_subcomp ``jaxpr_subcomp`` likes to lower control-flow primitives by tracing them again as JAX callables, but they're all axis primitives now and so they do require a properly initialized axis env.
260,287
01.10.2021 11:24:39
0
6c36c3e11c6ec6ff0ca2b6fa6552b80490a764e7
Fix xmap error message when checking axis specs The error message helpfully suggested using dictionaries, but it swapped the types for keys and values, for added confusion :)
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -306,7 +306,7 @@ def _parse_entry(arg_name, entry):\nraise TypeError(f\"\"\"\\\nValue mapping specification in xmap {arg_name} pytree can be either:\n- lists of axis names (possibly ending with the ellipsis object: ...)\n-- dictionaries that map axis names to positional axes (integers)\n+- dictionaries that map positional axes (integers) to axis names (e.g. {2: 'name'})\nbut got: {entry}\"\"\")\nif len(result) != num_mapped_dims:\nraise ValueError(f\"Named axes should be unique within each {arg_name} argument \"\n" } ]
Python
Apache License 2.0
google/jax
Fix xmap error message when checking axis specs The error message helpfully suggested using dictionaries, but it swapped the types for keys and values, for added confusion :)
260,287
04.10.2021 03:24:50
25,200
490d049751fec8c832c7b2d2e3af30d9436337ba
Strengthen resource type checking to verify physical mesh consistency This lets us verify that the users are not modifying physical mesh inside pjits.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -692,8 +692,9 @@ def make_xmap_callable(fun: lu.WrappedFun,\n_resource_typing_xmap([], dict(axis_resources=axis_resources,\nout_axes=out_axes,\ncall_jaxpr=jaxpr,\n+ resource_env=resource_env,\nname=name),\n- None, {})\n+ None, resource_env, {})\njaxpr = plan.subst_axes_with_resources(jaxpr)\nuse_spmd_lowering = config.experimental_xmap_spmd_lowering\nensure_fixed_sharding = config.experimental_xmap_ensure_fixed_sharding\n@@ -713,7 +714,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\nf, name, resource_env.physical_mesh,\nmesh_in_axes, mesh_out_axes, donated_invars,\nuse_spmd_lowering, in_avals,\n- tile_by_mesh_axes=True, do_resource_typecheck=None)\n+ tile_by_mesh_axes=True)\nelse:\nreturn xla.lower_xla_callable(\nf, None, backend, name, donated_invars, *((a, None) for a in in_avals))\n@@ -930,6 +931,7 @@ def show_axes(axes):\ndef _resource_typing_xmap(avals,\nparams,\nsource_info: Optional[source_info_util.Traceback],\n+ resource_env,\nouter_axis_resources):\naxis_resources = params['axis_resources']\ninner_axis_resources = dict(outer_axis_resources)\n@@ -941,9 +943,12 @@ def _resource_typing_xmap(avals,\nf\"{source_info_util.summarize(source_info)} \"\nf\"(shadowed axes: {show_axes(overlap)})\")\n+ if resource_env.physical_mesh != params['resource_env'].physical_mesh:\n+ raise RuntimeError(\"Changing the physical mesh is not allowed inside xmap.\")\n+\ncall_jaxpr = params['call_jaxpr']\npxla.resource_typecheck(\n- params['call_jaxpr'], inner_axis_resources,\n+ params['call_jaxpr'], resource_env, inner_axis_resources,\nlambda: (f\"an xmapped function {params['name']} \" +\n(f\"(xmap called at {source_info_util.summarize(source_info)})\"\nif source_info else \"\")))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -432,6 +432,7 @@ def _pjit_lower(\nname: str):\nin_axes = [get_array_mapping(axes) for axes in in_axis_resources]\nout_axes = [get_array_mapping(axes) for axes in out_axis_resources]\n+ pxla.resource_typecheck(jaxpr, resource_env, {}, lambda: \"pjit\")\nf = core.jaxpr_as_fun(jaxpr)\nf.__name__ = name\nfun = lu.wrap_init(f)\n@@ -440,8 +441,7 @@ def _pjit_lower(\nreturn pxla.lower_mesh_computation(\nfun, name, resource_env.physical_mesh,\nin_axes, out_axes, donated_invars,\n- True, local_in_avals, tile_by_mesh_axes=False,\n- do_resource_typecheck=\"pjit\")\n+ True, local_in_avals, tile_by_mesh_axes=False)\ndef _pjit_abstract_eval(*args, jaxpr, out_axis_resources, resource_env, **_):\n@@ -683,13 +683,15 @@ def _check_resources_against_named_axes(what, aval, pos_axis_resources, named_ax\nf\"a named axis appearing in its named_shape (both use mesh axes \"\nf\"{maps.show_axes(overlap)})\")\n-def _resource_typing_pjit(avals, params, source_info, named_axis_resources):\n+def _resource_typing_pjit(avals, params, source_info, resource_env, named_axis_resources):\njaxpr = params[\"jaxpr\"]\nwhat = \"pjit input\"\n+ if resource_env.physical_mesh != params['resource_env'].physical_mesh:\n+ raise RuntimeError(\"Changing the physical mesh is not allowed inside pjit.\")\nfor aval, pos_axis_resources in zip(jaxpr.in_avals, params['in_axis_resources']):\n_check_resources_against_named_axes(what, aval, pos_axis_resources, named_axis_resources)\npxla.resource_typecheck(\n- jaxpr.jaxpr, named_axis_resources,\n+ jaxpr.jaxpr, resource_env, named_axis_resources,\nlambda: (f\"a pjit'ed function {params['name']} \"\nf\"(pjit called at {source_info_util.summarize(source_info)})\"))\nwhat = \"pjit output\"\n@@ -749,7 +751,7 @@ def _sharding_constraint_batcher(insert_axis, axis_size, axis_name, main_type, v\nbatching.axis_primitive_batchers[sharding_constraint_p] = partial(_sharding_constraint_batcher, False)\npxla.spmd_primitive_batchers[sharding_constraint_p] = partial(_sharding_constraint_batcher, True)\n-def _resource_typing_sharding_constraint(avals, params, source_info, named_axis_resources):\n+def _resource_typing_sharding_constraint(avals, params, source_info, resource_env, named_axis_resources):\naval, = avals\n_check_resources_against_named_axes(\n\"with_sharding_constraint input\", aval,\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1540,8 +1540,7 @@ def lower_mesh_computation(\ndonated_invars: Sequence[bool],\nspmd_lowering: bool,\nlocal_in_untiled_avals: Sequence[core.ShapedArray],\n- tile_by_mesh_axes: bool,\n- do_resource_typecheck: Optional[str]):\n+ tile_by_mesh_axes: bool):\nassert not mesh.empty\nbackend = xb.get_device_backend(mesh.devices.flat[0])\n@@ -1583,8 +1582,6 @@ def lower_mesh_computation(\nout_tiled_avals = out_jaxpr_avals\nlocal_out_untiled_avals = [untile_aval_nd(local_axis_sizes, aval_out_axes, aval)\nfor aval, aval_out_axes in safe_zip(out_tiled_avals, out_axes)]\n- if do_resource_typecheck is not None:\n- resource_typecheck(jaxpr, {}, lambda: do_resource_typecheck)\n_sanitize_mesh_jaxpr(jaxpr)\nif local_mesh.shape != mesh.shape:\ncheck_multihost_collective_allowlist(jaxpr)\n@@ -1739,7 +1736,7 @@ def _sanitize_mesh_jaxpr(jaxpr):\ncustom_resource_typing_rules: Dict[core.Primitive, Callable] = {}\n-def resource_typecheck(jaxpr, axis_resources, what_jaxpr_thunk):\n+def resource_typecheck(jaxpr, resource_env, axis_resources, what_jaxpr_thunk):\nif isinstance(jaxpr, core.ClosedJaxpr):\njaxpr = jaxpr.jaxpr\ndef _check_aval(aval, what_thunk):\n@@ -1769,10 +1766,11 @@ def resource_typecheck(jaxpr, axis_resources, what_jaxpr_thunk):\nfor eqn in jaxpr.eqns:\ntyping_rule = custom_resource_typing_rules.get(eqn.primitive, None)\nif typing_rule:\n- typing_rule([v.aval for v in eqn.invars], eqn.params,\n- eqn.source_info, axis_resources)\n+ typing_rule([v.aval for v in eqn.invars], eqn.params, eqn.source_info,\n+ resource_env, axis_resources)\nelse:\ncore.traverse_jaxpr_params(partial(resource_typecheck,\n+ resource_env=resource_env,\naxis_resources=axis_resources,\nwhat_jaxpr_thunk=rec_what_jaxpr_thunk),\neqn.params)\n" }, { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "@@ -699,6 +699,21 @@ class PJitErrorTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, error):\npjit(lambda x: x, (p,), [p, None])([x, x, x]) # Error, we raise a generic tree mismatch message\n+ @jtu.with_mesh([('x', 2)])\n+ def testNestedDifferentResources(self):\n+ @partial(pjit, in_axis_resources=P('x'), out_axis_resources=None)\n+ def f(x):\n+ with mesh(np.array([jax.local_devices()[0]]), ('x')):\n+ @partial(pjit, in_axis_resources=P('x'), out_axis_resources=None)\n+ def h(x):\n+ return x\n+ return h(x)\n+ xshape = (2, 5, 6)\n+ x = jnp.arange(np.prod(xshape)).reshape(xshape)\n+ with self.assertRaisesRegex(RuntimeError,\n+ \"Changing the physical mesh is not allowed.*\"):\n+ f(x)\n+\nclass UtilTest(jtu.JaxTestCase):\ndef testOpShardingRoundTrip(self):\n" } ]
Python
Apache License 2.0
google/jax
Strengthen resource type checking to verify physical mesh consistency This lets us verify that the users are not modifying physical mesh inside pjits. PiperOrigin-RevId: 400675775
260,392
04.10.2021 21:32:57
14,400
5d675220c0a437ea422180a65128a24d0ac27561
Add float0 support to equality and closeness check
[ { "change_type": "MODIFY", "old_path": "jax/_src/test_util.py", "new_path": "jax/_src/test_util.py", "diff": "@@ -101,6 +101,7 @@ def is_sequence(x):\nreturn True\n_default_tolerance = {\n+ _dtypes.float0: 0,\nnp.dtype(np.bool_): 0,\nnp.dtype(np.int8): 0,\nnp.dtype(np.int16): 0,\n@@ -136,6 +137,11 @@ default_gradient_tolerance = {\n}\ndef _assert_numpy_allclose(a, b, atol=None, rtol=None, err_msg=''):\n+ if a.dtype == b.dtype == _dtypes.float0:\n+ if a.shape != b.shape:\n+ raise AssertionError(\n+ f'float0 arrays have different shapes: {a.shape, b.shape}. {err_msg}')\n+ return\na = a.astype(np.float32) if a.dtype == _dtypes.bfloat16 else a\nb = b.astype(np.float32) if b.dtype == _dtypes.bfloat16 else b\nkw = {}\n" } ]
Python
Apache License 2.0
google/jax
Add float0 support to equality and closeness check
260,335
04.10.2021 21:47:12
25,200
7ec797b794a57c211ca7ee89a7165451ff3bf738
lower rng_bit_generator using a BitcastConvertType
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -55,6 +55,7 @@ import jax._src.lib\nfrom jax._src.lib import pytree\nfrom jax._src.lib import xla_bridge\nfrom jax._src.lib import xla_client\n+from jax._src.lib import version as jaxlib_version\nxb = xla_bridge\nxc = xla_client\n@@ -6754,8 +6755,7 @@ def _rng_bit_generator_weak_type_rule(key, *, shape, dtype, algorithm):\ndel shape, dtype, algorithm\nreturn (key.weak_type, False)\n-\n-def _rng_bit_generator_translation_rule(c, key, *, shape, dtype, algorithm):\n+def _rng_bit_generator_translation_rule(backend_is_gpu, c, key, *, shape, dtype, algorithm):\nkey_shape, key_dtype = c.get_shape(key).dimensions(), c.get_shape(key).numpy_dtype()\n# While the RngBitGenerator HLO accepts a u64[2] key on all backends, we\n# typically represent the key argument to this primitive as a u32[4] so as to\n@@ -6766,21 +6766,23 @@ def _rng_bit_generator_translation_rule(c, key, *, shape, dtype, algorithm):\n(key_shape == (2,) and key_dtype == dtypes.dtype('uint64')))\nxla_shape = xc.Shape.array_shape(np.dtype(dtype), shape)\nif key_dtype == dtypes.dtype('uint32'):\n- u64_etype = xla_client.dtype_to_etype(dtypes.dtype('uint64'))\n- # TODO(mattjj): use BitcastConvertType implementation with newer jaxlib\n- # new_key = xops.BitcastConvertType(xops.Reshape(key, (2, 2)), u64_etype)\n- new_key = xla_bridge.constant(c, np.zeros(2, dtype=np.dtype('uint64')),\n+ u64_etype = xc.dtype_to_etype(dtypes.dtype('uint64'))\n+ # TODO(mattjj): the BitcastConvertType segfaults on GPU\n+ # TODO(mattjj): remove fallback when minimum jaxlib is 0.1.72 or newer\n+ if jaxlib_version >= (0, 1, 72) and not backend_is_gpu:\n+ new_key = xops.BitcastConvertType(xops.Reshape(key, (2, 2)), u64_etype)\n+ else:\n+ new_key = xb.constant(c, np.zeros(2, dtype=np.dtype('uint64')),\ncanonicalize_types=False)\nfor i in range(4):\nelt = xops.ConvertElementType(xops.Slice(key, [i], [i+1], [1]), u64_etype)\nif i % 2 == 0:\n- elt = xops.ShiftLeft(elt, xla_bridge.constant(c, np.uint64(32), canonicalize_types=False))\n- new_key = xops.DynamicUpdateSlice(new_key, elt, [xla_bridge.constant(c, i // 2)])\n+ elt = xops.ShiftLeft(elt, xb.constant(c, np.uint64(32), canonicalize_types=False))\n+ new_key = xops.DynamicUpdateSlice(new_key, elt, [xb.constant(c, i // 2)])\nreturn xops.RngBitGenerator(algorithm, new_key, xla_shape)\nelse:\nreturn xops.RngBitGenerator(algorithm, key, xla_shape)\n-\ndef _rng_bit_generator_named_shape_rule(key, *, shape, dtype, algorithm):\nreturn [key.named_shape, key.named_shape]\n@@ -6793,7 +6795,10 @@ rng_bit_generator_p.def_abstract_eval(\n_rng_bit_generator_shape_rule, _rng_bit_generator_dtype_rule,\n_rng_bit_generator_weak_type_rule,\n_rng_bit_generator_named_shape_rule))\n-xla.translations[rng_bit_generator_p] = _rng_bit_generator_translation_rule\n+xla.translations[rng_bit_generator_p] = \\\n+ partial(_rng_bit_generator_translation_rule, False)\n+xla.backend_specific_translations['gpu'][rng_bit_generator_p] = \\\n+ partial(_rng_bit_generator_translation_rule, True)\nRandomAlgorithm = xops.RandomAlgorithm\nRandomAlgorithm.__str__ = lambda algorithm: algorithm.name # type: ignore[assignment]\n" } ]
Python
Apache License 2.0
google/jax
lower rng_bit_generator using a BitcastConvertType
260,645
05.10.2021 09:19:23
-3,600
8bb8c8e994ba4cfb183a8abf60c05b4d0a93d3d2
Update doc for eigh. Mention `eigenvectors` before `eigenvalues` in doc to match the order of returned values.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/linalg.py", "new_path": "jax/_src/lax/linalg.py", "diff": "@@ -89,7 +89,7 @@ def eig(x, compute_left_eigenvectors=True, compute_right_eigenvectors=True):\ndef eigh(x, lower: bool = True, symmetrize_input: bool = True):\n\"\"\"Eigendecomposition of a Hermitian matrix.\n- Computes the eigenvalues and eigenvectors of a complex Hermitian or real\n+ Computes the eigenvectors and eigenvalues of a complex Hermitian or real\nsymmetric square matrix.\nArgs:\n" } ]
Python
Apache License 2.0
google/jax
Update doc for eigh. Mention `eigenvectors` before `eigenvalues` in doc to match the order of returned values.
260,392
05.10.2021 11:30:19
14,400
ece532556bb79f3f0135b388f4b7ff691951b480
Simplify shape comparison with numpy assert
[ { "change_type": "MODIFY", "old_path": "jax/_src/test_util.py", "new_path": "jax/_src/test_util.py", "diff": "@@ -138,9 +138,7 @@ default_gradient_tolerance = {\ndef _assert_numpy_allclose(a, b, atol=None, rtol=None, err_msg=''):\nif a.dtype == b.dtype == _dtypes.float0:\n- if a.shape != b.shape:\n- raise AssertionError(\n- f'float0 arrays have different shapes: {a.shape, b.shape}. {err_msg}')\n+ np.testing.assert_array_equal(a, b, err_msg=err_msg)\nreturn\na = a.astype(np.float32) if a.dtype == _dtypes.bfloat16 else a\nb = b.astype(np.float32) if b.dtype == _dtypes.bfloat16 else b\n" } ]
Python
Apache License 2.0
google/jax
Simplify shape comparison with numpy assert
260,335
05.10.2021 13:46:57
25,200
8d641a1d1be49ef56e7c30b404f20d6dc48490b8
fix rng_bit_generator translation rule Fix two issues: 1. bit packing was incorrect 2. output key had different shape from input key
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -6745,12 +6745,10 @@ def _rng_bit_generator_shape_rule(key, *, shape, dtype, algorithm):\ndel dtype, algorithm\nreturn (key.shape, tuple(shape))\n-\ndef _rng_bit_generator_dtype_rule(key, *, shape, dtype, algorithm):\ndel shape, algorithm\nreturn (key.dtype, dtype)\n-\ndef _rng_bit_generator_weak_type_rule(key, *, shape, dtype, algorithm):\ndel shape, dtype, algorithm\nreturn (key.weak_type, False)\n@@ -6766,22 +6764,46 @@ def _rng_bit_generator_translation_rule(backend_is_gpu, c, key, *, shape, dtype,\n(key_shape == (2,) and key_dtype == dtypes.dtype('uint64')))\nxla_shape = xc.Shape.array_shape(np.dtype(dtype), shape)\nif key_dtype == dtypes.dtype('uint32'):\n- u64_etype = xc.dtype_to_etype(dtypes.dtype('uint64'))\n# TODO(mattjj): the BitcastConvertType segfaults on GPU\n# TODO(mattjj): remove fallback when minimum jaxlib is 0.1.72 or newer\nif jaxlib_version >= (0, 1, 72) and not backend_is_gpu:\n- new_key = xops.BitcastConvertType(xops.Reshape(key, (2, 2)), u64_etype)\n+ u64_etype = xc.dtype_to_etype(dtypes.dtype('uint64'))\n+ key = xops.BitcastConvertType(xops.Reshape(key, (2, 2)), u64_etype)\n+ else:\n+ key = _convert_4xU32_to_2xU64_without_bitcast(c, key)\n+ out_key, out_vals = xla.xla_destructure(\n+ c, xops.RngBitGenerator(algorithm, key, xla_shape))\n+ if key_dtype == dtypes.dtype('uint32'):\n+ if jaxlib_version >= (0, 1, 72) and not backend_is_gpu:\n+ u32_etype = xc.dtype_to_etype(dtypes.dtype('uint32'))\n+ out_key = xops.Reshape(xops.BitcastConvertType(out_key, u32_etype), (4,))\nelse:\n+ out_key = _convert_2xU64_to_4xU32_without_bitcast(c, out_key)\n+ return xops.Tuple(c, [out_key, out_vals])\n+\n+def _convert_4xU32_to_2xU64_without_bitcast(c, key):\n+ u64_etype = xc.dtype_to_etype(dtypes.dtype('uint64'))\nnew_key = xb.constant(c, np.zeros(2, dtype=np.dtype('uint64')),\ncanonicalize_types=False)\n- for i in range(4):\n- elt = xops.ConvertElementType(xops.Slice(key, [i], [i+1], [1]), u64_etype)\n- if i % 2 == 0:\n- elt = xops.ShiftLeft(elt, xb.constant(c, np.uint64(32), canonicalize_types=False))\n+ _32 = xb.constant(c, np.uint64(32), canonicalize_types=False)\n+ for i in [0, 2]:\n+ hi = xops.ConvertElementType(xops.Slice(key, [i] , [i+1], [1]), u64_etype)\n+ lo = xops.ConvertElementType(xops.Slice(key, [i+1], [i+2], [1]), u64_etype)\n+ elt = xops.Xor(xops.ShiftLeft(hi, _32), lo)\nnew_key = xops.DynamicUpdateSlice(new_key, elt, [xb.constant(c, i // 2)])\n- return xops.RngBitGenerator(algorithm, new_key, xla_shape)\n- else:\n- return xops.RngBitGenerator(algorithm, key, xla_shape)\n+ return new_key\n+\n+def _convert_2xU64_to_4xU32_without_bitcast(c, key):\n+ u32_etype = xc.dtype_to_etype(dtypes.dtype('uint32'))\n+ new_key = xb.constant(c, np.zeros(4, dtype=np.dtype('uint32')))\n+ _32 = xb.constant(c, np.uint64(32), canonicalize_types=False)\n+ for i in [0, 1]:\n+ elt = xops.Slice(key, [i], [i+1], [1])\n+ hi = xops.ConvertElementType(xops.ShiftRightLogical(elt, _32), u32_etype)\n+ lo = xops.ConvertElementType(elt, u32_etype)\n+ new_key = xops.DynamicUpdateSlice(new_key, hi, [xb.constant(c, 2 * i)])\n+ new_key = xops.DynamicUpdateSlice(new_key, lo, [xb.constant(c, 2 * i + 1)])\n+ return new_key\ndef _rng_bit_generator_named_shape_rule(key, *, shape, dtype, algorithm):\nreturn [key.named_shape, key.named_shape]\n@@ -6804,9 +6826,7 @@ RandomAlgorithm = xops.RandomAlgorithm\nRandomAlgorithm.__str__ = lambda algorithm: algorithm.name # type: ignore[assignment]\n-def rng_bit_generator(key,\n- shape,\n- dtype=np.uint32,\n+def rng_bit_generator(key, shape, dtype=np.uint32,\nalgorithm=RandomAlgorithm.RNG_DEFAULT):\n\"\"\"Stateless PRNG bit generator. Experimental and its use is discouraged.\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -2390,6 +2390,8 @@ class LaxTest(jtu.JaxTestCase):\nself.assertLen(jaxpr.jaxpr.eqns, 2)\ndef testRngBitGenerator(self):\n+ # This test covers the original behavior of lax.rng_bit_generator, which\n+ # required x64=True, and only checks shapes and jit invariance.\nif not config.x64_enabled:\nraise SkipTest(\"RngBitGenerator requires 64bit key\")\n@@ -2405,6 +2407,15 @@ class LaxTest(jtu.JaxTestCase):\nself.assertArraysEqual(out[0], out_jit[0])\nself.assertArraysEqual(out[1], out_jit[1])\n+ @jtu.skip_on_devices(\"tpu\")\n+ def testRngBitGeneratorReturnedKey(self):\n+ # This test ensures that the key bit-packing/unpacking operations used in\n+ # the translation rule for rng_bit_generator, on older jaxlibs and at time\n+ # of writing on GPU, are inverses of one another.\n+ key = np.array([3, 1, 4, 2], dtype=np.dtype('uint32'))\n+ new_key, _ = lax.rng_bit_generator(key, (0,))\n+ self.assertAllClose(key, new_key)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_dtype={}_weak_type={}\".format(dtype.__name__, weak_type),\n\"dtype\": dtype, \"weak_type\": weak_type}\n" } ]
Python
Apache License 2.0
google/jax
fix rng_bit_generator translation rule Fix two issues: 1. bit packing was incorrect 2. output key had different shape from input key Co-authored-by: Lena Martens <lenamartens@google.com>
260,424
05.10.2021 10:57:21
-3,600
342948dcc446b882cb7ec779db1b55bb77cc015b
Add batching rule for rng_bit_generator.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -6826,6 +6826,25 @@ def _convert_2xU64_to_4xU32_without_bitcast(c, key):\ndef _rng_bit_generator_named_shape_rule(key, *, shape, dtype, algorithm):\nreturn [key.named_shape, key.named_shape]\n+def _rng_bit_generator_batching_rule(batched_args, batch_dims, *, shape, dtype, algorithm):\n+ \"\"\"Calls RBG in a loop and stacks the results.\"\"\"\n+ key, = batched_args\n+ bd, = batch_dims\n+ if bd is batching.not_mapped:\n+ return rng_bit_generator_p.bind(key, shape=shape, dtype=dtype,\n+ algorithm=algorithm), (None, None)\n+ key = batching.moveaxis(key, bd, 0)\n+ out_keys = []\n+ out_bits = []\n+ for k in key:\n+ updated_key, bits = rng_bit_generator_p.bind(k, shape=shape, dtype=dtype,\n+ algorithm=algorithm)\n+ out_keys.append(reshape(updated_key, (1,)+updated_key.shape))\n+ out_bits.append(reshape(bits, (1,)+bits.shape))\n+ stacked_keys = concatenate(out_keys, 0)\n+ stacked_bits = concatenate(out_bits, 0)\n+ return (stacked_keys, stacked_bits), (0, 0)\n+\nrng_bit_generator_p = Primitive(\"rng_bit_generator\")\nrng_bit_generator_p.multiple_results = True\nrng_bit_generator_p.def_impl(\n@@ -6835,6 +6854,7 @@ rng_bit_generator_p.def_abstract_eval(\n_rng_bit_generator_shape_rule, _rng_bit_generator_dtype_rule,\n_rng_bit_generator_weak_type_rule,\n_rng_bit_generator_named_shape_rule))\n+batching.primitive_batchers[rng_bit_generator_p] = _rng_bit_generator_batching_rule\nxla.translations[rng_bit_generator_p] = \\\npartial(_rng_bit_generator_translation_rule, False)\nxla.backend_specific_translations['gpu'][rng_bit_generator_p] = \\\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -1137,6 +1137,32 @@ class LaxRandomWithRBGPRNGTest(LaxRandomTest):\nkeys = vmap(lambda i: random.fold_in(key, i))(jnp.arange(3))\nself.assertEqual(keys.shape, (3,))\n+ def test_vmap_split_not_mapped_key(self):\n+ key = self.seed_prng(73)\n+ single_split_key = random.split(key)\n+ vmapped_keys = vmap(lambda _: random.split(key))(jnp.zeros(3,))\n+ self.assertEqual(vmapped_keys.shape, (3, 2))\n+ for vk in vmapped_keys:\n+ self.assertArraysEqual(vk.keys, single_split_key.keys)\n+\n+ def test_vmap_split_mapped_key(self):\n+ key = self.seed_prng(73)\n+ mapped_keys = random.split(key, num=3)\n+ forloop_keys = [random.split(k) for k in mapped_keys]\n+ vmapped_keys = vmap(random.split)(mapped_keys)\n+ self.assertEqual(vmapped_keys.shape, (3, 2))\n+ for fk, vk in zip(forloop_keys, vmapped_keys):\n+ self.assertArraysEqual(fk.keys, vk.keys)\n+\n+ def test_vmap_random_bits(self):\n+ rand_fun = lambda key: random.randint(key, (), 0, 100)\n+ key = self.seed_prng(73)\n+ mapped_keys = random.split(key, num=3)\n+ forloop_rand_nums = [rand_fun(k) for k in mapped_keys]\n+ rand_nums = vmap(rand_fun)(mapped_keys)\n+ self.assertEqual(rand_nums.shape, (3,))\n+ self.assertArraysEqual(rand_nums, jnp.array(forloop_rand_nums))\n+\ndef test_cannot_add(self):\nkey = self.seed_prng(73)\nself.assertRaisesRegex(\n" } ]
Python
Apache License 2.0
google/jax
Add batching rule for rng_bit_generator.
260,335
07.10.2021 19:14:13
25,200
ef710ec1f6b5f227db5f4d623df6656611b8650b
update test of dlpack error message
[ { "change_type": "MODIFY", "old_path": "tests/array_interoperability_test.py", "new_path": "tests/array_interoperability_test.py", "diff": "@@ -167,7 +167,7 @@ class DLPackTest(jtu.JaxTestCase):\nbackend = xla_bridge.get_backend()\nclient = getattr(backend, \"client\", backend)\n- regex_str = (r'Unimplemented: Only DLPack tensors with trivial \\(compact\\) '\n+ regex_str = (r'UNIMPLEMENTED: Only DLPack tensors with trivial \\(compact\\) '\nr'striding are supported')\nwith self.assertRaisesRegex(RuntimeError, regex_str):\nxla_client._xla.dlpack_managed_tensor_to_buffer(\n" } ]
Python
Apache License 2.0
google/jax
update test of dlpack error message
260,335
07.10.2021 21:19:06
25,200
022cb8c0fc035c6e2bb3c95354f80e2b5c831371
rbg_split and rbg_fold_in: use vmap for fewer HLOs
[ { "change_type": "MODIFY", "old_path": "jax/_src/prng.py", "new_path": "jax/_src/prng.py", "diff": "@@ -505,12 +505,10 @@ def _rbg_seed(seed: int) -> jnp.ndarray:\nreturn jnp.concatenate([halfkey, halfkey])\ndef _rbg_split(key: jnp.ndarray, num: int) -> jnp.ndarray:\n- return jnp.concatenate([_threefry_split(key[:2], num),\n- _threefry_split(key[2:], num)], axis=1)\n+ return vmap(_threefry_split, (0, None), 1)(key.reshape(2, 2), num).reshape(num, 4)\ndef _rbg_fold_in(key: jnp.ndarray, data: int) -> jnp.ndarray:\n- return jnp.concatenate([_threefry_fold_in(key[:2], data),\n- _threefry_fold_in(key[2:], data)])\n+ return vmap(_threefry_fold_in, (0, None), 0)(key.reshape(2, 2), data).reshape(4)\ndef _rbg_random_bits(key: jnp.ndarray, bit_width: int, shape: Sequence[int]\n) -> jnp.ndarray:\n" } ]
Python
Apache License 2.0
google/jax
rbg_split and rbg_fold_in: use vmap for fewer HLOs
260,335
07.10.2021 22:04:16
25,200
482e41d796aa3fe10b8755d9763557c3892466be
remove ShapedArray.__len__ It was confusing to overload, since we sometimes think of avals like shapes paired with dtypes, and in that case len(aval) should perhaps be like len(aval.shape). The only place where this behavior was relied on was sparse/ops.py.
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1159,15 +1159,12 @@ class ShapedArray(UnshapedArray):\ndef strip_named_shape(self):\nreturn self.update(named_shape={})\n- def __len__(self):\n+ def _len(self, ignored_tracer):\ntry:\nreturn self.shape[0]\nexcept IndexError as err:\nraise TypeError(\"len() of unsized object\") from err # same as numpy error\n- def _len(self, ignored_tracer):\n- return len(self)\n-\ndef _forward_to_value(self, fun, ignored_tracer, *args):\nreturn fun(self.val, *args)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/ops.py", "new_path": "jax/experimental/sparse/ops.py", "diff": "@@ -206,7 +206,7 @@ def _csr_matvec_abstract_eval(data, indices, indptr, v, *, shape, transpose):\nassert data.shape == indices.shape\nassert data.dtype == v.dtype\nassert indices.dtype == indptr.dtype\n- assert len(indptr) == shape[0] + 1\n+ assert indptr.shape[0] == shape[0] + 1\nout_shape = shape[1] if transpose else shape[0]\nassert v.shape[0] == (shape[0] if transpose else shape[1])\nreturn core.ShapedArray((out_shape,), data.dtype)\n@@ -258,7 +258,7 @@ def _csr_matmat_abstract_eval(data, indices, indptr, B, *, shape, transpose):\nassert data.shape == indices.shape\nassert data.dtype == B.dtype\nassert indices.dtype == indptr.dtype\n- assert len(indptr) == shape[0] + 1\n+ assert indptr.shape[0] == shape[0] + 1\nout_shape = shape[1] if transpose else shape[0]\nassert B.shape[0] == (shape[0] if transpose else shape[1])\nreturn core.ShapedArray((out_shape, B.shape[1]), data.dtype)\n" } ]
Python
Apache License 2.0
google/jax
remove ShapedArray.__len__ It was confusing to overload, since we sometimes think of avals like shapes paired with dtypes, and in that case len(aval) should perhaps be like len(aval.shape). The only place where this behavior was relied on was sparse/ops.py.
260,411
08.10.2021 10:11:31
-7,200
39380182289c44380437ecdf8df9ab77bfbc68cd
Applied review suggestsions
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -2721,20 +2721,12 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\nAt that time, the value ``jnp.sin(2.0)`` is recomputed, along with the values\n``jnp.cos(2.0)`` and ``jnp.cos(jnp.sin(2.0))``.\n- Note that in some cases the XLA compiler may do its optimization that affect\n- the meory usage, e.g., common-subexpression optimization, fusion, or\n- even rematerialization. For example, if the code uses only element-wise\n- operations, like in our example, XLA may fuse both the forward and backward\n- pass, or may rematerialize aggressively, resulting in low memory usage even\n- without ``jax.checkpoint``. In fact, in some such cases ``jax.checkpoint`` may\n- hinder the compiler and you may see larger memory usage. For complex examples,\n- the effect of ``jax.checkpoint`` is likely to be more significant than the\n- XLA optimizations.\n-\n- The best way to use ``jax.checkpoint`` is to experiment with its placement\n- on sub-computations. For example, ``lambda x: f(jax.checkpoint(g)(x))`` is\n- likely to have lower memory usage under ``jax.grad`` than when not using\n- ``jax.checkpoint``, or than when using it on ``f`` or the whole function.\n+ While ``jax.checkpoint`` controls what values are stored from the forward-pass\n+ to be used on the backward pass, the total amount of memory required to\n+ evaluate a function or its VJP depends on many additional internal details of\n+ that function. Those details include which numerical primitives are used,\n+ how they're composed, where jit and control flow primitives like scan\n+ are used, and other factors.\nThe :func:`jax.checkpoint` decorator can be applied recursively to express\nsophisticated autodiff rematerialization strategies. For example:\n" } ]
Python
Apache License 2.0
google/jax
Applied review suggestsions
260,287
11.10.2021 10:47:43
0
dad29d343d94fedeee7e42889ec1c1b59a42e536
Disallow jax2tf translation of multi-process pjits I'm pretty sure it doesn't handle the local/global shape boundary correctly which likely leads to very confusing errors on the TF side.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -3042,6 +3042,9 @@ def _pjit(*args: TfVal,\n_in_avals: Sequence[core.ShapedArray],\n_out_aval: core.ShapedArray) -> TfVal:\ndel donated_invars\n+ if resource_env.physical_mesh.is_multi_process:\n+ raise NotImplementedError(\"jax2tf translation for pjit over multi-process \"\n+ \"meshes is not supported yet\")\n# TODO: add `name` to the name stack\nshard_value_for_mesh = partial(_shard_value, resource_env.physical_mesh)\n# Apply sharding annotation to the arguments\n" } ]
Python
Apache License 2.0
google/jax
Disallow jax2tf translation of multi-process pjits I'm pretty sure it doesn't handle the local/global shape boundary correctly which likely leads to very confusing errors on the TF side.
260,287
11.10.2021 10:33:21
0
b8dc8ca0041c51e129d078569ff79ef08debe09c
Fix while loop batching rule for loops with constant bodies The previous implementation failed to reach a fixpoint when the body was ignoring the carry and was returning an unbatched constant. Ensuring that the result carry is at least as batched as the input carry should fix the issue.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -393,7 +393,7 @@ def _while_loop_batching_rule(axis_size, axis_name, main_type, args, dims,\n# reach a fixpoint.\nfor _ in range(1 + len(carry_bat)):\n_, carry_bat_out = batching.batch_jaxpr(\n- body_jaxpr, axis_size, bconst_bat + carry_bat, instantiate=False,\n+ body_jaxpr, axis_size, bconst_bat + carry_bat, instantiate=carry_bat,\naxis_name=axis_name, main_type=main_type)\nif carry_bat == carry_bat_out:\nbreak\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -357,6 +357,15 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nexpected = np.array([0, 2, 2, 4])\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ # TODO(b/202709967): Enable once fixed\n+ @unittest.skipIf(jtu.device_under_test() == 'gpu', \"Test triggers an internal XLA:GPU error\")\n+ def testWhileLoopBatchedWithConstBody(self):\n+ def f(x):\n+ def body_fn(_): return jnp.asarray(0., dtype=jnp.float32)\n+ def cond_fn(_): return jnp.logical_not(False) == False\n+ return jax.lax.while_loop(cond_fn, body_fn, x)\n+ x = jnp.arange(5, dtype=jnp.float32)\n+ self.assertAllClose(jax.vmap(f)(x), x)\ndef testWhileLoopCondConstsBatched(self):\ndef fun(x, y):\n" } ]
Python
Apache License 2.0
google/jax
Fix while loop batching rule for loops with constant bodies The previous implementation failed to reach a fixpoint when the body was ignoring the carry and was returning an unbatched constant. Ensuring that the result carry is at least as batched as the input carry should fix the issue.
260,544
11.10.2021 18:56:15
-7,200
bec943cee0234178a9143a0447b224a5faa9fbdc
fix fori_loop and scan when trivial and with disable_jit
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -210,6 +210,10 @@ def fori_loop(lower, upper, body_fun, init_val):\nuse_scan = False\nif use_scan:\n+ if config.jax_disable_jit and upper_ == lower_:\n+ # non-jit implementation of scan does not support length=0\n+ return init_val\n+\n(_, result), _ = scan(_fori_scan_body_fun(body_fun), (lower_, init_val),\nNone, length=upper_ - lower_)\nelse:\n@@ -1284,6 +1288,8 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\nlength, = unique_lengths\nif config.jax_disable_jit:\n+ if length == 0:\n+ raise ValueError(\"zero-length scan is not supported in disable_jit() mode because the output type is unknown.\")\ncarry = init\nys = []\nmaybe_reversed = reversed if reverse else lambda x: x\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -542,6 +542,23 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\nself.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\n+ def testForiLoopIssue8152(self):\n+ y = lax.fori_loop(lower=0, upper=0, body_fun=lambda x, i: x + i, init_val=1.)\n+ self.assertAllClose(y, 1., check_dtypes=False)\n+\n+ # trivial fori_loop should work - even when jit is disabled\n+ with jax.disable_jit():\n+ y = lax.fori_loop(lower=0, upper=0, body_fun=lambda x, i: x + i, init_val=1.)\n+ self.assertAllClose(y, 1., check_dtypes=False)\n+\n+ # scan with length 0 should work with jit, but raise an error without\n+ def should_raise_wo_jit():\n+ carry, out = lax.scan(lambda c, x: (c + x, x), 0., np.array([]))\n+ return carry\n+ self.assertAllClose(should_raise_wo_jit(), 0., check_dtypes=False)\n+ with jax.disable_jit():\n+ self.assertRaises(ValueError, should_raise_wo_jit)\n+\ndef testCond(self):\ndef fun(x):\nif x < 3:\n" } ]
Python
Apache License 2.0
google/jax
fix fori_loop and scan when trivial and with disable_jit
260,631
12.10.2021 13:57:03
25,200
9c1198167be0ba07dac5289a23115eb082889b59
Rollback: breaks when layouts of variadic tuple elements differ
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -5807,8 +5807,7 @@ argmin_p = standard_primitive(_argminmax_shape_rule, _argminmax_dtype_rule,\nweak_type_rule=_strip_weak_type)\nbatching.defreducer(argmin_p)\nad.defjvp_zero(argmin_p)\n-if jax._src.lib._xla_extension_version < 39:\n- xla.backend_specific_translations[\"gpu\"][argmin_p] = xla.lower_fun(\n+xla.backend_specific_translations['gpu'][argmin_p] = xla.lower_fun(\npartial(_argminmax_gpu_translation_rule, _reduce_min),\nmultiple_results=False)\n@@ -5817,8 +5816,7 @@ argmax_p = standard_primitive(_argminmax_shape_rule, _argminmax_dtype_rule,\nweak_type_rule=_strip_weak_type)\nbatching.defreducer(argmax_p)\nad.defjvp_zero(argmax_p)\n-if jax._src.lib._xla_extension_version < 39:\n- xla.backend_specific_translations[\"gpu\"][argmax_p] = xla.lower_fun(\n+xla.backend_specific_translations['gpu'][argmax_p] = xla.lower_fun(\npartial(_argminmax_gpu_translation_rule, _reduce_max),\nmultiple_results=False)\n" } ]
Python
Apache License 2.0
google/jax
Rollback: breaks when layouts of variadic tuple elements differ PiperOrigin-RevId: 402648033
260,335
12.10.2021 20:06:38
25,200
a310a8173c167d0faf46033657c6f0de6f6cb7f9
rewrite remat, leave old implementation for now
[ { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/ad_checkpoint.py", "diff": "+# Copyright 2021 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+from functools import partial\n+from typing import Callable, Optional\n+import types\n+\n+import jax\n+from jax import core\n+from jax import linear_util as lu\n+from jax.interpreters import ad\n+from jax.interpreters import batching\n+from jax.interpreters import partial_eval as pe\n+from jax.interpreters import xla\n+from jax.tree_util import tree_flatten, tree_unflatten\n+from jax._src import ad_util\n+from jax._src import source_info_util\n+from jax._src.api_util import flatten_fun\n+from jax._src.traceback_util import api_boundary\n+from jax._src.util import (unzip2, wraps, split_list, partition_list, safe_map,\n+ safe_zip)\n+\n+# TODO(mattjj): before this can be the standard remat implementation, we must:\n+# [ ] fix up callers who use the 'concrete' option (now removed)\n+# [ ] implement remat-of-control-flow-primitives (passing through the policy)\n+\n+map = safe_map\n+zip = safe_zip\n+\n+\n+def _checkpoint_dots(prim, *_, **__) -> bool:\n+ return prim in {jax._src.lax.lax.dot_general_p,\n+ jax._src.lax.lax.conv_general_dilated_p}\n+\n+def _dot_with_no_batch_dims(prim, *_, **params) -> bool:\n+ if prim is jax._src.lax.lax.dot_general_p:\n+ (_, _), (lhs_b, rhs_b) = params['dimension_numbers']\n+ if not lhs_b and not rhs_b:\n+ return True\n+ return False\n+\n+checkpoint_policies = types.SimpleNamespace(\n+ checkpoint_dots=_checkpoint_dots,\n+ checkpoint_dots_with_no_batch_dims=_dot_with_no_batch_dims,\n+)\n+\n+def checkpoint(fun: Callable, prevent_cse: bool = True,\n+ policy: Optional[Callable[..., bool]] = None\n+ ) -> Callable:\n+ \"\"\"Make ``fun`` recompute internal linearization points when differentiated.\n+\n+ The :func:`jax.checkpoint` decorator, aliased to ``jax.remat``, provides a\n+ way to trade off computation time and memory cost in the context of automatic\n+ differentiation, especially with reverse-mode autodiff like :func:`jax.grad`\n+ and :func:`jax.vjp` but also with :func:`jax.linearize`.\n+\n+ When differentiating a function in reverse-mode, by default all the\n+ linearization points (e.g. inputs to elementwise nonlinear primitive\n+ operations) are stored when evaluating the forward pass so that they can be\n+ reused on the backward pass. This evaluation strategy can lead to a high\n+ memory cost, or even to poor performance on hardware accelerators where memory\n+ access is much more expensive than FLOPs.\n+\n+ An alternative evaluation strategy is for some of the linearization points to\n+ be recomputed (i.e. rematerialized) rather than stored. This approach can\n+ reduce memory usage at the cost of increased computation.\n+\n+ This function decorator produces a new version of ``fun`` which follows\n+ the rematerialization strategy rather than the default store-everything\n+ strategy. That is, it returns a new version of ``fun`` which, when\n+ differentiated, doesn't store any of its intermediate linearization points.\n+ Instead, these linearization points are recomputed from the function's saved\n+ inputs.\n+\n+ See the examples below.\n+\n+ Args:\n+ fun: Function for which the autodiff evaluation strategy is to be changed\n+ from the default of storing all intermediate linearization points to\n+ recomputing them. Its arguments and return value should be arrays,\n+ scalars, or (nested) standard Python containers (tuple/list/dict) thereof.\n+ concrete: Optional, boolean indicating whether ``fun`` may involve\n+ value-dependent Python control flow (default False). Support for such\n+ control flow is optional, and disabled by default, because in some\n+ edge-case compositions with :func:`jax.jit` it can lead to some extra\n+ computation.\n+ prevent_cse: Optional, boolean indicating whether to prevent common\n+ subexpression elimination (CSE) optimizations in the HLO generated from\n+ differentiation. This CSE prevention has costs because it can foil other\n+ optimizations, and because it can incur high overheads on some backends,\n+ especially GPU. The default is True because otherwise, under a ``jit`` or\n+ ``pmap``, CSE can defeat the purpose of this decorator. But in some\n+ settings, like when used inside a ``scan``, this CSE prevention mechanism\n+ is unnecessary, in which case ``prevent_cse`` can be set to False.\n+ policy: This is an experimental feature and the API is likely to change.\n+ Optional callable, one of the attributes of ``jax.checkpoint_policies``,\n+ which takes as input a type-level specification of a first-order primitive\n+ application and returns a boolean indicating whether the corresponding\n+ output value(s) can be saved as a residual (or, if not, instead must be\n+ recomputed in the (co)tangent computation).\n+\n+ Returns:\n+ A function (callable) with the same input/output behavior as ``fun`` but\n+ which, when differentiated using e.g. :func:`jax.grad`, :func:`jax.vjp`, or\n+ :func:`jax.linearize`, recomputes rather than stores intermediate\n+ linearization points, thus potentially saving memory at the cost of extra\n+ computation.\n+\n+ Here is a simple example:\n+\n+ >>> import jax\n+ >>> import jax.numpy as jnp\n+\n+ >>> @jax.checkpoint\n+ ... def g(x):\n+ ... y = jnp.sin(x)\n+ ... z = jnp.sin(y)\n+ ... return z\n+ ...\n+ >>> jax.value_and_grad(g)(2.0)\n+ (DeviceArray(0.78907233, dtype=float32, weak_type=True), DeviceArray(-0.2556391, dtype=float32))\n+\n+ Here, the same value is produced whether or not the :func:`jax.checkpoint`\n+ decorator is present. When the decorator is not present, the values\n+ ``jnp.cos(2.0)`` and ``jnp.cos(jnp.sin(2.0))`` are computed on the forward\n+ pass and are stored for use in the backward pass, because they are needed\n+ on the backward pass and depend only on the primal inputs. When using\n+ :func:`jax.checkpoint`, the forward pass will compute only the primal outputs\n+ and only the primal inputs (``2.0``) will be stored for the backward pass.\n+ At that time, the value ``jnp.sin(2.0)`` is recomputed, along with the values\n+ ``jnp.cos(2.0)`` and ``jnp.cos(jnp.sin(2.0))``.\n+\n+ While ``jax.checkpoint`` controls what values are stored from the forward-pass\n+ to be used on the backward pass, the total amount of memory required to\n+ evaluate a function or its VJP depends on many additional internal details of\n+ that function. Those details include which numerical primitives are used,\n+ how they're composed, where jit and control flow primitives like scan\n+ are used, and other factors.\n+\n+ The :func:`jax.checkpoint` decorator can be applied recursively to express\n+ sophisticated autodiff rematerialization strategies. For example:\n+\n+ >>> def recursive_checkpoint(funs):\n+ ... if len(funs) == 1:\n+ ... return funs[0]\n+ ... elif len(funs) == 2:\n+ ... f1, f2 = funs\n+ ... return lambda x: f1(f2(x))\n+ ... else:\n+ ... f1 = recursive_checkpoint(funs[:len(funs)//2])\n+ ... f2 = recursive_checkpoint(funs[len(funs)//2:])\n+ ... return lambda x: f1(jax.checkpoint(f2)(x))\n+ ...\n+ \"\"\"\n+ @wraps(fun)\n+ @api_boundary\n+ def fun_remat(*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+ in_avals = [core.raise_to_shaped(core.get_aval(x)) for x in args_flat]\n+ debug = pe.debug_info(fun, in_tree, False, \"checkpoint\")\n+ jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(flat_fun, in_avals, debug)\n+ out_flat = remat_p.bind(\n+ *consts, *args_flat, jaxpr=pe.convert_constvars_jaxpr(jaxpr),\n+ prevent_cse=prevent_cse, differentiated=False, policy=policy)\n+ return tree_unflatten(out_tree(), out_flat)\n+ return fun_remat\n+\n+remat = checkpoint # alias\n+\n+remat_p = core.Primitive('remat2')\n+remat_p.multiple_results = True\n+\n+@remat_p.def_impl\n+def remat_impl(*args, jaxpr, prevent_cse, differentiated, policy):\n+ del prevent_cse, differentiated, policy # Unused.\n+ return core.eval_jaxpr(jaxpr, (), *args)\n+\n+@remat_p.def_abstract_eval\n+def remat_abstract_eval(*args, jaxpr, prevent_cse, differentiated, policy):\n+ del args, prevent_cse, differentiated, policy # Unused.\n+ return [v.aval for v in jaxpr.outvars]\n+\n+def remat_translation(c, axis_env, name_stack, avals, backend, *in_nodes,\n+ jaxpr, prevent_cse, differentiated, policy):\n+ del policy # Unused.\n+ if differentiated and prevent_cse:\n+ if backend == \"gpu\":\n+ return xla._remat_using_while(\n+ c, axis_env, in_nodes, name_stack, backend, \"checkpoint\", jaxpr)\n+ else:\n+ return xla._remat_using_cond(\n+ c, axis_env, in_nodes, name_stack, backend, \"checkpoint\", jaxpr)\n+ else:\n+ outs = xla.jaxpr_subcomp(c, jaxpr, backend, axis_env, (), \"\", *in_nodes)\n+ return xla.xops.Tuple(c, outs)\n+xla.initial_style_translations[remat_p] = remat_translation\n+\n+def remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\n+ assert not jaxpr.constvars\n+ in_nonzeros = [type(t) is not ad_util.Zero for t in tangents]\n+ jaxpr_ = core.ClosedJaxpr(jaxpr, ())\n+ jaxpr_jvp_, out_nonzeros = ad.jvp_jaxpr(jaxpr_, in_nonzeros, False)\n+ nonzero_tangents = [t for t in tangents if type(t) is not ad_util.Zero]\n+ jaxpr_jvp = pe.convert_constvars_jaxpr(jaxpr_jvp_.jaxpr)\n+ outs = remat_p.bind(\n+ *jaxpr_jvp_.consts, *primals, *nonzero_tangents, jaxpr=jaxpr_jvp,\n+ prevent_cse=prevent_cse, differentiated=differentiated, policy=policy)\n+ out_primals, out_tangents_ = split_list(outs, [len(jaxpr.outvars)])\n+ out_tangents_ = iter(out_tangents_)\n+ out_tangents = [next(out_tangents_) if nz else ad_util.Zero.from_value(p)\n+ for p, nz in zip(out_primals, out_nonzeros)]\n+ return out_primals, out_tangents\n+ad.primitive_jvps[remat_p] = remat_jvp\n+\n+def remat_partial_eval(trace, *tracers, jaxpr, **params):\n+ assert not jaxpr.constvars\n+ policy = params['policy'] or (lambda *_, **__: False)\n+ # unzip into known and jaxpr_unknown\n+ in_unknowns = [not t.is_known() for t in tracers]\n+ jaxpr_known, jaxpr_unknown, out_unknowns, out_inst, _ = \\\n+ pe._partial_eval_jaxpr_custom(jaxpr, in_unknowns, policy)\n+ jaxpr_known, in_used_known = pe.dce_jaxpr(jaxpr_known, [True] * len(jaxpr_known.outvars))\n+ _, used_outs_unknown = partition_list(out_inst, out_unknowns)\n+ jaxpr_unknown, in_used_unknown = pe.dce_jaxpr(jaxpr_unknown, used_outs_unknown)\n+\n+ # compute known outputs and residuals (hoisted out of remat primitive)\n+ _, in_consts_ = unzip2(t.pval for t in tracers if t.pval.is_known())\n+ _, in_consts = partition_list(in_used_known, in_consts_)\n+ out_consts = core.eval_jaxpr(jaxpr_known, (), *in_consts)\n+ out_consts_ = iter(out_consts)\n+ # form known outputs and collect residual tracers\n+ out_known_tracers = [\n+ pe.JaxprTracer(trace, pe.PartialVal.known(next(out_consts_)), None)\n+ for uk in out_unknowns if not uk]\n+ residuals = list(out_consts_)\n+\n+ # set up unknown outputs with a recipe to call remat\n+ res_tracers = map(trace.new_instantiated_const, residuals)\n+ in_jaxpr_tracers = [*res_tracers, *map(trace.instantiate_const, tracers)]\n+ _, in_jaxpr_tracers = partition_list(in_used_unknown, in_jaxpr_tracers)\n+ out_jaxpr_tracers = [pe.JaxprTracer(trace, pe.PartialVal.unknown(x.aval), None)\n+ for x in jaxpr_unknown.outvars]\n+ new_params = dict(params, jaxpr=jaxpr_unknown, differentiated=True)\n+ recipe = pe.new_eqn_recipe(in_jaxpr_tracers, out_jaxpr_tracers, remat_p,\n+ new_params, source_info_util.current())\n+ for t in out_jaxpr_tracers: t.recipe = recipe\n+\n+ # zip together known and unknown outputs\n+ return pe._zip_knowns(out_known_tracers, out_jaxpr_tracers, out_unknowns)\n+pe.custom_partial_eval_rules[remat_p] = remat_partial_eval\n+\n+def remat_paratial_eval_custom_params_updater(_, __, params_known, params_staged):\n+ jaxpr_known = params_known.pop('call_jaxpr')\n+ jaxpr_staged = params_staged.pop('call_jaxpr')\n+ return (dict(params_known, jaxpr=jaxpr_known),\n+ dict(params_staged, jaxpr=jaxpr_staged, differentiated=True))\n+pe.partial_eval_jaxpr_custom_rules[remat_p] = \\\n+ partial(pe.call_partial_eval_custom_rule, 'jaxpr',\n+ remat_paratial_eval_custom_params_updater)\n+\n+def remat_transpose(reduce_axes, out_cts, *in_primals, jaxpr, **params):\n+ assert not jaxpr.constvars\n+ cell = lambda: None\n+\n+ @lu.wrap_init\n+ def transposed(*args):\n+ in_primals, out_cts = tree_unflatten(treedef, args)\n+ in_pvals = [pe.PartialVal.unknown(x.aval) if ad.is_undefined_primal(x) else\n+ pe.PartialVal.known(x) for x in in_primals]\n+ primal_fun = lu.wrap_init(partial(core.eval_jaxpr, jaxpr, ()))\n+ tangent_jaxpr, _, consts = pe.trace_to_jaxpr(primal_fun, in_pvals, False)\n+ dummy_args = [ad.UndefinedPrimal(v.aval) for v in tangent_jaxpr.invars]\n+ in_cts_ = ad.backward_pass(tangent_jaxpr, reduce_axes, consts, dummy_args,\n+ out_cts)\n+ in_cts, cell.treedef = tree_flatten(in_cts_)\n+ return in_cts\n+\n+ args, treedef = tree_flatten((in_primals, out_cts))\n+ in_avals = [core.raise_to_shaped(core.get_aval(x)) for x in args]\n+ transposed_jaxpr_, _, consts = pe.trace_to_jaxpr_dynamic(transposed, in_avals)\n+ transposed_jaxpr = pe.convert_constvars_jaxpr(transposed_jaxpr_)\n+ in_cts = remat_p.bind(*consts, *args, jaxpr=transposed_jaxpr, **params)\n+ return tree_unflatten(cell.treedef, in_cts) # type: ignore\n+ad.reducing_transposes[remat_p] = remat_transpose\n+\n+def remat_vmap(axis_size, axis_name, main_type, args, dims, *, jaxpr, **params):\n+ assert not jaxpr.constvars\n+ in_batched = [d is not batching.not_mapped for d in dims]\n+ jaxpr_ = core.ClosedJaxpr(jaxpr, ())\n+ jaxpr_batched_, out_batched = batching.batch_jaxpr(\n+ jaxpr_, axis_size, in_batched, instantiate=False, axis_name=axis_name,\n+ main_type=main_type)\n+ jaxpr_batched, consts = jaxpr_batched_.jaxpr, jaxpr_batched_.consts\n+ out_dims = [0 if b else None for b in out_batched]\n+ return remat_p.bind(*consts, *args, jaxpr=jaxpr_batched, **params), out_dims\n+batching.axis_primitive_batchers[remat_p] = remat_vmap\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -76,6 +76,7 @@ from ..interpreters import invertible_ad as iad\nfrom ..interpreters.invertible_ad import custom_ivjp\nfrom ..custom_derivatives import (closure_convert, custom_gradient, custom_jvp,\ncustom_vjp, linear_call)\n+from ..ad_checkpoint import checkpoint as new_checkpoint, checkpoint_policies\nfrom .._src.config import (flags, config, bool_env, disable_jit as _disable_jit,\ndebug_nans as config_debug_nans,\n@@ -2861,6 +2862,10 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\n... return lambda x: f1(jax.checkpoint(f2)(x))\n...\n\"\"\"\n+ # TODO(mattjj): we temporarily have parallel code paths\n+ if policy is not None:\n+ return new_checkpoint(fun, prevent_cse=prevent_cse, policy=policy)\n+\n@wraps(fun)\n@api_boundary\ndef fun_remat(*args, **kwargs):\n@@ -2872,22 +2877,7 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\npolicy=policy)\nreturn tree_unflatten(out_tree(), out_flat)\nreturn fun_remat\n-remat = checkpoint\n-\n-def dot_with_no_batch_dims(prim, *_, **params) -> bool:\n- if prim.name == 'dot_general':\n- (_, _), (lhs_b, rhs_b) = params['dimension_numbers']\n- if not lhs_b and not rhs_b:\n- return True\n- return False\n-\n-checkpoint_policies = types.SimpleNamespace(\n- checkpoint_dots=\n- lambda prim, *_, **__: prim in {jax._src.lax.lax.dot_general_p,\n- jax._src.lax.lax.conv_general_dilated_p},\n- checkpoint_dots_with_no_batch_dims=dot_with_no_batch_dims\n-)\n-\n+remat = checkpoint # type: ignore\ndef named_call(\nfun: Callable[..., Any],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/ad_checkpoint.py", "diff": "+# Copyright 2021 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: F401\n+from jax._src.ad_checkpoint import (\n+ checkpoint,\n+ checkpoint_policies,\n+ remat,\n+)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -952,6 +952,7 @@ tf_not_yet_impl = [\n\"random_gamma_grad\",\n\"reduce_precision\",\n\"schur\",\n+ \"remat2\", # TODO(mattjj,necula): support new remat?\n# Not high priority?\n\"after_all\",\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -970,11 +970,12 @@ def partial_eval_jaxpr_custom_rule_not_implemented(\nParamsUpdater = Callable[[List[bool], int, dict, dict], Tuple[dict, dict]]\ndef call_partial_eval_custom_rule(\n- params_updater: ParamsUpdater, saveable: Callable[..., bool],\n- unks_in: List[bool], inst_in: List[bool], eqn: JaxprEqn\n+ jaxpr_param_name: str, params_updater: ParamsUpdater,\n+ saveable: Callable[..., bool], unks_in: List[bool], inst_in: List[bool],\n+ eqn: JaxprEqn\n) -> Tuple[JaxprEqn, JaxprEqn, Sequence[bool], Sequence[bool], List[Var]]:\njaxpr_known, jaxpr_staged, unks_out, inst_out, num_res = _partial_eval_jaxpr_custom(\n- eqn.params['call_jaxpr'], unks_in, saveable)\n+ eqn.params[jaxpr_param_name], unks_in, saveable)\nins_known, _ = partition_list(unks_in, eqn.invars)\nout_binders_known, _ = partition_list(unks_out, eqn.outvars)\nout_binders_known = [v for v in out_binders_known if v is not dropvar]\n@@ -993,11 +994,13 @@ def call_partial_eval_custom_rule(\nif type(x) is Var and not inst]\nreturn eqn_known, eqn_staged, unks_out, inst_out, new_inst + residuals\npartial_eval_jaxpr_custom_rules[core.call_p] = \\\n- partial(call_partial_eval_custom_rule, lambda _, __, x, y: (x, y))\n+ partial(call_partial_eval_custom_rule, 'call_jaxpr',\n+ lambda _, __, x, y: (x, y))\npartial_eval_jaxpr_custom_rules[core.named_call_p] = \\\n- partial(call_partial_eval_custom_rule, lambda _, __, x, y: (x, y))\n+ partial(call_partial_eval_custom_rule, 'call_jaxpr',\n+ lambda _, __, x, y: (x, y))\npartial_eval_jaxpr_custom_rules[remat_call_p] = \\\n- partial(call_partial_eval_custom_rule,\n+ partial(call_partial_eval_custom_rule, 'call_jaxpr',\nlambda _, __, p1, p2: (p1, dict(p2, differentiated=True)))\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -1071,7 +1071,7 @@ def _xla_call_partial_eval_custom_params_updater(\nnew_params_staged = dict(params_staged, donated_invars=tuple(donated_invars_staged))\nreturn new_params_known, new_params_staged\npe.partial_eval_jaxpr_custom_rules[xla_call_p] = \\\n- partial(pe.call_partial_eval_custom_rule,\n+ partial(pe.call_partial_eval_custom_rule, 'call_jaxpr',\n_xla_call_partial_eval_custom_params_updater)\npe.dce_rules[xla_call_p] = pe.dce_jaxpr_call_rule\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3768,6 +3768,38 @@ class RematTest(jtu.JaxTestCase):\nreturn lax.scan(lambda _, x: (None, f(x)), None, x)[1]\njtu.check_grads(g, (jnp.ones((2, 3)),), order=2, modes=['fwd', 'rev'])\n+ def test_constants_not_hoisted(self):\n+ # The old implementation of remat worked by data dependence, and so\n+ # (potentially large) constants would not be rematerialized and could be\n+ # wastefully instantiated. This test checks that the newer remat\n+ # implementation avoids that. We engage the newer implementation by passing\n+ # an explicit policy.\n+ def saved_residuals(f, *args, **kwargs):\n+ linearize = lambda *args: jax.linearize(f, *args, **kwargs)[1]\n+ jaxpr = jax.make_jaxpr(linearize)(*args).jaxpr\n+ return [v.aval for v in jaxpr.outvars]\n+\n+ # no residuals from constants created inside jnp.einsum\n+ @partial(jax.checkpoint, policy=lambda *_, **__: False)\n+ def f(x):\n+ return jnp.einsum('ii->i', x)\n+ res_avals = saved_residuals(f, jnp.ones((2, 2)))\n+ self.assertLen(res_avals, 0)\n+\n+ # no residuals from jnp.zeros\n+ @partial(jax.checkpoint, policy=lambda *_, **__: False)\n+ def f(x):\n+ return jnp.zeros_like(x) * x\n+ res_avals = saved_residuals(f, jnp.ones((2, 2)))\n+ self.assertLen(res_avals, 0)\n+\n+ # no residuals from jnp.zeros, but input must be saved\n+ @partial(jax.checkpoint, policy=lambda *_, **__: False)\n+ def f(x):\n+ return jnp.zeros_like(x) * jnp.sin(x)\n+ res_avals = saved_residuals(f, jnp.ones((2, 2)))\n+ self.assertLen(res_avals, 1)\n+\nclass JaxprTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
rewrite remat, leave old implementation for now
260,285
11.10.2021 12:00:43
21,600
63898b6ca6dc09e24fb61bfd081a6059411398c7
Allow random.choice and random.permutation on multidimensional arrays
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -39,6 +39,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\ndefault when using jaxlib 0.1.72 or newer. The feature can be disabled using\nthe `--experimental_cpp_pmap` flag (or `JAX_CPP_PMAP` environment variable).\n* `jax.numpy.unique` now supports an optional `fill_value` argument ({jax-issue}`#8121`)\n+ * `jax.random.choice` and `jax.random.permutation` now support\n+ multidimensional arrays and an optional `axis` argument ({jax-issue}`#8158`)\n## jax 0.2.21 (Sept 23, 2021)\n* [GitHub\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/random.py", "new_path": "jax/_src/random.py", "diff": "@@ -28,7 +28,8 @@ from jax.config import config\nfrom jax.core import NamedShape\nfrom jax._src.api import jit, vmap\nfrom jax._src.numpy.lax_numpy import (_arraylike, _check_arraylike,\n- _constant_like, _convert_and_clip_integer)\n+ _constant_like, _convert_and_clip_integer,\n+ _canonicalize_axis)\nfrom jax._src.lib import xla_bridge\nfrom jax.numpy.linalg import cholesky, svd, eigh\nfrom jax.interpreters import ad\n@@ -370,33 +371,35 @@ def shuffle(key: KeyArray, x: Array, axis: int = 0) -> jnp.ndarray:\nreturn _shuffle(key, x, axis) # type: ignore\n-def permutation(key: KeyArray, x: Array) -> jnp.ndarray:\n+def permutation(key: KeyArray,\n+ x: Union[int, Array],\n+ axis: int = 0) -> jnp.ndarray:\n\"\"\"\n- Permute elements of an array along its first axis or return a permuted range.\n+ Return a randomly permuted array or range.\n- If `x` is a multi-dimensional array, it is only shuffled along its\n- first index.\n-\n- Args:n\n+ Args:\nkey: a PRNG key used as the random key.\n- x: the array or integer range to be shuffled.\n+ x: int or array. If x is an integer, randomly shuffle np.arange(x).\n+ If x is an array, randomly shuffle its elements.\n+ axis: int, optional. The axis which x is shuffled along. Default is 0.\nReturns:\nA shuffled version of x or array range\n\"\"\"\nkey, _ = _check_prng_key(key)\n+ axis = _canonicalize_axis(axis, np.ndim(x) or 1)\nif not np.ndim(x):\n# scalar case, must be a concrete integer\nif not np.issubdtype(lax.dtype(x), np.integer):\nraise TypeError(\"x must be an integer or at least 1-dimensional\")\nx = int(x) # type: ignore[assignment]\n- return _shuffle(key, jnp.arange(x), 0)\n+ return _shuffle(key, jnp.arange(x), axis)\nelif np.ndim(x) == 1:\n- return _shuffle(key, x, 0)\n+ return _shuffle(key, x, axis)\nelse:\nassert isinstance(x, jnp.ndarray)\n- ind = _shuffle(key, jnp.arange(x.shape[0]), 0) # type: ignore[attribute-error]\n- return x[ind]\n+ ind = _shuffle(key, jnp.arange(x.shape[axis]), 0) # type: ignore[attribute-error]\n+ return jnp.take(x, ind, axis)\n@partial(jit, static_argnums=(2,), inline=True)\n@@ -428,15 +431,16 @@ def _shuffle(key, x, axis) -> jnp.ndarray:\ndef choice(key: KeyArray,\n- a: IntegerArray,\n+ a: Union[int, Array],\nshape: Sequence[int] = (),\nreplace: bool = True,\n- p=None) -> jnp.ndarray:\n- \"\"\"Generates a random sample from a given 1-D array.\n+ p: Optional[RealArray] = None,\n+ axis: int = 0) -> jnp.ndarray:\n+ \"\"\"Generates a random sample from a given array.\nArgs:\nkey: a PRNG key used as the random key.\n- a : 1D array or int. If an ndarray, a random sample is generated from\n+ a : array or int. If an ndarray, a random sample is generated from\nits elements. If an int, the random sample is generated as if a were\narange(a).\nshape : tuple of ints, optional. Output shape. If the given shape is,\n@@ -447,6 +451,8 @@ def choice(key: KeyArray,\np : 1-D array-like, The probabilities associated with each entry in a.\nIf not given the sample assumes a uniform distribution over all\nentries in a.\n+ axis: int, optional. The axis along which the selection is performed.\n+ The default, 0, selects by row.\nReturns:\nAn array of shape `shape` containing samples from `a`.\n@@ -455,14 +461,13 @@ def choice(key: KeyArray,\nif not isinstance(shape, Sequence):\nraise TypeError(\"shape argument of jax.random.choice must be a sequence, \"\nf\"got {shape}\")\n- if np.ndim(a) not in [0, 1]:\n- raise ValueError(\"a must be an integer or 1-dimensional\")\n_check_arraylike(\"choice\", a)\nif np.ndim(a) == 0:\na = core.concrete_or_error(int, a, \"The error occurred in jax.random.choice()\")\nelse:\na = jnp.asarray(a)\n- n_inputs = int(a) if np.ndim(a) == 0 else len(a) # type: ignore[arg-type]\n+ axis = _canonicalize_axis(axis, np.ndim(a) or 1)\n+ n_inputs = int(a) if np.ndim(a) == 0 else a.shape[axis] # type: ignore[arg-type]\nn_draws = prod(shape)\nif n_draws == 0:\nreturn jnp.zeros(shape, dtype=lax.dtype(a))\n@@ -474,9 +479,11 @@ def choice(key: KeyArray,\nif p is None:\nif replace:\nind = randint(key, shape, 0, n_inputs)\n- result = ind if np.ndim(a) == 0 else a[ind] # type: ignore[index]\n+ result = ind if np.ndim(a) == 0 else jnp.take(a, ind, axis)\nelse:\n- result = permutation(key, a)[:n_draws]\n+ slices = tuple(slice(n_draws if a == axis else None)\n+ for a in range(np.ndim(a) or 1))\n+ result = permutation(key, a, axis)[slices]\nelse:\nif p.shape != (n_inputs,):\nraise ValueError(\"p must be None or match the shape of a\")\n@@ -484,13 +491,14 @@ def choice(key: KeyArray,\np_cuml = jnp.cumsum(p)\nr = p_cuml[-1] * (1 - uniform(key, shape))\nind = jnp.searchsorted(p_cuml, r)\n- result = ind if np.ndim(a) == 0 else a[ind] # type: ignore[index]\nelse:\n# Gumbel top-k trick: https://timvieira.github.io/blog/post/2019/09/16/algorithms-for-sampling-without-replacement/\ng = -gumbel(key, (n_inputs,)) - jnp.log(p)\nind = jnp.argsort(g)[:n_draws]\n- result = ind if np.ndim(a) == 0 else a[ind] # type: ignore[index]\n- return result.reshape(shape)\n+ result = ind if np.ndim(a) == 0 else jnp.take(a, ind, axis)\n+\n+ return result.reshape(shape if np.ndim(a) == 0 else\n+ np.insert(np.delete(a.shape, axis), axis, shape))\ndef normal(key: KeyArray,\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -399,53 +399,65 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertAllClose(np.sort(perm1), x, check_dtypes=False)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_{}_shape={}_replace={}_weighted={}_array_input={}\".format(\n- np.dtype(dtype).name, shape, replace, weighted, array_input),\n- \"dtype\": dtype, \"shape\": shape, \"replace\": replace,\n- \"weighted\": weighted, \"array_input\": array_input}\n+ dict(\n+ testcase_name=\n+ f\"_{np.dtype(dtype).name}_input_range_or_shape={input_range_or_shape}\"\n+ f\"_shape={shape}_replace={replace}_weighted={weighted}_axis={axis}\",\n+ dtype=dtype, input_range_or_shape=input_range_or_shape,\n+ shape=shape, replace=replace, weighted=weighted, axis=axis)\nfor dtype in jtu.dtypes.floating + jtu.dtypes.integer\nfor shape in [(), (5,), (4, 5)]\nfor replace in [True, False]\nfor weighted in [True, False]\n- for array_input in [False, 'jnp', 'np']))\n- def testChoice(self, dtype, shape, replace, weighted, array_input):\n- N = 100\n+ for input_range_or_shape in [100, (10, 10), (10, 5, 2), 1, (1, 5)]\n+ for is_range in [type(input_range_or_shape) is int]\n+ for ndim in [1 if is_range else len(input_range_or_shape)]\n+ for axis in range(-ndim, ndim or 1)\n+ for ninputs in [input_range_or_shape if is_range else input_range_or_shape[axis]]\n+ if replace or np.prod(shape) <= ninputs))\n+ def testChoice(self, dtype, input_range_or_shape, shape, replace, weighted, axis):\nkey = self.seed_prng(0)\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))\n- p = None if not weighted else jnp.arange(N)\n- rand = lambda key: random.choice(key, x, shape, p=p, replace=replace)\n- crand = jax.jit(rand)\n-\n- sample1 = rand(key)\n- sample2 = crand(key)\n-\n- self.assertEqual(shape, sample1.shape)\n- if array_input == 'jnp':\n- self.assertEqual(x.dtype, sample1.dtype)\n- if not replace:\n- assert len(np.unique(sample1)) == len(np.ravel(sample1))\n- self.assertAllClose(sample1, sample2)\n+ is_range = type(input_range_or_shape) is int\n+ x = (input_range_or_shape if is_range else jnp.arange(\n+ np.prod(input_range_or_shape), dtype=dtype).reshape(input_range_or_shape))\n+ N = x if is_range else x.shape[axis]\n+ p = None if not weighted else (np.arange(N) + 1) / np.sum(np.arange(N) + 1)\n+ rand = lambda key, x: random.choice(key, x, shape, replace, p, axis)\n+ sample = rand(key, x)\n+ if not is_range:\n+ self.assertEqual(dtype, sample.dtype)\n+ np_shape = np.shape(np.random.default_rng(0).choice(\n+ x, shape or None, replace, p, axis))\n+ self.assertEqual(np_shape, sample.shape)\n+ if not replace and shape:\n+ self.assertArraysEqual(np.sort(sample, axis),\n+ np.sort(np.unique(sample, axis=axis), axis))\n+ self.assertAllClose(sample, rand(key, np.array(x)))\n+ self.assertAllClose(sample, jax.jit(rand, static_argnames=\n+ 'x' if is_range else None)(key, x))\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_{}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n- \"dtype\": dtype, \"shape\": shape}\n+ dict(\n+ testcase_name=f\"_{jtu.format_shape_dtype_string(shape, dtype)}\"\n+ f\"_axis={axis}\",\n+ dtype=dtype, shape=shape, axis=axis)\nfor dtype in jtu.dtypes.floating + jtu.dtypes.integer\n- for shape in [100, (10, 10), (10, 5, 2), 0, 1, (0, 5), (1, 5)]))\n- def testPermutationArray(self, dtype, shape):\n+ for shape in [100, (10, 10), (10, 5, 2), 0, 1, (0, 5), (1, 5)]\n+ for ndim in [1 if type(shape) is int else len(shape)]\n+ for axis in range(-ndim, ndim or 1)))\n+ def testPermutationArray(self, dtype, shape, axis):\nkey = self.seed_prng(0)\n- x = jnp.arange(np.prod(shape)).reshape(shape).astype(dtype)\n- rand = lambda key: random.permutation(key, x)\n+ x = jnp.arange(np.prod(shape), dtype=dtype).reshape(shape)\n+ rand = lambda key: random.permutation(key, x, axis)\ncrand = jax.jit(rand)\nperm1 = rand(key)\nperm2 = crand(key)\nself.assertAllClose(perm1, perm2)\n- if x.shape[0] > 1:\n+ if x.shape[axis] >= 10:\nself.assertFalse(np.all(perm1 == x)) # seems unlikely!\n- self.assertAllClose(np.sort(perm1.ravel()), x.ravel(), check_dtypes=False)\n+ self.assertAllClose(np.sort(perm1, axis=axis), x, check_dtypes=False)\nself.assertArraysAllClose(\nx, jnp.arange(np.prod(shape)).reshape(shape).astype(dtype))\n@@ -465,6 +477,8 @@ class LaxRandomTest(jtu.JaxTestCase):\ndef testPermutationErrors(self):\nkey = self.seed_prng(0)\n+ with self.assertRaises(ValueError):\n+ random.permutation(key, 10, axis=3)\nwith self.assertRaises(TypeError):\nrandom.permutation(key, 10.)\nwith self.assertRaises(core.ConcretizationTypeError):\n" } ]
Python
Apache License 2.0
google/jax
Allow random.choice and random.permutation on multidimensional arrays
260,335
13.10.2021 11:06:17
25,200
82d28899c7b9754609aa1e90eb89295014a3e957
add more grad-of-jit/pmap caching tests
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2265,6 +2265,21 @@ class APITest(jtu.JaxTestCase):\nself.assertAllClose(ans1, np.cos(2.), check_dtypes=False)\nself.assertAllClose(ans2, np.cos(3.), check_dtypes=False)\n+ def test_grad_of_jit_compilation_caching2(self):\n+ # Like the above test, but instead of logging use our compile counters.\n+ @api.jit\n+ def f(x):\n+ return jnp.sin(x)\n+\n+ with jtu.count_jit_and_pmap_compiles() as count: # noqa: F841\n+ _ = jax.grad(f)(3.)\n+ self.assertEqual(count[0], 2) # one for fwd, one for bwd\n+\n+ with jtu.count_jit_and_pmap_compiles() as count: # noqa: F841\n+ _ = jax.grad(f)(3.)\n+ _ = jax.grad(f)(4.)\n+ self.assertEqual(count[0], 0) # cache hits on both fwd and bwd\n+\ndef test_grad_does_not_unflatten_tree_with_none(self):\n# https://github.com/google/jax/issues/7546\nclass CustomNode(list):\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -1785,7 +1785,29 @@ class PythonPmapTest(jtu.JaxTestCase):\nValueError, \"Non-hashable static arguments are not supported.*\"):\npmapped_f(inputs, np.asarray(1))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_axis_size={axis_size}\", \"axis_size\": axis_size}\n+ for axis_size in [1, 2])\n+ def test_grad_of_pmap_compilation_caching(self, axis_size):\n+ if len(jax.local_devices()) < axis_size:\n+ raise SkipTest(\"too few devices for test\")\n+\n+ @jax.pmap\n+ def f(x):\n+ return jnp.sin(x)\n+ x = jnp.ones(axis_size)\n+ f(x) # warm-up any dispatching compilations\n+\n+ with jtu.count_jit_and_pmap_compiles() as count: # noqa: F841\n+ _, f_bwd = jax.vjp(f, x)\n+ _ = f_bwd(x)\n+ self.assertEqual(count[0], 2) # one for fwd, one for bwd\n+\n+ with jtu.count_jit_and_pmap_compiles() as count: # noqa: F841\n+ _ = jax.vjp(f, x)\n+ _ = f_bwd(x)\n+ self.assertEqual(count[0], 0) # cache hits on fwd and bwd\nclass CppPmapTest(PythonPmapTest):\n" } ]
Python
Apache License 2.0
google/jax
add more grad-of-jit/pmap caching tests
260,285
13.10.2021 11:57:57
21,600
1934fd6e65d9f3781935fab70b3279ae3491956b
Cleanup random.permutation
[ { "change_type": "MODIFY", "old_path": "jax/_src/random.py", "new_path": "jax/_src/random.py", "diff": "@@ -374,8 +374,7 @@ def shuffle(key: KeyArray, x: Array, axis: int = 0) -> jnp.ndarray:\ndef permutation(key: KeyArray,\nx: Union[int, Array],\naxis: int = 0) -> jnp.ndarray:\n- \"\"\"\n- Return a randomly permuted array or range.\n+ \"\"\"Returns a randomly permuted array or range.\nArgs:\nkey: a PRNG key used as the random key.\n@@ -387,18 +386,16 @@ def permutation(key: KeyArray,\nA shuffled version of x or array range\n\"\"\"\nkey, _ = _check_prng_key(key)\n+ _check_arraylike(\"permutation\", x)\naxis = _canonicalize_axis(axis, np.ndim(x) or 1)\nif not np.ndim(x):\n- # scalar case, must be a concrete integer\nif not np.issubdtype(lax.dtype(x), np.integer):\nraise TypeError(\"x must be an integer or at least 1-dimensional\")\n- x = int(x) # type: ignore[assignment]\n- return _shuffle(key, jnp.arange(x), axis)\n- elif np.ndim(x) == 1:\n+ r = core.concrete_or_error(int, x, 'argument x of jax.random.permutation()')\n+ return _shuffle(key, jnp.arange(r), axis)\n+ if np.ndim(x) == 1:\nreturn _shuffle(key, x, axis)\n- else:\n- assert isinstance(x, jnp.ndarray)\n- ind = _shuffle(key, jnp.arange(x.shape[axis]), 0) # type: ignore[attribute-error]\n+ ind = _shuffle(key, jnp.arange(x.shape[axis]), 0) # type: ignore[union-attr]\nreturn jnp.take(x, ind, axis)\n@@ -481,8 +478,7 @@ def choice(key: KeyArray,\nind = randint(key, shape, 0, n_inputs)\nresult = ind if np.ndim(a) == 0 else jnp.take(a, ind, axis)\nelse:\n- slices = tuple(slice(n_draws if a == axis else None)\n- for a in range(np.ndim(a) or 1))\n+ slices = (slice(None),) * axis + (slice(n_draws),)\nresult = permutation(key, a, axis)[slices]\nelse:\nif p.shape != (n_inputs,):\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -418,8 +418,9 @@ class LaxRandomTest(jtu.JaxTestCase):\ndef testChoice(self, dtype, input_range_or_shape, shape, replace, weighted, axis):\nkey = self.seed_prng(0)\nis_range = type(input_range_or_shape) is int\n- x = (input_range_or_shape if is_range else jnp.arange(\n- np.prod(input_range_or_shape), dtype=dtype).reshape(input_range_or_shape))\n+ x = (input_range_or_shape if is_range else\n+ np.random.default_rng(0).permutation(jnp.arange(np.prod(\n+ input_range_or_shape), dtype=dtype)).reshape(input_range_or_shape))\nN = x if is_range else x.shape[axis]\np = None if not weighted else (np.arange(N) + 1) / np.sum(np.arange(N) + 1)\nrand = lambda key, x: random.choice(key, x, shape, replace, p, axis)\n@@ -430,50 +431,47 @@ class LaxRandomTest(jtu.JaxTestCase):\nx, shape or None, replace, p, axis))\nself.assertEqual(np_shape, sample.shape)\nif not replace and shape:\n- self.assertArraysEqual(np.sort(sample, axis),\n- np.sort(np.unique(sample, axis=axis), axis))\n- self.assertAllClose(sample, rand(key, np.array(x)))\n- self.assertAllClose(sample, jax.jit(rand, static_argnames=\n+ def lsort(x):\n+ if not np.prod(x.shape): return x\n+ ind = np.lexsort(np.swapaxes(x, axis, -1).reshape((-1, x.shape[axis])))\n+ return jnp.take(x, ind, axis)\n+ self.assertArraysEqual(lsort(sample), lsort(np.unique(sample, axis=axis)))\n+ self.assertArraysEqual(sample, rand(key, np.array(x)))\n+ self.assertArraysEqual(sample, jax.jit(rand, static_argnames=\n'x' if is_range else None)(key, x))\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(\n- testcase_name=f\"_{jtu.format_shape_dtype_string(shape, dtype)}\"\n+ testcase_name=f\"_dtype={dtype}_range_or_shape={range_or_shape}\"\nf\"_axis={axis}\",\n- dtype=dtype, shape=shape, axis=axis)\n+ dtype=dtype, range_or_shape=range_or_shape, axis=axis)\nfor dtype in jtu.dtypes.floating + jtu.dtypes.integer\n- for shape in [100, (10, 10), (10, 5, 2), 0, 1, (0, 5), (1, 5)]\n- for ndim in [1 if type(shape) is int else len(shape)]\n+ for range_or_shape in [0, 1, 100, (0,), (1,), (100,),\n+ (10, 10), (10, 5, 2), (0, 5), (1, 5)]\n+ for ndim in [1 if type(range_or_shape) is int else len(range_or_shape)]\nfor axis in range(-ndim, ndim or 1)))\n- def testPermutationArray(self, dtype, shape, axis):\n+ def testPermutation(self, dtype, range_or_shape, axis):\nkey = self.seed_prng(0)\n- x = jnp.arange(np.prod(shape), dtype=dtype).reshape(shape)\n- rand = lambda key: random.permutation(key, x, axis)\n- crand = jax.jit(rand)\n-\n- perm1 = rand(key)\n- perm2 = crand(key)\n-\n- self.assertAllClose(perm1, perm2)\n- if x.shape[axis] >= 10:\n- self.assertFalse(np.all(perm1 == x)) # seems unlikely!\n- self.assertAllClose(np.sort(perm1, axis=axis), x, check_dtypes=False)\n- self.assertArraysAllClose(\n- x, jnp.arange(np.prod(shape)).reshape(shape).astype(dtype))\n-\n- def testPermutationInteger(self):\n- key = self.seed_prng(0)\n- x = 100\n- rand = lambda key: random.permutation(key, x)\n- crand = jax.jit(rand)\n-\n- perm1 = rand(key)\n- perm2 = crand(key)\n-\n- self.assertAllClose(perm1, perm2)\n- self.assertEqual(perm1.dtype, perm2.dtype)\n- self.assertFalse(np.all(perm1 == np.arange(100))) # seems unlikely!\n- self.assertAllClose(np.sort(perm1), np.arange(100), check_dtypes=False)\n+ is_range = type(range_or_shape) is int\n+ x = (range_or_shape if is_range else\n+ np.random.default_rng(0).permutation(jnp.arange(\n+ np.prod(range_or_shape), dtype=dtype)).reshape(range_or_shape))\n+ shape = ((range_or_shape,) if is_range else range_or_shape)\n+ x_ = np.copy(x)\n+ rand = lambda key, x: random.permutation(key, x, axis)\n+ perm = rand(key, x)\n+ if shape[axis] >= 10:\n+ self.assertFalse(np.all(perm == x)) # seems unlikely!\n+ arr = np.arange(x) if is_range else x\n+ def lsort(x):\n+ if not np.prod(x.shape): return x\n+ ind = np.lexsort(np.swapaxes(x, axis, -1).reshape((-1, x.shape[axis])))\n+ return jnp.take(x, ind, axis)\n+ self.assertArraysEqual(lsort(arr), lsort(perm), check_dtypes=not is_range)\n+ self.assertArraysEqual(x_, x)\n+ self.assertArraysEqual(perm, rand(key, np.array(x)))\n+ self.assertArraysEqual(perm, jax.jit(rand, static_argnames=\n+ 'x' if is_range else None)(key, x))\ndef testPermutationErrors(self):\nkey = self.seed_prng(0)\n" } ]
Python
Apache License 2.0
google/jax
Cleanup random.permutation
260,335
13.10.2021 18:21:20
25,200
6741da632fa2623c1a986d9981747e5a9223565a
checkpoint_name for checkpoint policies by name Also add the jax.ad_checkpoint.print_saved_residuals utility. All this is experimental, and undocumented for now...
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_checkpoint.py", "new_path": "jax/_src/ad_checkpoint.py", "diff": "# limitations under the License.\nfrom functools import partial\n-from typing import Callable, Optional\n+from typing import Callable, Optional, List, Tuple\nimport types\nimport jax\n@@ -31,6 +31,8 @@ from jax._src.traceback_util import api_boundary\nfrom jax._src.util import (unzip2, wraps, split_list, partition_list, safe_map,\nsafe_zip)\n+source_info_util.register_exclusion(__file__)\n+\n# TODO(mattjj): before this can be the standard remat implementation, we must:\n# [ ] fix up callers who use the 'concrete' option (now removed)\n# [ ] implement remat-of-control-flow-primitives (passing through the policy)\n@@ -39,22 +41,61 @@ map = safe_map\nzip = safe_zip\n-def _checkpoint_dots(prim, *_, **__) -> bool:\n+### Policies\n+\n+def everything_saveable(*_, **__) -> bool:\n+ # This is the effective policy without any use of jax.remat.\n+ return True\n+\n+def nothing_saveable(*_, **__) -> bool:\n+ # This is the effective policy when using jax.remat without explicit policy.\n+ return False\n+\n+def checkpoint_dots(prim, *_, **__) -> bool:\n+ # Matrix multiplies are expensive, so let's save them (and nothing else).\nreturn prim in {jax._src.lax.lax.dot_general_p,\njax._src.lax.lax.conv_general_dilated_p}\n-def _dot_with_no_batch_dims(prim, *_, **params) -> bool:\n+def dot_with_no_batch_dims(prim, *_, **params) -> bool:\n+ # This is a useful heuristic for transformers.\nif prim is jax._src.lax.lax.dot_general_p:\n(_, _), (lhs_b, rhs_b) = params['dimension_numbers']\nif not lhs_b and not rhs_b:\nreturn True\nreturn False\n+name_p = core.Primitive('name')\n+\n+def save_any_names_but_these(*names_not_to_save):\n+ # Save named values, excluding the names given.\n+ names_not_to_save = frozenset(names_not_to_save)\n+ def policy(prim, *_, **params):\n+ if prim is name_p:\n+ return params['name'] not in names_not_to_save\n+ return False # only allow saving named values\n+ return policy\n+\n+def save_only_these_names(*names_which_can_be_saved):\n+ # Save named values, only among the names given.\n+ names_which_can_be_saved = set(names_which_can_be_saved)\n+ def policy(prim, *_, **params):\n+ if prim is name_p:\n+ return params['name'] in names_which_can_be_saved\n+ return False # not saveable unless it's in the allow-list\n+ return policy\n+\ncheckpoint_policies = types.SimpleNamespace(\n- checkpoint_dots=_checkpoint_dots,\n- checkpoint_dots_with_no_batch_dims=_dot_with_no_batch_dims,\n+ everything_saveable=everything_saveable,\n+ nothing_saveable=nothing_saveable,\n+ checkpoint_dots=checkpoint_dots,\n+ checkpoint_dots_with_no_batch_dims=dot_with_no_batch_dims,\n+ save_any_names_but_these=save_any_names_but_these,\n+ save_only_these_names=save_only_these_names,\n)\n+\n+### Main API\n+\ndef checkpoint(fun: Callable, prevent_cse: bool = True,\npolicy: Optional[Callable[..., bool]] = None\n) -> Callable:\n@@ -179,6 +220,50 @@ def checkpoint(fun: Callable, prevent_cse: bool = True,\nremat = checkpoint # alias\n+\n+### Utilities\n+\n+def saved_residuals(f, *args, **kwargs) -> List[Tuple[core.AbstractValue, str]]:\n+ args, in_tree = tree_flatten((args, kwargs))\n+\n+ def f_(*args):\n+ args, kwargs = tree_unflatten(in_tree, args)\n+ return f(*args, **kwargs)\n+\n+ jaxpr = jax.make_jaxpr(lambda *args: jax.linearize(f_, *args)[1])(*args).jaxpr\n+ res_vars = set(jaxpr.outvars)\n+ results = []\n+\n+ for v in jaxpr.constvars:\n+ if v in res_vars:\n+ results.append((v, 'from a constant'))\n+\n+ assert len(jaxpr.invars) == len(args)\n+ for i, v in enumerate(jaxpr.invars):\n+ if v in res_vars:\n+ src = f'from {pe.arg_info_pytree(f, in_tree, True, [i])}'\n+ results.append((v, src))\n+\n+ for eqn in jaxpr.eqns:\n+ src = source_info_util.summarize(eqn.source_info)\n+ for v in eqn.outvars:\n+ if v in res_vars:\n+ if eqn.primitive is name_p:\n+ results.append((v, f'named {eqn.params[\"name\"]} from {src}'))\n+ else:\n+ results.append((v, f'from {src}'))\n+\n+ res_vars_accounted_for = {v for v, _ in results}\n+ assert res_vars == res_vars_accounted_for, (res_vars, res_vars_accounted_for)\n+ return [(v.aval, src) for v, src in results]\n+\n+def print_saved_residuals(f, *args, **kwargs):\n+ for aval, src in saved_residuals(f, *args, **kwargs):\n+ print(f'{aval.str_short(short_dtypes=True)} {src}')\n+\n+\n+### Implementation\n+\nremat_p = core.Primitive('remat2')\nremat_p.multiple_results = True\n@@ -306,3 +391,22 @@ def remat_vmap(axis_size, axis_name, main_type, args, dims, *, jaxpr, **params):\nout_dims = [0 if b else None for b in out_batched]\nreturn remat_p.bind(*consts, *args, jaxpr=jaxpr_batched, **params), out_dims\nbatching.axis_primitive_batchers[remat_p] = remat_vmap\n+\n+\n+def checkpoint_name(x, name):\n+ return name_p.bind(x, name=name)\n+\n+name_p.def_impl(lambda x, *, name: x)\n+name_p.def_abstract_eval(lambda x, *, name: x)\n+\n+def name_jvp(primals, tangents, *, name):\n+ (x,), (xdot,) = primals, tangents\n+ return name_p.bind(x, name=name), xdot # don't name the tangent value\n+ad.primitive_jvps[name_p] = name_jvp\n+\n+xla.translations[name_p] = lambda c, x, *, name: x\n+\n+def name_batcher(args, dims, *, name):\n+ (x,), (d,) = args, dims\n+ return name_p.bind(x, name=name), d\n+batching.primitive_batchers[name_p] = name_batcher\n" }, { "change_type": "MODIFY", "old_path": "jax/ad_checkpoint.py", "new_path": "jax/ad_checkpoint.py", "diff": "from jax._src.ad_checkpoint import (\ncheckpoint,\ncheckpoint_policies,\n+ checkpoint_name,\n+ print_saved_residuals,\nremat,\n)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -953,6 +953,7 @@ tf_not_yet_impl = [\n\"reduce_precision\",\n\"schur\",\n\"remat2\", # TODO(mattjj,necula): support new remat?\n+ \"name\",\n# Not high priority?\n\"after_all\",\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -54,6 +54,8 @@ from jax._src import test_util as jtu\nfrom jax import tree_util\nfrom jax import linear_util as lu\nimport jax._src.util\n+from jax._src.ad_checkpoint import saved_residuals\n+from jax.ad_checkpoint import checkpoint_name\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -3827,11 +3829,7 @@ class RematTest(jtu.JaxTestCase):\n# (potentially large) constants would not be rematerialized and could be\n# wastefully instantiated. This test checks that the newer remat\n# implementation avoids that. We engage the newer implementation by passing\n- # an explicit policy.\n- def saved_residuals(f, *args, **kwargs):\n- linearize = lambda *args: jax.linearize(f, *args, **kwargs)[1]\n- jaxpr = jax.make_jaxpr(linearize)(*args).jaxpr\n- return [v.aval for v in jaxpr.outvars]\n+ # an explicit policy. See https://github.com/google/jax/pull/8191.\n# no residuals from constants created inside jnp.einsum\n@partial(jax.checkpoint, policy=lambda *_, **__: False)\n@@ -3854,6 +3852,74 @@ class RematTest(jtu.JaxTestCase):\nres_avals = saved_residuals(f, jnp.ones((2, 2)))\nself.assertLen(res_avals, 1)\n+ def test_name_denylist(self):\n+ def f(x):\n+ y = checkpoint_name(jnp.multiply(2., 2.), 'y')\n+ z = checkpoint_name(jnp.multiply(2., 2.), 'z')\n+ w = checkpoint_name(jnp.multiply(2., 2.), 'w')\n+ u = jnp.multiply(2., 2.)\n+ return (((x * y) * z) * w) * u\n+\n+ policy = jax.checkpoint_policies.save_any_names_but_these('y', 'z', 'w')\n+ res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ self.assertLen(res, 0) # can't save anything\n+\n+ policy = jax.checkpoint_policies.save_any_names_but_these('z', 'w')\n+ res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ self.assertLen(res, 1) # can save only y\n+\n+ policy = jax.checkpoint_policies.save_any_names_but_these('w')\n+ res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ self.assertLen(res, 2) # can save y and z\n+\n+ policy = jax.checkpoint_policies.save_any_names_but_these()\n+ res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ self.assertLen(res, 3) # can save y, z, and w\n+\n+ def test_name_allowlist(self):\n+ def f(x):\n+ y = checkpoint_name(jnp.multiply(2., 2.), 'y')\n+ z = checkpoint_name(jnp.multiply(2., 2.), 'z')\n+ w = checkpoint_name(jnp.multiply(2., 2.), 'w')\n+ u = jnp.multiply(2., 2.)\n+ return (((x * y) * z) * w) * u\n+\n+ policy = jax.checkpoint_policies.save_only_these_names('y', 'z', 'w')\n+ res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ self.assertLen(res, 3) # can save y, z, and w\n+\n+ policy = jax.checkpoint_policies.save_only_these_names('z', 'w')\n+ res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ self.assertLen(res, 2) # can save z and w\n+\n+ policy = jax.checkpoint_policies.save_only_these_names('w')\n+ res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ self.assertLen(res, 1) # can save w\n+\n+ policy = jax.checkpoint_policies.save_only_these_names()\n+ res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ self.assertLen(res, 0) # can't save anything!\n+\n+ def test_saved_residuals_utility(self):\n+ def f(x, y):\n+ x1, x2 = x\n+ z = checkpoint_name(jnp.sin(3.), 'z')\n+ return z * ((x1 * x2) * y) * np.array([3.])\n+\n+ res = saved_residuals(f, (2., 3.), y=4.)\n+ self.assertLen(res, 6)\n+ self.assertEqual(res[0][0].shape, (1,))\n+ self.assertEqual(res[0][1], \"from a constant\")\n+ self.assertEqual(res[1][0].shape, ())\n+ self.assertEqual(res[1][1], \"from the argument 'x'\")\n+ self.assertEqual(res[2][0].shape, ())\n+ self.assertEqual(res[2][1], \"from the argument 'x'\")\n+ self.assertEqual(res[3][0].shape, ())\n+ self.assertEqual(res[3][1], \"from the argument 'y'\")\n+ self.assertEqual(res[4][0].shape, ())\n+ self.assertStartsWith(res[4][1], \"named z\")\n+ self.assertEqual(res[5][0].shape, ())\n+\nclass JaxprTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
checkpoint_name for checkpoint policies by name Also add the jax.ad_checkpoint.print_saved_residuals utility. All this is experimental, and undocumented for now... Co-authored-by: Qiao Zhang <zhangqiaorjc@google.com>
260,335
14.10.2021 07:09:06
25,200
725fe3abd4afb6a09b4d34ae3f3183325930c8e8
don't automatically use new checkpoint implementation There's a bug we're struggling to repro. To use the new checkpoint, just use ```python from jax.ad_checkpoint import checkpoint ``` rather than `from jax import checkpoint.
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -76,7 +76,7 @@ from ..interpreters import invertible_ad as iad\nfrom ..interpreters.invertible_ad import custom_ivjp\nfrom ..custom_derivatives import (closure_convert, custom_gradient, custom_jvp,\ncustom_vjp, linear_call)\n-from ..ad_checkpoint import checkpoint as new_checkpoint, checkpoint_policies\n+from ..ad_checkpoint import checkpoint_policies\nfrom .._src.config import (flags, config, bool_env, disable_jit as _disable_jit,\ndebug_nans as config_debug_nans,\n@@ -2896,10 +2896,6 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\n... return lambda x: f1(jax.checkpoint(f2)(x))\n...\n\"\"\"\n- # TODO(mattjj): we temporarily have parallel code paths\n- if policy is not None:\n- return new_checkpoint(fun, prevent_cse=prevent_cse, policy=policy)\n-\n@wraps(fun)\n@api_boundary\ndef fun_remat(*args, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -55,7 +55,7 @@ from jax import tree_util\nfrom jax import linear_util as lu\nimport jax._src.util\nfrom jax._src.ad_checkpoint import saved_residuals\n-from jax.ad_checkpoint import checkpoint_name\n+from jax.ad_checkpoint import checkpoint as new_checkpoint, checkpoint_name\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -3153,7 +3153,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_basic(self, remat):\n@remat\n@@ -3194,7 +3195,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_freevars(self, remat):\ndef f1(x):\n@@ -3239,7 +3241,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_jit(self, remat):\n@remat\n@@ -3266,7 +3269,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_vmap(self, remat):\n@remat\n@@ -3291,7 +3295,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_higher_order_autodiff(self, remat):\ndef f(x):\n@@ -3333,7 +3338,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_no_redundant_flops(self, remat):\n# see https://github.com/google/jax/pull/1749#issuecomment-558267584\n@@ -3361,7 +3367,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_binomial_checkpointing(self, remat):\ndef binom_checkpoint(funs):\n@@ -3409,7 +3416,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_jit2(self, remat):\n@api.jit\n@@ -3455,7 +3463,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_jit3(self, remat):\n# https://github.com/google/jax/issues/2180\n@@ -3518,7 +3527,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_remat_eval_counter(self, remat):\n# https://github.com/google/jax/issues/2737\n@@ -3578,7 +3588,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_escaped_tracer_remat(self, remat):\n# b/169779185\n@@ -3598,7 +3609,8 @@ class RematTest(jtu.JaxTestCase):\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n('', api.remat),\n- ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n])\ndef test_no_cse_widget_on_primals(self, remat):\n@remat\n@@ -3857,25 +3869,24 @@ class RematTest(jtu.JaxTestCase):\n# The old implementation of remat worked by data dependence, and so\n# (potentially large) constants would not be rematerialized and could be\n# wastefully instantiated. This test checks that the newer remat\n- # implementation avoids that. We engage the newer implementation by passing\n- # an explicit policy. See https://github.com/google/jax/pull/8191.\n+ # implementation avoids that. See https://github.com/google/jax/pull/8191.\n# no residuals from constants created inside jnp.einsum\n- @partial(jax.checkpoint, policy=lambda *_, **__: False)\n+ @partial(new_checkpoint, policy=lambda *_, **__: False)\ndef f(x):\nreturn jnp.einsum('ii->i', x)\nres_avals = saved_residuals(f, jnp.ones((2, 2)))\nself.assertLen(res_avals, 0)\n# no residuals from jnp.zeros\n- @partial(jax.checkpoint, policy=lambda *_, **__: False)\n+ @partial(new_checkpoint, policy=lambda *_, **__: False)\ndef f(x):\nreturn jnp.zeros_like(x) * x\nres_avals = saved_residuals(f, jnp.ones((2, 2)))\nself.assertLen(res_avals, 0)\n# no residuals from jnp.zeros, but input must be saved\n- @partial(jax.checkpoint, policy=lambda *_, **__: False)\n+ @partial(new_checkpoint, policy=lambda *_, **__: False)\ndef f(x):\nreturn jnp.zeros_like(x) * jnp.sin(x)\nres_avals = saved_residuals(f, jnp.ones((2, 2)))\n@@ -3890,19 +3901,19 @@ class RematTest(jtu.JaxTestCase):\nreturn (((x * y) * z) * w) * u\npolicy = jax.checkpoint_policies.save_any_names_but_these('y', 'z', 'w')\n- res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ res = saved_residuals(new_checkpoint(f, policy=policy), 1.)\nself.assertLen(res, 0) # can't save anything\npolicy = jax.checkpoint_policies.save_any_names_but_these('z', 'w')\n- res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ res = saved_residuals(new_checkpoint(f, policy=policy), 1.)\nself.assertLen(res, 1) # can save only y\npolicy = jax.checkpoint_policies.save_any_names_but_these('w')\n- res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ res = saved_residuals(new_checkpoint(f, policy=policy), 1.)\nself.assertLen(res, 2) # can save y and z\npolicy = jax.checkpoint_policies.save_any_names_but_these()\n- res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ res = saved_residuals(new_checkpoint(f, policy=policy), 1.)\nself.assertLen(res, 3) # can save y, z, and w\ndef test_name_allowlist(self):\n@@ -3914,19 +3925,19 @@ class RematTest(jtu.JaxTestCase):\nreturn (((x * y) * z) * w) * u\npolicy = jax.checkpoint_policies.save_only_these_names('y', 'z', 'w')\n- res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ res = saved_residuals(new_checkpoint(f, policy=policy), 1.)\nself.assertLen(res, 3) # can save y, z, and w\npolicy = jax.checkpoint_policies.save_only_these_names('z', 'w')\n- res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ res = saved_residuals(new_checkpoint(f, policy=policy), 1.)\nself.assertLen(res, 2) # can save z and w\npolicy = jax.checkpoint_policies.save_only_these_names('w')\n- res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ res = saved_residuals(new_checkpoint(f, policy=policy), 1.)\nself.assertLen(res, 1) # can save w\npolicy = jax.checkpoint_policies.save_only_these_names()\n- res = saved_residuals(jax.checkpoint(f, policy=policy), 1.)\n+ res = saved_residuals(new_checkpoint(f, policy=policy), 1.)\nself.assertLen(res, 0) # can't save anything!\ndef test_saved_residuals_utility(self):\n" } ]
Python
Apache License 2.0
google/jax
don't automatically use new checkpoint implementation There's a bug we're struggling to repro. To use the new checkpoint, just use ```python from jax.ad_checkpoint import checkpoint ``` rather than `from jax import checkpoint.
260,410
14.10.2021 09:40:41
25,200
de777c8d37fed5504e5b161a40f4fbdc3bb31026
Set dtypes of constant coefficients appropriately based on the state dtypes. This avoids unexpected casting of the output states.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ode.py", "new_path": "jax/experimental/ode.py", "diff": "@@ -58,7 +58,7 @@ def interp_fit_dopri(y0, y1, k, dt):\ndps_c_mid = jnp.array([\n6025192743 / 30085553152 / 2, 0, 51252292925 / 65400821598 / 2,\n-2691868925 / 45128329728 / 2, 187940372067 / 1594534317056 / 2,\n- -1776094331 / 19743644256 / 2, 11237099 / 235043384 / 2])\n+ -1776094331 / 19743644256 / 2, 11237099 / 235043384 / 2], dtype=y0.dtype)\ny_mid = y0 + dt * jnp.dot(dps_c_mid, k)\nreturn jnp.asarray(fit_4th_order_polynomial(y0, y1, y_mid, k[0], k[-1], dt))\n@@ -92,19 +92,21 @@ def initial_step_size(fun, t0, y0, order, rtol, atol, f0):\ndef runge_kutta_step(func, y0, f0, t0, dt):\n# Dopri5 Butcher tableaux\n- alpha = jnp.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0])\n- beta = jnp.array([\n- [1 / 5, 0, 0, 0, 0, 0, 0],\n- [3 / 40, 9 / 40, 0, 0, 0, 0, 0],\n+ alpha = jnp.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0], dtype=f0.dtype)\n+ beta = jnp.array(\n+ [[1 / 5, 0, 0, 0, 0, 0, 0], [3 / 40, 9 / 40, 0, 0, 0, 0, 0],\n[44 / 45, -56 / 15, 32 / 9, 0, 0, 0, 0],\n[19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729, 0, 0, 0],\n[9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656, 0, 0],\n- [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0]\n- ])\n- c_sol = jnp.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0])\n- c_error = jnp.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085,\n- 125 / 192 - 451 / 720, -2187 / 6784 - -12231 / 42400,\n- 11 / 84 - 649 / 6300, -1. / 60.])\n+ [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0]],\n+ dtype=f0.dtype)\n+ c_sol = jnp.array(\n+ [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0],\n+ dtype=f0.dtype)\n+ c_error = jnp.array([\n+ 35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085, 125 / 192 -\n+ 451 / 720, -2187 / 6784 - -12231 / 42400, 11 / 84 - 649 / 6300, -1. / 60.\n+ ], dtype=f0.dtype)\ndef body_fun(i, k):\nti = t0 + dt * alpha[i-1]\n" } ]
Python
Apache License 2.0
google/jax
Set dtypes of constant coefficients appropriately based on the state dtypes. This avoids unexpected casting of the output states. PiperOrigin-RevId: 403116057
260,424
14.10.2021 17:37:50
-3,600
f5d8d4bc4e26c991b3302e646f3e34d6d1c1f247
Replace loop with map in RBG batching_rule.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -1979,6 +1979,19 @@ def _memcpy(axis, num, src, dst, offset):\nmasking.masking_rules[lax.concatenate_p] = _concat_masking_rule # type: ignore\n+def _rng_bit_generator_batching_rule(batched_args, batch_dims, *, shape, dtype, algorithm):\n+ \"\"\"Calls RBG in a loop and stacks the results.\"\"\"\n+ key, = batched_args\n+ bd, = batch_dims\n+ if bd is batching.not_mapped:\n+ return lax.rng_bit_generator_p.bind(key, shape=shape, dtype=dtype,\n+ algorithm=algorithm), (None, None)\n+ key = batching.moveaxis(key, bd, 0)\n+ map_body = lambda k: lax.rng_bit_generator_p.bind(k, shape=shape, dtype=dtype, algorithm=algorithm)\n+ stacked_keys, stacked_bits = map(map_body, key)\n+ return (stacked_keys, stacked_bits), (0, 0)\n+\n+batching.primitive_batchers[lax.rng_bit_generator_p] = _rng_bit_generator_batching_rule\ndef _check_tree_and_avals(what, tree1, avals1, tree2, avals2):\n\"\"\"Raises TypeError if (tree1, avals1) does not match (tree2, avals2).\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -6780,7 +6780,7 @@ def _rng_bit_generator_translation_rule(backend_is_gpu, c, key, *, shape, dtype,\n# need to convert u32[4] -> u64[2] here in the translation rule. However, we\n# also polymorphically allow a u64[2] for backward compatibility.\nassert ((key_shape == (4,) and key_dtype == dtypes.dtype('uint32')) or\n- (key_shape == (2,) and key_dtype == dtypes.dtype('uint64')))\n+ (key_shape == (2,) and key_dtype == dtypes.dtype('uint64'))), (key_shape, key_dtype)\nxla_shape = xc.Shape.array_shape(np.dtype(dtype), shape)\nif key_dtype == dtypes.dtype('uint32'):\n# TODO(mattjj): the BitcastConvertType segfaults on GPU\n@@ -6827,25 +6827,6 @@ def _convert_2xU64_to_4xU32_without_bitcast(c, key):\ndef _rng_bit_generator_named_shape_rule(key, *, shape, dtype, algorithm):\nreturn [key.named_shape, key.named_shape]\n-def _rng_bit_generator_batching_rule(batched_args, batch_dims, *, shape, dtype, algorithm):\n- \"\"\"Calls RBG in a loop and stacks the results.\"\"\"\n- key, = batched_args\n- bd, = batch_dims\n- if bd is batching.not_mapped:\n- return rng_bit_generator_p.bind(key, shape=shape, dtype=dtype,\n- algorithm=algorithm), (None, None)\n- key = batching.moveaxis(key, bd, 0)\n- out_keys = []\n- out_bits = []\n- for k in key:\n- updated_key, bits = rng_bit_generator_p.bind(k, shape=shape, dtype=dtype,\n- algorithm=algorithm)\n- out_keys.append(reshape(updated_key, (1,)+updated_key.shape))\n- out_bits.append(reshape(bits, (1,)+bits.shape))\n- stacked_keys = concatenate(out_keys, 0)\n- stacked_bits = concatenate(out_bits, 0)\n- return (stacked_keys, stacked_bits), (0, 0)\n-\nrng_bit_generator_p = Primitive(\"rng_bit_generator\")\nrng_bit_generator_p.multiple_results = True\nrng_bit_generator_p.def_impl(\n@@ -6855,7 +6836,6 @@ rng_bit_generator_p.def_abstract_eval(\n_rng_bit_generator_shape_rule, _rng_bit_generator_dtype_rule,\n_rng_bit_generator_weak_type_rule,\n_rng_bit_generator_named_shape_rule))\n-batching.primitive_batchers[rng_bit_generator_p] = _rng_bit_generator_batching_rule\nxla.translations[rng_bit_generator_p] = \\\npartial(_rng_bit_generator_translation_rule, False)\nxla.backend_specific_translations['gpu'][rng_bit_generator_p] = \\\n" } ]
Python
Apache License 2.0
google/jax
Replace loop with map in RBG batching_rule.
260,335
14.10.2021 11:32:09
25,200
297f79c1de3d5ada6952fe177a8939c16a040b6d
make saved_residuals utility work w/ literals
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_checkpoint.py", "new_path": "jax/_src/ad_checkpoint.py", "diff": "@@ -231,31 +231,35 @@ def saved_residuals(f, *args, **kwargs) -> List[Tuple[core.AbstractValue, str]]:\nreturn f(*args, **kwargs)\njaxpr = jax.make_jaxpr(lambda *args: jax.linearize(f_, *args)[1])(*args).jaxpr\n- res_vars = set(jaxpr.outvars)\n+ res_lits = [x for x in jaxpr.outvars if isinstance(x, core.Literal)]\n+ res_vars = {x for x in jaxpr.outvars if not isinstance(x, core.Literal)}\n+\nresults = []\n+ for x in res_lits:\n+ results.append((x.aval, 'from a literal'))\n+\nfor v in jaxpr.constvars:\nif v in res_vars:\n- results.append((v, 'from a constant'))\n+ results.append((v.aval, 'from a constant'))\nassert len(jaxpr.invars) == len(args)\nfor i, v in enumerate(jaxpr.invars):\nif v in res_vars:\nsrc = f'from {pe.arg_info_pytree(f, in_tree, True, [i])}'\n- results.append((v, src))\n+ results.append((v.aval, src))\nfor eqn in jaxpr.eqns:\nsrc = source_info_util.summarize(eqn.source_info)\nfor v in eqn.outvars:\nif v in res_vars:\nif eqn.primitive is name_p:\n- results.append((v, f'named {eqn.params[\"name\"]} from {src}'))\n+ results.append((v.aval, f'named {eqn.params[\"name\"]} from {src}'))\nelse:\n- results.append((v, f'from {src}'))\n+ results.append((v.aval, f'from {src}'))\n- res_vars_accounted_for = {v for v, _ in results}\n- assert res_vars == res_vars_accounted_for, (res_vars, res_vars_accounted_for)\n- return [(v.aval, src) for v, src in results]\n+ assert len(results) == len(jaxpr.outvars)\n+ return results\ndef print_saved_residuals(f, *args, **kwargs):\nfor aval, src in saved_residuals(f, *args, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3960,6 +3960,11 @@ class RematTest(jtu.JaxTestCase):\nself.assertStartsWith(res[4][1], \"named z\")\nself.assertEqual(res[5][0].shape, ())\n+ def test_saved_residuals_utility_literals(self):\n+ res = saved_residuals(lambda x: x * 2., 3.)\n+ self.assertLen(res, 1)\n+ self.assertEqual(res[0][0].shape, ())\n+\nclass JaxprTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
make saved_residuals utility work w/ literals
260,335
14.10.2021 13:09:24
25,200
584aa13360887f5ea739027a880525f1e3ae9fba
document `axis_name` in the `vmap` docstring fixes
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -1329,6 +1329,8 @@ def vmap(fun: F, in_axes=0, out_axes=0, axis_name=None) -> F:\n(axes) of the array returned by the :func:`vmap`-ed function, which is one\nmore than the number of dimensions (axes) of the corresponding array\nreturned by ``fun``.\n+ axis_name: Optional, a hashable Python object used to identify the mapped\n+ axis so that parallel collectives can be applied.\nReturns:\nBatched/vectorized version of ``fun`` with arguments that correspond to\n@@ -1403,6 +1405,16 @@ def vmap(fun: F, in_axes=0, out_axes=0, axis_name=None) -> F:\nIf the ``out_axes`` is specified for a mapped result, the result is transposed\naccordingly.\n+\n+ Finally, here's an example using ``axis_name`` together with collectives:\n+\n+ >>> xs = jnp.arange(3. * 4.).reshape(3, 4)\n+ >>> print(vmap(lambda x: lax.psum(x, 'i'), axis_name='i')(xs))\n+ [[12. 15. 18. 21.]\n+ [12. 15. 18. 21.]\n+ [12. 15. 18. 21.]]\n+\n+ See the :py:func:`jax.pmap` docstring for more examples involving collectives.\n\"\"\"\n_check_callable(fun)\ndocstr = (\"Vectorized version of {fun}. Takes similar arguments as {fun} \"\n" } ]
Python
Apache License 2.0
google/jax
document `axis_name` in the `vmap` docstring fixes #8220
260,335
14.10.2021 20:41:29
25,200
8bfa5eec8cbcef84e41006a03f67d71760d738ab
fix dce logic
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1020,13 +1020,18 @@ def dce_jaxpr(jaxpr: Jaxpr, used_outputs: List[bool]\nmap(write, jaxpr.outvars, used_outputs)\nfor eqn in jaxpr.eqns[::-1]:\nused_outs = map(read, eqn.outvars)\n+ # If any outputs are used, then we need to keep a version of the eqn and\n+ # potentially mark some inputs as used. Otherwise mark all inputs as unused.\n+ if any(used_outs):\n+ # If there's a rule for modifying the eqn and computing used inputs, apply\n+ # it. Otherwise, keep the eqn unmodified and mark all inputs as used.\nrule = dce_rules.get(eqn.primitive)\nif rule:\nused_ins, new_eqn = rule(used_outs, eqn)\n- if any(used_ins): new_eqns.append(new_eqn)\n- elif any(used_outs):\n- new_eqns.append(eqn)\n+ else:\nused_ins = [True] * len(eqn.invars)\n+ new_eqn = eqn\n+ new_eqns.append(new_eqn)\nelse:\nused_ins = [False] * len(eqn.invars)\nmap(write, eqn.invars, used_ins)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3997,6 +3997,13 @@ class RematTest(jtu.JaxTestCase):\n_ = api.grad(f)(3.) # doesn't crash\n+ def test_dce_keeps_eqns_with_used_outputs_but_no_used_inputs(self):\n+ @new_checkpoint\n+ def f(x):\n+ c = jax.jit(lambda: 3.)()\n+ return c * x\n+\n+ _ = jax.grad(f)(3.) # doesn't crash\nclass JaxprTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
fix dce logic
260,287
15.10.2021 14:37:38
0
49d9affce0161fb49bd99b6aa3a51ef2991ed6a5
Enable batcher and batched collective rules for tiled all gathers Fixes
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -1089,12 +1089,10 @@ def _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_\naxis=concat_axis),)\ndef _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):\n- if tiled:\n- raise NotImplementedError(\"Please open a feature request!\")\n(x,), (d,) = vals_in, dims_in\nif d <= all_gather_dimension:\nall_gather_dimension += 1\n- else:\n+ elif not tiled: # Tiled all-gather doesn't modify the set of dimensions\nd += 1\nresult = all_gather_p.bind(\nx,\n@@ -1107,8 +1105,6 @@ def _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, ax\ndef _all_gather_batched_collective(frame_size, frame_name, _, vals_in, dims_in, all_gather_dimension, axis_name,\naxis_index_groups, axis_size, tiled):\n- if tiled:\n- raise NotImplementedError(\"Please open a feature request!\")\nassert axis_index_groups is None, \"axis_index_groups not supported in vmap\"\nassert axis_size == frame_size, \"axis size doesn't match\"\nif not isinstance(axis_name, tuple):\n@@ -1121,8 +1117,12 @@ def _all_gather_batched_collective(frame_size, frame_name, _, vals_in, dims_in,\nout_shape = list(np.shape(x))\nout_shape.insert(all_gather_dimension, axis_size)\nbroadcast_dims = [i for i in range(len(out_shape)) if i != all_gather_dimension]\n- return lax.broadcast_in_dim(x, out_shape, broadcast_dims), batching.not_mapped\n- return _moveaxis(d, all_gather_dimension, x), batching.not_mapped\n+ y = lax.broadcast_in_dim(x, out_shape, broadcast_dims)\n+ else:\n+ y = _moveaxis(d, all_gather_dimension, x)\n+ if tiled:\n+ y = _foldaxis(all_gather_dimension, y)\n+ return y, batching.not_mapped\nall_gather_p = core.AxisPrimitive('all_gather')\nall_gather_p.def_abstract_eval(_all_gather_abstract_eval)\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -1193,6 +1193,22 @@ class BatchingTest(jtu.JaxTestCase):\nres = vmap(vmap(f, axis_name='j'), axis_name='i', out_axes=None)(x)\nself.assertAllClose(res, x.T)\n+ def testAllGatherTiled(self):\n+ def f(x):\n+ return lax.all_gather(x, axis_name='i', tiled=True)\n+\n+ x = jnp.arange(60).reshape((4, 3, 5))\n+ res = vmap(f, axis_name='i', in_axes=(1,), out_axes=None)(x)\n+ self.assertAllClose(res, x.transpose((1, 0, 2)).reshape(-1, 5))\n+\n+ def testBatchedAllGatherTiled(self):\n+ def f(x):\n+ return lax.all_gather(x, axis_name='i', tiled=True)\n+\n+ x = jnp.arange(60).reshape((4, 3, 5))\n+ res = vmap(vmap(f, in_axes=1, out_axes=1), axis_name='i', in_axes=1, out_axes=None)(x)\n+ self.assertAllClose(res, x.transpose((1, 0, 2)).reshape(-1, 5))\n+\ndef testAllGatherVjp(self):\ndef f(x):\nreturn lax.all_gather(x, axis_name='i')\n" } ]
Python
Apache License 2.0
google/jax
Enable batcher and batched collective rules for tiled all gathers Fixes #8221.
260,631
19.10.2021 08:09:16
25,200
e96f3632425e9b6f1076b8ff4083df73d8567682
[XLA:TPU] Adding approximate nearest neighbor search on TPU feature to JAX. The JAX primitive would call the XLA python interface for ApproxTopK on TPU, and fallbacked to sort-and-slice XLA implementation on other platforms. Auto differntiation have two possible implementations and will be submitted in seprated CLs.
[ { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/ann.py", "diff": "+# Copyright 2021 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+from functools import partial\n+from typing import (Any, Tuple)\n+\n+import numpy as np\n+from jax import lax, core\n+from jax._src.lib import xla_bridge as xb\n+from jax._src.lib import xla_client as xc\n+from jax._src import dtypes\n+\n+from jax.interpreters import xla, batching\n+\n+Array = Any\n+r\"\"\"ANN (Approximate Nearest Neighbor) is an **experimental** module for fast top-k with a configurable recall rate on TPU.\n+\n+TPUs are highly efficient on matrix multiplication, which scales up by TPU\n+generation. Nevertheless, TPUs are surprisingly inefficient in the other\n+generalized instructions used in standard algorithm designs.\n+\n+We can illustrate the inefficiency of writing general algorithms on TPU by\n+comparing general instructions and matrix multiplication instruction throughput.\n+We could only use no more than ten vector instructions per matrix\n+multiplication; otherwise, we would see a significant performance regression.\n+This constraint prevents us from almost all standard exact top-k algorithms,\n+including parallel binary-heap, median-of-medians, and bitonic sort.\n+\n+Our approach to this problem is to reshape the inputs into equally sized windows,\n+and return the top-1s in each window containing the true top-k. Suppose we have\n+the actual top-k elements randomly spreaded in the windows, and we select the\n+top-1 from each window. The collision rate of the top-k affects the accuracy,\n+which we can model by the number of people with shared birthdays in the Birthday\n+problem.\n+\n+The recall of this approximation depends on the output size M and desired\n+Kelements in top-k. The recall is approximately :math:`\\mathrm{EXP}((1-K)/M)`.\n+A quick estimate is the output would roughly be :math:`M=10*K` for 90% target\n+recall, and :math:`M=100*K` for 99% target recall. The smaller the output, the\n+smaller memory bandwidth it consumes.\n+\n+Example usage:\n+\n+ from jax.experimental import ann\n+ # Maximum inner product search\n+ scores, docids = ann.approx_max_k(lax.dot(qy, db), k=10, recall_target=0.95)\n+\n+The current JAX implementation sorts and slice the approximate results M into\n+the final top-k on TPU. We'll also provide a on-host final top-k aggregation\n+for JAX in the future.\n+\n+.. todo::\n+\n+ * On host top-k aggregation\n+ * Accurate but slow differentiation\n+ * Inaccurate but fast differentiation\n+\"\"\"\n+\n+\n+def approx_max_k(operand: Array,\n+ k: int,\n+ reduction_dimension: int = -1,\n+ recall_target: float = 0.95) -> Tuple[Array, Array]:\n+ \"\"\"Returns max ``k`` values and their indices of the ``operand``.\n+\n+ Args:\n+ operand : Array to search for max-k.\n+ k : Specifies the number of max-k.\n+ reduction_dimension: Integer dimension along which to search. Default: -1.\n+ recall_target: Recall target for the approximation.\n+\n+ Returns:\n+ Tuple[Array, Array] : Max k values and their indices of the inputs.\n+ \"\"\"\n+ return approx_top_k_p.bind(\n+ operand,\n+ k=k,\n+ reduction_dimension=reduction_dimension,\n+ recall_target=recall_target,\n+ is_max_k=True)\n+\n+\n+# Build comparator like lax.sort\n+def approx_min_k(operand: Array,\n+ k: int,\n+ reduction_dimension: int = -1,\n+ recall_target: float = 0.95) -> Tuple[Array, Array]:\n+ \"\"\"Returns min ``k`` values and their indices of the ``operand``.\n+\n+ Args:\n+ operand : Array to search for min-k.\n+ k : Specifies the number of min-k.\n+ reduction_dimension: Integer dimension along which to search. Default: -1.\n+ recall_target: Recall target for the approximation.\n+\n+ Returns:\n+ Tuple[Array, Array] : Least k values and their indices of the inputs.\n+ \"\"\"\n+ return approx_top_k_p.bind(\n+ operand,\n+ k=k,\n+ reduction_dimension=reduction_dimension,\n+ recall_target=recall_target,\n+ is_max_k=False)\n+\n+\n+def _approx_top_k_abstract_eval(operand, *, k, reduction_dimension,\n+ recall_target, is_max_k):\n+ if k <= 0:\n+ raise ValueError('k must be positive, got {}'.format(k))\n+ if len(operand.shape) == 0:\n+ raise TypeError('approx_top_k operand must have >= 1 dimension, got {}'.format(\n+ operand.shape))\n+ dims = list(operand.shape)\n+ if dims[reduction_dimension] < k:\n+ raise ValueError(\n+ 'k must be smaller than the size of reduction_dim {}, got {}'.format(\n+ dims[reduction_dimension], k))\n+ dims[reduction_dimension] = k\n+ return (operand.update(\n+ shape=dims, dtype=operand.dtype, weak_type=operand.weak_type),\n+ operand.update(shape=dims, dtype=np.dtype(np.int32)))\n+\n+\n+def _comparator_builder(operand, op_type, is_max_k):\n+ c = xc.XlaBuilder(\n+ 'top_k_{}_comparator'.format('gt' if is_max_k else 'lt'))\n+ p0 = xb.parameter(c, 0, xc.Shape.scalar_shape(op_type))\n+ p1 = xb.parameter(c, 1, xc.Shape.scalar_shape(op_type))\n+ xb.parameter(c, 2, xc.Shape.scalar_shape(np.dtype(np.int32)))\n+ xb.parameter(c, 3, xc.Shape.scalar_shape(np.dtype(np.int32)))\n+ if is_max_k:\n+ cmp_result = xc.ops.Gt(p0, p1)\n+ else:\n+ cmp_result = xc.ops.Lt(p0, p1)\n+ return c.build(cmp_result)\n+\n+\n+def _approx_top_k_tpu_translation(c, operand, k, reduction_dimension,\n+ recall_target, is_max_k):\n+ op_shape = c.get_shape(operand)\n+ if not op_shape.is_array():\n+ raise ValueError('operand must be an array, but was {}'.format(op_shape))\n+ op_dims = op_shape.dimensions()\n+ op_type = op_shape.element_type()\n+ if reduction_dimension < 0:\n+ reduction_dimension = len(op_dims) + reduction_dimension\n+ comparator = _comparator_builder(operand, op_type, is_max_k)\n+ if is_max_k:\n+ if dtypes.issubdtype(op_type, np.floating):\n+ init_literal = np.array(np.NINF, dtype=op_type)\n+ else:\n+ init_literal = np.iinfo(op_type).min()\n+ else:\n+ if dtypes.issubdtype(op_type, np.floating):\n+ init_literal = np.array(np.Inf, dtype=op_type)\n+ else:\n+ init_literal = np.iinfo(op_type).max()\n+ iota = xc.ops.Iota(c, xc.Shape.array_shape(np.dtype(np.int32), op_dims),\n+ reduction_dimension)\n+ init_val = xc.ops.Constant(c, init_literal)\n+ init_arg = xc.ops.Constant(c, np.int32(-1))\n+ return xc.ops.ApproxTopK(c, [operand, iota], [init_val, init_arg], k,\n+ reduction_dimension, comparator, recall_target, True)\n+\n+\n+def _approx_top_k_fallback_translation(c, operand, k, reduction_dimension,\n+ recall_target, is_max_k):\n+ op_shape = c.get_shape(operand)\n+ if not op_shape.is_array():\n+ raise ValueError('operand must be an array, but was {}'.format(op_shape))\n+ op_dims = op_shape.dimensions()\n+ op_type = op_shape.element_type()\n+ if reduction_dimension < 0:\n+ reduction_dimension = len(op_dims) + reduction_dimension\n+ comparator = _comparator_builder(operand, op_type, is_max_k)\n+ iota = xc.ops.Iota(c, xc.Shape.array_shape(np.dtype(np.int32), op_dims),\n+ reduction_dimension)\n+ val_arg = xc.ops.Sort(c, [operand, iota], comparator, reduction_dimension)\n+ vals = xc.ops.GetTupleElement(val_arg, 0)\n+ args = xc.ops.GetTupleElement(val_arg, 1)\n+ sliced_vals = xc.ops.SliceInDim(vals, 0, k, 1, reduction_dimension)\n+ sliced_args = xc.ops.SliceInDim(args, 0, k, 1, reduction_dimension)\n+ return xc.ops.Tuple(c, [sliced_vals, sliced_args])\n+\n+\n+def _approx_top_k_batch_rule(batched_args, batch_dims, *, k,\n+ reduction_dimension, recall_target, is_max_k):\n+ prototype_arg, new_bdim = next(\n+ (a, b) for a, b in zip(batched_args, batch_dims) if b is not None)\n+ new_args = []\n+ for arg, bdim in zip(batched_args, batch_dims):\n+ if bdim is None:\n+ dims = np.delete(np.arange(prototype_arg.ndim), new_bdim)\n+ new_args.append(lax.broadcast_in_dim(arg, prototype_arg.shape, dims))\n+ else:\n+ new_args.append(batching.moveaxis(arg, bdim, new_bdim))\n+ new_reduction_dim = reduction_dimension + (new_bdim <= reduction_dimension)\n+ bdims = (new_bdim,) * len(new_args)\n+ return (approx_top_k_p.bind(\n+ *new_args,\n+ k=k,\n+ reduction_dimension=new_reduction_dim,\n+ recall_target=recall_target,\n+ is_max_k=False), bdims)\n+\n+\n+approx_top_k_p = core.Primitive('approx_top_k')\n+approx_top_k_p.multiple_results = True\n+approx_top_k_p.def_impl(partial(xla.apply_primitive, approx_top_k_p))\n+approx_top_k_p.def_abstract_eval(_approx_top_k_abstract_eval)\n+xla.backend_specific_translations['tpu'][\n+ approx_top_k_p] = _approx_top_k_tpu_translation\n+xla.backend_specific_translations['cpu'][\n+ approx_top_k_p] = _approx_top_k_fallback_translation\n+xla.backend_specific_translations['gpu'][\n+ approx_top_k_p] = _approx_top_k_fallback_translation\n+batching.primitive_batchers[approx_top_k_p] = _approx_top_k_batch_rule\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/ann_test.py", "diff": "+# Copyright 2021 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+from absl.testing import absltest\n+from absl.testing import parameterized\n+\n+from jax import lax\n+from jax.experimental import ann\n+from jax._src import test_util as jtu\n+\n+from jax.config import config\n+\n+config.parse_flags_with_absl()\n+\n+\n+class AnnTest(jtu.JaxTestCase):\n+\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_qy={}_db={}_k={}_recall={}\".format(\n+ jtu.format_shape_dtype_string(qy_shape, dtype),\n+ jtu.format_shape_dtype_string(db_shape, dtype), k, recall),\n+ \"qy_shape\": qy_shape, \"db_shape\": db_shape, \"dtype\": dtype,\n+ \"k\": k, \"recall\": recall }\n+ for qy_shape in [(200, 128), (128, 128)]\n+ for db_shape in [(128, 500), (128, 3000)]\n+ for dtype in jtu.dtypes.all_floating\n+ for k in [10, 50] for recall in [0.9, 0.95]))\n+ def test_approx_max_k(self, qy_shape, db_shape, dtype, k, recall):\n+ rng = jtu.rand_default(self.rng())\n+ qy = rng(qy_shape, dtype)\n+ db = rng(db_shape, dtype)\n+ scores = lax.dot(qy, db)\n+ _, gt_args = lax.top_k(scores, k)\n+ _, ann_args = ann.approx_max_k(scores, k, recall_target=recall)\n+ gt_args_sets = [set(x) for x in gt_args]\n+ hits = sum(\n+ len(list(x\n+ for x in ann_args_per_q\n+ if x in gt_args_sets[q]))\n+ for q, ann_args_per_q in enumerate(ann_args))\n+ self.assertGreater(hits / (qy_shape[0] * k), recall)\n+\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_qy={}_db={}_k={}_recall={}\".format(\n+ jtu.format_shape_dtype_string(qy_shape, dtype),\n+ jtu.format_shape_dtype_string(db_shape, dtype), k, recall),\n+ \"qy_shape\": qy_shape, \"db_shape\": db_shape, \"dtype\": dtype,\n+ \"k\": k, \"recall\": recall }\n+ for qy_shape in [(200, 128), (128, 128)]\n+ for db_shape in [(128, 500), (128, 3000)]\n+ for dtype in jtu.dtypes.all_floating\n+ for k in [10, 50] for recall in [0.9, 0.95]))\n+ def test_approx_min_k(self, qy_shape, db_shape, dtype, k, recall):\n+ rng = jtu.rand_default(self.rng())\n+ qy = rng(qy_shape, dtype)\n+ db = rng(db_shape, dtype)\n+ scores = lax.dot(qy, db)\n+ _, gt_args = lax.top_k(-scores, k)\n+ _, ann_args = ann.approx_min_k(scores, k, recall_target=recall)\n+ gt_args_sets = [set(x) for x in gt_args]\n+ hits = sum(\n+ len(list(x\n+ for x in ann_args_per_q\n+ if x in gt_args_sets[q]))\n+ for q, ann_args_per_q in enumerate(ann_args))\n+ self.assertGreater(hits / (qy_shape[0] * k), recall)\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[XLA:TPU] Adding approximate nearest neighbor search on TPU feature to JAX. The JAX primitive would call the XLA python interface for ApproxTopK on TPU, and fallbacked to sort-and-slice XLA implementation on other platforms. Auto differntiation have two possible implementations and will be submitted in seprated CLs. PiperOrigin-RevId: 404263763
260,400
20.10.2021 03:21:55
25,200
142be1348b025837a5dbade80ae007422b80a5e5
Update jax2tf documentation with leading underscore when setting tf.Module() variables, e.g. `m._variables = ...`. Also added a test for this.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -151,7 +151,7 @@ prediction_tf = lambda inputs: jax2tf.convert(model_jax)(params_vars, inputs)\nmy_model = tf.Module()\n# Tell the model saver what are the variables.\n-my_model.variables = tf.nest.flatten(params_vars)\n+my_model._variables = tf.nest.flatten(params_vars)\nmy_model.f = tf.function(prediction_tf, jit_compile=True)\ntf.saved_model.save(my_model)\n```\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/savedmodel_test.py", "new_path": "jax/experimental/jax2tf/tests/savedmodel_test.py", "diff": "@@ -154,6 +154,27 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\n# g = tape.gradient(res, xv)\n#self.assertAllClose(g.numpy(), jax.grad(f_jax)(x))\n+ def test_save_without_embedding_params(self):\n+ def model_jax(params, inputs):\n+ return params[0] + params[1] * inputs\n+\n+ params = (np.array(1.0, dtype=jnp.float32),\n+ np.array(2.0, dtype=jnp.float32))\n+ params_vars = tf.nest.map_structure(tf.Variable, params)\n+\n+ prediction_tf = lambda x: jax2tf.convert(model_jax)(params_vars, x)\n+\n+ model = tf.Module()\n+ model._variables = tf.nest.flatten(params_vars)\n+ model.f = tf.function(prediction_tf, jit_compile=True)\n+\n+ x = np.array(0.7, dtype=jnp.float32)\n+ self.assertAllClose(model.f(x), model_jax(params, x))\n+ restored_model = tf_test_util.SaveAndLoadModel(model,\n+ save_gradients=False)\n+ self.assertAllClose(restored_model.f(x), model_jax(params, x))\n+\n+\ndef test_save_grad_integers(self):\n# https://github.com/google/jax/issues/7123\n# In the end this is a test that does not involve JAX at all\n" } ]
Python
Apache License 2.0
google/jax
Update jax2tf documentation with leading underscore when setting tf.Module() variables, e.g. `m._variables = ...`. Also added a test for this. PiperOrigin-RevId: 404483990
260,631
20.10.2021 12:07:16
25,200
06b595321f4d62fb20d8bbf0116636aef7e7c7bb
[XLA:TPU] Support jvp/vjp in approx_top_k Copies the jvp implementation lax.sort uses. Left some comments for future optimizations
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ann.py", "new_path": "jax/experimental/ann.py", "diff": "@@ -19,9 +19,9 @@ import numpy as np\nfrom jax import lax, core\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\n-from jax._src import dtypes\n+from jax._src import ad_util, dtypes\n-from jax.interpreters import xla, batching\n+from jax.interpreters import ad, xla, batching\nArray = Any\nr\"\"\"ANN (Approximate Nearest Neighbor) is an **experimental** module for fast top-k with a configurable recall rate on TPU.\n@@ -37,7 +37,8 @@ multiplication; otherwise, we would see a significant performance regression.\nThis constraint prevents us from almost all standard exact top-k algorithms,\nincluding parallel binary-heap, median-of-medians, and bitonic sort.\n-Our approach to this problem is to reshape the inputs into equally sized windows,\n+Our approach to this problem is to reshape the inputs into equally sized\n+windows,\nand return the top-1s in each window containing the true top-k. Suppose we have\nthe actual top-k elements randomly spreaded in the windows, and we select the\ntop-1 from each window. The collision rate of the top-k affects the accuracy,\n@@ -216,6 +217,40 @@ def _approx_top_k_batch_rule(batched_args, batch_dims, *, k,\nis_max_k=False), bdims)\n+# Slow jvp implementation using gather.\n+#\n+# TODO(fchern): Some optimization ideas\n+# 1. ApproxTopK is internally a variadic reduce, so we can simply call\n+# ApproxTopK(operand, tangent, iota) for jvp.\n+# 2. vjp cannot benefit from the algorithm above. We must run scatter to\n+# distribute the output cotangent to input cotangent. A reasonable way to do\n+# this is to run it on CPU.\n+def _approx_top_k_jvp(primals, tangents, *, k, reduction_dimension,\n+ recall_target, is_max_k):\n+ operand, = primals\n+ tangent, = tangents\n+ if is_max_k:\n+ val_out, arg_out = approx_max_k(operand, k, reduction_dimension,\n+ recall_target)\n+ else:\n+ val_out, arg_out = approx_min_k(operand, k, reduction_dimension,\n+ recall_target)\n+ if type(tangent) is ad_util.Zero:\n+ tangent_out = ad_util.Zero.from_value(val_out)\n+ else:\n+ arg_shape = arg_out.shape\n+ rank = len(arg_shape)\n+ if reduction_dimension < 0:\n+ reduction_dimension += rank\n+ iotas = [\n+ lax.broadcasted_iota(arg_out.dtype, arg_shape, i) for i in range(rank)\n+ ]\n+ idx = tuple(\n+ arg_out if i == reduction_dimension else iotas[i] for i in range(rank))\n+ tangent_out = tangent[idx]\n+ return (val_out, arg_out), (tangent_out, ad_util.Zero.from_value(arg_out))\n+\n+\napprox_top_k_p = core.Primitive('approx_top_k')\napprox_top_k_p.multiple_results = True\napprox_top_k_p.def_impl(partial(xla.apply_primitive, approx_top_k_p))\n@@ -227,3 +262,4 @@ xla.backend_specific_translations['cpu'][\nxla.backend_specific_translations['gpu'][\napprox_top_k_p] = _approx_top_k_fallback_translation\nbatching.primitive_batchers[approx_top_k_p] = _approx_top_k_batch_rule\n+ad.primitive_jvps[approx_top_k_p] = _approx_top_k_jvp\n" }, { "change_type": "MODIFY", "old_path": "tests/ann_test.py", "new_path": "tests/ann_test.py", "diff": "from absl.testing import absltest\nfrom absl.testing import parameterized\n+import numpy as np\n+\nfrom jax import lax\nfrom jax.experimental import ann\nfrom jax._src import test_util as jtu\n+from jax._src.util import prod\nfrom jax.config import config\n@@ -82,6 +85,30 @@ class AnnTest(jtu.JaxTestCase):\nfor q, ann_args_per_q in enumerate(ann_args))\nself.assertGreater(hits / (qy_shape[0] * k), recall)\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_shape={}_k={}_max_k={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), k, is_max_k),\n+ \"shape\":\n+ shape,\n+ \"dtype\":\n+ dtype,\n+ \"k\":\n+ k,\n+ \"is_max_k\":\n+ is_max_k\n+ } for dtype in [np.float32] for shape in [(4,), (5, 5), (2, 1, 4)]\n+ for k in [2, 3] for is_max_k in [True, False]))\n+ def test_autodiff(self, shape, dtype, k, is_max_k):\n+ vals = np.arange(prod(shape), dtype=dtype)\n+ vals = self.rng().permutation(vals).reshape(shape)\n+ if is_max_k:\n+ fn = lambda vs: ann.approx_max_k(vs, k=k)[0]\n+ else:\n+ fn = lambda vs: ann.approx_min_k(vs, k=k)[0]\n+ jtu.check_grads(fn, (vals,), 2, [\"fwd\", \"rev\"], eps=1e-2)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[XLA:TPU] Support jvp/vjp in approx_top_k Copies the jvp implementation lax.sort uses. Left some comments for future optimizations PiperOrigin-RevId: 404608289
260,631
20.10.2021 12:38:59
25,200
09c2c9a24b5ac34ec8be6cae60405e7368865377
[JAX] Export ann documentation.
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/jax.experimental.ann.rst", "diff": "+jax.experimental.ann module\n+===========================\n+\n+.. automodule:: jax.experimental.ann\n+\n+API\n+---\n+\n+.. autofunction:: approx_max_k\n+.. autofunction:: approx_min_k\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.experimental.rst", "new_path": "docs/jax.experimental.rst", "diff": "@@ -7,6 +7,7 @@ jax.experimental package\n.. toctree::\n:maxdepth: 1\n+ jax.experimental.ann\njax.experimental.host_callback\njax.experimental.loops\njax.experimental.maps\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Export ann documentation. PiperOrigin-RevId: 404615254
260,317
20.10.2021 13:01:26
25,200
6cfbb890e683efab9b8a2cc05f86ba404deb8a0a
Fix broken link to experimental/README.md
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -98,7 +98,7 @@ For a deeper dive into JAX:\nnotebooks](https://github.com/google/jax/tree/main/docs/notebooks).\nYou can also take a look at [the mini-libraries in\n-`jax.example_libraries`](https://github.com/google/jax/tree/main/jax/experimental/README.md),\n+`jax.example_libraries`](https://github.com/google/jax/tree/main/jax/example_libraries/README.md),\nlike [`stax` for building neural\nnetworks](https://github.com/google/jax/tree/main/jax/example_libraries/README.md#neural-net-building-with-stax)\nand [`optimizers` for first-order stochastic\n" } ]
Python
Apache License 2.0
google/jax
Fix broken link to experimental/README.md
260,362
20.10.2021 12:46:50
-3,600
67dc16fc24fbaae5a09fb1617e767433315b0ece
add fft normalisation
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/fft.py", "new_path": "jax/_src/numpy/fft.py", "diff": "@@ -23,6 +23,17 @@ from .util import _wraps\nfrom . import lax_numpy as jnp\n+def _fft_norm(s, func_name, norm):\n+ if norm is None or norm == \"backward\":\n+ return 1\n+ elif norm == \"ortho\":\n+ return jnp.sqrt(jnp.prod(s)) if func_name.startswith('i') else 1/jnp.sqrt(jnp.prod(s))\n+ elif norm == \"forward\":\n+ return jnp.prod(s) if func_name.startswith('i') else 1/jnp.prod(s)\n+ raise ValueError(f'Invalid norm value {norm}; should be \"backward\",'\n+ '\"ortho\" or \"forward\".')\n+\n+\ndef _fft_core(func_name, fft_type, a, s, axes, norm):\nfull_name = \"jax.numpy.fft.\" + func_name\n@@ -30,8 +41,7 @@ def _fft_core(func_name, fft_type, a, s, axes, norm):\ns = tuple(map(operator.index, s))\nif np.any(np.less(s, 0)):\nraise ValueError(\"Shape should be non-negative.\")\n- if norm is not None:\n- raise NotImplementedError(\"%s only supports norm=None, got %s\" % (full_name, norm))\n+\nif s is not None and axes is not None and len(s) != len(axes):\n# Same error as numpy.\nraise ValueError(\"Shape and axes have different lengths.\")\n@@ -76,8 +86,7 @@ def _fft_core(func_name, fft_type, a, s, axes, norm):\ns += [max(0, 2 * (a.shape[axes[-1]] - 1))]\nelse:\ns = [a.shape[axis] for axis in axes]\n-\n- transformed = lax.fft(a, fft_type, tuple(s))\n+ transformed = lax.fft(a, fft_type, tuple(s)) * _fft_norm(jnp.array(s), func_name, norm)\nif orig_axes is not None:\ntransformed = jnp.moveaxis(transformed, axes, orig_axes)\n" }, { "change_type": "MODIFY", "old_path": "tests/fft_test.py", "new_path": "tests/fft_test.py", "diff": "@@ -28,6 +28,12 @@ from jax._src import test_util as jtu\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n+numpy_version = tuple(map(int, np.__version__.split('.')[:3]))\n+if numpy_version < (1, 20):\n+ FFT_NORMS = [None, \"ortho\"]\n+else:\n+ FFT_NORMS = [None, \"ortho\", \"forward\", \"backward\"]\n+\nfloat_dtypes = jtu.dtypes.floating\ninexact_dtypes = jtu.dtypes.inexact\n@@ -64,8 +70,8 @@ def _irfft_with_zeroed_inputs(irfft_fun):\n# irfft isn't defined on the full domain of inputs, so in order to have a\n# well defined derivative on the whole domain of the function, we zero-out\n# the imaginary part of the first and possibly the last elements.\n- def wrapper(z, axes, s=None):\n- return irfft_fun(_zero_for_irfft(z, axes), axes=axes, s=s)\n+ def wrapper(z, axes, s=None, norm=None):\n+ return irfft_fun(_zero_for_irfft(z, axes), axes=axes, s=s, norm=norm)\nreturn wrapper\n@@ -96,23 +102,25 @@ class FftTest(jtu.JaxTestCase):\nfunc()\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_inverse={}_real={}_shape={}_axes={}_s={}\".format(\n- inverse, real, jtu.format_shape_dtype_string(shape, dtype), axes, s),\n- \"axes\": axes, \"shape\": shape, \"dtype\": dtype, \"inverse\": inverse, \"real\": real, \"s\": s}\n+ {\"testcase_name\": \"_inverse={}_real={}_shape={}_axes={}_s={}_norm={}\".format(\n+ inverse, real, jtu.format_shape_dtype_string(shape, dtype), axes, s, norm),\n+ \"axes\": axes, \"shape\": shape, \"dtype\": dtype, \"inverse\": inverse, \"real\": real, \"s\": s, \"norm\":norm}\nfor inverse in [False, True]\nfor real in [False, True]\nfor dtype in (real_dtypes if real and not inverse else all_dtypes)\nfor shape in [(10,), (10, 10), (9,), (2, 3, 4), (2, 3, 4, 5)]\nfor axes in _get_fftn_test_axes(shape)\n- for s in _get_fftn_test_s(shape, axes)))\n+ for s in _get_fftn_test_s(shape, axes)\n+ for norm in FFT_NORMS\n+ ))\n@jtu.skip_on_devices(\"rocm\")\n- def testFftn(self, inverse, real, shape, dtype, axes, s):\n+ def testFftn(self, inverse, real, shape, dtype, axes, s, norm):\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: (rng(shape, dtype),)\njnp_op = _get_fftn_func(jnp.fft, inverse, real)\nnp_op = _get_fftn_func(np.fft, inverse, real)\n- jnp_fn = lambda a: jnp_op(a, axes=axes)\n- np_fn = lambda a: np_op(a, axes=axes) if axes is None or axes else a\n+ jnp_fn = lambda a: jnp_op(a, axes=axes, norm=norm)\n+ np_fn = lambda a: np_op(a, axes=axes, norm=norm) if axes is None or axes else a\n# Numpy promotes to complex128 aggressively.\nself._CheckAgainstNumpy(np_fn, jnp_fn, args_maker, check_dtypes=False,\ntol=1e-4)\n@@ -239,16 +247,18 @@ class FftTest(jtu.JaxTestCase):\nValueError, lambda: func(rng([2, 3], dtype=np.float64), axis=[-3]))\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_inverse={}_real={}_shape={}_axes={}\".format(\n- inverse, real, jtu.format_shape_dtype_string(shape, dtype), axes),\n- \"axes\": axes, \"shape\": shape, \"dtype\": dtype, \"inverse\": inverse, \"real\": real}\n+ {\"testcase_name\": \"_inverse={}_real={}_shape={}_axes={}_norm={}\".format(\n+ inverse, real, jtu.format_shape_dtype_string(shape, dtype), axes, norm),\n+ \"axes\": axes, \"shape\": shape, \"dtype\": dtype, \"inverse\": inverse, \"real\": real, \"norm\":norm}\nfor inverse in [False, True]\nfor real in [False, True]\nfor dtype in (real_dtypes if real and not inverse else all_dtypes)\nfor shape in [(16, 8, 4, 8), (16, 8, 4, 8, 4)]\n- for axes in [(-2, -1), (0, 1), (1, 3), (-1, 2)]))\n+ for axes in [(-2, -1), (0, 1), (1, 3), (-1, 2)]\n+ for norm in FFT_NORMS\n+ ))\n@jtu.skip_on_devices(\"rocm\")\n- def testFft2(self, inverse, real, shape, dtype, axes):\n+ def testFft2(self, inverse, real, shape, dtype, axes, norm):\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: (rng(shape, dtype),)\nname = 'fft2'\n@@ -258,8 +268,10 @@ class FftTest(jtu.JaxTestCase):\nname = 'i' + name\njnp_op = getattr(jnp.fft, name)\nnp_op = getattr(np.fft, name)\n+ jnp_fn = lambda a: jnp_op(a, axes=axes, norm=norm)\n+ np_fn = lambda a: np_op(a, axes=axes, norm=norm) if axes is None or axes else a\n# Numpy promotes to complex128 aggressively.\n- self._CheckAgainstNumpy(np_op, jnp_op, args_maker, check_dtypes=False,\n+ self._CheckAgainstNumpy(np_fn, jnp_fn, args_maker, check_dtypes=False,\ntol=1e-4)\nself._CompileAndCheck(jnp_op, args_maker)\n" } ]
Python
Apache License 2.0
google/jax
add fft normalisation