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,510 | 15.09.2022 19:04:49 | 25,200 | 2d8b228706211a4b3db578a0c92d5377de8b75a7 | Add function to visualize `Sharding`s | [
{
"change_type": "MODIFY",
"old_path": "build/test-requirements.txt",
"new_path": "build/test-requirements.txt",
"diff": "@@ -5,3 +5,4 @@ pillow>=9.1.0\npytest-benchmark\npytest-xdist\nwheel\n+rich\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "@@ -17,7 +17,7 @@ import functools\nimport string\nimport sys\n-from typing import Callable, Any\n+from typing import Any, Dict, Callable, Sequence, Set, Tuple\nfrom jax import core\nfrom jax import tree_util\n@@ -26,6 +26,8 @@ from jax._src import ad_checkpoint\nfrom jax._src import custom_derivatives\nfrom jax._src import lib as jaxlib\nfrom jax._src import util\n+from jax.config import config\n+from jax.experimental.sharding import Sharding\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\n@@ -34,6 +36,18 @@ from jax._src.lax import control_flow as lcf\nfrom jax._src.lib import xla_client as xc\nimport jax.numpy as jnp\n+# pytype: disable=import-error\n+try:\n+ import rich\n+ import rich.align\n+ import rich.box\n+ import rich.padding\n+ import rich.table\n+ RICH_ENABLED = True\n+except:\n+ RICH_ENABLED = False\n+# pytype: enable=import-error\n+\nDebugEffect = enum.Enum('DebugEffect', ['PRINT', 'ORDERED_PRINT'])\ncore.ordered_effects.add(DebugEffect.ORDERED_PRINT)\n@@ -230,3 +244,93 @@ def debug_print(fmt: str, *args, ordered: bool = False, **kwargs) -> None:\ndebug_callback(functools.partial(_format_print_callback, fmt), *args,\n**kwargs, ordered=ordered)\n+\n+def _slice_to_chunk_idx(size: int, slc: slice) -> int:\n+ if slc.stop == slc.start == None:\n+ return 0\n+ slice_size = slc.stop - slc.start\n+ assert slc.start % slice_size == 0\n+ assert size % slice_size == 0\n+ return slc.start // slice_size\n+\n+def visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\n+ use_color: bool = False, scale: float = 1.):\n+ \"\"\"Visualizes a `Sharding`.\"\"\"\n+ if not RICH_ENABLED:\n+ raise ValueError(\"`visualize_sharding` requires `rich` to be installed.\")\n+ if use_color:\n+ # TODO(sharadmv): Implement color in the visualizer\n+ raise NotImplementedError\n+ if len(shape) > 2 or len(shape) < 1:\n+ raise ValueError(\n+ \"`visualize_sharding` only works for shapes with 1 and 2 dimensions.\")\n+\n+ base_height = int(10 * scale)\n+ aspect_ratio = (shape[1] if len(shape) == 2 else 1) / shape[0]\n+ base_width = int(base_height * aspect_ratio)\n+ height_to_width_ratio = 2.5\n+\n+ # Grab the device kind from the first device\n+ device_kind = next(iter(sharding.device_set)).device_kind.upper()\n+\n+ device_indices_map = sharding.devices_indices_map(tuple(shape))\n+ slices: Dict[Tuple[int, ...], Set[int]] = {}\n+ heights: Dict[Tuple[int, ...], int] = {}\n+ widths: Dict[Tuple[int, ...], int] = {}\n+ for dev, slcs in device_indices_map.items():\n+ chunk_idxs = tuple(map(_slice_to_chunk_idx, shape, slcs))\n+ if slcs is None:\n+ raise NotImplementedError\n+ if len(slcs) == 2:\n+ vert, horiz = slcs\n+ vert_size = ((vert.stop - vert.start ) if vert.stop is not None\n+ else shape[0])\n+ horiz_size = ((horiz.stop - horiz.start) if horiz.stop is not None\n+ else shape[1])\n+ chunk_height = vert_size / shape[0] * base_height\n+ chunk_width = (\n+ horiz_size / shape[1] * base_width *\n+ height_to_width_ratio)\n+ heights[chunk_idxs] = int(chunk_height)\n+ widths[chunk_idxs] = int(chunk_width)\n+ slices.setdefault(chunk_idxs, set()).add(dev.id)\n+ else:\n+ # In the 1D case, we set the height to 1.\n+ horiz, = slcs\n+ vert = slice(0, 1, None)\n+ horiz_size = (\n+ (horiz.stop - horiz.start) if horiz.stop is not None else shape[0])\n+ heights[(0, *chunk_idxs)] = 1\n+ widths[(0, *chunk_idxs)] = int(horiz_size / shape[0] * base_width)\n+ slices.setdefault((0, *chunk_idxs), set()).add(dev.id)\n+ num_rows = max([a[0] for a in slices.keys()]) + 1\n+ if len(list(slices.keys())[0]) == 1:\n+ num_cols = 1\n+ else:\n+ num_cols = max([a[1] for a in slices.keys()]) + 1\n+\n+ table = rich.table.Table(show_header=False, show_lines=True, padding=0,\n+ highlight=True, pad_edge=False,\n+ box=rich.box.SQUARE)\n+ for i in range(num_rows):\n+ col = []\n+ for j in range(num_cols):\n+ entry = f\"{device_kind} \"+\",\".join([str(s) for s in sorted(slices[i, j])])\n+ width, height = widths[i, j], heights[i, j]\n+ left_padding, remainder = divmod(width - len(entry), 2)\n+ right_padding = left_padding + remainder\n+ top_padding, remainder = divmod(height - 1, 2)\n+ bottom_padding = top_padding + remainder\n+ padding = (top_padding, right_padding, bottom_padding, left_padding)\n+ padding = tuple(max(x, 0) for x in padding) # type: ignore\n+ col.append(\n+ rich.padding.Padding(\n+ rich.align.Align(entry, \"center\", vertical=\"middle\"), padding))\n+ table.add_row(*col)\n+ rich.get_console().print(table, end='\\n\\n')\n+\n+def visualize_array_sharding(arr, **kwargs):\n+ \"\"\"Visualizes an array's sharding.\"\"\"\n+ if not config.jax_array:\n+ raise NotImplementedError(\"`visualize_array_sharding` not implemented.\")\n+ return visualize_sharding(arr.shape, arr.sharding, **kwargs)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/debug.py",
"new_path": "jax/debug.py",
"diff": "from jax._src.debugging import debug_callback as callback\nfrom jax._src.debugging import debug_print as print\nfrom jax._src.debugging import DebugEffect\n+from jax._src.debugging import visualize_array_sharding\n+from jax._src.debugging import visualize_sharding\nfrom jax._src.debugger import breakpoint\n"
}
] | Python | Apache License 2.0 | google/jax | Add function to visualize `Sharding`s |
260,510 | 19.09.2022 18:35:22 | 25,200 | f825a3c8c0eda55f2f2ffebf4723d36bb1da7046 | Limit console width for visualize_sharding | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "@@ -41,6 +41,7 @@ try:\nimport rich\nimport rich.align\nimport rich.box\n+ import rich.console\nimport rich.padding\nimport rich.table\nRICH_ENABLED = True\n@@ -254,7 +255,8 @@ def _slice_to_chunk_idx(size: int, slc: slice) -> int:\nreturn slc.start // slice_size\ndef visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\n- use_color: bool = False, scale: float = 1.):\n+ use_color: bool = False, scale: float = 1.,\n+ min_width: int = 9, max_width: int = 80):\n\"\"\"Visualizes a `Sharding`.\"\"\"\nif not RICH_ENABLED:\nraise ValueError(\"`visualize_sharding` requires `rich` to be installed.\")\n@@ -271,7 +273,7 @@ def visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\nheight_to_width_ratio = 2.5\n# Grab the device kind from the first device\n- device_kind = next(iter(sharding.device_set)).device_kind.upper()\n+ device_kind = next(iter(sharding.device_set)).platform.upper()\ndevice_indices_map = sharding.devices_indices_map(tuple(shape))\nslices: Dict[Tuple[int, ...], Set[int]] = {}\n@@ -312,14 +314,16 @@ def visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\ntable = rich.table.Table(show_header=False, show_lines=True, padding=0,\nhighlight=True, pad_edge=False,\nbox=rich.box.SQUARE)\n+ console = rich.console.Console(width=max_width)\nfor i in range(num_rows):\ncol = []\nfor j in range(num_cols):\nentry = f\"{device_kind} \"+\",\".join([str(s) for s in sorted(slices[i, j])])\nwidth, height = widths[i, j], heights[i, j]\n- left_padding, remainder = divmod(width - len(entry), 2)\n+ width = min(max(width, min_width), max_width)\n+ left_padding, remainder = divmod(width - len(entry) - 2, 2)\nright_padding = left_padding + remainder\n- top_padding, remainder = divmod(height - 1, 2)\n+ top_padding, remainder = divmod(height - 2, 2)\nbottom_padding = top_padding + remainder\npadding = (top_padding, right_padding, bottom_padding, left_padding)\npadding = tuple(max(x, 0) for x in padding) # type: ignore\n@@ -327,7 +331,7 @@ def visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\nrich.padding.Padding(\nrich.align.Align(entry, \"center\", vertical=\"middle\"), padding))\ntable.add_row(*col)\n- rich.get_console().print(table, end='\\n\\n')\n+ console.print(table, end='\\n\\n')\ndef visualize_array_sharding(arr, **kwargs):\n\"\"\"Visualizes an array's sharding.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | Limit console width for visualize_sharding |
260,510 | 19.09.2022 19:19:45 | 25,200 | 0276a6e77c12a50ad0f77b27441fc6b685d0e927 | Add support for pmap sharding | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "@@ -17,7 +17,7 @@ import functools\nimport string\nimport sys\n-from typing import Any, Dict, Callable, Sequence, Set, Tuple\n+from typing import Any, Dict, Callable, Sequence, Set, Tuple, Union\nfrom jax import core\nfrom jax import tree_util\n@@ -254,6 +254,11 @@ def _slice_to_chunk_idx(size: int, slc: slice) -> int:\nassert size % slice_size == 0\nreturn slc.start // slice_size\n+def _raise_to_slice(slc: Union[slice, int]):\n+ if isinstance(slc, int):\n+ return slice(slc, slc + 1)\n+ return slc\n+\ndef visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\nuse_color: bool = False, scale: float = 1.,\nmin_width: int = 9, max_width: int = 80):\n@@ -280,6 +285,7 @@ def visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\nheights: Dict[Tuple[int, ...], int] = {}\nwidths: Dict[Tuple[int, ...], int] = {}\nfor dev, slcs in device_indices_map.items():\n+ slcs = tuple(map(_raise_to_slice, slcs))\nchunk_idxs = tuple(map(_slice_to_chunk_idx, shape, slcs))\nif slcs is None:\nraise NotImplementedError\n"
}
] | Python | Apache License 2.0 | google/jax | Add support for pmap sharding |
260,424 | 16.09.2022 17:46:25 | -3,600 | 018e700ead0612a56f1e7702220012661161f4fc | Checkify: support batched while. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -662,18 +662,54 @@ def ignore_error_output_jaxpr(jaxpr):\nnew_jaxpr = jaxpr.replace(outvars=jaxpr.outvars[3:])\nreturn core.ClosedJaxpr(new_jaxpr, consts)\n+def batch_error(err, code, payload, batch_shape):\n+ err = jnp.broadcast_to(err, batch_shape)\n+ code = jnp.broadcast_to(code, batch_shape)\n+ payload = jnp.broadcast_to(payload, batch_shape+(3,))\n+ return err, code, payload\n+\n+def unbatch_error(err, code, payload):\n+ err = err.ravel()[0]\n+ code = code.ravel()[0]\n+ payload = payload.reshape(-1, 3)[0]\n+ return err, code, payload\n+\n+def trivial_batched_jaxpr(jaxpr, batch_shape, batched_err):\n+ fun = core.jaxpr_as_fun(jaxpr)\n+\n+ def g(err, code, payload, *a):\n+ err_args = unbatch_error(err, code, payload)\n+ err, code, payload, *out = fun(*err_args, *a)\n+ err, code, payload = batch_error(err, code, payload, batch_shape)\n+ return (err, code, payload, *out)\n+\n+ error_avals = map(lambda x: core.raise_to_shaped(core.get_aval(x)), batched_err)\n+ new_jaxpr, _, literals_out = pe.trace_to_jaxpr_dynamic(\n+ lu.wrap_init(g), [*error_avals, *jaxpr.in_avals[3:]])\n+ return core.ClosedJaxpr(new_jaxpr, literals_out)\n+\ndef while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\ncond_jaxpr, body_nconsts, body_jaxpr):\n+ batch_shape = cond_jaxpr.out_avals[0].shape\n+ if batch_shape:\n+ err_args = batch_error(error.err, error.code, error.payload, batch_shape)\n+ else:\n+ err_args = [error.err, error.code, error.payload]\n+\nc_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\n# Check if the first cond application will error.\nchecked_cond_jaxpr, msgs_cond = checkify_jaxpr(cond_jaxpr, error,\nenabled_errors)\n+ if batch_shape:\n+ checked_cond_jaxpr = trivial_batched_jaxpr(checked_cond_jaxpr, batch_shape, err_args)\ncond_err, cond_code, cond_payload, _ = core.jaxpr_as_fun(checked_cond_jaxpr)(\n- error.err, error.code, error.payload, *c_consts, *carry)\n+ *err_args, *c_consts, *carry)\nchecked_body_jaxpr_, msgs_body = checkify_while_body_jaxpr(\ncond_jaxpr, body_jaxpr, error, enabled_errors, c_consts)\n+ if batch_shape:\n+ checked_body_jaxpr_ = trivial_batched_jaxpr(checked_body_jaxpr_, batch_shape, err_args)\nto_move = [False] * 3 + [True] * body_nconsts + [False] * len(carry)\nchecked_body_jaxpr = pe.move_binders_to_front(checked_body_jaxpr_, to_move)\n@@ -686,6 +722,9 @@ def while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\n*new_in_flat, cond_nconsts=cond_nconsts, cond_jaxpr=compat_cond_jaxpr,\nbody_nconsts=body_nconsts, body_jaxpr=checked_body_jaxpr)\nnew_msgs = {**error.msgs, **msgs_body, **msgs_cond}\n+ if batch_shape:\n+ err, code, payload = unbatch_error(err, code, payload)\n+\nreturn out, Error(err, code, new_msgs, payload)\nerror_checks[lax.while_p] = while_loop_error_check\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -875,5 +875,35 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertIn(\"should be positive\", err.get())\n+ def test_checkify_of_vmap_of_while(self):\n+ @jax.vmap\n+ def fun(n, v):\n+ def while_cond(s):\n+ counter, value = s\n+ checkify.check(value < 6, \"value needs to be less than 6!\")\n+ return counter > 0\n+\n+ def while_body(s):\n+ counter, value = s\n+ checkify.check(value >= 0, \"value needs to be positive!\")\n+ return counter/value, value - 1.\n+\n+ _, result = jax.lax.while_loop(while_cond, while_body, (n, v))\n+ return result\n+\n+ checked_f = checkify.checkify(fun, errors=checkify.all_checks)\n+\n+ err, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([5., 2., 4.]))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"divided by zero\")\n+\n+ err, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([5., 2., -4.]))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"value needs to be positive\")\n+\n+ err, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([6., 2., -4.]))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"value needs to be less than 6\")\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Checkify: support batched while. |
260,631 | 21.09.2022 09:47:21 | 25,200 | c7f2712e74211a36c0ec5056d4bbf257806e78c1 | Flip default value of jax_unique_mhlo_module_names to False.
This should help avoid unnecessary cache misses. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/config.py",
"new_path": "jax/_src/config.py",
"diff": "@@ -876,7 +876,7 @@ config.define_bool_state(\nconfig.define_bool_state(\nname='jax_unique_mhlo_module_names',\n- default=True,\n+ default=False,\nhelp='Enables the generation of unique MHLO module names. This is useful '\n'to clients that expect modules to have unique names (e.g, trace data).')\n"
}
] | Python | Apache License 2.0 | google/jax | Flip default value of jax_unique_mhlo_module_names to False.
This should help avoid unnecessary cache misses.
PiperOrigin-RevId: 475852954 |
260,661 | 22.09.2022 14:29:30 | 14,400 | 9a11b61829191e58089b23405c2c1c74aeb0f4b2 | [ROCM] Update Dockerfil.rocm to Ubuntu20 | [
{
"change_type": "MODIFY",
"old_path": "build/rocm/Dockerfile.rocm",
"new_path": "build/rocm/Dockerfile.rocm",
"diff": "-FROM ubuntu:bionic\n+FROM ubuntu:focal\nMAINTAINER Reza Rahimi <reza.rahimi@amd.com>\nARG ROCM_DEB_REPO=http://repo.radeon.com/rocm/apt/5.2/\n@@ -82,8 +82,7 @@ RUN add-apt-repository ppa:deadsnakes/ppa && \\\npython3-pip \\\npython3.9-distutils\n-RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1 && \\\n- update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 2\n+RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 1\nRUN pip3 install --upgrade --force-reinstall setuptools pip\n"
}
] | Python | Apache License 2.0 | google/jax | [ROCM] Update Dockerfil.rocm to Ubuntu20 |
260,672 | 22.09.2022 11:44:22 | 25,200 | d52de206cb349173d961a57d0288eafbf423959d | Disable tests that timeout in debug mode in CI | [
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -477,6 +477,7 @@ jax_test(\n\"tpu\": [\n\"cpu:8\",\n\"noasan\", # Times out.\n+ \"nodebug\", # Times out.\n\"notsan\", # Times out.\n],\n},\n@@ -535,9 +536,10 @@ jax_test(\nsrcs = [\"pmap_test.py\"],\nbackend_tags = {\n\"tpu\": [\n- \"noasan\",\n- \"notsan\",\n- ], # Times out under asan/tsan.\n+ \"noasan\", # Times out.\n+ \"nodebug\", # Times out.\n+ \"notsan\", # Times out.\n+ ],\n},\npjrt_c_api_bypass = True,\nshard_count = {\n"
}
] | Python | Apache License 2.0 | google/jax | Disable tests that timeout in debug mode in CI
PiperOrigin-RevId: 476157051 |
260,510 | 22.09.2022 12:55:55 | 25,200 | 1a8a8a5586c4c4097aa2fa99a4450da1efed0c41 | Fix example in `pjit` docstring | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/pjit.py",
"new_path": "jax/experimental/pjit.py",
"diff": "@@ -304,13 +304,14 @@ def pjit(fun: Callable,\n>>> import jax\n>>> import jax.numpy as jnp\n+ >>> import numpy as np\n>>> from jax.experimental.maps import Mesh\n>>> from jax.experimental.pjit import PartitionSpec, pjit\n>>>\n>>> x = jnp.arange(8, dtype=jnp.float32)\n>>> f = pjit(lambda x: jax.numpy.convolve(x, jnp.asarray([0.5, 1.0, 0.5]), 'same'),\n... in_axis_resources=None, out_axis_resources=PartitionSpec('devices'))\n- >>> with Mesh(jax.devices(), ('devices',)):\n+ >>> with Mesh(np.array(jax.devices()), ('devices',)):\n... print(f(x)) # doctest: +SKIP\n[ 0.5 2. 4. 6. 8. 10. 12. 10. ]\n\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | Fix example in `pjit` docstring |
260,510 | 22.09.2022 17:36:20 | 25,200 | 805073f36a03aa1a93486c98c4ac9851e630ea05 | Add inspect_array_sharding, enabling looking at shardings in pjit-ted functions | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "@@ -16,24 +16,33 @@ import enum\nimport functools\nimport string\nimport sys\n+import weakref\nfrom typing import Any, Dict, Callable, Sequence, Set, Tuple, Union\nfrom jax import core\nfrom jax import tree_util\nfrom jax import lax\n-from jax._src import ad_checkpoint\n-from jax._src import custom_derivatives\n-from jax._src import lib as jaxlib\n-from jax._src import util\n+from jax import linear_util as lu\nfrom jax.config import config\nfrom jax.experimental.sharding import Sharding\n+from jax.experimental.sharding import OpShardingSharding\n+from jax.experimental import pjit\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\n+from jax.interpreters import pxla\n+from jax.interpreters import xla\n+from jax._src import ad_checkpoint\n+from jax._src import custom_derivatives\n+from jax._src import lib as jaxlib\n+from jax._src import source_info_util\n+from jax._src import util\nfrom jax._src.lax import control_flow as lcf\nfrom jax._src.lib import xla_client as xc\n+from jax._src.lib.mlir import ir\n+from jax._src.lib.mlir.dialects import mhlo\nimport jax.numpy as jnp\n# pytype: disable=import-error\n@@ -246,6 +255,139 @@ def debug_print(fmt: str, *args, ordered: bool = False, **kwargs) -> None:\ndebug_callback(functools.partial(_format_print_callback, fmt), *args,\n**kwargs, ordered=ordered)\n+\n+# Sharding visualization\n+\n+inspect_sharding_p = core.Primitive(\"inspect_sharding\")\n+inspect_sharding_p.multiple_results = True\n+\n+def _inspect_sharding_impl(value, *, callback):\n+ if not config.jax_array:\n+ raise NotImplementedError(\"`inspect_sharding` not implemented.\")\n+ callback(value.sharding)\n+ return []\n+inspect_sharding_p.def_impl(_inspect_sharding_impl)\n+\n+def _inspect_sharding_abstract_eval(aval, **_):\n+ del aval\n+ # Effectful abstract avoids DCE\n+ return [], {DebugEffect.PRINT}\n+inspect_sharding_p.def_effectful_abstract_eval(_inspect_sharding_abstract_eval)\n+\n+def _inspect_sharding_batching_rule(args, _, *, callback):\n+ value, = args\n+ inspect_sharding_p.bind(value, callback=callback)\n+ return [], []\n+batching.primitive_batchers[inspect_sharding_p] = (\n+ _inspect_sharding_batching_rule)\n+\n+def _inspect_sharding_jvp_rule(primals, _, **params):\n+ return inspect_sharding_p.bind(*primals, **params)\n+ad.primitive_jvps[inspect_sharding_p] = _inspect_sharding_jvp_rule\n+\n+sharding_callbacks = weakref.WeakValueDictionary() # type: ignore\n+_INSPECT_SHARDING_CALL_NAME = \"InspectSharding\"\n+\n+class ShardingCallbackInfo:\n+ def __init__(self, callback, module_context):\n+ self.callback = callback\n+ self.module_context = module_context\n+\n+def _inspect_sharding_lowering_rule(ctx: mlir.LoweringRuleContext, value, *,\n+ callback):\n+\n+ mesh = pxla.thread_resources.env.physical_mesh\n+ axis_context = ctx.module_context.axis_context\n+\n+ if isinstance(axis_context, mlir.ShardingContext):\n+ devices = axis_context.device_assignment\n+ elif isinstance(axis_context, mlir.SPMDAxisContext):\n+ devices = list(axis_context.mesh.devices.flat)\n+ else:\n+ raise NotImplementedError(type(axis_context))\n+\n+ def _op_sharding_callback(op_sharding: xc.OpSharding):\n+ if mesh.empty:\n+ return callback(OpShardingSharding(\n+ devices, op_sharding))\n+ pspec = pjit.parse_flatten_op_sharding(\n+ op_sharding, mesh)[0].get_partition_spec()\n+ return callback(pjit.MeshPspecSharding(mesh, pspec))\n+\n+ if len(devices) == 1:\n+ # If we only have one device in our computation, we can construct a trivial\n+ # OpSharding and call it right now.\n+ trivial_sharding = xc.OpSharding()\n+ trivial_sharding.type = xc.OpSharding.Type.REPLICATED\n+ _op_sharding_callback(trivial_sharding)\n+ return []\n+\n+ # If we have a nontrivial parallel computation, we need to wait until the SPMD\n+ # partitioner calls back with the `HloSharding.\n+ def _hlo_sharding_callback(hlo_sharding):\n+ op_sharding = hlo_sharding.to_proto()\n+ return _op_sharding_callback(op_sharding)\n+\n+ # Here we store information in a container that we store globally so the\n+ # custom partitioning code can access it.\n+ sharding_callback_info = ShardingCallbackInfo(_hlo_sharding_callback,\n+ ctx.module_context)\n+ key = str(id(sharding_callback_info))\n+ sharding_callbacks[key] = sharding_callback_info\n+ # We need to make sure `sharding_callback_info` is still alive when the SPMD\n+ # partitioner runs so we keep it alive by attaching it to the executable.\n+ ctx.module_context.add_keepalive(sharding_callback_info)\n+\n+ mhlo.CustomCallOp([ir.TupleType.get_tuple([])], [value],\n+ call_target_name=ir.StringAttr.get(\n+ _INSPECT_SHARDING_CALL_NAME),\n+ has_side_effect=ir.BoolAttr.get(True),\n+ api_version=mlir.i32_attr(1),\n+ called_computations=ir.ArrayAttr.get([]),\n+ backend_config=ir.StringAttr.get(key),\n+ operand_layouts=None,\n+ result_layouts=None)\n+ return []\n+mlir.register_lowering(inspect_sharding_p, _inspect_sharding_lowering_rule)\n+\n+def inspect_sharding_prop_user_sharding(sharding, backend_string):\n+ del sharding, backend_string\n+ return []\n+\n+def inspect_sharding_partition(shapes, arg_shardings, result_shape,\n+ result_sharding, backend_string):\n+ del result_shape, result_sharding\n+ sharding_callback_info = sharding_callbacks[backend_string]\n+ sharding_callback = sharding_callback_info.callback\n+ module_context = sharding_callback_info.module_context\n+\n+ # Execute callback\n+ hlo_sharding, = arg_shardings\n+ sharding_callback(hlo_sharding)\n+\n+ tiled_args = [p.tile(s) for s, p in zip(shapes, arg_shardings)]\n+ in_avals = [core.ShapedArray(arg.dimensions(), arg.numpy_dtype())\n+ for arg in tiled_args]\n+ fun = lu.wrap_init(lambda *args: [])\n+ jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(fun, in_avals)\n+ closed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\n+ trivial_comp = mlir.build_xla_computation_helper(closed_jaxpr,\n+ name=\"tmp_xla_computation\", platform=module_context.platform,\n+ backend_or_name=module_context.backend_or_name,\n+ axis_context=module_context.axis_context)\n+ return trivial_comp, arg_shardings, arg_shardings[0]\n+\n+def inspect_sharding_infer_sharding_from_operands(arg_shapes, arg_shardings,\n+ shape, backend_string):\n+ del arg_shapes, shape, backend_string\n+ return arg_shardings[0]\n+\n+if jaxlib.xla_extension_version >= 94:\n+ xc.register_custom_call_partitioner( # pytype: disable=module-attr\n+ _INSPECT_SHARDING_CALL_NAME, inspect_sharding_prop_user_sharding,\n+ inspect_sharding_partition, inspect_sharding_infer_sharding_from_operands,\n+ True)\n+\ndef _slice_to_chunk_idx(size: int, slc: slice) -> int:\nif slc.stop == slc.start == None:\nreturn 0\n@@ -339,8 +481,63 @@ def visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\ntable.add_row(*col)\nconsole.print(table, end='\\n\\n')\n+def inspect_array_sharding(value, *, callback: Callable[[Sharding], None]):\n+ \"\"\"Enables inspecting array sharding inside JIT-ted functions.\n+\n+ This function, when provided with a Pytree of arrays, calls back with each of\n+ their shardings and works in ``pjit``-ted computations, enabling inspecting\n+ the chosen intermediate shardings.\n+\n+ The policy for when ``callback`` is called is *as early as possible* when the\n+ sharding information is available. This means if ``inspect_array_callback`` is\n+ called without any transformations, The callback will happen immediately\n+ since we have the array and its sharding readily available. Inside of a\n+ ``jax.jit``, the callback will happen at lowering time, meaning you can\n+ trigger the callback using the AOT API( ``jit(f).lower(...)``). When inside of\n+ a ``pjit``, the callback happens **at compile time** since the sharding is\n+ determined by XLA. You can trigger the callback by using JAX's AOT API\n+ (``pjit(f).lower(...).compile()``). In all cases, the callback will be\n+ triggered by running the function, since running a function entails lowering\n+ and compiling it first. However, once the function is compiled and cached,\n+ the callback will no longer occur.\n+\n+ This function is experimental and its behavior may change in the future.\n+\n+ Args:\n+ value: A Pytree of JAX arrays.\n+ callback: A callable that takes in a `Sharding` and doesn't return a value.\n+\n+ In the following example, we print out the sharding of an intermediate value\n+ in a ``pjit``-ted computation:\n+\n+ >>> import jax\n+ >>> import jax.numpy as jnp\n+ >>> from jax.experimental.maps import Mesh\n+ >>> from jax.experimental.pjit import PartitionSpec, pjit\n+ >>>\n+ >>> x = jnp.arange(8, dtype=jnp.float32)\n+ >>> def f_(x):\n+ ... x = jnp.sin(x)\n+ ... jax.debug.inspect_array_sharding(x, callback=print)\n+ ... return jnp.square(x)\n+ >>> f = pjit(f_, in_axis_resources=PartitionSpec('dev'),\n+ ... out_axis_resources=PartitionSpec('dev'))\n+ >>> with Mesh(jax.devices(), ('dev',)):\n+ ... f.lower(x).compile() # doctest: +SKIP\n+ ...\n+ MeshPspecSharding(mesh={'dev': 8}, partition_spec=PartitionSpec(('dev',),))\n+ \"\"\"\n+ if jaxlib.xla_extension_version < 94:\n+ raise NotImplementedError(\"`inspect_array_sharding` not implemented. \"\n+ \"Please upgrade `jaxlib` to the latest version.\")\n+ def _inspect(val):\n+ inspect_sharding_p.bind(val, callback=callback)\n+ tree_util.tree_map(_inspect, value)\n+\ndef visualize_array_sharding(arr, **kwargs):\n\"\"\"Visualizes an array's sharding.\"\"\"\nif not config.jax_array:\nraise NotImplementedError(\"`visualize_array_sharding` not implemented.\")\n- return visualize_sharding(arr.shape, arr.sharding, **kwargs)\n+ def _visualize(sharding):\n+ return visualize_sharding(arr.shape, sharding, **kwargs)\n+ inspect_array_sharding(arr, callback=_visualize)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/debug.py",
"new_path": "jax/debug.py",
"diff": "@@ -15,5 +15,6 @@ from jax._src.debugging import debug_callback as callback\nfrom jax._src.debugging import debug_print as print\nfrom jax._src.debugging import DebugEffect\nfrom jax._src.debugging import visualize_array_sharding\n+from jax._src.debugging import inspect_array_sharding\nfrom jax._src.debugging import visualize_sharding\nfrom jax._src.debugger import breakpoint\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1208,6 +1208,7 @@ tf_not_yet_impl = [\n\"full_to_shard\",\n\"shard_to_full\",\n\"pure_callback\",\n+ \"inspect_sharding\",\n# Not high priority?\n\"after_all\",\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -1641,6 +1641,21 @@ def emit_python_callback(\ntoken, *results = results\nreturn results, token, keepalive\n+def build_xla_computation_helper(\n+ closed_jaxpr: core.ClosedJaxpr, *, name: str, platform: str,\n+ backend_or_name: str, axis_context: AxisContext) -> xc.XlaComputation:\n+ \"\"\"Helper to generate pmap-style XLA computations for custom partitioners.\"\"\"\n+ if closed_jaxpr.effects:\n+ raise NotImplementedError\n+ lowering_result = lower_jaxpr_to_module(name, closed_jaxpr,\n+ backend_or_name=backend_or_name, unordered_effects=[], ordered_effects=[],\n+ name_stack=source_info_util.NameStack(),\n+ donated_args=[False] * len(closed_jaxpr.jaxpr.invars),\n+ axis_context=axis_context, platform=platform)\n+ return xc._xla.mlir.mlir_module_to_xla_computation(\n+ module_to_string(lowering_result.module), use_tuple_args=False,\n+ return_tuple=False)\n+\n# Lax ops missing MLIR lowerings.\n# # TODO(b/203775215): these are missing from the cHLO dialect. Either add\n# # them or port them to Python.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/debugging_primitives_test.py",
"new_path": "tests/debugging_primitives_test.py",
"diff": "@@ -694,7 +694,7 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\nelse:\nspec = pjit.PartitionSpec('dev')\nout_spec = pjit.PartitionSpec()\n- f = pjit.pjit(f, in_axis_resources=spec, out_axis_resources=spec)\n+ f = pjit.pjit(f, in_axis_resources=spec, out_axis_resources=out_spec)\nwith mesh:\nwith jtu.capture_stdout() as output:\nf(np.arange(8, dtype=jnp.int32))\n@@ -1049,6 +1049,60 @@ class VisualizeShardingTest(jtu.JaxTestCase):\n\"\"\")\nself.assertEqual(output(), expected)\n+class InspectShardingTest(jtu.JaxTestCase):\n+\n+ def test_inspect_sharding_is_called_in_pjit(self):\n+\n+ if jaxlib.xla_extension_version < 94:\n+ raise unittest.SkipTest(\"Inspect sharding not supported.\")\n+\n+ is_called = False\n+ def _cb(sd):\n+ nonlocal is_called\n+ is_called = True\n+ self.assertIsInstance(sd, sharding.Sharding)\n+ self.assertLen(sd.device_set, len(jax.devices()))\n+\n+ def f(x):\n+ debugging.inspect_array_sharding(x, callback=_cb)\n+ return jnp.square(x)\n+\n+ mesh = maps.Mesh(np.array(jax.devices()), ['dev'])\n+ if config.jax_array:\n+ spec = sharding.MeshPspecSharding(mesh, pjit.PartitionSpec('dev'))\n+ out_spec = sharding.MeshPspecSharding(mesh, pjit.PartitionSpec())\n+ else:\n+ spec = pjit.PartitionSpec('dev')\n+ out_spec = pjit.PartitionSpec()\n+ f = pjit.pjit(f, in_axis_resources=spec, out_axis_resources=out_spec)\n+ with mesh:\n+ f(np.arange(8, dtype=jnp.int32))\n+ self.assertTrue(is_called)\n+\n+ def test_inspect_sharding_is_called_in_jit(self):\n+\n+ if jaxlib.xla_extension_version < 94:\n+ raise unittest.SkipTest(\"Inspect sharding not supported.\")\n+\n+ if not config.jax_array:\n+ raise unittest.SkipTest(\"jax_array to work inside of `jit`.\")\n+\n+ is_called = False\n+ def _cb(sd):\n+ nonlocal is_called\n+ is_called = True\n+ self.assertIsInstance(sd, sharding.Sharding)\n+ self.assertLen(sd.device_set, 1)\n+\n+ def f(x):\n+ debugging.inspect_array_sharding(x, callback=_cb)\n+ return jnp.square(x)\n+\n+ f = jax.jit(f)\n+ f(np.arange(8, dtype=jnp.int32))\n+ self.assertTrue(is_called)\n+\n+\nif not rich:\ndel VisualizeShardingTest\n"
}
] | Python | Apache License 2.0 | google/jax | Add inspect_array_sharding, enabling looking at shardings in pjit-ted functions
PiperOrigin-RevId: 476237731 |
260,510 | 22.09.2022 19:04:23 | 25,200 | 99d4d8b89ad759d6c53e9a2d1830c334dacf9238 | Update debugging docs to have sharding visualization | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.debug.rst",
"new_path": "docs/jax.debug.rst",
"diff": "@@ -6,10 +6,11 @@ jax.debug package\n.. automodule:: jax.debug\n-Debugging utilities\n---------------------------\n+Runtime value debugging utilities\n+---------------------------------\n-:doc:`debugging/print_breakpoint` describes how to make use of JAX's debugging features.\n+:doc:`debugging/print_breakpoint` describes how to make use of JAX's runtime value\n+debugging features.\n.. autosummary::\n:toctree: _autosummary\n@@ -17,3 +18,16 @@ Debugging utilities\ncallback\nprint\nbreakpoint\n+\n+Sharding debugging utilities\n+----------------------------\n+\n+Functions that enable inspecting and visualizing array shardings inside (and outside)\n+staged functions.\n+\n+.. autosummary::\n+ :toctree: _autosummary\n+\n+ inspect_array_sharding\n+ visualize_array_sharding\n+ visualize_sharding\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "@@ -404,7 +404,7 @@ def _raise_to_slice(slc: Union[slice, int]):\ndef visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\nuse_color: bool = False, scale: float = 1.,\nmin_width: int = 9, max_width: int = 80):\n- \"\"\"Visualizes a `Sharding`.\"\"\"\n+ \"\"\"Visualizes a ``Sharding`` using ``rich``.\"\"\"\nif not RICH_ENABLED:\nraise ValueError(\"`visualize_sharding` requires `rich` to be installed.\")\nif use_color:\n@@ -490,11 +490,11 @@ def inspect_array_sharding(value, *, callback: Callable[[Sharding], None]):\nThe policy for when ``callback`` is called is *as early as possible* when the\nsharding information is available. This means if ``inspect_array_callback`` is\n- called without any transformations, The callback will happen immediately\n+ called without any transformations, the callback will happen immediately\nsince we have the array and its sharding readily available. Inside of a\n``jax.jit``, the callback will happen at lowering time, meaning you can\ntrigger the callback using the AOT API (``jit(f).lower(...)``). When inside of\n- a ``pjit``, the callback happens **at compile time** since the sharding is\n+ a ``pjit``, the callback happens *at compile time* since the sharding is\ndetermined by XLA. You can trigger the callback by using JAX's AOT API\n(``pjit(f).lower(...).compile()``). In all cases, the callback will be\ntriggered by running the function, since running a function entails lowering\n@@ -505,7 +505,7 @@ def inspect_array_sharding(value, *, callback: Callable[[Sharding], None]):\nArgs:\nvalue: A Pytree of JAX arrays.\n- callback: A callable that takes in a `Sharding` and doesn't return a value.\n+ callback: A callable that takes in a ``Sharding`` and doesn't return a value.\nIn the following example, we print out the sharding of an intermediate value\nin a ``pjit``-ted computation:\n"
}
] | Python | Apache License 2.0 | google/jax | Update debugging docs to have sharding visualization |
260,447 | 22.09.2022 20:21:29 | 25,200 | 67b7ae259fca8fc6aea0efc632bac438dae01919 | [sparse] Move `_bcoo_nse` to sparse util. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcoo.py",
"new_path": "jax/experimental/sparse/bcoo.py",
"diff": "@@ -29,7 +29,7 @@ from jax import tree_util\nfrom jax import vmap\nfrom jax.config import config\nfrom jax.experimental.sparse._base import JAXSparse\n-from jax.experimental.sparse.util import _safe_asarray, CuSparseEfficiencyWarning, SparseEfficiencyError, SparseEfficiencyWarning\n+from jax.experimental.sparse.util import _count_stored_elements, _safe_asarray, CuSparseEfficiencyWarning, SparseEfficiencyError, SparseEfficiencyWarning\nfrom jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import mlir\n@@ -76,14 +76,6 @@ def broadcasting_vmap(fun, in_axes=0, out_axes=0):\n#----------------------------------------------------------------------\n# BCOO primitives: batched extension of COO.\n-def _bcoo_nse(mat, n_batch=0, n_dense=0):\n- mat = jnp.asarray(mat)\n- mask = (mat != 0)\n- if n_dense > 0:\n- mask = mask.any([-(i + 1) for i in range(n_dense)])\n- mask = mask.sum(list(range(n_batch, mask.ndim)))\n- return mask.max()\n-\ndef _bcoo_set_nse(mat, nse):\n\"\"\"Return a copy of `mat` with the specified nse.\nNote that if nse < mat.nse, this will potentially discard data.\n@@ -261,9 +253,9 @@ bcoo_fromdense_p = core.Primitive('bcoo_fromdense')\nbcoo_fromdense_p.multiple_results = True\n_TRACED_NSE_ERROR = \"\"\"\n-The error arose for the nse argument of bcoo_fromdense. In order for BCOO.fromdense()\n-to be used in traced/compiled code, you must pass a concrete value to the nse\n-(number of specified elements) argument.\n+The error arose for the nse argument of bcoo_fromdense. In order for\n+BCOO.fromdense() to be used in traced/compiled code, you must pass a concrete\n+value to the nse (number of stored elements) argument.\n\"\"\"\ndef bcoo_fromdense(mat, *, nse=None, n_batch=0, n_dense=0, index_dtype=jnp.int32):\n@@ -281,7 +273,7 @@ def bcoo_fromdense(mat, *, nse=None, n_batch=0, n_dense=0, index_dtype=jnp.int32\n\"\"\"\nmat = jnp.asarray(mat)\nif nse is None:\n- nse = _bcoo_nse(mat, n_batch, n_dense)\n+ nse = _count_stored_elements(mat, n_batch, n_dense)\nnse = core.concrete_or_error(operator.index, nse, _TRACED_NSE_ERROR)\nreturn BCOO(_bcoo_fromdense(mat, nse=nse, n_batch=n_batch, n_dense=n_dense,\nindex_dtype=index_dtype),\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/util.py",
"new_path": "jax/experimental/sparse/util.py",
"diff": "@@ -34,6 +34,12 @@ class CuSparseEfficiencyWarning(SparseEfficiencyWarning):\n# utilities\n# TODO: possibly make these primitives, targeting cusparse rountines\n# csr2coo/coo2csr/SPDDMM\n+\n+def _asarray_or_float0(arg):\n+ if isinstance(arg, np.ndarray) and arg.dtype == dtypes.float0:\n+ return arg\n+ return jnp.asarray(arg)\n+\n@jax.jit\ndef _csr_to_coo(indices, indptr):\n\"\"\"Given CSR (indices, indptr) return COO (row, col)\"\"\"\n@@ -47,6 +53,19 @@ def _coo_extract(row, col, mat):\n\"\"\"Extract values of dense matrix mat at given COO indices.\"\"\"\nreturn mat[row, col]\n+def _count_stored_elements_per_batch(mat, n_batch=0, n_dense=0):\n+ \"\"\"Return per-batch number of stored elements (nse) of a dense matrix.\"\"\"\n+ mat = jnp.asarray(mat)\n+ mask = (mat != 0)\n+ if n_dense > 0:\n+ mask = mask.any([-(i + 1) for i in range(n_dense)])\n+ mask = mask.sum(list(range(n_batch, mask.ndim)))\n+ return mask\n+\n+def _count_stored_elements(mat, n_batch=0, n_dense=0):\n+ \"\"\"Return the number of stored elements (nse) of the given dense matrix.\"\"\"\n+ return int(_count_stored_elements_per_batch(mat, n_batch, n_dense).max())\n+\ndef _is_pytree_placeholder(*args):\n# Returns True if the arguments are consistent with being a placeholder within\n# pytree validation.\n@@ -58,11 +77,6 @@ def _is_aval(*args):\ndef _is_arginfo(*args):\nreturn all(isinstance(arg, stages.ArgInfo) for arg in args)\n-def _asarray_or_float0(arg):\n- if isinstance(arg, np.ndarray) and arg.dtype == dtypes.float0:\n- return arg\n- return jnp.asarray(arg)\n-\ndef _safe_asarray(args):\nif _is_pytree_placeholder(*args) or _is_aval(*args) or _is_arginfo(*args):\nreturn args\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -732,7 +732,8 @@ class BCOOTest(jtu.JaxTestCase):\nrng = rand_sparse(self.rng())\nM = rng(shape, dtype)\nn_sparse = M.ndim - n_batch - n_dense\n- nse = int(sparse_bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)\ndata_jit, indices_jit = jit(partial(sparse_bcoo._bcoo_fromdense, nse=nse, n_batch=n_batch, n_dense=n_dense))(M)\nself.assertArraysEqual(data, data_jit)\n@@ -758,7 +759,8 @@ class BCOOTest(jtu.JaxTestCase):\ndef test_bcoo_todense_ad(self, shape, dtype, n_batch, n_dense):\nrng = rand_sparse(self.rng())\nM = rng(shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)\ntodense = partial(sparse_bcoo._bcoo_todense, indices=indices, spinfo=BCOOInfo(shape))\n@@ -780,7 +782,8 @@ class BCOOTest(jtu.JaxTestCase):\ndef test_bcoo_fromdense_ad(self, shape, dtype, n_batch, n_dense):\nrng = rand_sparse(self.rng())\nM = rng(shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\ndef fromdense(M):\nreturn sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)[0]\n@@ -823,7 +826,8 @@ class BCOOTest(jtu.JaxTestCase):\nrng = rand_sparse(self.rng())\nM = rng(shape, dtype)\nn_sparse = M.ndim - n_batch - n_dense\n- nse = int(sparse.bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\nfromdense = partial(sparse_bcoo._bcoo_fromdense, nse=nse, n_dense=n_dense)\ntodense = partial(sparse_bcoo._bcoo_todense, spinfo=BCOOInfo(shape[n_batch:]))\n@@ -852,7 +856,8 @@ class BCOOTest(jtu.JaxTestCase):\ndef test_bcoo_extract(self, shape, dtype, n_batch, n_dense):\nrng = rand_sparse(self.rng())\nM = rng(shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse)\ndata2 = sparse.bcoo_extract(indices, M)\nself.assertArraysEqual(data, data2)\n@@ -890,7 +895,8 @@ class BCOOTest(jtu.JaxTestCase):\ndef test_bcoo_extract_ad(self, shape, dtype, n_batch, n_dense):\nrng = rand_sparse(self.rng())\nM = rng(shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)\nextract = partial(sparse.bcoo_extract, indices)\n@@ -914,7 +920,8 @@ class BCOOTest(jtu.JaxTestCase):\nrng = self.rng()\nsprng = rand_sparse(rng)\nM = sprng(shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)\npermutation = np.concatenate([\n@@ -1022,7 +1029,8 @@ class BCOOTest(jtu.JaxTestCase):\nsprng = rand_sparse(self.rng())\nM = sprng(shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)\npermutation = np.concatenate([\n@@ -1070,7 +1078,8 @@ class BCOOTest(jtu.JaxTestCase):\ndef test_bcoo_todense_partial_batch(self, shape, dtype, n_batch, n_dense):\nrng = rand_sparse(self.rng())\nM = rng(shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)\nM1 = sparse_bcoo._bcoo_todense(data, indices[:1], spinfo=BCOOInfo(M.shape))\n@@ -1094,7 +1103,8 @@ class BCOOTest(jtu.JaxTestCase):\ndef args_maker():\nlhs = rng_sparse(props.lhs_shape, props.dtype)\nrhs = rng(props.rhs_shape, props.dtype)\n- nse = int(sparse_bcoo._bcoo_nse(lhs, n_batch=props.n_batch, n_dense=props.n_dense))\n+ nse = sparse.util._count_stored_elements(lhs, n_batch=props.n_batch,\n+ n_dense=props.n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(lhs, nse=nse, n_batch=props.n_batch, n_dense=props.n_dense)\nreturn data, indices, lhs, rhs\n@@ -1141,7 +1151,7 @@ class BCOOTest(jtu.JaxTestCase):\ndef args_maker():\nlhs = rng_sparse(lhs_shape, dtype)\nrhs = rng(rhs_shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(lhs, n_batch=0, n_dense=0))\n+ nse = sparse.util._count_stored_elements(lhs, n_batch=0, n_dense=0)\nlhs_bcoo = sparse_bcoo.bcoo_fromdense(lhs, nse=nse, index_dtype=jnp.int32)\nreturn lhs_bcoo, lhs, rhs\n@@ -1186,7 +1196,8 @@ class BCOOTest(jtu.JaxTestCase):\ndef args_maker():\nlhs = rng_sparse(lhs_shape, dtype)\nrhs = rng(rhs_shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(lhs, n_batch=n_batch, n_dense=0))\n+ nse = sparse.util._count_stored_elements(lhs, n_batch=n_batch,\n+ n_dense=0)\nlhs_bcoo = sparse_bcoo.bcoo_fromdense(lhs, n_batch=n_batch, nse=nse,\nindex_dtype=jnp.int32)\nreturn lhs_bcoo, lhs, rhs\n@@ -1243,7 +1254,8 @@ class BCOOTest(jtu.JaxTestCase):\nrng_sparse = rand_sparse(self.rng())\nlhs = rng_sparse(lhs_shape, dtype)\nrhs = rng(rhs_shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(lhs, n_batch=n_batch, n_dense=0))\n+ nse = sparse.util._count_stored_elements(lhs, n_batch=n_batch,\n+ n_dense=0)\nlhs_bcoo = sparse_bcoo.bcoo_fromdense(lhs, n_batch=n_batch, nse=nse,\nindex_dtype=jnp.int32)\ndimension_numbers = ((lhs_contracting, rhs_contracting), ([], []))\n@@ -1334,7 +1346,8 @@ class BCOOTest(jtu.JaxTestCase):\ndef args_maker():\nlhs = rng_sparse(lhs_shape, props.dtype)\nrhs = rng(rhs_shape, props.dtype)\n- nse = int(sparse_bcoo._bcoo_nse(rhs, n_batch=props.n_batch, n_dense=props.n_dense))\n+ nse = sparse.util._count_stored_elements(rhs, n_batch=props.n_batch,\n+ n_dense=props.n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(\nrhs, nse=nse, n_batch=props.n_batch, n_dense=props.n_dense)\nreturn data, indices, lhs, rhs\n@@ -1377,7 +1390,8 @@ class BCOOTest(jtu.JaxTestCase):\nrng_sparse = rand_sparse(self.rng())\nX = rng_sparse(lhs_shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(X, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(X, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(X, nse=nse, n_batch=n_batch, n_dense=n_dense)\nY = rng(rhs_shape, dtype)\n@@ -1419,7 +1433,8 @@ class BCOOTest(jtu.JaxTestCase):\nrng_sparse = rand_sparse(self.rng())\nX = rng_sparse(lhs_shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(X, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(X, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(X, nse=nse, n_batch=n_batch, n_dense=n_dense)\nY = rng(rhs_shape, dtype)\n@@ -1971,7 +1986,8 @@ class BCOOTest(jtu.JaxTestCase):\ndef test_bcoo_reduce_sum(self, shape, dtype, n_batch, n_dense, axes):\nrng = rand_sparse(self.rng())\nM = rng(shape, dtype)\n- nse = int(sparse_bcoo._bcoo_nse(M, n_batch=n_batch, n_dense=n_dense))\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)\ndata_out, indices_out, shape_out = sparse_bcoo._bcoo_reduce_sum(\ndata, indices, spinfo=BCOOInfo(shape), axes=axes)\n@@ -2539,5 +2555,43 @@ class SparseSolverTest(jtu.JaxTestCase):\nself._CompileAndCheck(sparse_solve, args_maker)\n+class SparseUtilTest(jtu.JaxTestCase):\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"dtype_{}_nbatch={}_ndense={}_nse={}\".format(\n+ dtype, n_batch, n_dense, expected_nse),\n+ \"dtype\": dtype, \"n_batch\": n_batch, \"n_dense\": n_dense,\n+ \"expected_nse\": expected_nse}\n+ for n_batch, n_dense, expected_nse in\n+ [(0, 0, 4), (1, 0, 2), (0, 1, 2), (2, 0, 1), (1, 1, 1), (0, 2, 1)]\n+ for dtype in all_dtypes))\n+ def test_count_stored_elements(self, dtype, n_batch, n_dense, expected_nse):\n+ \"\"\"Test counting nse.\"\"\"\n+ mat = np.array([[1, 0, 2, 0], [0, 0, 0, 0], [0, 3, 0, 4]], dtype=dtype)\n+ actual_nse = sparse.util._count_stored_elements(\n+ mat, n_batch=n_batch, n_dense=n_dense)\n+ self.assertEqual(expected_nse, actual_nse)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"dtype_{}_nbatch={}_ndense={}_nse={}\".format(\n+ dtype, n_batch, n_dense, expected_nse),\n+ \"dtype\": dtype, \"n_batch\": n_batch, \"n_dense\": n_dense,\n+ \"expected_nse\": expected_nse}\n+ for n_batch, n_dense, expected_nse in\n+ [(0, 0, 14), (1, 0, np.array([6, 8])), (0, 1, 9),\n+ (2, 0, np.array([[3, 3], [4, 4]]))]\n+ for dtype in all_dtypes))\n+ def test_count_stored_elements_per_batch(self, dtype, n_batch, n_dense,\n+ expected_nse):\n+ \"\"\"Test counting nse.\"\"\"\n+ mat = np.array([[[[1, 0, 0, 0], [0, 0, 0, 0], [0, 2, 0, 3]],\n+ [[0, 1, 2, 0], [0, 0, 0, 0], [0, 0, 0, 3]]],\n+ [[[1, 0, 2, 0], [0, 0, 0, 0], [0, 3, 0, 4]],\n+ [[0, 0, 0, 1], [0, 0, 2, 0], [3, 0, 0, 4]]]], dtype=dtype)\n+ actual_nse = sparse.util._count_stored_elements_per_batch(\n+ mat, n_batch=n_batch, n_dense=n_dense)\n+ self.assertArraysEqual(expected_nse, actual_nse)\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Move `_bcoo_nse` to sparse util.
PiperOrigin-RevId: 476263483 |
260,424 | 22.09.2022 15:23:54 | -3,600 | 7078f81dd00646b0236463cf81e2ad1bfb08a008 | Checkify: misc improvements.
err.throw == check_error(err) -> meaning they have the same behavior
under checkify now
"divided by zero" -> "division by zero"
add validation that check_error only takes args of type Error | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -110,8 +110,14 @@ class Error:\nreturn None\ndef throw(self):\n- \"\"\"Throw ValueError with error message if error happened.\"\"\"\n- err = self.get()\n+ check_error(self)\n+\n+ def __str__(self):\n+ return f'Error({self.get()})'\n+\n+\n+def raise_error(error):\n+ err = error.get()\nif err:\nraise ValueError(err)\n@@ -142,7 +148,6 @@ class CheckifyTracer(core.Tracer):\ndef __init__(self, trace, val):\nself._trace = trace\nself.val = val\n- core.get_aval(val), val\naval = property(lambda self: core.get_aval(self.val))\nfull_lower = lambda self: self\n@@ -457,6 +462,10 @@ def check_error(error: Error) -> None:\n>>> # can re-checkify\n>>> error, _ = checkify.checkify(with_inner_jit)(-1)\n\"\"\"\n+ if not isinstance(error, Error):\n+ raise ValueError('check_error takes an Error as argument, '\n+ f'got type {type(error)} instead.')\n+\nif np.shape(error.err):\nerr, code, payload = _reduce_any_error(error.err, error.code, error.payload)\nelse:\n@@ -470,7 +479,7 @@ assert_p.multiple_results = True # zero results\n@assert_p.def_impl\ndef assert_impl(err, code, payload, *, msgs):\n- Error(err, code, msgs, payload).throw()\n+ raise_error(Error(err, code, msgs, payload))\nreturn []\nCheckEffect = object()\n@@ -564,7 +573,7 @@ def div_error_check(error, enabled_errors, x, y):\n\"\"\"Checks for division by zero and NaN.\"\"\"\nif ErrorCategory.DIV in enabled_errors:\nany_zero = jnp.any(jnp.equal(y, 0))\n- msg = f'divided by zero at {summary()}'\n+ msg = f'division by zero at {summary()}'\nerror = assert_func(error, any_zero, msg, None)\nreturn nan_error_check(lax.div_p, error, enabled_errors, x, y)\nerror_checks[lax.div_p] = div_error_check\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -109,7 +109,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, _ = checked_f(jnp.ones((3,)), jnp.array([1., 0., 1.]))\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"divided by zero\")\n+ self.assertStartsWith(err.get(), \"division by zero\")\nerr, _ = checked_f(jnp.array([1, jnp.inf, 1]), jnp.array([1, jnp.inf, 1]))\nself.assertIsNotNone(err.get())\n@@ -281,7 +281,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, (ch_out_carry, ch_outs) = checked_f(carry, xs)\nout_carry, outs = f(carry, xs)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"divided by zero\")\n+ self.assertStartsWith(err.get(), \"division by zero\")\nself.assertArraysEqual(ch_outs, outs)\nself.assertArraysEqual(ch_out_carry, out_carry)\n@@ -290,7 +290,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, (ch_out_carry, ch_outs) = checked_f(carry, xs)\nout_carry, outs = f(carry, xs)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"divided by zero\")\n+ self.assertStartsWith(err.get(), \"division by zero\")\nself.assertArraysEqual(ch_outs, outs)\nself.assertArraysEqual(ch_out_carry, out_carry)\n@@ -321,7 +321,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, ch_out = checked_f(init_val)\nout = f(init_val)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"divided by zero\")\n+ self.assertStartsWith(err.get(), \"division by zero\")\nself.assertArraysEqual(ch_out, out)\n@jtu.skip_on_devices(\"tpu\")\n@@ -349,7 +349,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, ch_out = checked_f(init_val)\nout = f(init_val)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"divided by zero\")\n+ self.assertStartsWith(err.get(), \"division by zero\")\nself.assertArraysEqual(ch_out, out)\n@jtu.skip_on_devices(\"tpu\")\n@@ -369,13 +369,13 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ninit_val = 0.\nerr, _ = checked_f(init_val)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"divided by zero\")\n+ self.assertStartsWith(err.get(), \"division by zero\")\n# error on second cond\ninit_val = 1.\nerr, _ = checked_f(init_val)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"divided by zero\")\n+ self.assertStartsWith(err.get(), \"division by zero\")\n@jtu.skip_on_devices(\"tpu\")\ndef test_while_loop_body_and_cond_error(self):\n@@ -441,9 +441,9 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nb_err, _ = g(x, x)\nself.assertIsNotNone(u_err.get())\n- self.assertStartsWith(u_err.get(), \"divided by zero\")\n+ self.assertStartsWith(u_err.get(), \"division by zero\")\nself.assertIsNotNone(b_err.get())\n- self.assertStartsWith(b_err.get(), \"divided by zero\")\n+ self.assertStartsWith(b_err.get(), \"division by zero\")\ndef test_empty_enabled_errors(self):\ndef multi_errors(x):\n@@ -459,10 +459,10 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n@parameterized.named_parameters(\n(\"assert\", checkify.user_checks, \"must be negative!\"),\n- (\"div\", {checkify.ErrorCategory.DIV}, \"divided by zero\"),\n+ (\"div\", {checkify.ErrorCategory.DIV}, \"division by zero\"),\n(\"nan\", {checkify.ErrorCategory.NAN}, \"nan generated\"),\n(\"oob\", checkify.index_checks, \"out-of-bounds indexing\"),\n- (\"automatic_checks\", checkify.automatic_checks, \"divided by zero\"),\n+ (\"automatic_checks\", checkify.automatic_checks, \"division by zero\"),\n)\n@jtu.skip_on_devices(\"tpu\")\ndef test_enabled_errors(self, error_set, expected_error):\n@@ -625,7 +625,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nchecked_f = checkify.checkify(f, errors=checkify.float_checks)\nerr, _ = checked_f(jnp.ones((7, 3)))\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"divided by zero\")\n+ self.assertStartsWith(err.get(), \"division by zero\")\ndef test_multiple_payloads(self):\ndef f(x):\n@@ -651,7 +651,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ncf = checkify.checkify(f, errors=checkify.automatic_checks)\nerrs, _ = jax.vmap(cf)(jnp.ones((2, 1)), jnp.array([0, 100]))\nself.assertIsNotNone(errs.get())\n- self.assertIn(\"divided by zero\", errs.get())\n+ self.assertIn(\"division by zero\", errs.get())\nself.assertIn(\"index 100\", errs.get())\n@@ -895,7 +895,7 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nerr, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([5., 2., 4.]))\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"divided by zero\")\n+ self.assertStartsWith(err.get(), \"division by zero\")\nerr, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([5., 2., -4.]))\nself.assertIsNotNone(err.get())\n"
}
] | Python | Apache License 2.0 | google/jax | Checkify: misc improvements.
- err.throw == check_error(err) -> meaning they have the same behavior
under checkify now
- "divided by zero" -> "division by zero"
- add validation that check_error only takes args of type Error |
260,506 | 22.09.2022 21:33:07 | 25,200 | c823151771977e91bbb53a0a04885be7fbb659f4 | Allow transpose axes to be negative to match (undocumented) NumPy behavior | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -528,6 +528,7 @@ view of the input.\ndef transpose(a, axes=None):\n_stackable(a) or _check_arraylike(\"transpose\", a)\naxes = np.arange(ndim(a))[::-1] if axes is None else axes\n+ axes = tuple(_canonicalize_axis(i, ndim(a)) for i in axes)\nreturn lax.transpose(a, axes)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -2120,7 +2120,8 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfor dtype in default_dtypes\nfor shape in array_shapes\nfor arg_type in [\"splat\", \"value\"]\n- for perm in [None, tuple(np.random.RandomState(0).permutation(np.zeros(shape).ndim))]))\n+ for perm in [None, tuple(np.random.RandomState(0).permutation(np.zeros(shape).ndim)),\n+ tuple(np.random.RandomState(0).permutation(np.zeros(shape).ndim) - np.zeros(shape).ndim)]))\ndef testTransposeTuple(self, shape, dtype, perm, arg_type):\nrng = jtu.rand_some_zero(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\n"
}
] | Python | Apache License 2.0 | google/jax | Allow transpose axes to be negative to match (undocumented) NumPy behavior |
260,332 | 23.09.2022 12:11:56 | 25,200 | 4dd0d851393758c98b8002eea9d138e31b69f1f3 | add multihost pjit tests | [
{
"change_type": "MODIFY",
"old_path": "tests/multiprocess_gpu_test.py",
"new_path": "tests/multiprocess_gpu_test.py",
"diff": "@@ -17,16 +17,23 @@ import subprocess\nimport sys\nimport threading\nimport unittest\n+import functools\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n+import numpy as np\nimport jax\n+from jax import experimental\nfrom jax.config import config\nfrom jax._src import distributed\nimport jax.numpy as jnp\nfrom jax._src.lib import xla_extension_version\nfrom jax._src import test_util as jtu\n+from jax._src import util\n+from jax.experimental import global_device_array\n+from jax.experimental import maps\n+from jax.experimental import pjit\ntry:\nimport portpicker\n@@ -40,7 +47,6 @@ except ImportError:\nconfig.parse_flags_with_absl()\n-\n@unittest.skipIf(not portpicker, \"Test requires portpicker\")\nclass DistributedTest(jtu.JaxTestCase):\n@@ -170,6 +176,49 @@ class SlurmMultiNodeGpuTest(jtu.JaxTestCase):\nif pytest is not None:\npytestmark = pytest.mark.SlurmMultiNodeGpuTest\n+ def sorted_devices(self):\n+ devices = sorted(jax.devices(), key=lambda d: (d.id, d.host_id))\n+ if len(devices) != 16:\n+ raise unittest.SkipTest(\n+ \"Test assumes that it runs on 16 devices (2 nodes)\")\n+ return devices\n+\n+ def create_2d_non_contiguous_mesh(self):\n+ devices = self.sorted_devices()\n+ device_mesh = np.array([[devices[0], devices[2]],\n+ [devices[4], devices[6]],\n+ [devices[1], devices[3]],\n+ [devices[5], devices[7]],\n+ [devices[8], devices[10]],\n+ [devices[12], devices[14]],\n+ [devices[9], devices[11]],\n+ [devices[13], devices[15]]])\n+ # The mesh looks like this (the integers are process index):\n+ # 0 2\n+ # 4 6\n+ # 1 3\n+ # 5 7\n+ # 8 10\n+ # 12 14\n+ # 9 11\n+ # 13 15\n+ assert [d.id for d in device_mesh.flat\n+ ] == [0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15]\n+ return maps.Mesh(device_mesh, (\"x\", \"y\"))\n+\n+ def setUp(self):\n+ super().setUp()\n+ self.xmap_spmd_lowering_enabled = jax.config.experimental_xmap_spmd_lowering\n+ jax.config.update(\"experimental_xmap_spmd_lowering\", True)\n+ self.gda_enabled = jax.config.jax_parallel_functions_output_gda\n+ jax.config.update('jax_parallel_functions_output_gda', True)\n+\n+ def tearDown(self):\n+ jax.config.update(\"experimental_xmap_spmd_lowering\",\n+ self.xmap_spmd_lowering_enabled)\n+ jax.config.update('jax_parallel_functions_output_gda', self.gda_enabled)\n+ super().tearDown()\n+\ndef test_gpu_multi_node_initialize_and_psum(self):\n# Hookup the ENV vars expected to be set already in the SLURM environment\n@@ -224,5 +273,244 @@ class SlurmMultiNodeGpuTest(jtu.JaxTestCase):\nself.assertEqual(y[0], jax.device_count())\nprint(y)\n+ # TODO(sudhakarsingh27): To change/omit test in favor of using `Array`\n+ # since `GlobalDeviceArray` is going to be deprecated in the future\n+ def test_pjit_gda_multi_input_multi_output(self):\n+ jax.distributed.initialize()\n+ global_mesh = jtu.create_global_mesh((8, 2), (\"x\", \"y\"))\n+ global_input_shape = (16, 2)\n+ global_input_data = np.arange(\n+ util.prod(global_input_shape)).reshape(global_input_shape)\n+\n+ def cb(index):\n+ return global_input_data[index]\n+\n+ mesh_axes1 = experimental.PartitionSpec(\"x\", \"y\")\n+ gda1 = global_device_array.GlobalDeviceArray.from_callback(\n+ global_input_shape, global_mesh, mesh_axes1, cb)\n+ mesh_axes2 = experimental.PartitionSpec(\"x\")\n+ gda2 = global_device_array.GlobalDeviceArray.from_callback(\n+ global_input_shape, global_mesh, mesh_axes2, cb)\n+ mesh_axes3 = experimental.PartitionSpec((\"x\", \"y\"))\n+ gda3 = global_device_array.GlobalDeviceArray.from_callback(\n+ global_input_shape, global_mesh, mesh_axes3, cb)\n+\n+ with maps.Mesh(global_mesh.devices, global_mesh.axis_names):\n+\n+ @functools.partial(\n+ pjit.pjit,\n+ # `FROM_GDA` will be replicated for all the inputs.\n+ in_axis_resources=pjit.FROM_GDA,\n+ out_axis_resources=(mesh_axes1, None, mesh_axes2))\n+ def f(x, y, z):\n+ return x @ x.T, y, z\n+\n+ out1, out2, out3 = f(gda1, gda2, gda3)\n+\n+ self.assertIsInstance(out1, global_device_array.GlobalDeviceArray)\n+ self.assertEqual(out1.shape, (16, 16))\n+ self.assertEqual(out1.local_shards[0].data.shape, (2, 8))\n+ self.assertDictEqual(out1.mesh.shape, {\"x\": 8, \"y\": 2})\n+ expected_matrix_mul = global_input_data @ global_input_data.T\n+ for s in out1.local_shards:\n+ np.testing.assert_array_equal(np.asarray(s.data),\n+ expected_matrix_mul[s.index])\n+\n+ self.assertIsInstance(out2, global_device_array.GlobalDeviceArray)\n+ self.assertEqual(out2.shape, (16, 2))\n+ self.assertEqual(out2.local_shards[0].data.shape, (16, 2))\n+ for s in out2.local_shards:\n+ np.testing.assert_array_equal(np.asarray(s.data), global_input_data)\n+\n+ self.assertIsInstance(out3, global_device_array.GlobalDeviceArray)\n+ self.assertEqual(out3.shape, (16, 2))\n+ self.assertEqual(out3.local_shards[0].data.shape, (2, 2))\n+ for s in out3.local_shards:\n+ np.testing.assert_array_equal(np.asarray(s.data),\n+ global_input_data[s.index])\n+\n+ # TODO(sudhakarsingh27): To change/omit test in favor of using `Array`\n+ # since `GlobalDeviceArray` is going to be deprecated in the future\n+ def test_pjit_gda_non_contiguous_mesh(self):\n+ jax.distributed.initialize()\n+ devices = self.sorted_devices()\n+ mesh_devices = np.array(devices[0:8:2] + devices[1:8:2] + devices[8:16:2] +\n+ devices[9:16:2])\n+ # The device order in the below mesh is:\n+ # [0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15]\n+ # each having the following process index:\n+ # The process-gpu mapping is random: @sudhakarsingh27 to figure out why so\n+ # and the data is:\n+ # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n+ global_mesh = maps.Mesh(mesh_devices, (\"x\",))\n+ global_input_shape = (16,)\n+ mesh_axes = experimental.PartitionSpec(\"x\")\n+ global_input_data = np.arange(\n+ util.prod(global_input_shape)).reshape(global_input_shape)\n+\n+ def cb(index):\n+ return global_input_data[index]\n+\n+ gda1 = global_device_array.GlobalDeviceArray.from_callback(\n+ global_input_shape, global_mesh, mesh_axes, cb)\n+\n+ # device_id -> (index, replica_id)\n+ expected_idx_rid = {\n+ 0: ((slice(0, 1),), 0),\n+ 1: ((slice(4, 5),), 0),\n+ 2: ((slice(1, 2),), 0),\n+ 3: ((slice(5, 6),), 0),\n+ 4: ((slice(2, 3),), 0),\n+ 5: ((slice(6, 7),), 0),\n+ 6: ((slice(3, 4),), 0),\n+ 7: ((slice(7, 8),), 0),\n+ 8: ((slice(8, 9),), 0),\n+ 9: ((slice(12, 13),), 0),\n+ 10: ((slice(9, 10),), 0),\n+ 11: ((slice(13, 14),), 0),\n+ 12: ((slice(10, 11),), 0),\n+ 13: ((slice(14, 15),), 0),\n+ 14: ((slice(11, 12),), 0),\n+ 15: ((slice(15, 16),), 0),\n+ }\n+\n+ with maps.Mesh(global_mesh.devices, global_mesh.axis_names):\n+ f = pjit.pjit(lambda x: x,\n+ in_axis_resources=pjit.FROM_GDA,\n+ out_axis_resources=mesh_axes)\n+ out = f(gda1)\n+ for s in out.local_shards:\n+ device_id = s.device.id\n+ expected_index = expected_idx_rid[device_id][0]\n+ expected_replica_id = expected_idx_rid[device_id][1]\n+ self.assertEqual(s.index, expected_index)\n+ self.assertEqual(s.replica_id, expected_replica_id)\n+ self.assertEqual(s.data.shape, (1,))\n+ np.testing.assert_array_equal(np.asarray(s.data),\n+ global_input_data[expected_index])\n+\n+ # TODO(sudhakarsingh27): To change/omit test in favor of using `Array`\n+ # since `GlobalDeviceArray` is going to be deprecated in the future\n+ def test_pjit_gda_non_contiguous_mesh_2d(self):\n+ jax.distributed.initialize()\n+ global_mesh = self.create_2d_non_contiguous_mesh()\n+ global_input_shape = (16, 2)\n+ mesh_axes = experimental.PartitionSpec(\"x\", \"y\")\n+ global_input_data = np.arange(\n+ util.prod(global_input_shape)).reshape(global_input_shape)\n+\n+ def cb(index):\n+ return global_input_data[index]\n+\n+ gda1 = global_device_array.GlobalDeviceArray.from_callback(\n+ global_input_shape, global_mesh, mesh_axes, cb)\n+\n+ # device_id -> (index, replica_id)\n+ expected_idx_rid = {\n+ 0: ((slice(0, 2), slice(0, 1)), 0),\n+ 1: ((slice(4, 6), slice(0, 1)), 0),\n+ 2: ((slice(0, 2), slice(1, 2)), 0),\n+ 3: ((slice(4, 6), slice(1, 2)), 0),\n+ 4: ((slice(2, 4), slice(0, 1)), 0),\n+ 5: ((slice(6, 8), slice(0, 1)), 0),\n+ 6: ((slice(2, 4), slice(1, 2)), 0),\n+ 7: ((slice(6, 8), slice(1, 2)), 0),\n+ 8: ((slice(8, 10), slice(0, 1)), 0),\n+ 9: ((slice(12, 14), slice(0, 1)), 0),\n+ 10: ((slice(8, 10), slice(1, 2)), 0),\n+ 11: ((slice(12, 14), slice(1, 2)), 0),\n+ 12: ((slice(10, 12), slice(0, 1)), 0),\n+ 13: ((slice(14, 16), slice(0, 1)), 0),\n+ 14: ((slice(10, 12), slice(1, 2)), 0),\n+ 15: ((slice(14, 16), slice(1, 2)), 0),\n+ }\n+\n+ with global_mesh:\n+ f = pjit.pjit(lambda x: x,\n+ in_axis_resources=pjit.FROM_GDA,\n+ out_axis_resources=mesh_axes)\n+ out = f(gda1)\n+\n+ for s in out.local_shards:\n+ device_id = s.device.id\n+ expected_index = expected_idx_rid[device_id][0]\n+ expected_replica_id = expected_idx_rid[device_id][1]\n+ self.assertEqual(s.index, expected_index)\n+ self.assertEqual(s.replica_id, expected_replica_id)\n+ self.assertEqual(s.data.shape, (2, 1))\n+ np.testing.assert_array_equal(np.asarray(s.data),\n+ global_input_data[expected_index])\n+\n+ with global_mesh:\n+ f = pjit.pjit(lambda x: x,\n+ in_axis_resources=experimental.PartitionSpec(None),\n+ out_axis_resources=mesh_axes)\n+ # Fully replicated values allows a non-contiguous mesh.\n+ out = f(global_input_data)\n+ self.assertIsInstance(out, global_device_array.GlobalDeviceArray)\n+\n+ with global_mesh:\n+ f = pjit.pjit(lambda x: x,\n+ in_axis_resources=None,\n+ out_axis_resources=mesh_axes)\n+ # Fully replicated values allows a non-contiguous mesh.\n+ out = f(global_input_data)\n+ self.assertIsInstance(out, global_device_array.GlobalDeviceArray)\n+\n+ gda2 = global_device_array.GlobalDeviceArray.from_callback(\n+ global_input_shape, global_mesh, experimental.PartitionSpec(None), cb)\n+\n+ with global_mesh:\n+ f = pjit.pjit(lambda x, y: (x, y),\n+ in_axis_resources=(None, None),\n+ out_axis_resources=(mesh_axes, mesh_axes))\n+ # Fully replicated values + GDA allows a non-contiguous mesh.\n+ out1, out2 = f(global_input_data, gda2)\n+ self.assertIsInstance(out1, global_device_array.GlobalDeviceArray)\n+ self.assertIsInstance(out2, global_device_array.GlobalDeviceArray)\n+\n+ # TODO(sudhakarsingh27): To change/omit test in favor of using `Array`\n+ # since `GlobalDeviceArray` is going to be deprecated in the future\n+ def test_pjit_gda_non_contiguous_mesh_2d_aot(self):\n+ jax.distributed.initialize()\n+ global_mesh = self.create_2d_non_contiguous_mesh()\n+ global_input_shape = (8, 2)\n+ mesh_axes = experimental.PartitionSpec(\"x\", \"y\")\n+ global_input_data = np.arange(\n+ util.prod(global_input_shape)).reshape(global_input_shape)\n+ gda1 = global_device_array.GlobalDeviceArray.from_callback(\n+ global_input_shape, global_mesh, mesh_axes,\n+ lambda idx: global_input_data[idx])\n+\n+ with global_mesh:\n+ f = pjit.pjit(lambda x, y: (x, y),\n+ in_axis_resources=experimental.PartitionSpec(\"x\", \"y\"),\n+ out_axis_resources=experimental.PartitionSpec(\"x\", \"y\"))\n+ inp_aval = jax.ShapedArray((8, 2), jnp.int32)\n+ # `ShapedArray` is considered global when lowered and compiled.\n+ # Hence it can bypass the contiguous mesh restriction.\n+ compiled = f.lower(inp_aval, gda1, _global_avals=True).compile()\n+ out1, out2 = compiled(gda1, gda1)\n+ self.assertIsInstance(out1, global_device_array.GlobalDeviceArray)\n+ self.assertEqual(out1.shape, (8, 2))\n+ self.assertIsInstance(out2, global_device_array.GlobalDeviceArray)\n+ self.assertEqual(out2.shape, (8, 2))\n+\n+ # TODO(sudhakarsingh27): To change/omit test in favor of using `Array`\n+ # since `GlobalDeviceArray` is going to be deprecated in the future\n+ def test_pjit_gda_eval_shape(self):\n+ jax.distributed.initialize()\n+\n+ with jtu.create_global_mesh((16,), (\"x\")):\n+\n+ @functools.partial(pjit.pjit,\n+ in_axis_resources=experimental.PartitionSpec(None),\n+ out_axis_resources=experimental.PartitionSpec(\"x\"))\n+ def f():\n+ return jnp.zeros([32, 10])\n+\n+ self.assertEqual(f().shape, (32, 10))\n+ self.assertEqual(jax.eval_shape(f).shape, (32, 10))\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | add multihost pjit tests |
260,631 | 25.09.2022 20:53:45 | 25,200 | ec15e83018087d3379a4c71150cf632ae11d4d2c | Wraps calls to lax.xeinsum and _einsum in a named call with their 'spec', the string specifying the computation. Makes xprof traces more interpretable. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -2897,8 +2897,10 @@ def einsum(*operands, out=None, optimize='optimal', precision=None,\nif out is not None:\nraise NotImplementedError(\"The 'out' argument to jnp.einsum is not supported.\")\n- if (_use_xeinsum or isinstance(operands[0], str) and '{' in operands[0]):\n- return lax.xeinsum(*operands)\n+ spec = operands[0] if isinstance(operands[0], str) else None\n+\n+ if (_use_xeinsum or spec is not None and '{' in spec):\n+ return jax.named_call(lax.xeinsum, name=spec)(*operands)\noptimize = 'optimal' if optimize is True else optimize\n# using einsum_call=True here is an internal api for opt_einsum\n@@ -2917,7 +2919,10 @@ def einsum(*operands, out=None, optimize='optimal', precision=None,\n*operands, einsum_call=True, use_blas=True, optimize=optimize)\ncontractions = tuple((a, frozenset(b), c) for a, b, c, *_ in contractions)\n- return _einsum(operands, contractions, precision)\n+\n+ _einsum_computation = jax.named_call(\n+ _einsum, name=spec) if spec is not None else _einsum\n+ return _einsum_computation(operands, contractions, precision)\n# Enable other modules to override einsum_contact_path.\n# Indexed by the type of the non constant dimension\n"
}
] | Python | Apache License 2.0 | google/jax | - Wraps calls to lax.xeinsum and _einsum in a named call with their 'spec', the string specifying the computation. Makes xprof traces more interpretable.
PiperOrigin-RevId: 476796185 |
260,424 | 23.09.2022 14:30:49 | -3,600 | 78ecc1442c5d853e0d4b2d1b9471f3a78cadf51f | Lowerable checks!! | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/config.py",
"new_path": "jax/_src/config.py",
"diff": "@@ -909,6 +909,15 @@ config.define_bool_state(\nupgrade=True,\nhelp='Enable eager-mode pmap when jax_disable_jit is activated.')\n+config.define_bool_state(\n+ name='jax_unsafe_xla_runtime_errors',\n+ default=False,\n+ help=('Enable XLA runtime errors for jax.experimental.checkify.checks '\n+ 'on CPU and GPU. These errors are async, might get lost and not '\n+ 'very readable but they DO crash the computation and enable you '\n+ 'to write jittable checks without needing to checkify.')\n+)\n+\n@contextlib.contextmanager\ndef explicit_device_put_scope() -> Iterator[None]:\n\"\"\"Indicates that the current context is an explicit device_put*() call.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | Lowerable checks!! |
260,380 | 26.09.2022 17:14:09 | -3,600 | 8bcf358fdef98771ae66bd61182ed803b01e46bd | Remove unused _remat_static_argnums import. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -73,7 +73,6 @@ from jax._src.lib.xla_bridge import (device_count, local_device_count, devices,\nprocess_count, host_id, host_ids,\nhost_count, default_backend)\nfrom jax.ad_checkpoint import checkpoint_policies, checkpoint as new_checkpoint\n-from jax._src.ad_checkpoint import _remat_static_argnums\nfrom jax.core import ShapedArray, raise_to_shaped\nfrom jax.custom_batching import custom_vmap\nfrom jax.custom_derivatives import (closure_convert, custom_gradient, custom_jvp,\n"
}
] | Python | Apache License 2.0 | google/jax | Remove unused _remat_static_argnums import. |
260,424 | 23.09.2022 15:10:41 | -3,600 | 27e3981d52a0f18a553336d56d56d27320d0356a | lowerable errors behind a config flag. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -489,17 +489,47 @@ CheckEffect = object()\ndef assert_abstract_eval(err, code, payload, *, msgs):\nreturn [], {CheckEffect}\n-def assert_lowering_rule(*a, **k):\n- # TODO(lenamartens): actually throw an error through emit_python_callable\n# TODO(lenamartens) add in-depth error explanation to link to in module docs.\n- raise ValueError('Cannot abstractly evaluate a checkify.check which was not'\n+functionalization_error = ValueError(\n+ 'Cannot abstractly evaluate a checkify.check which was not'\n' functionalized. This probably means you tried to stage'\n' (jit/scan/pmap/...) a `check` without functionalizing it'\n' through `checkify.checkify`.'\n)\n-mlir.register_lowering(assert_p, assert_lowering_rule)\n+\n+def python_err(msgs, err, code, payload):\n+ error = Error(err, code, msgs, payload)\n+ check_error(error)\n+ return []\n+\n+def assert_lowering_rule(ctx, err, code, payload, *, msgs):\n+ if not config.jax_experimental_unsafe_xla_runtime_errors:\n+ raise functionalization_error\n+\n+ out_op, token_out, keep_alive = mlir.emit_python_callback(\n+ ctx, callback=lambda *a: python_err(msgs, *a),\n+ token=ctx.tokens_in.get(CheckEffect)[0],\n+ operands=[err, code, payload],\n+ operand_avals=list(ctx.avals_in),\n+ result_avals=list(ctx.avals_out),\n+ has_side_effect=True)\n+ ctx.set_tokens_out(ctx.tokens_in.update_tokens(\n+ mlir.TokenSet({CheckEffect: token_out})))\n+ ctx.module_context.add_keepalive(keep_alive)\n+ return out_op\n+\n+def assert_lowering_rule_unsupported(*a, **k):\n+ raise functionalization_error\n+\n+mlir.register_lowering(assert_p, assert_lowering_rule_unsupported,\n+ platform='tpu')\n+mlir.register_lowering(assert_p, assert_lowering_rule,\n+ platform='cpu')\n+mlir.register_lowering(assert_p, assert_lowering_rule,\n+ platform='gpu')\nmlir.lowerable_effects.add(CheckEffect)\ncf.allowed_effects.add(CheckEffect)\n+core.ordered_effects.add(CheckEffect)\ndef assert_batching_rule(batched_args, batch_dims, *, msgs):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/config.py",
"new_path": "jax/_src/config.py",
"diff": "@@ -910,12 +910,13 @@ config.define_bool_state(\nhelp='Enable eager-mode pmap when jax_disable_jit is activated.')\nconfig.define_bool_state(\n- name='jax_unsafe_xla_runtime_errors',\n+ name='jax_experimental_unsafe_xla_runtime_errors',\ndefault=False,\nhelp=('Enable XLA runtime errors for jax.experimental.checkify.checks '\n- 'on CPU and GPU. These errors are async, might get lost and not '\n- 'very readable but they DO crash the computation and enable you '\n- 'to write jittable checks without needing to checkify.')\n+ 'on CPU and GPU. These errors are async, might get lost and are not '\n+ 'very readable. But, they crash the computation and enable you '\n+ 'to write jittable checks without needing to checkify. Does not '\n+ 'work under pmap/pjit.')\n)\n@contextlib.contextmanager\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -22,6 +22,7 @@ import numpy as np\nimport jax\nfrom jax import lax\nimport jax._src.test_util as jtu\n+from jax._src.lib import xla_extension\nfrom jax.config import config\nfrom jax.experimental import checkify\nfrom jax.experimental import pjit\n@@ -905,5 +906,26 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"value needs to be less than 6\")\n+class LowerableChecksTest(jtu.JaxTestCase):\n+ def setUp(self):\n+ super().setUp()\n+ self.prev = config.jax_experimental_unsafe_xla_runtime_errors\n+ config.update(\"jax_experimental_unsafe_xla_runtime_errors\", True)\n+\n+ def tearDown(self):\n+ config.update(\"jax_experimental_unsafe_xla_runtime_errors\", self.prev)\n+ super().tearDown()\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_jit(self):\n+ @jax.jit\n+ def f(x):\n+ checkify.check(x > 0, \"x needs to be positive\")\n+ return x\n+\n+ with self.assertRaisesRegex(xla_extension.XlaRuntimeError,\n+ \"x needs to be positive\"):\n+ f(-1.)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | lowerable errors behind a config flag. |
260,447 | 26.09.2022 16:01:47 | 25,200 | 71bcabe4992e41f0056a47541bf57fd3446d815d | [sparse] Add BCSR format template. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/__init__.py",
"new_path": "jax/experimental/sparse/__init__.py",
"diff": "@@ -217,6 +217,9 @@ from jax.experimental.sparse.bcoo import (\nBCOO as BCOO,\n)\n+from jax.experimental.sparse.bcsr import (\n+ BCSR as BCSR,\n+)\nfrom jax.experimental.sparse.api import (\nempty as empty,\neye as eye,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/api.py",
"new_path": "jax/experimental/sparse/api.py",
"diff": "@@ -37,6 +37,7 @@ from jax import core\nfrom jax import tree_util\nfrom jax.experimental.sparse._base import JAXSparse\nfrom jax.experimental.sparse.bcoo import BCOO\n+from jax.experimental.sparse.bcsr import BCSR\nfrom jax.experimental.sparse.coo import COO\nfrom jax.experimental.sparse.csr import CSR, CSC\nfrom jax.experimental.sparse.util import _coo_extract\n@@ -116,7 +117,7 @@ def empty(shape, dtype=None, index_dtype='int32', sparse_format='bcoo', **kwds):\nReturns:\nmat: empty sparse matrix.\n\"\"\"\n- formats = {'bcoo': BCOO, 'coo': COO, 'csr': CSR, 'csc': CSC}\n+ formats = {'bcsr': BCSR, 'bcoo': BCOO, 'coo': COO, 'csr': CSR, 'csc': CSC}\nif sparse_format not in formats:\nraise ValueError(f\"sparse_format={sparse_format!r} not recognized; \"\nf\"must be one of {list(formats.keys())}\")\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/sparse/bcsr.py",
"diff": "+# Copyright 2022 The JAX Authors.\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+\"\"\"BCSR (Bached compressed row) matrix object and associated primitives.\"\"\"\n+\n+from typing import Tuple\n+\n+from jax import core\n+from jax.experimental.sparse._base import JAXSparse\n+from jax.experimental.sparse.util import _safe_asarray\n+import jax.numpy as jnp\n+from jax.util import split_list\n+\n+Shape = Tuple[int, ...]\n+\n+\n+class BCSR(JAXSparse):\n+ \"\"\"Experimental batched CSR matrix implemented in JAX.\"\"\"\n+\n+ data: jnp.ndarray\n+ indices: jnp.ndarray\n+ indptr: jnp.ndarray\n+ shape: Shape\n+ nse = property(lambda self: self.indices.shape[-1])\n+ dtype = property(lambda self: self.data.dtype)\n+ n_batch = property(lambda self: self.indices.ndim - 1)\n+ n_sparse = property(lambda _: 2)\n+ n_dense = property(lambda self: self.data.ndim - self.indices.ndim)\n+\n+ @property\n+ def _sparse_shape(self):\n+ return tuple(self.shape[self.n_batch:self.n_batch + 2])\n+\n+ def __init__(self, args, *, shape):\n+ # JAX transforms will sometimes instantiate pytrees with null values, so we\n+ # must catch that in the initialization of inputs.\n+ self.data, self.indices, self.indptr = _safe_asarray(args)\n+ super().__init__(args, shape=shape)\n+\n+ def __repr__(self):\n+ name = self.__class__.__name__\n+ try:\n+ nse = self.nse\n+ n_batch = self.n_batch\n+ n_dense = self.n_dense\n+ dtype = self.dtype\n+ shape = list(self.shape)\n+ except Exception: # pylint: disable=broad-except\n+ repr_ = f\"{name}(<invalid>)\"\n+ else:\n+ extra = f\", nse={nse}\"\n+ if n_batch: extra += f\", n_batch={n_batch}\"\n+ if n_dense: extra += f\", n_dense={n_dense}\"\n+ repr_ = f\"{name}({dtype}{shape}{extra})\"\n+ if isinstance(self.data, core.Tracer):\n+ repr_ = f\"{type(self.data).__name__}[{repr_}]\"\n+ return repr_\n+\n+ def transpose(self, *args, **kwargs):\n+ raise NotImplementedError(\"Tranpose is not implemented.\")\n+\n+ def tree_flatten(self):\n+ return (self.data, self.indices, self.indptr), {}\n+\n+ @classmethod\n+ def _empty(cls, shape, *, dtype=None, index_dtype='int32', n_dense=0,\n+ n_batch=0, nse=0):\n+ \"\"\"Create an empty BCSR instance. Public method is sparse.empty().\"\"\"\n+ shape = tuple(shape)\n+ if n_dense < 0 or n_batch < 0 or nse < 0:\n+ raise ValueError(f\"Invalid inputs: shape={shape}, n_dense={n_dense},\"\n+ f\"n_batch={n_batch}, nse={nse}\")\n+ n_sparse = len(shape) - n_dense - n_batch\n+ if n_sparse != 2:\n+ raise ValueError(\"BCSR sparse.empty: must have 2 sparse dimensions.\")\n+ batch_shape, sparse_shape, dense_shape = split_list(shape,\n+ [n_batch, n_sparse])\n+ data = jnp.zeros((*batch_shape, nse, *dense_shape), dtype)\n+ indices = jnp.full((*batch_shape, nse), jnp.array(sparse_shape[1]),\n+ index_dtype)\n+ indptr = jnp.zeros((*batch_shape, sparse_shape[0] + 1), index_dtype)\n+ return cls((data, indices, indptr), shape=shape)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -2275,6 +2275,18 @@ class SparseGradTest(jtu.JaxTestCase):\nclass SparseObjectTest(jtu.JaxTestCase):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_{cls.__name__}\", \"cls\": cls}\n+ for cls in [sparse.CSR, sparse.CSC, sparse.COO, sparse.BCOO, sparse.BCSR])\n+ def test_pytree_flattening(self, cls):\n+ sparse_format = cls.__name__.lower()\n+ M = sparse.empty((2, 4), sparse_format=sparse_format)\n+ self.assertIsInstance(M, cls)\n+ buffers, tree = tree_util.tree_flatten(M)\n+ M_out = tree_util.tree_unflatten(tree, buffers)\n+ self.assertEqual(M.dtype, M_out.dtype)\n+ self.assertEqual(M.shape, M_out.shape)\n+ self.assertEqual(M.nse, M_out.nse)\n@parameterized.named_parameters(\n{\"testcase_name\": f\"_{cls.__name__}\", \"cls\": cls}\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Add BCSR format template.
PiperOrigin-RevId: 477013899 |
260,510 | 26.09.2022 17:29:08 | 25,200 | 1d895b2c85e17b9f563cd41d9a340528179d29aa | Fix lax imports | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -36,6 +36,8 @@ from jax._src import util\nfrom jax._src import source_info_util\nfrom jax._src import traceback_util\nfrom jax._src.api_util import flatten_fun, shaped_abstractify\n+from jax._src.lax import lax as lax_internal\n+from jax._src.lax import convolution as lax_convolution\nfrom jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.traceback_util import api_boundary\nfrom jax._src.util import (unzip2, wraps, split_list, partition_list, safe_map,\n@@ -60,12 +62,12 @@ def nothing_saveable(*_, **__) -> bool:\ndef checkpoint_dots(prim, *_, **__) -> bool:\n# Matrix multiplies are expensive, so let's save them (and nothing else).\n- return prim in {lax.lax.dot_general_p,\n- lax.convolution.conv_general_dilated_p}\n+ return prim in {lax_internal.dot_general_p,\n+ lax_convolution.conv_general_dilated_p}\ndef dot_with_no_batch_dims(prim, *_, **params) -> bool:\n# This is a useful heuristic for transformers.\n- if prim is lax.lax.dot_general_p:\n+ if prim is lax_internal.dot_general_p:\n(_, _), (lhs_b, rhs_b) = params['dimension_numbers']\nif not lhs_b and not rhs_b:\nreturn True\n@@ -439,8 +441,8 @@ def remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\nad.primitive_jvps[remat_p] = remat_jvp\nremat_allowed_effects: Set[core.Effect] = set()\n-remat_allowed_effects.add(lax.lax.InOutFeedEffect.Infeed)\n-remat_allowed_effects.add(lax.lax.InOutFeedEffect.Outfeed)\n+remat_allowed_effects.add(lax_internal.InOutFeedEffect.Infeed)\n+remat_allowed_effects.add(lax_internal.InOutFeedEffect.Outfeed)\ndef remat_partial_eval(trace, *tracers, jaxpr, **params):\nassert not jaxpr.constvars\n"
}
] | Python | Apache License 2.0 | google/jax | Fix lax imports |
260,335 | 23.09.2022 14:21:18 | 25,200 | 1e7ca8f77a739b93b156506bd6eb7b13aa504781 | fix bug in djax type signature inference logic | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -2095,7 +2095,9 @@ def infer_lambda_input_type(\nidxs, implicit_types = _collect_implicit(args, specs)\nimplicit_sig = [(ty, False) for ty in implicit_types]\nexplicit_sig = [(_arg_type(idxs, x, s), True) for x, s in zip(args, specs)]\n- return (*implicit_sig, *explicit_sig)\n+ input_type = (*implicit_sig, *explicit_sig)\n+ lu._check_input_type(input_type)\n+ return input_type\ndef _canonicalize_specs(\nndims: Sequence[int], specs: Optional[Sequence[AbstractedAxesSpec]]\n@@ -2143,6 +2145,7 @@ def _complete_specs(\nfor x, spec in zip(args, specs))\nreturn specs\n+\ndef _collect_implicit(\nargs: Sequence[Any], specs: List[Dict[int, AbstractedAxisName]]\n) -> Tuple[Dict[AbstractedAxisName, DBIdx], List[AbstractValue]]:\n@@ -2153,24 +2156,23 @@ def _collect_implicit(\nidxs: Dict[AbstractedAxisName, DBIdx] = {}\nimplicit_types: List[AbstractValue] = []\nexplicit_tracers: Dict[TracerId, int] = {}\n- counter = (DBIdx(i) for i in it.count())\n+ counter = it.count()\n# Add implicit arguments to idxs.\n-\nfor explicit_idx, (x, spec) in enumerate(zip(args, specs)):\nfor i, name in spec.items():\nif name not in idxs and id(x.shape[i]) not in explicit_tracers:\n- idxs[name] = next(counter)\n+ idxs[name] = DBIdx(next(counter))\nimplicit_types.append(raise_to_shaped(get_aval(x.shape[i])))\nif isinstance(x, Tracer):\n- explicit_tracers[id(x)] = explicit_idx\n+ explicit_tracers.setdefault(id(x), explicit_idx) # use the first\n# Now that we know the implicit args, add explicit args to idxs.\noffset = len(implicit_types)\nfor x, spec in zip(args, specs):\nfor i, name in spec.items():\nif id(x.shape[i]) in explicit_tracers:\n- idxs[name] = DBIdx(offset + explicit_tracers[id(x.shape[i])])\n+ idxs.setdefault(name, DBIdx(offset + explicit_tracers[id(x.shape[i])]))\nreturn idxs, implicit_types\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/linear_util.py",
"new_path": "jax/linear_util.py",
"diff": "@@ -236,17 +236,29 @@ def wrap_init(f, params=None) -> WrappedFun:\nparams = () if params is None else tuple(sorted(params.items()))\nreturn WrappedFun(f, (), (), params, None)\n-def annotate(f: WrappedFun,\n- in_type: Optional[Tuple[Tuple[core.AbstractValue, bool], ...]]\n- ) -> WrappedFun:\n+\n+def annotate(f: WrappedFun, in_type: core.InputType) -> WrappedFun:\nassert f.in_type is None\nif in_type is None:\nreturn f\n+ _check_input_type(in_type)\n+ return WrappedFun(f.f, f.transforms, f.stores, f.params, in_type)\n+\n+def _check_input_type(in_type: core.InputType) -> None:\n+ # Check that in_type is syntactically well-formed\nassert (type(in_type) is tuple and all(type(e) is tuple for e in in_type) and\nall(isinstance(a, core.AbstractValue) and type(b) is bool\nand not isinstance(a, core.ConcreteArray) for a, b in in_type) and\nall(isinstance(d, (int, core.BInt, core.DBIdx)) for a, _ in in_type\nif type(a) is core.DShapedArray for d in a.shape))\n+\n+ # Check that all DBIdx point to positions to the left of the input on which\n+ # they appear.\n+ assert all(d.val < i for i, (aval, _) in enumerate(in_type)\n+ if isinstance(aval, core.DShapedArray) for d in aval.shape\n+ if isinstance(d, core.DBIdx))\n+\n+ # Check that all implicit arguments have at least one DBIdx pointing to them.\nprovided = [e for _, e in in_type]\nfor aval, _ in in_type:\nif type(aval) is core.DShapedArray:\n@@ -254,7 +266,6 @@ def annotate(f: WrappedFun,\nif isinstance(d, core.DBIdx):\nprovided[d.val] = True\nassert all(provided)\n- return WrappedFun(f.f, f.transforms, f.stores, f.params, in_type)\nclass _CacheLocalContext(threading.local):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/dynamic_api_test.py",
"new_path": "tests/dynamic_api_test.py",
"diff": "@@ -1354,6 +1354,12 @@ class DynamicShapeTest(jtu.JaxTestCase):\nd, = jaxpr.eqns[0].outvars\nself.assertEqual(d.aval.shape, (a, a))\n+ def test_inferring_valid_subjaxpr_type_add(self):\n+ def f(x):\n+ return x + x.shape[0]\n+\n+ jax.make_jaxpr(f, abstracted_axes=('n',))(jnp.arange(3)) # doesn't crash\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | fix bug in djax type signature inference logic
Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com> |
260,335 | 27.09.2022 20:39:19 | 25,200 | b175e117313fc7c554c828e054e2b7cee70ffcbe | [c++ jit] only set use_fastpath in cache_miss if all args are DeviceArrays
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -537,6 +537,8 @@ def _device_array_use_fast_path(execute, out_pytree_def, args_flat, out_flat):\nnot execute.args[5] and not execute.args[6] and\n# Has no host callbacks\nnot execute.args[8] and\n+ # impl rule must have been called, i.e. top trace is an EvalTrace\n+ isinstance(core.find_top_trace(args_flat), core.EvalTrace) and\n# Not supported: ShardedDeviceArray\nall(device_array.type_is_device_array(x) for x in out_flat) and\n# Not supported: dynamic shapes\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -3872,6 +3872,53 @@ class APITest(jtu.JaxTestCase):\ng = jax.jit(lambda x, y: x * y, static_argnums=-1)\ng(1, 2) # doesn't crash\n+ def test_fastpath_cache_confusion(self):\n+ # https://github.com/google/jax/issues/12542\n+ @jax.jit\n+ def a(x):\n+ return ()\n+\n+ @jax.jit\n+ def b(x):\n+ return a(x)\n+\n+\n+ @jax.jit\n+ def g(x):\n+ return x, x\n+\n+ @jax.jit\n+ def h(x):\n+ return g(x)\n+\n+ jaxpr = jax.make_jaxpr(h)(7)\n+ jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, 7)\n+\n+ b(8) # don't crash\n+\n+ def test_fastpath_cache_confusion2(self):\n+ @jax.jit\n+ def a(): # note nullary function, still staged out though\n+ return ()\n+\n+ @jax.jit\n+ def b(x):\n+ return a()\n+\n+\n+ @jax.jit\n+ def g(x):\n+ return x, x\n+\n+ @jax.jit\n+ def h(x):\n+ return g(x)\n+\n+ jaxpr = jax.make_jaxpr(h)(7)\n+ jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, 7)\n+\n+ b(8) # don't crash\n+\n@jtu.with_config(jax_experimental_subjaxpr_lowering_cache=True)\nclass SubcallTraceCacheTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | [c++ jit] only set use_fastpath in cache_miss if all args are DeviceArrays
fixes #12542
Co-authored-by: Peter Hawkins <phawkins@google.com>
Co-authored-by: Kuangyuan Chen <chky@google.com> |
260,510 | 27.09.2022 15:19:03 | 25,200 | ddeaa8dbbc707b8ca485d9ca077b45535623d352 | Fix lowering bug in effectful batched cond and add tests | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/loops.py",
"new_path": "jax/_src/lax/control_flow/loops.py",
"diff": "@@ -1439,7 +1439,11 @@ def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\ncore.ordered_effects]\nif cond_ordered_effects:\ndef cond(args):\n- return core.eval_jaxpr(cond_jaxpr.jaxpr, cond_jaxpr.consts, *args)[0]\n+ # Pred can be batched\n+ pred = core.eval_jaxpr(cond_jaxpr.jaxpr, cond_jaxpr.consts, *args)[0]\n+ if batched:\n+ pred = lax._reduce_or(pred, tuple(range(len(pred_aval.shape))))\n+ return pred\ndef body(args):\nreturn tuple(core.eval_jaxpr(body_jaxpr.jaxpr, body_jaxpr.consts, *args))\ndef new_cond(pred_args):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/debugging_primitives_test.py",
"new_path": "tests/debugging_primitives_test.py",
"diff": "@@ -575,6 +575,66 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nx: 10\n\"\"\"))\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\n+ for ordered in [False, True]))\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_can_print_in_batched_while_cond(self, ordered):\n+ def f(x):\n+ def _cond(x):\n+ debug_print(\"x: {x}\", x=x, ordered=ordered)\n+ return x < 5\n+ def _body(x):\n+ return x + 1\n+ return lax.while_loop(_cond, _body, x)\n+ with jtu.capture_stdout() as output:\n+ jax.vmap(f)(jnp.arange(2))\n+ jax.effects_barrier()\n+ if ordered:\n+ expected = _format_multiline(\"\"\"\n+ x: 0\n+ x: 1\n+ x: 1\n+ x: 2\n+ x: 2\n+ x: 3\n+ x: 3\n+ x: 4\n+ x: 4\n+ x: 5\n+ x: 5\n+ x: 6\n+ \"\"\")\n+ self.assertEqual(output(), expected)\n+ else:\n+ # When the print is unordered, the `cond` is called an additional time\n+ # after the `_body` runs, so we get more prints.\n+ expected = _format_multiline(\"\"\"\n+ x: 0\n+ x: 1\n+ x: 0\n+ x: 1\n+ x: 1\n+ x: 2\n+ x: 1\n+ x: 2\n+ x: 2\n+ x: 3\n+ x: 2\n+ x: 3\n+ x: 3\n+ x: 4\n+ x: 3\n+ x: 4\n+ x: 4\n+ x: 5\n+ x: 4\n+ x: 5\n+ x: 5\n+ x: 5\n+ \"\"\")\n+ self._assertLinesEqual(output(), expected)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\nfor ordered in [False, True]))\n"
}
] | Python | Apache License 2.0 | google/jax | Fix lowering bug in effectful batched cond and add tests |
260,335 | 26.09.2022 16:31:18 | 25,200 | a8826e672bb031d3f0e054b14b9eff1161a4ec52 | [dynamic-shapes] Add basic slicing support
If e.g. `x : f32[10, n]` then we want to handle Python expressions like `x[0]`.
To do that, we can use a generalized version of `dynamic_slice` which allows
dynamic slice sizes (where the result shape depends on those slice sizes). | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -1456,10 +1456,9 @@ def _iter(tracer):\nraise TypeError(\"iteration over a 0-d array\") # same as numpy error\nelse:\nn = int(tracer.shape[0])\n- # return (index_in_dim(tracer, i, keepdims=False) for i in range(n))\n- return iter([slicing.index_in_dim(tracer, i, keepdims=False)\n- for i in range(n)])\n+ return (slicing.index_in_dim(tracer, i, keepdims=False) for i in range(n))\nShapedArray._iter = staticmethod(_iter)\n+core.DShapedArray._iter = staticmethod(_iter)\n# Add some ad handlers that use (or could use) lax primitives\n@@ -2884,6 +2883,8 @@ def _broadcast_in_dim_pp_rule(eqn, context, settings):\nreturn [lhs, pp.text(\" = \", annotation=annotation), *rhs]\ndef _broadcast_in_dim_abstract_eval(x, *dyn_shape, shape, broadcast_dimensions):\n+ if dyn_shape: raise NotImplementedError\n+ del dyn_shape\nif not any(isinstance(d, core.BInt) for d in shape):\nshape = _broadcast_in_dim_shape_rule( # error checking\nx, shape=shape, broadcast_dimensions=broadcast_dimensions)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/slicing.py",
"new_path": "jax/_src/lax/slicing.py",
"diff": "@@ -104,8 +104,13 @@ def dynamic_slice(operand: Array, start_indices: Sequence[Array],\n[ 8, 9, 10, 11]], dtype=int32)\n\"\"\"\nstart_indices = _dynamic_slice_indices(operand, start_indices)\n- return dynamic_slice_p.bind(operand, *start_indices,\n- slice_sizes=core.canonicalize_shape(slice_sizes))\n+ if jax.config.jax_dynamic_shapes:\n+ dynamic_sizes, static_sizes = lax._extract_tracers_dyn_shape(slice_sizes)\n+ else:\n+ dynamic_sizes = []\n+ static_sizes = core.canonicalize_shape(slice_sizes) # type: ignore\n+ return dynamic_slice_p.bind(operand, *start_indices, *dynamic_sizes,\n+ slice_sizes=tuple(static_sizes))\ndef dynamic_update_slice(operand: Array, update: Array,\nstart_indices: Array) -> Array:\n@@ -684,7 +689,7 @@ def index_in_dim(operand: Array, index: int, axis: int = 0,\ndef dynamic_slice_in_dim(operand: Array, start_index: Array,\nslice_size: int, axis: int = 0) -> Array:\n\"\"\"Convenience wrapper around dynamic_slice applying to one dimension.\"\"\"\n- start_indices = [lax._zero(start_index)] * operand.ndim\n+ start_indices = [np.zeros((), dtype=dtypes.dtype(start_index))] * operand.ndim\nslice_sizes = list(operand.shape)\naxis = int(axis)\n@@ -746,13 +751,16 @@ def _slice_shape_rule(operand, *, start_indices, limit_indices, strides):\nmsg = (\"slice start_indices must be greater than or equal to zero, \"\n\"got start_indices of {}.\")\nraise TypeError(msg.format(start_indices))\n+ if not jax.config.jax_dynamic_shapes:\nif not core.greater_equal_shape(limit_indices, start_indices):\nmsg = (\"slice limit_indices must be greater than or equal to start_indices,\"\n\" got start_indices {} and limit_indices {}.\")\nraise TypeError(msg.format(start_indices, limit_indices))\n- if strides is None:\n- strides = np.ones(operand.ndim, np.int32)\n- else:\n+ if strides is None or tuple(strides) == (1,) * len(operand.shape):\n+ shape = [limit if type(start) is int and start == 0 else limit - start\n+ for start, limit in zip(start_indices, limit_indices)]\n+ return tuple(shape)\n+\nlax._check_shapelike(\"slice\", \"strides\", strides)\nif len(strides) != operand.ndim:\nmsg = (\"slice strides must have length equal to the number of dimensions \"\n@@ -761,7 +769,6 @@ def _slice_shape_rule(operand, *, start_indices, limit_indices, strides):\nif not core.greater_equal_shape(strides, (0,) * len(strides)):\nmsg = \"slice strides must be positive, got {}\"\nraise TypeError(msg.format(strides))\n-\ndiff = core.diff_shape(limit_indices, start_indices)\nreturn core.stride_shape(diff, (1,) * len(diff), strides)\n@@ -902,6 +909,31 @@ def _dynamic_slice_batching_rule(batched_args, batch_dims, *, slice_sizes):\nslice_sizes=slice_sizes, unique_indices=True, indices_are_sorted=True,\nmode=GatherScatterMode.PROMISE_IN_BOUNDS, fill_value=None)\n+def _dynamic_slice_staging_rule(trace, x, *starts_and_dyn_sizes, slice_sizes):\n+ start_indices, dyn = util.split_list(starts_and_dyn_sizes, [x.ndim])\n+ if not dyn:\n+ return trace.default_process_primitive(dynamic_slice_p, (x, *start_indices),\n+ dict(slice_sizes=slice_sizes))\n+ shape = lax._merge_dyn_shape(slice_sizes, dyn)\n+ aval = core.DShapedArray(shape, x.dtype, False)\n+ return lax._dyn_shape_staging_rule(trace, dynamic_slice_p, aval, x,\n+ *starts_and_dyn_sizes,\n+ slice_sizes=slice_sizes)\n+\n+def _dynamic_slice_typecheck_rule(x, *starts_and_dyn_sizes, slice_sizes):\n+ start_indices, dyn = util.split_list(starts_and_dyn_sizes, [x.aval.ndim])\n+ if not dyn:\n+ out_aval, effects = dynamic_slice_p.abstract_eval(\n+ x.aval, *(d.aval for d in start_indices), slice_sizes=slice_sizes)\n+ return [out_aval], effects\n+ else:\n+ # TODO(mattjj): perform more checks\n+ out_shape = lax._merge_dyn_shape(slice_sizes, dyn)\n+ out_shape = [d.val if type(d) is core.Literal else d for d in out_shape]\n+ out_aval = core.DShapedArray(tuple(out_shape), x.aval.dtype,\n+ x.aval.weak_type)\n+ return [out_aval], core.no_effects\n+\ndynamic_slice_p = standard_primitive(\n_dynamic_slice_shape_rule, _dynamic_slice_dtype_rule, 'dynamic_slice',\n@@ -909,17 +941,37 @@ dynamic_slice_p = standard_primitive(\nad.primitive_jvps[dynamic_slice_p] = _dynamic_slice_jvp\nad.primitive_transposes[dynamic_slice_p] = _dynamic_slice_transpose_rule\nbatching.primitive_batchers[dynamic_slice_p] = _dynamic_slice_batching_rule\n+pe.custom_staging_rules[dynamic_slice_p] = _dynamic_slice_staging_rule\n+core.custom_typechecks[dynamic_slice_p] = _dynamic_slice_typecheck_rule\n-def _dynamic_slice_lower(ctx, x, *start_indices, slice_sizes):\n+def _dynamic_slice_lower(ctx, x, *starts_and_dyn_sizes, slice_sizes):\n+ x_aval, *_ = ctx.avals_in\n+ start_indices, dyn = util.split_list(starts_and_dyn_sizes, [x_aval.ndim])\naval_out, = ctx.avals_out\n+ if core.is_opaque_dtype(aval_out.dtype) and dyn: raise NotImplementedError\n+ if not dyn:\nif core.is_opaque_dtype(aval_out.dtype):\n- return aval_out.dtype._rules.dynamic_slice_mlir(\n- ctx, x, start_indices, slice_sizes)\n+ return aval_out.dtype._rules.dynamic_slice_mlir(ctx, x, start_indices,\n+ slice_sizes)\nreturn mhlo.DynamicSliceOp(x, start_indices,\nmlir.dense_int_elements(slice_sizes)).results\n-\n+ slice_sizes = lax._merge_dyn_shape(slice_sizes, dyn)\n+ return mhlo.RealDynamicSliceOp(\n+ mlir.aval_to_ir_type(aval_out), x,\n+ mlir.shape_tensor(start_indices),\n+ mlir.shape_tensor(slice_sizes),\n+ mlir.shape_tensor([1] * len(slice_sizes))\n+ ).results\nmlir.register_lowering(dynamic_slice_p, _dynamic_slice_lower)\n+# def _getslice_lower(ctx, x, lo, hi):\n+# aval_out, = ctx.avals_out\n+# return mhlo.RealDynamicSliceOp(\n+# mlir.aval_to_ir_type(aval_out), x,\n+# mlir.shape_tensor([lo]), mlir.shape_tensor([hi]), mlir.shape_tensor([1])\n+# ).results\n+# mlir.register_lowering(getslice_p, _getslice_lower)\n+\ndef _dynamic_update_slice_shape_rule(operand, update, *start_indices):\nif operand.ndim != update.ndim:\n@@ -2055,9 +2107,14 @@ def _dynamic_slice_indices(operand, start_indices: Any):\nstart_indices = list(start_indices)\nresult = []\nfor i, d in zip(start_indices, operand.shape):\n+ # We test whether i and d are static to avoid unnecessary staging.\nif isinstance(i, (int, np.integer)) and core.is_constant_dim(d):\nresult.append(lax.convert_element_type(i + d, _dtype(i)) if i < 0 else i)\n- else:\n- d = lax.convert_element_type(core.dimension_as_value(d), _dtype(i))\n+ continue\n+ d = core.dimension_as_value(d)\n+ if isinstance(i, (int, np.integer)):\n+ result.append(i + lax.convert_element_type(d, _dtype(i)) if i < 0 else i)\n+ continue\n+ d = lax.convert_element_type(d, _dtype(i))\nresult.append(lax.select(i < 0, i + d, i))\nreturn result\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3621,6 +3621,9 @@ def _rewriting_take(arr, idx, indices_are_sorted=False, unique_indices=False,\nif (arr.ndim > 0 and isinstance(idx, (int, np.integer)) and\nnot isinstance(idx, (bool, np.bool_)) and isinstance(arr.shape[0], int)):\nif 0 <= idx < arr.shape[0]:\n+ if _any(isinstance(d, core.Tracer) for d in arr.shape[1:]):\n+ return lax.dynamic_index_in_dim(arr, idx, keepdims=False)\n+ else:\nreturn lax.index_in_dim(arr, idx, keepdims=False)\nif (arr.ndim > 0 and isinstance(arr.shape[0], int) and\nisinstance(idx, slice) and\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1747,7 +1747,7 @@ def symbolic_equal_shape(s1: Shape, s2: Shape) -> bool:\ndef greater_equal_dim(d1: DimSize, d2: DimSize) -> bool:\nhandler, ds = _dim_handler_and_canonical(d1, d2)\n- return handler.greater_equal(*ds)\n+ return handler.symbolic_equal(*ds) or handler.greater_equal(*ds)\ndef greater_equal_shape(s1: Shape, s2: Shape) -> bool:\nreturn all(map(greater_equal_dim, s1, s2))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/dynamic_api_test.py",
"new_path": "tests/dynamic_api_test.py",
"diff": "@@ -1360,6 +1360,37 @@ class DynamicShapeTest(jtu.JaxTestCase):\njax.make_jaxpr(f, abstracted_axes=('n',))(jnp.arange(3)) # doesn't crash\n+ def test_slicing_basic_jaxpr(self):\n+ def f(x):\n+ return x[0]\n+\n+ jaxpr = jax.make_jaxpr(f, abstracted_axes=(None, 'n'))(jnp.zeros((3, 4)))\n+ # { lambda ; a:i32[] b:f32[3,a]. let\n+ # c:f32[1,a] = dynamic_slice[slice_sizes=(1, None)] b 0 0 a\n+ # d:f32[a] = squeeze[dimensions=(0,)] c\n+ # in (d,) }\n+ self.assertLen(jaxpr.jaxpr.invars, 2)\n+ a, _ = jaxpr.jaxpr.invars\n+ self.assertLen(jaxpr.jaxpr.outvars, 1)\n+ d, = jaxpr.jaxpr.outvars\n+ self.assertLen(d.aval.shape, 1)\n+ self.assertEqual(d.aval.shape, (a,))\n+\n+ def test_slicing_basic_lower(self):\n+ @partial(jax.jit, abstracted_axes=(None, 'n'))\n+ def f(x):\n+ return x[0]\n+ f.lower(jnp.zeros((3, 4))).compiler_ir() # doesn't crash\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_slicing_basic_execute(self):\n+ @partial(jax.jit, abstracted_axes=(None, 'n'))\n+ def f(x):\n+ return x[0]\n+\n+ y = f(jnp.arange(3 * 4).reshape(3, 4))\n+ self.assertAllClose(y, jnp.array([0, 1, 2, 3]))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [dynamic-shapes] Add basic slicing support
If e.g. `x : f32[10, n]` then we want to handle Python expressions like `x[0]`.
To do that, we can use a generalized version of `dynamic_slice` which allows
dynamic slice sizes (where the result shape depends on those slice sizes).
Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com> |
260,424 | 16.09.2022 19:52:18 | -3,600 | 0639aced5b8bffb04ecb1ff409ee2b07eab1feac | Raise cond index into tracing context in case of effects.
So even if the cond is not data dependent at all, it's included in the
dynamic trace, and effects can be discharged. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/conditionals.py",
"new_path": "jax/_src/lax/control_flow/conditionals.py",
"diff": "@@ -139,6 +139,10 @@ def switch(index, branches: Sequence[Callable], *operands,\nif disallowed_effects:\nraise NotImplementedError(\nf'Effects not supported in `switch`: {disallowed_effects}')\n+ if joined_effects:\n+ # Raise index in case of effects to allow data-dependence-based discharging\n+ # of those effects (even if they don't have an explicit data dependence).\n+ index = core.raise_as_much_as_possible(index)\nlinear = (False,) * (len(consts) + len(ops))\nout = cond_p.bind(\n@@ -235,6 +239,10 @@ def _cond(pred, true_fun: Callable, false_fun: Callable, *operands,\nf'Effects not supported in `cond`: {disallowed_effects}')\nindex = lax.convert_element_type(pred, np.int32)\n+ if joined_effects:\n+ # Raise index in case of effects to allow data-dependence-based discharging\n+ # of those effects (even if they don't have an explicit data dependence).\n+ index = core.raise_as_much_as_possible(index)\nlinear = [False] * len(consts) + linear_ops\nout = cond_p.bind(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -766,6 +766,33 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"x must be negative\")\n+ def test_assert_discharging_cond(self):\n+ def true_branch(x):\n+ checkify.check(jnp.all(x != 0.), \"x cannot be 0\")\n+ return 1/x\n+\n+ def false_branch(x):\n+ checkify.check(jnp.all(x >= 0), \"x must be positive\")\n+ return x*2\n+\n+ @jax.jit\n+ def f(pred, x):\n+ return lax.cond(pred, true_branch, false_branch, x)\n+\n+ checked_f = checkify.checkify(f)\n+\n+ err, _ = checked_f(True, 0.)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"x cannot be 0\")\n+ err, _ = checked_f(False, 0.)\n+ self.assertIsNone(err.get())\n+\n+ err, _ = checked_f(False, -1.)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"x must be positive\")\n+ err, _ = checked_f(True, -1.)\n+ self.assertIsNone(err.get())\n+\ndef test_assert_batching_rule(self):\n@jax.vmap\ndef f(x):\n@@ -863,12 +890,12 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\ncheckify.checkify(g)(0.) # does not crash\ndef test_grad(self):\n- @checkify.checkify\n@jax.grad\ndef f(x):\ncheckify.check(jnp.all(x > 0), \"should be positive!\")\nreturn x\n+ f = checkify.checkify(f)\nerr, _ = f(1.)\nself.assertIsNone(err.get())\n@@ -906,6 +933,30 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"value needs to be less than 6\")\n+ def test_assert_cond_no_data_dependence(self):\n+ def f():\n+ return jax.lax.cond(True,\n+ lambda: checkify.check(False, \"hi!\"),\n+ lambda: checkify.check(False, \"bye!\"))\n+\n+ f = checkify.checkify(f)\n+ err, _ = f()\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"hi!\")\n+\n+ def test_assert_switch_no_data_dependence(self):\n+ def branch():\n+ checkify.check(False, \"hi!\")\n+\n+ def f():\n+ return lax.switch(0, [branch]*3)\n+\n+ checked_f = checkify.checkify(f)\n+\n+ err, _ = checked_f()\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"hi!\")\n+\nclass LowerableChecksTest(jtu.JaxTestCase):\ndef setUp(self):\nsuper().setUp()\n@@ -926,6 +977,5 @@ class LowerableChecksTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(xla_extension.XlaRuntimeError,\n\"x needs to be positive\"):\nf(-1.)\n-\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Raise cond index into tracing context in case of effects.
So even if the cond is not data dependent at all, it's included in the
dynamic trace, and effects can be discharged. |
260,661 | 29.09.2022 12:40:40 | 0 | 0783f8982d78c26d765120a127ee39e8f203f8d7 | [ROCM] Add TENSORFLOW_ROCM_COMMIT parameter to ROCM ci build | [
{
"change_type": "MODIFY",
"old_path": "build/rocm/build_rocm.sh",
"new_path": "build/rocm/build_rocm.sh",
"diff": "@@ -19,6 +19,15 @@ ROCM_TF_FORK_REPO=\"https://github.com/ROCmSoftwarePlatform/tensorflow-upstream\"\nROCM_TF_FORK_BRANCH=\"develop-upstream\"\nrm -rf /tmp/tensorflow-upstream || true\ngit clone -b ${ROCM_TF_FORK_BRANCH} ${ROCM_TF_FORK_REPO} /tmp/tensorflow-upstream\n+if [ ! -v TENSORFLOW_ROCM_COMMIT ]; then\n+ echo \"The TENSORFLOW_ROCM_COMMIT environment variable is not set, using top of branch\"\n+elif [ ! -z \"$TENSORFLOW_ROCM_COMMIT\" ]\n+then\n+ echo \"Using tensorflow-rocm at commit: $TENSORFLOW_ROCM_COMMIT\"\n+ cd /tmp/tensorflow-upstream\n+ git checkout $TENSORFLOW_ROCM_COMMIT\n+ cd -\n+fi\npython3 ./build/build.py --enable_rocm --rocm_path=${ROCM_PATH} --bazel_options=--override_repository=org_tensorflow=/tmp/tensorflow-upstream\npip3 install --use-feature=2020-resolver --force-reinstall dist/*.whl # installs jaxlib (includes XLA)\n"
},
{
"change_type": "MODIFY",
"old_path": "build/rocm/ci_build.sh",
"new_path": "build/rocm/ci_build.sh",
"diff": "@@ -105,6 +105,7 @@ echo \"Running '${POSITIONAL_ARGS[*]}' inside ${DOCKER_IMG_NAME}...\"\ndocker run ${KEEP_IMAGE} --name ${DOCKER_IMG_NAME} --pid=host \\\n-v ${WORKSPACE}:/workspace \\\n-w /workspace \\\n+ -e TENSORFLOW_ROCM_COMMIT=${TENSORFLOW_ROCM_COMMIT} \\\n${ROCM_EXTRA_PARAMS} \\\n\"${DOCKER_IMG_NAME}\" \\\n${POSITIONAL_ARGS[@]}\n"
}
] | Python | Apache License 2.0 | google/jax | [ROCM] Add TENSORFLOW_ROCM_COMMIT parameter to ROCM ci build |
260,631 | 29.09.2022 11:31:48 | 25,200 | 4f90af91d3760dc82f20d4afffd11373b52ae704 | Remove unused jax_unique_mhlo_module_names flag. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/config.py",
"new_path": "jax/_src/config.py",
"diff": "@@ -874,12 +874,6 @@ config.define_bool_state(\ndefault=True,\nhelp='Enable using the context manager-based name stack.')\n-config.define_bool_state(\n- name='jax_unique_mhlo_module_names',\n- default=False,\n- help='Enables the generation of unique MHLO module names. This is useful '\n- 'to clients that expect modules to have unique names (e.g, trace data).')\n-\n# This flag is temporary during rollout of the remat barrier.\n# TODO(parkers): Remove if there are no complaints.\nconfig.define_bool_state(\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -543,7 +543,6 @@ def flatten_lowering_ir_args(\n) -> Sequence[Sequence[ir.Value]]:\nreturn util.flatten(map(wrap_singleton_ir_values, xs))\n-_module_unique_id = itertools.count()\n_module_name_regex = re.compile(r\"[^\\w.-]\")\ndef sharded_aval(aval: core.ShapedArray,\n@@ -642,12 +641,6 @@ def lower_jaxpr_to_module(\n# Remove module name characters that XLA would alter. This ensures that\n# XLA computation preserves the module name.\nmodule_name = _module_name_regex.sub(\"_\", module_name)\n- if config.jax_unique_mhlo_module_names:\n- # Some clients expect modules to have unique names, e.g., in trace data.\n- # This may or may not be a reasonable assumption.\n- ctx.module.operation.attributes[\"sym_name\"] = ir.StringAttr.get(\n- f\"{module_name}.{next(_module_unique_id)}\")\n- else:\nctx.module.operation.attributes[\"sym_name\"] = ir.StringAttr.get(\nmodule_name)\nunlowerable_effects = {eff for eff in jaxpr.effects\n"
}
] | Python | Apache License 2.0 | google/jax | Remove unused jax_unique_mhlo_module_names flag.
PiperOrigin-RevId: 477778135 |
260,332 | 29.09.2022 17:06:56 | 25,200 | 4fbc9a10d116cfe49f2e502718a320ed4734e235 | Add multihost GPU CI run with last public jaxlib release | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/nightly-ci-multiprocess-gpu.yml",
"new_path": ".github/workflows/nightly-ci-multiprocess-gpu.yml",
"diff": "@@ -15,7 +15,7 @@ on:\n- '**workflows/nightly-ci-multiprocess-gpu.yml'\njobs:\n- build:\n+ jaxlib-nightly:\nruns-on: self-hosted\nsteps:\n- uses: actions/checkout@v3\n@@ -24,7 +24,46 @@ jobs:\nrun: |\nexport JOBSCRIPTSDIR=${GITHUB_WORKSPACE}/.github/workflows/slurm_job_scripts\nsource $JOBSCRIPTSDIR/slurm_utils_common.sh\n- sbatch -N 2 $JOBSCRIPTSDIR/multinode_pytest.sub | tee output.log\n+ sbatch -N 2 $JOBSCRIPTSDIR/multinode_pytest_jaxlib_nightly.sub | tee output.log\n+ sleep 2m\n+ export SLURM_JOBID=$(grep 'Submitted batch job' \"output.log\" | awk '{ print $4 }')\n+ export SLURM_OUTPUT=$(scontrol show job \"${SLURM_JOBID}\" | grep 'StdOut' | awk -F '=' '{ print $2 }')\n+ job_wait \"${SLURM_JOBID}\" & PID=$!\n+ touch \"${SLURM_OUTPUT}\"\n+ echo -e \" ---------------------------------------------------\\n\" \\\n+ \"----------WAITING FOR SLURM JOB TO BEGIN-----------\\n\" \\\n+ \"---------------------------------------------------\\n\"\n+ tail --pid=\"${PID}\" -f \"${SLURM_OUTPUT}\"\n+ export SLURM_STATE=$(job_state \"${SLURM_JOBID}\"); echo \"SLURM_JOBID=${SLURM_JOBID} SLURM_STATE='${SLURM_STATE}'\"\n+ export SLURM_WALLTIME=$(job_time \"${SLURM_JOBID}\"); echo \"SLURM_WALLTIME=${SLURM_WALLTIME} secs\"\n+ export SLURM_EXITCODE=$(job_exit_code \"${SLURM_JOBID}\" || echo $?); echo \"SLURM_EXITCODE='${SLURM_EXITCODE}'\"\n+ if [ \"${SLURM_EXITCODE}\" != \"0\" ]; then exit ${SLURM_EXITCODE:-999}; fi\n+ if [ \"${SLURM_STATE}\" != \"COMPLETED\" ]; then exit 1; fi\n+\n+ - name: Publish Test Results\n+ uses: EnricoMi/publish-unit-test-result-action@v2\n+ if: always()\n+ with:\n+ junit_files: \"outputs/*.xml\"\n+\n+ - name: Upload run results from all nodes\n+ uses: actions/upload-artifact@v3\n+ if: always()\n+ with:\n+ name: output-from-nodes\n+ path: \"outputs/*.txt\"\n+\n+ jaxlib-release:\n+ runs-on: self-hosted\n+ needs: jaxlib-nightly\n+ steps:\n+ - uses: actions/checkout@v3\n+\n+ - name: Launch slurm job and hook output to this shell\n+ run: |\n+ export JOBSCRIPTSDIR=${GITHUB_WORKSPACE}/.github/workflows/slurm_job_scripts\n+ source $JOBSCRIPTSDIR/slurm_utils_common.sh\n+ sbatch -N 2 $JOBSCRIPTSDIR/multinode_pytest_jaxlib_release.sub | tee output.log\nsleep 2m\nexport SLURM_JOBID=$(grep 'Submitted batch job' \"output.log\" | awk '{ print $4 }')\nexport SLURM_OUTPUT=$(scontrol show job \"${SLURM_JOBID}\" | grep 'StdOut' | awk -F '=' '{ print $2 }')\n@@ -55,7 +94,7 @@ jobs:\nreport:\nname: report\n- needs: build\n+ needs: [jaxlib-nightly, jaxlib-release]\nif: |\nfailure()\n&& github.event_name == 'schedule'\n"
},
{
"change_type": "RENAME",
"old_path": ".github/workflows/slurm_job_scripts/multinode_pytest.sub",
"new_path": ".github/workflows/slurm_job_scripts/multinode_pytest_jaxlib_nightly.sub",
"diff": "@@ -50,7 +50,7 @@ OUTPUT_DIR=\"${BASE_WORKSPACE_DIR}/outputs/\"\nmkdir -p $OUTPUT_DIR\n# redirect both stdout and stderr in the same file for ease of analysis\n-OUTFILE=\"${OUTPUT_DIR}/output-%j-%n.txt\"\n+OUTFILE=\"${OUTPUT_DIR}/output-test-jaxlib-nightly-%j-%n.txt\"\n# Run any setup commands before the actual pytest command to make sure\n# that the processes are launched together\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/workflows/slurm_job_scripts/multinode_pytest_jaxlib_release.sub",
"diff": "+#!/bin/bash\n+#SBATCH -A ci-jax-gpu\n+#SBATCH -p compute\n+#SBATCH -N 2 # number of nodes\n+#SBATCH -t 00:15:00 # wall time\n+#SBATCH -J \"ci-jax-gpu\" # job name\n+#SBATCH --exclusive # exclusive node access\n+#SBATCH --mem=0 # all mem avail\n+#SBATCH --mail-type=FAIL # only send email on failures\n+#SBATCH --overcommit # Needed for pytorch\n+\n+set -x\n+\n+# File system and volume glue code\n+#-------------------------------------------------------------------------------\n+CONTAINER=\"nvcr.io/nvidian/jax_t5x:cuda11.4-cudnn8.2-ubuntu20.04-manylinux2014-multipython\"\n+CONTAINER_NAME=\"multinode_ci_test_container\"\n+\n+BASE_WORKSPACE_DIR=$GITHUB_WORKSPACE\n+WORKSPACE_DIR=/workspace\n+\n+MOUNTS=\"--container-mounts=$BASE_WORKSPACE_DIR:/$WORKSPACE_DIR\"\n+\n+# Since the docker container doesn't contain MLX drivers for IB, following flags\n+# are needed to make NCCL work with an ethernet setup\n+# Note:@sudhakarsingh27 This is very specific, need to abstract this out\n+EXPORTS=\"--export=ALL,NCCL_SOCKET_IFNAME=enp45s0f0,NCCL_SOCKET_NTHREADS=2,NCCL_NSOCKS_PERTHREAD=2\"\n+#-------------------------------------------------------------------------------\n+\n+# Setup command to be run before the actual pytest command\n+read -r -d '' setup_cmd <<EOF\n+python3.8 -m pip install --upgrade \"jax[cuda]\" -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html \\\n+&& python3.8 -m pip install pytest \\\n+&& python3.8 -m pip install pytest-forked \\\n+&& mkdir -p /workspace/outputs/\n+EOF\n+\n+# Main pytest command that runs the tests\n+read -r -d '' cmd <<EOF\n+date \\\n+&& python3.8 -m pip list | grep jax \\\n+&& python3.8 -m pytest -m SlurmMultiNodeGpuTest --forked -v -s --continue-on-collection-errors \\\n+ --junit-xml=/workspace/outputs/junit_output_\\${SLURM_PROCID}.xml \\\n+ /workspace/tests/multiprocess_gpu_test.py\n+EOF\n+\n+# create run specific output directory for ease of analysis\n+OUTPUT_DIR=\"${BASE_WORKSPACE_DIR}/outputs/\"\n+mkdir -p $OUTPUT_DIR\n+\n+# redirect both stdout and stderr in the same file for ease of analysis\n+OUTFILE=\"${OUTPUT_DIR}/output-test-jaxlib-release-%j-%n.txt\"\n+\n+# Run any setup commands before the actual pytest command to make sure\n+# that the processes are launched together\n+echo $setup_cmd\n+srun -o $OUTFILE -e $OUTFILE \\\n+ --ntasks-per-node=1 \\\n+ --container-writable \\\n+ --container-image=\"$CONTAINER\" \\\n+ --container-name=$CONTAINER_NAME \\\n+ $MOUNTS \\\n+ $EXPORTS \\\n+ bash -c \"${setup_cmd}\"\n+\n+# Barrier command\n+wait\n+\n+# Run the actual pytest command\n+echo $cmd\n+srun -o $OUTFILE -e $OUTFILE \\\n+ --ntasks-per-node=8 \\\n+ --open-mode=append \\\n+ --container-writable \\\n+ --container-image=\"$CONTAINER\" \\\n+ --container-name=$CONTAINER_NAME \\\n+ $MOUNTS \\\n+ $EXPORTS \\\n+ bash -c \"${cmd}\"\n+set +x\n"
}
] | Python | Apache License 2.0 | google/jax | Add multihost GPU CI run with last public jaxlib release |
260,335 | 29.09.2022 20:01:42 | 25,200 | b8c87bc9dedeae5066ecf1bad46075c9564e7546 | improve custom_jvp/vjp error messages
In particular:
* add function names so it's clear what decorated functions and rules
are causing the error;
* when possible (because the functions were run), check for agreement of pytree
structure and leaf shapes/dtypes between the primal function and rules
context: | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/custom_derivatives.py",
"new_path": "jax/_src/custom_derivatives.py",
"diff": "@@ -28,7 +28,7 @@ from jax._src import custom_api_util\nfrom jax._src import dtypes\nfrom jax._src.lax import lax\nfrom jax._src.util import cache, safe_zip, safe_map, split_list, Unhashable\n-from jax._src.api_util import flatten_fun_nokwargs, argnums_partial\n+from jax._src.api_util import argnums_partial, flatten_fun_nokwargs\nfrom jax.core import raise_to_shaped\nfrom jax.errors import UnexpectedTracerError\nfrom jax._src.ad_util import Zero, zeros_like_aval, stop_gradient_p\n@@ -80,6 +80,15 @@ def _stop_gradient(x):\nelse:\nreturn x\n+# like the api_util.py function, but also grabs output avals for error checking\n+@lu.transformation_with_aux\n+def _flatten_fun_nokwargs(in_tree, *args_flat):\n+ py_args = tree_unflatten(in_tree, args_flat)\n+ ans = yield py_args, {}\n+ ans_flat, ans_tree = tree_flatten(ans)\n+ ans_avals = [core.raise_to_shaped(core.get_aval(x)) for x in ans_flat]\n+ yield ans_flat, (ans_tree, ans_avals)\n+\n### JVPs\nReturnValue = TypeVar('ReturnValue')\n@@ -205,9 +214,11 @@ class custom_jvp(Generic[ReturnValue]):\n@traceback_util.api_boundary\ndef __call__(self, *args: Any, **kwargs: Any) -> ReturnValue: # pytype: disable=invalid-annotation\n+ primal_name = getattr(self.fun, '__name__', str(self.fun))\nif not self.jvp:\n- msg = \"No JVP defined for custom_jvp function {} using defjvp.\"\n- raise AttributeError(msg.format(self.__name__))\n+ msg = f\"No JVP defined for custom_jvp function {primal_name} using defjvp.\"\n+ raise AttributeError(msg)\n+ jvp_name = getattr(self.jvp, '__name__', str(self.jvp))\nargs = _resolve_kwargs(self.fun, args, kwargs)\nif self.nondiff_argnums:\nnondiff_argnums = set(self.nondiff_argnums)\n@@ -222,10 +233,11 @@ class custom_jvp(Generic[ReturnValue]):\nf_, dyn_args = lu.wrap_init(self.fun), args\njvp = lu.wrap_init(self.jvp)\nargs_flat, in_tree = tree_flatten(dyn_args)\n- flat_fun, out_tree1 = flatten_fun_nokwargs(f_, in_tree)\n- flat_jvp, out_tree2 = _flatten_jvp(jvp, in_tree)\n+ flat_fun, out_type1 = _flatten_fun_nokwargs(f_, in_tree)\n+ flat_jvp, out_type2 = _flatten_jvp(jvp, primal_name, jvp_name, in_tree,\n+ out_type1)\nout_flat = custom_jvp_call_p.bind(flat_fun, flat_jvp, *args_flat)\n- _, out_tree = lu.merge_linear_aux(out_tree1, out_tree2)\n+ _, (out_tree, _) = lu.merge_linear_aux(out_type1, out_type2)\nreturn tree_unflatten(out_tree, out_flat)\ndef _add_args(f, extra_args):\n@@ -238,22 +250,59 @@ def _add_args_(extra_args, *args, **kwargs):\nyield (yield all_args, kwargs)\n@lu.transformation_with_aux\n-def _flatten_jvp(in_tree, *args):\n+def _flatten_jvp(primal_name, jvp_name, in_tree, maybe_out_type, *args):\nprimals_in, tangents_in = split_list(args, [len(args) // 2])\npy_primals = tree_unflatten(in_tree, primals_in)\npy_tangents = tree_unflatten(in_tree, tangents_in)\npair_out = yield (py_primals, py_tangents), {}\nif not isinstance(pair_out, (list, tuple)) or len(pair_out) != 2:\n- msg = (\"Custom JVP rule must produce a pair (list or tuple of length two) \"\n- \"representing primal and tangent outputs, got {}.\")\n- raise TypeError(msg.format(pair_out))\n+ msg = (f\"Custom JVP rule {jvp_name} for function {primal_name} \"\n+ \"must produce a pair (list or tuple of length two) representing \"\n+ f\"primal and tangent outputs, but got {pair_out}.\")\n+ raise TypeError(msg)\npy_primals_out, py_tangents_out = pair_out\nprimals_out, out_tree = tree_flatten(py_primals_out)\ntangents_out, out_tree2 = tree_flatten(py_tangents_out)\n+ primal_avals = [core.raise_to_shaped(core.get_aval(x)) for x in primals_out]\nif out_tree != out_tree2:\n- msg = (\"Custom JVP rule must produce primal and tangent outputs with equal \"\n- \"container (pytree) structures, but got {} and {} respectively.\")\n- raise TypeError(msg.format(out_tree, out_tree2))\n+ msg = (f\"Custom JVP rule {jvp_name} for function {primal_name} must \"\n+ \"produce primal and tangent outputs with equal container (pytree) \"\n+ f\"structures, but got {out_tree} and {out_tree2} respectively.\")\n+ raise TypeError(msg)\n+ # If the primal function already ran, check out_tree agreement.\n+ try: out_type_ = maybe_out_type()\n+ except lu.StoreException: out_type_ = None\n+ if out_type_ is not None:\n+ out_tree_, primal_avals_ = out_type_\n+ ty_tree = tree_unflatten(out_tree , [a.str_short() for a in primal_avals])\n+ ty_tree_ = tree_unflatten(out_tree_, [a.str_short() for a in primal_avals_])\n+ if out_tree_ != out_tree:\n+ m = (f\"Custom JVP rule {jvp_name} for function {primal_name} must \"\n+ \"produce a pair (list or tuple of length two) \"\n+ \"where the first element represents the primal output \"\n+ \"(equal in value to the output of the custom_jvp-decorated function \"\n+ f\"{primal_name}, \"\n+ \"and in particular of the same container/pytree structure), but \"\n+ \"instead the JVP rule output's first element had container/pytree \"\n+ \"structure:\\n\"\n+ f\"\"\" {str(ty_tree ).replace(\"'\", \"\")}\\n\"\"\"\n+ f\"while the custom_jvp-decorated function {primal_name} had output \"\n+ \"container/pytree structure:\\n\"\n+ f\"\"\" {str(ty_tree_).replace(\"'\", \"\")}.\"\"\")\n+ raise TypeError(m)\n+ if not all(map(core.typematch, primal_avals, primal_avals_)):\n+ m = (f\"Custom JVP rule {jvp_name} for function {primal_name} must \"\n+ \"produce a pair (list or tuple of length two) \"\n+ \"where the first element represents the primal output \"\n+ \"(equal in value to the output of the custom_jvp-decorated function \"\n+ f\"{primal_name}, \"\n+ \"and in particular with leaves of the same shape/dtype), but \"\n+ \"instead the JVP rule output's first element had shapes/dtypes of:\\n\"\n+ f\"\"\" {str(ty_tree ).replace(\"'\", \"\")}\\n\"\"\"\n+ f\"while the custom_jvp-decorated function {primal_name} had output \"\n+ \"shapes/dtypes of:\\n\"\n+ f\"\"\" {str(ty_tree_).replace(\"'\", \"\")}\"\"\")\n+ raise TypeError(m)\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()\n@@ -274,7 +323,7 @@ def _flatten_jvp(in_tree, *args):\nf\" primal {av1.str_short()} for tangent {av2.str_short()}\"\nfor av1, av2 in zip(primal_avals_out, tangent_avals_out) if av1 != av2)\nraise TypeError(msg.format('\\n'.join(disagreements)))\n- yield primals_out + tangents_out, out_tree\n+ yield primals_out + tangents_out, (out_tree, primal_avals)\nclass CustomJVPCallPrimitive(core.Primitive):\nmultiple_results = True\n@@ -472,9 +521,11 @@ class custom_vjp(Generic[ReturnValue]):\n@traceback_util.api_boundary\ndef __call__(self, *args: Any, **kwargs: Any) -> ReturnValue: # pytype: disable=invalid-annotation\n+ primal_name = getattr(self.fun, '__name__', str(self.fun))\nif not self.fwd or not self.bwd:\n- msg = \"No VJP defined for custom_vjp function {} using defvjp.\"\n- raise AttributeError(msg.format(self.__name__))\n+ msg = f\"No VJP defined for custom_vjp function {primal_name} using defvjp.\"\n+ raise AttributeError(msg)\n+ fwd_name = getattr(self.fwd, '__name__', str(self.fwd))\nargs = _resolve_kwargs(self.fun, args, kwargs)\nif config.jax_enable_custom_vjp_by_custom_transpose:\nif self.nondiff_argnums:\n@@ -497,13 +548,13 @@ class custom_vjp(Generic[ReturnValue]):\nfwd, bwd = lu.wrap_init(self.fwd), lu.wrap_init(self.bwd)\nargs_flat, in_tree = tree_flatten(dyn_args)\nin_avals = [core.raise_to_shaped(core.get_aval(x)) for x in args_flat]\n- flat_fun, out_tree = flatten_fun_nokwargs(f_, in_tree)\n- flat_fwd, out_trees = _flatten_fwd(fwd, in_tree)\n+ flat_fun, out_type = _flatten_fun_nokwargs(f_, in_tree)\n+ flat_fwd, out_trees = _flatten_fwd(fwd, primal_name, fwd_name, in_tree,\n+ out_type)\nflat_bwd = _flatten_bwd(bwd, in_tree, in_avals, out_trees)\nout_flat = custom_vjp_call_p.bind(flat_fun, flat_fwd, flat_bwd,\n*args_flat, out_trees=out_trees)\n- fst, aux = lu.merge_linear_aux(out_tree, out_trees)\n- out_tree = aux if fst else aux[0]\n+ _, (out_tree, _) = lu.merge_linear_aux(out_type, out_trees)\nreturn tree_unflatten(out_tree, out_flat)\ndef _check_for_tracers(x):\n@@ -519,19 +570,59 @@ def _check_for_tracers(x):\nraise UnexpectedTracerError(msg)\n@lu.transformation_with_aux\n-def _flatten_fwd(in_tree, *args):\n+def _flatten_fwd(primal_name, fwd_name, in_tree, maybe_out_type, *args):\npy_args = tree_unflatten(in_tree, args)\npair_out = yield py_args, {}\nif not isinstance(pair_out, (list, tuple)) or len(pair_out) != 2:\n- msg = (\"Custom VJP fwd function must produce a pair (list or tuple of \"\n- \"length two) representing primal outputs and residuals (values \"\n- \"stored from the forward pass for use on the backward pass), \"\n- \"got {}.\")\n- raise TypeError(msg.format(pair_out))\n- py_outs, res = pair_out\n- out, out_tree = tree_flatten(py_outs)\n+ msg = (f\"Custom VJP fwd rule {fwd_name} for function {primal_name} \"\n+ \"must produce a pair (list or tuple of length two) where the first \"\n+ \"element represents the primal output (equal to those of the \"\n+ f\"custom_vjp-decorated function {primal_name}) and the \"\n+ \"second element represents residuals (i.e. values stored from the \"\n+ \"forward pass for use on the backward pass), but \"\n+ f\"instead of a pair the fwd rule {fwd_name} produced {pair_out}.\")\n+ raise TypeError(msg)\n+ py_primals_out, res = pair_out\n+ primals_out, out_tree = tree_flatten(py_primals_out)\nres, res_tree = tree_flatten(res)\n- yield res + out, (out_tree, res_tree)\n+ primal_avals = [core.raise_to_shaped(core.get_aval(x)) for x in primals_out]\n+ # If the primal function already ran, check out_tree agreement.\n+ try: out_type_ = maybe_out_type()\n+ except lu.StoreException: out_type_ = None\n+ if out_type_ is not None:\n+ out_tree_, primal_avals_ = out_type_\n+ ty_tree = tree_unflatten(out_tree , [a.str_short() for a in primal_avals])\n+ ty_tree_ = tree_unflatten(out_tree_, [a.str_short() for a in primal_avals_])\n+ if out_tree_ != out_tree:\n+ m = (f\"Custom VJP fwd rule {fwd_name} for function {primal_name} \"\n+ \"must produce a pair (list or tuple of length two) where the first \"\n+ \"element represents the primal output \"\n+ \"(equal to the output of the custom_vjp-decorated function \"\n+ f\"{primal_name}) and the \"\n+ \"second element represents residuals (i.e. values stored from the \"\n+ \"forward pass for use on the backward pass), but \"\n+ \"instead the fwd rule output's first element had container/pytree \"\n+ \"structure:\\n\"\n+ f\"\"\" {str(ty_tree ).replace(\"'\", \"\")}\\n\"\"\"\n+ f\"while the custom_vjp-decorated function {primal_name} had output \"\n+ \"container/pytree structure:\\n\"\n+ f\"\"\" {str(ty_tree_).replace(\"'\", \"\")}.\"\"\")\n+ raise TypeError(m)\n+ if not all(map(core.typematch, primal_avals, primal_avals_)):\n+ m = (f\"Custom VJP fwd rule {fwd_name} for function {primal_name} must \"\n+ \"produce a pair (list or tuple of length two) \"\n+ \"where the first element represents the primal output \"\n+ \"(equal to the output of the custom_vjp-decorated function \"\n+ f\"{primal_name}) and the second element represents residuals \"\n+ \"(i.e. values stored from the forward pass for use on the \"\n+ \"backward pass), but \"\n+ \"instead the fwd rule output's first element had shapes/dtypes of:\\n\"\n+ f\"\"\" {str(ty_tree ).replace(\"'\", \"\")}\\n\"\"\"\n+ f\"while the custom_vjp-decorated function {primal_name} had output \"\n+ \"shapes/dtypes of:\\n\"\n+ f\"\"\" {str(ty_tree_).replace(\"'\", \"\")}\"\"\")\n+ raise TypeError(m)\n+ yield (*res, *primals_out), (out_tree, res_tree)\n@lu.transformation\ndef _flatten_bwd(in_tree, in_avals, out_trees, *args):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -6322,7 +6322,8 @@ class CustomJVPTest(jtu.JaxTestCase):\nself.assertRaisesRegex(\nTypeError,\nre.escape(\n- \"Custom JVP rule must produce primal and tangent outputs \"\n+ \"Custom JVP rule foo_jvp for function f \"\n+ \"must produce primal and tangent outputs \"\n\"with equal container (pytree) structures, but got \"\n\"{} and {} respectively.\".format(\ntree_util.tree_structure((1,)),\n@@ -6367,10 +6368,65 @@ class CustomJVPTest(jtu.JaxTestCase):\nself.assertRaisesRegex(\nTypeError,\nre.escape(\n- \"Custom JVP rule must produce a pair (list or tuple of length two) \"\n- \"representing primal and tangent outputs, got 1.0\"),\n+ \"Custom JVP rule foo_jvp for function f \"\n+ \"must produce a pair (list or tuple of length two) \"\n+ \"representing primal and tangent outputs, but got 1.0\"),\nlambda: api.jvp(f, (2.,), (1.,)))\n+ def test_jvp_rule_primal_out_type_doesnt_match_primal_error_message(self):\n+ # https://github.com/lucidrains/flash-attention-jax/issues/7\n+\n+ def scan_apply(f, x):\n+ y, _ = jax.lax.scan(lambda x, _: (f(x), None), x, None, length=1)\n+ return y\n+\n+ @jax.custom_jvp\n+ def f(x):\n+ return x\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ (x,), (xdot,) = primals, tangents\n+ return (x, x), (xdot, xdot)\n+\n+ x = jnp.float32(1.)\n+ self.assertRaisesRegex(\n+ TypeError,\n+ re.escape(\n+ \"Custom JVP rule f_jvp for function f must produce a pair \"\n+ \"(list or tuple of length two) where the first element represents \"\n+ \"the primal output (equal in value to the output of the \"\n+ \"custom_jvp-decorated function f, and in particular of the \"\n+ \"same container/pytree structure), but instead the JVP rule \"\n+ \"output's first element had container/pytree structure:\\n\"\n+ \" (float32[], float32[])\\n\"\n+ \"while the custom_jvp-decorated function f had output \"\n+ \"container/pytree structure:\\n\"\n+ \" float32[].\"\n+ ),\n+ lambda: jax.jvp(lambda x: scan_apply(f, x), (x,), (x,)))\n+\n+ @f.defjvp\n+ def f_jvp2(primals, tangents):\n+ (x,), (xdot,) = primals, tangents\n+ return jnp.zeros((3, *x.shape), x.dtype), xdot\n+\n+ self.assertRaisesRegex(\n+ TypeError,\n+ re.escape(\n+ \"Custom JVP rule f_jvp2 for function f must produce a pair \"\n+ \"(list or tuple of length two) where the first element represents \"\n+ \"the primal output (equal in value to the output of the \"\n+ \"custom_jvp-decorated function f, and in particular \"\n+ \"with leaves of the same shape/dtype), but instead the JVP rule \"\n+ \"output's first element had shapes/dtypes of:\\n\"\n+ \" float32[3]\\n\"\n+ \"while the custom_jvp-decorated function f had output shapes/dtypes\"\n+ \" of:\\n\"\n+ \" float32[]\"\n+ ),\n+ lambda: jax.jvp(lambda x: scan_apply(f, x), (x,), (x,)))\n+\ndef test_multiple_rule_invocations(self):\n@jax.custom_jvp\ndef expit(x):\n@@ -7361,6 +7417,67 @@ class CustomVJPTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(TypeError, \"Custom VJP rule .* must produce a tuple\"):\napi.grad(f)(3.)\n+ def test_fwd_rule_primal_out_type_doesnt_match_primal_error_message(self):\n+ # https://github.com/lucidrains/flash-attention-jax/issues/7\n+\n+ def scan_apply(f, x):\n+ y, _ = jax.lax.scan(lambda x, _: (f(x), None), x, None, length=1)\n+ return y\n+\n+ @jax.custom_vjp\n+ def f(x):\n+ return x\n+\n+ def f_fwd(x):\n+ return (x, x), None\n+\n+ def f_bwd(_, y_bar):\n+ return (y_bar,)\n+\n+ f.defvjp(f_fwd, f_bwd)\n+\n+ self.assertRaisesRegex(\n+ TypeError,\n+ re.escape(\n+ \"Custom VJP fwd rule f_fwd for function f must produce a pair \"\n+ \"(list or tuple of length two) where the first element represents \"\n+ \"the primal output (equal to the output of the \"\n+ \"custom_vjp-decorated function f) and the second element \"\n+ \"represents residuals (i.e. values stored from the forward \"\n+ \"pass for use on the backward pass), but instead the fwd rule \"\n+ \"output's first element had container/pytree structure:\\n\"\n+ \" (float32[], float32[])\\n\"\n+ \"while the custom_vjp-decorated function f had output \"\n+ \"container/pytree structure:\\n\"\n+ \" float32[].\"\n+ ),\n+ lambda: jax.grad(lambda x: scan_apply(f, x))(jnp.float32(1.)))\n+\n+ def f_fwd2(x):\n+ return jnp.zeros((3, *x.shape), x.dtype), None\n+\n+ def f_bwd2(_, y_bar):\n+ return (y_bar,)\n+\n+ f.defvjp(f_fwd2, f_bwd2)\n+\n+ self.assertRaisesRegex(\n+ TypeError,\n+ re.escape(\n+ \"Custom VJP fwd rule f_fwd2 for function f must produce a pair \"\n+ \"(list or tuple of length two) where the first element represents \"\n+ \"the primal output (equal to the output of the \"\n+ \"custom_vjp-decorated function f) and the second element \"\n+ \"represents residuals (i.e. values stored from the forward \"\n+ \"pass for use on the backward pass), but instead the fwd rule \"\n+ \"output's first element had shapes/dtypes of:\\n\"\n+ \" float32[3]\\n\"\n+ \"while the custom_vjp-decorated function f had output \"\n+ \"shapes/dtypes of:\\n\"\n+ \" float32[]\"\n+ ),\n+ lambda: jax.grad(lambda x: scan_apply(f, x))(jnp.float32(1.)))\n+\ndef test_issue2511(self):\narr = jnp.ones((5, 2, 2))\nfoo = lambda x: api.vmap(jnp.linalg.det, (0,))(x)\n"
}
] | Python | Apache License 2.0 | google/jax | improve custom_jvp/vjp error messages
In particular:
* add function names so it's clear what decorated functions and rules
are causing the error;
* when possible (because the functions were run), check for agreement of pytree
structure and leaf shapes/dtypes between the primal function and rules
context: https://github.com/lucidrains/flash-attention-jax/issues/7 |
260,640 | 03.10.2022 13:38:45 | -7,200 | 27360b9988e863b8f8d5d474f3b77d3488f1e015 | Fix book links | [
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/autodiff_cookbook.ipynb",
"new_path": "docs/notebooks/autodiff_cookbook.ipynb",
"diff": "\"id\": \"MDl5UZl4oyzB\"\n},\n\"source\": [\n- \"This `grad` API has a direct correspondence to the excellent notation in Spivak's classic *Calculus on Manifolds* (1965), also used in Sussman and Wisdom's [*Structure and Interpretation of Classical Mechanics*](http://mitpress.mit.edu/sites/default/files/titles/content/sicm_edition_2/book.html) (2015) and their [*Functional Differential Geometry*](https://mitpress.mit.edu/books/functional-differential-geometry) (2013). Both books are open-access. See in particular the \\\"Prologue\\\" section of *Functional Differential Geometry* for a defense of this notation.\\n\",\n+ \"This `grad` API has a direct correspondence to the excellent notation in Spivak's classic *Calculus on Manifolds* (1965), also used in Sussman and Wisdom's [*Structure and Interpretation of Classical Mechanics*](https://mitpress.mit.edu/9780262028967/structure-and-interpretation-of-classical-mechanics) (2015) and their [*Functional Differential Geometry*](https://mitpress.mit.edu/9780262019347/functional-differential-geometry) (2013). Both books are open-access. See in particular the \\\"Prologue\\\" section of *Functional Differential Geometry* for a defense of this notation.\\n\",\n\"\\n\",\n\"Essentially, when using the `argnums` argument, if `f` is a Python function for evaluating the mathematical function $f$, then the Python expression `grad(f, i)` evaluates to a Python function for evaluating $\\\\partial_i f$.\"\n]\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/autodiff_cookbook.md",
"new_path": "docs/notebooks/autodiff_cookbook.md",
"diff": "@@ -125,7 +125,7 @@ print('b_grad', b_grad)\n+++ {\"id\": \"MDl5UZl4oyzB\"}\n-This `grad` API has a direct correspondence to the excellent notation in Spivak's classic *Calculus on Manifolds* (1965), also used in Sussman and Wisdom's [*Structure and Interpretation of Classical Mechanics*](http://mitpress.mit.edu/sites/default/files/titles/content/sicm_edition_2/book.html) (2015) and their [*Functional Differential Geometry*](https://mitpress.mit.edu/books/functional-differential-geometry) (2013). Both books are open-access. See in particular the \"Prologue\" section of *Functional Differential Geometry* for a defense of this notation.\n+This `grad` API has a direct correspondence to the excellent notation in Spivak's classic *Calculus on Manifolds* (1965), also used in Sussman and Wisdom's [*Structure and Interpretation of Classical Mechanics*](https://mitpress.mit.edu/9780262028967/structure-and-interpretation-of-classical-mechanics) (2015) and their [*Functional Differential Geometry*](https://mitpress.mit.edu/9780262019347/functional-differential-geometry) (2013). Both books are open-access. See in particular the \"Prologue\" section of *Functional Differential Geometry* for a defense of this notation.\nEssentially, when using the `argnums` argument, if `f` is a Python function for evaluating the mathematical function $f$, then the Python expression `grad(f, i)` evaluates to a Python function for evaluating $\\partial_i f$.\n"
}
] | Python | Apache License 2.0 | google/jax | Fix book links |
260,503 | 03.10.2022 10:39:07 | 25,200 | be56a3559d177d2aa0c6e80ac38626f11fb59ce7 | Add unsafe_buffer_pointer to _DeviceArray | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/device_array.py",
"new_path": "jax/_src/device_array.py",
"diff": "@@ -178,6 +178,10 @@ class _DeviceArray(DeviceArray): # type: ignore\nif self._npy_value is None:\nself.device_buffer.copy_to_host_async() # pytype: disable=attribute-error\n+ def unsafe_buffer_pointer(self):\n+ self._check_if_deleted()\n+ return self.device_buffer.unsafe_buffer_pointer() # pytype: disable=attribute-error\n+\ndef delete(self):\n\"\"\"Deletes the device array and any cached copy on the host.\n"
}
] | Python | Apache License 2.0 | google/jax | Add unsafe_buffer_pointer to _DeviceArray
PiperOrigin-RevId: 478544225 |
260,447 | 03.10.2022 11:55:48 | 25,200 | 58a2abe1b5496acb177a5fd10394e001c381bff9 | [sparse] Move broadcasting_vmap to sparse util. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcoo.py",
"new_path": "jax/experimental/sparse/bcoo.py",
"diff": "@@ -29,7 +29,7 @@ from jax import tree_util\nfrom jax import vmap\nfrom jax.config import config\nfrom jax.experimental.sparse._base import JAXSparse\n-from jax.experimental.sparse.util import _count_stored_elements, _safe_asarray, CuSparseEfficiencyWarning, SparseEfficiencyError, SparseEfficiencyWarning\n+from jax.experimental.sparse.util import _broadcasting_vmap, _count_stored_elements, _safe_asarray, CuSparseEfficiencyWarning, SparseEfficiencyError, SparseEfficiencyWarning\nfrom jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import mlir\n@@ -37,7 +37,6 @@ import jax.numpy as jnp\nfrom jax.interpreters import ad\nfrom jax.util import safe_zip, unzip2, split_list\nfrom jax._src import api_util\n-from jax._src.api_util import flatten_axes\nfrom jax._src.lax.lax import (\n_const, ranges_like, remaining, _dot_general_batch_dim_nums, _dot_general_shape_rule,\nDotDimensionNumbers)\n@@ -52,26 +51,6 @@ from jax._src.lib import gpu_sparse\nDtype = Any\nShape = Tuple[int, ...]\n-#----------------------------------------------------------------------\n-# General utilities...\n-def broadcasting_vmap(fun, in_axes=0, out_axes=0):\n- @functools.wraps(fun)\n- def batched_fun(*args):\n- args_flat, in_tree = tree_util.tree_flatten(args)\n- in_axes_flat = flatten_axes(\"vmap in_axes\", in_tree, in_axes, kws=False)\n- size = max(arg.shape[i] for arg, i in safe_zip(args_flat, in_axes_flat) if i is not None)\n- if size > 1:\n- if any(i is not None and arg.shape[i] not in (1, size)\n- for arg, i in safe_zip(args_flat, in_axes_flat)):\n- raise ValueError(\"broadcasting_vmap: mismatched input shapes\")\n- args_flat, in_axes_flat = zip(*(\n- (arg, None) if i is None else (lax.squeeze(arg, (i,)), None) if arg.shape[i] == 1 else (arg, i)\n- for arg, i in zip(args_flat, in_axes_flat)\n- ))\n- new_args = tree_util.tree_unflatten(in_tree, args_flat)\n- new_in_axes = tree_util.tree_unflatten(in_tree, in_axes_flat)\n- return vmap(fun, in_axes=new_in_axes, out_axes=out_axes)(*new_args)\n- return batched_fun\n#----------------------------------------------------------------------\n# BCOO primitives: batched extension of COO.\n@@ -682,7 +661,7 @@ def _bcoo_dot_general_impl(lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs\nelse:\nreturn prod.sum(tuple(range(prod.ndim - out_array.ndim)), dtype=out_array.dtype)\nfor _ in range(n_batch - len(lhs_contracting_b)):\n- result = broadcasting_vmap(result)\n+ result = _broadcasting_vmap(result)\nrhs = lax.expand_dims(rhs, range(len(rhs_batch), n_batch - len(lhs_contracting_b)))\nout_array = jnp.zeros(out_aval.shape, out_aval.dtype)\nreturn result(out_array, lhs_data, lhs_indices, rhs)\n@@ -1186,11 +1165,11 @@ def _bcoo_spdot_general_impl(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lh\nrhs_contracting=[d - rhs.n_batch for d in rhs_contracting])\nfor _ in reversed(range(len(rhs_batch), rhs.n_batch)):\n- func = broadcasting_vmap(func, in_axes=(None, None, 0, 0))\n+ func = _broadcasting_vmap(func, in_axes=(None, None, 0, 0))\nfor _ in reversed(range(len(lhs_batch), lhs.n_batch)):\n- func = broadcasting_vmap(func, in_axes=(0, 0, None, None))\n+ func = _broadcasting_vmap(func, in_axes=(0, 0, None, None))\nfor _ in range(len(lhs_batch)):\n- func = broadcasting_vmap(func, in_axes=0)\n+ func = _broadcasting_vmap(func, in_axes=0)\nreturn func(lhs_data, lhs_indices, rhs_data, rhs_indices)\n@bcoo_spdot_general_p.def_abstract_eval\n@@ -1326,7 +1305,7 @@ def _bcoo_sort_indices_impl(data, indices, *, spinfo):\nindices, perm = f(indices)\npermute = lambda d, p: d[p]\nfor _ in range(props.n_batch):\n- permute = broadcasting_vmap(permute)\n+ permute = _broadcasting_vmap(permute)\ndata = permute(data, perm)\nreturn data, indices\n@@ -1374,11 +1353,11 @@ def _bcoo_sort_indices_jvp(primals, tangents, *, spinfo):\ndata_dot, _ = tangents\nf = _bcoo_sort_indices_unbatched\nfor _ in range(props.n_batch):\n- f = broadcasting_vmap(f)\n+ f = _broadcasting_vmap(f)\nindices_out, perm = f(indices)\npermute = lambda d, p: d[p]\nfor _ in range(props.n_batch):\n- permute = broadcasting_vmap(permute)\n+ permute = _broadcasting_vmap(permute)\ndata_out = permute(data, perm)\nindices_dot_out = ad.Zero.from_value(indices)\n@@ -1440,7 +1419,7 @@ def _bcoo_sum_duplicates_impl(data, indices, *, spinfo, nse):\nnse, *data.shape[props.n_batch + 1:]), dtype=data.dtype)\npermute = lambda d_out, m, d: d_out.at[m].add(d, mode='drop')\nfor _ in range(props.n_batch):\n- permute = broadcasting_vmap(permute)\n+ permute = _broadcasting_vmap(permute)\ndata_out = permute(data_out, mapping, data)\nreturn data_out, indices_out\n@@ -1512,7 +1491,7 @@ def _bcoo_sum_duplicates_jvp(primals, tangents, *, spinfo, nse):\ndata_dot, _ = tangents\nf = functools.partial(_bcoo_sum_duplicates_unbatched, shape=spinfo.shape[props.n_batch:])\nfor _ in range(props.n_batch):\n- f = broadcasting_vmap(f)\n+ f = _broadcasting_vmap(f)\nindices_out, mapping, nse_batched = f(indices)\nif nse is None:\nnse = jnp.sum(nse_batched)\n@@ -1530,7 +1509,7 @@ def _bcoo_sum_duplicates_jvp(primals, tangents, *, spinfo, nse):\ndata_dot_out = data_out\npermute = lambda d_out, m, d: d_out.at[m].add(d, mode='drop')\nfor _ in range(props.n_batch):\n- permute = broadcasting_vmap(permute)\n+ permute = _broadcasting_vmap(permute)\ndata_out = permute(data_out, mapping, data)\nindices_dot_out = ad.Zero.from_value(indices_out)\ndata_dot_out = ad.Zero.from_value(data_out) if type(data_dot) is ad.Zero else permute(data_dot_out, mapping, data_dot)\n@@ -1630,7 +1609,7 @@ def bcoo_update_layout(mat, *, n_batch=None, n_dense=None, on_inefficient='error\n*map(jnp.ravel, meshes)])\nreturn new_d, new_i\nfor _ in range(current_n_batch + 1):\n- _update = broadcasting_vmap(_update)\n+ _update = _broadcasting_vmap(_update)\nnew_data, new_indices = _update(new_data, new_indices)\nnew_data = new_data.reshape(*new_data.shape[:current_n_batch],\nnp.prod(new_data.shape[current_n_batch:current_n_batch + 2]),\n@@ -1651,7 +1630,7 @@ def bcoo_update_layout(mat, *, n_batch=None, n_dense=None, on_inefficient='error\nnew_i = jnp.column_stack((*(m.ravel() for m in meshes[:-1]), new_i))\nreturn new_d, new_i\nfor _ in range(n_batch):\n- _update = broadcasting_vmap(_update)\n+ _update = _broadcasting_vmap(_update)\nnew_data, new_indices = _update(new_data, new_indices)\ncurrent_n_batch = n_batch\n@@ -1662,7 +1641,7 @@ def bcoo_update_layout(mat, *, n_batch=None, n_dense=None, on_inefficient='error\nnew_i = i[:-n]\nreturn new_d, new_i\nfor _ in range(current_n_batch + 1):\n- _update = broadcasting_vmap(_update)\n+ _update = _broadcasting_vmap(_update)\nnew_data, new_indices = _update(new_data, new_indices)\ncurrent_n_dense = n_dense\n@@ -1677,7 +1656,7 @@ def bcoo_update_layout(mat, *, n_batch=None, n_dense=None, on_inefficient='error\nnew_d = jnp.zeros_like(d, shape=new_d_shape).at[idx].set(d)\nreturn new_d, new_i\nfor _ in range(current_n_batch):\n- _update = broadcasting_vmap(_update)\n+ _update = _broadcasting_vmap(_update)\nnew_data, new_indices = _update(new_data, new_indices)\ncurrent_n_batch = n_batch\n@@ -2108,7 +2087,7 @@ def _bcoo_multiply_sparse(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_s\nlhs_shape=lhs_shape[n_batch:],\nrhs_shape=rhs_shape[n_batch:])\nfor _ in range(n_batch):\n- _mul = broadcasting_vmap(_mul)\n+ _mul = _broadcasting_vmap(_mul)\ndata, indices = _mul(lhs_data, lhs_indices, rhs_data, rhs_indices)\nreturn data, indices, jnp.broadcast_shapes(lhs_shape, rhs_shape)\n@@ -2179,7 +2158,7 @@ def _bcoo_multiply_dense(data, indices, v, *, spinfo):\nind = tuple(i if s != 1 else 0 for i, s in zip(ind, v.shape))\nreturn data * v[ind]\nfor _ in range(props.n_batch):\n- _mul = broadcasting_vmap(_mul)\n+ _mul = _broadcasting_vmap(_mul)\nreturn _mul(data, indices, v)\n@tree_util.register_pytree_node_class\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/util.py",
"new_path": "jax/experimental/sparse/util.py",
"diff": "\"\"\"Sparse utilities.\"\"\"\n+import functools\n+\nimport numpy as np\nimport jax\nfrom jax import core\n+from jax import lax\n+from jax import tree_util\n+from jax import vmap\nfrom jax._src import dtypes\nfrom jax._src import stages\n+from jax._src.api_util import flatten_axes\nimport jax.numpy as jnp\n+from jax.util import safe_zip\nclass SparseEfficiencyError(ValueError):\npass\n@@ -40,6 +47,25 @@ def _asarray_or_float0(arg):\nreturn arg\nreturn jnp.asarray(arg)\n+def _broadcasting_vmap(fun, in_axes=0, out_axes=0):\n+ @functools.wraps(fun)\n+ def batched_fun(*args):\n+ args_flat, in_tree = tree_util.tree_flatten(args)\n+ in_axes_flat = flatten_axes(\"vmap in_axes\", in_tree, in_axes, kws=False)\n+ size = max(arg.shape[i] for arg, i in safe_zip(args_flat, in_axes_flat) if i is not None)\n+ if size > 1:\n+ if any(i is not None and arg.shape[i] not in (1, size)\n+ for arg, i in safe_zip(args_flat, in_axes_flat)):\n+ raise ValueError(\"broadcasting_vmap: mismatched input shapes\")\n+ args_flat, in_axes_flat = zip(*(\n+ (arg, None) if i is None else (lax.squeeze(arg, (i,)), None) if arg.shape[i] == 1 else (arg, i)\n+ for arg, i in zip(args_flat, in_axes_flat)\n+ ))\n+ new_args = tree_util.tree_unflatten(in_tree, args_flat)\n+ new_in_axes = tree_util.tree_unflatten(in_tree, in_axes_flat)\n+ return vmap(fun, in_axes=new_in_axes, out_axes=out_axes)(*new_args)\n+ return batched_fun\n+\n@jax.jit\ndef _csr_to_coo(indices, indptr):\n\"\"\"Given CSR (indices, indptr) return COO (row, col)\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Move broadcasting_vmap to sparse util.
PiperOrigin-RevId: 478566197 |
260,447 | 04.10.2022 09:59:26 | 25,200 | ae49d2e033f5aa637d67c5679102cc1a21164e6e | [sparse] Add conversions between BCSR and BCOO. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcoo.py",
"new_path": "jax/experimental/sparse/bcoo.py",
"diff": "@@ -138,6 +138,27 @@ def _validate_bcoo_indices(indices: jnp.ndarray, shape: Sequence[int]) -> BCOOPr\nreturn BCOOProperties(n_batch=n_batch, n_sparse=n_sparse, n_dense=n_dense, nse=nse)\n+def _bcoo_to_bcsr(indices: jnp.ndarray, *, shape: Sequence[int],\n+ index_dtype=jnp.int32):\n+ \"\"\"Given BCOO (indices), return BCSR (indices, indptr).\"\"\"\n+ n_batch, n_sparse, _, _ = _validate_bcoo_indices(indices, shape)\n+\n+ if n_sparse != 2:\n+ raise ValueError(\"Must have 2 sparse dimensions to be converted to BCSR.\")\n+\n+ n_rows = shape[n_batch]\n+\n+ def get_ptr(i):\n+ indptr = jnp.zeros(n_rows + 1, index_dtype)\n+ return indptr.at[1:].set(jnp.cumsum(\n+ jnp.bincount(i, length=n_rows).astype(index_dtype)))\n+\n+ for _ in range(n_batch):\n+ get_ptr = vmap(get_ptr)\n+\n+ return indices[..., 1], get_ptr(indices[..., 0])\n+\n+\n#----------------------------------------------------------------------\n# bcoo_todense\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcsr.py",
"new_path": "jax/experimental/sparse/bcsr.py",
"diff": "\"\"\"BCSR (Bached compressed row) matrix object and associated primitives.\"\"\"\n-from typing import Tuple\n+from typing import NamedTuple, Sequence, Tuple\nfrom jax import core\nfrom jax.experimental.sparse._base import JAXSparse\n-from jax.experimental.sparse.util import _safe_asarray\n+from jax.experimental.sparse.util import _broadcasting_vmap, _csr_to_coo, _safe_asarray\nimport jax.numpy as jnp\n-from jax.util import split_list\n+from jax.util import split_list, safe_zip\nShape = Tuple[int, ...]\n+class BCSRProperties(NamedTuple):\n+ n_batch: int\n+ n_dense: int\n+ nse: int\n+\n+\n+def _compatible(shape1, shape2):\n+ return all(s1 in (1, s2) for s1, s2 in safe_zip(shape1, shape2))\n+\n+\n+def _validate_bcsr_indices(indices: jnp.ndarray, indptr: jnp.ndarray,\n+ shape: Sequence[int]) -> BCSRProperties:\n+ assert jnp.issubdtype(indices.dtype, jnp.integer)\n+ assert jnp.issubdtype(indptr.dtype, jnp.integer)\n+ shape = tuple(shape)\n+\n+ nse = indices.shape[-1]\n+ n_batch = indices.ndim - 1\n+ n_dense = len(shape) - n_batch - 2\n+ assert n_dense >= 0\n+\n+ if not _compatible(indices.shape[:n_batch], shape[:n_batch]):\n+ raise ValueError(\"indices batch dimensions not compatible for \"\n+ f\"indices.shape={indices.shape}, shape={shape}\")\n+ if not _compatible(indptr.shape[:n_batch], shape[:n_batch]):\n+ raise ValueError(\"indptr batch dimensions not compatible for \"\n+ f\"indptr.shape={indptr.shape}, shape={shape}\")\n+ if indptr.shape[n_batch:] != (shape[n_batch] + 1,):\n+ raise ValueError(\"indptr shape must match the matrix shape plus 1.\")\n+\n+ return BCSRProperties(n_batch=n_batch, n_dense=n_dense, nse=nse)\n+\n+\n+def _validate_bcsr(data: jnp.ndarray, indices: jnp.ndarray,\n+ indptr: jnp.ndarray, shape: Sequence[int]) -> BCSRProperties:\n+ props = _validate_bcsr_indices(indices, indptr, shape)\n+ shape = tuple(shape)\n+ n_batch, n_dense, nse = props.n_batch, props.n_dense, props.nse\n+ n_sparse = data.ndim - n_batch - n_dense\n+ if n_sparse != 2:\n+ raise ValueError(\"BCSR array must have 2 sparse dimensions; \"\n+ f\"{n_sparse} is given.\")\n+ if not _compatible(data.shape[:n_batch], shape[:n_batch]):\n+ raise ValueError(\"data batch dimensions not compatible for \"\n+ f\"data.shape={data.shape}, shape={shape}\")\n+ if data.shape[-(n_dense + 1):] != (nse,) + shape[n_batch + 2:]:\n+ raise ValueError(f\"Invalid data.shape={data.shape} for \"\n+ f\"nse={nse}, n_batch={n_batch}, n_dense={n_dense}\")\n+ return props\n+\n+\n+def _bcsr_to_bcoo(indices: jnp.ndarray, indptr: jnp.ndarray, *,\n+ shape: Sequence[int]) -> jnp.ndarray:\n+ \"\"\"Given BCSR (indices, indptr), return BCOO (indices).\"\"\"\n+ n_batch, _, _ = _validate_bcsr_indices(indices, indptr, shape)\n+ csr_to_coo = _csr_to_coo\n+ for _ in range(n_batch):\n+ csr_to_coo = _broadcasting_vmap(csr_to_coo)\n+ return jnp.stack(csr_to_coo(indices, indptr), axis=indices.ndim)\n+\n+\nclass BCSR(JAXSparse):\n\"\"\"Experimental batched CSR matrix implemented in JAX.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -31,6 +31,7 @@ from jax import dtypes\nfrom jax.experimental import sparse\nfrom jax.experimental.sparse import coo as sparse_coo\nfrom jax.experimental.sparse import bcoo as sparse_bcoo\n+from jax.experimental.sparse import bcsr as sparse_bcsr\nfrom jax.experimental.sparse.bcoo import BCOOInfo\nfrom jax import lax\nfrom jax._src.lib import xla_extension_version\n@@ -2498,6 +2499,40 @@ class SparseObjectTest(jtu.JaxTestCase):\nself.assertArraysEqual(M.sum(1), Msp.sum(1).todense())\nself.assertArraysEqual(M.sum(), Msp.sum())\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_nbatch={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), n_batch),\n+ \"shape\": shape, \"dtype\": dtype, \"n_batch\": n_batch}\n+ for shape in [(5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.complex\n+ for n_batch in range(len(shape) - 1)))\n+ def test_bcoo_to_bcsr_round_trip(self, shape, dtype, n_batch):\n+ rng = rand_sparse(self.rng())\n+ M = rng(shape, dtype)\n+ n_dense = len(shape) - 2 - n_batch\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\n+ _, bcoo_indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch,\n+ n_dense=n_dense)\n+\n+ bcoo_to_bcsr = partial(sparse_bcoo._bcoo_to_bcsr, shape=shape)\n+\n+ args_maker_bcoo_to_bcsr = lambda: [bcoo_indices]\n+ self._CompileAndCheck(bcoo_to_bcsr, args_maker_bcoo_to_bcsr)\n+\n+ bcsr_indices, indptr = bcoo_to_bcsr(bcoo_indices)\n+ bcsr_indices_jit, indptr_jit = jit(bcoo_to_bcsr)(bcoo_indices)\n+\n+ self.assertEqual(bcsr_indices.dtype, jnp.int32)\n+ self.assertEqual(bcsr_indices.shape, shape[:n_batch] + (nse,))\n+ self.assertEqual(indptr.dtype, jnp.int32)\n+ self.assertEqual(indptr.shape, shape[:n_batch] + (shape[n_batch] + 1,))\n+\n+ bcsr_to_bcoo = partial(sparse_bcsr._bcsr_to_bcoo, shape=shape)\n+ self.assertArraysEqual(bcoo_indices, bcsr_to_bcoo(bcsr_indices, indptr))\n+ args_maker_bcsr_to_bcoo = lambda: [bcsr_indices, indptr]\n+ self._CompileAndCheck(bcsr_to_bcoo, args_maker_bcsr_to_bcoo)\n+\nclass SparseRandomTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Add conversions between BCSR and BCOO.
PiperOrigin-RevId: 478816413 |
260,510 | 04.10.2022 12:14:13 | 25,200 | a60ca9f0519a63ade5399f3a9eeff7c24c92ab9c | Test that array layout is preserved in Python callbacks | [
{
"change_type": "MODIFY",
"old_path": "tests/python_callback_test.py",
"new_path": "tests/python_callback_test.py",
"diff": "@@ -800,6 +800,13 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\nout = f(np.arange(40.))\nnp.testing.assert_allclose(out, jnp.arange(1., 41.))\n+ def test_array_layout_is_preserved(self):\n+\n+ def g(x):\n+ return jax.pure_callback(lambda x: x, x, x)\n+\n+ x = np.arange(6, dtype=np.int32).reshape((3, 2))\n+ np.testing.assert_allclose(g(x), x)\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Test that array layout is preserved in Python callbacks
PiperOrigin-RevId: 478852392 |
260,335 | 29.09.2022 14:00:47 | 25,200 | 06a2c85d521aeb94781e9c473172eaa7cbf72dd7 | [dynamic-shapes] small fix to einsum (and indexing) | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -1456,6 +1456,10 @@ def _iter(tracer):\nraise TypeError(\"iteration over a 0-d array\") # same as numpy error\nelse:\nn = int(tracer.shape[0])\n+ if any(isinstance(d, core.Tracer) for d in tracer.shape):\n+ return (slicing.dynamic_index_in_dim(tracer, i, keepdims=False)\n+ for i in range(n))\n+ else:\nreturn (slicing.index_in_dim(tracer, i, keepdims=False) for i in range(n))\nShapedArray._iter = staticmethod(_iter)\ncore.DShapedArray._iter = staticmethod(_iter)\n@@ -3186,11 +3190,9 @@ def _squeeze_lower(ctx, operand, *, dimensions):\n).results\nelse:\nreturn mhlo.ReshapeOp(mlir.aval_to_ir_type(aval_out), operand).results\n-\nmlir.register_lowering(squeeze_p, _squeeze_lower)\n-\ndef shape_as_value(shape: core.Shape):\n\"\"\"Converts a shape that may contain Poly values into a JAX value.\"\"\"\nif len(shape) == 0:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -77,7 +77,8 @@ from jax._src.numpy.util import ( # noqa: F401\nfrom jax._src.numpy.vectorize import vectorize\nfrom jax._src.ops import scatter\nfrom jax._src.typing import Array, ArrayLike, DTypeLike\n-from jax._src.util import (unzip2, prod as _prod, subvals, safe_zip, ceil_of_ratio,\n+from jax._src.util import (unzip2, prod as _prod, subvals, safe_zip,\n+ ceil_of_ratio, partition_list,\ncanonicalize_axis as _canonicalize_axis)\nfrom jax._src.array import ArrayImpl\n@@ -2979,15 +2980,11 @@ def _einsum(operands: Sequence,\nreturn operand, names\ndef filter_singleton_dims(operand, names, other_shape, other_names):\n- s = shape(operand)\n- new_shape = []\n- new_names = []\n- for i, d in enumerate(names):\n- other_i = other_names.find(d)\n- if not core.symbolic_equal_dim(s[i], 1) or other_i == -1 or core.symbolic_equal_dim(other_shape[other_i], 1):\n- new_shape.append(s[i])\n- new_names.append(d)\n- return reshape(operand, tuple(new_shape)), \"\".join(new_names)\n+ eq = core.symbolic_equal_dim\n+ keep = [not eq(operand.shape[i], 1) or j == -1 or eq(other_shape[j], 1)\n+ for i, j in enumerate(map(other_names.find, names))]\n+ sqez_axes, keep_axes = partition_list(keep, list(range(operand.ndim)))\n+ return lax.squeeze(operand, sqez_axes), \"\".join(names[i] for i in keep_axes)\nfor operand_indices, contracted_names_set, einstr in contractions:\ncontracted_names = sorted(contracted_names_set)\n@@ -3658,6 +3655,10 @@ def _rewriting_take(arr, idx, indices_are_sorted=False, unique_indices=False,\nstep = idx.step if idx.step is not None else 1\nif (0 <= start < n and 0 <= stop <= n and 0 < step and\n(start, stop, step) != (0, n, 1)):\n+ if _any(isinstance(d, core.Tracer) for d in arr.shape[1:]):\n+ if step == 1: # TODO(mattjj, sharadmv): handle step != 1\n+ return lax.dynamic_slice_in_dim(arr, start, _max(0, stop - start), 0)\n+ else:\nreturn lax.slice_in_dim(arr, start, stop, step)\n# TODO(mattjj,dougalm): expand dynamic shape indexing support\n"
}
] | Python | Apache License 2.0 | google/jax | [dynamic-shapes] small fix to einsum (and indexing) |
260,510 | 04.10.2022 14:31:17 | 25,200 | 83ef7d09e78f9aa9521896a1de1889d42ccea307 | Fix collect_profile _src import | [
{
"change_type": "MODIFY",
"old_path": "jax/collect_profile.py",
"new_path": "jax/collect_profile.py",
"diff": "@@ -21,6 +21,7 @@ from typing import Optional\n# pytype: disable=import-error\nimport jax\n+from jax._src import profiler as jax_profiler\ntry:\nfrom tensorflow.python.profiler import profiler_v2 as profiler\nfrom tensorflow.python.profiler import profiler_client\n@@ -96,8 +97,8 @@ def collect_profile(port: int, duration_in_ms: int, host: str,\nfp.write(result.encode(\"utf-8\"))\nif not no_perfetto_link:\n- path = jax._src.profiler._write_perfetto_trace_file(str(log_dir_))\n- jax._src.profiler._host_perfetto_trace_file(path)\n+ path = jax_profiler._write_perfetto_trace_file(str(log_dir_))\n+ jax_profiler._host_perfetto_trace_file(path)\ndef main(args):\ncollect_profile(args.port, args.duration_in_ms, args.host, args.log_dir,\n"
}
] | Python | Apache License 2.0 | google/jax | Fix collect_profile _src import |
260,608 | 03.10.2022 22:52:03 | 0 | 78a7e161bb19e10d468fb02aa10c2cca7a217999 | Set JAX_PLATFORMS=tpu,cpu on TPUs | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/cloud_tpu_init.py",
"new_path": "jax/_src/cloud_tpu_init.py",
"diff": "@@ -48,6 +48,7 @@ def cloud_tpu_init():\nlibtpu.configure_library_path()\nos.environ.setdefault('GRPC_VERBOSITY', 'ERROR')\n+ os.environ.setdefault('JAX_PLATFORMS', 'tpu,cpu')\nos.environ['TPU_ML_PLATFORM'] = 'JAX'\n# If the user has set any topology-related env vars, don't set any\n"
}
] | Python | Apache License 2.0 | google/jax | Set JAX_PLATFORMS=tpu,cpu on TPUs |
260,608 | 04.10.2022 23:37:37 | 0 | ef559534ad7ad50fb216e218f4e542f9465853a5 | Add set up message for JAX_PLATFORMS | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lib/xla_bridge.py",
"new_path": "jax/_src/lib/xla_bridge.py",
"diff": "@@ -350,7 +350,8 @@ def backends():\n# we expect a RuntimeError.\nerr_msg = f\"Unable to initialize backend '{platform}': {err}\"\nif config.jax_platforms:\n- raise RuntimeError(err_msg)\n+ setup_msg = f\"(Set JAX_PLATFORMS='' to auto fallback to CPU or JAX_PLATFORMS=cpu to always use CPU)\"\n+ raise RuntimeError(err_msg + setup_msg)\nelse:\n_backends_errors[platform] = str(err)\nlogging.info(err_msg)\n"
}
] | Python | Apache License 2.0 | google/jax | Add set up message for JAX_PLATFORMS |
260,608 | 04.10.2022 23:53:07 | 0 | 22e1547e3cc21101840bfbf1c4b44fa0fd32d660 | Update set up message | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lib/xla_bridge.py",
"new_path": "jax/_src/lib/xla_bridge.py",
"diff": "@@ -350,7 +350,7 @@ def backends():\n# we expect a RuntimeError.\nerr_msg = f\"Unable to initialize backend '{platform}': {err}\"\nif config.jax_platforms:\n- setup_msg = f\"(Set JAX_PLATFORMS='' to auto fallback to CPU or JAX_PLATFORMS=cpu to always use CPU)\"\n+ setup_msg = f\" (set JAX_PLATFORMS='' to choose backend automatically)\"\nraise RuntimeError(err_msg + setup_msg)\nelse:\n_backends_errors[platform] = str(err)\n"
}
] | Python | Apache License 2.0 | google/jax | Update set up message |
260,608 | 05.10.2022 01:01:31 | 0 | 4870fd3be8eaeba1fb429c41e368e5d72b257c81 | Update message and change log | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -8,7 +8,12 @@ Remember to align the itemized text with the first line of an item within a list\nPLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n-->\n-## jax 0.3.22\n+## jax 0.3.22 (Oct 5, 2022)\n+* Changes\n+ * Add `JAX_PLATFORMS=tpu,cpu` as default setting in TPU initialization,\n+ so JAX will raise an error if TPU cannot be initialized instead of falling\n+ back to CPU. Users are able to override this behavior to automatically choose\n+ an available backend by setting `JAX_PLATFORMS=''`.\n## jaxlib 0.3.22\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lib/xla_bridge.py",
"new_path": "jax/_src/lib/xla_bridge.py",
"diff": "@@ -350,8 +350,8 @@ def backends():\n# we expect a RuntimeError.\nerr_msg = f\"Unable to initialize backend '{platform}': {err}\"\nif config.jax_platforms:\n- setup_msg = f\" (set JAX_PLATFORMS='' to choose backend automatically)\"\n- raise RuntimeError(err_msg + setup_msg)\n+ err_msg += \" (set JAX_PLATFORMS='' to automatically choose an available backend)\"\n+ raise RuntimeError(err_msg)\nelse:\n_backends_errors[platform] = str(err)\nlogging.info(err_msg)\n"
}
] | Python | Apache License 2.0 | google/jax | Update message and change log |
260,608 | 05.10.2022 18:16:49 | 0 | f3ded0fc1e45af47e99ea887c5bdbc0549072fb1 | Address comments for change log | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -8,12 +8,13 @@ Remember to align the itemized text with the first line of an item within a list\nPLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n-->\n-## jax 0.3.22 (Oct 5, 2022)\n+## jax 0.3.22\n* Changes\n* Add `JAX_PLATFORMS=tpu,cpu` as default setting in TPU initialization,\nso JAX will raise an error if TPU cannot be initialized instead of falling\n- back to CPU. Users are able to override this behavior to automatically choose\n- an available backend by setting `JAX_PLATFORMS=''`.\n+ back to CPU. Set `JAX_PLATFORMS=''` to override this behavior and automatically\n+ choose an available backend (the original default), or set `JAX_PLATFORMS=cpu`\n+ to always use CPU regardless of if the TPU is available.\n## jaxlib 0.3.22\n"
}
] | Python | Apache License 2.0 | google/jax | Address comments for change log |
260,335 | 05.10.2022 15:47:59 | 25,200 | e8dc6d14e488dfe09ff2c107a333ecd55e680ad4 | improve jit(f).lower(duck_args) and pjit(f).lower(duck_args) | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -3018,10 +3018,11 @@ def _valid_jaxtype(arg):\nclass ShapeDtypeStruct:\n- __slots__ = [\"shape\", \"dtype\", \"named_shape\"]\n- def __init__(self, shape, dtype, named_shape=None):\n+ __slots__ = [\"shape\", \"dtype\", \"named_shape\", \"sharding\"]\n+ def __init__(self, shape, dtype, sharding=None, named_shape=None):\nself.shape = shape\nself.dtype = dtype if core.is_opaque_dtype(dtype) else np.dtype(dtype)\n+ self.sharding = sharding\nself.named_shape = {} if named_shape is None else dict(named_shape)\nsize = property(lambda self: prod(self.shape))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/stages.py",
"new_path": "jax/_src/stages.py",
"diff": "@@ -379,6 +379,20 @@ class Compiled(Stage):\n\"\"\"\nreturn self._executable.runtime_executable()\n+ @property\n+ def input_shardings(self): # PyTree[XLACompatibleSharding]\n+ shardings_flat = getattr(self._executable, '_in_shardings', None)\n+ if shardings_flat is None:\n+ raise ValueError(\"no input_shardings on compiled object\")\n+ return tree_util.tree_unflatten(self.in_tree, shardings_flat) # pytype: disable=attribute-error\n+\n+ @property\n+ def output_shardings(self): # PyTree[XLACompatibleSharding]\n+ shardings_flat = getattr(self._executable, '_out_shardings', None)\n+ if shardings_flat is None:\n+ raise ValueError(\"no output_shardings on compiled object\")\n+ return tree_util.tree_unflatten(self.out_tree, shardings_flat) # pytype: disable=attribute-error\n+\ndef __call__(self, *args, **kwargs):\nif jax.config.jax_dynamic_shapes:\nraise NotImplementedError\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/pjit.py",
"new_path": "jax/experimental/pjit.py",
"diff": "@@ -438,14 +438,14 @@ def pjit(fun: Callable,\ndef lower(*args, _global_avals=False, **kwargs):\n(_, flat_local_in_avals, params, in_tree, out_tree,\ndonate_argnums) = infer_params(*args, _global_avals=_global_avals, **kwargs)\n- if any(_is_unspecified(i) for i in params['in_shardings']):\n- raise ValueError(\"Please specify sharding on pjit's in_axis_resources.\")\n+ in_shardings = _resolve_in_shardings(\n+ args, params['in_shardings'], params['out_shardings'],\n+ params['resource_env'].physical_mesh)\nin_is_global = _calc_is_global_sequence(\n- params['in_positional_semantics'], params['in_shardings'])\n+ params['in_positional_semantics'], in_shardings)\nlowering = _pjit_lower(\n- params['jaxpr'], params['in_shardings'],\n- params['out_shardings'], params['resource_env'],\n- params['donated_invars'], params['name'],\n+ params['jaxpr'], in_shardings, params['out_shardings'],\n+ params['resource_env'], params['donated_invars'], params['name'],\nin_is_global)\nargs_kwargs_in_tree = treedef_tuple([in_tree, tree_flatten({})[1]])\n"
}
] | Python | Apache License 2.0 | google/jax | improve jit(f).lower(duck_args) and pjit(f).lower(duck_args)
Co-authored-by: Yash Katariya <yashkatariya@google.com> |
260,335 | 05.10.2022 15:17:29 | 25,200 | ce95ebad945a63e9ef111e6ae99609d471e7b39a | make device_put work with Sharding 2nd arg | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -19,6 +19,7 @@ arguments and outputs. The Python containers handled are pytrees (see\ntree_util.py), which include nested tuples/lists/dicts, where the leaves are\narrays.\n\"\"\"\n+from __future__ import annotations\nimport collections\nimport functools\n@@ -2794,13 +2795,18 @@ def make_jaxpr(fun: Callable,\nreturn make_jaxpr_f\n-def device_put(x, device: Optional[xc.Device] = None):\n+def device_put(\n+ x, device: Optional[Union[xc.Device, jax.sharding.Sharding]] = None):\n\"\"\"Transfers ``x`` to ``device``.\nArgs:\nx: An array, scalar, or (nested) standard Python container thereof.\n- device: The (optional) :py:class:`Device` to which ``x`` should be\n- transferred. If given, then the result is committed to the device.\n+ device: The (optional) :py:class:`Device` or `Sharding` representing the\n+ device(s) to which ``x`` should be transferred. If given, then the result\n+ is committed to the device(s).\n+\n+ Returns:\n+ A copy of ``x`` that resides on ``device``.\nIf the ``device`` parameter is ``None``, then this operation behaves like the\nidentity function if the operand is on any device already, otherwise it\n@@ -2809,10 +2815,8 @@ def device_put(x, device: Optional[xc.Device] = None):\nFor more details on data placement see the\n:ref:`FAQ on data placement <faq-data-placement>`.\n- This function is always asynchronous, i.e. returns immediately.\n-\n- Returns:\n- A copy of ``x`` that resides on ``device``.\n+ This function is always asynchronous, i.e. returns immediately without\n+ blocking the calling Python thread until any transfers are completed.\n\"\"\"\nwith config_explicit_device_put_scope():\nreturn tree_map(lambda y: dispatch.device_put_p.bind(y, device=device), x)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -1291,15 +1291,39 @@ def _copy_array_to_device(x: jax.Array, device: Optional[xc.Device]) -> jax.Arra\ncommitted=(device is not None))\n-def _device_put_impl(x, device: Optional[Device] = None):\n+def _device_put_impl(\n+ x, device: Optional[Union[Device, jax.sharding.Sharding]] = None):\nfrom jax._src import array, sharding\n+ if not isinstance(device, (Device, jax.sharding.Sharding, type(None))):\n+ raise TypeError(\n+ \"device_put's second argument must be a Device, a Sharding, or None, \"\n+ f\"but got type {type(device)} with value {device}\")\n- if device_array.type_is_device_array(x):\n- return _copy_device_array_to_device(x, device)\n+ if isinstance(device, sharding.Sharding):\n+ if not device.is_fully_addressable(): # type: ignore\n+ raise ValueError(\n+ \"device_put's second argument must be a Device or a Sharding which \"\n+ f\"represents addressable devices, but got {sharding}\")\n+ if getattr(x, 'sharding', None) == device:\n+ return x\n+ # TODO(mattjj,yashkatariya,phawkins): runtime fast resharding here?\n+ return array.make_array_from_callback(x.shape, device, lambda idx: x[idx])\n+\n+ assert isinstance(device, (Device, type(None)))\n- if type(x) is array.ArrayImpl and isinstance(x.sharding, sharding.SingleDeviceSharding):\n+ if isinstance(x, array.ArrayImpl):\n+ if not x.is_fully_addressable():\n+ raise ValueError(\n+ \"device_put's first argument must be a fully addressable array, but \"\n+ f\"got value with devices {x.devices()}\")\n+ if device is None:\n+ return x\n+ elif is_single_device_sharding(x.sharding):\nreturn _copy_array_to_device(x, device)\n+ if device_array.type_is_device_array(x):\n+ return _copy_device_array_to_device(x, device)\n+\ntry:\na = xla.abstractify(x)\nexcept TypeError as err:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -1926,7 +1926,7 @@ def _convert_to_array_if_dtype_fails(x):\ndef asarray(a: Any, dtype: Optional[DTypeLike] = None, order: Any = None) -> Array:\nlax_internal._check_user_dtype_supported(dtype, \"asarray\")\ndtype = dtypes.canonicalize_dtype(dtype) if dtype is not None else dtype\n- return array(a, dtype=dtype, copy=False, order=order)\n+ return array(a, dtype=dtype, copy=False, order=order) # type: ignore\n@_wraps(np.copy, lax_description=_ARRAY_DOC)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -3462,7 +3462,7 @@ def is_op_sharding_replicated(op: xc.OpSharding) -> bool:\nif xla_extension_version >= 82:\nif len(op.tile_assignment_devices) == 1:\nreturn True\n- return xc.HloSharding.from_proto(op).is_replicated()\n+ return xc.HloSharding.from_proto(op).is_replicated() # type: ignore\nelse:\nreturn op.type == xc.OpSharding.Type.REPLICATED\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -56,6 +56,7 @@ from jax.interpreters import partial_eval as pe\nfrom jax.interpreters.pxla import PartitionSpec as P\nfrom jax._src import array, sharding\nfrom jax.experimental import pjit\n+from jax.experimental import maps\nfrom jax._src import config as jax_config\nfrom jax._src import custom_derivatives\nfrom jax._src import device_array\n@@ -1486,6 +1487,32 @@ class APITest(jtu.JaxTestCase):\nself.assertIsInstance(y2[1][1], np.ndarray)\nassert np.all(y2[1][1] == 3 * x)\n+ def test_device_put_sharding(self):\n+ mesh = maps.Mesh(jax.devices(), ('x',))\n+ s = sharding.MeshPspecSharding(mesh, P('x'))\n+ x = jnp.arange(len(jax.devices()))\n+ y = jax.device_put(x, s)\n+ self.assertEqual(y.sharding, s)\n+ self.assertArraysAllClose(y, x)\n+\n+ # this might hit a special fast path\n+ z = jax.device_put(y, s)\n+ self.assertEqual(z.sharding, s)\n+ self.assertArraysAllClose(z, x)\n+ self.assertIs(z, y) # no copy\n+\n+ w = jax.device_put(z)\n+ self.assertIs(w, z)\n+\n+ u = jax.device_put(y, jax.devices()[0])\n+ self.assertArraysAllClose(u, y)\n+ self.assertEqual(u.device(), jax.devices()[0])\n+\n+ # TODO(frostig): make this pass with JAX_ENABLE_CUSTOM_PRNG=1\n+ # # this can cover opaque dtypes\n+ # x = jax.random.split(jax.random.PRNGKey(0), len(jax.devices()))\n+ # jax.device_put(x, s) # doesn't crash\n+\ndef test_device_get_scalar(self):\nx = np.arange(12.).reshape((3, 4)).astype(\"float32\")\nx = api.device_put(x)\n"
}
] | Python | Apache License 2.0 | google/jax | make device_put work with Sharding 2nd arg
Co-authored-by: Yash Katariya <yashkatariya@google.com> |
260,335 | 06.10.2022 16:12:20 | 25,200 | bcca6fb57afd20c46172bb29f5c5a224b06f9f6c | add test, small fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -668,7 +668,7 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\n# this might naturally be a method, with ``fun`` as a ``self`` and\n# all the other arguments stored as attributes.\n- def arg_spec(x):\n+ def arg_spec(always_committed, x):\nfrom jax._src.sharding import PmapSharding\nfrom jax.experimental import pjit\n# like xla.arg_spec but duck-types on x.shape and x.dtype\n@@ -678,7 +678,7 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\nif isinstance(x.sharding, PmapSharding):\nreturn aval, None\nreturn aval, (pjit.to_op_sharding_sharding(x.sharding, x.ndim)\n- if x._committed else None)\n+ if getattr(x, '_committed', always_committed) else None)\nelse:\nreturn aval, None\nelse:\n@@ -699,7 +699,8 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\nclosed_fun, in_tree, args_flat, donated_invars = _prepare_jit(\nfun, static_argnums, static_argnames, donate_argnums, args, kwargs)\nflat_fun, out_tree = flatten_fun(closed_fun, in_tree)\n- arg_specs_and_devices = map(arg_spec, args_flat)\n+ always_committed = all(not hasattr(x, '_committed') for x in args_flat)\n+ arg_specs_and_devices = map(partial(arg_spec, always_committed), args_flat)\nif jax.config.jax_dynamic_shapes:\naxes_specs = (None if abstracted_axes is None else\n_flat_axes_specs(abstracted_axes, *args, **kwargs))\n@@ -3019,7 +3020,7 @@ def _valid_jaxtype(arg):\nclass ShapeDtypeStruct:\n__slots__ = [\"shape\", \"dtype\", \"named_shape\", \"sharding\"]\n- def __init__(self, shape, dtype, sharding=None, named_shape=None):\n+ def __init__(self, shape, dtype, named_shape=None, sharding=None):\nself.shape = shape\nself.dtype = dtype if core.is_opaque_dtype(dtype) else np.dtype(dtype)\nself.sharding = sharding\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/stages.py",
"new_path": "jax/_src/stages.py",
"diff": "@@ -28,6 +28,7 @@ Finally, this module defines a couple more classes to commonly adapt our\nvarious internal XLA-backed lowerings and executables into the lowering and\nexecutable protocols described above.\n\"\"\"\n+from __future__ import annotations\nimport warnings\n@@ -40,7 +41,6 @@ from jax import core\nfrom jax import tree_util\nfrom jax.lib import xla_client as xc\n-from jax._src import sharding\nfrom jax._src import source_info_util\nfrom jax._src import traceback_util\nfrom jax._src import util\n@@ -66,7 +66,7 @@ class Executable(Protocol):\n# TODO(frostig): improve annotation (sequences of arrays/buffers)\nraise NotImplementedError\n- def input_shardings(self) -> Sequence[sharding.XLACompatibleSharding]:\n+ def input_shardings(self) -> Sequence[jax.sharding.XLACompatibleSharding]:\n\"\"\"Flat sequence of input shardings.\nMay raise ``NotImplementedError`` if unavailable, e.g. based on backend,\n@@ -74,7 +74,7 @@ class Executable(Protocol):\n\"\"\"\nraise NotImplementedError\n- def output_shardings(self) -> Sequence[sharding.XLACompatibleSharding]:\n+ def output_shardings(self) -> Sequence[jax.sharding.XLACompatibleSharding]:\n\"\"\"Flat sequence of output shardings.\nMay raise ``NotImplementedError`` if unavailable, e.g. based on backend,\n@@ -179,11 +179,11 @@ class XlaExecutable(Executable):\ndef call(self, *args_flat) -> Sequence[Any]:\nraise NotImplementedError(\"must override\")\n- def input_shardings(self) -> Sequence[sharding.XLACompatibleSharding]:\n+ def input_shardings(self) -> Sequence[jax.sharding.XLACompatibleSharding]:\nraise NotImplementedError(\n\"compiled executable carries no input sharding information\")\n- def output_shardings(self) -> Sequence[sharding.XLACompatibleSharding]:\n+ def output_shardings(self) -> Sequence[jax.sharding.XLACompatibleSharding]:\nraise NotImplementedError(\n\"compiled executable carries no output sharding information\")\n@@ -498,8 +498,10 @@ class Lowered(Stage):\ndef compile(self) -> Compiled:\n\"\"\"Compile, returning a corresponding ``Compiled`` instance.\"\"\"\n- return Compiled(self._lowering.compile(), self.args_info,\n- self.out_tree, no_kwargs=self._no_kwargs)\n+ kw = (dict(_allow_propagation_to_outputs=True) if jax.config.jax_array\n+ else {})\n+ return Compiled(self._lowering.compile(**kw), self.args_info, self.out_tree,\n+ no_kwargs=self._no_kwargs)\ndef as_text(self, dialect: Optional[str] = None) -> str:\n\"\"\"A human-readable text representation of this lowering.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/pjit.py",
"new_path": "jax/experimental/pjit.py",
"diff": "@@ -436,11 +436,14 @@ def pjit(fun: Callable,\nwrapped = _python_pjit(fun, infer_params)\ndef lower(*args, _global_avals=False, **kwargs):\n- (_, flat_local_in_avals, params, in_tree, out_tree,\n+ (args_flat, flat_local_in_avals, params, in_tree, out_tree,\ndonate_argnums) = infer_params(*args, _global_avals=_global_avals, **kwargs)\n+ if config.jax_array:\nin_shardings = _resolve_in_shardings(\n- args, params['in_shardings'], params['out_shardings'],\n+ args_flat, params['in_shardings'], params['out_shardings'],\nparams['resource_env'].physical_mesh)\n+ else:\n+ in_shardings = params['in_shardings']\nin_is_global = _calc_is_global_sequence(\nparams['in_positional_semantics'], in_shardings)\nlowering = _pjit_lower(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -53,6 +53,7 @@ from jax.interpreters import mlir\nfrom jax.interpreters import xla\nfrom jax.interpreters import pxla\nfrom jax.interpreters import partial_eval as pe\n+from jax.experimental import maps\nfrom jax.interpreters.pxla import PartitionSpec as P\nfrom jax._src import array, sharding\nfrom jax.experimental import pjit\n@@ -2121,6 +2122,23 @@ class APITest(jtu.JaxTestCase):\nself.assertEqual(hash(s1), hash(s2))\nself.assertNotEqual(hash(s1), hash(s3))\n+ @jax_config.jax_array(True)\n+ def test_shape_dtype_struct_sharding(self):\n+ mesh = maps.Mesh(jax.devices(), ('x',))\n+ s = sharding.MeshPspecSharding(mesh, P('x'))\n+\n+ x = jax.ShapeDtypeStruct(\n+ shape=(3,),\n+ dtype=jnp.dtype('float32'),\n+ sharding=s)\n+\n+ def f(x):\n+ return x * 2\n+\n+ c = jit(f).lower(x).compile()\n+ print(c.input_shardings )\n+ print(c.output_shardings)\n+\ndef test_eval_shape(self):\ndef fun(x, y):\nreturn jnp.tanh(jnp.dot(x, y) + 3.)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/array_test.py",
"new_path": "tests/array_test.py",
"diff": "@@ -481,6 +481,42 @@ class JaxArrayTest(jtu.JaxTestCase):\nx = jnp.array([1, 2, 3])\nself.assertIsInstance(x.device_buffer, array.ArrayImpl)\n+ def test_shape_dtype_struct_sharding(self):\n+ mesh = maps.Mesh(np.array(jax.devices()).reshape(4, 2), ('x', 'y'))\n+ s = sharding.MeshPspecSharding(mesh, P('x', 'y'))\n+\n+ def f(x):\n+ return x * 2.\n+\n+ # x_dummy = jax.ShapeDtypeStruct(\n+ # shape=(8, 2),\n+ # dtype=jnp.dtype('float32'),\n+ # sharding=s)\n+ import types\n+ x_dummy = types.SimpleNamespace(\n+ shape=(8, 2),\n+ dtype=jnp.dtype('float32'),\n+ sharding=s,\n+ _committed=True,\n+ ndim=2,\n+ )\n+\n+ # from jax.experimental.pjit import pjit\n+ # c = pjit(f).lower(x_dummy).compile()\n+ c = jax.jit(f).lower(x_dummy).compile()\n+ # input_shardings, output_shardings = c.input_shardings, c.output_shardings\n+ # self.assertIsInstance(input_shardings, tuple)\n+ # self.assertLen(input_shardings, 2)\n+ # self.assertEqual(input_shardings[1], {})\n+ # self.assertEqual(input_shardings[1], {})\n+\n+ x_data = jnp.arange(8 * 2.).reshape(8, 2)\n+ x = array.make_array_from_callback((8, 2), s, lambda idx: x_data[idx])\n+ y = jax.jit(f)(x)\n+ print(y.sharding)\n+ print(c.output_shardings)\n+ # self.assertEqual(y.sharding, c.output_shardings)\n+\n@jtu.with_config(jax_array=True)\nclass ShardingTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | add test, small fixes
Co-authored-by: Yash Katariya <yashkatariya@google.com> |
260,447 | 06.10.2022 17:28:16 | 25,200 | 7a825362faebde6ca7ffbf3a50d59042d2a5ae0b | [sparse] Bug fix in _validate_bcsr. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcsr.py",
"new_path": "jax/experimental/sparse/bcsr.py",
"diff": "@@ -63,7 +63,7 @@ def _validate_bcsr(data: jnp.ndarray, indices: jnp.ndarray,\nprops = _validate_bcsr_indices(indices, indptr, shape)\nshape = tuple(shape)\nn_batch, n_dense, nse = props.n_batch, props.n_dense, props.nse\n- n_sparse = data.ndim - n_batch - n_dense\n+ n_sparse = len(shape) - n_batch - n_dense\nif n_sparse != 2:\nraise ValueError(\"BCSR array must have 2 sparse dimensions; \"\nf\"{n_sparse} is given.\")\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Bug fix in _validate_bcsr.
PiperOrigin-RevId: 479452053 |
260,335 | 06.10.2022 23:15:22 | 25,200 | 076a7348d051a8f0091ae9fe708b7d80c666d14b | fix -O / PYTHONOPTIMIZE bug
fixes
I'm not sure how to write test cases for PYTHONOPTIMIZE=1 (without growing our
whole test matrix), so I'm leaving this untested... | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -898,7 +898,8 @@ def tracers_to_jaxpr(\ndef newvar(t: JaxprTracer) -> Var:\nvar = gensym(type_substitute(t.aval))\n- assert t_to_var.setdefault(id(t), var) is var\n+ var_ = t_to_var.setdefault(id(t), var)\n+ assert var is var_\nreturn var\ndef type_substitute(aval: AbstractValue) -> AbstractValue:\n"
}
] | Python | Apache License 2.0 | google/jax | fix -O / PYTHONOPTIMIZE bug
fixes #12688
I'm not sure how to write test cases for PYTHONOPTIMIZE=1 (without growing our
whole test matrix), so I'm leaving this untested... |
260,411 | 07.10.2022 14:13:20 | -10,800 | 7c7c94c8ddba1737931f3f95575682f20f37f0d2 | Expand support for __jax_array__ in jnp.array.
This relates to the long discussion in and | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -1862,6 +1862,8 @@ def array(object: Any, dtype: Optional[DTypeLike] = None, copy: bool = True,\nif isinstance(object, (bool, int, float, complex)):\n_ = dtypes.coerce_to_array(object, dtype)\n+ object = tree_map(lambda leaf: leaf.__jax_array__() if hasattr(leaf, \"__jax_array__\") else leaf,\n+ object)\nleaves = tree_leaves(object)\nif dtype is None:\n# Use lattice_result_type rather than result_type to avoid canonicalization.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -3574,6 +3574,13 @@ class APITest(jtu.JaxTestCase):\nfor f in [jnp.isscalar, jnp.size, jnp.shape, jnp.dtype]:\nself.assertEqual(f(x), f(a))\n+ x = AlexArray(jnp.array(1))\n+ a1 = jnp.array(x)\n+ self.assertAllClose(1, a1)\n+\n+ a2 = jnp.array(((x, x), [x, x]))\n+ self.assertAllClose(np.array(((1, 1), (1, 1))), a2)\n+\ndef test_constant_handler_mro(self):\n# https://github.com/google/jax/issues/6129\n"
}
] | Python | Apache License 2.0 | google/jax | Expand support for __jax_array__ in jnp.array.
This relates to the long discussion in #4725 and #10065. |
260,661 | 07.10.2022 19:57:53 | 0 | 34f6646050687e3391f4e824591b7e4b280666a1 | Add default setting for TENSORFLOW_ROCM_COMMIT | [
{
"change_type": "MODIFY",
"old_path": "build/rocm/ci_build.sh",
"new_path": "build/rocm/ci_build.sh",
"diff": "@@ -101,6 +101,7 @@ fi\n# Run the command inside the container.\necho \"Running '${POSITIONAL_ARGS[*]}' inside ${DOCKER_IMG_NAME}...\"\n+export TENSORFLOW_ROCM_COMMIT=\"${TENSORFLOW_ROCM_COMMIT:-}\"\ndocker run ${KEEP_IMAGE} --name ${DOCKER_IMG_NAME} --pid=host \\\n-v ${WORKSPACE}:/workspace \\\n"
}
] | Python | Apache License 2.0 | google/jax | Add default setting for TENSORFLOW_ROCM_COMMIT |
260,335 | 07.10.2022 16:48:34 | 25,200 | 0a0f492a3dc9f52ea401453aaf725416e9a2082c | make device_put(prngkeyarray, sharding) for Array | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/array.py",
"new_path": "jax/_src/array.py",
"diff": "@@ -116,6 +116,8 @@ class ArrayImpl(basearray.Array):\narrays: Union[Sequence[DeviceArray], Sequence[ArrayImpl]],\ncommitted: bool, _skip_checks: bool = False):\n# NOTE: the actual implementation of the constructor is moved to C++.\n+ assert all(isinstance(a, DeviceArray) or hasattr(a, '_arrays')\n+ for a in arrays)\nself.aval = aval\nself._sharding = sharding\n@@ -545,39 +547,17 @@ def _array_pmap_shard_arg(x, devices, indices, mode):\nreturn pxla._shard_sharded_device_array_slow_path(x, devices, indices, mode)\n-def _array_rest_shard_arg(x, devices, indices, mode):\n- if not x._committed:\n- if dispatch.is_single_device_sharding(x.sharding):\n- # This condition is to break the recursion that happens when only\n- # `pxla._shard_device_array` is used since it has `_multi_slice` in the\n- # implementation which is jitted. Eventually it calls back here and the\n- # recursion happens.\n- x_indices = tuple(x.sharding.addressable_devices_indices_map(x.shape).values())\n- if x_indices == indices:\n+def _array_rest_shard_arg(x: ArrayImpl, devices, indices, mode):\n+ x_indices = x.sharding.addressable_devices_indices_map(x.shape).values()\n+ if tuple(indices) == tuple(x_indices):\nreturn [buf if buf.device() == d else buf.copy_to_device(d)\nfor buf, d in safe_zip(x._arrays, devices)]\n- return pxla._shard_device_array(x, devices, indices, mode)\n- else:\n- raise NotImplementedError('Resharding uncommitted arrays sharded over '\n- 'multiple devices is not supported.')\n- # TODO(yashkatariya): Remove the special case here and don't move to another\n- # device if its already committed. There is a TODO in dispatch.py already\n- # for this.\n- if dispatch.is_single_device_sharding(x.sharding):\n- return [buf if buf.device() == d else buf.copy_to_device(d)\n- for buf, d in safe_zip(x._arrays, devices)]\n- # If PmapSharding exists, then do a round trip via host. This will happen\n- # if the input Array containing PmapSharding takes the jit path\n- # i.e. `apply_primitive` or `xla_callable_uncached`. `jit(pmap)` is the most\n- # common case where this will happen.\n- # TODO(yashkatariya): Remove the special case here and don't move to another\n- # device if its already committed. There is a TODO in dispatch.py already\n- # for this.\nelif isinstance(x.sharding, PmapSharding):\nreturn pxla.device_put(x._value, devices, replicate=True)\n+ elif x.is_fully_addressable():\n+ return pxla._shard_device_array(x, devices, indices, mode)\nelse:\n- return x._arrays\n-\n+ raise NotImplementedError(\"foo\")\ndef _array_shard_arg(x, devices, indices, mode):\nif mode == pxla.InputsHandlerMode.pmap:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -1295,16 +1295,28 @@ def _copy_array_to_device(x: jax.Array, device: Optional[xc.Device]) -> jax.Arra\ndef _device_put_impl(\nx, device: Optional[Union[Device, jax.sharding.Sharding]] = None):\nfrom jax._src import array, sharding\n+ from jax.interpreters import pxla\n+\n+ try:\n+ a = xla.abstractify(x)\n+ except TypeError as err:\n+ raise TypeError(\n+ f\"Argument '{x}' of type {type(x)} is not a valid JAX type\") from err\nif isinstance(device, sharding.Sharding):\n- if not device.is_fully_addressable(): # type: ignore\n+ s = device\n+ if not s.is_fully_addressable(): # type: ignore\nraise ValueError(\n\"device_put's second argument must be a Device or a Sharding which \"\nf\"represents addressable devices, but got {sharding}\")\n- if getattr(x, 'sharding', None) == device:\n+ if getattr(x, 'sharding', None) == s:\nreturn x\n- # TODO(mattjj,yashkatariya,phawkins): runtime fast resharding here?\n- return array.make_array_from_callback(x.shape, device, lambda idx: x[idx])\n+ # TODO(mattjj,yashkatariya,phawkins): more runtime fast resharding here?\n+ arg_handler = pxla.shard_arg_handlers[type(x)]\n+ result_handler = array._array_global_result_handler(a, s, True, False)\n+ map_ = s.devices_indices_map(x.shape)\n+ return result_handler(arg_handler(x, list(map_), list(map_.values()),\n+ pxla.InputsHandlerMode.pjit_or_xmap))\n# Only `Device` exists below. `Sharding` instance is handled above.\nif isinstance(x, array.ArrayImpl):\n@@ -1320,11 +1332,6 @@ def _device_put_impl(\nif device_array.type_is_device_array(x):\nreturn _copy_device_array_to_device(x, device)\n- try:\n- a = xla.abstractify(x)\n- except TypeError as err:\n- raise TypeError(\n- f\"Argument '{x}' of type {type(x)} is not a valid JAX type\") from err\nreturn aval_to_result_handler(device, a)(None, *device_put(x, device))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1491,6 +1491,7 @@ class APITest(jtu.JaxTestCase):\nmesh = maps.Mesh(jax.devices(), ('x',))\ns = sharding.MeshPspecSharding(mesh, P('x'))\nx = jnp.arange(len(jax.devices()))\n+\ny = jax.device_put(x, s)\nself.assertEqual(y.sharding, s)\nself.assertArraysAllClose(y, x)\n@@ -1508,11 +1509,6 @@ class APITest(jtu.JaxTestCase):\nself.assertArraysAllClose(u, y)\nself.assertEqual(u.device(), jax.devices()[0])\n- # TODO(frostig): make this pass with JAX_ENABLE_CUSTOM_PRNG=1\n- # # this can cover opaque dtypes\n- # x = jax.random.split(jax.random.PRNGKey(0), len(jax.devices()))\n- # jax.device_put(x, s) # doesn't crash\n-\ndef test_device_get_scalar(self):\nx = np.arange(12.).reshape((3, 4)).astype(\"float32\")\nx = api.device_put(x)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pjit_test.py",
"new_path": "tests/pjit_test.py",
"diff": "@@ -41,6 +41,7 @@ from jax.experimental import PartitionSpec as P\nfrom jax.experimental.maps import xmap\nfrom jax.experimental import global_device_array\nfrom jax._src import array\n+from jax._src import sharding\nfrom jax._src.sharding import MeshPspecSharding, Sharding, OpShardingSharding\nimport jax.experimental.pjit as pjit_lib\nfrom jax.experimental.pjit import (pjit, pjit_p, with_sharding_constraint,\n@@ -2291,6 +2292,17 @@ class ArrayPjitTest(jtu.JaxTestCase):\ncache_info3 = OpShardingSharding.devices_indices_map.cache_info()\nself.assertEqual(cache_info3.hits, cache_info2.hits + 1)\n+ @jax_array(True)\n+ def test_device_put_sharding_prng(self):\n+ mesh = jtu.create_global_mesh((8,), ('x',))\n+ s = sharding.MeshPspecSharding(mesh, P('x'))\n+\n+ x = jax.random.split(jax.random.PRNGKey(0), len(jax.devices()))\n+ y = jax.device_put(x, s) # doesn't crash\n+\n+ if config.jax_enable_custom_prng:\n+ self.assertIsInstance(y, jax.random.KeyArray)\n+\nclass ArrayCppPjitTest(ArrayPjitTest):\n"
}
] | Python | Apache License 2.0 | google/jax | make device_put(prngkeyarray, sharding) for Array
Co-authored-by: Yash Katariya <yashkatariya@google.com>
Co-authored-by: Roy Frostig <frostig@google.com> |
260,447 | 10.10.2022 11:53:45 | 25,200 | 34eb6ce36b929e71956f9123f1452d127c1955a5 | [sparse] BCSR fromdense and todense. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/__init__.py",
"new_path": "jax/experimental/sparse/__init__.py",
"diff": "@@ -218,8 +218,13 @@ from jax.experimental.sparse.bcoo import (\n)\nfrom jax.experimental.sparse.bcsr import (\n+ bcsr_fromdense as bcsr_fromdense,\n+ bcsr_fromdense_p as bcsr_fromdense_p,\n+ bcsr_todense as bcsr_todense,\n+ bcsr_todense_p as bcsr_todense_p,\nBCSR as BCSR,\n)\n+\nfrom jax.experimental.sparse.api import (\nempty as empty,\neye as eye,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcsr.py",
"new_path": "jax/experimental/sparse/bcsr.py",
"diff": "\"\"\"BCSR (Bached compressed row) matrix object and associated primitives.\"\"\"\n+import operator\n+\nfrom typing import NamedTuple, Sequence, Tuple\n+import numpy as np\n+\nfrom jax import core\nfrom jax.experimental.sparse._base import JAXSparse\n-from jax.experimental.sparse.util import _broadcasting_vmap, _csr_to_coo, _safe_asarray\n+from jax.experimental.sparse import bcoo\n+from jax.experimental.sparse.util import _broadcasting_vmap, _count_stored_elements, _csr_to_coo, _safe_asarray\nimport jax.numpy as jnp\nfrom jax.util import split_list, safe_zip\n+from jax.interpreters import mlir\nShape = Tuple[int, ...]\n@@ -86,6 +92,146 @@ def _bcsr_to_bcoo(indices: jnp.ndarray, indptr: jnp.ndarray, *,\nreturn jnp.stack(csr_to_coo(indices, indptr), axis=indices.ndim)\n+#--------------------------------------------------------------------\n+# bcsr_fromdense\n+bcsr_fromdense_p = core.Primitive('bcsr_fromdense')\n+bcsr_fromdense_p.multiple_results = True\n+\n+\n+_TRACED_NSE_ERROR = \"\"\"\n+The error arose for the nse argument of bcsr_fromdense. In order for\n+BCSR.fromdense() to be used in traced/compiled code, you must pass a concrete\n+value to the nse (number of stored elements) argument.\n+\"\"\"\n+\n+\n+def bcsr_fromdense(mat, *, nse=None, n_batch=0, n_dense=0, index_dtype=jnp.int32):\n+ \"\"\"Create BCSR-format sparse matrix from a dense matrix.\n+\n+ Args:\n+ mat : array to be converted to BCOO.\n+ nse : number of stored elements in each batch\n+ n_batch : number of batch dimensions (default: 0)\n+ n_dense : number of dense dimensions (default: 0)\n+ index_dtype : dtype of sparse indices (default: int32)\n+\n+ Returns:\n+ mat_bcsr: BCSR representation of the matrix.\n+ \"\"\"\n+ mat = jnp.asarray(mat)\n+ if nse is None:\n+ nse = _count_stored_elements(mat, n_batch, n_dense)\n+ nse = core.concrete_or_error(operator.index, nse, _TRACED_NSE_ERROR)\n+ return BCSR(_bcsr_fromdense(mat, nse=nse, n_batch=n_batch, n_dense=n_dense,\n+ index_dtype=index_dtype),\n+ shape=mat.shape)\n+\n+\n+def _bcsr_fromdense(mat, *, nse, n_batch=0, n_dense=0, index_dtype=jnp.int32):\n+ \"\"\"Create BCSR-format sparse matrix from a dense matrix.\n+\n+ Args:\n+ mat : array to be converted to BCSR, with\n+ ``ndim = n_batch + n_sparse + n_dense``.\n+ nse : number of stored elements in each batch.\n+ n_batch : number of batch dimensions (default: 0)\n+ n_dense : number of dense dimensions (default: 0)\n+ index_dtype : dtype of sparse indices (default: int32)\n+\n+ Returns:\n+ data : array of shape\n+ ``mat.shape[:n_batch] + (nse,) + mat.shape[mat.ndim - n_dense:]``\n+ and dtype ``mat.dtype``\n+ indices : array of shape ``mat.shape[:n_batch] + (nse,)`` and dtype of\n+ ``index_type``.\n+ indptr: array of shape ``mat.shape[:n_batch] + (mat.shape[n_batch] + 1,)``\n+ and dtype of ``index_type``.\n+ \"\"\"\n+ mat = jnp.asarray(mat)\n+ nse = core.concrete_or_error(operator.index, nse, _TRACED_NSE_ERROR)\n+ return bcsr_fromdense_p.bind(mat, nse=nse, n_batch=n_batch, n_dense=n_dense,\n+ index_dtype=index_dtype)\n+\n+\n+@bcsr_fromdense_p.def_impl\n+def _bcsr_fromdense_impl(mat, *, nse, n_batch, n_dense, index_dtype):\n+ mat = jnp.asarray(mat)\n+ n_sparse = mat.ndim - n_dense - n_batch\n+ if n_sparse != 2:\n+ raise ValueError(\"bcsr_fromdense: must have 2 sparse dimensions.\")\n+ bcoo_mat = bcoo.bcoo_fromdense(mat, nse=nse, index_dtype=index_dtype,\n+ n_dense=n_dense, n_batch=n_batch)\n+ indices, indptr = bcoo._bcoo_to_bcsr(bcoo_mat.indices, shape=mat.shape)\n+ return bcoo_mat.data, indices, indptr\n+\n+\n+@bcsr_fromdense_p.def_abstract_eval\n+def _bcoo_fromdense_abstract_eval(mat, *, nse, n_batch, n_dense, index_dtype):\n+ n_sparse = mat.ndim - n_batch - n_dense\n+ if n_sparse != 2:\n+ raise ValueError(\"bcsr_fromdense: must have 2 sparse dimensions.\")\n+ data_shape = mat.shape[:n_batch] + (nse,) + mat.shape[n_batch + n_sparse:]\n+ index_shape = mat.shape[:n_batch] + (nse,)\n+ indptr_shape = mat.shape[:n_batch] + (mat.shape[n_batch] + 1,)\n+ return (core.ShapedArray(data_shape, mat.dtype),\n+ core.ShapedArray(index_shape, index_dtype),\n+ core.ShapedArray(indptr_shape, index_dtype))\n+\n+\n+mlir.register_lowering(bcsr_fromdense_p, mlir.lower_fun(\n+ _bcsr_fromdense_impl, multiple_results=True))\n+\n+\n+#----------------------------------------------------------------------\n+# bcsr_todense\n+bcsr_todense_p = core.Primitive('bcsr_todense')\n+\n+\n+def bcsr_todense(mat):\n+ \"\"\"Convert batched sparse matrix to a dense matrix.\n+\n+ Args:\n+ mat: BCSR matrix.\n+\n+ Returns:\n+ The dense version of ``mat``.\n+ \"\"\"\n+ return _bcsr_todense(mat.data, mat.indices, mat.indptr,\n+ shape=tuple(mat.shape))\n+\n+\n+def _bcsr_todense(data, indices, indptr, *, shape):\n+ \"\"\"Convert batched sparse matrix to a dense matrix.\n+\n+ Args:\n+ data : array of shape ``batch_dims + (nse,) + dense_dims``.\n+ indices : array of shape ``batch_dims + (nse,)``.\n+ indptr : array of shape ``batch_dims + (shape[len(batch_dims)] + 1,).\n+ shape : tuple; the shape of the (batched) matrix. Equal to\n+ ``batch_dims + 2(sparse_dims) + dense_dims``\n+ Returns:\n+ mat : array with specified shape and dtype matching ``data``\n+ \"\"\"\n+ return bcsr_todense_p.bind(jnp.asarray(data), jnp.asarray(indices),\n+ jnp.asarray(indptr), shape=shape)\n+\n+\n+@bcsr_todense_p.def_impl\n+def _bcsr_todense_impl(data, indices, indptr, *, shape):\n+ bcoo_indices = _bcsr_to_bcoo(indices, indptr, shape=shape)\n+ return (bcoo.BCOO((data, bcoo_indices), shape=shape)).todense()\n+\n+\n+@bcsr_todense_p.def_abstract_eval\n+def _bcsr_todense_abstract_eval(data, indices, indptr, *, shape):\n+ _validate_bcsr(data, indices, indptr, shape)\n+ return core.ShapedArray(shape, data.dtype)\n+\n+\n+mlir.register_lowering(bcsr_todense_p, mlir.lower_fun(\n+ _bcsr_todense_impl, multiple_results=False))\n+\n+\nclass BCSR(JAXSparse):\n\"\"\"Experimental batched CSR matrix implemented in JAX.\"\"\"\n@@ -152,3 +298,14 @@ class BCSR(JAXSparse):\nindex_dtype)\nindptr = jnp.zeros((*batch_shape, sparse_shape[0] + 1), index_dtype)\nreturn cls((data, indices, indptr), shape=shape)\n+\n+ @classmethod\n+ def fromdense(cls, mat, *, nse=None, index_dtype=np.int32, n_dense=0,\n+ n_batch=0):\n+ \"\"\"Create a BCSR array from a (dense) :class:`DeviceArray`.\"\"\"\n+ return bcsr_fromdense(mat, nse=nse, index_dtype=index_dtype,\n+ n_dense=n_dense, n_batch=n_batch)\n+\n+ def todense(self):\n+ \"\"\"Create a dense version of the array.\"\"\"\n+ return bcsr_todense(self)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -2250,6 +2250,44 @@ class BCOOTest(jtu.JaxTestCase):\nself.assertArraysEqual((y_sp @ x_sp).todense(), y_de @ x_de)\n+# TODO(tianjianlu): Unify the testing for BCOOTest and BCSRTest.\n+class BCSRTest(jtu.JaxTestCase):\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_nbatch={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), n_batch),\n+ \"shape\": shape, \"dtype\": dtype, \"n_batch\": n_batch}\n+ for shape in [(5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.complex\n+ for n_batch in range(len(shape) - 1)))\n+ def test_bcsr_dense_round_trip(self, shape, dtype, n_batch):\n+ n_sparse = 2\n+ n_dense = len(shape) - n_sparse - n_batch\n+ rng = rand_sparse(self.rng())\n+ M = rng(shape, dtype)\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\n+\n+ args_maker_fromdense = lambda: [M]\n+ fromdense = partial(sparse_bcsr._bcsr_fromdense, nse=nse, n_batch=n_batch,\n+ n_dense=n_dense)\n+ self._CompileAndCheck(fromdense, args_maker_fromdense)\n+\n+ data, indices, indptr = fromdense(M)\n+\n+ self.assertEqual(data.dtype, dtype)\n+ self.assertEqual(data.shape,\n+ shape[:n_batch] + (nse,) + shape[n_batch + n_sparse:])\n+ self.assertEqual(indices.dtype, jnp.int32)\n+ self.assertEqual(indices.shape, shape[:n_batch] + (nse,))\n+ self.assertEqual(indptr.dtype, jnp.int32)\n+ self.assertEqual(indptr.shape, shape[:n_batch] + (shape[n_batch] + 1,))\n+\n+ todense = partial(sparse_bcsr._bcsr_todense, shape=shape)\n+ self.assertArraysEqual(M, todense(data, indices, indptr))\n+ args_maker_todense = lambda: [data, indices, indptr]\n+ self._CompileAndCheck(todense, args_maker_todense)\n+\n+\nclass SparseGradTest(jtu.JaxTestCase):\ndef test_sparse_grad(self):\nrng_sparse = rand_sparse(self.rng())\n@@ -2521,7 +2559,6 @@ class SparseObjectTest(jtu.JaxTestCase):\nself._CompileAndCheck(bcoo_to_bcsr, args_maker_bcoo_to_bcsr)\nbcsr_indices, indptr = bcoo_to_bcsr(bcoo_indices)\n- bcsr_indices_jit, indptr_jit = jit(bcoo_to_bcsr)(bcoo_indices)\nself.assertEqual(bcsr_indices.dtype, jnp.int32)\nself.assertEqual(bcsr_indices.shape, shape[:n_batch] + (nse,))\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] BCSR fromdense and todense.
PiperOrigin-RevId: 480141918 |
260,411 | 06.09.2022 09:32:45 | -10,800 | 9c879adb736816ee32b2b11ff57bf49b8e2f9c51 | [jax2tf] Implement jax2tf(pjit) for experimental_native_lowering
This implementation is for the case jax2tf.convert(pjit(f_jax)),
that is, the `pjit` appears at the top-level of the function to
be lowered. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -422,6 +422,21 @@ def flatten_fun_jax(fun_jax: Callable, args_tf: Sequence[TfVal],\nout_tree_ref = out_tree\nreturn res_flat_jax\n+ if hasattr(fun_jax, \"lower\"):\n+ # If the fun_jax is already a jit(f) or pjit(f), we must\n+ # preserve the lowering function. This will be used in the _lower_native_and_run.\n+ # We rely on the fact that the lowering is the same for the function\n+ # taking pytrees, and the one taking flat args.\n+ def fun_flat_jax_lower(*args_flat_jax):\n+ tree_args, tree_kwargs = tree_util.tree_unflatten(in_tree, args_flat_jax)\n+ lowered = fun_jax.lower(*tree_args, **tree_kwargs)\n+ out_tree = lowered.out_tree\n+ nonlocal out_tree_ref\n+ assert out_tree_ref is None or out_tree_ref == out_tree\n+ out_tree_ref = out_tree\n+ return lowered\n+ setattr(fun_flat_jax, \"lower\", fun_flat_jax_lower)\n+\nreturn fun_flat_jax, args_flat_tf, in_tree, lambda: out_tree_ref\ndef preprocess_arg_tf(arg_idx: int,\n@@ -604,19 +619,24 @@ def _lower_native_and_run(fun_jax: Callable,\nabstracted_axes = None # type: ignore\narg_specs_jax = [\n- jax.ShapeDtypeStruct(aval.shape, aval.dtype)\n+ jax.ShapeDtypeStruct(aval.shape, aval.dtype, named_shape=aval.named_shape)\nfor aval in args_avals\n]\n# TODO: specify the backend for experimental_native_lowering\nbackend = jax.default_backend()\n- lowered = jax.jit(fun_jax, backend=backend,\n+ if not hasattr(fun_jax, \"lower\") or abstracted_axes:\n+ # We support convert(pjit(f_jax, ...)) and convert(jit(f_jax)) but also\n+ # convert(f_jax), in which case a \"jit\" is implied. We also add a jit when\n+ # we need to pass the abstracted axes.\n+ fun_jax_lower = jax.jit(fun_jax, backend=backend,\nkeep_unused=True, # TODO: allow dropping unused\n- abstracted_axes=abstracted_axes).lower(*arg_specs_jax)._lowering\n-\n+ abstracted_axes=abstracted_axes).lower\n+ else:\n+ fun_jax_lower = fun_jax.lower\n+ lowered = fun_jax_lower(*arg_specs_jax)._lowering\nmhlo_module = lowered.mhlo()\nmhlo_module_text = mlir.module_to_string(mhlo_module)\n- if jaxlib.version <= (0, 3, 14):\n- mhlo_module_text = _fixup_mhlo_module_text(mhlo_module_text)\n+ logging.vlog(2, f\"XlaCallModule {mhlo_module_text}\")\n# We do not support custom_call, try to give an error for now\nif \"mhlo.custom_call\" in mhlo_module_text:\n# Try to give a nice error message. We could just dump the module...\n@@ -626,20 +646,25 @@ def _lower_native_and_run(fun_jax: Callable,\n\"work on TPU.\")\ncustom_calls = re.findall(r'mhlo.custom_call.*call_target_name\\s+=\\s+\"([^\"]+)\".*loc\\(([^\\)]+)\\)',\nmhlo_module_text)\n- for cc in custom_calls:\n+ bad_custom_calls = tuple(filter(lambda cc: cc[0] != \"Sharding\", custom_calls))\n+ if bad_custom_calls:\n+ for cc in bad_custom_calls:\nmsg += f\"\\n{cc[0]}\"\n# Get the line number\nm = re.search('^' + cc[1] + ' =.*', mhlo_module_text, re.MULTILINE)\nif m:\nmsg += f\"\\n from line {m.group(0)}\"\nraise NotImplementedError(msg)\n- logging.vlog(2, f\"XlaCallModule {mhlo_module_text}\")\n# Figure out the result types and shapes\n- if config.jax_array:\n+ if \"global_out_avals\" in lowered.compile_args:\n+ # This is currently the case for pjit\nout_avals = lowered.compile_args[\"global_out_avals\"]\nelse:\nout_avals = lowered.compile_args[\"out_avals\"]\n+ if lowered.compile_args[\"host_callbacks\"]:\n+ raise NotImplementedError(\"host_callbacks are not yet implemented for the jax2tf native lowering\")\n+\n# TODO(necula): handle d being InDBIdx\nout_shapes = tuple(\ntuple(d if type(d) is int else None\n@@ -652,12 +677,22 @@ def _lower_native_and_run(fun_jax: Callable,\nreturn jax_type\nout_types = tuple(_out_type(out_aval.dtype) for out_aval in out_avals)\n+ # Apply the shardings on arguments and results for pjit. This is redundant\n+ # because the mhlo_module_text will already contain the shardings, but it\n+ # makes it easier for tools like the TPU inference converter to see the\n+ # sharding without digging into the `module` attribute of the `XlaCallModule`\n+ # op, in the same way as it is done for the legacy jax2tf conversion.\n+ if \"in_shardings\" in lowered.compile_args:\n+ args_tf = tuple(\n+ map(_shard_value, args_tf, args_avals, lowered.compile_args[\"in_shardings\"]))\nres = tfxla.call_module(\nargs_tf,\nmodule=mhlo_module_text,\nTout=out_types,\nSout=out_shapes,\ndim_args_spec=dim_args_spec)\n+ if \"out_shardings\" in lowered.compile_args:\n+ res = list(map(_shard_value, res, out_avals, lowered.compile_args[\"out_shardings\"]))\n# Convert the results to the needed TF types\ndef _convert_res(res_val, res_jax_type):\n@@ -672,15 +707,6 @@ def _lower_native_and_run(fun_jax: Callable,\nfor res_val, out_aval in zip(res, out_avals))\nreturn res, out_avals\n-def _fixup_mhlo_module_text(mhlo_module_text: str) -> str:\n- # A workaround for MHLO not (yet) having backwards compatibility. With\n- # jaxlib 0.3.14 we have an old serialization method that puts \"...\" around\n- # MHLO attributes. The parser is new and does not accept those attributes.\n- # We try to fix it up here, temporarily.\n- import re\n- return re.sub(r'#mhlo<\"([^\"]+)\">', \"#mhlo<\\\\1>\", mhlo_module_text)\n-\n-\ndef _call_wrapped_with_new_constant_cache(fun: lu.WrappedFun,\nin_vals: Sequence[TfVal],\nfresh_constant_cache: bool = False\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"new_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for the jax2tf conversion for control-flow primitives.\"\"\"\n+import unittest\nfrom absl.testing import absltest\n@@ -29,6 +30,12 @@ config.parse_flags_with_absl()\nclass ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\n+ def setUp(self):\n+ super().setUp()\n+ # TODO(b/252947617): re-enable these tests\n+ if config.jax_array and config.jax2tf_default_experimental_native_lowering:\n+ raise unittest.SkipTest(\"Test disabled for JAX_ARRAY\")\n+\n@jtu.ignore_warning(category=UserWarning,\nmessage=\"Explicitly requested dtype .* requested in array is not available\")\ndef test_cond(self):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -51,6 +51,12 @@ config.parse_flags_with_absl()\nclass Jax2TfTest(tf_test_util.JaxToTfTestCase):\n+ def setUp(self):\n+ super().setUp()\n+ # TODO(b/252943725): re-enable these tests\n+ if config.jax_array and config.jax2tf_default_experimental_native_lowering:\n+ raise unittest.SkipTest(\"Test disabled for JAX_ARRAY\")\n+\ndef test_empty(self):\nf_jax = lambda x, y: x\nself.ConvertAndCompare(f_jax, 0.7, 1)\n@@ -117,8 +123,16 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ndef test_nested_jit(self):\nf_jax = jax.jit(lambda x: jnp.sin(jax.jit(jnp.cos)(x)))\n- f_tf = jax2tf.convert(f_jax)\n- np.testing.assert_allclose(f_jax(0.7), f_tf(0.7))\n+ x = 0.7\n+ self.ConvertAndCompare(f_jax, x)\n+\n+ def test_nested_jit_pytree(self):\n+ @jax.jit\n+ def f_jax(xy):\n+ x, y = xy\n+ return x + y\n+ xy = (0.7, 0.8)\n+ self.ConvertAndCompare(f_jax, xy)\ndef test_nested_jit_is_compiled(self):\n# Check that nested jax.jit are compiled with tf.function(jit_compile=True)\n@@ -1241,7 +1255,16 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ndef get_serialized_computation(\nf_jax: Callable,\n*args,\n- abstracted_axes: Optional[Tuple[Dict[int, str]]] = None) -> str:\n+ abstracted_axes: Optional[Tuple[Dict[int, str]]] = None,\n+ use_pjit: bool = False,\n+ in_axis_resources = None,\n+ out_axis_resources = None) -> str:\n+ if use_pjit:\n+ assert not abstracted_axes\n+ lowered = pjit(f_jax,\n+ in_axis_resources=in_axis_resources,\n+ out_axis_resources=out_axis_resources).lower(*args)\n+ else:\nlowered = jax.jit(f_jax, abstracted_axes=abstracted_axes).lower(*args)\nmhlo_module = lowered.compiler_ir(dialect='mhlo')\nmhlo_module_text = mlir.module_to_string(mhlo_module)\n@@ -1364,23 +1387,29 @@ class XlaCallModuleTest(tf_test_util.JaxToTfTestCase):\n# TODO(b/243146552) We can switch to ConvertAndCompare after this bug fix.\nnp.array_equal(jax_out._value, np.array(tf_out))\n- # Test 2: use GDA as JAX function input\n- def jax_func_2(input_data, params):\n- handle = pjit(\n- jnp.matmul,\n- in_axis_resources=(P(\"y\", \"x\"), P((\"x\", \"y\"),)),\n- out_axis_resources=None)\n- return handle(input_data, params)\n+ @jtu.with_mesh([(\"x\", 2)])\n+ def test_pjit_basic1D(self):\n+ def func_jax(x, y):\n+ return x + y\n- with global_mesh:\n- tf_func_2 = tf.function(\n- jax2tf.convert(jax_func_2, enable_xla=True),\n- jit_compile=True,\n- )\n- jax_out_2 = jax_func_2(input_data=input_data, params=params)\n- tf_out_2 = tf_func_2(input_data=input_data, params=params)\n- # TODO(b/243146552) We can switch to ConvertAndCompare after this bug fix.\n- np.array_equal(jax_out_2._value, np.array(tf_out_2))\n+ shape = (8, 10)\n+ x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n+ in_axis_resources = (P(\"x\"), P(\"x\"))\n+ out_axis_resources = None\n+ res_jax = pjit(func_jax,\n+ in_axis_resources=in_axis_resources,\n+ out_axis_resources=out_axis_resources)(x, x)\n+ module = get_serialized_computation(func_jax, x, x,\n+ use_pjit=True,\n+ in_axis_resources=in_axis_resources,\n+ out_axis_resources=out_axis_resources)\n+ def f_tf(x_tf, y_tf):\n+ return tfxla.call_module([x_tf, y_tf],\n+ module=module,\n+ Tout=[x.dtype],\n+ Sout=[x.shape])\n+ res_tf = tf.function(f_tf, jit_compile=True, autograph=False)(x, x)[0]\n+ self.assertAllClose(res_tf.numpy(), res_jax)\nif __name__ == \"__main__\":\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"diff": "@@ -696,6 +696,16 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ndict(a=\"(_,)\", b=\"(4,)\")],\nexpected_output_signature=tf.TensorSpec([4]))\n+ def test_with_nested_jit(self):\n+ @jax.jit\n+ def f_jax(x):\n+ return jnp.sin(x)\n+\n+ self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([1, None])],\n+ polymorphic_shapes=[\"1, b\"])\n+\ndef test_with_custom_vjp(self):\n\"\"\"Shape-polymorphic custom VJP.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Implement jax2tf(pjit) for experimental_native_lowering
This implementation is for the case jax2tf.convert(pjit(f_jax)),
that is, the `pjit` appears at the top-level of the function to
be lowered. |
260,287 | 11.10.2022 06:46:59 | 25,200 | 9c994985a44371fba6f8699ed4555afb2fb14330 | Support MANUAL collectives in top-level xmaps
It's a bit of a weird use-case, since MANUAL mode is meant for xmaps that
are nested inside pjits, but it doesn't hurt us to support it. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -2963,12 +2963,14 @@ def lower_mesh_computation(\n# 1. Trace to jaxpr and preprocess/verify it\nif spmd_lowering:\n+ manual_axes: FrozenSet[MeshAxisName] = frozenset()\n# TODO: Consider handling xmap's 'vectorize' in here. We can vmap once instead of vtile twice!\nif tiling_method is not None:\nif isinstance(tiling_method, TileVectorize):\ntiling_transform = vtile_by_mesh\nelif isinstance(tiling_method, TileManual):\ntiling_transform = lambda f, *args: vtile_manual(f, tiling_method.manual_axes, *args) # type: ignore\n+ manual_axes = tiling_method.manual_axes\nelse:\nraise NotImplementedError(f\"Unrecognized tiling method: {tiling_method}\")\nassert not callable(out_shardings)\n@@ -3031,7 +3033,7 @@ def lower_mesh_computation(\nelse:\nout_partitions.append(o._to_xla_op_sharding(aval.ndim))\nreplicated_args = [False] * len(in_jaxpr_avals)\n- axis_ctx = mlir.SPMDAxisContext(mesh)\n+ axis_ctx = mlir.SPMDAxisContext(mesh, manual_axes)\nelse:\nreplicated_args = [not _get_array_mapping(i.spec) for i in in_shardings] # type: ignore\nin_partitions = None\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/xmap_test.py",
"new_path": "tests/xmap_test.py",
"diff": "@@ -865,6 +865,14 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\nx = jnp.arange(16, dtype=jnp.float32).reshape(4, 4)\nself.assertAllClose(h(x), (x * x).sum(0))\n+ @jtu.with_mesh([('x', 2)])\n+ def testBareXmapCollective(self):\n+ x = jnp.arange(20, dtype=jnp.float32).reshape(4, 5)\n+\n+ y = xmap(lambda x: lax.psum(x, 'i'),\n+ in_axes=['i', ...], out_axes=[...], axis_resources={'i': 'x'})(x)\n+ self.assertAllClose(x.sum(0), y)\n+\nclass NamedNumPyTest(XMapTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Support MANUAL collectives in top-level xmaps
It's a bit of a weird use-case, since MANUAL mode is meant for xmaps that
are nested inside pjits, but it doesn't hurt us to support it.
PiperOrigin-RevId: 480342531 |
260,305 | 11.10.2022 07:30:49 | 25,200 | 8c13142ae6fa821d06004059393d724c0c72190a | fixed build instructions typo | [
{
"change_type": "MODIFY",
"old_path": "build/rocm/README.md",
"new_path": "build/rocm/README.md",
"diff": "@@ -9,9 +9,9 @@ This directory contains files and setup instructions t0 build and test JAX for R\n./build/rocm/ci_build.sh --keep_image bash -c \"./build/rocm/build_rocm.sh\"\n- 3. Launch a container: If the build was successful, there should be a docker image with name \"jax-rocm:latest\" in list of docker images (use \"docker images\" command to list them).\n+ 3. Launch a container: If the build was successful, there should be a docker image with name \"jax_ci.rocm\" in list of docker images (use \"docker images\" command to list them).\n```\n- sudo docker run -it --device=/dev/kfd --device=/dev/dri --security-opt seccomp=unconfined --group-add video --entrypoint /bin/bash jax-rocm:latest\n+ sudo docker run -it --device=/dev/kfd --device=/dev/dri --security-opt seccomp=unconfined --group-add video --entrypoint /bin/bash jax_ci.rocm:latest\n```\n***\n"
}
] | Python | Apache License 2.0 | google/jax | fixed build instructions typo |
260,335 | 10.10.2022 17:47:18 | 25,200 | b27acedf1f61d13c7908e22cf9330db99bd61f58 | add more info to pytree prefix key errors
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/tree_util.py",
"new_path": "jax/_src/tree_util.py",
"diff": "@@ -475,15 +475,27 @@ def _prefix_error(key_path: KeyPath, prefix_tree: Any, full_tree: Any,\n# point, and because prefix_tree is not a leaf, each can be flattened once):\nprefix_tree_children, prefix_tree_meta = flatten_one_level(prefix_tree)\nfull_tree_children, full_tree_meta = flatten_one_level(full_tree)\n+ prefix_tree_keys = _child_keys(prefix_tree)\n+ full_tree_keys = _child_keys(full_tree)\n+ try:\n+ diff = set(prefix_tree_keys).symmetric_difference(set(full_tree_keys))\n+ except:\n+ diff = None\nif len(prefix_tree_children) != len(full_tree_children):\nyield lambda name: ValueError(\n\"pytree structure error: different numbers of pytree children at key path\\n\"\nf\" {{name}}{key_path.pprint()}\\n\"\nf\"At that key path, the prefix pytree {{name}} has a subtree of type\\n\"\nf\" {type(prefix_tree)}\\n\"\n- f\"with {len(prefix_tree_children)} children, \"\n+ f\"with {len(prefix_tree_children)} child keys\\n\"\n+ f\" {' '.join(str(k.key) for k in prefix_tree_keys)}\\n\"\nf\"but at the same key path the full pytree has a subtree of the same \"\n- f\"type but with {len(full_tree_children)} children.\".format(name=name))\n+ f\"type but with {len(full_tree_children)} child keys\\n\"\n+ f\" {' '.join(str(k.key) for k in full_tree_keys)}\\n\"\n+ .format(name=name)\n+ + (\"\" if diff is None else\n+ f\"so the symmetric difference on key sets is\\n\"\n+ f\" {' '.join(str(k.key) for k in diff)}\"))\nreturn # don't look for more errors in this subtree\n# Or they may disagree if their roots have different pytree metadata:\n@@ -510,11 +522,10 @@ def _prefix_error(key_path: KeyPath, prefix_tree: Any, full_tree: Any,\n# If the root types and numbers of children agree, there must be an error\n# in a subtree, so recurse:\n- keys = _child_keys(prefix_tree)\n- keys_ = _child_keys(full_tree)\n- assert keys == keys_, \\\n- f\"equal pytree nodes gave differing keys: {keys} and {keys_}\"\n- for k, t1, t2 in zip(keys, prefix_tree_children, full_tree_children):\n+ assert prefix_tree_keys == full_tree_keys, \\\n+ (\"equal pytree nodes gave differing prefix_tree_keys: \"\n+ f\"{prefix_tree_keys} and {full_tree_keys}\")\n+ for k, t1, t2 in zip(prefix_tree_keys, prefix_tree_children, full_tree_children):\nyield from _prefix_error(key_path + k, t1, t2)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pjit_test.py",
"new_path": "tests/pjit_test.py",
"diff": "@@ -2603,9 +2603,7 @@ class PJitErrorTest(jtu.JaxTestCase):\n\" pjit out_axis_resources tree root\\n\"\n\"At that key path, the prefix pytree pjit out_axis_resources has a \"\n\"subtree of type\\n\"\n- \" <class 'list'>\\n\"\n- \"with 2 children, but at the same key path the full pytree has a \"\n- \"subtree of the same type but with 3 children.\")\n+ \" <class 'list'>\\n\")\nwith self.assertRaisesRegex(ValueError, error):\npjit(lambda x: x, (p,), [p, None])([x, x, x]) # Error, we raise a generic tree mismatch message\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/tree_util_test.py",
"new_path": "tests/tree_util_test.py",
"diff": "@@ -505,6 +505,13 @@ class TreePrefixErrorsTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, expected):\nraise e2('in_axes')\n+ def test_different_num_children_print_key_diff(self):\n+ e, = prefix_errors({'a': 1}, {'a': 2, 'b': 3})\n+ expected = (\"so the symmetric difference on key sets is\\n\"\n+ \" b\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\ndef test_different_metadata(self):\ne, = prefix_errors({1: 2}, {3: 4})\nexpected = (\"pytree structure error: different pytree metadata \"\n"
}
] | Python | Apache License 2.0 | google/jax | add more info to pytree prefix key errors
fixes #12643 |
260,510 | 11.10.2022 12:38:52 | 25,200 | 07e1144af086e5b1db47db129d097241cb15da3e | Make webpdb debugger lower priority | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugger/web_debugger.py",
"new_path": "jax/_src/debugger/web_debugger.py",
"diff": "@@ -92,4 +92,4 @@ def run_debugger(frames: List[debugger_core.DebuggerFrame],\nWebDebugger(frames, thread_id, **kwargs).run()\nif WEB_PDB_ENABLED:\n- debugger_core.register_debugger(\"web\", run_debugger, 0)\n+ debugger_core.register_debugger(\"web\", run_debugger, -2)\n"
}
] | Python | Apache License 2.0 | google/jax | Make webpdb debugger lower priority |
260,510 | 11.10.2022 13:57:00 | 25,200 | bbf69d10cce9c34e9cfa4b28d22ec38a30168f8f | Enable partially discharging state effects from jaxprs | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/discharge.py",
"new_path": "jax/_src/state/discharge.py",
"diff": "@@ -16,7 +16,7 @@ from __future__ import annotations\nimport dataclasses\nfrom functools import partial\n-from typing import Any, Dict, List, Optional, Sequence, Tuple\n+from typing import Any, Dict, List, Optional, Sequence, Tuple, Union\nfrom typing_extensions import Protocol\nimport numpy as np\n@@ -43,13 +43,17 @@ zip, unsafe_zip = safe_zip, zip\n# into a \"pure\" jaxpr that takes in and outputs values and no longer has the\n# `Read/Write/Accum` effects.\n-def discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any]\n+def discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any], * ,\n+ should_discharge: Union[bool, Sequence[bool]] = True\n) -> Tuple[core.Jaxpr, List[Any]]:\n\"\"\"Converts a jaxpr that takes in `Ref`s into one that doesn't.\"\"\"\n+ if isinstance(should_discharge, bool):\n+ should_discharge = [should_discharge] * len(jaxpr.invars)\nin_avals = [core.ShapedArray(v.aval.shape, v.aval.dtype)\n- if type(v.aval) is ShapedArrayRef\n- else v.aval for v in jaxpr.invars]\n- eval_jaxpr = lu.wrap_init(partial(_eval_jaxpr_discharge_state, jaxpr, consts))\n+ if type(v.aval) is ShapedArrayRef and d\n+ else v.aval for v, d in zip(jaxpr.invars, should_discharge)]\n+ eval_jaxpr = lu.wrap_init(partial(_eval_jaxpr_discharge_state, jaxpr,\n+ should_discharge, consts))\nnew_jaxpr, _ , new_consts = pe.trace_to_jaxpr_dynamic(eval_jaxpr, in_avals)\nreturn new_jaxpr, new_consts\n@@ -82,7 +86,8 @@ def register_discharge_rule(prim: core.Primitive):\ndef _has_refs(eqn: core.JaxprEqn):\nreturn any(isinstance(v.aval, ShapedArrayRef) for v in eqn.invars)\n-def _eval_jaxpr_discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any],\n+def _eval_jaxpr_discharge_state(\n+ jaxpr: core.Jaxpr, should_discharge: Sequence[bool], consts: Sequence[Any],\n*args: Any):\nenv = Environment({})\n@@ -91,8 +96,13 @@ def _eval_jaxpr_discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any],\n# regular values in this interpreter.\nmap(env.write, jaxpr.invars, args)\n+ refs_to_discharge = set(id(v.aval) for v, d\n+ in zip(jaxpr.invars, should_discharge) if d\n+ and isinstance(v.aval, ShapedArrayRef))\n+\nfor eqn in jaxpr.eqns:\n- if _has_refs(eqn):\n+ if _has_refs(eqn) and any(id(v.aval) in refs_to_discharge\n+ for v in eqn.invars):\nif eqn.primitive not in _discharge_rules:\nraise NotImplementedError(\"No state discharge rule implemented for \"\nf\"primitive: {eqn.primitive}\")\n@@ -119,7 +129,7 @@ def _eval_jaxpr_discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any],\n# them up by looking at `len(jaxpr.outvars)`.\nout_vals = map(env.read, jaxpr.outvars)\nref_vals = map(\n- env.read, [v for v in jaxpr.invars if type(v.aval) is ShapedArrayRef])\n+ env.read, [v for v in jaxpr.invars if id(v.aval) in refs_to_discharge])\nreturn out_vals + ref_vals\n@register_discharge_rule(get_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/state_test.py",
"new_path": "tests/state_test.py",
"diff": "@@ -627,6 +627,26 @@ class StateDischargeTest(jtu.JaxTestCase):\nself.assertTrue((b == inval + 1).all())\nself.assertTrue((refval == inval).all())\n+ def test_partially_discharging_jaxpr_keeps_refs(self):\n+ def f(a_ref, b_ref):\n+ state.ref_set(a_ref, (), jnp.ones(4, jnp.float32))\n+ state.ref_set(b_ref, (), jnp.ones(4, jnp.float32))\n+ return []\n+ in_avals = [\n+ state.ShapedArrayRef((4,), jnp.dtype('float32')),\n+ state.ShapedArrayRef((4,), jnp.dtype('float32'))\n+ ]\n+ stateful_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(lu.wrap_init(f),\n+ in_avals)\n+ discharged_jaxpr, _ = state.discharge_state(\n+ stateful_jaxpr, consts, should_discharge=[False, True])\n+ self.assertLen(discharged_jaxpr.invars, 2)\n+ self.assertLen(discharged_jaxpr.outvars, 1)\n+ self.assertIsInstance(discharged_jaxpr.invars[0].aval, state.ShapedArrayRef)\n+ self.assertIsInstance(discharged_jaxpr.invars[1].aval, core.ShapedArray)\n+ self.assertEqual(discharged_jaxpr.effects,\n+ {state.WriteEffect(discharged_jaxpr.invars[0].aval)})\n+\nif CAN_USE_HYPOTHESIS:\n"
}
] | Python | Apache License 2.0 | google/jax | Enable partially discharging state effects from jaxprs |
260,502 | 11.10.2022 21:45:15 | 25,200 | bd054f81976f95776a88f4f78aa647b2c9d76331 | add sharding property to GDA
should improve forward compatibility with Array | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/global_device_array.py",
"new_path": "jax/experimental/global_device_array.py",
"diff": "@@ -457,6 +457,10 @@ class GlobalDeviceArray:\nself._sharded_buffer.block_until_ready() # type: ignore\nreturn self\n+ @property\n+ def sharding(self):\n+ return jax.sharding.MeshPspecSharding(self._global_mesh, self.mesh_axes)\n+\n@classmethod\ndef from_callback(cls, global_shape: Shape, global_mesh: pxla.Mesh,\nmesh_axes: MeshAxes, data_callback: Callable[[Index],\n"
}
] | Python | Apache License 2.0 | google/jax | add sharding property to GDA
should improve forward compatibility with Array |
260,557 | 13.10.2022 18:31:47 | -7,200 | 6ddbe5d5ece97393ac91e6134bc9c83bd659d22a | expose `jax.block_until_ready()` from jax | [
{
"change_type": "MODIFY",
"old_path": "jax/__init__.py",
"new_path": "jax/__init__.py",
"diff": "@@ -63,7 +63,7 @@ from jax._src.environment_info import print_environment_info as print_environmen\nfrom jax._src.api import (\nad, # TODO(phawkins): update users to avoid this.\neffects_barrier,\n- block_until_ready,\n+ block_until_ready as block_until_ready,\ncheckpoint as checkpoint,\ncheckpoint_policies as checkpoint_policies,\nclear_backends as clear_backends,\n"
}
] | Python | Apache License 2.0 | google/jax | expose `jax.block_until_ready()` from jax |
260,332 | 13.10.2022 17:22:15 | 25,200 | cbcd0cdd045689abbf5400de23f5ebace423157c | ignore UserWarning | [
{
"change_type": "MODIFY",
"old_path": "pytest.ini",
"new_path": "pytest.ini",
"diff": "@@ -19,5 +19,6 @@ filterwarnings =\n# numpy uses distutils which is deprecated\nignore:The distutils.* is deprecated.*:DeprecationWarning\nignore:`sharded_jit` is deprecated. Please use `pjit` instead.*:DeprecationWarning\n+ ignore:Running operations on `Array`s that are not fully addressable by this process.*:UserWarning\ndoctest_optionflags = NUMBER NORMALIZE_WHITESPACE\naddopts = --doctest-glob=\"*.rst\"\n"
}
] | Python | Apache License 2.0 | google/jax | ignore UserWarning |
260,631 | 14.10.2022 03:12:10 | 25,200 | 1945208d34758e42eb401f88a54038f18ebf399d | Rollback because of failing tests internally. | [
{
"change_type": "MODIFY",
"old_path": "benchmarks/api_benchmark.py",
"new_path": "benchmarks/api_benchmark.py",
"diff": "@@ -629,7 +629,7 @@ def bench_slicing_compilation2(state):\njax.jit(lambda x: (x[:1], x[1:2], x[2:3])).lower(x).compile()\n-def pjit_simple_benchmark(state, num_devices, num_args, cpp_jit, use_aot=False):\n+def pjit_simple_benchmark(state, num_devices, num_args, cpp_jit):\nspec = pjit_lib.PartitionSpec('x')\nmesh = jtu.create_global_mesh((num_devices,), ('x',))\ns = sharding.MeshPspecSharding(mesh, spec)\n@@ -649,9 +649,6 @@ def pjit_simple_benchmark(state, num_devices, num_args, cpp_jit, use_aot=False):\nin_axis_resources=in_axis_resources,\nout_axis_resources=out_axis_resources)\n- if use_aot:\n- f = f.lower(x).compile()\n-\nx = f(x)\nwhile state:\n@@ -700,59 +697,5 @@ def pjit_simple_4000_device(state):\nstate, num_devices=4000, num_args=state.range(0), cpp_jit=state.range(1))\n-@google_benchmark.register\n-@google_benchmark.option.arg_names(['num_args', 'cpp_pjit'])\n-@google_benchmark.option.args([1, False])\n-@google_benchmark.option.args([1, True])\n-@google_benchmark.option.args([10, False])\n-@google_benchmark.option.args([10, True])\n-@google_benchmark.option.args([100, False])\n-@google_benchmark.option.args([100, True])\n-@jax_config.jax_array(True)\n-def pjit_aot_1_device(state):\n- pjit_simple_benchmark(\n- state,\n- num_devices=1,\n- num_args=state.range(0),\n- cpp_jit=state.range(1),\n- use_aot=True)\n-\n-\n-@google_benchmark.register\n-@google_benchmark.option.arg_names(['num_args', 'cpp_pjit'])\n-@google_benchmark.option.args([1, False])\n-@google_benchmark.option.args([1, True])\n-@google_benchmark.option.args([10, False])\n-@google_benchmark.option.args([10, True])\n-@google_benchmark.option.args([100, False])\n-@google_benchmark.option.args([100, True])\n-@jax_config.jax_array(True)\n-def pjit_aot_4_device(state):\n- pjit_simple_benchmark(\n- state,\n- num_devices=4,\n- num_args=state.range(0),\n- cpp_jit=state.range(1),\n- use_aot=True)\n-\n-\n-@google_benchmark.register\n-@google_benchmark.option.arg_names(['num_args', 'cpp_pjit'])\n-@google_benchmark.option.args([1, False])\n-@google_benchmark.option.args([1, True])\n-@google_benchmark.option.args([10, False])\n-@google_benchmark.option.args([10, True])\n-@google_benchmark.option.args([100, False])\n-@google_benchmark.option.args([100, True])\n-@jax_config.jax_array(True)\n-def pjit_aot_4000_device(state):\n- pjit_simple_benchmark(\n- state,\n- num_devices=4000,\n- num_args=state.range(0),\n- cpp_jit=state.range(1),\n- use_aot=True)\n-\n-\nif __name__ == \"__main__\":\ngoogle_benchmark.main()\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/stages.py",
"new_path": "jax/_src/stages.py",
"diff": "@@ -33,7 +33,7 @@ from __future__ import annotations\nimport warnings\nfrom dataclasses import dataclass\n-from typing import Any, Callable, Dict, List, NamedTuple, Optional, Sequence, Tuple\n+from typing import Any, Dict, List, Optional, Sequence, Tuple\nfrom typing_extensions import Protocol\nimport jax\n@@ -306,12 +306,6 @@ def make_args_info(in_tree, in_avals, donate_argnums):\nArgInfo(aval, i in donate_argnums)\nfor i, aval in enumerate(flat_avals)])\n-class CompiledCallParams(NamedTuple):\n- executable: Executable\n- no_kwargs: bool\n- in_tree: tree_util.PyTreeDef\n- out_tree: tree_util.PyTreeDef\n-\nclass Compiled(Stage):\n\"\"\"Compiled representation of a function specialized to types/values.\n@@ -328,19 +322,11 @@ class Compiled(Stage):\n_executable: Executable\n_no_kwargs: bool\n- def __init__(self, executable, args_info, out_tree, no_kwargs=False, create_cpp_call=None):\n+ def __init__(self, executable, args_info, out_tree, no_kwargs=False):\nself._executable = executable\nself._no_kwargs = no_kwargs\nself.args_info = args_info\nself.out_tree = out_tree\n- self._params = CompiledCallParams(self._executable, self._no_kwargs,\n- self.in_tree, self.out_tree)\n- # TODO(chky): Remove this conditional statement once we implement the fast\n- # path in C++ for all AOT paths.\n- if create_cpp_call is not None:\n- self._cpp_call = create_cpp_call(self._params)\n- else:\n- self._cpp_call = None\ndef compiler_ir(self):\n\"\"\"Post-compilation IR.\n@@ -429,23 +415,22 @@ class Compiled(Stage):\nshardings_flat = self._executable.output_shardings()\nreturn tree_util.tree_unflatten(self.out_tree, shardings_flat) # pytype: disable=attribute-error\n- @staticmethod\n- def call(params, *args, **kwargs):\n+ def __call__(self, *args, **kwargs):\nif jax.config.jax_dynamic_shapes:\nraise NotImplementedError\n- if params.no_kwargs and kwargs:\n+ if self._no_kwargs and kwargs:\nkws = ', '.join(kwargs.keys())\nraise NotImplementedError(\n\"function was compiled by a transformation that does not support \"\nf\"keyword arguments, but called with keyword arguments: {kws}\")\nargs_flat, in_tree = tree_util.tree_flatten((args, kwargs))\n- if in_tree != params.in_tree:\n+ if in_tree != self.in_tree:\n# TODO(frostig): provide more info about the source function\n# and transformation\nraise TypeError(\n- f\"function compiled for {params.in_tree}, called with {in_tree}\")\n+ f\"function compiled for {self.in_tree}, called with {in_tree}\")\ntry:\n- out_flat = params.executable.call(*args_flat)\n+ out_flat = self._executable.call(*args_flat)\nexcept TypeError as e:\n# We can't transform ahead-of-time compiled calls, since we've\n# lowered and compiled for a fixed function signature, and JAX\n@@ -463,15 +448,7 @@ class Compiled(Stage):\nf\"Tracer type {type(arg)}.\") from e\nelse:\nraise\n- outs = tree_util.tree_unflatten(params.out_tree, out_flat)\n- return outs, out_flat\n-\n- def __call__(self, *args, **kwargs):\n- if self._cpp_call is not None:\n- return self._cpp_call(*args, **kwargs)\n-\n- outs, _ = Compiled.call(self._params, *args, **kwargs)\n- return outs\n+ return tree_util.tree_unflatten(self.out_tree, out_flat)\nclass Lowered(Stage):\n@@ -489,18 +466,16 @@ class Lowered(Stage):\nout_tree: tree_util.PyTreeDef\n_lowering: XlaLowering\n_no_kwargs: bool\n- _create_cpp_call: Optional[Callable]\ndef __init__(self,\nlowering: XlaLowering,\nargs_info, # PyTreee of ArgInfo\nout_tree: tree_util.PyTreeDef,\n- no_kwargs: bool = False, create_cpp_call: Optional[Callable] = None):\n+ no_kwargs: bool = False):\nself._lowering = lowering\nself._no_kwargs = no_kwargs\nself.args_info = args_info\nself.out_tree = out_tree\n- self._create_cpp_call = create_cpp_call\n@classmethod\ndef from_flat_info(cls,\n@@ -509,7 +484,7 @@ class Lowered(Stage):\nin_avals,\ndonate_argnums: Tuple[int, ...],\nout_tree: tree_util.PyTreeDef,\n- no_kwargs: bool = False, create_cpp_call: Optional[Callable] = None):\n+ no_kwargs: bool = False):\n\"\"\"Initialize from flat info (``in_avals`` etc.) and an input PyTreeDef.\nArgs:\n@@ -520,7 +495,7 @@ class Lowered(Stage):\narguments (an error will be raised if some are provided).\n\"\"\"\nreturn cls(lowering, make_args_info(in_tree, in_avals, donate_argnums),\n- out_tree, no_kwargs=no_kwargs, create_cpp_call=create_cpp_call)\n+ out_tree, no_kwargs=no_kwargs)\ndef compile(self) -> Compiled:\n\"\"\"Compile, returning a corresponding ``Compiled`` instance.\"\"\"\n@@ -534,7 +509,7 @@ class Lowered(Stage):\nkw = {}\nreturn Compiled(self._lowering.compile(**kw), self.args_info, self.out_tree,\n- no_kwargs=self._no_kwargs, create_cpp_call=self._create_cpp_call)\n+ no_kwargs=self._no_kwargs)\ndef as_text(self, dialect: Optional[str] = None) -> str:\n\"\"\"A human-readable text representation of this lowering.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/pjit.py",
"new_path": "jax/experimental/pjit.py",
"diff": "@@ -30,7 +30,6 @@ from jax import core\nfrom jax import linear_util as lu\nfrom jax import stages\nfrom jax._src import array\n-from jax._src.stages import CompiledCallParams\nfrom jax._src.api import _check_callable, _check_arg, FLAGS, device_put\nfrom jax._src.config import config\nfrom jax._src import dispatch\n@@ -171,45 +170,6 @@ def _cpp_pjit(fun: Callable, infer_params, static_argnums):\nreturn wraps(fun)(cpp_pjit_f)\n-class _CppPjitAotCall:\n- def __init__(self, fun: Callable, static_argnums: Any):\n- self._fun = fun\n- self._static_argnums = static_argnums\n-\n- def __call__(self, params: CompiledCallParams):\n-\n- def aot_cache_miss(*args, **kwargs):\n- # The first invocation for a signature will use the python path. If it is\n- # a correct signature, the later invocations will use the C++ path.\n- # Otherwise, if the signature is wrong, it will be caught by the python\n- # path during the first invocation.\n- outs, out_flat = stages.Compiled.call(params, *args, **kwargs)\n-\n- executable = params.executable\n-\n- use_fastpath = (\n- isinstance(executable, pxla.MeshExecutable) and\n- isinstance(executable.unsafe_call, pxla.ExecuteReplicated) and\n- not executable.unsafe_call.has_unordered_effects and\n- not executable.unsafe_call.has_host_callbacks and\n- all(isinstance(x, xc.ArrayImpl) for x in out_flat))\n-\n- if use_fastpath:\n- out_avals = [o.aval for o in out_flat]\n- out_committed = [o._committed for o in out_flat]\n- fastpath_data = _PjitFastpathData(executable.xla_executable, params.out_tree,\n- executable._in_shardings,\n- executable._out_shardings,\n- out_avals, out_committed)\n- else:\n- fastpath_data = None\n-\n- return outs, fastpath_data\n-\n- self._cpp_aot_pjit_f = xc._xla.pjit(self._fun, aot_cache_miss,\n- self._static_argnums)\n- return self._cpp_aot_pjit_f\n-\n# TODO(yashkatariya): Add pjit microbenchmarks.\n# in_axis_resources and out_axis_resources can't be None as the default value\n@@ -470,16 +430,11 @@ def pjit(fun: Callable,\nparams['resource_env'], params['donated_invars'], params['name'],\nin_is_global, always_lower=True)\n- if FLAGS.experimental_cpp_pjit and xc._version >= 96:\n- create_cpp_call = _CppPjitAotCall(fun, static_argnums)\n- else:\n- create_cpp_call = None\n-\nargs_kwargs_in_tree = treedef_tuple([in_tree, tree_flatten({})[1]])\nlocal_in_avals = args_kwargs_in_tree.unflatten(flat_local_in_avals)\nreturn stages.Lowered.from_flat_info(\nlowering, args_kwargs_in_tree, local_in_avals, donate_argnums, out_tree,\n- no_kwargs=True, create_cpp_call=create_cpp_call)\n+ no_kwargs=True)\nwrapped.lower = lower\nreturn wrapped\n"
}
] | Python | Apache License 2.0 | google/jax | Rollback because of failing tests internally.
PiperOrigin-RevId: 481103002 |
260,424 | 14.10.2022 17:01:12 | -3,600 | 3b24e772e0d44fe508f553a3b1b23452a36f30e7 | Checkify: Only create one init_payload.
While debugging some `const` issues, I noticed a huge list of payloads
included as constants. Not sure why I made this a lambda in the first
place, maybe to avoid calling numpy at a module level? I could make this
a cached call instead. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -70,7 +70,7 @@ Payload = Union[np.ndarray, Array]\n# For now, the payload needs to be a fixed-size array: 3 int32s, used for the\n# OOB message.\n# TODO(lenamartens): Relax this fixed-size constraint.\n-init_payload = lambda: np.ones((3,), np.int32)\n+init_payload = np.ones((3,), np.int32)\ndef _format_msg(msg, payloads):\n@@ -95,7 +95,7 @@ class Error:\nobject.__setattr__(self, \"code\", code)\nobject.__setattr__(self, \"msgs\", msgs)\nobject.__setattr__(self, \"payload\",\n- init_payload() if payload is None else payload)\n+ init_payload if payload is None else payload)\ndef get(self) -> Optional[str]:\n\"\"\"Returns error message is error happened, None if no error happened.\"\"\"\n@@ -136,7 +136,7 @@ next_code = it.count(1).__next__ # globally unique ids, could be uuid4\ndef assert_func(error: Error, err: Bool, msg: str,\npayload: Optional[Payload]) -> Error:\ncode = next_code()\n- payload = init_payload() if payload is None else payload\n+ payload = init_payload if payload is None else payload\nout_err = error.err | err\nout_code = lax.select(error.err, error.code, code)\nout_payload = lax.select(error.err, error.payload, payload)\n"
}
] | Python | Apache License 2.0 | google/jax | Checkify: Only create one init_payload.
While debugging some `const` issues, I noticed a huge list of payloads
included as constants. Not sure why I made this a lambda in the first
place, maybe to avoid calling numpy at a module level? I could make this
a cached call instead. |
260,287 | 14.10.2022 08:59:05 | 25,200 | 746dd5ab1394e94a33eb204c4cbfc986db8f20b2 | Add support for MANUAL lowering of ppermute | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/parallel.py",
"new_path": "jax/_src/lax/parallel.py",
"diff": "@@ -843,7 +843,18 @@ def _ppermute_lowering(ctx, x, *, axis_name, perm):\nfull_perm[i, j, 0] = grp[src]\nfull_perm[i, j, 1] = grp[dst]\nfull_perm = full_perm.reshape((-1, 2))\n- return mhlo.CollectivePermuteOp(x, mlir.dense_int_elements(full_perm)).results\n+\n+ axis_context = ctx.module_context.axis_context\n+ is_manual = isinstance(axis_context, mlir.SPMDAxisContext) and axis_context.manual_axes\n+ if is_manual:\n+ channel = ctx.module_context.new_channel()\n+ other_args = dict(\n+ channel_handle=mhlo.ChannelHandle.get(channel, mlir.DEVICE_TO_DEVICE_TYPE))\n+ else:\n+ other_args = {}\n+\n+ return mhlo.CollectivePermuteOp(\n+ x, mlir.dense_int_elements(full_perm), **other_args).results\ndef _ppermute_transpose_rule(t, x, perm, axis_name):\nsrcs, dsts = unzip2(perm)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/xmap_test.py",
"new_path": "tests/xmap_test.py",
"diff": "@@ -873,6 +873,16 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\nin_axes=['i', ...], out_axes=[...], axis_resources={'i': 'x'})(x)\nself.assertAllClose(x.sum(0), y)\n+ @jtu.with_mesh([('x', 2)])\n+ def testRepro(self):\n+ n = 2\n+ x = jnp.arange(n * 5, dtype=jnp.float32).reshape(n, 5)\n+\n+ f = xmap(lambda x: lax.ppermute(x, 'i', perm=[(j, (j + 1) % n) for j in range(n)]),\n+ in_axes=['i', ...], out_axes=['i', ...], axis_resources={'i': 'x'})\n+ g = pjit(f, in_axis_resources=P('x'), out_axis_resources=P('x'))\n+ self.assertAllClose(g(x), x[::-1])\n+\nclass NamedNumPyTest(XMapTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Add support for MANUAL lowering of ppermute
PiperOrigin-RevId: 481157480 |
260,447 | 14.10.2022 16:26:58 | 25,200 | 69525cd96dc3a55258aeabcd6624ddf909595198 | [sparse] Make BCSR vmappable. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcsr.py",
"new_path": "jax/experimental/sparse/bcsr.py",
"diff": "@@ -26,6 +26,7 @@ from jax.experimental.sparse import bcoo\nfrom jax.experimental.sparse.util import _broadcasting_vmap, _count_stored_elements, _csr_to_coo, _safe_asarray\nimport jax.numpy as jnp\nfrom jax.util import split_list, safe_zip\n+from jax.interpreters import batching\nfrom jax.interpreters import mlir\nShape = Tuple[int, ...]\n@@ -309,3 +310,31 @@ class BCSR(JAXSparse):\ndef todense(self):\n\"\"\"Create a dense version of the array.\"\"\"\nreturn bcsr_todense(self)\n+\n+\n+#--------------------------------------------------------------------\n+# vmappable handlers\n+def _bcsr_to_elt(cont, _, val, axis):\n+ if axis is None:\n+ return val\n+ if axis >= val.n_batch:\n+ raise ValueError(f\"Cannot map in_axis={axis} for BCSR array with n_batch=\"\n+ f\"{val.n_batch}. in_axes for batched BCSR operations must \"\n+ \"correspond to a batched dimension.\")\n+ return BCSR((cont(val.data, axis),\n+ cont(val.indices, axis),\n+ cont(val.indptr, axis)),\n+ shape=val.shape[:axis] + val.shape[axis + 1:])\n+\n+\n+def _bcsr_from_elt(cont, axis_size, elt, axis):\n+ if axis > elt.n_batch:\n+ raise ValueError(f\"BCSR: cannot add out_axis={axis} for BCSR array with \"\n+ f\"n_batch={elt.n_batch}. BCSR batch axes must be a \"\n+ \"contiguous block of leading dimensions.\")\n+ return BCSR((cont(axis_size, elt.data, axis),\n+ cont(axis_size, elt.indices, axis),\n+ cont(axis_size, elt.indptr, axis)),\n+ shape=elt.shape[:axis] + (axis_size,) + elt.shape[axis:])\n+\n+batching.register_vmappable(BCSR, int, int, _bcsr_to_elt, _bcsr_from_elt, None)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -32,6 +32,7 @@ from jax.experimental.sparse import coo as sparse_coo\nfrom jax.experimental.sparse import bcoo as sparse_bcoo\nfrom jax.experimental.sparse import bcsr as sparse_bcsr\nfrom jax.experimental.sparse.bcoo import BCOOInfo\n+from jax.experimental.sparse.util import _csr_to_coo\nfrom jax import lax\nfrom jax._src.lib import xla_extension_version\nfrom jax._src.lib import gpu_sparse\n@@ -641,6 +642,29 @@ class cuSparseTest(jtu.JaxTestCase):\nclass BCOOTest(jtu.JaxTestCase):\n+ def test_vmappable(self):\n+ \"\"\"Test does not depend on batching rules of BCOO primitives.\"\"\"\n+ M = jnp.arange(9).reshape((3, 3))\n+\n+ def fromdense_1d(x):\n+ assert x.ndim == 1\n+ ind = jnp.where(x != 0, size=3)[0]\n+ val = x[ind]\n+ return sparse.BCOO((val, ind[:, None]), shape=x.shape)\n+\n+ with self.subTest('_bcoo_from_elt'):\n+ self.assertEqual(M.shape, vmap(fromdense_1d)(M).shape)\n+\n+ def todense_1d(bcoo_mat):\n+ assert bcoo_mat.ndim == 1\n+ assert bcoo_mat.n_sparse == 1\n+ x = jnp.empty(bcoo_mat.shape, dtype=bcoo_mat.dtype)\n+ return x.at[bcoo_mat.indices.ravel()].set(bcoo_mat.data)\n+\n+ with self.subTest('_bcoo_to_elt'):\n+ bcoo_mat = sparse.BCOO.fromdense(M, n_batch=1)\n+ self.assertEqual(bcoo_mat.shape, vmap(todense_1d)(bcoo_mat).shape)\n+\ndef test_repr(self):\nx = sparse.BCOO.fromdense(jnp.arange(5, dtype='float32'))\nself.assertEqual(repr(x), \"BCOO(float32[5], nse=4)\")\n@@ -2182,6 +2206,34 @@ class BCOOTest(jtu.JaxTestCase):\n# TODO(tianjianlu): Unify the testing for BCOOTest and BCSRTest.\nclass BCSRTest(jtu.JaxTestCase):\n+ def test_vmappable(self):\n+ \"\"\"Test does not depend on batching rules of BCSR primitives.\"\"\"\n+ M = jnp.arange(36).reshape((4, 3, 3))\n+\n+ def fromdense_2d(x):\n+ assert x.ndim == 2\n+ row, col = jnp.where(x != 0, size=3)\n+ val = x[row, col]\n+ indices = col\n+ indptr = jnp.zeros(x.shape[0] + 1, dtype=int)\n+ indptr = indptr.at[1:].set(jnp.cumsum(\n+ jnp.bincount(row, length=x.shape[0]).astype(int)))\n+ return sparse.BCSR((val, indices, indptr), shape=x.shape)\n+\n+ with self.subTest('_bcsr_from_elt'):\n+ self.assertEqual(M.shape, vmap(fromdense_2d)(M).shape)\n+\n+ def todense_2d(bcsr_mat):\n+ assert bcsr_mat.ndim == 2\n+ assert bcsr_mat.n_sparse == 2\n+ x = jnp.empty(bcsr_mat.shape, dtype=bcsr_mat.dtype)\n+ row, col = _csr_to_coo(bcsr_mat.indices, bcsr_mat.indptr)\n+ return x.at[row, col].set(bcsr_mat.data)\n+\n+ with self.subTest('_bcsr_to_elt'):\n+ bcsr_mat = sparse.BCSR.fromdense(M, n_batch=1)\n+ self.assertEqual(bcsr_mat.shape, vmap(todense_2d)(bcsr_mat).shape)\n+\n@jtu.sample_product(\n[dict(shape=shape, n_batch=n_batch)\nfor shape in [(5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Make BCSR vmappable.
PiperOrigin-RevId: 481257762 |
260,424 | 17.10.2022 21:48:38 | -3,600 | c2a00a0526a183a2d5eddbd69e0dd85457bffd63 | Disallow checkify-of-vmap-of-while. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -702,38 +702,14 @@ def ignore_error_output_jaxpr(jaxpr):\nnew_jaxpr = jaxpr.replace(outvars=jaxpr.outvars[3:])\nreturn core.ClosedJaxpr(new_jaxpr, consts)\n-def batch_error(err, code, payload, batch_shape):\n- err = jnp.broadcast_to(err, batch_shape)\n- code = jnp.broadcast_to(code, batch_shape)\n- payload = jnp.broadcast_to(payload, batch_shape+(3,))\n- return err, code, payload\n-\n-def unbatch_error(err, code, payload):\n- err = err.ravel()[0]\n- code = code.ravel()[0]\n- payload = payload.reshape(-1, 3)[0]\n- return err, code, payload\n-\n-def trivial_batched_jaxpr(jaxpr, batch_shape, batched_err):\n- fun = core.jaxpr_as_fun(jaxpr)\n-\n- def g(err, code, payload, *a):\n- err_args = unbatch_error(err, code, payload)\n- err, code, payload, *out = fun(*err_args, *a)\n- err, code, payload = batch_error(err, code, payload, batch_shape)\n- return (err, code, payload, *out)\n-\n- error_avals = map(lambda x: core.raise_to_shaped(core.get_aval(x)), batched_err)\n- new_jaxpr, _, literals_out = pe.trace_to_jaxpr_dynamic(\n- lu.wrap_init(g), [*error_avals, *jaxpr.in_avals[3:]])\n- return core.ClosedJaxpr(new_jaxpr, literals_out)\n-\ndef while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\ncond_jaxpr, body_nconsts, body_jaxpr):\n- batch_shape = cond_jaxpr.out_avals[0].shape\n- if batch_shape:\n- err_args = batch_error(error.err, error.code, error.payload, batch_shape)\n- else:\n+ if cond_jaxpr.out_avals[0].shape:\n+ # TODO(lenamartens, sharadmv): support batched while.\n+ raise ValueError('Checkify does not support batched while-loops '\n+ '(checkify-of-vmap-of-while). \\nHint: if possible, move '\n+ 'the vmap to the outer level to get '\n+ 'vmap-of-checkify-of-while.')\nerr_args = [error.err, error.code, error.payload]\nc_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\n@@ -741,15 +717,11 @@ def while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\n# Check if the first cond application will error.\nchecked_cond_jaxpr, msgs_cond = checkify_jaxpr(cond_jaxpr, error,\nenabled_errors)\n- if batch_shape:\n- checked_cond_jaxpr = trivial_batched_jaxpr(checked_cond_jaxpr, batch_shape, err_args)\ncond_err, cond_code, cond_payload, _ = core.jaxpr_as_fun(checked_cond_jaxpr)(\n*err_args, *c_consts, *carry)\nchecked_body_jaxpr_, msgs_body = checkify_while_body_jaxpr(\ncond_jaxpr, body_jaxpr, error, enabled_errors, c_consts)\n- if batch_shape:\n- checked_body_jaxpr_ = trivial_batched_jaxpr(checked_body_jaxpr_, batch_shape, err_args)\nto_move = [False] * 3 + [True] * body_nconsts + [False] * len(carry)\nchecked_body_jaxpr = pe.move_binders_to_front(checked_body_jaxpr_, to_move)\n@@ -762,8 +734,6 @@ def while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\n*new_in_flat, cond_nconsts=cond_nconsts, cond_jaxpr=compat_cond_jaxpr,\nbody_nconsts=body_nconsts, body_jaxpr=checked_body_jaxpr)\nnew_msgs = {**error.msgs, **msgs_body, **msgs_cond}\n- if batch_shape:\n- err, code, payload = unbatch_error(err, code, payload)\nreturn out, Error(err, code, new_msgs, payload)\nerror_checks[lax.while_p] = while_loop_error_check\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -891,7 +891,7 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertIn(\"should be positive\", err.get())\n- def test_checkify_of_vmap_of_while(self):\n+ def test_checkify_of_vmap_of_while_errors(self):\n@jax.vmap\ndef fun(n, v):\ndef while_cond(s):\n@@ -909,17 +909,39 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nchecked_f = checkify.checkify(fun, errors=checkify.all_checks)\n- err, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([5., 2., 4.]))\n- self.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"division by zero\")\n+ with self.assertRaisesRegex(ValueError, \"checkify-of-vmap-of-while\"):\n+ checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([5., 2., 4.]))\n+ # TODO(lenamartens): reenable assertions below.\n+ # self.assertIsNotNone(err.get())\n+ # self.assertStartsWith(err.get(), \"division by zero\")\n- err, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([5., 2., -4.]))\n- self.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"value needs to be positive\")\n+ # err, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([5., 2., -4.]))\n+ # self.assertIsNotNone(err.get())\n+ # self.assertStartsWith(err.get(), \"value needs to be positive\")\n- err, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([6., 2., -4.]))\n- self.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"value needs to be less than 6\")\n+ # err, _ = checked_f(jnp.asarray([1., 2., 3.]), jnp.asarray([6., 2., -4.]))\n+ # self.assertIsNotNone(err.get())\n+ # self.assertStartsWith(err.get(), \"value needs to be less than 6\")\n+\n+ def test_checkify_of_vmap_of_while_masked_errors(self):\n+ def cond(x):\n+ return x < 5\n+\n+ def body(x):\n+ # This will only trigger in the masked portion of the batched while.\n+ checkify.check(x < 5, \"should never happen\")\n+ return x + 1\n+\n+ @jax.vmap\n+ def fun(x):\n+ return lax.while_loop(cond, body, x)\n+\n+ checked_f = checkify.checkify(fun)\n+\n+ with self.assertRaisesRegex(ValueError, \"checkify-of-vmap-of-while\"):\n+ checked_f(jnp.arange(5))\n+ # TODO(lenamartens): reenable assertions below.\n+ # self.assertIsNone(err.get())\ndef test_assert_cond_no_data_dependence(self):\ndef f():\n@@ -965,5 +987,6 @@ class LowerableChecksTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(xla_extension.XlaRuntimeError,\n\"x needs to be positive\"):\nf(-1.)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Disallow checkify-of-vmap-of-while. |
260,327 | 06.10.2022 10:19:44 | -3,600 | ccbc3059b0d5329584c7db7bffba25350bf2df2f | Add JAX equivalent of scipy.stats.mode | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/_src/scipy/stats/_core.py",
"diff": "+# Copyright 2022 The JAX Authors.\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 collections import namedtuple\n+from functools import partial\n+from typing import Optional, Tuple\n+\n+import jax.numpy as jnp\n+import scipy\n+from jax import jit\n+from jax._src import dtypes\n+from jax._src.api import vmap\n+from jax._src.numpy.lax_numpy import _check_arraylike\n+from jax._src.numpy.util import _wraps\n+from jax._src.typing import ArrayLike\n+from jax._src.util import canonicalize_axis, prod\n+\n+ModeResult = namedtuple('ModeResult', ('mode', 'count'))\n+\n+@_wraps(scipy.stats.mode, lax_description=\"\"\"\\\n+Currently the only supported nan_policy is 'propagate'\n+\"\"\")\n+@partial(jit, static_argnames=['axis', 'nan_policy', 'keepdims'])\n+def mode(a: ArrayLike, axis: Optional[int] = 0, nan_policy: str = \"propagate\", keepdims: bool = False) -> ModeResult:\n+ _check_arraylike(\"mode\", a)\n+ x = jnp.atleast_1d(a)\n+\n+ if nan_policy not in [\"propagate\", \"omit\", \"raise\"]:\n+ raise ValueError(\n+ f\"Illegal nan_policy value {nan_policy!r}; expected one of \"\n+ \"{'propoagate', 'omit', 'raise'}\"\n+ )\n+ if nan_policy == \"omit\":\n+ # TODO: return answer without nans included.\n+ raise NotImplementedError(\n+ f\"Logic for `nan_policy` of {nan_policy} is not implemented\"\n+ )\n+ if nan_policy == \"raise\":\n+ raise NotImplementedError(\n+ \"In order to best JIT compile `mode`, we cannot know whether `x` contains nans. \"\n+ \"Please check if nans exist in `x` outside of the `mode` function.\"\n+ )\n+\n+ input_shape = x.shape\n+ if keepdims:\n+ if axis is None:\n+ output_shape = tuple(1 for i in input_shape)\n+ else:\n+ output_shape = tuple(1 if i == axis else s for i, s in enumerate(input_shape))\n+ else:\n+ if axis is None:\n+ output_shape = ()\n+ else:\n+ output_shape = tuple(s for i, s in enumerate(input_shape) if i != axis)\n+\n+ if axis is None:\n+ axis = 0\n+ x = x.ravel()\n+\n+ def _mode_helper(x: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]:\n+ \"\"\"Helper function to return mode and count of a given array.\"\"\"\n+ if x.size == 0:\n+ return jnp.array(jnp.nan, dtype=dtypes.canonicalize_dtype(jnp.float_)), jnp.array(jnp.nan, dtype=dtypes.canonicalize_dtype(jnp.float_))\n+ else:\n+ vals, counts = jnp.unique(x, return_counts=True, size=x.size)\n+ return vals[jnp.argmax(counts)], counts.max()\n+\n+ axis = canonicalize_axis(axis, x.ndim)\n+ x = jnp.moveaxis(x, axis, 0)\n+ x = x.reshape(x.shape[0], prod(x.shape[1:]))\n+ vals, counts = vmap(_mode_helper, in_axes=1)(x)\n+ return ModeResult(vals.reshape(output_shape), counts.reshape(output_shape))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/__init__.py",
"new_path": "jax/scipy/stats/__init__.py",
"diff": "@@ -33,3 +33,4 @@ from jax.scipy.stats import chi2 as chi2\nfrom jax.scipy.stats import betabinom as betabinom\nfrom jax.scipy.stats import gennorm as gennorm\nfrom jax._src.scipy.stats.kde import gaussian_kde as gaussian_kde\n+from jax._src.scipy.stats._core import mode as mode\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -20,15 +20,19 @@ from absl.testing import absltest\nimport numpy as np\nimport scipy.stats as osp_stats\n+import scipy.version\nimport jax\n-from jax._src import test_util as jtu, tree_util\n+from jax._src import dtypes, test_util as jtu, tree_util\nfrom jax.scipy import stats as lsp_stats\nfrom jax.scipy.special import expit\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n+scipy_version = tuple(map(int, scipy.version.version.split('.')[:3]))\n+numpy_version = tuple(map(int, np.version.version.split('.')[:3]))\n+\nall_shapes = [(), (4,), (3, 4), (3, 1), (1, 4), (2, 1, 4)]\none_and_two_dim_shapes = [(4,), (3, 4), (3, 1), (1, 4)]\n@@ -880,5 +884,73 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\ntree_util.tree_map(lambda a, b: self.assertAllClose(a, b), kde, kde2)\nself.assertAllClose(evaluate_kde(kde, x), kde.evaluate(x))\n+ @jtu.sample_product(\n+ [dict(shape=shape, axis=axis)\n+ for shape, axis in (\n+ ((0,), None),\n+ ((0,), 0),\n+ ((7,), None),\n+ ((7,), 0),\n+ ((47, 8), None),\n+ ((47, 8), 0),\n+ ((47, 8), 1),\n+ ((0, 2, 3), None),\n+ ((0, 2, 3), 0),\n+ ((0, 2, 3), 1),\n+ ((0, 2, 3), 2),\n+ ((10, 5, 21), None),\n+ ((10, 5, 21), 0),\n+ ((10, 5, 21), 1),\n+ ((10, 5, 21), 2),\n+ )\n+ ],\n+ dtype=jtu.dtypes.integer + jtu.dtypes.floating,\n+ contains_nans=[True, False],\n+ keepdims=[True, False]\n+ )\n+ def testMode(self, shape, dtype, axis, contains_nans, keepdims):\n+ if scipy_version < (1, 9, 0) and keepdims != True:\n+ self.skipTest(\"scipy < 1.9.0 only support keepdims == True\")\n+ if numpy_version < (1, 21, 0) and contains_nans:\n+ self.skipTest(\"numpy < 1.21.0 only support contains_nans == False\")\n+\n+ if contains_nans:\n+ rng = jtu.rand_some_nan(self.rng())\n+ else:\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+\n+ def scipy_mode_wrapper(a, axis=0, nan_policy='propagate', keepdims=None):\n+ \"\"\"Wrapper to manage the shape discrepancies between scipy and jax\"\"\"\n+ if scipy_version < (1, 9, 0) and a.size == 0 and keepdims == True:\n+ if axis == None:\n+ output_shape = tuple(1 for _ in a.shape)\n+ else:\n+ output_shape = tuple(1 if i == axis else s for i, s in enumerate(a.shape))\n+ return (np.full(output_shape, np.nan, dtype=dtypes.canonicalize_dtype(jax.numpy.float_)),\n+ np.full(output_shape, np.nan, dtype=dtypes.canonicalize_dtype(jax.numpy.float_)))\n+\n+ if scipy_version < (1, 9, 0):\n+ result = osp_stats.mode(a, axis=axis, nan_policy=nan_policy)\n+ else:\n+ result = osp_stats.mode(a, axis=axis, nan_policy=nan_policy, keepdims=keepdims)\n+\n+ if a.size != 0 and axis == None and keepdims == True:\n+ output_shape = tuple(1 for _ in a.shape)\n+ return (result.mode.reshape(output_shape), result.count.reshape(output_shape))\n+ return result\n+\n+ scipy_fun = partial(scipy_mode_wrapper, axis=axis, keepdims=keepdims)\n+ scipy_fun = jtu.ignore_warning(category=RuntimeWarning,\n+ message=\"Mean of empty slice.*\")(scipy_fun)\n+ scipy_fun = jtu.ignore_warning(category=RuntimeWarning,\n+ message=\"invalid value encountered.*\")(scipy_fun)\n+ lax_fun = partial(lsp_stats.mode, axis=axis, keepdims=keepdims)\n+ tol_spec = {np.float32: 2e-4, np.float64: 5e-6}\n+ tol = jtu.tolerance(dtype, tol_spec)\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n+ tol=tol)\n+ self._CompileAndCheck(lax_fun, args_maker, rtol=tol)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add JAX equivalent of scipy.stats.mode |
260,335 | 14.10.2022 17:19:37 | 25,200 | 43098f906a60929a6498f6132253195ed2f272e2 | initial commit of DevicesSharding (fka SimpleSharding)
need to add tests! | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/sharding.py",
"new_path": "jax/_src/sharding.py",
"diff": "# 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+from __future__ import annotations\nimport abc\nimport functools\nfrom collections import Counter\n-from typing import Sequence, Tuple, Optional, Mapping, Dict, Set, Union, cast\n+import operator as op\n+from typing import (Sequence, List, Tuple, Optional, Mapping, Dict, Set,\n+ FrozenSet, Union, cast)\n-from jax._src.util import safe_zip\n+import jax\n+from jax._src.util import safe_map, safe_zip, unzip2, prod\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\nfrom jax._src.lib import xla_extension_version\n@@ -344,6 +348,119 @@ class PmapSharding(XLACompatibleSharding):\nreturn global_shape[:sharded_dim] + global_shape[sharded_dim+1:]\n+class DevicesSharding(XLACompatibleSharding):\n+ _devices: List[xc.Device]\n+ _ids: np.ndarray # dtype DeviceIdSet\n+\n+ def __init__(self, devices: Union[Sequence[xc.Device], np.ndarray]):\n+ if not isinstance(devices, np.ndarray):\n+ devices = np.array(devices, dtype='object')\n+ if not devices.size:\n+ raise ValueError(f\"{self.__class__.__name__}.__init__ requires at least \"\n+ f\"one devices, got {devices}\")\n+ self._devices = list(devices.flat)\n+ name = self._devices[0].platform.upper()\n+ self._ids = np.array([DeviceIdSet(name, i) for i in range(devices.size)],\n+ dtype='object')\n+\n+ shape = property(op.attrgetter('_ids.shape'))\n+ ndim = property(op.attrgetter('_ids.ndim'))\n+\n+ def __repr__(self) -> str:\n+ cls_name = self.__class__.__name__\n+ body = np.array2string(self._ids, prefix=cls_name + '(', suffix=')',\n+ max_line_width=100)\n+ return f'{cls_name}({body})'\n+\n+ def reshape(self, *shape):\n+ return self.remake(self._devices, self._ids.reshape(*shape))\n+\n+ def transpose(self, *axes):\n+ return self.remake(self._devices, self._ids.transpose(*axes))\n+ T = property(transpose)\n+\n+ def replicate(self, axis=None, keepdims=True):\n+ new_ids = self._ids.sum(axis=axis, keepdims=keepdims) # union\n+ return self.remake(self._devices, new_ids)\n+\n+ @classmethod\n+ def remake(cls, devices: List[xc.Device], ids: np.ndarray) -> DevicesSharding:\n+ self = cls.__new__(cls)\n+ self._devices = devices\n+ self._ids = ids\n+ return self\n+\n+ # Hashable\n+\n+ def __hash__(self) -> int:\n+ return id(self._devices)\n+\n+ def __eq__(self, other) -> bool:\n+ return (isinstance(other, DevicesSharding) and\n+ id(self._devices) == id(other._devices) and\n+ bool(np.all(self._ids == other._ids)))\n+\n+ # Sharding interface\n+\n+ @pxla.maybe_cached_property\n+ def device_set(self) -> set[xc.Device]:\n+ return set(self._devices)\n+\n+ # XLACompatibleSharding interface\n+\n+ @functools.lru_cache(maxsize=4096)\n+ def _to_xla_op_sharding(self, num_dimensions: int, axis_ctx=None):\n+ assert axis_ctx is None\n+\n+ pbuf = xc.OpSharding()\n+ if self.shape == (1,) * self.ndim:\n+ pbuf.type = xc.OpSharding.Type.REPLICATED\n+ return pbuf\n+\n+ shape = self.shape[self.ndim - num_dimensions:] # 'rank promotion' of val\n+ set_size, = {len(device_set) for device_set in self._ids.flat}\n+ pbuf.type = xc.OpSharding.Type.OTHER\n+ if set_size > 1:\n+ pbuf.last_tile_dims = [xc.OpSharding.Type.REPLICATED]\n+ pbuf.tile_assignment_dimensions = (*shape, set_size)\n+ else:\n+ pbuf.tile_assignment_dimensions = shape\n+ pbuf.tile_assignment_devices = [i for ids in self._ids.flat for i in ids]\n+ return pbuf\n+\n+ @property\n+ def _device_assignment(self) -> list[xc.Device]:\n+ return self._devices\n+\n+class DeviceIdSet:\n+ _name: str\n+ _ids: FrozenSet[int]\n+ def __init__(self, name, *ids):\n+ self._name = name\n+ self._ids = frozenset(ids)\n+\n+ def __iter__(self):\n+ return iter(sorted(self._ids))\n+\n+ def __add__(self, other) -> DeviceIdSet:\n+ assert isinstance(other, DeviceIdSet)\n+ return DeviceIdSet(self._name, *(self._ids | other._ids))\n+\n+ def __len__(self) -> int:\n+ return len(self._ids)\n+\n+ def __repr__(self) -> str:\n+ ids = ', '.join(safe_map(str, sorted(self._ids)))\n+ return f'{{{self._name} {ids}}}'\n+\n+ def __hash__(self) -> int:\n+ return hash((self._name, self._ids))\n+\n+ def __eq__(self, other) -> bool:\n+ return (isinstance(other, DeviceIdSet) and self._name == other._name and\n+ self._ids == other._ids)\n+\n+\n# TODO(yashkatariya): Remove this when minimum_jaxlib version is 0.3.17\ndef _hash_op_sharding(op: xc.OpSharding):\nif op.type == xc.OpSharding.Type.TUPLE:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/sharding.py",
"new_path": "jax/sharding.py",
"diff": "@@ -19,4 +19,5 @@ from jax._src.sharding import (\nSingleDeviceSharding as SingleDeviceSharding,\nPmapSharding as PmapSharding,\nOpShardingSharding as OpShardingSharding,\n+ DevicesSharding as DevicesSharding,\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/array_test.py",
"new_path": "tests/array_test.py",
"diff": "@@ -697,6 +697,34 @@ class ShardingTest(jtu.JaxTestCase):\ns2 = sharding.OpShardingSharding(jax.devices(), op2)\nself.assertEqual(repr(s2), 'OpShardingSharding({replicated})')\n+ @parameterized.named_parameters(\n+ (\"mesh_x_y\", P(\"x\", \"y\"), (4, 2), (), False),\n+ (\"mesh_x\", P(\"x\"), (4, 2), (1,), False),\n+ (\"mesh_y\", P(\"y\"), (4, 2), (0,), True),\n+ (\"mesh_none_y\", P(None, \"y\"), (4, 2), (0,), False),\n+ (\"mesh_none_x\", P(None, \"x\"), (4, 2), (1,), True),\n+ (\"mesh_xy\", P((\"x\", \"y\")), (8, 1), (), False),\n+ (\"mesh_fully_replicated\", P(), (4, 2), None, False),\n+ )\n+ def test_devices_sharding_op_sharding_lowering(\n+ self, pspec, shape, axes, transpose):\n+ value_shape = (8, 4)\n+\n+ mesh = jtu.create_global_mesh((4, 2), ('x', 'y'))\n+ mps = sharding.MeshPspecSharding(mesh, pspec)\n+\n+ devices_sharding = sharding.DevicesSharding(jax.devices())\n+ devices_sharding = devices_sharding.reshape(shape).replicate(axes)\n+ if transpose:\n+ devices_sharding = devices_sharding.T\n+\n+ op1 = mps._to_xla_op_sharding(len(value_shape))\n+ op2 = devices_sharding._to_xla_op_sharding(len(value_shape))\n+\n+ self.assertEqual(mps.shard_shape(value_shape),\n+ devices_sharding.shard_shape(value_shape))\n+ self.assertTrue(pxla.are_op_shardings_equal(op1, op2))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | initial commit of DevicesSharding (fka SimpleSharding)
need to add tests!
Co-authored-by: Yash Katariya <yashkatariya@google.com>
Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com> |
260,335 | 17.10.2022 11:15:14 | 25,200 | a1d303b081474e0ba01b1525c9270eedd6071163 | [dynamic-shapes] fix nested vmap callable annotation logic | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -42,15 +42,17 @@ def identity(x): return x\ndef _update_annotation(\nf: lu.WrappedFun,\norig_type: Optional[Tuple[Tuple[core.AbstractValue, bool], ...]],\n- nonzeros: List[bool]\n+ explicit_nonzeros: List[bool]\n) -> lu.WrappedFun:\nif orig_type is None:\nreturn f\n+ # By convention, `explicit_nonzeros` only accounts for explicit arguments.\n+ assert len(explicit_nonzeros) == sum(explicit for _, explicit in orig_type)\n# Implicit arguments never have tangents, so generate the tangent part of the\n# type annotation from explicit arguments only.\n- orig_avals = [aval for aval, explicit in orig_type if explicit]\n+ explicit_avals = [aval for aval, explicit in orig_type if explicit]\ntan_types = [(aval.at_least_vspace(), True)\n- for nz, aval in zip(nonzeros, orig_avals) if nz]\n+ for nz, aval in zip(explicit_nonzeros, explicit_avals) if nz]\nreturn lu.annotate(f, (*orig_type, *tan_types))\ndef jvp(fun: lu.WrappedFun, has_aux=False, instantiate=True,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -33,20 +33,30 @@ from jax._src.util import (unzip2, unzip3, safe_map, safe_zip, wrap_name,\nweakref_lru_cache)\nfrom jax.interpreters import partial_eval as pe\n-map = safe_map\n+map, unsafe_map = safe_map, map\n+zip, unsafe_zip = safe_zip, zip\ndef _update_annotation(\nf: lu.WrappedFun, orig_type: Optional[core.InputType],\naxis_size: core.AxisSize, axis_name: core.AxisName,\n- in_dims: Sequence[Optional[int]]) -> lu.WrappedFun:\n+ explicit_in_dims: Sequence[Optional[int]]) -> lu.WrappedFun:\nif orig_type is None: return f\n- if isinstance(axis_size, core.Tracer):\n- in_type_ = [(core.unmapped_aval(core.DBIdx(0), axis_name, dim, aval), keep)\n- for dim, (aval, keep) in zip(in_dims, orig_type)]\n- in_type = [(axis_size.aval, False), *in_type_]\n- else:\n- in_type = [(core.unmapped_aval(axis_size, axis_name, dim, aval), keep)\n- for dim, (aval, keep) in zip(in_dims, orig_type)]\n+ # By convention, `explicit_in_dims` only accounts for explicit arguments.\n+ assert len(explicit_in_dims) == sum(explicit for _, explicit in orig_type)\n+ # We add a batch dim to each mapped argument type. If `axis_size` is dynamic\n+ # (i.e. a Tracer) the added batch dim size is a DBIdx and we add a new leading\n+ # implicit argument and increment all other DBIdx.\n+ new_arg = isinstance(axis_size, Tracer)\n+ sz = core.DBIdx(0) if new_arg else axis_size\n+ def unmap(d, a):\n+ if isinstance(a, core.DShapedArray):\n+ a = a.update(shape=tuple(core.DBIdx(d.val + new_arg)\n+ if type(d) is core.DBIdx else d for d in a.shape))\n+ return core.unmapped_aval(sz, axis_name, d, a)\n+ in_dims = iter(explicit_in_dims)\n+ in_type = [(unmap(next(in_dims), a), explicit) if explicit else (a, explicit)\n+ for a, explicit in orig_type]\n+ if new_arg: in_type = [(axis_size.aval, False), *in_type] # type: ignore\nreturn lu.annotate(f, tuple(in_type))\n### vmappable typeclass\n@@ -285,8 +295,8 @@ class BatchTrace(Trace):\nfor out_axis, d in zip(out_axes_thunk(), dims_out()))\nnew_params = dict(params, in_axes=new_in_axes, out_axes_thunk=new_out_axes_thunk)\nvals_out = map_primitive.bind(f, *vals, **new_params)\n- dims_out = (d + 1 if both_mapped(out_axis, d) and out_axis <= d else d\n- for d, out_axis in zip(dims_out(), out_axes_thunk()))\n+ dims_out = [d + 1 if both_mapped(out_axis, d) and out_axis <= d else d\n+ for d, out_axis in zip(dims_out(), out_axes_thunk())]\nsrc = source_info_util.current()\nreturn [BatchTracer(self, v, d, src) for v, d in zip(vals_out, dims_out)]\n@@ -345,7 +355,8 @@ class BatchTrace(Trace):\nout_vals = prim.bind(fun, fwd, bwd, *in_vals, out_trees=out_trees)\nfst, out_dims = lu.merge_linear_aux(out_dims1, out_dims2)\nif not fst:\n- out_dims = out_dims[-len(out_vals) % len(out_dims):]\n+ _, res_tree = out_trees()\n+ _, out_dims = split_list(out_dims, [res_tree.num_leaves])\nsrc = source_info_util.current()\nreturn [BatchTracer(self, v, d, src) for v, d in zip(out_vals, out_dims)]\n@@ -551,7 +562,8 @@ zero_if_mapped = ZeroIfMapped()\n@lu.transformation_with_aux\ndef batch_custom_jvp_subtrace(main, in_dims, *in_vals):\n- size, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\n+ size, = {x.shape[d] for x, d in zip(in_vals, in_dims * 2)\n+ if d is not not_mapped}\ntrace = main.with_cur_sublevel()\nin_tracers = [BatchTracer(trace, val, dim) if dim is not None else val\nfor val, dim in zip(in_vals, in_dims * 2)]\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/dynamic_api_test.py",
"new_path": "tests/dynamic_api_test.py",
"diff": "@@ -1303,6 +1303,24 @@ class DynamicShapeTest(jtu.JaxTestCase):\nf, = jaxpr.outvars\nself.assertEqual(f.aval.shape, (a,))\n+ def test_vmap_abstracted_axes_2d(self):\n+ def foo(x, y):\n+ z = jax.vmap(jax.vmap(jnp.sin))(x) * y\n+ return jax.vmap(jax.vmap(jnp.add))(x, z)\n+\n+ x = jnp.arange(12.).reshape(3, 4)\n+ jaxpr = jax.make_jaxpr(foo, abstracted_axes=('n', 'm'))(x, x).jaxpr\n+ self.assertLen(jaxpr.invars, 4)\n+ a, b, c, d = jaxpr.invars\n+ self.assertEqual(a.aval.shape, ())\n+ self.assertEqual(b.aval.shape, ())\n+ self.assertEqual(c.aval.shape, (a, b))\n+ self.assertEqual(c.aval.shape, (a, b))\n+ self.assertLen(jaxpr.eqns, 3)\n+ self.assertLen(jaxpr.outvars, 1)\n+ f, = jaxpr.outvars\n+ self.assertEqual(f.aval.shape, (a, b))\n+\ndef test_vmap_of_indexing_basic(self):\nx = jnp.arange(3.)\n"
}
] | Python | Apache License 2.0 | google/jax | [dynamic-shapes] fix nested vmap callable annotation logic |
260,447 | 20.10.2022 10:29:48 | 25,200 | 2d563bf0a2aaf68b7d992613da4982bdd74d69b4 | [sparse] Add BCSR primitive bcsr_extract. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/__init__.py",
"new_path": "jax/experimental/sparse/__init__.py",
"diff": "@@ -218,6 +218,8 @@ from jax.experimental.sparse.bcoo import (\n)\nfrom jax.experimental.sparse.bcsr import (\n+ bcsr_extract as bcsr_extract,\n+ bcsr_extract_p as bcsr_extract_p,\nbcsr_fromdense as bcsr_fromdense,\nbcsr_fromdense_p as bcsr_fromdense_p,\nbcsr_todense as bcsr_todense,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcsr.py",
"new_path": "jax/experimental/sparse/bcsr.py",
"diff": "@@ -233,6 +233,43 @@ mlir.register_lowering(bcsr_todense_p, mlir.lower_fun(\n_bcsr_todense_impl, multiple_results=False))\n+#--------------------------------------------------------------------\n+# bcsr_extract\n+bcsr_extract_p = core.Primitive('bcsr_extract')\n+\n+\n+def bcsr_extract(indices, indptr, mat):\n+ \"\"\"Extract values from a dense matrix at given BCSR (indices, indptr).\n+\n+ Args:\n+ indices: An ndarray; see BCSR indices.\n+ indptr: An ndarray; see BCSR indptr.\n+ mat: A dense matrix.\n+\n+ Returns:\n+ An ndarray; see BCSR data.\n+ \"\"\"\n+ return bcsr_extract_p.bind(indices, indptr, mat)\n+\n+\n+@bcsr_extract_p.def_impl\n+def _bcsr_extract_impl(indices, indptr, mat):\n+ mat = jnp.asarray(mat)\n+ bcoo_indices = _bcsr_to_bcoo(indices, indptr, shape=mat.shape)\n+ return bcoo.bcoo_extract(bcoo_indices, mat)\n+\n+\n+@bcsr_extract_p.def_abstract_eval\n+def _bcsr_extract_abstract_eval(indices, indptr, mat):\n+ n_batch, n_dense, nse = _validate_bcsr_indices(indices, indptr, mat.shape)\n+ out_shape = mat.shape[:n_batch] + (nse,) + mat.shape[mat.ndim - n_dense:]\n+ return core.ShapedArray(out_shape, mat.dtype)\n+\n+\n+mlir.register_lowering(bcsr_extract_p, mlir.lower_fun(\n+ _bcsr_extract_impl, multiple_results=False))\n+\n+\nclass BCSR(JAXSparse):\n\"\"\"Experimental batched CSR matrix implemented in JAX.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -2269,6 +2269,26 @@ class BCSRTest(jtu.JaxTestCase):\nargs_maker_todense = lambda: [data, indices, indptr]\nself._CompileAndCheck(todense, args_maker_todense)\n+ @jtu.sample_product(\n+ [dict(shape=shape, n_batch=n_batch)\n+ for shape in [(5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]\n+ for n_batch in range(len(shape) - 1)\n+ ],\n+ dtype=jtu.dtypes.floating + jtu.dtypes.complex,\n+ )\n+ def test_bcsr_extract(self, shape, dtype, n_batch):\n+ n_dense = len(shape) - n_batch - 2\n+ rng = rand_sparse(self.rng())\n+ M = rng(shape, dtype)\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\n+ data, indices, indptr = sparse_bcsr._bcsr_fromdense(\n+ M, nse=nse, n_batch=n_batch, n_dense=n_dense)\n+ data2 = sparse.bcsr_extract(indices, indptr, M)\n+ self.assertArraysEqual(data, data2)\n+ args_maker_bcsr_extract = lambda: [indices, indptr, M]\n+ self._CompileAndCheck(sparse.bcsr_extract, args_maker_bcsr_extract)\n+\nclass SparseGradTest(jtu.JaxTestCase):\ndef test_sparse_grad(self):\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Add BCSR primitive bcsr_extract.
PiperOrigin-RevId: 482530210 |
260,447 | 20.10.2022 11:48:18 | 25,200 | 7093142f616c4fc883dda5287a93131fa07e961e | [sparse] Update the default cuSparse matvec algorithm in jaxlib. | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusparse.cc",
"new_path": "jaxlib/cuda/cusparse.cc",
"diff": "@@ -295,7 +295,7 @@ std::pair<size_t, py::bytes> BuildCsrMatvecDescriptor(\nCudaConst beta = CudaZero(y.type);\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseSpMV_bufferSize(\nhandle.get(), op, &alpha, mat_a, vec_x, &beta, vec_y, y.type,\n- CUSPARSE_MV_ALG_DEFAULT, &buffer_size)));\n+ CUSPARSE_SPMV_CSR_ALG2, &buffer_size)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseDestroySpMat(mat_a)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseDestroyDnVec(vec_x)));\n@@ -468,7 +468,7 @@ std::pair<size_t, py::bytes> BuildCooMatvecDescriptor(\nCudaConst beta = CudaZero(y.type);\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseSpMV_bufferSize(\nhandle.get(), op, &alpha, mat_a, vec_x, &beta, vec_y, y.type,\n- CUSPARSE_MV_ALG_DEFAULT, &buffer_size)));\n+ CUSPARSE_SPMV_COO_ALG2, &buffer_size)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseDestroySpMat(mat_a)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseDestroyDnVec(vec_x)));\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusparse_kernels.cc",
"new_path": "jaxlib/cuda/cusparse_kernels.cc",
"diff": "@@ -277,7 +277,7 @@ static absl::Status CsrMatvec_(cudaStream_t stream, void** buffers,\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(\ncusparseSpMV(handle.get(), d.op, &alpha, mat_a, vec_x, &beta, vec_y,\n- d.y.type, CUSPARSE_MV_ALG_DEFAULT, buf)));\n+ d.y.type, CUSPARSE_SPMV_CSR_ALG2, buf)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseDestroySpMat(mat_a)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseDestroyDnVec(vec_x)));\n@@ -474,7 +474,7 @@ static absl::Status CooMatvec_(cudaStream_t stream, void** buffers,\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(\ncusparseSpMV(handle.get(), d.op, &alpha, mat_a, vec_x, &beta, vec_y,\n- d.y.type, CUSPARSE_MV_ALG_DEFAULT, buf)));\n+ d.y.type, CUSPARSE_SPMV_COO_ALG2, buf)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseDestroySpMat(mat_a)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseDestroyDnVec(vec_x)));\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Update the default cuSparse matvec algorithm in jaxlib.
PiperOrigin-RevId: 482553550 |
260,310 | 20.10.2022 16:08:16 | 25,200 | 408953bc3ec9798a5d227d4f6844b898f1e2fedd | fix jax2tf readme typo | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -76,7 +76,7 @@ def f_jax(x):\nf_tf = jax2tf.convert(f_jax)\n# For example you execute f_tf eagerly with valid TensorFlow inputs:\n-f_tf(np.random(...))\n+f_tf(np.random.random(...))\n# Additionally you can use tools like `tf.function` to improve the execution\n# time of your function, or to stage it out to a SavedModel:\n@@ -441,7 +441,7 @@ new shape:\n```python\njax2tf.convert(lambda x: jnp.reshape(x, (x.shape[0] * x.shape[1],)),\n- polymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4))\n+ polymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4)))\n```\nOther operations are partially supported for dimension polynomials:\n@@ -486,7 +486,7 @@ expression. Consider again the reshape example from above:\n```python\njax2tf.convert(lambda x: jnp.reshape(x, (x.shape[0] * x.shape[1],)),\n- polymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4))\n+ polymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4)))\n```\nThe internal shape environment would map `b` to `tf.shape(x)[0]`, and\n@@ -666,7 +666,7 @@ same dtype, you should use `jax2tf.dtype_of_val`:\n# The following two calls will lower jax_fun at the same dtypes\n# independently of the value of JAX_ENABLE_X64.\njax2tf.convert(jax_fun)(3.14)\n-jax2tf.convert(jax_fun)(tf.Variable(3.14, dtype=jax2tf.dtype_of_val(3.14))\n+jax2tf.convert(jax_fun)(tf.Variable(3.14, dtype=jax2tf.dtype_of_val(3.14)))\n```\n### Incomplete TensorFlow data type coverage\n@@ -804,7 +804,7 @@ def f_jax(x): # x: int16\njax.grad(f_jax, allow_int=True)(x)\n# returns a special `float0`: array((b'',), dtype=[('float0', 'V')])\n-jax2tf.convert(jax.grad(f_jax, allow_int=True))(x))\n+jax2tf.convert(jax.grad(f_jax, allow_int=True))(x)\n# returns a tf.Tensor(0, shape=(), dtype=int32)\n```\n@@ -1013,7 +1013,7 @@ self.assertEqual(0, f_jax(x0)) # JAX sees that the x.shape[0] == 0\n# jax2tf catches the broken assumption b >= 1 if the lowered function is executed\n# eagerly.\n# Raises: ValueError: Dimension variable b must have integer value >= 1. Found value 0 when solving b == 0\n-jax2tf.convert(f_jax, polymorphic_shapes=[\"b\"])(x0))\n+jax2tf.convert(f_jax, polymorphic_shapes=[\"b\"])(x0)\n# However, if we first trace to a TensorFlow graph, we may miss the broken assumption:\nf_tf = tf.function(\n"
}
] | Python | Apache License 2.0 | google/jax | fix jax2tf readme typo
PiperOrigin-RevId: 482625385 |
260,335 | 13.10.2022 16:03:44 | 25,200 | 60b236cff01de3b8bd63e7c0dd381f02962dd9d4 | improve (and shorten!) pmap error messages about inconsistent axis sizes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -44,7 +44,6 @@ from jax.tree_util import (tree_map, tree_flatten, tree_unflatten,\ntree_structure, tree_transpose, tree_leaves,\ntreedef_is_leaf, treedef_children,\nPartial, PyTreeDef, all_leaves, treedef_tuple)\n-\nfrom jax._src import callback as jcb\nfrom jax._src import device_array\nfrom jax._src import dispatch\n@@ -63,7 +62,7 @@ from jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\nfrom jax._src.lib import pmap_lib\nfrom jax._src.traceback_util import api_boundary\n-from jax._src.tree_util import broadcast_prefix\n+from jax._src.tree_util import broadcast_prefix, _generate_key_paths\nfrom jax._src.util import (unzip2, curry, safe_map, safe_zip, prod, split_list,\nextend_name_stack, new_name_stack, wrap_name, cache,\nwraps, HashableFunction, weakref_lru_cache)\n@@ -1664,8 +1663,7 @@ def vmap(fun: F,\nflat_fun, out_tree = batching.flatten_fun_for_vmap(f, in_tree)\nin_axes_flat = flatten_axes(\"vmap in_axes\", in_tree, (in_axes, 0), kws=True)\naxis_size_ = (axis_size if axis_size is not None else\n- _mapped_axis_size(in_tree, args_flat, in_axes_flat, \"vmap\",\n- kws=True))\n+ _mapped_axis_size(fun, in_tree, args_flat, in_axes_flat, \"vmap\"))\nout_flat = batching.batch(\nflat_fun, axis_name, axis_size_, in_axes_flat,\nlambda: flatten_axes(\"vmap out_axes\", out_tree(), out_axes),\n@@ -1675,7 +1673,7 @@ def vmap(fun: F,\nreturn vmap_f\n-def _mapped_axis_size(tree, vals, dims, name, *, kws=False):\n+def _mapped_axis_size(fn, tree, vals, dims, name):\nif not vals:\nargs, kwargs = tree_unflatten(tree, vals)\nraise ValueError(\n@@ -1689,53 +1687,56 @@ def _mapped_axis_size(tree, vals, dims, name, *, kws=False):\nreturn shape[axis]\nexcept (IndexError, TypeError) as e:\nmin_rank = axis + 1 if axis >= 0 else -axis\n+ # TODO(mattjj): better error message here\nraise ValueError(\nf\"{name} was requested to map its argument along axis {axis}, \"\nf\"which implies that its rank should be at least {min_rank}, \"\nf\"but is only {len(shape)} (its shape is {shape})\") from e\n- axis_sizes = core.dedup_referents(\n- _get_axis_size(name, np.shape(x), d) for x, d in zip(vals, dims)\n- if d is not None)\n- if len(axis_sizes) == 1:\n- return axis_sizes[0]\n- if not axis_sizes:\n+ sizes = core.dedup_referents(_get_axis_size(name, np.shape(x), d)\n+ for x, d in zip(vals, dims) if d is not None)\n+ if len(sizes) == 1:\n+ sz, = sizes\n+ return sz\n+ if not sizes:\nmsg = f\"{name} must have at least one non-None value in in_axes\"\nraise ValueError(msg)\n- msg = f\"{name} got inconsistent sizes for array axes to be mapped:\\n\" + \"{}\"\n- # we switch the error message based on whether args is a tuple of arrays,\n- # in which case we can produce an error message based on argument indices,\n- # or if it has nested containers.\n- if kws:\n- position_only_tree, leaf = treedef_children(tree)\n- if not treedef_is_leaf(leaf):\n- sizes = [x.shape[d] if d is not None else None for x, d in zip(vals, dims)]\n- sizes = tree_unflatten(tree, sizes)\n- raise ValueError(msg.format(f\"the tree of axis sizes is:\\n{sizes}\")) from None\n- # if keyword arguments are included in the tree, we adapt the error\n- # message only to be about the positional arguments\n- tree = position_only_tree\n-\n- # TODO(mattjj,phawkins): add a way to inspect pytree kind more directly\n- if tree == tree_flatten((0,) * tree.num_leaves)[1]:\n- lines1 = [f\"arg {i} has shape {np.shape(x)} and axis {d} is to be mapped\"\n- for i, (x, d) in enumerate(zip(vals, dims))]\n- sizes = collections.defaultdict(list)\n- for i, (x, d) in enumerate(zip(vals, dims)):\n- if d is not None:\n- sizes[x.shape[d]].append(i)\n- lines2 = [\"{} {} {} {} to be mapped of size {}\".format(\n- \"args\" if len(idxs) > 1 else \"arg\",\n- \", \".join(map(str, idxs)),\n- \"have\" if len(idxs) > 1 else \"has\",\n- \"axes\" if len(idxs) > 1 else \"an axis\",\n- size)\n- for size, idxs in sizes.items()]\n- raise ValueError(msg.format(\"\\n\".join(lines1 + [\"so\"] + lines2))) from None\n+\n+ msg = [f\"{name} got inconsistent sizes for array axes to be mapped:\\n\"]\n+ args, kwargs = tree_unflatten(tree, vals)\n+ try:\n+ ba = inspect.signature(fn).bind(*args, **kwargs)\n+ except (TypeError, ValueError):\n+ ba = None\n+ if ba is None:\n+ args_paths = [f'args{p.pprint(\"\")} '\n+ f'of type {shaped_abstractify(x).str_short()}'\n+ for p, x in _generate_key_paths(args)]\n+ kwargs_paths = [f'kwargs{p.pprint(\"\")} '\n+ f'of type {shaped_abstractify(x).str_short()}'\n+ for p, x in _generate_key_paths(kwargs)]\n+ key_paths = [*args_paths, *kwargs_paths]\n+ else:\n+ key_paths = [f'argument {name}{p.pprint(\"\")} '\n+ f'of type {shaped_abstractify(x).str_short()}'\n+ for name, arg in ba.arguments.items()\n+ for p, x in _generate_key_paths(arg)]\n+ all_sizes = [_get_axis_size(name, np.shape(x), d) if d is not None else None\n+ for x, d in zip(vals, dims)]\n+ size_counts = collections.Counter(s for s in all_sizes if s is not None)\n+ (sz, ct), *other_counts = counts = size_counts.most_common()\n+ ex, *examples = [key_paths[all_sizes.index(sz)] for sz, _ in counts]\n+ ax, *axs = [dims[all_sizes.index(sz)] for sz, _ in counts]\n+ if ct == 1:\n+ msg.append(f\" * one axis had size {sz}: axis {ax} of {ex};\\n\")\n+ else:\n+ msg.append(f\" * most axes ({ct} of them) had size {sz}, e.g. axis {ax} of {ex};\\n\")\n+ for ex, ax, (sz, ct) in zip(examples, axs, other_counts):\n+ if ct == 1:\n+ msg.append(f\" * one axis had size {sz}: axis {ax} of {ex};\\n\")\nelse:\n- sizes = [x.shape[d] if d is not None else None for x, d in zip(vals, dims)]\n- sizes = tree_unflatten(tree, sizes)\n- raise ValueError(msg.format(f\"the tree of axis sizes is:\\n{sizes}\")) from None\n+ msg.append(f\" * some axes ({ct} of them) had size {sz}, e.g. axis {ax} of {ex};\\n\")\n+ raise ValueError(''.join(msg)[:-2]) # remove last semicolon and newline\ndef pmap(\n@@ -2036,8 +2037,7 @@ def _prepare_pmap(fun, in_axes, out_axes, static_broadcasted_tuple,\nglobal_arg_shapes_flat = tuple(flatten_axes(\n\"pmap global_arg_shapes\", in_tree, (dyn_global_arg_shapes, None),\nkws=True))\n- local_axis_size = _mapped_axis_size(\n- in_tree, args, in_axes_flat, \"pmap\", kws=True)\n+ local_axis_size = _mapped_axis_size(fun, in_tree, args, in_axes_flat, \"pmap\")\nflat_fun, out_tree = flatten_fun(f, in_tree)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/tree_util.py",
"new_path": "jax/_src/tree_util.py",
"diff": "@@ -411,9 +411,9 @@ class KeyPath(NamedTuple):\nif isinstance(other, KeyPathEntry):\nreturn KeyPath(self.keys + (other,))\nraise TypeError(type(other))\n- def pprint(self) -> str:\n+ def pprint(self, root: str = ' tree root') -> str:\nif not self.keys:\n- return ' tree root'\n+ return root\nreturn ''.join(k.pprint() for k in self.keys)\nclass GetitemKeyPathEntry(KeyPathEntry):\n@@ -453,6 +453,19 @@ register_keypaths(list,\nregister_keypaths(dict,\nlambda dct: [GetitemKeyPathEntry(k) for k in sorted(dct)])\n+def _generate_key_paths(tree: Any) -> List[Tuple[KeyPath, Any]]:\n+ return list(_generate_key_paths_(KeyPath(()), tree))\n+\n+def _generate_key_paths_(key_path: KeyPath, tree: Any\n+ ) -> Iterable[Tuple[KeyPath, Any]]:\n+ if treedef_is_strict_leaf(tree_structure(tree)):\n+ yield key_path, tree\n+ else:\n+ child_keys = _child_keys(tree)\n+ tree_children, _ = flatten_one_level(tree)\n+ for k, c in zip(child_keys, tree_children):\n+ yield from _generate_key_paths_(key_path + k, c)\n+\ndef _prefix_error(key_path: KeyPath, prefix_tree: Any, full_tree: Any,\nis_leaf: Optional[Callable[[Any], bool]] = None,\n) -> Iterable[Callable[[str], ValueError]]:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2751,45 +2751,42 @@ class APITest(jtu.JaxTestCase):\nreturn x + y\nwith self.assertRaisesRegex(\n- ValueError, \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n- \"the tree of axis sizes is:\\n\"\n- r\"\\(\\(1,\\), \\{'y': 2\\}\\)\"):\n- f(jnp.array([1]), y=jnp.array([1, 2]))\n+ ValueError,\n+ \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n+ r\" \\* one axis had size 1: axis 0 of argument x of type int32\\[1\\];\"\n+ \"\\n\"\n+ r\" \\* one axis had size 2: axis 0 of argument y of type int32\\[2\\]\"):\n+ f(jnp.array([1], 'int32'), y=jnp.array([1, 2], 'int32'))\ndef test_vmap_mismatched_axis_sizes_error_message_issue_705(self):\n# https://github.com/google/jax/issues/705\ndef h(a, b):\nreturn jnp.sum(a) + jnp.sum(b)\n- X = self.rng().randn(10, 4)\n- U = self.rng().randn(10, 2)\n+ X = self.rng().randn(10, 4).astype('float32')\n+ U = self.rng().randn(10, 2).astype('float32')\nwith self.assertRaisesRegex(\nValueError,\n\"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n- r\"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n- r\"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\" \"\\n\"\n- \"so\\n\"\n- \"arg 0 has an axis to be mapped of size 10\\n\"\n- \"arg 1 has an axis to be mapped of size 2\"):\n+ r\" \\* one axis had size 10: axis 0 of argument a of type float32\\[10,4\\];\"\"\\n\"\n+ r\" \\* one axis had size 2: axis 1 of argument b of type float32\\[10,2\\]\"):\napi.vmap(h, in_axes=(0, 1))(X, U)\nwith self.assertRaisesRegex(\nValueError,\n\"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n- r\"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n- r\"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\" \"\\n\"\n- r\"arg 2 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n- \"so\\n\"\n- \"args 0, 2 have axes to be mapped of size 10\\n\"\n- \"arg 1 has an axis to be mapped of size 2\"):\n+ r\" \\* most axes \\(2 of them\\) had size 10, e.g. axis 0 of argument x \"\n+ r\"of type float32\\[10,4\\];\" \"\\n\"\n+ r\" \\* one axis had size 2: axis 1 of argument y of type float32\\[10,2\\]\"):\napi.vmap(lambda x, y, z: None, in_axes=(0, 1, 0))(X, U, X)\nwith self.assertRaisesRegex(\nValueError,\n\"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n- \"the tree of axis sizes is:\\n\"\n- r\"\\(10, \\[2, 2\\]\\)\"):\n+ r\" \\* most axes \\(2 of them\\) had size 2, e.g. axis 1 of argument b\\[0\\] \"\n+ r\"of type float32\\[10,2\\];\" \"\\n\"\n+ r\" \\* one axis had size 10: axis 0 of argument a of type float32\\[10,4\\]\"):\napi.vmap(h, in_axes=(0, 1))(X, [U, U])\nerror = (r\"vmap was requested to map its argument along axis 0, which \"\n"
}
] | Python | Apache License 2.0 | google/jax | improve (and shorten!) pmap error messages about inconsistent axis sizes |
260,335 | 20.10.2022 21:56:00 | 25,200 | f76fc010e40e21d9b8d0814b911028f38a6062fd | put back some unsafe_maps | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -508,7 +508,7 @@ def _batch_jaxpr_axes(closed_jaxpr, axis_size, in_axes, out_axes_dest,\nf, out_batched = _batch_jaxpr_inner(f, axis_size, out_axes_dest)\nf = _batch_jaxpr_outer(f, axis_name, axis_size, in_axes, main_type)\navals_in = [core.unmapped_aval(axis_size, axis_name, b, aval) if b is not not_mapped\n- else aval for aval, b in zip(closed_jaxpr.in_avals, in_axes)]\n+ else aval for aval, b in unsafe_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@@ -523,7 +523,7 @@ def _batch_jaxpr_inner(axis_size, out_axes_dest, main, in_axes, *in_vals):\nout_axes_dest = [(None if src is not_mapped else 0)\nif dst is zero_if_mapped else dst\n- for src, dst in zip(out_axes, out_axes_dest)]\n+ for src, dst in unsafe_zip(out_axes, out_axes_dest)]\nif len(out_axes_dest) != len(out_axes):\nout_axis_dest, = out_axes_dest\nout_axes_dest = [out_axis_dest] * len(out_axes)\n@@ -538,7 +538,7 @@ def _batch_jaxpr_outer(axis_name, axis_size, in_dims, main_type, *in_vals):\naxis_size, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\nin_dims = in_dims() if callable(in_dims) else in_dims\nin_dims = [canonicalize_axis(ax, np.ndim(x)) if isinstance(ax, int)\n- else ax for x, ax in zip(in_vals, in_dims)]\n+ else ax for x, ax in unsafe_zip(in_vals, in_dims)]\nwith core.new_main(main_type, axis_name=axis_name) as main:\nwith core.extend_axis_env(axis_name, axis_size, main):\nout_vals = yield (main, in_dims, *in_vals), {}\n"
}
] | Python | Apache License 2.0 | google/jax | put back some unsafe_maps |
260,590 | 21.10.2022 10:22:36 | 25,200 | 7c1bf0e7cd868a667406f323348eea18fada23b3 | Fix an NameError caused by | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/third_party/scipy/signal_helper.py",
"new_path": "jax/_src/third_party/scipy/signal_helper.py",
"diff": "@@ -53,8 +53,10 @@ def _triage_segments(window: Union[ArrayLike, str, Tuple[Any, ...]], nperseg: Op\nraise ValueError('window is longer than input signal')\nif nperseg is None:\nnperseg_int = win.size\n- elif nperseg != win.size:\n+ else:\n+ if nperseg != win.size:\nraise ValueError(\"value specified for nperseg is different from length of window\")\n+ nperseg_int = win.size\nreturn win, nperseg_int\n"
}
] | Python | Apache License 2.0 | google/jax | Fix an NameError caused by #12754 |
260,447 | 21.10.2022 15:05:42 | 25,200 | e219d55c366d510316642d46eaf00cf288159f35 | Roll-back because CUSPARSE_SPMV_COO_ALG2 is not available in CUDA 11.1 | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusparse.cc",
"new_path": "jaxlib/cuda/cusparse.cc",
"diff": "@@ -295,7 +295,7 @@ std::pair<size_t, py::bytes> BuildCsrMatvecDescriptor(\nCudaConst beta = CudaZero(y.type);\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseSpMV_bufferSize(\nhandle.get(), op, &alpha, mat_a, vec_x, &beta, vec_y, y.type,\n- CUSPARSE_SPMV_CSR_ALG2, &buffer_size)));\n+ CUSPARSE_MV_ALG_DEFAULT, &buffer_size)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseDestroySpMat(mat_a)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseDestroyDnVec(vec_x)));\n@@ -468,7 +468,7 @@ std::pair<size_t, py::bytes> BuildCooMatvecDescriptor(\nCudaConst beta = CudaZero(y.type);\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseSpMV_bufferSize(\nhandle.get(), op, &alpha, mat_a, vec_x, &beta, vec_y, y.type,\n- CUSPARSE_SPMV_COO_ALG2, &buffer_size)));\n+ CUSPARSE_MV_ALG_DEFAULT, &buffer_size)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseDestroySpMat(mat_a)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(cusparseDestroyDnVec(vec_x)));\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusparse_kernels.cc",
"new_path": "jaxlib/cuda/cusparse_kernels.cc",
"diff": "@@ -277,7 +277,7 @@ static absl::Status CsrMatvec_(cudaStream_t stream, void** buffers,\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(\ncusparseSpMV(handle.get(), d.op, &alpha, mat_a, vec_x, &beta, vec_y,\n- d.y.type, CUSPARSE_SPMV_CSR_ALG2, buf)));\n+ d.y.type, CUSPARSE_MV_ALG_DEFAULT, buf)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseDestroySpMat(mat_a)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseDestroyDnVec(vec_x)));\n@@ -474,7 +474,7 @@ static absl::Status CooMatvec_(cudaStream_t stream, void** buffers,\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(\ncusparseSpMV(handle.get(), d.op, &alpha, mat_a, vec_x, &beta, vec_y,\n- d.y.type, CUSPARSE_SPMV_COO_ALG2, buf)));\n+ d.y.type, CUSPARSE_MV_ALG_DEFAULT, buf)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseDestroySpMat(mat_a)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseDestroyDnVec(vec_x)));\n"
}
] | Python | Apache License 2.0 | google/jax | Roll-back #12892 because CUSPARSE_SPMV_COO_ALG2 is not available in CUDA 11.1
PiperOrigin-RevId: 482897448 |
260,631 | 21.10.2022 19:53:28 | 25,200 | 3be5ab218a9f3b875ae5911b2f30fb4798955cac | Allow calling `initialize_cache` a second time if the path is the same. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/compilation_cache.py",
"new_path": "jax/experimental/compilation_cache/compilation_cache.py",
"diff": "@@ -20,6 +20,7 @@ import sys\nfrom typing import List, Optional\nfrom jax.experimental.compilation_cache.gfile_cache import GFileCache\n+from jax._src import path as pathlib\nfrom jax._src.lib import version_str as jaxlib_version_str\nfrom jax._src.lib import xla_client\nfrom jax.interpreters import xla\n@@ -31,8 +32,18 @@ logger = logging.getLogger(__name__)\ndef initialize_cache(path):\n\"\"\"Creates a global cache object. Should only be called once per process.\n+\n+ Will throw an assertion error if called a second time with a different path.\n+\n+ Args:\n+ path: path for the cache directory.\n+\n\"\"\"\nglobal _cache\n+ if _cache is not None and _cache._path == pathlib.Path(path):\n+ logger.warning(\"Cache already previoulsy initialized at %s\", _cache._path)\n+ return\n+\nassert _cache == None, f\"The cache path has already been initialized to {_cache._path}\"\n_cache = GFileCache(path)\nlogger.warning(\"Initialized persistent compilation cache at %s\", path)\n"
}
] | Python | Apache License 2.0 | google/jax | Allow calling `initialize_cache` a second time if the path is the same.
PiperOrigin-RevId: 482945880 |
260,411 | 25.10.2022 10:06:05 | -10,800 | 05b9c3be57ebc139e4be7677aecc36c4004937d1 | [jax2tf] Fixes uses of tf.Variable in README.md | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -634,7 +634,7 @@ jax2tf.convert(jnp.sin)(3.14) # Has type float32\njax2tf.convert(jnp.sin)(np.float64(3.14)) # Has type float32\n# The following will still compute `sin` in float32 (with a tf.cast on the argument).\n-tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, tf.float64))\n+tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, dtype=tf.float64))\n```\nWhen the `JAX_ENABLE_X64` flas is set, JAX uses 64-bit types\n@@ -649,7 +649,7 @@ tf.math.sin(3.14) # Has type float32\njax2tf.convert(jnp.sin)(3.14) # Has type float64\n# The following will compute `sin` in float64.\n-tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, tf.float64))\n+tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, dtype=tf.float64))\n# The following will compute `sin` in float32.\ntf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -218,31 +218,40 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(jnp.sin(big_const),\nf_conv(tf.constant(big_const)))\n- def test_64bit_behavior_enable_x64(self):\n+ def test_64bit_behavior_enable_x64_readme(self):\n+ # Tests some of the examples from the README\nif not config.jax_enable_x64:\nself.skipTest(\"requires x64 mode\")\n# JAX and TF have different default float types if JAX_ENABLE_X64=1\n- self.assertEqual(tf.math.sin(0.7).dtype, tf.float32)\n- self.assertEqual(jnp.sin(0.7).dtype, jnp.float64)\n+ self.assertEqual(tf.math.sin(3.14).dtype, tf.float32)\n+ self.assertEqual(jnp.sin(3.14).dtype, jnp.float64)\n# jax2tf.convert has the same behavior as JAX\n- self.assertEqual(jax2tf.convert(jnp.sin)(0.7).dtype, tf.float64)\n+ self.assertEqual(jax2tf.convert(jnp.sin)(3.14).dtype, tf.float64)\n+ # The following will compute `sin` in float64.\n+ self.assertEqual(tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, dtype=tf.float64)).dtype, tf.float64)\n- def test_64bit_behavior_not_enable_x64(self):\n+ # The following will compute `sin` in float32.\n+ self.assertEqual(tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14)).dtype, tf.float32)\n+\n+ def test_64bit_behavior_not_enable_x64_readme(self):\n+ # Tests some of the examples from the README\nif config.jax_enable_x64:\nself.skipTest(\"requires not x64 mode\")\n- # JAX and TF have same default float types if JAX_ENABLE_X64=1\n- self.assertEqual(tf.math.sin(0.7).dtype, tf.float32)\n- self.assertEqual(jnp.sin(0.7).dtype, jnp.float32)\n+ # JAX and TF have same default float types if JAX_ENABLE_X64=0\n+ self.assertEqual(tf.math.sin(3.14).dtype, tf.float32)\n+ self.assertEqual(jnp.sin(3.14).dtype, jnp.float32)\n- # Except that JAX forces values to 32-bit\n- self.assertEqual(jnp.sin(np.float64(0.7)).dtype, jnp.float32)\n+ self.assertEqual(tf.math.sin(np.float64(3.14)).dtype, tf.float64)\n+ # JAX forces values to 32-bit\n+ self.assertEqual(jnp.sin(np.float64(3.14)).dtype, jnp.float32)\n# jax2tf.convert has the same behavior as JAX\n- self.assertEqual(jax2tf.convert(jnp.sin)(0.7).dtype, tf.float32)\n- self.assertEqual(jax2tf.convert(jnp.sin)(np.float64(0.7)).dtype, tf.float32)\n+ self.assertEqual(jax2tf.convert(jnp.sin)(3.14).dtype, tf.float32)\n+ self.assertEqual(jax2tf.convert(jnp.sin)(np.float64(3.14)).dtype, tf.float32)\n+ self.assertEqual(tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, dtype=tf.float64)).dtype, tf.float32)\ndef test_function(self):\nf_jax = jax.jit(lambda x: jnp.sin(jnp.cos(x)))\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fixes uses of tf.Variable in README.md |
260,283 | 25.10.2022 19:29:32 | 0 | 63964237b2be0dc8a1a68f9b1b8a82062fff76e1 | Skip two unit tests about custom sharding on libtpu
DETAILS:
Due to xc.register_custom_call_partitioner is not supported on libtpu, the following two tests are skipped:
tests/pjit_test.py::PJitTest::test_custom_partitioner
tests/debugging_primitives_test.py::InspectShardingTest::test_inspect_sharding_is_called_in_pjit | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/test_util.py",
"new_path": "jax/_src/test_util.py",
"diff": "@@ -255,6 +255,9 @@ def is_device_rocm():\ndef is_device_cuda():\nreturn xla_bridge.get_backend().platform_version.startswith('cuda')\n+def is_cloud_tpu():\n+ return 'libtpu' in xla_bridge.get_backend().platform_version\n+\ndef is_device_tpu_v4():\nreturn jax.devices()[0].device_kind == \"TPU v4\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/debugging_primitives_test.py",
"new_path": "tests/debugging_primitives_test.py",
"diff": "@@ -1164,6 +1164,9 @@ class InspectShardingTest(jtu.JaxTestCase):\nif jaxlib.xla_extension_version < 94:\nraise unittest.SkipTest(\"Inspect sharding not supported.\")\n+ if jtu.is_cloud_tpu():\n+ raise unittest.SkipTest(\"Inspect sharding is not supported on libtpu.\")\n+\nis_called = False\ndef _cb(sd):\nnonlocal is_called\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pjit_test.py",
"new_path": "tests/pjit_test.py",
"diff": "@@ -1098,6 +1098,9 @@ class PJitTest(jtu.BufferDonationTestCase):\nif xla_extension_version < 95:\nraise unittest.SkipTest('Must support custom partitioning.')\n+ if jtu.is_cloud_tpu():\n+ raise unittest.SkipTest(\"Custom partitioning is not supported on libtpu.\")\n+\ndef partition(arg_shapes, arg_shardings, result_shape, result_sharding):\nself.assertEqual(arg_shardings[0], result_sharding)\nself.assertEqual(P(('x',)), result_sharding.spec)\n"
}
] | Python | Apache License 2.0 | google/jax | Skip two unit tests about custom sharding on libtpu
DETAILS:
Due to xc.register_custom_call_partitioner is not supported on libtpu, the following two tests are skipped:
tests/pjit_test.py::PJitTest::test_custom_partitioner
tests/debugging_primitives_test.py::InspectShardingTest::test_inspect_sharding_is_called_in_pjit |
260,335 | 25.10.2022 14:28:48 | 25,200 | 95eb4249bb020661b3f96171339a5abc490b2733 | tweaks to DevicesSharding
1. rename DevicesSharding -> ReshapeableDevicesSharding
2. fix repr to print device order faithfully
3. respect shape of np.ndarray argument to __init__ | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/sharding.py",
"new_path": "jax/_src/sharding.py",
"diff": "@@ -358,7 +358,7 @@ class PmapSharding(XLACompatibleSharding):\nreturn global_shape[:sharded_dim] + global_shape[sharded_dim+1:]\n-class DevicesSharding(XLACompatibleSharding):\n+class ReshapeableDevicesSharding(XLACompatibleSharding):\n_devices: List[xc.Device]\n_ids: np.ndarray # dtype DeviceIdSet\n@@ -367,18 +367,22 @@ class DevicesSharding(XLACompatibleSharding):\ndevices = np.array(devices, dtype='object')\nif not devices.size:\nraise ValueError(f\"{self.__class__.__name__}.__init__ requires at least \"\n- f\"one devices, got {devices}\")\n+ f\"one device, got {devices}\")\nself._devices = list(devices.flat)\nname = self._devices[0].platform.upper()\nself._ids = np.array([DeviceIdSet(name, i) for i in range(devices.size)],\n- dtype='object')\n+ dtype='object').reshape(devices.shape)\nshape = property(op.attrgetter('_ids.shape'))\nndim = property(op.attrgetter('_ids.ndim'))\ndef __repr__(self) -> str:\ncls_name = self.__class__.__name__\n- body = np.array2string(self._ids, prefix=cls_name + '(', suffix=')',\n+ ids = self._ids.copy()\n+ platform_name = self._devices[0].platform.upper()\n+ for idx, x in np.ndenumerate(ids):\n+ ids[idx] = DeviceIdSet(platform_name, *(self._devices[i].id for i in x))\n+ body = np.array2string(ids, prefix=cls_name + '(', suffix=')',\nmax_line_width=100)\nreturn f'{cls_name}({body})'\n@@ -394,7 +398,8 @@ class DevicesSharding(XLACompatibleSharding):\nreturn self.remake(self._devices, new_ids)\n@classmethod\n- def remake(cls, devices: List[xc.Device], ids: np.ndarray) -> DevicesSharding:\n+ def remake(cls, devices: List[xc.Device], ids: np.ndarray\n+ ) -> ReshapeableDevicesSharding:\nself = cls.__new__(cls)\nself._devices = devices\nself._ids = ids\n@@ -406,7 +411,7 @@ class DevicesSharding(XLACompatibleSharding):\nreturn id(self._devices)\ndef __eq__(self, other) -> bool:\n- return (isinstance(other, DevicesSharding) and\n+ return (isinstance(other, ReshapeableDevicesSharding) and\nid(self._devices) == id(other._devices) and\nbool(np.all(self._ids == other._ids)))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/sharding.py",
"new_path": "jax/sharding.py",
"diff": "@@ -19,5 +19,5 @@ from jax._src.sharding import (\nSingleDeviceSharding as SingleDeviceSharding,\nPmapSharding as PmapSharding,\nOpShardingSharding as OpShardingSharding,\n- DevicesSharding as DevicesSharding,\n+ ReshapeableDevicesSharding as ReshapeableDevicesSharding,\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/array_test.py",
"new_path": "tests/array_test.py",
"diff": "@@ -730,7 +730,7 @@ class ShardingTest(jtu.JaxTestCase):\nmesh = jtu.create_global_mesh((4, 2), ('x', 'y'))\nmps = sharding.MeshPspecSharding(mesh, pspec)\n- devices_sharding = sharding.DevicesSharding(jax.devices())\n+ devices_sharding = sharding.ReshapeableDevicesSharding(jax.devices())\ndevices_sharding = devices_sharding.reshape(shape).replicate(axes)\nif transpose:\ndevices_sharding = devices_sharding.T\n@@ -742,6 +742,21 @@ class ShardingTest(jtu.JaxTestCase):\ndevices_sharding.shard_shape(value_shape))\nself.assertTrue(pxla.are_op_shardings_equal(op1, op2))\n+ def test_devices_sharding_respects_init_mesh_shape(self):\n+ value_shape = (8, 4)\n+\n+ mesh = jtu.create_global_mesh((4, 2), ('x', 'y'))\n+ mps = sharding.MeshPspecSharding(mesh, P('x', 'y'))\n+\n+ devices_sharding = sharding.ReshapeableDevicesSharding(mesh.devices)\n+\n+ op1 = mps._to_xla_op_sharding(len(value_shape))\n+ op2 = devices_sharding._to_xla_op_sharding(len(value_shape))\n+\n+ self.assertEqual(mps.shard_shape(value_shape),\n+ devices_sharding.shard_shape(value_shape))\n+ self.assertTrue(pxla.are_op_shardings_equal(op1, op2))\n+\ndef test_pmap_sharding_repr(self):\nif jax.device_count() < 2:\nself.skipTest('Test needs >= 2 devices.')\n"
}
] | Python | Apache License 2.0 | google/jax | tweaks to DevicesSharding
1. rename DevicesSharding -> ReshapeableDevicesSharding
2. fix repr to print device order faithfully
3. respect shape of np.ndarray argument to __init__ |
260,681 | 25.10.2022 14:46:21 | 25,200 | 5a8f2dd8855add7fdea831f0e72e120bf0f74a8a | Add additional pjit tests using a trivial computation. | [
{
"change_type": "MODIFY",
"old_path": "tests/pjit_test.py",
"new_path": "tests/pjit_test.py",
"diff": "@@ -2502,6 +2502,36 @@ class ArrayPjitTest(jtu.JaxTestCase):\nout = pjit(lambda x: x)(arr)\nself.assertArraysEqual(out, inp_data)\n+ @jax_array(True)\n+ def test_trivial_computation_with_sharded_const(self):\n+ mesh = jtu.create_global_mesh((2, 1), ('x', 'y'))\n+ const = jax.device_put(np.arange(16).reshape(8, 2),\n+ MeshPspecSharding(mesh, P('x', 'y')))\n+ with mesh:\n+ out = pjit(lambda: const)()\n+ self.assertIsInstance(out, array.ArrayImpl)\n+ self.assertArraysEqual(out, np.arange(16).reshape(8, 2))\n+\n+ @jax_array(True)\n+ def test_trivial_computation_with_sharded_const_using_transposed_mesh(self):\n+ mesh = jtu.create_global_mesh((2, 1), ('x', 'y'))\n+ const = jax.device_put(np.arange(16).reshape(8, 2),\n+ MeshPspecSharding(mesh, P('x', 'y')))\n+ mesh2 = jtu.create_global_mesh((1, 2), ('x', 'y'))\n+ with mesh2:\n+ out = pjit(lambda: const)()\n+ self.assertIsInstance(out, array.ArrayImpl)\n+ self.assertArraysEqual(out, np.arange(16).reshape(8, 2))\n+\n+ @jax_array(True)\n+ def test_trivial_computation_with_replicated_literal(self):\n+ mesh = jtu.create_global_mesh((2, 1), ('x', 'y'))\n+ with mesh:\n+ out = pjit(lambda: 1)()\n+ self.assertIsInstance(out, array.ArrayImpl)\n+ self.assertEqual(out, 1)\n+\n+\n@jax_array(True)\ndef test_multi_device_pjit_mul(self):\nshape = (8, 2)\n"
}
] | Python | Apache License 2.0 | google/jax | Add additional pjit tests using a trivial computation.
PiperOrigin-RevId: 483781291 |
260,335 | 25.10.2022 15:10:55 | 25,200 | 612bb175083dbc476c114331fb58be76a6ae84c0 | hopefully fix pjit bug | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/pjit.py",
"new_path": "jax/experimental/pjit.py",
"diff": "@@ -1245,10 +1245,18 @@ def _pjit_partial_eval(trace, *in_tracers,\n_allow_propagation_to_outputs=True,\n_allow_compile_replicated=False)\nda = compiled._device_assignment\n- _, out_op_shardings = _get_op_sharding_from_executable(compiled.xla_executable)\n+ _, out_op_sharding_shardings = pxla._get_op_sharding_shardings_from_executable(\n+ compiled.xla_executable, da, len(known_jaxpr.in_avals),\n+ len(known_jaxpr.out_avals))\n+ assert len(out_op_sharding_shardings) == len(known_jaxpr.out_avals), (\n+ len(out_op_shardings), len(known_jaxpr.out_avals))\n+ out_op_shardings = [o._to_xla_op_sharding(a.ndim) for o, a in\n+ safe_zip(out_op_sharding_shardings, known_jaxpr.out_avals)]\nresidual_op_shardings = tuple(out_op_shardings[-num_residuals:])\nelse:\nresidual_op_shardings = ()\n+ assert len(residual_shardings) == len(residual_op_shardings), (\n+ len(residual_shardings), len(residual_op_shardings))\nresidual_shardings = tuple(OpShardingSharding(da, op) for op in residual_op_shardings)\nknown_params['out_shardings'] = (\nkeep_where(out_shardings, known_outs) + residual_shardings)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -3214,6 +3214,7 @@ def _get_op_sharding_shardings_from_executable(\n# TODO(b/245667823): Remove this when XLA fixes this.\nif len(out_shardings_xla) == 1 and len(out_shardings_xla) < num_out_avals:\nout_shardings_xla = out_shardings_xla * num_out_avals\n+ assert len(out_shardings_xla) == len(num_out_avals)\nreturn in_shardings_xla, out_shardings_xla\n"
}
] | Python | Apache License 2.0 | google/jax | hopefully fix pjit bug
Co-authored-by: Yash Katariya <yashkatariya@google.com> |
260,287 | 26.10.2022 15:44:06 | 0 | 6e43ce363ee49bd485ace57acb1a149c78ffa436 | Remove a TODO from the xmap tutorial
xeinsum is already powerful enough to support the example. | [
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/xmap_tutorial.ipynb",
"new_path": "docs/notebooks/xmap_tutorial.ipynb",
"diff": "},\n\"outputs\": [],\n\"source\": [\n- \"if False: # TODO: Implement all necessary cases in xeinsum\\n\",\n\"def named_batch_matrix_single_matrix(\\n\",\n\" x: f32[(5,), {'b': 20, 'k': 7}],\\n\",\n\" y: f32[(), {'k': 7, 'm': 11}]) \\\\\\n\",\n\"z = jnp.einsum('bnk,km->bnm', x, y)\\n\",\n\"zx = xmap(named_batch_matrix_single_matrix,\\n\",\n\" in_axes=[{0: 'b', 2: 'k'}, ['k', 'm', ...]],\\n\",\n- \" out_axes=['b', 'n', 'm', ...])(x, y)\"\n+ \" out_axes={0: 'b', 2: 'm'})(x, y)\\n\",\n+ \"np.testing.assert_allclose(z, zx)\"\n]\n},\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/xmap_tutorial.md",
"new_path": "docs/notebooks/xmap_tutorial.md",
"diff": "@@ -431,7 +431,6 @@ It is acceptable to omit a named dimension from _all arguments and the result_ i\n```{code-cell} ipython3\n:id: rQgkof6lyJps\n-if False: # TODO: Implement all necessary cases in xeinsum\ndef named_batch_matrix_single_matrix(\nx: f32[(5,), {'b': 20, 'k': 7}],\ny: f32[(), {'k': 7, 'm': 11}]) \\\n@@ -443,7 +442,8 @@ if False: # TODO: Implement all necessary cases in xeinsum\nz = jnp.einsum('bnk,km->bnm', x, y)\nzx = xmap(named_batch_matrix_single_matrix,\nin_axes=[{0: 'b', 2: 'k'}, ['k', 'm', ...]],\n- out_axes=['b', 'n', 'm', ...])(x, y)\n+ out_axes={0: 'b', 2: 'm'})(x, y)\n+np.testing.assert_allclose(z, zx)\n```\n+++ {\"id\": \"JuFg25Yro4kZ\"}\n"
}
] | Python | Apache License 2.0 | google/jax | Remove a TODO from the xmap tutorial
xeinsum is already powerful enough to support the example. |
260,631 | 27.10.2022 09:20:17 | 25,200 | 978dcde8d6b17026198ab6f023aa332a0b354203 | MHLO Pretty Print - Enhance type printing for CopyOp, ClampOp, CstrReshapeOp, ComputeReshapeShapeOp, SelectOp.
Based on: | [
{
"change_type": "MODIFY",
"old_path": "tests/filecheck/array.filecheck.py",
"new_path": "tests/filecheck/array.filecheck.py",
"diff": "@@ -77,9 +77,7 @@ def main(_):\n# CHECK-LABEL: TEST: select bool[2,7] int32[2,7] int32[2,7]\n# CHECK: mhlo.select\n- # CHECK-SAME: tensor<2x7xi1>\n- # CHECK-SAME: tensor<2x7xi32>\n- # CHECK-SAME: tensor<2x7xi32>\n+ # CHECK-SAME: tensor<2x7xi1>, tensor<2x7xi32>\nprint_ir(np.empty([2, 7], np.bool_), np.empty([2, 7], np.int32),\nnp.empty([2, 7], np.int32))(lax.select)\n"
}
] | Python | Apache License 2.0 | google/jax | MHLO Pretty Print - Enhance type printing for CopyOp, ClampOp, CstrReshapeOp, ComputeReshapeShapeOp, SelectOp.
Based on:
https://github.com/openxla/stablehlo/pull/37
PiperOrigin-RevId: 484271777 |
260,294 | 20.10.2022 15:13:24 | 0 | e84a7e25b2010cb39c931ea9ecd05b83f03a9087 | [ROCm]: Enable/update multiprocess gpu tests for ROCm | [
{
"change_type": "MODIFY",
"old_path": "tests/multiprocess_gpu_test.py",
"new_path": "tests/multiprocess_gpu_test.py",
"diff": "@@ -104,6 +104,10 @@ class MultiProcessGpuTest(jtu.JaxTestCase):\nenv[\"JAX_PORT\"] = str(port)\nenv[\"NUM_TASKS\"] = str(num_tasks)\nenv[\"TASK\"] = str(task)\n+ if jtu.is_device_rocm():\n+ env[\"HIP_VISIBLE_DEVICES\"] = \",\".join(\n+ str((task * num_gpus_per_task) + i) for i in range(num_gpus_per_task))\n+ else:\nenv[\"CUDA_VISIBLE_DEVICES\"] = \",\".join(\nstr((task * num_gpus_per_task) + i) for i in range(num_gpus_per_task))\nargs = [\n@@ -129,9 +133,8 @@ class MultiProcessGpuTest(jtu.JaxTestCase):\nfor proc in subprocesses:\nproc.kill()\n- @jtu.skip_on_devices(\"rocm\")\n- def test_distributed_jax_cuda_visible_devices(self):\n- \"\"\"Test jax_cuda_visible_devices works in distributed settings.\"\"\"\n+ def test_distributed_jax_visible_devices(self):\n+ \"\"\"Test jax_visible_devices works in distributed settings.\"\"\"\nif jtu.device_under_test() != 'gpu':\nraise unittest.SkipTest('Tests only for GPU.')\n@@ -149,6 +152,18 @@ class MultiProcessGpuTest(jtu.JaxTestCase):\nenv[\"TASK\"] = str(task)\nvisible_devices = \",\".join(\nstr((task * num_gpus_per_task) + i) for i in range(num_gpus_per_task))\n+\n+ if jtu.is_device_rocm():\n+ program = (\n+ 'import jax, os; '\n+ f'jax.config.update(\"jax_rocm_visible_devices\", \"{visible_devices}\"); '\n+ 'jax.distributed.initialize('\n+ 'f\\'localhost:{os.environ[\"JAX_PORT\"]}\\', '\n+ 'int(os.environ[\"NUM_TASKS\"]), int(os.environ[\"TASK\"])); '\n+ 's = jax.pmap(lambda x: jax.lax.psum(x, \"i\"), axis_name=\"i\")(jax.numpy.ones(jax.local_device_count())); '\n+ 'print(f\\'{jax.local_device_count()},{jax.device_count()},{s}\\', end=\"\"); '\n+ )\n+ else:\nprogram = (\n'import jax, os; '\nf'jax.config.update(\"jax_cuda_visible_devices\", \"{visible_devices}\"); '\n"
}
] | Python | Apache License 2.0 | google/jax | [ROCm]: Enable/update multiprocess gpu tests for ROCm |
260,287 | 26.10.2022 15:30:11 | 0 | 0fce5be556a5344f7caec69d1d2df86f522d0989 | Improve undefined axis checks
Previously we checked for out axes being a superset of the defined axes,
but that's just not the right relation. In particular, out_axes of {'a'}
are not a superset of defined axes {'b'}, but axis 'a' is undefined. The
correct check is to verify emptiness of their difference. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/maps.py",
"new_path": "jax/experimental/maps.py",
"diff": "@@ -490,6 +490,16 @@ def xmap(fun: Callable,\nreturn name\nreturn r\n+ axes_with_resources = set(axis_resources.keys())\n+ if axes_with_resources - defined_names:\n+ raise ValueError(f\"All axes that were assigned resources have to appear in \"\n+ f\"in_axes or axis_sizes, but the following are missing: \"\n+ f\"{axes_with_resources - defined_names}\")\n+ if out_axes_names - defined_names:\n+ raise ValueError(f\"All axis names appearing in out_axes must also appear in \"\n+ f\"in_axes or axis_sizes, but the following are missing: \"\n+ f\"{out_axes_names - defined_names}\")\n+\nnormalized_axis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]] = {}\nfor axis in defined_names:\nresources = axis_resources.get(axis, ())\n@@ -499,16 +509,6 @@ def xmap(fun: Callable,\nfrozen_axis_resources = FrozenDict(normalized_axis_resources)\nnecessary_resources = set(it.chain(*frozen_axis_resources.values()))\n- axes_with_resources = set(frozen_axis_resources.keys())\n- if axes_with_resources > defined_names:\n- raise ValueError(f\"All axes that were assigned resources have to appear in \"\n- f\"in_axes or axis_sizes, but the following are missing: \"\n- f\"{axes_with_resources - defined_names}\")\n- if out_axes_names > defined_names:\n- raise ValueError(f\"All axis names appearing in out_axes must also appear in \"\n- f\"in_axes or axis_sizes, but the following are missing: \"\n- f\"{out_axes_names - defined_names}\")\n-\nfor axis, resources in frozen_axis_resources.items():\nif len(set(resources)) != len(resources): # type: ignore\nraise ValueError(f\"Resource assignment of a single axis must be a tuple of \"\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/xmap_test.py",
"new_path": "tests/xmap_test.py",
"diff": "@@ -1779,6 +1779,22 @@ class XMapErrorTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(TypeError, error):\nfm(x, y)\n+ def testUndefinedOutAxis(self):\n+ error = (r\"All axis names appearing in out_axes must also appear in \"\n+ r\"in_axes or axis_sizes, but the following are missing: {'c'}\")\n+ with self.assertRaisesRegex(ValueError, error):\n+ xmap(lambda x, y: x + y,\n+ in_axes=(['a', ...], ['b', ...]), out_axes=['c', ...])\n+\n+ @jtu.with_mesh([('x', 2)])\n+ def testUndefinedAxisInAxisResources(self):\n+ error = (r\"All axes that were assigned resources have to appear in in_axes \"\n+ r\"or axis_sizes, but the following are missing: {'b'}\")\n+ with self.assertRaisesRegex(ValueError, error):\n+ xmap(lambda x, y: x + y,\n+ in_axes=(['a', ...], ['a', ...]), out_axes=['a', ...],\n+ axis_resources={'b': 'x'})\n+\n@jtu.with_mesh([('x', 2)])\ndef testResourceConflictArgs(self):\nfm = xmap(lambda x: lax.psum(x, ('a', 'b')),\n"
}
] | Python | Apache License 2.0 | google/jax | Improve undefined axis checks
Previously we checked for out axes being a superset of the defined axes,
but that's just not the right relation. In particular, out_axes of {'a'}
are not a superset of defined axes {'b'}, but axis 'a' is undefined. The
correct check is to verify emptiness of their difference. |
260,510 | 27.10.2022 12:47:30 | 25,200 | 3e38675ac4159092396dafdd64eae5a7b636fea0 | Update debugging_primitives_test to not use nontrivial floating point text comparisons | [
{
"change_type": "MODIFY",
"old_path": "tests/debugging_primitives_test.py",
"new_path": "tests/debugging_primitives_test.py",
"diff": "@@ -261,7 +261,7 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\nreturn x, t\ndef f(x):\n- x = jnp.sin(x)\n+ x = jnp.square(x)\nx = print_tangent(x)\nreturn x\n@@ -269,7 +269,7 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\nx = jnp.array(1., jnp.float32)\njax.jvp(f, (x,), (x,))\njax.effects_barrier()\n- expected = jnp.cos(jnp.array(1., jnp.float32))\n+ expected = jnp.array(2., jnp.float32)\nself.assertEqual(output(), f\"x_tangent: {expected}\\n\")\n@unittest.skip(\"doesn't work yet!\") # TODO(mattjj,sharadmv)\n@@ -318,12 +318,12 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\ndef f(x):\ndebug_print(\"x: {}\", x)\nx = print_grad(x)\n- return jnp.sin(x)\n+ return jnp.square(x)\nwith jtu.capture_stdout() as output:\njax.grad(f)(jnp.array(1., jnp.float32))\njax.effects_barrier()\n- expected = jnp.cos(jnp.array(1., jnp.float32))\n+ expected = jnp.array(2., jnp.float32)\nself.assertEqual(output(), f\"x: 1.0\\nx_grad: {expected}\\n\")\ndef test_debug_print_transpose_rule(self):\n"
}
] | Python | Apache License 2.0 | google/jax | Update debugging_primitives_test to not use nontrivial floating point text comparisons
PiperOrigin-RevId: 484325096 |
260,681 | 28.10.2022 10:34:28 | 25,200 | 54967e9aba30fbaf39eb16b72ded488a957c11c3 | Improve effect support on internal backends. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1631,7 +1631,8 @@ class PmapExecutable(stages.XlaExecutable):\nif hasattr(pci.backend, \"compile_replicated\"):\nreturn _compile_replicated_pmap_executable_from_hlo(\nxla_computation, pci, input_indices, in_shardings, handle_outs,\n- compile_options, host_callbacks)\n+ compile_options, host_callbacks, bool(unordered_effects),\n+ ordered_effects)\nwith dispatch.log_elapsed_time(\nf\"Finished XLA compilation of {pci.name} in {{elapsed_time}} sec\"):\n@@ -3316,8 +3317,8 @@ class MeshExecutable(stages.XlaExecutable):\nreturn _compile_replicated_mesh_executable_from_hlo(\nname, computation, global_in_avals, global_out_avals, in_shardings,\nout_shardings, in_is_global, auto_spmd_lowering, compile_options,\n- host_callbacks, kept_var_idx, backend, device_assignment, committed,\n- pmap_nreps)\n+ host_callbacks, bool(unordered_effects), ordered_effects,\n+ kept_var_idx, backend, device_assignment, committed, pmap_nreps)\nelse:\nwith dispatch.log_elapsed_time(f\"Finished XLA compilation of {name} \"\n\"in {elapsed_time} sec\"):\n@@ -3460,17 +3461,18 @@ def _execute_trivial(jaxpr, consts, in_handler, out_handler, kept_var_idx, *args\nreturn out_handler(in_handler(outs))\n-def _compile_replicated_pmap_executable_from_hlo(xla_computation, pci,\n- input_indices, in_shardings,\n- handle_outs, compile_options,\n- host_callbacks):\n+def _compile_replicated_pmap_executable_from_hlo(\n+ xla_computation, pci, input_indices, in_shardings, handle_outs,\n+ compile_options, host_callbacks, has_unordered_effects, ordered_effects):\n# Use the standard out_handler.\nexecute_fun = pci.backend.compile_replicated(\nis_trivial=False, name=pci.name, computation=xla_computation,\ncompile_options=compile_options, host_callbacks=host_callbacks,\n- in_avals=pci.avals, in_indices=input_indices,\n- in_shardings=in_shardings, kept_var_idx=set(range(len(pci.avals))),\n- mode=InputsHandlerMode.pmap, out_handler=handle_outs)\n+ has_unordered_effects=has_unordered_effects,\n+ ordered_effects=ordered_effects, in_avals=pci.avals,\n+ in_indices=input_indices, in_shardings=in_shardings,\n+ kept_var_idx=set(range(len(pci.avals))), mode=InputsHandlerMode.pmap,\n+ out_handler=handle_outs)\n# TODO(frostig): need `compile_replicated` to give us the XLA executable\nreturn PmapExecutable(None, execute_fun, None, pci.avals)\n@@ -3479,8 +3481,8 @@ def _compile_replicated_pmap_executable_from_hlo(xla_computation, pci,\ndef _compile_replicated_mesh_executable_from_hlo(\nname, computation, global_in_avals, global_out_avals, in_shardings,\nout_shardings, in_is_global, auto_spmd_lowering, compile_options,\n- host_callbacks, kept_var_idx, backend, device_assignment, committed,\n- pmap_nreps):\n+ host_callbacks, has_unordered_effects, ordered_effects, kept_var_idx,\n+ backend, device_assignment, committed, pmap_nreps):\nassert not auto_spmd_lowering\nin_shardings, input_indices, input_avals = _get_input_metadata(\nglobal_in_avals, in_shardings, in_is_global) # type: ignore\n@@ -3493,10 +3495,12 @@ def _compile_replicated_mesh_executable_from_hlo(\nunsafe_call = backend.compile_replicated(\nis_trivial=False, name=name, computation=computation,\ncompile_options=compile_options, host_callbacks=host_callbacks,\n- in_avals=input_avals, in_indices=input_indices,\n- in_shardings=in_shardings, kept_var_idx=kept_var_idx,\n- mode=InputsHandlerMode.pjit_or_xmap, out_avals=global_out_avals,\n- out_shardings=out_shardings, committed=committed)\n+ has_unordered_effects=has_unordered_effects,\n+ ordered_effects=ordered_effects, in_avals=input_avals,\n+ in_indices=input_indices, in_shardings=in_shardings,\n+ kept_var_idx=kept_var_idx, mode=InputsHandlerMode.pjit_or_xmap,\n+ out_avals=global_out_avals, out_shardings=out_shardings,\n+ committed=committed)\nxla_executable = None\nreturn MeshExecutable(xla_executable, unsafe_call, input_avals,\nin_shardings, out_shardings, auto_spmd_lowering,\n"
}
] | Python | Apache License 2.0 | google/jax | Improve effect support on internal backends.
PiperOrigin-RevId: 484566725 |
260,294 | 16.08.2022 18:44:36 | 0 | 4370b3385f53fbfe1fa1a5ac80087b51426032c2 | [ROCm] Add dlpack backend support
Depends on the Tensorflow commit included in this
PR | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/dlpack.py",
"new_path": "jax/_src/dlpack.py",
"diff": "@@ -64,6 +64,14 @@ def from_dlpack(dlpack):\ngpu_backend = xla_bridge.get_backend(\"cuda\")\nexcept RuntimeError:\ngpu_backend = None\n+\n+ # Try ROCm if CUDA backend not found\n+ if gpu_backend is None:\n+ try:\n+ gpu_backend = xla_bridge.get_backend(\"rocm\")\n+ except RuntimeError:\n+ gpu_backend = None\n+\nbuf = xla_client._xla.dlpack_managed_tensor_to_buffer(\ndlpack, cpu_backend, gpu_backend)\n"
}
] | Python | Apache License 2.0 | google/jax | [ROCm] Add dlpack backend support
Depends on the Tensorflow commit included in this
PR https://github.com/tensorflow/tensorflow/pull/57640 |
260,294 | 16.08.2022 18:45:22 | 0 | 96eaf1d7d168a30bec5f33797c7d0de692b90425 | [ROCM]: Enable more array interoperability tests | [
{
"change_type": "MODIFY",
"old_path": "tests/array_interoperability_test.py",
"new_path": "tests/array_interoperability_test.py",
"diff": "@@ -73,7 +73,6 @@ class DLPackTest(jtu.JaxTestCase):\ntake_ownership=[False, True],\ngpu=[False, True],\n)\n- @jtu.skip_on_devices(\"rocm\") # TODO(sharadmv,phawkins): see GH issue #10973\ndef testJaxRoundTrip(self, shape, dtype, take_ownership, gpu):\nrng = jtu.rand_default(self.rng())\nnp = rng(shape, dtype)\n@@ -96,7 +95,6 @@ class DLPackTest(jtu.JaxTestCase):\ndtype=dlpack_dtypes,\n)\n@unittest.skipIf(not tf, \"Test requires TensorFlow\")\n- @jtu.skip_on_devices(\"rocm\") # TODO(sharadmv,phawkins): see GH issue #10973\ndef testTensorFlowToJax(self, shape, dtype):\nif not config.x64_enabled and dtype in [jnp.int64, jnp.uint64, jnp.float64]:\nraise self.skipTest(\"x64 types are disabled by jax_enable_x64\")\n@@ -203,7 +201,6 @@ class DLPackTest(jtu.JaxTestCase):\ndtype=torch_dtypes,\n)\n@unittest.skipIf(numpy_version < (1, 22, 0), \"Requires numpy 1.22 or newer\")\n- @jtu.skip_on_devices(\"rocm\") # TODO(sharadmv,phawkins): see GH issue #10973\ndef testNumpyToJax(self, shape, dtype):\nrng = jtu.rand_default(self.rng())\nx_np = rng(shape, dtype)\n@@ -215,7 +212,7 @@ class DLPackTest(jtu.JaxTestCase):\ndtype=torch_dtypes,\n)\n@unittest.skipIf(numpy_version < (1, 23, 0), \"Requires numpy 1.23 or newer\")\n- @jtu.skip_on_devices(\"gpu\")\n+ @jtu.skip_on_devices(\"gpu\") #NumPy only accepts cpu DLPacks\ndef testJaxToNumpy(self, shape, dtype):\nrng = jtu.rand_default(self.rng())\nx_jax = jnp.array(rng(shape, dtype))\n"
}
] | Python | Apache License 2.0 | google/jax | [ROCM]: Enable more array interoperability tests |
260,335 | 26.10.2022 14:14:58 | 25,200 | 6ebf44a68160af0c6df3e086e822055f67fd7f45 | make leak checker errors explain why objects are alive | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -20,6 +20,7 @@ from dataclasses import dataclass\nimport functools\nfrom functools import partial, partialmethod, total_ordering\nimport gc\n+import inspect\nimport itertools as it\nimport operator\nfrom operator import attrgetter\n@@ -888,7 +889,9 @@ def maybe_find_leaked_tracers(x: Optional[Union[MainTrace, Sublevel]]\n\"\"\"\nif not getattr(threading.current_thread(), 'pydev_do_not_trace', True):\nwarnings.warn(TRACER_LEAK_DEBUGGER_WARNING)\n- # Trigger garbage collection to filter out cyclical dependency false positives\n+ # Trigger garbage collection to filter out unreachable objects that are alive\n+ # only due to cyclical dependencies. (We don't care about unreachable leaked\n+ # tracers since they can't interact with user code and cause a problem.)\ngc.collect()\ntraces = list(filter(lambda x: isinstance(x, Trace), gc.get_referrers(x)))\ntracers = list(filter(lambda x: isinstance(x, Tracer), gc.get_referrers(*traces)))\n@@ -896,9 +899,71 @@ def maybe_find_leaked_tracers(x: Optional[Union[MainTrace, Sublevel]]\ndef leaked_tracer_error(name: str, t, tracers: List[Tracer]) -> Exception:\nassert tracers\n- msgs = '\\n\\n'.join(f'{tracer}{tracer._origin_msg()}' for tracer in tracers)\n+ why = partial(_why_alive, {id(tracers)})\n+ msgs = '\\n\\n'.join(f'{tracers[i]}{tracers[i]._origin_msg()}{why(tracers[i])}'\n+ for i in range(len(tracers)))\nreturn Exception(f'Leaked {name} {t}. Leaked tracer(s):\\n\\n{msgs}\\n')\n+def _why_alive(ignore_ids: Set[int], x: Any) -> str:\n+ parents = lambda x: [r for r in gc.get_referrers(x) if id(r) not in ignore_ids]\n+ child, lines, seen = x, [], set()\n+ while (id(child) not in seen and type(child) is not types.ModuleType\n+ and parents(child)):\n+ parent = parents(child)[0] # just pick one parent\n+\n+ # For namespaces (like modules and class instances) and closures, the\n+ # references may form a simple chain: e.g. instance refers to its own\n+ # __dict__ which refers to child, or function refers to its __closure__\n+ # which refers to cells which refer to child. In these cases, we can provide\n+ # a more intuitive description by collapsing the chain into a single\n+ # parent->child jump. We do that by setting `parent` here to be a\n+ # grandparent (or great-grandparent) of `child`, and then handling that case\n+ # in _why_alive_container_info. See example:\n+ # https://github.com/google/jax/pull/13022#discussion_r1008456599\n+ # To prevent this collapsing behavior, just comment out this code block.\n+ # TODO(mattjj): after Python 3.7 is unsupported, replace with types.CellType\n+ cell_type = type((lambda x: lambda: x)(10.28).__closure__[0]) # type: ignore\n+ if (isinstance(parent, dict) and\n+ getattr(parents(parent)[0], '__dict__', None) is parents(child)[0]):\n+ parent = parents(parent)[0]\n+ elif type(parent) is cell_type:\n+ parent = parents(parents(parent)[0])[0]\n+\n+ line = f'<{type(child).__name__} {id(child)}> is referred to by '\n+ lines.append(line + _why_alive_container_info(parent, id(child)))\n+ seen.add(id(child))\n+ child = parent\n+ return '\\n' + '\\n'.join(lines) if lines else ''\n+\n+def _why_alive_container_info(container, obj_id) -> str:\n+ name = f'<{type(container).__name__} {id(container)}>'\n+ if type(container) is types.ModuleType:\n+ name = getattr(container, '__name__', name)\n+ if type(container) is types.FunctionType:\n+ name_ = getattr(container, '__name__', '<no-name>')\n+ closure = inspect.getclosurevars(container)\n+ keys = [k for k, v in dict(closure.nonlocals, **closure.globals).items()\n+ if id(v) == obj_id]\n+ if len(keys) == 1: return f'{name} ({name_}) closed-over variable {keys[0]}'\n+ elif len(keys) > 1: return (f'{name} in closed-over variables ' +\n+ ', '.join(map(repr, keys)))\n+ if hasattr(container, '__dict__'):\n+ keys = [k for k in vars(container) if id(vars(container)[k]) == obj_id]\n+ if len(keys) == 1: return f'{name}.{str(keys[0])}'\n+ elif len(keys) > 1: return f'{name} in vars ' + ', '.join(map(repr, keys))\n+ if isinstance(container, (list, tuple)):\n+ idxs = [i for i, x in enumerate(container) if id(x) == obj_id]\n+ if len(idxs) == 1: return f'{name}[{idxs[0]}]'\n+ else: return f'{name} at indices ' + ', '.join(map(str, idxs))\n+ if isinstance(container, dict):\n+ keys = [k for k in container if id(container[k]) == obj_id]\n+ if len(keys) == 1: return f'{name}[{repr(keys[0])}]'\n+ else: return f'{name} at keys ' + ', '.join(map(repr, keys))\n+ if isinstance(container, types.ModuleType):\n+ return f' named {container.__name__}'\n+ return name\n+\n+\n@contextmanager\ndef new_main(trace_type: Type[Trace],\ndynamic: bool = False,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -164,8 +164,8 @@ class BatchTracer(Tracer):\ndef _origin_msg(self):\nif self.source_info is None:\nreturn \"\"\n- return (\"\\nThis Tracer was created on line \"\n- f\"{source_info_util.summarize(self.source_info)}\")\n+ return (f\"\\nThis BatchTracer with object id {id(self)} was created on line:\"\n+ f\"\\n {source_info_util.summarize(self.source_info)}\")\ndef _contents(self):\nreturn [('val', self.val), ('batch_dim', self.batch_dim)]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1460,7 +1460,7 @@ class DynamicJaxprTracer(core.Tracer):\nif not self._trace.main.jaxpr_stack: # type: ignore\n# If this Tracer has been leaked the jaxpr stack may no longer be\n# available. So we can't print as much origin information.\n- return (\"\\nThis Tracer was created on line \"\n+ return (\"\\nThis DynamicJaxprTracer was created on line \"\nf\"{source_info_util.summarize(self._line_info)}\")\nelse:\ninvar_pos, progenitor_eqns = self._trace.frame.find_progenitors(self)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -3554,6 +3554,41 @@ class APITest(jtu.JaxTestCase):\nwith jax.check_tracer_leaks():\njax.jit(apply_fn)(1.0) # don't crash\n+ def test_leak_checker_reference_chain(self):\n+ class A:\n+ def __init__(self, dct):\n+ self.dct = dct\n+\n+ a = A({})\n+ x = jnp.arange(3)\n+\n+ def sketch(x):\n+ def foo():\n+ return x\n+ a.dct['hi'] = [foo]\n+ return x\n+\n+ # TODO(mattjj): full test msg below fails (harmlessly) on CI, investigate\n+ msg = (\n+ r\"This BatchTracer with object id [0-9]+ was created on line:\\n\"\n+ r\" .*\\n\"\n+ r\"<BatchTracer [0-9]+> is referred to by\"\n+ )\n+\n+ # msg = (\n+ # r\"This BatchTracer with object id [0-9]+ was created on line:\\n\"\n+ # r\" .*\\n\"\n+ # r\"<BatchTracer [0-9]+> is referred to by <function [0-9]+> \\(foo\\) \"\n+ # r\"closed-over variable x\\n\"\n+ # r\"<function [0-9]+> is referred to by <list [0-9]+>\\[0\\]\\n\"\n+ # r\"<list [0-9]+> is referred to by <dict [0-9]+>\\['hi'\\]\\n\"\n+ # r\"<dict [0-9]+> is referred to by <A [0-9]+>\\.dct\\n\"\n+ # )\n+\n+ with jax.check_tracer_leaks():\n+ with self.assertRaisesRegex(Exception, msg):\n+ jax.vmap(sketch)(x)\n+\ndef test_default_backend(self):\nfirst_local_device = api.local_devices()[0]\nself.assertEqual(first_local_device.platform, api.default_backend())\n"
}
] | Python | Apache License 2.0 | google/jax | make leak checker errors explain why objects are alive
Co-authored-by: Qiao Zhang <zhangqiaorjc@google.com>
Co-authored-by: Roy Frostig <frostig@google.com> |
260,335 | 28.10.2022 14:39:51 | 25,200 | 020353478b03dc95993cd7e6d8e36786037cc2d5 | fix ci failure by skipping tests on gpu | [
{
"change_type": "MODIFY",
"old_path": "tests/array_test.py",
"new_path": "tests/array_test.py",
"diff": "@@ -786,6 +786,7 @@ class RngShardingTest(jtu.JaxTestCase):\n# tests that the PRNGs are automatically sharded as expected\n@parameterized.named_parameters((\"3\", 3), (\"4\", 4), (\"5\", 5))\n+ @jtu.skip_on_devices(\"gpu\")\ndef test_random_bits_is_pure_map_1d(self, num_devices):\n@jax.jit\ndef f(x):\n@@ -824,6 +825,7 @@ class RngShardingTest(jtu.JaxTestCase):\n\"mesh_shape\": mesh_shape, \"pspec\": pspec}\nfor mesh_shape in [(3, 2), (4, 2), (2, 3)]\nfor pspec in [P('x', None), P(None, 'y'), P('x', 'y')])\n+ @jtu.skip_on_devices(\"gpu\")\ndef test_random_bits_is_pure_map_2d(self, mesh_shape, pspec):\n@jax.jit\ndef f(x):\n"
}
] | Python | Apache License 2.0 | google/jax | fix ci failure by skipping tests on gpu |
260,335 | 28.10.2022 14:39:00 | 25,200 | 213d2c8592e1bd2bab5bda23a2d7ea94792bb87e | integrate new (partitionable, count-space-exhaustive) counts generation | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/config.py",
"new_path": "jax/_src/config.py",
"diff": "@@ -742,11 +742,7 @@ threefry_partitionable = config.define_bool_state(\n'standard jax.random pseudo-random number generation may result '\n'in extraneous communication and/or redundant distributed '\n'computation. With this flag, the communication overheads disappear '\n- 'in some cases.\\n'\n- '\\n'\n- 'Currently, setting this flag does not change random values '\n- 'generated by a given PRNG key value. However, its behavior may '\n- 'change in the future.'))\n+ 'in some cases.'))\nenable_custom_vjp_by_custom_transpose = config.define_bool_state(\nname='jax_enable_custom_vjp_by_custom_transpose',\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/prng.py",
"new_path": "jax/_src/prng.py",
"diff": "import abc\n-from functools import partial\n+from functools import partial, reduce\nimport operator as op\nfrom typing import Any, Callable, Hashable, Iterator, NamedTuple, Sequence\n@@ -987,6 +987,7 @@ def iota_32x2_shape(shape):\niota_32x2_shape_p = core.Primitive('iota_32x2_shape')\niota_32x2_shape_p.multiple_results = True\n+iota_32x2_shape_p.def_impl(partial(xla.apply_primitive, iota_32x2_shape_p))\n@iota_32x2_shape_p.def_abstract_eval\ndef iota_32x2_shape_abstract_eval(*, shape):\n@@ -1013,14 +1014,14 @@ def iota_32x2_shape_lowering(ctx, *, shape):\nfor dimension in range(len(shape))]\nstrides = (*map(int, np.cumprod(shape[1:][::-1])[::-1]), 1)\ncounts = _sum(_mul(s, i) for i, s in zip(iotas, strides)) # type: ignore\n- counts_shifted = mlir.mhlo.ShiftRightLogicalOp(\n- counts, mlir.ir_constant(np.full(shape, 32, np.dtype('uint64')),\n- canonicalize_types=False)).result\n+ shift = mlir.ir_constant(np.array(32, np.dtype('uint64')),\n+ canonicalize_types=False)\n+ shift = mlir.mhlo.BroadcastOp(shift, mlir.dense_int_elements(shape)).result\n+ counts_shifted = mlir.mhlo.ShiftRightLogicalOp(counts, shift).result\ncounts_lo = mlir.mhlo.ConvertOp(mlir.aval_to_ir_type(aval_out), counts).result\ncounts_hi = mlir.mhlo.ConvertOp(mlir.aval_to_ir_type(aval_out),\ncounts_shifted).result\nreturn (counts_hi, counts_lo)\n-\nmlir.register_lowering(iota_32x2_shape_p, iota_32x2_shape_lowering)\n@@ -1093,39 +1094,19 @@ def _threefry_random_bits_partitionable(key: jnp.ndarray, bit_width, shape):\nif all(core.is_constant_dim(d) for d in shape) and prod(shape) > 2 ** 64:\nraise NotImplementedError('random bits array of size exceeding 2 ** 64')\n- size = prod(shape)\n- n, r = divmod(bit_width * size, 32)\n- if r > 0:\n- n += 1\n- even_size = n + (n % 2)\n-\n- if not shape:\n- counts = jnp.arange(n, dtype=jnp.uint32).reshape(shape)\n- else:\n- iotas = [lax.broadcasted_iota(jnp.dtype('uint32'), shape, i)\n- for i in range(len(shape))]\n- strides = (*map(int, np.cumprod(shape[1:][::-1])[::-1]), 1)\n- counts = sum(s * i for i, s in zip(iotas, strides)) # type: ignore\n- circ0 = counts % (even_size // 2)\n- circ1 = (circ0 + even_size // 2) % n\nk1, k2 = key\n- bits_xx, bits_yy = threefry2x32_p.bind(k1, k2, circ0, circ1)\n+ counts1, counts2 = iota_32x2_shape(shape)\n+ bits1, bits2 = threefry2x32_p.bind(k1, k2, counts1, counts2)\ndtype = UINT_DTYPES[bit_width]\nif bit_width == 64:\n- assert n == even_size\n- assert False # broken...\n- bits_x, bits_y = bits_xx[:size // 2], bits_yy[:size // 2]\n- bits_x = lax.convert_element_type(bits_x, dtype)\n- bits_y = lax.convert_element_type(bits_y, dtype)\n- bits = lax.shift_left(bits_x, dtype(32)) | bits_y\n+ bits_hi = lax.convert_element_type(bits1, dtype)\n+ bits_lo = lax.convert_element_type(bits2, dtype)\n+ return lax.shift_left(bits_hi, dtype(32)) | bits_lo\n+ elif bit_width == 32:\n+ return bits1 ^ bits2\nelse:\n- bits = jnp.where(counts < even_size // 2, bits_xx, bits_yy)\n- if bit_width != 32:\n- assert False # broken...\n- bits = bits.view(dtype)\n-\n- return bits\n+ return lax.convert_element_type(bits1 ^ bits2, dtype)\n@partial(jit, static_argnums=(1, 2), inline=True)\ndef _threefry_random_bits_original(key: jnp.ndarray, bit_width, shape):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1226,6 +1226,7 @@ tf_not_yet_impl = [\n\"shard_to_full\",\n\"pure_callback\",\n\"inspect_sharding\",\n+ \"iota_32x2_shape\",\n# Not high priority?\n\"after_all\",\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -232,6 +232,7 @@ class PrngTest(jtu.JaxTestCase):\nfinally:\nxla.apply_primitive = apply_primitive\n+ @skipIf(config.jax_threefry_partitionable, 'changed random bit values')\ndef testRngRandomBits(self):\n# Test specific outputs to ensure consistent random values between JAX versions.\n@@ -295,6 +296,7 @@ class PrngTest(jtu.JaxTestCase):\nself.assertEqual(bits64.shape, (3,))\nself.assertEqual(bits64.dtype, expected_dtype)\n+ @skipIf(config.jax_threefry_partitionable, 'changed random bit values')\ndef testRngRandomBitsViewProperty(self):\n# TODO: add 64-bit if it ever supports this property.\n# TODO: will this property hold across endian-ness?\n@@ -313,6 +315,7 @@ class PrngTest(jtu.JaxTestCase):\n@jtu.sample_product(case=_RANDOM_VALUES_CASES)\n+ @skipIf(config.jax_threefry_partitionable, 'changed random bit values')\n@jtu.skip_on_devices(\"tpu\") # TPU precision causes issues.\ndef testRandomDistributionValues(self, case):\n\"\"\"\n@@ -334,6 +337,7 @@ class PrngTest(jtu.JaxTestCase):\nactual = func(key, **case.params, shape=case.shape)\nself.assertAllClose(actual, case.expected, atol=case.atol, rtol=case.rtol)\n+ @skipIf(config.jax_threefry_partitionable, 'changed random bit values')\ndef testPRNGValues(self):\n# Test to ensure consistent random values between JAX versions\nk = random.PRNGKey(0)\n@@ -952,7 +956,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nself._CheckChiSquared(samples, scipy.stats.poisson(lam).pmf)\n# TODO(shoyer): determine error bounds for moments more rigorously (e.g.,\n# based on the central limit theorem).\n- self.assertAllClose(samples.mean(), lam, rtol=0.01, check_dtypes=False)\n+ self.assertAllClose(samples.mean(), lam, rtol=0.02, check_dtypes=False)\nself.assertAllClose(samples.var(), lam, rtol=0.03, check_dtypes=False)\ndef testPoissonBatched(self):\n"
}
] | Python | Apache License 2.0 | google/jax | integrate new (partitionable, count-space-exhaustive) counts generation |
260,447 | 01.11.2022 11:45:12 | 25,200 | d207194c3c39c519485f85d44df1f5ea61345c1f | [sparse] fix a typo in n_sparse calculation. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcoo.py",
"new_path": "jax/experimental/sparse/bcoo.py",
"diff": "@@ -350,7 +350,7 @@ def _bcoo_fromdense_jvp(primals, tangents, *, nse, n_batch, n_dense, index_dtype\ndef _bcoo_fromdense_transpose(ct, M, *, nse, n_batch, n_dense, index_dtype):\ndata, indices = ct\n- n_sparse = M.ndim = n_batch - n_dense\n+ n_sparse = M.ndim - n_batch - n_dense\nassert data.shape == M.shape[:n_batch] + (nse,) + M.shape[n_batch + n_sparse:]\nassert indices.shape == M.shape[:n_batch] + (n_sparse, nse)\nassert indices.dtype == index_dtype\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] fix a typo in n_sparse calculation.
PiperOrigin-RevId: 485376576 |
260,681 | 01.11.2022 14:32:27 | 25,200 | bb0702842b8944ddd97a7e61250905ac2b777764 | Make device_put accept a prefix tree with Sharding leaves as the second argument | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -2831,14 +2831,15 @@ def make_jaxpr(fun: Callable,\ndef device_put(\n- x, device: Optional[Union[xc.Device, jax.sharding.Sharding]] = None):\n+ x, device: Union[None, xc.Device, jax.sharding.Sharding, Any] = None):\n\"\"\"Transfers ``x`` to ``device``.\nArgs:\nx: An array, scalar, or (nested) standard Python container thereof.\n- device: The (optional) :py:class:`Device` or `Sharding` representing the\n- device(s) to which ``x`` should be transferred. If given, then the result\n- is committed to the device(s).\n+ device: The (optional) :py:class:`Device`, `Sharding`, or a (nested)\n+ `Sharding` in standard Python container (must be a tree prefix of ``x``),\n+ representing the device(s) to which ``x`` should be transferred. If\n+ given, then the result is committed to the device(s).\nReturns:\nA copy of ``x`` that resides on ``device``.\n@@ -2854,8 +2855,17 @@ def device_put(\nblocking the calling Python thread until any transfers are completed.\n\"\"\"\nwith config_explicit_device_put_scope():\n+ if device is None or isinstance(device, (xc.Device, jax.sharding.Sharding)):\nreturn tree_map(lambda y: dispatch.device_put_p.bind(y, device=device), x)\n+ x_flat, treedef = tree_flatten(x)\n+ device_flat = flatten_axes(\"device_put device\", treedef, device)\n+ out_flat = [\n+ dispatch.device_put_p.bind(y, device=d)\n+ for y, d in zip(x_flat, device_flat)\n+ ]\n+ return tree_unflatten(treedef, out_flat)\n+\ndef device_put_sharded(shards: Sequence[Any], devices: Sequence[xc.Device]): # noqa: F811\n\"\"\"Transfer array shards to specified devices and form ShardedDeviceArray(s).\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1516,6 +1516,95 @@ class APITest(jtu.JaxTestCase):\nself.assertArraysAllClose(u, y)\nself.assertEqual(u.device(), jax.devices()[0])\n+ @jax_config.jax_array(True)\n+ def test_device_put_sharding_tree(self):\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices\")\n+\n+ mesh = maps.Mesh(np.array(jax.devices()[:2]).reshape((2, 1)), (\"x\", \"y\"))\n+ s1 = sharding.MeshPspecSharding(mesh, P(\"x\"))\n+ s2 = sharding.MeshPspecSharding(mesh, P(\"y\"))\n+ s3 = sharding.MeshPspecSharding(mesh, P(\"x\", \"y\"))\n+\n+ x = jnp.arange(2)\n+ y = jnp.arange(2) + 10\n+ z = (jnp.arange(2) + 100).reshape((2, 1))\n+\n+ out = jax.device_put((x, (y, z)), device=(s1, (s2, s3)))\n+ self.assertEqual(out[0].sharding, s1)\n+ self.assertEqual(out[1][0].sharding, s2)\n+ self.assertEqual(out[1][1].sharding, s3)\n+\n+ self.assertArraysAllClose(out[0], x)\n+ self.assertArraysAllClose(out[1][0], y)\n+ self.assertArraysAllClose(out[1][1], z)\n+\n+ @jax_config.jax_array(True)\n+ def test_device_put_sharding_tree_prefix(self):\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices\")\n+\n+ mesh = maps.Mesh(np.array(jax.devices()[:2]).reshape((2, 1)), (\"x\", \"y\"))\n+ s1 = sharding.MeshPspecSharding(mesh, P(\"x\"))\n+ s2 = sharding.MeshPspecSharding(mesh, P(\"y\"))\n+\n+ x = jnp.arange(2)\n+ y = jnp.arange(2) + 10\n+ z = jnp.arange(2) + 100\n+\n+ out = jax.device_put((x, (y, z)), device=(s1, s2))\n+ self.assertEqual(out[0].sharding, s1)\n+ self.assertEqual(out[1][0].sharding, s2)\n+ self.assertEqual(out[1][1].sharding, s2)\n+\n+ self.assertArraysAllClose(out[0], x)\n+ self.assertArraysAllClose(out[1][0], y)\n+ self.assertArraysAllClose(out[1][1], z)\n+\n+ @jax_config.jax_array(True)\n+ def test_device_put_sharding_mismatched_tree_same_leaf_count(self):\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices\")\n+\n+ mesh = maps.Mesh(np.array(jax.devices()[:2]).reshape((2, 1)), (\"x\", \"y\"))\n+ s1 = sharding.MeshPspecSharding(mesh, P(\"x\"))\n+ s2 = sharding.MeshPspecSharding(mesh, P(\"y\"))\n+\n+ x = jnp.arange(2)\n+ y = jnp.arange(2) + 10\n+ z = jnp.arange(2) + 100\n+\n+ with self.assertRaisesRegex(\n+ ValueError,\n+ \"device_put device specification must be a tree prefix of the \"\n+ r\"corresponding value, got specification \\(\\(MeshPspecSharding\\(.*\\), \"\n+ r\"MeshPspecSharding\\(.*\\)\\), MeshPspecSharding\\(.*\\)\\) for value tree \"\n+ r\"PyTreeDef\\(\\(\\*, \\(\\*, \\*\\)\\)\\).\"\n+ ):\n+ jax.device_put((x, (y, z)), device=((s1, s2), s2))\n+\n+ @jax_config.jax_array(True)\n+ def test_device_put_sharding_mismatched_tree_different_leaf_count(self):\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices\")\n+\n+ mesh = maps.Mesh(np.array(jax.devices()[:2]).reshape((2, 1)), (\"x\", \"y\"))\n+ s1 = sharding.MeshPspecSharding(mesh, P(\"x\"))\n+ s2 = sharding.MeshPspecSharding(mesh, P(\"y\"))\n+\n+ x = jnp.arange(2)\n+ y = jnp.arange(2) + 10\n+ z = jnp.arange(2) + 100\n+\n+ with self.assertRaisesRegex(\n+ ValueError,\n+ \"device_put device specification must be a tree prefix of the \"\n+ r\"corresponding value, got specification \\(MeshPspecSharding\\(.*\\), \"\n+ r\"MeshPspecSharding\\(.*\\)\\) for value tree PyTreeDef\\(\\(\\*, \\*, \\*\\)\\).\"\n+ ):\n+ jax.device_put((x, y, z), device=(s1, s2))\n+\n+\ndef test_device_get_scalar(self):\nx = np.arange(12.).reshape((3, 4)).astype(\"float32\")\nx = api.device_put(x)\n"
}
] | Python | Apache License 2.0 | google/jax | Make device_put accept a prefix tree with Sharding leaves as the second argument
PiperOrigin-RevId: 485419880 |
260,510 | 01.11.2022 13:00:41 | 25,200 | 3bbd5f3028629c56c598d514091f7bc16c12d145 | Add colors to sharding visualization | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "@@ -18,7 +18,7 @@ import string\nimport sys\nimport weakref\n-from typing import Any, Dict, Callable, Sequence, Set, Tuple, Union\n+from typing import Any, Dict, Callable, Optional, Sequence, Set, Tuple, Union\nfrom jax import core\nfrom jax import tree_util\n@@ -42,6 +42,7 @@ from jax._src.lib.mlir import ir\nfrom jax._src.lib.mlir.dialects import mhlo\nimport jax.numpy as jnp\n+import numpy as np\n# pytype: disable=import-error\ntry:\nimport rich\n@@ -49,6 +50,7 @@ try:\nimport rich.box\nimport rich.console\nimport rich.padding\n+ import rich.style\nimport rich.table\nRICH_ENABLED = True\nexcept:\n@@ -398,18 +400,47 @@ def _raise_to_slice(slc: Union[slice, int]):\nreturn slice(slc, slc + 1)\nreturn slc\n+Color = Union[Tuple[float, float, float], str]\n+ColorMap = Callable[[float], Tuple[float, float, float, float]]\n+\n+def _canonicalize_color(color: Color) -> str:\n+ if isinstance(color, str):\n+ return color\n+ r, g, b = (int(a * 255) for a in color)\n+ return f\"#{r:02X}{g:02X}{b:02X}\"\n+\n+def _get_text_color(color: str) -> str:\n+ r, g, b = map(lambda x: int(x, 16), (color[1:3], color[3:5], color[5:7]))\n+ if (r * 0.299 + g * 0.587 + b * 0.114) > 186:\n+ return \"#000000\"\n+ return \"#ffffff\"\n+\n+def make_color_iter(color_map, num_rows, num_cols):\n+ num_colors = num_rows * num_cols\n+ color_values = np.linspace(0, 1, num_colors)\n+ idx = 0\n+ for _ in range(num_colors):\n+ yield color_map(color_values[idx])\n+ idx = (idx + num_colors // 2 + bool(num_colors % 2 == 0)) % num_colors\n+\ndef visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\n- use_color: bool = False, scale: float = 1.,\n- min_width: int = 9, max_width: int = 80):\n+ use_color: bool = True, scale: float = 1.,\n+ min_width: int = 9, max_width: int = 80,\n+ color_map: Optional[ColorMap] = None):\n\"\"\"Visualizes a ``Sharding`` using ``rich``.\"\"\"\nif not RICH_ENABLED:\nraise ValueError(\"`visualize_sharding` requires `rich` to be installed.\")\n- if use_color:\n- # TODO(sharadmv): Implement color in the visualizer\n- raise NotImplementedError\nif len(shape) > 2 or len(shape) < 1:\nraise ValueError(\n\"`visualize_sharding` only works for shapes with 1 and 2 dimensions.\")\n+ console = rich.console.Console(width=max_width)\n+ use_color = use_color and console.color_system is not None\n+ if use_color and not color_map:\n+ try:\n+ import matplotlib as mpl # pytype: disable=import-error\n+ color_map = mpl.colormaps[\"tab20b\"]\n+ except ModuleNotFoundError:\n+ use_color = False\nbase_height = int(10 * scale)\naspect_ratio = (shape[1] if len(shape) == 2 else 1) / shape[0]\n@@ -421,9 +452,10 @@ def visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\ndevice_indices_map = sharding.devices_indices_map(tuple(shape))\nslices: Dict[Tuple[int, ...], Set[int]] = {}\n- heights: Dict[Tuple[int, ...], int] = {}\n- widths: Dict[Tuple[int, ...], int] = {}\n- for dev, slcs in device_indices_map.items():\n+ heights: Dict[Tuple[int, ...], Optional[float]] = {}\n+ widths: Dict[Tuple[int, ...], float] = {}\n+\n+ for i, (dev, slcs) in enumerate(device_indices_map.items()):\nassert slcs is not None\nslcs = tuple(map(_raise_to_slice, slcs))\nchunk_idxs = tuple(map(_slice_to_chunk_idx, shape, slcs))\n@@ -435,47 +467,63 @@ def visualize_sharding(shape: Sequence[int], sharding: Sharding, *,\nelse shape[0])\nhoriz_size = ((horiz.stop - horiz.start) if horiz.stop is not None\nelse shape[1])\n- chunk_height = vert_size / shape[0] * base_height\n- chunk_width = (\n- horiz_size / shape[1] * base_width *\n- height_to_width_ratio)\n- heights[chunk_idxs] = int(chunk_height)\n- widths[chunk_idxs] = int(chunk_width)\n- slices.setdefault(chunk_idxs, set()).add(dev.id)\n+ chunk_height = vert_size / shape[0]\n+ chunk_width = horiz_size / shape[1]\n+ heights[chunk_idxs] = chunk_height\n+ widths[chunk_idxs] = chunk_width\nelse:\n# In the 1D case, we set the height to 1.\nhoriz, = slcs\nvert = slice(0, 1, None)\nhoriz_size = (\n(horiz.stop - horiz.start) if horiz.stop is not None else shape[0])\n- heights[(0, *chunk_idxs)] = 1\n- widths[(0, *chunk_idxs)] = int(horiz_size / shape[0] * base_width)\n- slices.setdefault((0, *chunk_idxs), set()).add(dev.id)\n+ chunk_idxs = (0, *chunk_idxs)\n+ heights[chunk_idxs] = None\n+ widths[chunk_idxs] = horiz_size / shape[0]\n+ slices.setdefault(chunk_idxs, set()).add(dev.id)\nnum_rows = max([a[0] for a in slices.keys()]) + 1\nif len(list(slices.keys())[0]) == 1:\nnum_cols = 1\nelse:\nnum_cols = max([a[1] for a in slices.keys()]) + 1\n- table = rich.table.Table(show_header=False, show_lines=True, padding=0,\n- highlight=True, pad_edge=False,\n- box=rich.box.SQUARE)\n- console = rich.console.Console(width=max_width)\n+ color_iter = make_color_iter(color_map, num_rows, num_cols)\n+ table = rich.table.Table(show_header=False, show_lines=not use_color,\n+ padding=0,\n+ highlight=not use_color, pad_edge=False,\n+ box=rich.box.SQUARE if not use_color else None)\nfor i in range(num_rows):\ncol = []\nfor j in range(num_cols):\nentry = f\"{device_kind} \"+\",\".join([str(s) for s in sorted(slices[i, j])])\n- width, height = widths[i, j], heights[i, j]\n+ width, maybe_height = widths[i, j], heights[i, j]\n+ width = int(width * base_width * height_to_width_ratio)\n+ if maybe_height is None:\n+ height = 1\n+ else:\n+ height = int(maybe_height * base_height)\nwidth = min(max(width, min_width), max_width)\nleft_padding, remainder = divmod(width - len(entry) - 2, 2)\nright_padding = left_padding + remainder\ntop_padding, remainder = divmod(height - 2, 2)\nbottom_padding = top_padding + remainder\n+ if use_color:\n+ color = _canonicalize_color(next(color_iter)[:3])\n+ text_color = _get_text_color(color)\n+ top_padding += 1\n+ bottom_padding += 1\n+ left_padding += 1\n+ right_padding += 1\n+ else:\n+ color = None\n+ text_color = None\npadding = (top_padding, right_padding, bottom_padding, left_padding)\npadding = tuple(max(x, 0) for x in padding) # type: ignore\ncol.append(\nrich.padding.Padding(\n- rich.align.Align(entry, \"center\", vertical=\"middle\"), padding))\n+ rich.align.Align(entry, \"center\", vertical=\"middle\"), padding,\n+ style=rich.style.Style(bgcolor=color,\n+ color=text_color)))\ntable.add_row(*col)\nconsole.print(table, end='\\n\\n')\n"
}
] | Python | Apache License 2.0 | google/jax | Add colors to sharding visualization |
260,287 | 02.11.2022 08:26:30 | 25,200 | 94ba43bfba8606a8e99d122c643c7008ead10123 | Don't assume that vmap doesn't introduce constants
Because it doesn't hold e.g. for the batcher of ppermute. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/maps.py",
"new_path": "jax/experimental/maps.py",
"diff": "@@ -1366,7 +1366,7 @@ def _xmap_lowering_rule_replica(ctx, *in_nodes,\n# them!\nvectorized_jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(f, local_avals)\n_check_out_avals_vs_out_axes(out_avals, out_axes, global_axis_sizes)\n- assert not consts\n+ const_nodes = map(mlir.ir_constants, consts)\nlocal_mesh_shape = mesh.local_mesh.shape\ntiled_ins = (\n@@ -1389,7 +1389,8 @@ def _xmap_lowering_rule_replica(ctx, *in_nodes,\nwrap_name(name, 'xmap')))\nif any(eff in core.ordered_effects for eff in vectorized_jaxpr.effects):\nraise NotImplementedError('Cannot lower `xmap` with ordered effects.')\n- tiled_outs, _ = mlir.jaxpr_subcomp(sub_ctx, vectorized_jaxpr, mlir.TokenSet(), (), *tiled_ins)\n+ tiled_outs, _ = mlir.jaxpr_subcomp(sub_ctx, vectorized_jaxpr, mlir.TokenSet(),\n+ const_nodes, *tiled_ins)\nouts = [\nmlir.lower_fun(\n@@ -1438,7 +1439,6 @@ def _xmap_lowering_rule_spmd(ctx, *global_in_nodes,\nadd_spmd_axes(mesh_out_axes, spmd_out_axes)\nglobal_in_avals = ctx.avals_in\nvectorized_jaxpr, global_out_avals, consts = pe.trace_to_jaxpr_dynamic(f, global_in_avals)\n- assert not consts\nglobal_sharding_spec = pxla.mesh_sharding_specs(mesh.shape, mesh.axis_names)\nsharded_global_in_nodes = [\n@@ -1446,6 +1446,7 @@ def _xmap_lowering_rule_spmd(ctx, *global_in_nodes,\nif aval_axes else [node]\nfor node, aval, aval_axes in zip(global_in_nodes, global_in_avals, mesh_in_axes)\n]\n+ const_nodes = map(mlir.ir_constants, consts)\n# We in-line here rather than generating a Call HLO as in the xla_call\n# translation rule just because the extra tuple stuff is a pain.\n@@ -1455,7 +1456,7 @@ def _xmap_lowering_rule_spmd(ctx, *global_in_nodes,\nif any(eff in core.ordered_effects for eff in vectorized_jaxpr.effects):\nraise NotImplementedError('Cannot lower `xmap` with ordered effects.')\nglobal_out_nodes, _ = mlir.jaxpr_subcomp(sub_ctx, vectorized_jaxpr,\n- mlir.TokenSet(), (), *sharded_global_in_nodes)\n+ mlir.TokenSet(), const_nodes, *sharded_global_in_nodes)\nsharded_global_out_nodes = [\nmlir.wrap_with_sharding_op(node, global_sharding_spec(aval, aval_axes).sharding_proto())\n@@ -1494,7 +1495,7 @@ def _xmap_lowering_rule_spmd_manual(ctx, *global_in_nodes,\n# them!\nglobal_in_avals = ctx.avals_in\nvectorized_jaxpr, global_out_avals, consts = pe.trace_to_jaxpr_dynamic(f, global_in_avals)\n- assert not consts\n+ const_nodes = map(mlir.ir_constants, consts)\n# We in-line here rather than generating a Call HLO as in the xla_call\n# translation rule just because the extra tuple stuff is a pain.\n@@ -1506,7 +1507,7 @@ def _xmap_lowering_rule_spmd_manual(ctx, *global_in_nodes,\nif any(eff in core.ordered_effects for eff in vectorized_jaxpr.effects):\nraise NotImplementedError('Cannot lower `xmap` with ordered effects.')\nglobal_out_nodes, _ = mlir.jaxpr_subcomp(sub_ctx, vectorized_jaxpr,\n- mlir.TokenSet(), (), *([n] for n in global_in_nodes))\n+ mlir.TokenSet(), const_nodes, *([n] for n in global_in_nodes))\nreturn global_out_nodes\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/xmap_test.py",
"new_path": "tests/xmap_test.py",
"diff": "@@ -118,6 +118,19 @@ core.axis_substitution_rules[ensure_bdim_p] = partial(\ndef ensure_bdim(x, axis_name, bdim):\nreturn ensure_bdim_p.bind(x, axis_name=(axis_name,), bdim=bdim)\n+# When we use the SPMD lowering, we vmap the xmap body to make all named\n+# axes positional again. This lowering can introduce constants, which we\n+# have to handle properly in the lowering rule.\n+constant_introducing_p = core.Primitive('introduce_constant')\n+constant_introducing_p.def_abstract_eval(lambda x, **_: core.raise_to_shaped(x))\n+def _constant_introducing_batcher(_1, _2, _3, xs, ds, axis_name):\n+ (x,), (d,) = xs, ds\n+ # Introduce a constant\n+ return (x + np.arange(x.size, dtype=x.dtype).reshape(x.shape)), d\n+batching.axis_primitive_batchers[constant_introducing_p] = _constant_introducing_batcher\n+core.axis_substitution_rules[constant_introducing_p] = partial(\n+ lax_parallel._subst_all_names_in_param, 'axis_name')\n+\n# -------------------- Axis resources generation --------------------\nAxisResources = Dict[str, Union[str, Tuple[str, ...]]]\n@@ -489,6 +502,17 @@ class XMapTest(XMapTestCase):\nf(x)\nself.assertDeleted(x)\n+ @jtu.with_mesh([('x', 2), ('y', 2)])\n+ def testConstantsInLowering(self):\n+ h = xmap(partial(constant_introducing_p.bind, axis_name='i'),\n+ in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})\n+ f = xmap(h, in_axes=['j', ...], out_axes=['j', ...], axis_resources={'j': 'y'})\n+\n+ yp = 1 + jnp.arange(10, dtype=np.float32)\n+ self.assertAllClose(\n+ f(jnp.ones((2, 20), dtype=np.float32)),\n+ jnp.broadcast_to(jnp.concatenate([yp, yp]), (2, 20)))\n+\ndef testControlFlow(self):\nx = jnp.arange(5)\nxmap(lambda x: lax.fori_loop(0, 10, lambda _, x: lax.psum(x, 'i'), x),\n@@ -808,6 +832,16 @@ class XMapTestSPMD(SPMDTestMixin, XMapTest):\nfinally:\nconfig.update(\"experimental_xmap_ensure_fixed_sharding\", False)\n+ @jtu.with_mesh([('x', 2)])\n+ def testConstantsInLowering(self):\n+ h = xmap(partial(constant_introducing_p.bind, axis_name='i'),\n+ in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})\n+ f = pjit(h, in_axis_resources=None, out_axis_resources=None)\n+ yp = 1 + jnp.arange(10, dtype=np.float32)\n+ self.assertAllClose(\n+ f(jnp.ones(20, dtype=np.float32)),\n+ jnp.concatenate([yp, yp]))\n+\nclass XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\n@jtu.with_mesh([('x', 2)])\n@@ -872,7 +906,7 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\nself.assertAllClose(x.sum(0), y)\n@jtu.with_mesh([('x', 2)])\n- def testRepro(self):\n+ def testPPermute(self):\nif mlir_api_version < 35:\nself.skipTest('MLIR api version should be greater than 35 for manual '\n'lowering of ppermute.')\n@@ -884,6 +918,16 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\ng = pjit(f, in_axis_resources=P('x'), out_axis_resources=P('x'))\nself.assertAllClose(g(x), x[::-1])\n+ @jtu.with_mesh([('x', 2)])\n+ def testConstantsInLowering(self):\n+ h = xmap(partial(constant_introducing_p.bind, axis_name='i'),\n+ in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})\n+ f = pjit(h, in_axis_resources=None, out_axis_resources=None)\n+ yp = 1 + jnp.arange(10, dtype=np.float32)\n+ self.assertAllClose(\n+ f(jnp.ones(20, dtype=np.float32)),\n+ jnp.concatenate([yp, yp]))\n+\nclass NamedNumPyTest(XMapTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Don't assume that vmap doesn't introduce constants
Because it doesn't hold e.g. for the batcher of ppermute.
PiperOrigin-RevId: 485601414 |
260,631 | 02.11.2022 12:01:04 | 25,200 | b467feb250c8920850118ebec19e6eff4634d5f9 | [JAX] Add RunTimeError to host_local_array_to_global_array | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/multihost_utils.py",
"new_path": "jax/experimental/multihost_utils.py",
"diff": "@@ -258,7 +258,17 @@ def host_local_array_to_global_array(local_inputs, global_mesh, pspecs):\nlocal_inputs: A Pytree of host local values.\nglobal_mesh: The global mesh.\npspecs: A Pytree of PartitionSpecs.\n+\n+ Raises:\n+ RuntimeError: If `jax.config.jax_array` not previously enabled.\n\"\"\"\n+ if not jax.config.jax_array:\n+ raise RuntimeError(\n+ \"Please enable `jax_array` to use `host_local_array_to_global_array`. \"\n+ \"You can use jax.config.update('jax_array', True) or set the \"\n+ \"environment variable JAX_ARRAY=1 , or set the `jax_array` boolean \"\n+ \"flag to something true-like.\")\n+\ndef _convert(arr, pspec):\nif isinstance(arr, array.ArrayImpl) and isinstance(\narr.sharding, jax.sharding.PmapSharding):\n@@ -313,7 +323,16 @@ def global_array_to_host_local_array(global_inputs, global_mesh, pspecs):\nglobal_inputs: A Pytree of global `jax.Array`s.\nglobal_mesh: The global mesh.\npspecs: A Pytree of PartitionSpecs.\n+\n+ Raises:\n+ RuntimeError: If `jax.config.jax_array` not previously enabled.\n\"\"\"\n+ if not jax.config.jax_array:\n+ raise RuntimeError(\n+ \"Please enable `jax_array` to use `global_array_to_host_local_array`. \"\n+ \"You can use jax.config.update('jax_array', True) or set the \"\n+ \"environment variable JAX_ARRAY=1 , or set the `jax_array` boolean \"\n+ \"flag to something true-like.\")\ndef _convert(arr, pspec):\nlocal_aval = global_mesh._global_to_local(\npxla._get_array_mapping(pspec), arr.aval)\n"
}
] | Python | Apache License 2.0 | google/jax | [JAX] Add RunTimeError to host_local_array_to_global_array
PiperOrigin-RevId: 485657586 |
260,510 | 02.11.2022 16:07:22 | 25,200 | e1af93a9ba6e5e746257e360518f73cf8b60a116 | Enable state effect in `cond_p` (except in `grad` and `vmap`) | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/conditionals.py",
"new_path": "jax/_src/lax/control_flow/conditionals.py",
"diff": "@@ -35,6 +35,7 @@ from jax._src import ad_util\nfrom jax._src import dtypes\nfrom jax._src import source_info_util\nfrom jax._src import util\n+from jax._src import state\nfrom jax._src.lax import lax\nfrom jax._src.traceback_util import api_boundary\nfrom jax._src.util import (safe_map, extend_name_stack, split_list,\n@@ -226,6 +227,8 @@ def _cond(pred, true_fun: Callable, false_fun: Callable, *operands,\njaxprs, consts, out_trees = _initial_style_jaxprs_with_common_consts(\n(true_fun, false_fun), ops_tree, ops_avals, 'cond')\n+ if any(isinstance(op_aval, state.ShapedArrayRef) for op_aval in ops_avals):\n+ raise ValueError(\"Cannot pass `Ref`s into `cond`.\")\ntrue_jaxpr, false_jaxpr = jaxprs\nout_tree, false_out_tree = out_trees\n@@ -288,14 +291,23 @@ def _cond_with_per_branch_args(pred,\nlambda op: false_fun(op[1]),\n(true_operand, false_operand))\n-def _cond_abstract_eval(*args, branches, **kwargs):\n+def _cond_abstract_eval(*avals, branches, **_):\njoined_effects = core.join_effects(*(b.effects for b in branches))\ndisallowed_effects = joined_effects - allowed_effects\nif disallowed_effects:\nraise NotImplementedError(\nf'Effects not supported in `cond`: {disallowed_effects}')\njoined_effects = core.join_effects(*(b.effects for b in branches))\n- return map(raise_to_shaped, branches[0].out_avals), joined_effects\n+ state_effects = {eff for eff in joined_effects if isinstance(eff,\n+ state.RefEffect)}\n+ jaxpr_aval_effects = state.get_ref_state_effects(\n+ [v.aval for v in branches[0].jaxpr.invars], joined_effects)\n+ aval_effects = [set(eff.replace(ref_aval=aval) for eff in effs) for aval, effs\n+ in zip(avals[1:], jaxpr_aval_effects)\n+ if isinstance(aval, state.ShapedArrayRef)]\n+ nonlocal_state_effects = core.join_effects(*aval_effects)\n+ all_effects = (joined_effects - state_effects) | nonlocal_state_effects\n+ return map(raise_to_shaped, branches[0].out_avals), all_effects\ndef _bcast_select(pred, on_true, on_false):\nif np.ndim(pred) != np.ndim(on_true):\n@@ -312,6 +324,10 @@ def _bcast_select_n(pred, *cases):\ndef _cond_batching_rule(axis_size, axis_name, main_type, args, dims, branches, linear):\nindex, *ops = args\nindex_dim, *op_dims = dims\n+ if any(isinstance(eff, state.RefEffect) for branch in branches for eff in\n+ branch.jaxpr.effects):\n+ raise NotImplementedError(\n+ \"State effect not supported in cond vmap.\")\nif index_dim is not batching.not_mapped:\n# Convert to a lax.select. While we could get away with not broadcasting\n@@ -387,6 +403,10 @@ def _cond_jvp(primals, tangents, branches, linear):\ndef _cond_partial_eval(trace, *tracers, branches, linear):\nin_unknowns = [t.pval[0] is not None for t in tracers]\nindex_uk, *ops_uk = in_unknowns\n+ if any(isinstance(eff, state.RefEffect) for branch in branches for eff in\n+ branch.jaxpr.effects):\n+ raise NotImplementedError(\n+ \"State effect not supported in cond partial-eval.\")\nif index_uk:\n# When the branch index is unknown, we stage out the whole cond.\n@@ -657,6 +677,9 @@ def _cond_transpose(reduce_axes, cts, *args, branches, linear):\nindex, *ops = args\nin_avals = map(raise_to_shaped, branches[0].in_avals)\nnum_res = len(ops) - sum(linear)\n+ if any(isinstance(eff, state.RefEffect) for branch in branches for eff in\n+ branch.jaxpr.effects):\n+ raise NotImplementedError(\"State effect not supported in cond transpose.\")\nbranches_trans = tuple(\n_transpose_cond_jaxpr(jaxpr, num_res, reduce_axes) for jaxpr in branches)\n@@ -740,10 +763,6 @@ def _cond_typecheck(*in_atoms, branches, linear):\nraise core.JaxprTypeError(\nf'cond branches take input types {jaxpr0_in_avals_str}, '\nf'called with operands of type {_avals_short(op_avals)}')\n- if any(b.effects != branches[0].effects for b in branches[1:]):\n- raise core.JaxprTypeError(\n- f'cond branches must have matching effect types: '\n- f'{[b.effects for b in branches]}')\njoined_effects = core.join_effects(*(b.effects for b in branches))\nreturn jaxpr0.out_avals, joined_effects\n@@ -808,3 +827,18 @@ def _cond_lowering(ctx, index, *args, branches, linear):\nreturn outputs\nmlir.register_lowering(cond_p, _cond_lowering)\n+\n+@state.register_discharge_rule(cond_p)\n+def _cond_state_discharge_rule(in_avals, out_avals, *args, branches, linear):\n+ discharged_branches = tuple(\n+ core.ClosedJaxpr(state.discharge_state(branch.jaxpr, ())[0], ())\n+ for branch in branches)\n+ out_vals = cond_p.bind(*args, branches=discharged_branches, linear=linear)\n+ out_ref_vals, out_vals = util.split_list(\n+ out_vals, [len(out_vals) - len(out_avals)])\n+ ref_val_iter = iter(out_ref_vals)\n+ new_invals = []\n+ for aval in in_avals:\n+ new_invals.append(\n+ next(ref_val_iter) if isinstance(aval, state.ShapedArrayRef) else None)\n+ return new_invals, out_vals\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/for_loop.py",
"new_path": "jax/_src/lax/control_flow/for_loop.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Module for the `for_loop` primitive.\"\"\"\n-from functools import partial\n+import functools\nimport operator\nfrom typing import Any, Callable, Generic, List, Optional, Sequence, Set, Tuple, TypeVar, Union\n@@ -152,7 +152,8 @@ def for_loop(nsteps: Union[int, Sequence[int]],\nouter_step, *rest_steps = nsteps\ndef wrapped_body(i, refs):\nvals = tree_map(lambda ref: state.ref_get(ref, ()), refs)\n- vals = for_loop(rest_steps, partial(body, i), vals, unroll=unroll)\n+ vals = for_loop(\n+ rest_steps, functools.partial(body, i), vals, unroll=unroll)\ntree_map(lambda ref, val: state.ref_set(ref, (), val), refs, vals)\nreturn for_loop(outer_step, wrapped_body, init_state, unroll=unroll)\nnsteps, = nsteps\n@@ -243,16 +244,11 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\nunroll=unroll)\nreturn init, ys\n-def _get_ref_state_effects(jaxpr: core.Jaxpr) -> List[Set[StateEffect]]:\n- all_effects = jaxpr.effects\n- return [{eff for eff in all_effects\n- if isinstance(eff, (ReadEffect, WriteEffect, AccumEffect))\n- and eff.ref_aval is v.aval} for v in jaxpr.invars]\n-\n@for_p.def_effectful_abstract_eval\ndef _for_abstract_eval(*avals, jaxpr, **__):\n# Find out for each of the `Ref`s in our jaxpr what effects they have.\n- jaxpr_aval_effects = _get_ref_state_effects(jaxpr)[1:]\n+ jaxpr_aval_effects = state.get_ref_state_effects(\n+ [v.aval for v in jaxpr.invars], jaxpr.effects)[1:]\naval_effects = [set(eff.replace(ref_aval=aval) for eff in effs) for aval, effs\nin zip(avals, jaxpr_aval_effects)\nif isinstance(aval, ShapedArrayRef)]\n@@ -260,7 +256,7 @@ def _for_abstract_eval(*avals, jaxpr, **__):\nreturn list(avals), nonlocal_state_effects\n@state.register_discharge_rule(for_p)\n-def _for_discharge_rule(in_avals, *args: Any, jaxpr: core.Jaxpr,\n+def _for_discharge_rule(in_avals, _, *args: Any, jaxpr: core.Jaxpr,\nreverse: bool, which_linear: Sequence[bool],\nnsteps: int, unroll: int\n) -> Tuple[Sequence[Optional[Any]], Sequence[Any]]:\n@@ -302,7 +298,7 @@ def _for_impl_unrolled(body, nsteps, unroll, *args):\nreturn state\nmlir.register_lowering(for_p, mlir.lower_fun(_for_impl, multiple_results=True))\n-for_p.def_impl(partial(xla.apply_primitive, for_p))\n+for_p.def_impl(functools.partial(xla.apply_primitive, for_p))\ndef _for_vmap(axis_size, axis_name, main_type, args, dims, *,\njaxpr, nsteps, reverse, which_linear, unroll):\n@@ -390,7 +386,8 @@ def _is_read_only(ref_effects: Set[StateEffect]) -> bool:\ndef _loop_invariant_outputs(jaxpr: core.Jaxpr) -> List[bool]:\n# Get effects for each of the jaxpr inputs and remove the loop index.\n- ref_effects = _get_ref_state_effects(jaxpr)[1:]\n+ ref_effects = state.get_ref_state_effects(\n+ [v.aval for v in jaxpr.invars], jaxpr.effects)[1:]\n# We first assume that *read-only `Ref`s* are loop-invariant. We can safely do\n# this because the only way something can be loop-varying is if we write to it\n# at some point. It's *possible* that read-write `Ref`s are loop-invariant but\n@@ -786,3 +783,9 @@ def discharged_for_loop(nsteps, body, init_state, *, reverse: bool = False):\nreturn out_flat\nout_flat = loops.fori_loop(0, nsteps, fori_body, flat_state)\nreturn tree_unflatten(state_tree, out_flat)\n+\n+def run_state(f, init_state):\n+ @functools.wraps(f)\n+ def wrapped_body(_, *args):\n+ return f(*args)\n+ return for_loop(1, wrapped_body, init_state)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/__init__.py",
"new_path": "jax/_src/state/__init__.py",
"diff": "# limitations under the License.\n\"\"\"Module for state.\"\"\"\nfrom jax._src.state.types import (ShapedArrayRef, ReadEffect, WriteEffect,\n- AccumEffect, StateEffect)\n+ AccumEffect, StateEffect, RefEffect,\n+ get_ref_state_effects)\nfrom jax._src.state.primitives import (ref_get, ref_set, ref_swap,\nref_addupdate, get_p, swap_p,\naddupdate_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/discharge.py",
"new_path": "jax/_src/state/discharge.py",
"diff": "@@ -71,7 +71,8 @@ class Environment:\nclass DischargeRule(Protocol):\n- def __call__(self, in_avals: Sequence[core.AbstractValue], *args: Any,\n+ def __call__(self, in_avals: Sequence[core.AbstractValue],\n+ out_avals: Sequence[core.AbstractValue], *args: Any,\n**params: Any) -> Tuple[Sequence[Optional[Any]], Sequence[Any]]:\n...\n@@ -107,8 +108,9 @@ def _eval_jaxpr_discharge_state(\nf\"primitive: {eqn.primitive}\")\ninvals = map(env.read, eqn.invars)\nin_avals = [v.aval for v in eqn.invars]\n- new_invals, ans = _discharge_rules[eqn.primitive](in_avals, *invals,\n- **eqn.params)\n+ out_avals = [v.aval for v in eqn.outvars]\n+ new_invals, ans = _discharge_rules[eqn.primitive](\n+ in_avals, out_avals, *invals, **eqn.params)\nfor new_inval, invar in zip(new_invals, eqn.invars):\nif new_inval is not None:\nenv.write(invar, new_inval) # type: ignore[arg-type]\n@@ -132,8 +134,11 @@ def _eval_jaxpr_discharge_state(\nreturn out_vals + ref_vals\n@register_discharge_rule(get_p)\n-def _get_discharge_rule(_: Sequence[core.AbstractValue], x, *non_slice_idx,\n+def _get_discharge_rule(\n+ in_avals: Sequence[core.AbstractValue],\n+ out_avals: Sequence[core.AbstractValue], x, *non_slice_idx,\nindexed_dims: Sequence[bool]):\n+ del in_avals, out_avals\ny = _get_discharge(x, non_slice_idx, indexed_dims)\nreturn (None,) * (len(non_slice_idx) + 1), y\n@@ -163,8 +168,11 @@ def _indexer(idx, indexed_dims):\nreturn indexer\n@register_discharge_rule(swap_p)\n-def _swap_discharge_rule(_: Sequence[core.AbstractValue], x, val, *non_slice_idx,\n+def _swap_discharge_rule(\n+ in_avals: Sequence[core.AbstractValue],\n+ out_avals: Sequence[core.AbstractValue], x, val, *non_slice_idx,\nindexed_dims: Sequence[bool]):\n+ del in_avals, out_avals\nif not any(indexed_dims):\nz, x_new = x, val\nz, x_new = _swap_discharge(x, val, non_slice_idx, indexed_dims)\n@@ -182,8 +190,11 @@ def _swap_discharge(x, val, idx, indexed_dims):\nreturn z, x_new\n@register_discharge_rule(addupdate_p)\n-def _addupdate_discharge_rule(_: Sequence[core.AbstractValue], x, val,\n- *non_slice_idx, indexed_dims: Sequence[bool]):\n+def _addupdate_discharge_rule(\n+ in_avals: Sequence[core.AbstractValue],\n+ out_avals: Sequence[core.AbstractValue], x, val, *non_slice_idx,\n+ indexed_dims: Sequence[bool]):\n+ del in_avals, out_avals\nans = _addupdate_discharge(x, val, non_slice_idx, indexed_dims)\nreturn (ans, None) + (None,) * len(non_slice_idx), []\n@@ -214,7 +225,8 @@ def _dynamic_update_index(x, idx, val, indexed_dims):\nreturn lax.dynamic_update_slice(x, val.reshape(sizes), starts)\n@register_discharge_rule(core.closed_call_p)\n-def _closed_call_discharge_rule(in_avals: Sequence[core.AbstractValue], *args,\n+def _closed_call_discharge_rule(\n+ in_avals: Sequence[core.AbstractValue], _,*args,\ncall_jaxpr: core.ClosedJaxpr):\njaxpr, consts = call_jaxpr.jaxpr, call_jaxpr.consts\nnum_outs = len(jaxpr.outvars)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/primitives.py",
"new_path": "jax/_src/state/primitives.py",
"diff": "@@ -21,18 +21,18 @@ from jax import core\nfrom jax import lax\nfrom jax._src import ad_util\nfrom jax._src import pretty_printer as pp\n+from jax._src.typing import Array\nfrom jax._src.util import safe_map, safe_zip, partition_list, tuple_insert\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\n-import jax.numpy as jnp\n+import numpy as np\nfrom jax._src.state.types import (ShapedArrayRef, ReadEffect, WriteEffect,\nAccumEffect)\n## General utilities\n-Array = Any\nT = TypeVar('T')\nclass Ref(Protocol):\n@@ -65,13 +65,14 @@ def _get_impl(ref: Ref, *idx: int, **_):\nraise ValueError(\"Cannot run stateful primitive.\")\nget_p.def_impl(_get_impl)\n-Indexer = Tuple[Union[int, slice, jnp.ndarray], ...]\n+Indexer = Tuple[Union[int, slice, Array], ...]\ndef _unpack_idx(idx: Indexer, ndim: int\n) -> Tuple[Tuple[Array, ...], Tuple[bool, ...]]:\nindexed_dims_ = [type(i) != slice for i in idx]\n_, non_slice_idx = partition_list(indexed_dims_, idx)\nindexed_dims = indexed_dims_ + [False] * (ndim - len(indexed_dims_))\n+ import jax.numpy as jnp\nreturn (tuple(map(jnp.int32, non_slice_idx)), tuple(indexed_dims))\ndef _get_slice_output_shape(in_shape: Tuple[int, ...],\n@@ -85,8 +86,8 @@ def _get_slice_output_shape(in_shape: Tuple[int, ...],\ndef ref_get(ref: Ref, idx: Tuple[Union[int, slice], ...]) -> Array:\n\"\"\"Reads a value from a `Ref`, a.k.a. value <- ref[idx].\"\"\"\n- idx, indexed_dims = _unpack_idx(idx, ref.ndim)\n- return get_p.bind(ref, *idx, indexed_dims=indexed_dims)\n+ non_slice_idx, indexed_dims = _unpack_idx(idx, ref.ndim)\n+ return get_p.bind(ref, *non_slice_idx, indexed_dims=indexed_dims)\n# `swap` mutates a `Ref`, setting its value and returns its previous value.\n# b = swap_p.bind(x, a)\n@@ -113,8 +114,8 @@ swap_p.def_impl(_swap_impl)\ndef ref_swap(ref: Ref, idx: Tuple[int, ...], value: Array) -> Array:\n\"\"\"Sets a `Ref`'s value and returns the original value.\"\"\"\n- idx, indexed_dims = _unpack_idx(idx, ref.ndim)\n- return swap_p.bind(ref, value, *idx, indexed_dims=indexed_dims)\n+ non_slice_idx, indexed_dims = _unpack_idx(idx, ref.ndim)\n+ return swap_p.bind(ref, value, *non_slice_idx, indexed_dims=indexed_dims)\ndef ref_set(ref: Ref, idx: Tuple[int, ...], value: Array) -> None:\n\"\"\"Sets a `Ref`'s value, a.k.a. ref[idx] <- value.\"\"\"\n@@ -141,8 +142,8 @@ addupdate_p.def_impl(_addupdate_impl)\ndef ref_addupdate(ref: Ref, idx: Tuple[int, ...], x: Array) -> None:\n\"\"\"Mutates a ref with an additive update i.e. `ref[idx] += x`.\"\"\"\n- idx, indexed_dims = _unpack_idx(idx, ref.ndim)\n- return addupdate_p.bind(ref, x, *idx, indexed_dims=indexed_dims)\n+ non_slice_idx, indexed_dims = _unpack_idx(idx, ref.ndim)\n+ return addupdate_p.bind(ref, x, *non_slice_idx, indexed_dims=indexed_dims)\n## get/set/addupdate abstract evaluation rules\n@@ -374,7 +375,7 @@ def _get_vmap(batched_args, batched_dims, *, indexed_dims):\n# `idxs` doesn't include the non indexed dims.\nidx_place = [i for i, i_dim in enumerate(indexed_dims)\nif i_dim].index(ref_dim)\n- iota = lax.broadcasted_iota(jnp.dtype('int32'), idxs_shape, 0)\n+ iota = lax.broadcasted_iota(np.dtype('int32'), idxs_shape, 0)\nidxs = tuple_insert(idxs, idx_place, iota)\nelse:\nbdim_out = _output_bdim(indexed_dims, ref_dim, idxs_shape)\n@@ -407,7 +408,7 @@ def _swap_vmap(batched_args, batched_dims, *, indexed_dims):\nindexed_dims = tuple_insert(indexed_dims, ref_dim, True)\nidx_place = [i for i, i_dim in enumerate(indexed_dims)\nif i_dim].index(ref_dim)\n- iota = lax.broadcasted_iota(jnp.dtype('int32'), idxs_shape, 0)\n+ iota = lax.broadcasted_iota(np.dtype('int32'), idxs_shape, 0)\nidxs = tuple_insert(idxs, idx_place, iota)\nval = batching.moveaxis(val, val_dim, 0)\nbdim_out = 0\n@@ -440,7 +441,7 @@ def _addupdate_vmap(batched_args, batched_dims, *, indexed_dims):\nidx_place = [i for i, i_dim in enumerate(indexed_dims)\nif i_dim].index(ref_dim)\nidxs_shape, = {i.shape for i in idxs} or [()]\n- iota = lax.broadcasted_iota(jnp.dtype('int32'), idxs_shape, 0)\n+ iota = lax.broadcasted_iota(np.dtype('int32'), idxs_shape, 0)\nidxs = tuple_insert(idxs, idx_place, iota)\nval = batching.moveaxis(val, val_dim, 0)\nreturn addupdate_p.bind(ref, val, *idxs, indexed_dims=indexed_dims), []\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/types.py",
"new_path": "jax/_src/state/types.py",
"diff": "\"\"\"Module for state types.\"\"\"\nfrom __future__ import annotations\n-from typing import Any, Optional, Union\n+from typing import Any, List, Optional, Sequence, Set, Union\nfrom jax import core\nfrom jax._src.lib import xla_bridge, xla_client\nfrom jax._src.util import safe_map, safe_zip, tuple_insert, tuple_delete, prod\n+from jax._src.lax.control_flow import common\nxc = xla_client\nxb = xla_bridge\n@@ -33,6 +34,7 @@ Array = Any\nclass RefEffect:\ndef __init__(self, ref_aval: ShapedArrayRef):\nself.ref_aval = ref_aval\n+ common.allowed_effects.add(self)\ndef __eq__(self, other):\nif not isinstance(other, self.__class__):\n@@ -130,3 +132,10 @@ def _unmap_ref(size, axis_name, axis, aval):\nreturn ShapedArrayRef(tuple_insert(aval.shape, axis, size), aval.dtype)\ncore.aval_mapping_handlers[ShapedArrayRef] = (_map_ref, _unmap_ref)\n+\n+def get_ref_state_effects(\n+ avals: Sequence[core.AbstractValue],\n+ effects: core.Effects) -> List[Set[StateEffect]]:\n+ return [{eff for eff in effects\n+ if isinstance(eff, (ReadEffect, WriteEffect, AccumEffect))\n+ and eff.ref_aval is aval} for aval in avals]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1226,6 +1226,7 @@ tf_not_yet_impl = [\n\"full_to_shard\",\n\"shard_to_full\",\n\"pure_callback\",\n+ \"for\",\n\"inspect_sharding\",\n\"iota_32x2_shape\",\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/state_test.py",
"new_path": "tests/state_test.py",
"diff": "@@ -28,6 +28,7 @@ from jax.interpreters import partial_eval as pe\nfrom jax._src import test_util as jtu\nfrom jax._src.util import tuple_insert\nimport jax.numpy as jnp\n+from jax._src.lax.control_flow import for_loop\ntry:\nimport hypothesis as hp\n@@ -929,5 +930,86 @@ if CAN_USE_HYPOTHESIS:\nself.assertAllClose(discharge_of_vmap_ans, vmap_of_discharge_ans,\ncheck_dtypes=False)\n+\n+class StateControlFlowTest(jtu.JaxTestCase):\n+\n+ def test_simple_cond(self):\n+ def f(pred):\n+ def body(x_ref):\n+ def true_fun():\n+ x_ref[()] = 1.\n+ def false_fun():\n+ pass\n+ lax.cond(pred, true_fun, false_fun)\n+ return for_loop.run_state(body, 0.)\n+ jaxpr = jax.make_jaxpr(f)(True).jaxpr\n+ self.assertEmpty(jaxpr.effects)\n+ self.assertAllClose(jax.jit(f)(True), 1.)\n+ self.assertAllClose(jax.jit(f)(False), 0.)\n+\n+ def test_nested_cond(self):\n+ def f(pred):\n+ def body(x_ref):\n+ def true_fun():\n+ def true_fun_inner():\n+ x_ref[()] = 1.\n+ def false_fun_inner():\n+ pass\n+ return lax.cond(pred, true_fun_inner, false_fun_inner)\n+ def false_fun():\n+ pass\n+ lax.cond(pred, true_fun, false_fun)\n+ return for_loop.run_state(body, 0.)\n+ jaxpr = jax.make_jaxpr(f)(True).jaxpr\n+ self.assertEmpty(jaxpr.effects)\n+ self.assertAllClose(jax.jit(f)(True), 1.)\n+ self.assertAllClose(jax.jit(f)(False), 0.)\n+\n+ def test_cond_jvp_with_state(self):\n+ def f(pred, init_value):\n+ def body(x_ref):\n+ def true_fun():\n+ x_ref[()] = x_ref[()] ** 2\n+ def false_fun():\n+ pass\n+ lax.cond(pred, true_fun, false_fun)\n+ return for_loop.run_state(body, init_value)\n+\n+ out_primal, out_tangent = jax.jvp(partial(f, True), (3.,), (1.,))\n+ self.assertAllClose(out_primal, 9.)\n+ self.assertAllClose(out_tangent, 6.)\n+\n+ out_primal, out_tangent = jax.jvp(partial(f, False), (3.,), (1.,))\n+ self.assertAllClose(out_primal, 3.)\n+ self.assertAllClose(out_tangent, 1.)\n+\n+ def test_cond_vmap_not_implemented(self):\n+ @jax.jit\n+ def f(init_value):\n+ def body(x_ref):\n+ def true_fun():\n+ x_ref[()] = x_ref[()] ** 2\n+ def false_fun():\n+ pass\n+ lax.cond(x_ref[()] < 1, true_fun, false_fun)\n+ return for_loop.run_state(body, init_value)\n+\n+ with self.assertRaises(NotImplementedError):\n+ jax.vmap(f)(jnp.arange(2.))\n+\n+ def test_cond_grad_not_implemented(self):\n+ @jax.jit\n+ def f(init_value):\n+ def body(x_ref):\n+ def true_fun():\n+ x_ref[()] = x_ref[()] ** 2\n+ def false_fun():\n+ pass\n+ lax.cond(True, true_fun, false_fun)\n+ return for_loop.run_state(body, init_value)\n+\n+ with self.assertRaises(NotImplementedError):\n+ jax.grad(f)(3.)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Enable state effect in `cond_p` (except in `grad` and `vmap`)
PiperOrigin-RevId: 485719926 |
260,287 | 03.11.2022 05:33:36 | 25,200 | b0621e300c615ee139f181d21e08cd8eb806ec3b | Fix the vmap rule for remat_p
It treated constants like args, but failed to convert_constvars_jaxpr to
adjust the calling convention. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -569,6 +569,8 @@ def remat_vmap(axis_size, axis_name, main_type, args, dims, *, jaxpr, **params):\n[batching.zero_if_mapped] * len(jaxpr.outvars),\naxis_name=axis_name, main_type=main_type)\njaxpr_batched, consts = jaxpr_batched_.jaxpr, jaxpr_batched_.consts\n+ if consts:\n+ jaxpr_batched = pe.convert_constvars_jaxpr(jaxpr_batched)\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"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -52,6 +52,7 @@ from jax.interpreters import ad\nfrom jax.interpreters import mlir\nfrom jax.interpreters import xla\nfrom jax.interpreters import pxla\n+from jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters.pxla import PartitionSpec as P\nfrom jax._src import array, sharding\n@@ -4403,6 +4404,16 @@ class RematTest(jtu.JaxTestCase):\nexpected = np.diag(np.cos(np.sin(x)) * np.cos(x))\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ # Make sure that introducing constants in vmap works.\n+ constant_introducing_p = core.Primitive('introduce_constant')\n+ constant_introducing_p.def_abstract_eval(core.raise_to_shaped)\n+ def _constant_introducing_batcher(xs, ds):\n+ (x,), (d,) = xs, ds\n+ return (x + np.arange(x.size, dtype=x.dtype).reshape(x.shape)), d\n+ batching.primitive_batchers[constant_introducing_p] = _constant_introducing_batcher\n+\n+ api.vmap(remat(constant_introducing_p.bind))(jnp.ones(20))\n+\n@parameterized.named_parameters(\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n"
}
] | Python | Apache License 2.0 | google/jax | Fix the vmap rule for remat_p
It treated constants like args, but failed to convert_constvars_jaxpr to
adjust the calling convention.
PiperOrigin-RevId: 485847686 |
260,674 | 03.11.2022 05:54:38 | 25,200 | 91d134d65b39c5570800fd788c3d41fac87ccebf | Remove unsupported type combinations from dot primitive tests. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -2737,6 +2737,14 @@ def _make_dot_general_harness(name,\nsuffix += f\"_precision={precision}\"\nif preferred_element_type is not None:\nsuffix += f\"_preferred={jtu.dtype_str(preferred_element_type)}\"\n+\n+ # Check if dtype/preferred_element_type combination is allowed\n+ floating_point_types = [np.float16, dtypes.bfloat16, np.float32, np.float64, np.complex64, np.complex128]\n+ limitations = []\n+ if preferred_element_type is not None and dtype in floating_point_types and dtype != preferred_element_type:\n+ # Create limitation\n+ limitations = [Limitation(\"Floating point types must match\", devices=\"gpu\", enabled=False)]\n+\ndefine(\nlax.dot_general_p,\nf\"{name}_lhs={jtu.format_shape_dtype_string(lhs_shape, dtype)}_rhs={jtu.format_shape_dtype_string(rhs_shape, dtype)}_dimensionnumbers={dimension_numbers}{suffix}\"\n@@ -2755,6 +2763,7 @@ def _make_dot_general_harness(name,\ndimension_numbers=dimension_numbers,\nprecision=precision,\npreferred_element_type=preferred_element_type,\n+ jax_unimplemented=limitations\n)\n"
}
] | Python | Apache License 2.0 | google/jax | Remove unsupported type combinations from dot primitive tests.
PiperOrigin-RevId: 485850678 |
260,335 | 03.11.2022 15:10:03 | 25,200 | 40330079794ba0b3f4588dbaba70676f1fd1ea38 | improve error when f_vjp gets more than one argument
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -2531,8 +2531,30 @@ def _lift_linearized(jaxpr, primal_avals, io_tree, out_pvals, consts, *py_args):\nreturn apply_flat_fun(fun, io_tree, *py_args)\n-def _vjp_pullback_wrapper(cotangent_dtypes, cotangent_shapes,\n- io_tree, fun, py_args):\n+def _vjp_pullback_wrapper(name, cotangent_dtypes, cotangent_shapes, io_tree,\n+ fun, *py_args_):\n+ if len(py_args_) != 1:\n+ msg = (f\"The function returned by `jax.vjp` applied to {name} was called \"\n+ f\"with {len(py_args_)} arguments, but functions returned by \"\n+ \"`jax.vjp` must be called with a single argument corresponding to \"\n+ f\"the single value returned by {name} (even if that returned \"\n+ \"value is a tuple or other container).\\n\"\n+ \"\\n\"\n+ \"For example, if we have:\\n\"\n+ \"\\n\"\n+ \" def f(x):\\n\"\n+ \" return (x, x)\\n\"\n+ \" _, f_vjp = jax.vjp(f, 1.0)\\n\"\n+ \"\\n\"\n+ \"the function `f` returns a single tuple as output, and so we call \"\n+ \"`f_vjp` with a single tuple as its argument:\\n\"\n+ \"\\n\"\n+ \" x_bar, = f_vjp((2.0, 2.0))\\n\"\n+ \"\\n\"\n+ \"If we instead call `f_vjp(2.0, 2.0)`, with the values 'splatted \"\n+ \"out' as arguments rather than in a tuple, this error can arise.\")\n+ raise TypeError(msg)\n+ py_args, = py_args_\nin_tree_expected, out_tree = io_tree\nargs, in_tree = tree_flatten(py_args)\nif in_tree != in_tree_expected:\n@@ -2637,9 +2659,8 @@ def _vjp(fun: lu.WrappedFun, *primals, has_aux=False, reduce_axes=()):\nct_shapes = [np.shape(x) for x in out_primal]\n# Ensure that vjp_py is a PyTree so that we can pass it from the forward to the\n# backward pass in a custom VJP.\n- vjp_py = Partial(partial(_vjp_pullback_wrapper,\n- ct_dtypes, ct_shapes,\n- (out_tree, in_tree)),\n+ vjp_py = Partial(partial(_vjp_pullback_wrapper, fun.__name__,\n+ ct_dtypes, ct_shapes, (out_tree, in_tree)),\nout_vjp)\nif not has_aux:\nreturn out_primal_py, vjp_py\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -4095,6 +4095,14 @@ class APITest(jtu.JaxTestCase):\nb(8) # don't crash\n+ def test_vjp_multiple_arguments_error_message(self):\n+ # https://github.com/google/jax/issues/13099\n+ def foo(x):\n+ return (x, x)\n+ _, f_vjp = jax.vjp(foo, 1.0)\n+ with self.assertRaisesRegex(TypeError, \"applied to foo\"):\n+ f_vjp(1.0, 1.0)\n+\n@jtu.with_config(jax_experimental_subjaxpr_lowering_cache=True)\nclass SubcallTraceCacheTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | improve error when f_vjp gets more than one argument
fixes #13099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.