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,680 | 21.10.2021 16:12:33 | -10,800 | b056f796542c4a1714111f2450ed2dc659f8049f | Fix typo in doc for barrier_wait | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -181,7 +181,7 @@ of the computation, if all the callbacks are :func:`call`::\nres1 = jax.jit(device_fun)(1.)\nres2 = jax.jit(device_fun)(1.)\n- res2.block_until_ready()\n+ res1.block_until_ready()\nres2.block_until_ready()\n"
}
] | Python | Apache License 2.0 | google/jax | Fix typo in doc for barrier_wait |
260,631 | 21.10.2021 08:09:48 | 25,200 | bc1c6b10904bb604b8a9fc664f766b003e0fdcc0 | [JAX] Fix sphinx formatting issue | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ann.py",
"new_path": "jax/experimental/ann.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-from functools import partial\n-from typing import (Any, Tuple)\n-\n-import numpy as np\n-from jax import lax, core\n-from jax._src.lib import xla_bridge as xb\n-from jax._src.lib import xla_client as xc\n-from jax._src import ad_util, dtypes\n-\n-from jax.interpreters import ad, xla, batching\n-\n-Array = Any\n-r\"\"\"ANN (Approximate Nearest Neighbor) is an **experimental** module for fast top-k with a configurable recall rate on TPU.\n+\"\"\"ANN (Approximate Nearest Neighbor) is an **experimental** module for fast top-k with a configurable recall rate on TPU.\nTPUs are highly efficient on matrix multiplication, which scales up by TPU\ngeneration. Nevertheless, TPUs are surprisingly inefficient in the other\n@@ -46,12 +34,12 @@ which we can model by the number of people with shared birthdays in the Birthday\nproblem.\nThe recall of this approximation depends on the output size M and desired\n-Kelements in top-k. The recall is approximately :math:`\\mathrm{EXP}((1-K)/M)`.\n+Kelements in top-k. The recall is approximately :math:`\\\\mathrm{EXP}((1-K)/M)`.\nA quick estimate is the output would roughly be :math:`M=10*K` for 90% target\nrecall, and :math:`M=100*K` for 99% target recall. The smaller the output, the\nsmaller memory bandwidth it consumes.\n-Example usage:\n+Usage::\nfrom jax.experimental import ann\n# Maximum inner product search\n@@ -61,13 +49,27 @@ The current JAX implementation sorts and slice the approximate results M into\nthe final top-k on TPU. We'll also provide a on-host final top-k aggregation\nfor JAX in the future.\n-.. todo::\n+Todos::\n* On host top-k aggregation\n* Accurate but slow differentiation\n* Inaccurate but fast differentiation\n+\n\"\"\"\n+from functools import partial\n+from typing import (Any, Tuple)\n+\n+import numpy as np\n+from jax import lax, core\n+from jax._src.lib import xla_bridge as xb\n+from jax._src.lib import xla_client as xc\n+from jax._src import ad_util, dtypes\n+\n+from jax.interpreters import ad, xla, batching\n+\n+Array = Any\n+\ndef approx_max_k(operand: Array,\nk: int,\n"
}
] | Python | Apache License 2.0 | google/jax | [JAX] Fix sphinx formatting issue
PiperOrigin-RevId: 404797143 |
260,631 | 26.10.2021 06:56:05 | 25,200 | 7ae47cbc505698fd8a7fbad9493bf2260b340440 | [JAX] Polish doc formatting for approx_top_k. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ann.py",
"new_path": "jax/experimental/ann.py",
"diff": "@@ -33,11 +33,12 @@ top-1 from each window. The collision rate of the top-k affects the accuracy,\nwhich we can model by the number of people with shared birthdays in the Birthday\nproblem.\n-The recall of this approximation depends on the output size M and desired\n-Kelements in top-k. The recall is approximately :math:`\\\\mathrm{EXP}((1-K)/M)`.\n-A quick estimate is the output would roughly be :math:`M=10*K` for 90% target\n-recall, and :math:`M=100*K` for 99% target recall. The smaller the output, the\n-smaller memory bandwidth it consumes.\n+The recall of this approximation depends on the output size :math:`M` and\n+desired :math`K` elements in top-k. The recall is approximately\n+:math:`\\\\exp\\\\left(\\\\frac{1-K}{M}\\\\right)`. A quick estimate is the output\n+would roughly be :math:`M=10\\\\cdot K` for 90% target recall, and\n+:math:`M=100\\\\cdot K` for 99% target recall. The smaller the output, the smaller\n+memory bandwidth it consumes.\nUsage::\n"
}
] | Python | Apache License 2.0 | google/jax | [JAX] Polish doc formatting for approx_top_k.
PiperOrigin-RevId: 405637140 |
260,335 | 22.07.2020 12:10:43 | 25,200 | 96623c3048351d4f43dee8d999fb440ef1a2c557 | make iter(DeviceArray) return DeviceArrays w/o sync | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -919,7 +919,7 @@ def dynamic_slice(operand: Array, start_indices: Sequence[Array],\n\"\"\"\nstart_indices = _dynamic_slice_indices(operand, start_indices)\nreturn dynamic_slice_p.bind(operand, *start_indices,\n- slice_sizes=tuple(slice_sizes))\n+ slice_sizes=core.canonicalize_shape(slice_sizes))\ndef dynamic_update_slice(operand: Array, update: Array,\nstart_indices: Array) -> Array:\n@@ -1355,7 +1355,7 @@ def transpose(operand: Array, permutation: Sequence[int]) -> Array:\n<https://www.tensorflow.org/xla/operation_semantics#transpose>`_\noperator.\n\"\"\"\n- permutation = tuple(permutation)\n+ permutation = tuple(operator.index(d) for d in permutation)\nif (permutation == tuple(range(np.ndim(operand)))\nand isinstance(operand, (core.Tracer, xla.DeviceArray))):\nreturn operand\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -6695,6 +6695,22 @@ def _multi_slice(arr,\nresults.append(sliced)\nreturn results\n+# The next two functions are related to iter(device_array), implemented here to\n+# avoid circular imports.\n+@jit\n+def _unstack(x):\n+ return [lax.index_in_dim(x, i, keepdims=False) for i in range(x.shape[0])]\n+setattr(DeviceArray, \"_unstack\", _unstack)\n+def _chunk_iter(x, size):\n+ if size > x.shape[0]:\n+ yield x\n+ else:\n+ num_chunks, tail = divmod(x.shape[0], size)\n+ for i in range(num_chunks):\n+ yield lax.dynamic_slice_in_dim(x, i * size, size)\n+ if tail:\n+ yield lax.dynamic_slice_in_dim(x, num_chunks * size, tail)\n+setattr(DeviceArray, \"_chunk_iter\", _chunk_iter)\n# Syntactic sugar for scatter operations.\nclass _IndexUpdateHelper:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -622,21 +622,34 @@ def _sda_value(self):\ndef _sda__getitem__(self, idx):\n+ self._check_if_deleted()\nif not isinstance(idx, tuple):\ncidx = (idx,) + (slice(None),) * (len(self.aval.shape) - 1)\nelse:\ncidx = idx + (slice(None),) * (len(self.aval.shape) - len(idx))\n+ if self._npy_value is None:\ntry:\nbuf_idx = self.indices.index(cidx)\nexcept ValueError:\n- # NOTE: Slow path, this will materialize the sharded array on a single\n- # device and use XLA's Gather to index into the resulting array.\n- return xla.DeviceArray.__getitem__(self, idx)\n- else:\n- self._check_if_deleted()\n+ buf_idx = None\n+ if buf_idx is not None:\nbuf = self.device_buffers[buf_idx]\naval = ShapedArray(buf.xla_shape().dimensions(), self.aval.dtype)\nreturn xla.make_device_array(aval, None, buf)\n+ return super(self.__class__, self).__getitem__(idx)\n+\n+\n+def _sda__iter__(self):\n+ if self.ndim == 0:\n+ raise TypeError(\"iteration over a 0-d array\") # same as numpy error\n+ else:\n+ return (self[i] for i in range(self.shape[0]))\n+\n+def _sda__reversed__(self):\n+ if self.ndim == 0:\n+ raise TypeError(\"iteration over a 0-d array\") # same as numpy error\n+ else:\n+ return (self[i] for i in range(self.shape[0] - 1, -1, -1))\nfor sda in [_ShardedDeviceArray, pmap_lib.ShardedDeviceArray]:\n@@ -647,6 +660,8 @@ for sda in [_ShardedDeviceArray, pmap_lib.ShardedDeviceArray]:\nsetattr(sda, \"block_until_ready\", _sda_block_until_ready)\nsetattr(sda, \"_value\", property(_sda_value))\nsetattr(sda, \"__getitem__\", _sda__getitem__)\n+ setattr(sda, \"__iter__\", _sda__iter__)\n+ setattr(sda, \"__reversed__\", _sda__reversed__)\ndel (_sda_one_replica_buffer_indices, _sda_copy_to_host_async,\n_sda_check_if_deleted, _sda_block_until_ready, _sda_value, _sda__getitem__)\n@@ -659,6 +674,7 @@ else:\nShardedDeviceArray = _ShardedDeviceArray\n+\ndef _hashable_index(idx):\nreturn tree_map(lambda x: (x.start, x.stop) if type(x) == slice else x,\nidx)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1596,15 +1596,12 @@ for device_array in [DeviceArray]:\nif self.ndim == 0:\nraise TypeError(\"iteration over a 0-d array\") # same as numpy error\nelse:\n- return self._value.__iter__()\n+ return (sl for chunk in self._chunk_iter(100) for sl in chunk._unstack())\nsetattr(device_array, \"__iter__\", __iter__)\ndef __reversed__(self):\n- if self.ndim == 0:\n- raise TypeError(\"iteration over a 0-d array\")\n- else:\n- return reversed(self._value)\n+ return iter(self[::-1])\nsetattr(device_array, \"__reversed__\", __reversed__)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2281,7 +2281,7 @@ class APITest(jtu.JaxTestCase):\nself.assertStartsWith(repr(rep), \"DeviceArray\")\ndef test_device_array_hash(self):\n- rep = jnp.ones(()) + 1.\n+ rep = jnp.ones((1,)) + 1.\nself.assertIsInstance(rep, jax.interpreters.xla.DeviceArray)\nself.assertNotIsInstance(rep, collections.abc.Hashable)\nwith self.assertRaisesRegex(TypeError, 'unhashable type'):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -26,6 +26,7 @@ from absl.testing import parameterized\nimport numpy as np\nimport jax\n+import jax.numpy as jnp\nfrom jax import core\nfrom jax._src import dtypes\nfrom jax import lax\n@@ -1497,6 +1498,12 @@ class LaxTest(jtu.JaxTestCase):\nx = rng((6, 7), np.int32)\nnp.testing.assert_equal(lax.dynamic_slice_in_dim(x, 2, 3), x[2:5])\n+ def testDynamicSliceArraySliceSizes(self):\n+ rng = jtu.rand_default(self.rng())\n+ x = rng((6, 7), np.int32)\n+ np.testing.assert_equal(lax.dynamic_slice(x, [2, 3], jnp.array([2, 2])),\n+ x[2:4, 3:5])\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_indices={}_update_shape={}\".format(\njtu.format_shape_dtype_string(shape, dtype),\n@@ -1556,6 +1563,10 @@ class LaxTest(jtu.JaxTestCase):\nop = lambda x: lax.transpose(x, perm)\nself._CompileAndCheck(op, args_maker)\n+ def testTransposeWithArrayPermutation(self):\n+ x = lax.transpose(np.ones((2, 3)), jnp.array([1, 0]))\n+ self.assertEqual((3, 2), x.shape)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_perm={}\".format(\njtu.format_shape_dtype_string(shape, dtype), perm),\n"
}
] | Python | Apache License 2.0 | google/jax | make iter(DeviceArray) return DeviceArrays w/o sync |
260,510 | 06.10.2021 17:21:40 | -7,200 | ae9e69814ad4212ba0feec178c61970d5bad1196 | Broadcast unmapped values in all_to_all batching rule
Fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/parallel.py",
"new_path": "jax/_src/lax/parallel.py",
"diff": "@@ -896,6 +896,12 @@ def _all_to_all_batched_collective(axis_size, frame_name, _, vals_in, dims_in,\nraise NotImplementedError(\"Please open a feature request!\")\nx, = vals_in\nd, = dims_in\n+ if d is batching.not_mapped:\n+ # TODO(sharadmv,apaszke): Remove this broadcast that comes from\n+ # all_gather_transpose and instead avoid using all_to_all in\n+ # all_gather_transpose.\n+ x = lax.broadcast(x, (axis_size, *x.shape))\n+ d = 0\nif isinstance(axis_name, (list, tuple)):\npos = axis_name.index(frame_name)\nmajor_axes, minor_axes = axis_name[:pos], axis_name[pos + 1:]\n@@ -1087,6 +1093,9 @@ def _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_\ncts, axis_name=axis_name, split_axis=all_gather_dimension,\nconcat_axis=concat_axis, axis_index_groups=axis_index_groups),\naxis=concat_axis),)\n+ # TODO(sharadmv,apaszke): re-enable this when we can properly detect\n+ # replication.\n+ # return (lax.dynamic_index_in_dim(cts, idx, axis=all_gather_dimension, keepdims=False) * axis_size,)\ndef _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):\nif tiled:\n"
}
] | Python | Apache License 2.0 | google/jax | Broadcast unmapped values in all_to_all batching rule
Fixes #7965.
Co-authored-by: Sharad Vikram<sharad.vikram@gmail.com>
Co-authored-by: Adam Paszke <apaszke@google.com> |
260,335 | 27.10.2021 13:31:55 | 25,200 | 2bda894a30809340e2159c2973c327d82c3d8617 | MeshComputation.hlo should be a method | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1656,15 +1656,19 @@ def lower_mesh_computation(\nclass MeshComputation:\ndef __init__(self, hlo, *compile_args):\nself._executable = None\n- self.hlo = hlo\n+ self._hlo = hlo\nself.compile_args = compile_args\n+ def hlo(self):\n+ # this is a method for api consistency with xla.XlaComputation\n+ return self._hlo\n+\ndef compile(self,\n_allow_propagation_to_outputs : bool = False,\n_allow_compile_replicated : bool = True) -> 'MeshExecutable':\nif self._executable is None:\nself._executable = MeshExecutable(\n- self.hlo, *self.compile_args,\n+ self._hlo, *self.compile_args,\n_allow_propagation_to_outputs=_allow_propagation_to_outputs,\n_allow_compile_replicated=_allow_compile_replicated) # type: ignore\nreturn self._executable\n"
}
] | Python | Apache License 2.0 | google/jax | MeshComputation.hlo should be a method
Co-authored-by: Brennan Saeta <saeta@google.com> |
260,270 | 28.10.2021 18:37:15 | -3,600 | d890ae906854fa8a530e2e5b9670d21b2e7b3bf3 | Use default backend if no backend supplied to xla_computation | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -772,6 +772,8 @@ def xla_computation(fun: Callable,\nfun_name = getattr(fun, \"__name__\", \"unknown\")\n+ backend = backend if backend is not None else xb.get_backend().platform\n+\ndef make_axis_env(nreps):\nif axis_env is None:\nreturn xla.AxisEnv(nreps, (), ())\n"
}
] | Python | Apache License 2.0 | google/jax | Use default backend if no backend supplied to xla_computation |
260,510 | 27.10.2021 15:20:45 | 25,200 | b40245e38d7837a7777735ad60f3b5b1ac2d499d | Use `SourceInfo` named tuple to keep track of source information | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/source_info_util.py",
"new_path": "jax/_src/source_info_util.py",
"diff": "@@ -16,7 +16,7 @@ import contextlib\nimport itertools\nimport os.path\nimport threading\n-from typing import Optional, Iterator\n+from typing import Optional, Iterator, NamedTuple\nimport jax.version\nfrom jax._src.lib import xla_client\n@@ -33,7 +33,17 @@ _exclude_paths = [os.path.dirname(jax.version.__file__)]\ndef register_exclusion(path):\n_exclude_paths.append(path)\n-def user_frames(source_info: Optional[Traceback]) -> Iterator[Frame]:\n+class SourceInfo(NamedTuple):\n+ traceback: Optional[Traceback]\n+\n+ def replace(self, *, traceback: Optional[Traceback] = None) -> 'SourceInfo':\n+ traceback = traceback or self.traceback\n+ return self._replace(traceback=traceback)\n+\n+def new_source_info() -> SourceInfo:\n+ return SourceInfo(None)\n+\n+def user_frames(source_info: SourceInfo) -> Iterator[Frame]:\n\"\"\"Heuristic that guesses the identity of the user's code in a stack trace.\"\"\"\n# Guess the user's frame is the innermost frame not in the jax source tree\n# We don't use traceback_util.path_starts_with because that incurs filesystem\n@@ -41,30 +51,33 @@ def user_frames(source_info: Optional[Traceback]) -> Iterator[Frame]:\n# provenance annotations to XLA lowerings, so we don't want to incur the cost.\n# We consider files that end with _test.py as user frames, to allow testing\n# this mechanism from tests.\n- return (x for x in (source_info.frames if source_info else [])\n+ traceback = source_info.traceback\n+ return (x for x in (traceback.frames if traceback else [])\nif x.file_name.endswith(\"_test.py\") or not any(x.file_name.startswith(p) for p in _exclude_paths))\n-def user_frame(source_info: Optional[Traceback]) -> Optional[Frame]:\n+def user_frame(source_info: SourceInfo) -> Optional[Frame]:\nreturn next(user_frames(source_info), None)\n-def summarize(source_info: Optional[Traceback], num_frames=1) -> str:\n+def summarize(source_info: SourceInfo, num_frames=1) -> str:\nframes = itertools.islice(user_frames(source_info), num_frames)\nframe_strs = [f\"{frame.file_name}:{frame.line_num} ({frame.function_name})\"\nif frame else \"unknown\" for frame in frames]\nreturn '\\n'.join(reversed(frame_strs))\n-\nclass _SourceInfoContext(threading.local):\n- context: Optional[Traceback]\n+ context: SourceInfo\ndef __init__(self):\n- self.context = None\n+ self.context = new_source_info()\n_source_info_context = _SourceInfoContext()\n+def current() -> SourceInfo:\n+ context = _source_info_context.context\n+ if not context.traceback:\n+ return context.replace(traceback=xla_client.Traceback.get_traceback())\n+ return context\n-def current() -> Optional[Traceback]:\n- return _source_info_context.context or xla_client.Traceback.get_traceback()\nclass JaxStackTraceBeforeTransformation(Exception): pass\n@@ -81,9 +94,9 @@ def has_user_context(e):\nreturn False\n@contextlib.contextmanager\n-def user_context(c):\n+def user_context(c: Optional[Traceback]):\nprev = _source_info_context.context\n- _source_info_context.context = c or _source_info_context.context\n+ _source_info_context.context = _source_info_context.context.replace(traceback=c)\nfiltered_tb = None\ntry:\nyield\n@@ -94,12 +107,12 @@ def user_context(c):\nif filtered_tb:\nmsg = traceback_util.format_exception_only(e)\nmsg = f'{msg}\\n\\n{_message}'\n- c = JaxStackTraceBeforeTransformation(msg).with_traceback(filtered_tb)\n- c.__context__ = e.__context__\n- c.__cause__ = e.__cause__\n- c.__suppress_context__ = e.__suppress_context__\n+ exp = JaxStackTraceBeforeTransformation(msg).with_traceback(filtered_tb)\n+ exp.__context__ = e.__context__\n+ exp.__cause__ = e.__cause__\n+ exp.__suppress_context__ = e.__suppress_context__\ne.__context__ = None\n- e.__cause__ = c\n+ e.__cause__ = exp\nraise\nfinally:\n_source_info_context.context = prev\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -148,11 +148,11 @@ class JaxprEqn(NamedTuple):\noutvars: List['Var']\nprimitive: 'Primitive'\nparams: Dict[str, Any]\n- source_info: Optional[source_info_util.Traceback]\n+ source_info: source_info_util.SourceInfo\ndef __repr__(self): return str(pp_eqn(self, JaxprPpContext())).rstrip()\n-def new_jaxpr_eqn(invars, outvars, primitive, params, source_info=None):\n+def new_jaxpr_eqn(invars, outvars, primitive, params, source_info):\nif primitive.call_primitive:\nassert len(outvars) == len(params[\"call_jaxpr\"].outvars)\nreturn JaxprEqn(invars, outvars, primitive, params, source_info)\n@@ -339,7 +339,7 @@ def eval_jaxpr_eqn(eqn, in_vals):\ndel bind_params['out_axes']\nelse:\nbind_params = params\n- with source_info_util.user_context(eqn.source_info):\n+ with source_info_util.user_context(eqn.source_info.traceback):\nreturn eqn.primitive.bind(*(subfuns + in_vals), **bind_params)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/djax.py",
"new_path": "jax/experimental/djax.py",
"diff": "@@ -20,6 +20,7 @@ from typing import (Tuple, List, Sequence, Set, Dict, Any, Callable, Union,\nfrom jax import core\nfrom jax._src import dtypes\n+from jax._src import source_info_util\nfrom jax.core import Var, Literal, Atom, Tracer\nfrom jax._src.util import (safe_zip, safe_map, curry, unzip2, split_list,\ntuple_delete)\n@@ -920,7 +921,7 @@ def _dynamic_xla_call_pe(trace, *tracers, jaxpr, num_consts):\nfor v in jaxpr2.outs]\neqn = pe.new_eqn_recipe(in_dim_tracers + res_tracers + unknown_tracers, outs2,\ndynamic_xla_call_p, dict(jaxpr=jaxpr2, num_consts=0),\n- None)\n+ source_info_util.new_source_info())\nfor t in outs2: t.recipe = eqn\nouts1, outs2 = iter(outs1), iter(outs2)\nreturn [next(outs2) if uk else next(outs1) for uk in out_unknowns]\n@@ -950,7 +951,8 @@ def partial_eval_jaxpr(jaxpr, in_unknowns):\nif any(unks):\ninvars = [v if unk else new_res(v) for unk, v in zip(unks, eqn.invars)]\neqns2.append(pe.new_jaxpr_eqn(invars, eqn.outvars, eqn.primitive,\n- eqn.params, None))\n+ eqn.params,\n+ source_info_util.new_source_info()))\nmap(partial(write, True), eqn.outvars)\nelse:\neqns1.append(eqn)\n@@ -1265,7 +1267,8 @@ def _nonzero_staging_rule(trace, tracers, params):\nout_val_tracer = pe.DynamicJaxprTracer(trace, out_val_aval, None)\ninvars = map(trace.getvar, tracers)\noutvars = map(trace.makevar, [out_dim_tracer, out_val_tracer])\n- eqn = pe.new_jaxpr_eqn(invars, outvars, nonzero_p, {}, None)\n+ eqn = pe.new_jaxpr_eqn(invars, outvars, nonzero_p, {},\n+ source_info_util.new_source_info())\ntrace.frame.eqns.append(eqn)\nreturn out_val_tracer\ncustom_staging_rules[nonzero_p] = _nonzero_staging_rule\n@@ -1319,7 +1322,8 @@ def _iota_staging_rule(trace, tracers, params):\nout_aval = core.ShapedArray((n,), np.dtype('int32'))\nout_tracer = pe.DynamicJaxprTracer(trace, out_aval, None)\noutvar = trace.makevar(out_tracer)\n- eqn = pe.new_jaxpr_eqn([], [outvar], iota_p, dict(size=n), None)\n+ eqn = pe.new_jaxpr_eqn([], [outvar], iota_p, dict(size=n),\n+ source_info_util.new_source_info())\nelse:\naval = tracer.aval\nif not isinstance(aval, AbsArray): raise TypeError\n@@ -1332,7 +1336,8 @@ def _iota_staging_rule(trace, tracers, params):\nout_tracer = pe.DynamicJaxprTracer(trace, out_aval, None)\noutvar = trace.makevar(out_tracer)\ninvar = trace.getvar(tracer)\n- eqn = pe.new_jaxpr_eqn([invar], [outvar], iota_p, {}, None)\n+ eqn = pe.new_jaxpr_eqn([invar], [outvar], iota_p, {},\n+ source_info_util.new_source_info())\ntrace.frame.eqns.append(eqn)\nreturn out_tracer\ncustom_staging_rules[iota_p] = _iota_staging_rule\n@@ -1381,7 +1386,8 @@ def _broadcast_staging_rule(trace, tracers, params):\nout_aval = AbsArray((d, *x.shape), BaseType(dtype))\nout_tracer = pe.DynamicJaxprTracer(trace, out_aval, None)\neqn = pe.new_jaxpr_eqn([trace.getvar(x), trace.getvar(d)],\n- [trace.makevar(out_tracer)], broadcast_p, {}, None)\n+ [trace.makevar(out_tracer)], broadcast_p, {},\n+ source_info_util.new_source_info())\ntrace.frame.eqns.append(eqn)\nreturn out_tracer\ncustom_staging_rules[broadcast_p] = _broadcast_staging_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/maps.py",
"new_path": "jax/experimental/maps.py",
"diff": "@@ -713,7 +713,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\ncall_jaxpr=jaxpr,\nresource_env=resource_env,\nname=name),\n- None, resource_env, {})\n+ source_info_util.new_source_info(), resource_env, {})\njaxpr = plan.subst_axes_with_resources(jaxpr)\nuse_spmd_lowering = config.experimental_xmap_spmd_lowering\nensure_fixed_sharding = config.experimental_xmap_ensure_fixed_sharding\n@@ -950,7 +950,7 @@ def show_axes(axes):\ndef _resource_typing_xmap(avals,\nparams,\n- source_info: Optional[source_info_util.Traceback],\n+ source_info: source_info_util.SourceInfo,\nresource_env,\nouter_axis_resources):\naxis_resources = params['axis_resources']\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -215,7 +215,7 @@ def backward_pass(jaxpr: core.Jaxpr, reduce_axes, consts, primals_in, cotangents\ncts_in = map(read_cotangent, eqn.outvars)\nelse:\ncts_in, = map(read_cotangent, eqn.outvars)\n- with source_info_util.user_context(eqn.source_info):\n+ with source_info_util.user_context(eqn.source_info.traceback):\nif eqn.primitive.call_primitive or eqn.primitive.map_primitive:\ncts_in_avals = [v.aval for v in eqn.outvars]\ncall_jaxpr, params = core.extract_call_jaxpr(eqn.primitive, eqn.params)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -552,13 +552,13 @@ class JaxprEqnRecipe(NamedTuple):\noutvars: 'Sequence[ref[JaxprTracer]]'\nprimitive: Primitive\nparams: Dict[str, Any]\n- source_info: Optional[source_info_util.Traceback]\n+ source_info: source_info_util.SourceInfo\ndef new_eqn_recipe(invars: Sequence[JaxprTracer],\noutvars: Sequence[JaxprTracer],\nprimitive: Primitive,\nparams: Dict[str, Any],\n- source_info: Optional[source_info_util.Traceback]\n+ source_info: source_info_util.SourceInfo\n) -> JaxprEqnRecipe:\n\"\"\"Constructs a new JaxEqnRecipe.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -98,12 +98,12 @@ def _get_canonical_source_file(frame: source_info_util.Frame):\ntracebacks = {}\ndef make_op_metadata(primitive: core.Primitive,\nparams: Dict, *,\n+ source_info: source_info_util.SourceInfo,\nname_stack: str = \"\",\n- source_info: Optional[source_info_util.Traceback] = None\n) -> xc.OpMetadata:\neqn_str = str(pp.text(name_stack) +\npp_eqn_compact(primitive.name, params, JaxprPpContext()))\n- tracebacks[eqn_str] = source_info\n+ tracebacks[eqn_str] = source_info.traceback\nframe = source_info_util.user_frame(source_info) if source_info else None\nreturn xc.OpMetadata(\nop_type=primitive.name,\n@@ -573,7 +573,7 @@ def jaxpr_subcomp(ctx: TranslationContext, jaxpr: core.Jaxpr,\nraise NotImplementedError(\nf\"XLA translation rule for primitive '{eqn.primitive.name}' not found\")\n- with source_info_util.user_context(eqn.source_info):\n+ with source_info_util.user_context(eqn.source_info.traceback):\nans = rule(ctx, map(aval, eqn.invars), map(aval, eqn.outvars),\n*in_nodes, **eqn.params)\n"
}
] | Python | Apache License 2.0 | google/jax | Use `SourceInfo` named tuple to keep track of source information |
260,631 | 28.10.2021 23:07:25 | 25,200 | 2ab00151edb3497f7fbbad394a866f1455743b5c | Copybara import of the project:
by Sharad Vikram
Use `SourceInfo` named tuple to keep track of source information | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/source_info_util.py",
"new_path": "jax/_src/source_info_util.py",
"diff": "@@ -16,7 +16,7 @@ import contextlib\nimport itertools\nimport os.path\nimport threading\n-from typing import Optional, Iterator, NamedTuple\n+from typing import Optional, Iterator\nimport jax.version\nfrom jax._src.lib import xla_client\n@@ -33,17 +33,7 @@ _exclude_paths = [os.path.dirname(jax.version.__file__)]\ndef register_exclusion(path):\n_exclude_paths.append(path)\n-class SourceInfo(NamedTuple):\n- traceback: Optional[Traceback]\n-\n- def replace(self, *, traceback: Optional[Traceback] = None) -> 'SourceInfo':\n- traceback = traceback or self.traceback\n- return self._replace(traceback=traceback)\n-\n-def new_source_info() -> SourceInfo:\n- return SourceInfo(None)\n-\n-def user_frames(source_info: SourceInfo) -> Iterator[Frame]:\n+def user_frames(source_info: Optional[Traceback]) -> Iterator[Frame]:\n\"\"\"Heuristic that guesses the identity of the user's code in a stack trace.\"\"\"\n# Guess the user's frame is the innermost frame not in the jax source tree\n# We don't use traceback_util.path_starts_with because that incurs filesystem\n@@ -51,33 +41,30 @@ def user_frames(source_info: SourceInfo) -> Iterator[Frame]:\n# provenance annotations to XLA lowerings, so we don't want to incur the cost.\n# We consider files that end with _test.py as user frames, to allow testing\n# this mechanism from tests.\n- traceback = source_info.traceback\n- return (x for x in (traceback.frames if traceback else [])\n+ return (x for x in (source_info.frames if source_info else [])\nif x.file_name.endswith(\"_test.py\") or not any(x.file_name.startswith(p) for p in _exclude_paths))\n-def user_frame(source_info: SourceInfo) -> Optional[Frame]:\n+def user_frame(source_info: Optional[Traceback]) -> Optional[Frame]:\nreturn next(user_frames(source_info), None)\n-def summarize(source_info: SourceInfo, num_frames=1) -> str:\n+def summarize(source_info: Optional[Traceback], num_frames=1) -> str:\nframes = itertools.islice(user_frames(source_info), num_frames)\nframe_strs = [f\"{frame.file_name}:{frame.line_num} ({frame.function_name})\"\nif frame else \"unknown\" for frame in frames]\nreturn '\\n'.join(reversed(frame_strs))\n+\nclass _SourceInfoContext(threading.local):\n- context: SourceInfo\n+ context: Optional[Traceback]\ndef __init__(self):\n- self.context = new_source_info()\n+ self.context = None\n_source_info_context = _SourceInfoContext()\n-def current() -> SourceInfo:\n- context = _source_info_context.context\n- if not context.traceback:\n- return context.replace(traceback=xla_client.Traceback.get_traceback())\n- return context\n+def current() -> Optional[Traceback]:\n+ return _source_info_context.context or xla_client.Traceback.get_traceback()\nclass JaxStackTraceBeforeTransformation(Exception): pass\n@@ -94,9 +81,9 @@ def has_user_context(e):\nreturn False\n@contextlib.contextmanager\n-def user_context(c: Optional[Traceback]):\n+def user_context(c):\nprev = _source_info_context.context\n- _source_info_context.context = _source_info_context.context.replace(traceback=c)\n+ _source_info_context.context = c or _source_info_context.context\nfiltered_tb = None\ntry:\nyield\n@@ -107,12 +94,12 @@ def user_context(c: Optional[Traceback]):\nif filtered_tb:\nmsg = traceback_util.format_exception_only(e)\nmsg = f'{msg}\\n\\n{_message}'\n- exp = JaxStackTraceBeforeTransformation(msg).with_traceback(filtered_tb)\n- exp.__context__ = e.__context__\n- exp.__cause__ = e.__cause__\n- exp.__suppress_context__ = e.__suppress_context__\n+ c = JaxStackTraceBeforeTransformation(msg).with_traceback(filtered_tb)\n+ c.__context__ = e.__context__\n+ c.__cause__ = e.__cause__\n+ c.__suppress_context__ = e.__suppress_context__\ne.__context__ = None\n- e.__cause__ = exp\n+ e.__cause__ = c\nraise\nfinally:\n_source_info_context.context = prev\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -148,11 +148,11 @@ class JaxprEqn(NamedTuple):\noutvars: List['Var']\nprimitive: 'Primitive'\nparams: Dict[str, Any]\n- source_info: source_info_util.SourceInfo\n+ source_info: Optional[source_info_util.Traceback]\ndef __repr__(self): return str(pp_eqn(self, JaxprPpContext())).rstrip()\n-def new_jaxpr_eqn(invars, outvars, primitive, params, source_info):\n+def new_jaxpr_eqn(invars, outvars, primitive, params, source_info=None):\nif primitive.call_primitive:\nassert len(outvars) == len(params[\"call_jaxpr\"].outvars)\nreturn JaxprEqn(invars, outvars, primitive, params, source_info)\n@@ -339,7 +339,7 @@ def eval_jaxpr_eqn(eqn, in_vals):\ndel bind_params['out_axes']\nelse:\nbind_params = params\n- with source_info_util.user_context(eqn.source_info.traceback):\n+ with source_info_util.user_context(eqn.source_info):\nreturn eqn.primitive.bind(*(subfuns + in_vals), **bind_params)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/djax.py",
"new_path": "jax/experimental/djax.py",
"diff": "@@ -20,7 +20,6 @@ from typing import (Tuple, List, Sequence, Set, Dict, Any, Callable, Union,\nfrom jax import core\nfrom jax._src import dtypes\n-from jax._src import source_info_util\nfrom jax.core import Var, Literal, Atom, Tracer\nfrom jax._src.util import (safe_zip, safe_map, curry, unzip2, split_list,\ntuple_delete)\n@@ -921,7 +920,7 @@ def _dynamic_xla_call_pe(trace, *tracers, jaxpr, num_consts):\nfor v in jaxpr2.outs]\neqn = pe.new_eqn_recipe(in_dim_tracers + res_tracers + unknown_tracers, outs2,\ndynamic_xla_call_p, dict(jaxpr=jaxpr2, num_consts=0),\n- source_info_util.new_source_info())\n+ None)\nfor t in outs2: t.recipe = eqn\nouts1, outs2 = iter(outs1), iter(outs2)\nreturn [next(outs2) if uk else next(outs1) for uk in out_unknowns]\n@@ -951,8 +950,7 @@ def partial_eval_jaxpr(jaxpr, in_unknowns):\nif any(unks):\ninvars = [v if unk else new_res(v) for unk, v in zip(unks, eqn.invars)]\neqns2.append(pe.new_jaxpr_eqn(invars, eqn.outvars, eqn.primitive,\n- eqn.params,\n- source_info_util.new_source_info()))\n+ eqn.params, None))\nmap(partial(write, True), eqn.outvars)\nelse:\neqns1.append(eqn)\n@@ -1267,8 +1265,7 @@ def _nonzero_staging_rule(trace, tracers, params):\nout_val_tracer = pe.DynamicJaxprTracer(trace, out_val_aval, None)\ninvars = map(trace.getvar, tracers)\noutvars = map(trace.makevar, [out_dim_tracer, out_val_tracer])\n- eqn = pe.new_jaxpr_eqn(invars, outvars, nonzero_p, {},\n- source_info_util.new_source_info())\n+ eqn = pe.new_jaxpr_eqn(invars, outvars, nonzero_p, {}, None)\ntrace.frame.eqns.append(eqn)\nreturn out_val_tracer\ncustom_staging_rules[nonzero_p] = _nonzero_staging_rule\n@@ -1322,8 +1319,7 @@ def _iota_staging_rule(trace, tracers, params):\nout_aval = core.ShapedArray((n,), np.dtype('int32'))\nout_tracer = pe.DynamicJaxprTracer(trace, out_aval, None)\noutvar = trace.makevar(out_tracer)\n- eqn = pe.new_jaxpr_eqn([], [outvar], iota_p, dict(size=n),\n- source_info_util.new_source_info())\n+ eqn = pe.new_jaxpr_eqn([], [outvar], iota_p, dict(size=n), None)\nelse:\naval = tracer.aval\nif not isinstance(aval, AbsArray): raise TypeError\n@@ -1336,8 +1332,7 @@ def _iota_staging_rule(trace, tracers, params):\nout_tracer = pe.DynamicJaxprTracer(trace, out_aval, None)\noutvar = trace.makevar(out_tracer)\ninvar = trace.getvar(tracer)\n- eqn = pe.new_jaxpr_eqn([invar], [outvar], iota_p, {},\n- source_info_util.new_source_info())\n+ eqn = pe.new_jaxpr_eqn([invar], [outvar], iota_p, {}, None)\ntrace.frame.eqns.append(eqn)\nreturn out_tracer\ncustom_staging_rules[iota_p] = _iota_staging_rule\n@@ -1386,8 +1381,7 @@ def _broadcast_staging_rule(trace, tracers, params):\nout_aval = AbsArray((d, *x.shape), BaseType(dtype))\nout_tracer = pe.DynamicJaxprTracer(trace, out_aval, None)\neqn = pe.new_jaxpr_eqn([trace.getvar(x), trace.getvar(d)],\n- [trace.makevar(out_tracer)], broadcast_p, {},\n- source_info_util.new_source_info())\n+ [trace.makevar(out_tracer)], broadcast_p, {}, None)\ntrace.frame.eqns.append(eqn)\nreturn out_tracer\ncustom_staging_rules[broadcast_p] = _broadcast_staging_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/maps.py",
"new_path": "jax/experimental/maps.py",
"diff": "@@ -713,7 +713,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\ncall_jaxpr=jaxpr,\nresource_env=resource_env,\nname=name),\n- source_info_util.new_source_info(), resource_env, {})\n+ None, resource_env, {})\njaxpr = plan.subst_axes_with_resources(jaxpr)\nuse_spmd_lowering = config.experimental_xmap_spmd_lowering\nensure_fixed_sharding = config.experimental_xmap_ensure_fixed_sharding\n@@ -950,7 +950,7 @@ def show_axes(axes):\ndef _resource_typing_xmap(avals,\nparams,\n- source_info: source_info_util.SourceInfo,\n+ source_info: Optional[source_info_util.Traceback],\nresource_env,\nouter_axis_resources):\naxis_resources = params['axis_resources']\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -215,7 +215,7 @@ def backward_pass(jaxpr: core.Jaxpr, reduce_axes, consts, primals_in, cotangents\ncts_in = map(read_cotangent, eqn.outvars)\nelse:\ncts_in, = map(read_cotangent, eqn.outvars)\n- with source_info_util.user_context(eqn.source_info.traceback):\n+ with source_info_util.user_context(eqn.source_info):\nif eqn.primitive.call_primitive or eqn.primitive.map_primitive:\ncts_in_avals = [v.aval for v in eqn.outvars]\ncall_jaxpr, params = core.extract_call_jaxpr(eqn.primitive, eqn.params)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -552,13 +552,13 @@ class JaxprEqnRecipe(NamedTuple):\noutvars: 'Sequence[ref[JaxprTracer]]'\nprimitive: Primitive\nparams: Dict[str, Any]\n- source_info: source_info_util.SourceInfo\n+ source_info: Optional[source_info_util.Traceback]\ndef new_eqn_recipe(invars: Sequence[JaxprTracer],\noutvars: Sequence[JaxprTracer],\nprimitive: Primitive,\nparams: Dict[str, Any],\n- source_info: source_info_util.SourceInfo\n+ source_info: Optional[source_info_util.Traceback]\n) -> JaxprEqnRecipe:\n\"\"\"Constructs a new JaxEqnRecipe.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -98,12 +98,12 @@ def _get_canonical_source_file(frame: source_info_util.Frame):\ntracebacks = {}\ndef make_op_metadata(primitive: core.Primitive,\nparams: Dict, *,\n- source_info: source_info_util.SourceInfo,\nname_stack: str = \"\",\n+ source_info: Optional[source_info_util.Traceback] = None\n) -> xc.OpMetadata:\neqn_str = str(pp.text(name_stack) +\npp_eqn_compact(primitive.name, params, JaxprPpContext()))\n- tracebacks[eqn_str] = source_info.traceback\n+ tracebacks[eqn_str] = source_info\nframe = source_info_util.user_frame(source_info) if source_info else None\nreturn xc.OpMetadata(\nop_type=primitive.name,\n@@ -573,7 +573,7 @@ def jaxpr_subcomp(ctx: TranslationContext, jaxpr: core.Jaxpr,\nraise NotImplementedError(\nf\"XLA translation rule for primitive '{eqn.primitive.name}' not found\")\n- with source_info_util.user_context(eqn.source_info.traceback):\n+ with source_info_util.user_context(eqn.source_info):\nans = rule(ctx, map(aval, eqn.invars), map(aval, eqn.outvars),\n*in_nodes, **eqn.params)\n"
}
] | Python | Apache License 2.0 | google/jax | Copybara import of the project:
--
b40245e38d7837a7777735ad60f3b5b1ac2d499d by Sharad Vikram <sharad.vikram@gmail.com>:
Use `SourceInfo` named tuple to keep track of source information
PiperOrigin-RevId: 406293469 |
260,447 | 29.10.2021 14:44:27 | 25,200 | c5f73b3d8e84acbb7613c33c97b7317aad5907e9 | [JAX] Added `jax.lax.linalg.qdwh`. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -20,6 +20,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Moved `jax.experimental.stax` to `jax.example_libraries.stax`\n* Moved `jax.experimental.optimizers` to `jax.example_libraries.optimizers`\n+* New features:\n+ * Added `jax.lax.linalg.qdwh`.\n## jax 0.2.24 (Oct 19, 2021)\n* [GitHub\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax.lax.rst",
"new_path": "docs/jax.lax.rst",
"diff": "@@ -199,6 +199,7 @@ Linear algebra operators (jax.lax.linalg)\neig\neigh\nlu\n+ qdwh\nqr\nsvd\ntriangular_solve\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/linalg.py",
"new_path": "jax/lax/linalg.py",
"diff": "@@ -34,3 +34,8 @@ from jax._src.lax.linalg import (\nschur,\nschur_p\n)\n+\n+\n+from jax._src.lax.qdwh import (\n+ qdwh as qdwh\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/qdwh_test.py",
"diff": "+# Copyright 2021 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License\n+\n+\"\"\"Tests for the library of QDWH-based polar decomposition.\"\"\"\n+\n+from jax import test_util as jtu\n+from jax.config import config\n+import jax.numpy as jnp\n+import numpy as np\n+import scipy.linalg as osp_linalg\n+from jax._src.lax import qdwh\n+\n+from absl.testing import absltest\n+from absl.testing import parameterized\n+\n+\n+config.parse_flags_with_absl()\n+_JAX_ENABLE_X64 = config.x64_enabled\n+\n+# Input matrix data type for PolarTest.\n+_POLAR_TEST_DTYPE = np.float64 if _JAX_ENABLE_X64 else np.float32\n+\n+# Machine epsilon used by PolarTest.\n+_POLAR_TEST_EPS = jnp.finfo(_POLAR_TEST_DTYPE).eps\n+\n+# Largest log10 value of condition numbers used by PolarTest.\n+_MAX_LOG_CONDITION_NUM = np.log10(int(1 / _POLAR_TEST_EPS))\n+\n+\n+def _check_symmetry(x: jnp.ndarray) -> bool:\n+ \"\"\"Check if the array is symmetric.\"\"\"\n+ m, n = x.shape\n+ eps = jnp.finfo(x.dtype).eps\n+ tol = 50.0 * eps\n+ is_symmetric = False\n+ if m == n:\n+ if np.linalg.norm(x - x.T.conj()) / np.linalg.norm(x) < tol:\n+ is_symmetric = True\n+\n+ return is_symmetric\n+\n+\n+class PolarTest(jtu.JaxTestCase):\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ { # pylint:disable=g-complex-comprehension\n+ 'testcase_name': '_m={}_by_n={}_log_cond={}'.format(m, n, log_cond),\n+ 'm': m, 'n': n, 'log_cond': log_cond}\n+ for m, n in zip([8, 10, 20], [6, 10, 18])\n+ for log_cond in np.linspace(1, _MAX_LOG_CONDITION_NUM, 4)))\n+ def testQdwhUnconvergedAfterMaxNumberIterations(\n+ self, m, n, log_cond):\n+ \"\"\"Tests unconvergence after maximum number of iterations.\"\"\"\n+ a = jnp.triu(jnp.ones((m, n)))\n+ u, s, v = jnp.linalg.svd(a, full_matrices=False)\n+ cond = 10**log_cond\n+ s = jnp.linspace(cond, 1, min(m, n))\n+ a = (u * s) @ v\n+ is_symmetric = _check_symmetry(a)\n+ max_iterations = 2\n+\n+ _, _, actual_num_iterations, is_converged = qdwh.qdwh(\n+ a, is_symmetric, max_iterations)\n+\n+ with self.subTest('Number of iterations.'):\n+ self.assertEqual(max_iterations, actual_num_iterations)\n+\n+ with self.subTest('Converged.'):\n+ self.assertFalse(is_converged)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ { # pylint:disable=g-complex-comprehension\n+ 'testcase_name': '_m={}_by_n={}_log_cond={}'.format(m, n, log_cond),\n+ 'm': m, 'n': n, 'log_cond': log_cond}\n+ for m, n in zip([8, 10, 20], [6, 10, 18])\n+ for log_cond in np.linspace(1, _MAX_LOG_CONDITION_NUM, 4)))\n+ def testQdwhWithUpperTriangularInputAllOnes(self, m, n, log_cond):\n+ \"\"\"Tests qdwh with upper triangular input of all ones.\"\"\"\n+ a = jnp.triu(jnp.ones((m, n)))\n+ u, s, v = jnp.linalg.svd(a, full_matrices=False)\n+ cond = 10**log_cond\n+ s = jnp.linspace(cond, 1, min(m, n))\n+ a = (u * s) @ v\n+ is_symmetric = _check_symmetry(a)\n+ max_iterations = 10\n+ actual_u, actual_h, _, _ = qdwh.qdwh(a, is_symmetric, max_iterations)\n+ expected_u, expected_h = osp_linalg.polar(a)\n+\n+ # Sets the test tolerance.\n+ rtol = 1E6 * _POLAR_TEST_EPS\n+\n+ with self.subTest('Test u.'):\n+ self.assertAllClose(actual_u, expected_u, rtol=rtol)\n+\n+ with self.subTest('Test h.'):\n+ self.assertAllClose(actual_h, expected_h, rtol=rtol)\n+\n+ with self.subTest('Test u.dot(h).'):\n+ a_round_trip = actual_u.dot(actual_h)\n+ self.assertAllClose(a_round_trip, a, rtol=rtol)\n+\n+ with self.subTest('Test orthogonality.'):\n+ actual_results = actual_u.T.dot(actual_u)\n+ expected_results = np.eye(n)\n+ self.assertAllClose(\n+ actual_results, expected_results, rtol=rtol, atol=1E-4)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ { # pylint:disable=g-complex-comprehension\n+ 'testcase_name': '_m={}_by_n={}_log_cond={}'.format(\n+ m, n, log_cond),\n+ 'm': m, 'n': n, 'log_cond': log_cond}\n+ for m, n in zip([6, 8], [6, 4])\n+ for log_cond in np.linspace(1, 4, 4)))\n+ def testQdwhWithRandomMatrix(self, m, n, log_cond):\n+ \"\"\"Tests qdwh with random input.\"\"\"\n+\n+ a = np.random.uniform(\n+ low=0.3, high=0.9, size=(m, n)).astype(_POLAR_TEST_DTYPE)\n+ u, s, v = jnp.linalg.svd(a, full_matrices=False)\n+ cond = 10**log_cond\n+ s = jnp.linspace(cond, 1, min(m, n))\n+ a = (u * s) @ v\n+ is_symmetric = _check_symmetry(a)\n+ max_iterations = 10\n+\n+ def lsp_linalg_fn(a):\n+ u, h, _, _ = qdwh.qdwh(\n+ a, is_symmetric=is_symmetric, max_iterations=max_iterations)\n+ return u, h\n+\n+ args_maker = lambda: [a]\n+\n+ # Sets the test tolerance.\n+ rtol = 1E6 * _POLAR_TEST_EPS\n+\n+ with self.subTest('Test JIT compatibility'):\n+ self._CompileAndCheck(lsp_linalg_fn, args_maker)\n+\n+ with self.subTest('Test against numpy.'):\n+ self._CheckAgainstNumpy(osp_linalg.polar, lsp_linalg_fn, args_maker,\n+ rtol=rtol, atol=1E-3)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ { # pylint:disable=g-complex-comprehension\n+ 'testcase_name': '_m={}_by_n={}_log_cond={}'.format(m, n, log_cond),\n+ 'm': m, 'n': n, 'log_cond': log_cond}\n+ for m, n in zip([10, 12], [10, 12])\n+ for log_cond in np.linspace(1, 4, 4)))\n+ def testQdwhWithOnRankDeficientInput(self, m, n, log_cond):\n+ \"\"\"Tests qdwh with rank-deficient input.\"\"\"\n+ a = jnp.triu(jnp.ones((m, n))).astype(_POLAR_TEST_DTYPE)\n+\n+ # Generates a rank-deficient input.\n+ u, s, v = jnp.linalg.svd(a, full_matrices=False)\n+ cond = 10**log_cond\n+ s = jnp.linspace(cond, 1, min(m, n))\n+ s = s.at[-1].set(0)\n+ a = (u * s) @ v\n+\n+ is_symmetric = _check_symmetry(a)\n+ max_iterations = 10\n+ actual_u, actual_h, _, _ = qdwh.qdwh(a, is_symmetric, max_iterations)\n+ _, expected_h = osp_linalg.polar(a)\n+\n+ # Sets the test tolerance.\n+ rtol = 1E6 * _POLAR_TEST_EPS\n+\n+ # For rank-deficient matrix, `u` is not unique.\n+ with self.subTest('Test h.'):\n+ self.assertAllClose(actual_h, expected_h, rtol=rtol)\n+\n+ with self.subTest('Test u.dot(h).'):\n+ a_round_trip = actual_u.dot(actual_h)\n+ self.assertAllClose(a_round_trip, a, rtol=rtol)\n+\n+ with self.subTest('Test orthogonality.'):\n+ actual_results = actual_u.T.dot(actual_u)\n+ expected_results = np.eye(n)\n+ self.assertAllClose(\n+ actual_results, expected_results, rtol=rtol, atol=1E-5)\n+\n+if __name__ == '__main__':\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [JAX] Added `jax.lax.linalg.qdwh`.
PiperOrigin-RevId: 406453671 |
260,510 | 29.10.2021 15:49:31 | 25,200 | 32319e1bc36e17ca270e9ff1a9545e6680f9eb28 | Fix forward for PR (made `source_info` for `new_jaxpr_eqn` argument optional again) | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/source_info_util.py",
"new_path": "jax/_src/source_info_util.py",
"diff": "@@ -16,7 +16,7 @@ import contextlib\nimport itertools\nimport os.path\nimport threading\n-from typing import Optional, Iterator\n+from typing import Optional, Iterator, NamedTuple\nimport jax.version\nfrom jax._src.lib import xla_client\n@@ -33,7 +33,17 @@ _exclude_paths = [os.path.dirname(jax.version.__file__)]\ndef register_exclusion(path):\n_exclude_paths.append(path)\n-def user_frames(source_info: Optional[Traceback]) -> Iterator[Frame]:\n+class SourceInfo(NamedTuple):\n+ traceback: Optional[Traceback]\n+\n+ def replace(self, *, traceback: Optional[Traceback] = None) -> 'SourceInfo':\n+ traceback = traceback or self.traceback\n+ return self._replace(traceback=traceback)\n+\n+def new_source_info() -> SourceInfo:\n+ return SourceInfo(None)\n+\n+def user_frames(source_info: SourceInfo) -> Iterator[Frame]:\n\"\"\"Heuristic that guesses the identity of the user's code in a stack trace.\"\"\"\n# Guess the user's frame is the innermost frame not in the jax source tree\n# We don't use traceback_util.path_starts_with because that incurs filesystem\n@@ -41,30 +51,33 @@ def user_frames(source_info: Optional[Traceback]) -> Iterator[Frame]:\n# provenance annotations to XLA lowerings, so we don't want to incur the cost.\n# We consider files that end with _test.py as user frames, to allow testing\n# this mechanism from tests.\n- return (x for x in (source_info.frames if source_info else [])\n+ traceback = source_info.traceback\n+ return (x for x in (traceback.frames if traceback else [])\nif x.file_name.endswith(\"_test.py\") or not any(x.file_name.startswith(p) for p in _exclude_paths))\n-def user_frame(source_info: Optional[Traceback]) -> Optional[Frame]:\n+def user_frame(source_info: SourceInfo) -> Optional[Frame]:\nreturn next(user_frames(source_info), None)\n-def summarize(source_info: Optional[Traceback], num_frames=1) -> str:\n+def summarize(source_info: SourceInfo, num_frames=1) -> str:\nframes = itertools.islice(user_frames(source_info), num_frames)\nframe_strs = [f\"{frame.file_name}:{frame.line_num} ({frame.function_name})\"\nif frame else \"unknown\" for frame in frames]\nreturn '\\n'.join(reversed(frame_strs))\n-\nclass _SourceInfoContext(threading.local):\n- context: Optional[Traceback]\n+ context: SourceInfo\ndef __init__(self):\n- self.context = None\n+ self.context = new_source_info()\n_source_info_context = _SourceInfoContext()\n+def current() -> SourceInfo:\n+ context = _source_info_context.context\n+ if not context.traceback:\n+ return context.replace(traceback=xla_client.Traceback.get_traceback())\n+ return context\n-def current() -> Optional[Traceback]:\n- return _source_info_context.context or xla_client.Traceback.get_traceback()\nclass JaxStackTraceBeforeTransformation(Exception): pass\n@@ -81,9 +94,9 @@ def has_user_context(e):\nreturn False\n@contextlib.contextmanager\n-def user_context(c):\n+def user_context(c: Optional[Traceback]):\nprev = _source_info_context.context\n- _source_info_context.context = c or _source_info_context.context\n+ _source_info_context.context = _source_info_context.context.replace(traceback=c)\nfiltered_tb = None\ntry:\nyield\n@@ -94,12 +107,12 @@ def user_context(c):\nif filtered_tb:\nmsg = traceback_util.format_exception_only(e)\nmsg = f'{msg}\\n\\n{_message}'\n- c = JaxStackTraceBeforeTransformation(msg).with_traceback(filtered_tb)\n- c.__context__ = e.__context__\n- c.__cause__ = e.__cause__\n- c.__suppress_context__ = e.__suppress_context__\n+ exp = JaxStackTraceBeforeTransformation(msg).with_traceback(filtered_tb)\n+ exp.__context__ = e.__context__\n+ exp.__cause__ = e.__cause__\n+ exp.__suppress_context__ = e.__suppress_context__\ne.__context__ = None\n- e.__cause__ = c\n+ e.__cause__ = exp\nraise\nfinally:\n_source_info_context.context = prev\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -148,13 +148,14 @@ class JaxprEqn(NamedTuple):\noutvars: List['Var']\nprimitive: 'Primitive'\nparams: Dict[str, Any]\n- source_info: Optional[source_info_util.Traceback]\n+ source_info: source_info_util.SourceInfo\ndef __repr__(self): return str(pp_eqn(self, JaxprPpContext())).rstrip()\ndef new_jaxpr_eqn(invars, outvars, primitive, params, source_info=None):\nif primitive.call_primitive:\nassert len(outvars) == len(params[\"call_jaxpr\"].outvars)\n+ source_info = source_info or source_info_util.new_source_info()\nreturn JaxprEqn(invars, outvars, primitive, params, source_info)\n@@ -339,7 +340,7 @@ def eval_jaxpr_eqn(eqn, in_vals):\ndel bind_params['out_axes']\nelse:\nbind_params = params\n- with source_info_util.user_context(eqn.source_info):\n+ with source_info_util.user_context(eqn.source_info.traceback):\nreturn eqn.primitive.bind(*(subfuns + in_vals), **bind_params)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/djax.py",
"new_path": "jax/experimental/djax.py",
"diff": "@@ -20,6 +20,7 @@ from typing import (Tuple, List, Sequence, Set, Dict, Any, Callable, Union,\nfrom jax import core\nfrom jax._src import dtypes\n+from jax._src import source_info_util\nfrom jax.core import Var, Literal, Atom, Tracer\nfrom jax._src.util import (safe_zip, safe_map, curry, unzip2, split_list,\ntuple_delete)\n@@ -921,7 +922,7 @@ def _dynamic_xla_call_pe(trace, *tracers, jaxpr, num_consts):\nfor v in jaxpr2.outs]\neqn = pe.new_eqn_recipe(in_dim_tracers + res_tracers + unknown_tracers, outs2,\ndynamic_xla_call_p, dict(jaxpr=jaxpr2, num_consts=0),\n- None)\n+ source_info_util.new_source_info())\nfor t in outs2: t.recipe = eqn\nouts1, outs2 = iter(outs1), iter(outs2)\nreturn [next(outs2) if uk else next(outs1) for uk in out_unknowns]\n@@ -951,7 +952,8 @@ def partial_eval_jaxpr(jaxpr, in_unknowns):\nif any(unks):\ninvars = [v if unk else new_res(v) for unk, v in zip(unks, eqn.invars)]\neqns2.append(pe.new_jaxpr_eqn(invars, eqn.outvars, eqn.primitive,\n- eqn.params, None))\n+ eqn.params,\n+ source_info_util.new_source_info()))\nmap(partial(write, True), eqn.outvars)\nelse:\neqns1.append(eqn)\n@@ -1266,7 +1268,8 @@ def _nonzero_staging_rule(trace, tracers, params):\nout_val_tracer = pe.DynamicJaxprTracer(trace, out_val_aval, None)\ninvars = map(trace.getvar, tracers)\noutvars = map(trace.makevar, [out_dim_tracer, out_val_tracer])\n- eqn = pe.new_jaxpr_eqn(invars, outvars, nonzero_p, {}, None)\n+ eqn = pe.new_jaxpr_eqn(invars, outvars, nonzero_p, {},\n+ source_info_util.new_source_info())\ntrace.frame.eqns.append(eqn)\nreturn out_val_tracer\ncustom_staging_rules[nonzero_p] = _nonzero_staging_rule\n@@ -1320,7 +1323,8 @@ def _iota_staging_rule(trace, tracers, params):\nout_aval = core.ShapedArray((n,), np.dtype('int32'))\nout_tracer = pe.DynamicJaxprTracer(trace, out_aval, None)\noutvar = trace.makevar(out_tracer)\n- eqn = pe.new_jaxpr_eqn([], [outvar], iota_p, dict(size=n), None)\n+ eqn = pe.new_jaxpr_eqn([], [outvar], iota_p, dict(size=n),\n+ source_info_util.new_source_info())\nelse:\naval = tracer.aval\nif not isinstance(aval, AbsArray): raise TypeError\n@@ -1333,7 +1337,8 @@ def _iota_staging_rule(trace, tracers, params):\nout_tracer = pe.DynamicJaxprTracer(trace, out_aval, None)\noutvar = trace.makevar(out_tracer)\ninvar = trace.getvar(tracer)\n- eqn = pe.new_jaxpr_eqn([invar], [outvar], iota_p, {}, None)\n+ eqn = pe.new_jaxpr_eqn([invar], [outvar], iota_p, {},\n+ source_info_util.new_source_info())\ntrace.frame.eqns.append(eqn)\nreturn out_tracer\ncustom_staging_rules[iota_p] = _iota_staging_rule\n@@ -1382,7 +1387,8 @@ def _broadcast_staging_rule(trace, tracers, params):\nout_aval = AbsArray((d, *x.shape), BaseType(dtype))\nout_tracer = pe.DynamicJaxprTracer(trace, out_aval, None)\neqn = pe.new_jaxpr_eqn([trace.getvar(x), trace.getvar(d)],\n- [trace.makevar(out_tracer)], broadcast_p, {}, None)\n+ [trace.makevar(out_tracer)], broadcast_p, {},\n+ source_info_util.new_source_info())\ntrace.frame.eqns.append(eqn)\nreturn out_tracer\ncustom_staging_rules[broadcast_p] = _broadcast_staging_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/maps.py",
"new_path": "jax/experimental/maps.py",
"diff": "@@ -713,7 +713,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\ncall_jaxpr=jaxpr,\nresource_env=resource_env,\nname=name),\n- None, resource_env, {})\n+ source_info_util.new_source_info(), resource_env, {})\njaxpr = plan.subst_axes_with_resources(jaxpr)\nuse_spmd_lowering = config.experimental_xmap_spmd_lowering\nensure_fixed_sharding = config.experimental_xmap_ensure_fixed_sharding\n@@ -950,7 +950,7 @@ def show_axes(axes):\ndef _resource_typing_xmap(avals,\nparams,\n- source_info: Optional[source_info_util.Traceback],\n+ source_info: source_info_util.SourceInfo,\nresource_env,\nouter_axis_resources):\naxis_resources = params['axis_resources']\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -215,7 +215,7 @@ def backward_pass(jaxpr: core.Jaxpr, reduce_axes, consts, primals_in, cotangents\ncts_in = map(read_cotangent, eqn.outvars)\nelse:\ncts_in, = map(read_cotangent, eqn.outvars)\n- with source_info_util.user_context(eqn.source_info):\n+ with source_info_util.user_context(eqn.source_info.traceback):\nif eqn.primitive.call_primitive or eqn.primitive.map_primitive:\ncts_in_avals = [v.aval for v in eqn.outvars]\ncall_jaxpr, params = core.extract_call_jaxpr(eqn.primitive, eqn.params)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -552,13 +552,13 @@ class JaxprEqnRecipe(NamedTuple):\noutvars: 'Sequence[ref[JaxprTracer]]'\nprimitive: Primitive\nparams: Dict[str, Any]\n- source_info: Optional[source_info_util.Traceback]\n+ source_info: source_info_util.SourceInfo\ndef new_eqn_recipe(invars: Sequence[JaxprTracer],\noutvars: Sequence[JaxprTracer],\nprimitive: Primitive,\nparams: Dict[str, Any],\n- source_info: Optional[source_info_util.Traceback]\n+ source_info: source_info_util.SourceInfo\n) -> JaxprEqnRecipe:\n\"\"\"Constructs a new JaxEqnRecipe.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -98,12 +98,12 @@ def _get_canonical_source_file(frame: source_info_util.Frame):\ntracebacks = {}\ndef make_op_metadata(primitive: core.Primitive,\nparams: Dict, *,\n+ source_info: source_info_util.SourceInfo,\nname_stack: str = \"\",\n- source_info: Optional[source_info_util.Traceback] = None\n) -> xc.OpMetadata:\neqn_str = str(pp.text(name_stack) +\npp_eqn_compact(primitive.name, params, JaxprPpContext()))\n- tracebacks[eqn_str] = source_info\n+ tracebacks[eqn_str] = source_info.traceback\nframe = source_info_util.user_frame(source_info) if source_info else None\nreturn xc.OpMetadata(\nop_type=primitive.name,\n@@ -573,7 +573,7 @@ def jaxpr_subcomp(ctx: TranslationContext, jaxpr: core.Jaxpr,\nraise NotImplementedError(\nf\"XLA translation rule for primitive '{eqn.primitive.name}' not found\")\n- with source_info_util.user_context(eqn.source_info):\n+ with source_info_util.user_context(eqn.source_info.traceback):\nans = rule(ctx, map(aval, eqn.invars), map(aval, eqn.outvars),\n*in_nodes, **eqn.params)\n"
}
] | Python | Apache License 2.0 | google/jax | Fix forward for PR #8392 (made `source_info` for `new_jaxpr_eqn` argument optional again)
PiperOrigin-RevId: 406466709 |
260,447 | 02.11.2021 14:13:42 | 25,200 | 4814d75768d00901297103ea5fbb4750e649a4ab | Update coo_matvec and coo_matmat comments. | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/cusparse.py",
"new_path": "jaxlib/cusparse.py",
"diff": "@@ -231,7 +231,7 @@ def coo_fromdense(c, mat, *, nnz, index_dtype):\nreturn tuple(_ops.GetTupleElement(out, i) for i in range(3))\ndef coo_matvec(c, data, row, col, x, *, shape, transpose=False, compute_dtype=None):\n- \"\"\"CSR matrix/vector multiply.\"\"\"\n+ \"\"\"COO matrix/vector multiply.\"\"\"\ndtype = np.dtype(c.get_shape(data).element_type())\nindex_dtype = np.dtype(c.get_shape(row).element_type())\nx_dtype = np.dtype(c.get_shape(x).element_type())\n@@ -268,7 +268,7 @@ def coo_matvec(c, data, row, col, x, *, shape, transpose=False, compute_dtype=No\ndef coo_matmat(c, data, row, col, B, *, shape, transpose=False, compute_dtype=None):\n- \"\"\"CSR from dense matrix.\"\"\"\n+ \"\"\"COO from dense matrix.\"\"\"\ndtype = np.dtype(c.get_shape(data).element_type())\nindex_dtype = np.dtype(c.get_shape(row).element_type())\nB_dtype = np.dtype(c.get_shape(B).element_type())\n"
}
] | Python | Apache License 2.0 | google/jax | Update coo_matvec and coo_matmat comments. |
260,411 | 04.11.2021 10:45:53 | -3,600 | 27de09cc2b5c82a66fb6cf685e52fb3223372f43 | [jax2tf] Improve the documentation for jax2tf and SavedModel
In particular, document better how to avoid embedding large constants
in the SavedModel. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -103,11 +103,12 @@ tf.saved_model.save(my_model, '/some/directory',\nrestored_model = tf.saved_model.load('/some/directory')\n```\n-An important point is that in the above code snippet **everything is standard\n-TensorFlow code. In particular, the saving of the model is not directly part\n+An important point is that in the above code snippet **everything after the\n+jax2tf conversion is standard TensorFlow code.\n+In particular, the saving of the model is not directly part\nof the jax2tf API, and the user has full control over how to create the SavedModel**.\n-Just like for regular TensorFlow functions, it is possible to include in the\n+For example, just like for regular TensorFlow functions, it is possible to include in the\nSavedModel multiple versions of a function for different input shapes, by\n\"warming up\" the function on different input shapes:\n@@ -119,29 +120,41 @@ tf.saved_model.save(my_model, '/some/directory',\noptions=tf.saved_model.SaveOptions(experimental_custom_gradients=True))\n```\n-Note that if the JAX function is not reverse-mode differentiable, e.g., uses `lax.while_loop` then\n-attempting to save its conversion to a SavedModel will fail with\n-```\n-ValueError: Error when tracing gradients for SavedModel\n-```\n-\n-You have two options, either pass `enable_gradients=False` to `jax2tf.convert`, or\n-set `tf.saved_model.SaveOption(experimental_custom_gradients=False)`. In either case,\n-you will not be able to compute the gradients of the function loaded from the SavedModel.\n+### Saved model with parameters\nSome special care is needed to ensure that the model parameters are not embedded\nas constants in the graph and are instead saved separately as variables.\nThis is useful for two reasons:\n-the parameters could be very large and exceed the limits of the\n+the parameters could be very large and exceed the 2GB limits of the\nGraphDef part of the SavedModel, or you may want to fine-tune the\nmodel and change the value of the parameters.\n+For example, consider the following function:\n```python\n+def model_jax(inputs):\n+ return param0 + param1 * inputs\n+```\n+\n+If you just convert and save the model directly, the values of\n+`param0` and `param1` will be embedded in the computation graph. In fact, the\n+value of `param1` is needed for the gradient computation and\n+will be embedded twice: once in the computation\n+graph for the forward computation and once for the backward computation,\n+unless you turn off the conversion of gradients or their saving as discussed\n+further below (e.g., `with_gradient=False`). Note also that if one\n+views the above function as an ML model parameterized by `param0` and `param1`\n+then the gradient function will be w.r.t. the inputs, while you probably\n+want gradients w.r.t. the parameters.\n+\n+A better way to deal with parameters (or any large constants) is to\n+pass them as parameters to the function to be converted:\n+```\ndef model_jax(params, inputs):\nreturn params[0] + params[1] * inputs\n# Wrap the parameter constants as tf.Variables; this will signal to the model\n-# saving code to save those constants as variables.\n+# saving code to save those constants as variables, separate from the\n+# computation graph.\nparams_vars = tf.nest.map_structure(tf.Variable, params)\n# Build the prediction function by closing over the `params_vars`. If you\n@@ -156,11 +169,15 @@ my_model.f = tf.function(prediction_tf, jit_compile=True)\ntf.saved_model.save(my_model)\n```\n+This strategy will avoid any copies of the large parameters in the computation\n+graph (they will be saved in a `variables` area of the model, which is not\n+subject to the 2GB limitation).\n+\nFor examples of how to save a Flax model as a SavedModel see the\n[examples directory](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/README.md).\n-## Differentiation\n+### Saved model and differentiation\nThe converted code supports differentiation from TensorFlow. In order to\nensure that the result of TensorFlow differentiation is identical to the\n@@ -209,6 +226,18 @@ The graph tensor has name: args_0:0\n(We are working with the TF team to give a more explicit error in this case.)\n+### Saved model for non-differentiable JAX functions\n+\n+Note that if the JAX function is not reverse-mode differentiable, e.g., uses `lax.while_loop` then\n+attempting to save its conversion to a SavedModel will fail with\n+```\n+ValueError: Error when tracing gradients for SavedModel\n+```\n+\n+You have two options, either pass `enable_gradients=False` to `jax2tf.convert`, or\n+set `tf.saved_model.SaveOption(experimental_custom_gradients=False)`. In either case,\n+you will not be able to compute the gradients of the function loaded from the SavedModel.\n+\n## Shape-polymorphic conversion\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Improve the documentation for jax2tf and SavedModel
In particular, document better how to avoid embedding large constants
in the SavedModel. |
260,335 | 04.11.2021 15:41:16 | 25,200 | 895f15d5e659569f30eae09ada01764d1e4a41d7 | generalize lax.cond to accept any number of args | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow.py",
"new_path": "jax/_src/lax/control_flow.py",
"diff": "@@ -679,43 +679,45 @@ def switch(index, branches: Sequence[Callable], operand):\nreturn tree_unflatten(out_trees[0], out)\n-def _cond(pred, true_fun: Callable, false_fun: Callable, operand):\n+# For backward compatibility with a previous cond calling convention, we allow a\n+# single (pytree) `operand` argument to be passed by keyword. We use a sentinel\n+# object as its default value to indicate when it is _not_ passed.\n+_no_operand_sentinel = object()\n+\n+def _cond(pred, true_fun: Callable, false_fun: Callable, *operands,\n+ operand=_no_operand_sentinel):\n\"\"\"Conditionally apply ``true_fun`` or ``false_fun``.\n``cond()`` has equivalent semantics to this Python implementation::\n- def cond(pred, true_fun, false_fun, operand):\n+ def cond(pred, true_fun, false_fun, *operands):\nif pred:\n- return true_fun(operand)\n+ return true_fun(*operands)\nelse:\n- return false_fun(operand)\n+ return false_fun(*operands)\n``pred`` must be a scalar type.\n- Functions ``true_fun``/``false_fun`` may not need to refer to an ``operand``\n- to compute their result, but one must still be provided to the ``cond`` call\n- and be accepted by both the branch functions, e.g.::\n-\n- jax.lax.cond(\n- get_predicate_value(),\n- lambda _: 23,\n- lambda _: 42,\n- operand=None)\n-\n-\nArgs:\npred: Boolean scalar type, indicating which branch function to apply.\ntrue_fun: Function (A -> B), to be applied if ``pred`` is True.\nfalse_fun: Function (A -> B), to be applied if ``pred`` is False.\n- operand: Operand (A) input to either branch depending on ``pred``. The type\n- can be a scalar, array, or any pytree (nested Python tuple/list/dict)\n+ operands: Operands (A) input to either branch depending on ``pred``. The\n+ type can be a scalar, array, or any pytree (nested Python tuple/list/dict)\nthereof.\nReturns:\n- Value (B) of either ``true_fun(operand)`` or ``false_fun(operand)``,\n+ Value (B) of either ``true_fun(*operands)`` or ``false_fun(*operands)``,\ndepending on the value of ``pred``. The type can be a scalar, array, or any\npytree (nested Python tuple/list/dict) thereof.\n\"\"\"\n+ if operand is not _no_operand_sentinel:\n+ if operands:\n+ raise TypeError(\"if 'operand' keyword is passed then no positional \"\n+ f\"operands can be passed, got operand={operand} \"\n+ f\"and positional operands {operands}\")\n+ operands = (operand,)\n+ del operand\nif isinstance(pred, Sequence) or np.ndim(pred) != 0:\nraise TypeError(\n@@ -738,11 +740,11 @@ def _cond(pred, true_fun: Callable, false_fun: Callable, operand):\nif config.jax_disable_jit and isinstance(core.get_aval(pred), ConcreteArray):\nif pred:\n- return true_fun(operand)\n+ return true_fun(*operands)\nelse:\n- return false_fun(operand)\n+ return false_fun(*operands)\n- ops, ops_tree = tree_flatten((operand,))\n+ ops, ops_tree = tree_flatten(operands)\nops_avals = tuple(_map(_abstractify, ops))\njaxprs, consts, out_trees = _initial_style_jaxprs_with_common_consts(\n"
}
] | Python | Apache License 2.0 | google/jax | generalize lax.cond to accept any number of args |
260,335 | 27.10.2021 20:27:09 | 25,200 | 05708aef2b43b8abd1705165b37e8498228d0969 | jit(f).lower(...) works w/ duck typed shape/dtype | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -321,9 +321,6 @@ def _prepare_jit(fun, static_argnums, static_argnames, donate_argnums,\nelse:\ndonated_invars = (False,) * len(args_flat)\n- for arg in args_flat:\n- _check_arg(arg)\n-\nreturn f, in_tree, args_flat, donated_invars\n@@ -351,6 +348,8 @@ def _python_jit(\nreturn fun(*args, **kwargs)\nclosed_fun, in_tree, args_flat, donated_invars = _prepare_jit(\nfun, static_argnums, static_argnames, donate_argnums, args, kwargs)\n+ for arg in args_flat:\n+ _check_arg(arg)\nflat_fun, out_tree = flatten_fun(closed_fun, in_tree)\nout_flat = xla.xla_call(\nflat_fun, *args_flat,\n@@ -412,6 +411,8 @@ def _cpp_jit(\n# work/code that is redundant between C++ and Python. We can try that later.\nclosed_fun, in_tree, args_flat, donated_invars = _prepare_jit(\nfun, static_argnums, static_argnames, donate_argnums, args, kwargs)\n+ for arg in args_flat:\n+ _check_arg(arg)\nflat_fun, out_tree = flatten_fun(closed_fun, in_tree)\nout_flat = xla.xla_call(\nflat_fun, *args_flat,\n@@ -561,6 +562,15 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\n# If the function we returned from ``jit`` were a class instance,\n# this might naturally be a method, with ``fun`` as a ``self`` and\n# all the other arguments stored as attributes.\n+\n+ def arg_spec(x):\n+ # like xla.arg_spec but duck-types on x.shape and x.dtype\n+ aval = shaped_abstractify(x)\n+ try:\n+ return aval, x._device\n+ except:\n+ return aval, None\n+\n@api_boundary\ndef lower(*args, **kwargs) -> Lowered:\n\"\"\"Lower this function for the given arguments.\n@@ -576,7 +586,7 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\nfun, static_argnums, static_argnames, donate_argnums, args, kwargs)\nflat_fun, out_tree = flatten_fun(closed_fun, in_tree)\nname = flat_fun.__name__\n- arg_specs = unsafe_map(xla.arg_spec, args_flat)\n+ arg_specs = unsafe_map(arg_spec, args_flat)\ncomputation = xla.lower_xla_callable(\nflat_fun, device, backend, name, donated_invars, *arg_specs)\nreturn Lowered(computation, in_tree, out_tree())\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -723,6 +723,12 @@ class CPPJitTest(jtu.BufferDonationTestCase):\nf_exe = f_low.compile()\nself.assertAllClose(f_exe(1.), 2.)\n+ def test_jit_lower_duck_typing(self):\n+ f_jit = self.jit(lambda x: 2 * x)\n+ f_low = f_jit.lower(jax.ShapeDtypeStruct((), 'float32')) # doesn't crash\n+ f_exe = f_low.compile()\n+ self.assertAllClose(f_exe(jnp.float32(1.)), jnp.float32(2.))\n+\ndef test_jit_lower_compile_in_tree_mismatch(self):\ndef f(x):\nreturn jnp.sqrt(x ** 2) + 1.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pjit_test.py",
"new_path": "tests/pjit_test.py",
"diff": "@@ -372,7 +372,7 @@ class PJitTest(jtu.BufferDonationTestCase):\nxla._translations[pjit_p] = rule\n@jtu.with_mesh([('x', 2)])\n- def testLowerWithAbstractArgs(self):\n+ def testLowerWithDuckTyping(self):\nx = jax.ShapeDtypeStruct((2, 2), jnp.float32)\n# Make sure this doesn't crash\npjit(lambda x: x + 4, in_axis_resources=P('x'), out_axis_resources=P('x')).lower(x)\n"
}
] | Python | Apache License 2.0 | google/jax | jit(f).lower(...) works w/ duck typed shape/dtype |
260,411 | 11.11.2021 13:21:55 | -7,200 | 9175ed611df9e8037538f891740d531098228b47 | [jax2tf] Improve the TF constant sharing
Use fewer cache tables for constants: one per top-level converted function,
and a separate table for the gradient. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -408,7 +408,8 @@ def convert(fun: Callable,\n@tf.custom_gradient\ndef converted_fun_flat_with_custom_gradient(*args_flat: TfVal) -> TfVal:\nout_with_avals = _interpret_fun(flat_fun, args_flat, args_avals_flat,\n- name_stack)\n+ name_stack,\n+ fresh_constant_cache=True)\nouts, out_avals = util.unzip2(out_with_avals)\nreturn (tuple(outs),\npartial(converted_grad_fn, _out_cts_avals=tuple(out_avals)))\n@@ -416,7 +417,7 @@ def convert(fun: Callable,\nout_flat = converted_fun_flat_with_custom_gradient(*args_flat)\nelse:\nout_with_avals = _interpret_fun(flat_fun, args_flat, args_avals_flat,\n- name_stack)\n+ name_stack, fresh_constant_cache=True)\nouts, out_avals = util.unzip2(out_with_avals)\nmessage = (\"The jax2tf-converted function does not support gradients. \"\n\"Use `with_gradient` parameter to enable gradients\")\n@@ -470,12 +471,15 @@ def _extended_name_stack(extra_name_stack: Optional[str]):\ndef _interpret_fun(\nfun: lu.WrappedFun, in_vals: Sequence[TfVal],\nin_avals: Sequence[core.ShapedArray],\n- extra_name_stack: Optional[str]\n+ extra_name_stack: Optional[str],\n+ fresh_constant_cache: bool = False\n) -> Sequence[Tuple[TfVal, core.ShapedArray]]:\ntry:\nprev_constant_cache = _thread_local_state.constant_cache\n+ prev_constant_cache_keys = set(prev_constant_cache.keys()) if prev_constant_cache is not None else set()\n# Start a new cache, so that we don't share constants across tf.function\n# boundaries.\n+ if fresh_constant_cache:\n_thread_local_state.constant_cache = {}\nwith core.new_base_main(TensorFlowTrace) as main: # type: ignore\n@@ -486,6 +490,11 @@ def _interpret_fun(\nfun.call_wrapped(*in_vals)\ndel main\nfinally:\n+ if prev_constant_cache is not None and not fresh_constant_cache:\n+ newly_added_keys = set(prev_constant_cache.keys()) - prev_constant_cache_keys\n+ # Delete the newly added keys\n+ for k in newly_added_keys:\n+ del prev_constant_cache[k]\n_thread_local_state.constant_cache = prev_constant_cache\nreturn tuple(out_vals)\n@@ -614,7 +623,8 @@ def _tfval_to_tensor_jax_dtype(val: TfVal,\n# collected and reused for a different value, which would create correctness\n# issues. We keep the `val` alive by storing in the cache the pair\n# `(val, tf_val)`.\n- if memoize_constants and _thread_local_state.constant_cache is not None:\n+ do_memoize = (memoize_constants and np.shape(val) and _thread_local_state.constant_cache is not None)\n+ if do_memoize:\n_, tf_val = _thread_local_state.constant_cache.get(const_key, (None, None))\nelse:\ntf_val = None\n@@ -624,7 +634,7 @@ def _tfval_to_tensor_jax_dtype(val: TfVal,\nif jax_dtype == dtypes.float0:\nval = np.zeros(np.shape(val), conversion_dtype.as_numpy_dtype)\ntf_val = tf.convert_to_tensor(val, dtype=conversion_dtype)\n- if memoize_constants and _thread_local_state.constant_cache is not None:\n+ if do_memoize:\n_thread_local_state.constant_cache[const_key] = (val, tf_val)\nreturn tf_val, jax_dtype\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "Specific JAX primitive conversion tests are in primitives_test.\"\"\"\n-import re\nfrom typing import Dict, Tuple\nfrom absl.testing import absltest\n@@ -753,11 +752,39 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ndef f(x):\nreturn x + const + const + const + const\n- f_tf_graph = tf.function(jax2tf.convert(f), autograph=False).get_concrete_function(const).graph.as_graph_def()\n- f_tf_graph_nr_consts = len(re.findall(r'op:\\s*\"Const\"', str(f_tf_graph)))\n+ f_tf_nr_consts = self.CountTfConstants(jax2tf.convert(f), const)\n# It seems that there is already a shape constant in the graph, we want to\n# make sure our 4 instances of \"const\" are shared.\n- self.assertEqual(f_tf_graph_nr_consts, 2)\n+ self.assertEqual(f_tf_nr_consts, 2)\n+\n+ def test_shared_constants_under_cond(self):\n+ # Check that the constants are shared properly in converted functions\n+ # See https://github.com/google/jax/issues/7992.\n+ const = np.arange(16, dtype=np.float32)\n+ x = np.ones((16,), dtype=np.float32)\n+ def f1(x):\n+ return lax.cond(x[0] >= 0., lambda x: x + const, lambda x: x * const, x) + const\n+ def f2(x):\n+ return f1(x) + const # The extra const should not cost anything\n+ f1_nr_consts = self.CountTfConstants(jax2tf.convert(f1), x)\n+ f2_nr_consts = self.CountTfConstants(jax2tf.convert(f2), x)\n+ self.assertEqual(f1_nr_consts, f2_nr_consts)\n+\n+ def test_shared_constants_under_scan(self):\n+ # See https://github.com/google/jax/issues/7992.\n+ const = np.arange(16, dtype=np.float32)\n+ xs = np.ones((8, 16), dtype=np.float32)\n+ def f1(xs):\n+ res, _ = lax.scan(lambda carry, x: (carry + x + const, None),\n+ np.zeros((16,), dtype=np.float32), xs)\n+ return res\n+\n+ def f2(xs):\n+ return f1(xs) + const # The extra const should not be saved\n+\n+ f1_nr_consts = self.CountTfConstants(jax2tf.convert(f1), xs)\n+ f2_nr_consts = self.CountTfConstants(jax2tf.convert(f2), xs)\n+ self.assertEqual(f1_nr_consts, f2_nr_consts)\ndef test_weak_types(self):\nmul = jax.jit(jnp.multiply)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"new_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"diff": "import contextlib\nimport dataclasses\nimport logging\n+import re\nimport os\nfrom typing import Any, Callable, List, Optional, Sequence, Tuple\n@@ -421,6 +422,10 @@ class JaxToTfTestCase(jtu.JaxTestCase):\nreturn tree_util.tree_multimap(polymorphic_shape_to_tensorspec, polymorphic_shapes)\n+ def CountTfConstants(self, tf_fun: Callable, *args):\n+ f_tf_graph = tf.function(tf_fun, autograph=False).get_concrete_function(*args).graph.as_graph_def()\n+ return len(re.findall(\"tensor_content\", str(f_tf_graph)))\n+\ndef CheckOpMetadata(self, jax_fun, x,\nexpected: Sequence[OpMetadataGraph],\ninclude_xla_op_metadata=True):\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Improve the TF constant sharing
Use fewer cache tables for constants: one per top-level converted function,
and a separate table for the gradient.
Bug: #7992 |
260,496 | 11.11.2021 20:19:47 | -3,600 | 3df11aee650ba1c9ee98b8d401eeef93c01cb8c2 | Add numerical comparison for jax2tf -> TFLite | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/all_examples.py",
"new_path": "jax/experimental/jax2tf/examples_eval/all_examples.py",
"diff": "@@ -118,7 +118,7 @@ def _flax_examples():\nModuleSpec(\nmodule_path='ppo.models.ActorCritic',\ninput_shape=(1, 8, 8, 4),\n- module_kwargs=dict(num_outputs=2)),\n+ module_kwargs=dict(num_outputs=8)),\n'seq2seq':\nModuleSpec(\nmodule_path='seq2seq.train.Seq2seq',\n@@ -135,10 +135,14 @@ def _flax_examples():\nmodule_path='sst2.models.TextClassifier',\ninput_shape=(2, 3),\nmodule_kwargs=dict(\n+ # TODO(marcvanzee): TFLite throws a concatenation error when\n+ # `embedding_size != hidden_size`. I suppose some arrays are\n+ # concatenation with incompatible shapes, which could mean\n+ # something is going wrong in the translation.\nembedding_size=3,\n- hidden_size=1,\n- vocab_size=5,\n- output_size=3,\n+ hidden_size=3,\n+ vocab_size=13,\n+ output_size=1,\ndropout_rate=0.,\nword_dropout_rate=0.),\ninit_args=(Arg.RNG, Arg.ONES, jnp.array([2, 3], dtype=jnp.int32)),\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"new_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"diff": "# limitations under the License.\n\"\"\"Converters for jax2tf.\"\"\"\nimport functools\n+import numpy as np\nimport tempfile\n+from typing import Any, Tuple\n+from jax._src import dtypes\n+import jax.numpy as jnp\nfrom jax.experimental import jax2tf\nfrom jax.experimental.jax2tf.examples import saved_model_lib\nfrom jax.experimental.jax2tf.examples_eval import examples_converter\n@@ -46,6 +50,18 @@ def jax2tf_to_tfjs(module: examples_converter.ModuleToConvert):\ntfjs_converter.convert([saved_model_path, converted_model_path])\n+def _get_random_data(dtype: jnp.dtype, shape: Tuple[int, ...]) -> Any:\n+ dtype = dtypes.canonicalize_dtype(dtype)\n+ if np.issubdtype(dtype, np.integer):\n+ return np.random.randint(0, 100, size=shape, dtype=dtype)\n+ elif np.issubdtype(dtype, np.floating):\n+ return np.array(np.random.uniform(size=shape), dtype=dtype)\n+ elif dtype == np.bool:\n+ return np.random.choice(a=[False, True], size=shape)\n+ else:\n+ raise ValueError(f\"Unsupported dtype for numerical comparison: {dtype}\")\n+\n+\ndef jax2tf_to_tflite(module: examples_converter.ModuleToConvert):\n\"\"\"Converts the given `module` using the TFLite converter.\"\"\"\napply = functools.partial(module.apply, module.variables)\n@@ -66,4 +82,39 @@ def jax2tf_to_tflite(module: examples_converter.ModuleToConvert):\ntf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\ntf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.\n]\n- converter.convert()\n+ # Convert the model.\n+ tflite_model = converter.convert()\n+\n+ # Construct an interpreter for doing a numerical comparison.\n+ interpreter = tf.lite.Interpreter(model_content=tflite_model)\n+ interpreter.allocate_tensors()\n+\n+ # We assume a single input, but we allows multiple outputs.\n+ inputs = interpreter.get_input_details()[0]\n+ output_details = interpreter.get_output_details()\n+ outputs = tuple(interpreter.tensor(out[\"index\"]) for out in output_details)\n+\n+ # Generate random data and get outputs from TFLite and JAX.\n+ input_data = _get_random_data(module.input_shape, module.dtype)\n+ interpreter.set_tensor(inputs['index'], input_data)\n+ interpreter.invoke()\n+ tflite_results = tuple(output() for output in outputs)\n+ jax_results = apply(input_data)\n+\n+ # If the model returns a single value, put the JAX return value in a tuple so\n+ # we can compare it with the TFLite output, which is always a tuple.\n+ if len(tflite_results) == 1:\n+ jax_results = (jax_results,)\n+\n+ if len(tflite_results) != len(jax_results):\n+ raise ValueError(f\"Numerical difference: returned output tuples lengths do \"\n+ f\"not match: TFLite length vs JAX length: {len(tflite_results)} != \"\n+ f\"{len(jax_results)}\")\n+\n+ for jax_result, tflite_result in zip(jax_results, tflite_results):\n+ for jax_array, tflite_array in zip(jax_result, tflite_result):\n+ jax_array = np.asarray(jax_array)\n+ tflite_array = np.asarray(tflite_array)\n+ if not np.allclose(jax_array, tflite_array, 1e-05):\n+ raise ValueError(f\"Numerical difference: jax_result={jax_result} vs \"\n+ f\"tflite_result={tflite_result}\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"new_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"diff": "# Evaluation Results\n-*Last generated on: 2021-10-13* (YYYY-MM-DD)\n+*Last generated on: 2021-11-11* (YYYY-MM-DD)\n## jax2tf --> TFLite\n@@ -13,11 +13,11 @@ These exampls are representative for what the average ML researcher is intereste\n| Example | Result | Error Message |\n| --- | --- | --- |\n| imagenet | SUCCESS |\n-| lm1b | SUCCESS |\n+| lm1b | FAIL | ValueError('Numerical difference: jax_result=[[[ 1.0656209e+00 9.3210316e-01 -7.5562042e-01 5.7160920e-01\\n 4.7576640e-04 -8.3388436e-01 -6.6835815e-01 8.1217813e-01]]\\n\\n [[ 1.0656208e+00 9.3210304e-01 -7.5562042e-01 5.7160914e-01\\n 4.7582600e-04 -8.3388436e-01 -6.6835815e-01 8.1217837e-01]]] vs tflite_result=[[[ 1.0656209e+00 9.3210316e-01 -7.5562030e-01 5.7160920e-01\\n 4.7570679e-04 -8.3388448e-01 -6.6835809e-01 8.1217837e-01]]\\n\\n [[ 1.0656209e+00 9.3210316e-01 -7.5562030e-01 5.7160920e-01\\n 4.7570679e-04 -8.3388448e-01 -6.6835809e-01 8.1217837e-01]]]')\n| mnist | SUCCESS |\n| nlp_seq | SUCCESS |\n-| pixelcnn++ | SUCCESS |\n-| ppo | SUCCESS |\n+| pixelcnn++ | FAIL | ValueError('Numerical difference: jax_result=[[[[-1.42588705e-01 4.43906128e-01 -4.43267524e-01 ... 2.41633713e-01\\n 4.30841953e-01 -3.73984545e-01]\\n [-4.39649850e-01 5.52693188e-01 -2.85841674e-01 ... -4.82337102e-02\\n 2.57767290e-01 -1.49030924e-01]\\n [-1.11790448e-01 4.16247308e-01 -4.37891722e-01 ... 2.55762637e-01\\n 4.27294075e-01 -3.77151638e-01]\\n ...\\n [-3.12222362e-01 6.24503791e-01 -5.10304689e-01 ... 1.91281274e-01\\n 4.87456709e-01 -3.91308606e-01]\\n [-5.44569135e-01 6.36496902e-01 -2.90352285e-01 ... -1.06496125e-01\\n 2.56181568e-01 -1.25419632e-01]\\n [-2.74163693e-01 4.84380186e-01 -3.63327265e-01 ... 1.05749786e-01\\n 3.44067216e-01 -2.64860481e-01]]\\n\\n [[-2.40709454e-01 5.66605926e-01 -5.06200612e-01 ... 2.30237216e-01\\n 4.87517625e-01 -4.06445533e-01]\\n [-5.57913125e-01 7.04271495e-01 -3.66582096e-01 ... -5.83822057e-02\\n 3.30919504e-01 -1.92696482e-01]\\n [-5.57003498e-01 7.44562387e-01 -4.20874745e-01 ... -1.80031136e-02\\n 3.84750396e-01 -2.43371978e-01]\\n ...\\n [ 3.23703378e-01 8.85252953e-02 -4.45828974e-01 ... 5.17160952e-01\\n 4.60283160e-01 -4.99921381e-01]\\n [-7.84780085e-02 4.18959796e-01 -4.75297749e-01 ... 3.02764535e-01\\n 4.66267854e-01 -4.20726597e-01]\\n [-3.81832868e-01 2.57512122e-01 4.64698970e-02 ... -2.58186400e-01\\n -6.80610538e-02 1.44345522e-01]]\\n\\n [[-5.36303878e-01 6.82846010e-01 -3.60135853e-01 ... -5.04315346e-02\\n 3.25781107e-01 -1.92434311e-01]\\n [-4.13200080e-01 6.43507600e-01 -4.32981879e-01 ... 7.52745569e-02\\n 4.05040056e-01 -2.92723596e-01]\\n [-5.08693814e-01 7.07601190e-01 -4.20951635e-01 ... 1.04043037e-02\\n 3.87613952e-01 -2.56244481e-01]\\n ...\\n [-4.62354958e-01 6.37909293e-01 -3.75672787e-01 ... 4.36854362e-03\\n 3.45437586e-01 -2.26462051e-01]\\n [-5.25030494e-01 5.88392317e-01 -2.46465072e-01 ... -1.27238512e-01\\n 2.13837355e-01 -8.98284614e-02]\\n [-3.39070499e-01 6.06849134e-01 -4.59667653e-01 ... 1.38362765e-01\\n 4.35750186e-01 -3.37155759e-01]]\\n\\n ...\\n\\n [[-1.80023760e-01 -2.04962850e-01 4.54223275e-01 ... -4.39002693e-01\\n -4.60308641e-01 4.69647795e-01]\\n [-3.61009240e-02 3.46753567e-01 -4.22667176e-01 ... 2.89008379e-01\\n 4.16580796e-01 -3.83065075e-01]\\n [-1.97503224e-01 2.04578102e-01 -7.05133975e-02 ... -6.41571060e-02\\n 5.84497154e-02 -1.31680667e-02]\\n ...\\n [ 6.29594445e-01 -2.10933590e+00 2.15497446e+00 ... -1.21205044e+00\\n -2.09823871e+00 1.83500791e+00]\\n [ 6.24921799e-01 -2.09842682e+00 2.14526725e+00 ... -1.20766854e+00\\n -2.08889318e+00 1.82722878e+00]\\n [ 8.55360699e+00 -6.76110506e+00 2.73621976e-01 ... 4.81894445e+00\\n 2.22493500e-01 -2.01234460e+00]]\\n\\n [[ 6.28618002e-01 -1.64117575e-01 -4.20674622e-01 ... 6.77641809e-01\\n 4.52959955e-01 -5.57350397e-01]\\n [-5.37976146e-01 6.62559867e-01 -3.31567317e-01 ... -7.23793134e-02\\n 2.97386676e-01 -1.65452838e-01]\\n [ 8.36412668e-01 -3.35356057e-01 -4.04769182e-01 ... 7.87914932e-01\\n 4.49194461e-01 -5.97636402e-01]\\n ...\\n [-1.32435262e-01 4.79223609e-01 -5.00355184e-01 ... 2.89488912e-01\\n 4.87974793e-01 -4.29705858e-01]\\n [ 9.67554951e+00 -7.69631195e+00 3.73595059e-01 ... 5.40399551e+00\\n 1.88200951e-01 -2.21676683e+00]\\n [-3.34489554e-01 1.41441345e-01 1.52162671e-01 ... -3.07970345e-01\\n -1.70021206e-01 2.29982585e-01]]\\n\\n [[-5.73506176e-01 8.37986112e-01 -5.27873397e-01 ... 5.08383326e-02\\n 4.89783496e-01 -3.38394195e-01]\\n [-1.21431410e-01 4.68201816e-01 -4.96924907e-01 ... 2.93429136e-01\\n 4.85211879e-01 -4.29435134e-01]\\n [-4.99263555e-01 5.34260869e-01 -2.00916573e-01 ... -1.45544931e-01\\n 1.70206934e-01 -5.43444455e-02]\\n ...\\n [ 5.05807877e-01 -8.23336840e-02 -4.04350072e-01 ... 5.93589127e-01\\n 4.29704130e-01 -5.09643853e-01]\\n [-6.71721458e-01 9.28758919e-01 -5.48419893e-01 ... 8.27892870e-03\\n 5.04468620e-01 -3.31455648e-01]\\n [ 4.47143412e+00 -3.35836935e+00 -9.01285410e-02 ... 2.69024301e+00\\n 3.47266555e-01 -1.26855779e+00]]]] vs tflite_result=[[[[-1.4258870e-01 4.4390613e-01 -4.4326755e-01 ... 2.4163373e-01\\n 4.3084195e-01 -3.7398458e-01]\\n [-4.3964982e-01 5.5269313e-01 -2.8584164e-01 ... -4.8233725e-02\\n 2.5776726e-01 -1.4903089e-01]\\n [-1.1179039e-01 4.1624728e-01 -4.3789172e-01 ... 2.5576267e-01\\n 4.2729408e-01 -3.7715167e-01]\\n ...\\n [-3.1222239e-01 6.2450385e-01 -5.1030469e-01 ... 1.9128124e-01\\n 4.8745668e-01 -3.9130858e-01]\\n [-5.4456913e-01 6.3649696e-01 -2.9035234e-01 ... -1.0649611e-01\\n 2.5618160e-01 -1.2541966e-01]\\n [-2.7416372e-01 4.8438025e-01 -3.6332729e-01 ... 1.0574977e-01\\n 3.4406722e-01 -2.6486048e-01]]\\n\\n [[-2.4070942e-01 5.6660587e-01 -5.0620061e-01 ... 2.3023726e-01\\n 4.8751763e-01 -4.0644553e-01]\\n [-5.5791312e-01 7.0427150e-01 -3.6658210e-01 ... -5.8382221e-02\\n 3.3091947e-01 -1.9269648e-01]\\n [-5.5700350e-01 7.4456239e-01 -4.2087471e-01 ... -1.8003114e-02\\n 3.8475040e-01 -2.4337198e-01]\\n ...\\n [ 3.2370314e-01 8.8525474e-02 -4.4582897e-01 ... 5.1716077e-01\\n 4.6028316e-01 -4.9992132e-01]\\n [-7.8478158e-02 4.1895992e-01 -4.7529775e-01 ... 3.0276448e-01\\n 4.6626785e-01 -4.2072654e-01]\\n [-3.8183290e-01 2.5751221e-01 4.6469748e-02 ... -2.5818634e-01\\n -6.8060935e-02 1.4434543e-01]]\\n\\n [[-5.3630388e-01 6.8284601e-01 -3.6013585e-01 ... -5.0431535e-02\\n 3.2578111e-01 -1.9243431e-01]\\n [-4.1320011e-01 6.4350760e-01 -4.3298191e-01 ... 7.5274557e-02\\n 4.0504006e-01 -2.9272363e-01]\\n [-5.0869381e-01 7.0760125e-01 -4.2095163e-01 ... 1.0404289e-02\\n 3.8761395e-01 -2.5624445e-01]\\n ...\\n [-4.6235496e-01 6.3790929e-01 -3.7567282e-01 ... 4.3685548e-03\\n 3.4543759e-01 -2.2646205e-01]\\n [-5.2503049e-01 5.8839238e-01 -2.4646513e-01 ... -1.2723847e-01\\n 2.1383741e-01 -8.9828506e-02]\\n [-3.3907056e-01 6.0684919e-01 -4.5966765e-01 ... 1.3836275e-01\\n 4.3575019e-01 -3.3715576e-01]]\\n\\n ...\\n\\n [[-1.8002376e-01 -2.0496285e-01 4.5422316e-01 ... -4.3900269e-01\\n -4.6030858e-01 4.6964785e-01]\\n [-3.6100924e-02 3.4675357e-01 -4.2266718e-01 ... 2.8900838e-01\\n 4.1658083e-01 -3.8306510e-01]\\n [-1.9750324e-01 2.0457810e-01 -7.0513427e-02 ... -6.4157099e-02\\n 5.8449715e-02 -1.3168067e-02]\\n ...\\n [ 6.2959445e-01 -2.1093359e+00 2.1549742e+00 ... -1.2120504e+00\\n -2.0982387e+00 1.8350079e+00]\\n [ 6.2492168e-01 -2.0984268e+00 2.1452668e+00 ... -1.2076684e+00\\n -2.0888929e+00 1.8272285e+00]\\n [ 8.5536060e+00 -6.7611046e+00 2.7362186e-01 ... 4.8189440e+00\\n 2.2249353e-01 -2.0123446e+00]]\\n\\n [[ 6.2861800e-01 -1.6411757e-01 -4.2067462e-01 ... 6.7764181e-01\\n 4.5295995e-01 -5.5735040e-01]\\n [-5.3797615e-01 6.6255987e-01 -3.3156732e-01 ... -7.2379321e-02\\n 2.9738668e-01 -1.6545282e-01]\\n [ 8.3641267e-01 -3.3535618e-01 -4.0476918e-01 ... 7.8791493e-01\\n 4.4919446e-01 -5.9763640e-01]\\n ...\\n [-1.3243538e-01 4.7922373e-01 -5.0035524e-01 ... 2.8948885e-01\\n 4.8797479e-01 -4.2970586e-01]\\n [ 9.6755476e+00 -7.6963100e+00 3.7359476e-01 ... 5.4039946e+00\\n 1.8820101e-01 -2.2167664e+00]\\n [-3.3448958e-01 1.4144140e-01 1.5216261e-01 ... -3.0797035e-01\\n -1.7002115e-01 2.2998253e-01]]\\n\\n [[-5.7350618e-01 8.3798611e-01 -5.2787340e-01 ... 5.0838351e-02\\n 4.8978353e-01 -3.3839419e-01]\\n [-1.2143147e-01 4.6820188e-01 -4.9692491e-01 ... 2.9342908e-01\\n 4.8521188e-01 -4.2943513e-01]\\n [-4.9926355e-01 5.3426087e-01 -2.0091659e-01 ... -1.4554493e-01\\n 1.7020695e-01 -5.4344445e-02]\\n ...\\n [ 5.0580800e-01 -8.2333684e-02 -4.0435010e-01 ... 5.9358925e-01\\n 4.2970419e-01 -5.0964397e-01]\\n [-6.7172146e-01 9.2875892e-01 -5.4841989e-01 ... 8.2789287e-03\\n 5.0446862e-01 -3.3145565e-01]\\n [ 4.4714332e+00 -3.3583684e+00 -9.0128660e-02 ... 2.6902425e+00\\n 3.4726658e-01 -1.2685575e+00]]]]')\n+| ppo | FAIL | ValueError('Numerical difference: jax_result=[[-2.0793679 -2.079479 -2.0793972 -2.0794969 -2.0793874 -2.0794647\\n -2.0794334 -2.0795062]] vs tflite_result=[[-2.0794415 -2.0794415 -2.0794415 -2.0794415 -2.0794415 -2.0794415\\n -2.0794415 -2.0794415]]')\n| seq2seq | SUCCESS |\n| sst2 | SUCCESS |\n| vae | SUCCESS |\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/examples_converter.py",
"new_path": "jax/experimental/jax2tf/examples_eval/examples_converter.py",
"diff": "@@ -86,8 +86,14 @@ def make_module(spec: all_examples.ModuleSpec) -> ModuleToConvert:\ndef apply(variables, inputs):\nreplace_map.update({Arg.VARS: variables, Arg.INPUT: inputs})\n+ mutable = spec.apply_kwargs.get(\"mutable\", None)\nresult = module.apply(*replace(spec.apply_args),\n**replace(spec.apply_kwargs))\n+ # If any variables are mutable, `apply` returns a pair\n+ # `(output, mutated_vars)`. In that case we only return the output.\n+ if mutable:\n+ return result[0]\n+ else:\nreturn result\nreturn ModuleToConvert(spec.input_shape, apply, variables, spec.dtype)\n"
}
] | Python | Apache License 2.0 | google/jax | Add numerical comparison for jax2tf -> TFLite |
260,456 | 11.11.2021 17:02:59 | 28,800 | e511b280d8fcb286f1759c2ac84eb6ee594177fb | fix for translation to cudaDataType | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/cusparse.cc",
"new_path": "jaxlib/cusparse.cc",
"diff": "@@ -59,7 +59,7 @@ cusparseIndexType_t DtypeToCuSparseIndexType(const py::dtype& np_type) {\ncudaDataType DtypeToCudaDataType(const py::dtype& np_type) {\nstatic auto* types =\nnew absl::flat_hash_map<std::pair<char, int>, cudaDataType>({\n- {{'f', 2}, CUDA_R_16F}, {{'f', 4}, CUDA_R_32F}, {{'f', 4}, CUDA_R_32F},\n+ {{'f', 2}, CUDA_R_16F}, {{'c', 4}, CUDA_C_16F}, {{'f', 4}, CUDA_R_32F},\n{{'c', 8}, CUDA_C_32F}, {{'f', 8}, CUDA_R_64F},\n{{'c', 16}, CUDA_C_64F}, {{'i', 1}, CUDA_R_8I},\n{{'u', 1}, CUDA_R_8U}, {{'i', 4}, CUDA_R_32I},\n"
}
] | Python | Apache License 2.0 | google/jax | fix for translation to cudaDataType |
260,496 | 15.11.2021 12:30:50 | -3,600 | 2c17076fb4e10fc614b9f3b56bdd07b1664e81dc | Fix incorrect param ordering | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"new_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"diff": "@@ -95,7 +95,7 @@ def jax2tf_to_tflite(module: examples_converter.ModuleToConvert):\noutputs = tuple(interpreter.tensor(out[\"index\"]) for out in output_details)\n# Generate random data and get outputs from TFLite and JAX.\n- input_data = _get_random_data(module.input_shape, module.dtype)\n+ input_data = _get_random_data(module.dtype, module.input_shape)\ninterpreter.set_tensor(inputs['index'], input_data)\ninterpreter.invoke()\ntflite_results = tuple(output() for output in outputs)\n"
}
] | Python | Apache License 2.0 | google/jax | Fix incorrect param ordering |
260,496 | 15.11.2021 13:29:52 | -3,600 | 775236aba6f5e0cb9cfe04492ee342e6d104863a | Update PPO shapes fixing numerical diff | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/all_examples.py",
"new_path": "jax/experimental/jax2tf/examples_eval/all_examples.py",
"diff": "@@ -117,7 +117,11 @@ def _flax_examples():\n'ppo':\nModuleSpec(\nmodule_path='ppo.models.ActorCritic',\n- input_shape=(1, 8, 8, 4),\n+ # TODO(marcvanzee): We get numerical differences if we run this\n+ # for input shapes (1, 8, 8, 4). conv_general_dilated then returns\n+ # only zeros for TFLite, but not for JAX. We should investigate\n+ # and fix this.\n+ input_shape=(1, 84, 84, 4),\nmodule_kwargs=dict(num_outputs=8)),\n'seq2seq':\nModuleSpec(\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"new_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"diff": "@@ -17,7 +17,7 @@ These exampls are representative for what the average ML researcher is intereste\n| mnist | SUCCESS |\n| nlp_seq | SUCCESS |\n| pixelcnn++ | FAIL | ValueError('Numerical difference: jax_result=[[[[-1.42588705e-01 4.43906128e-01 -4.43267524e-01 ... 2.41633713e-01\\n 4.30841953e-01 -3.73984545e-01]\\n [-4.39649850e-01 5.52693188e-01 -2.85841674e-01 ... -4.82337102e-02\\n 2.57767290e-01 -1.49030924e-01]\\n [-1.11790448e-01 4.16247308e-01 -4.37891722e-01 ... 2.55762637e-01\\n 4.27294075e-01 -3.77151638e-01]\\n ...\\n [-3.12222362e-01 6.24503791e-01 -5.10304689e-01 ... 1.91281274e-01\\n 4.87456709e-01 -3.91308606e-01]\\n [-5.44569135e-01 6.36496902e-01 -2.90352285e-01 ... -1.06496125e-01\\n 2.56181568e-01 -1.25419632e-01]\\n [-2.74163693e-01 4.84380186e-01 -3.63327265e-01 ... 1.05749786e-01\\n 3.44067216e-01 -2.64860481e-01]]\\n\\n [[-2.40709454e-01 5.66605926e-01 -5.06200612e-01 ... 2.30237216e-01\\n 4.87517625e-01 -4.06445533e-01]\\n [-5.57913125e-01 7.04271495e-01 -3.66582096e-01 ... -5.83822057e-02\\n 3.30919504e-01 -1.92696482e-01]\\n [-5.57003498e-01 7.44562387e-01 -4.20874745e-01 ... -1.80031136e-02\\n 3.84750396e-01 -2.43371978e-01]\\n ...\\n [ 3.23703378e-01 8.85252953e-02 -4.45828974e-01 ... 5.17160952e-01\\n 4.60283160e-01 -4.99921381e-01]\\n [-7.84780085e-02 4.18959796e-01 -4.75297749e-01 ... 3.02764535e-01\\n 4.66267854e-01 -4.20726597e-01]\\n [-3.81832868e-01 2.57512122e-01 4.64698970e-02 ... -2.58186400e-01\\n -6.80610538e-02 1.44345522e-01]]\\n\\n [[-5.36303878e-01 6.82846010e-01 -3.60135853e-01 ... -5.04315346e-02\\n 3.25781107e-01 -1.92434311e-01]\\n [-4.13200080e-01 6.43507600e-01 -4.32981879e-01 ... 7.52745569e-02\\n 4.05040056e-01 -2.92723596e-01]\\n [-5.08693814e-01 7.07601190e-01 -4.20951635e-01 ... 1.04043037e-02\\n 3.87613952e-01 -2.56244481e-01]\\n ...\\n [-4.62354958e-01 6.37909293e-01 -3.75672787e-01 ... 4.36854362e-03\\n 3.45437586e-01 -2.26462051e-01]\\n [-5.25030494e-01 5.88392317e-01 -2.46465072e-01 ... -1.27238512e-01\\n 2.13837355e-01 -8.98284614e-02]\\n [-3.39070499e-01 6.06849134e-01 -4.59667653e-01 ... 1.38362765e-01\\n 4.35750186e-01 -3.37155759e-01]]\\n\\n ...\\n\\n [[-1.80023760e-01 -2.04962850e-01 4.54223275e-01 ... -4.39002693e-01\\n -4.60308641e-01 4.69647795e-01]\\n [-3.61009240e-02 3.46753567e-01 -4.22667176e-01 ... 2.89008379e-01\\n 4.16580796e-01 -3.83065075e-01]\\n [-1.97503224e-01 2.04578102e-01 -7.05133975e-02 ... -6.41571060e-02\\n 5.84497154e-02 -1.31680667e-02]\\n ...\\n [ 6.29594445e-01 -2.10933590e+00 2.15497446e+00 ... -1.21205044e+00\\n -2.09823871e+00 1.83500791e+00]\\n [ 6.24921799e-01 -2.09842682e+00 2.14526725e+00 ... -1.20766854e+00\\n -2.08889318e+00 1.82722878e+00]\\n [ 8.55360699e+00 -6.76110506e+00 2.73621976e-01 ... 4.81894445e+00\\n 2.22493500e-01 -2.01234460e+00]]\\n\\n [[ 6.28618002e-01 -1.64117575e-01 -4.20674622e-01 ... 6.77641809e-01\\n 4.52959955e-01 -5.57350397e-01]\\n [-5.37976146e-01 6.62559867e-01 -3.31567317e-01 ... -7.23793134e-02\\n 2.97386676e-01 -1.65452838e-01]\\n [ 8.36412668e-01 -3.35356057e-01 -4.04769182e-01 ... 7.87914932e-01\\n 4.49194461e-01 -5.97636402e-01]\\n ...\\n [-1.32435262e-01 4.79223609e-01 -5.00355184e-01 ... 2.89488912e-01\\n 4.87974793e-01 -4.29705858e-01]\\n [ 9.67554951e+00 -7.69631195e+00 3.73595059e-01 ... 5.40399551e+00\\n 1.88200951e-01 -2.21676683e+00]\\n [-3.34489554e-01 1.41441345e-01 1.52162671e-01 ... -3.07970345e-01\\n -1.70021206e-01 2.29982585e-01]]\\n\\n [[-5.73506176e-01 8.37986112e-01 -5.27873397e-01 ... 5.08383326e-02\\n 4.89783496e-01 -3.38394195e-01]\\n [-1.21431410e-01 4.68201816e-01 -4.96924907e-01 ... 2.93429136e-01\\n 4.85211879e-01 -4.29435134e-01]\\n [-4.99263555e-01 5.34260869e-01 -2.00916573e-01 ... -1.45544931e-01\\n 1.70206934e-01 -5.43444455e-02]\\n ...\\n [ 5.05807877e-01 -8.23336840e-02 -4.04350072e-01 ... 5.93589127e-01\\n 4.29704130e-01 -5.09643853e-01]\\n [-6.71721458e-01 9.28758919e-01 -5.48419893e-01 ... 8.27892870e-03\\n 5.04468620e-01 -3.31455648e-01]\\n [ 4.47143412e+00 -3.35836935e+00 -9.01285410e-02 ... 2.69024301e+00\\n 3.47266555e-01 -1.26855779e+00]]]] vs tflite_result=[[[[-1.4258870e-01 4.4390613e-01 -4.4326755e-01 ... 2.4163373e-01\\n 4.3084195e-01 -3.7398458e-01]\\n [-4.3964982e-01 5.5269313e-01 -2.8584164e-01 ... -4.8233725e-02\\n 2.5776726e-01 -1.4903089e-01]\\n [-1.1179039e-01 4.1624728e-01 -4.3789172e-01 ... 2.5576267e-01\\n 4.2729408e-01 -3.7715167e-01]\\n ...\\n [-3.1222239e-01 6.2450385e-01 -5.1030469e-01 ... 1.9128124e-01\\n 4.8745668e-01 -3.9130858e-01]\\n [-5.4456913e-01 6.3649696e-01 -2.9035234e-01 ... -1.0649611e-01\\n 2.5618160e-01 -1.2541966e-01]\\n [-2.7416372e-01 4.8438025e-01 -3.6332729e-01 ... 1.0574977e-01\\n 3.4406722e-01 -2.6486048e-01]]\\n\\n [[-2.4070942e-01 5.6660587e-01 -5.0620061e-01 ... 2.3023726e-01\\n 4.8751763e-01 -4.0644553e-01]\\n [-5.5791312e-01 7.0427150e-01 -3.6658210e-01 ... -5.8382221e-02\\n 3.3091947e-01 -1.9269648e-01]\\n [-5.5700350e-01 7.4456239e-01 -4.2087471e-01 ... -1.8003114e-02\\n 3.8475040e-01 -2.4337198e-01]\\n ...\\n [ 3.2370314e-01 8.8525474e-02 -4.4582897e-01 ... 5.1716077e-01\\n 4.6028316e-01 -4.9992132e-01]\\n [-7.8478158e-02 4.1895992e-01 -4.7529775e-01 ... 3.0276448e-01\\n 4.6626785e-01 -4.2072654e-01]\\n [-3.8183290e-01 2.5751221e-01 4.6469748e-02 ... -2.5818634e-01\\n -6.8060935e-02 1.4434543e-01]]\\n\\n [[-5.3630388e-01 6.8284601e-01 -3.6013585e-01 ... -5.0431535e-02\\n 3.2578111e-01 -1.9243431e-01]\\n [-4.1320011e-01 6.4350760e-01 -4.3298191e-01 ... 7.5274557e-02\\n 4.0504006e-01 -2.9272363e-01]\\n [-5.0869381e-01 7.0760125e-01 -4.2095163e-01 ... 1.0404289e-02\\n 3.8761395e-01 -2.5624445e-01]\\n ...\\n [-4.6235496e-01 6.3790929e-01 -3.7567282e-01 ... 4.3685548e-03\\n 3.4543759e-01 -2.2646205e-01]\\n [-5.2503049e-01 5.8839238e-01 -2.4646513e-01 ... -1.2723847e-01\\n 2.1383741e-01 -8.9828506e-02]\\n [-3.3907056e-01 6.0684919e-01 -4.5966765e-01 ... 1.3836275e-01\\n 4.3575019e-01 -3.3715576e-01]]\\n\\n ...\\n\\n [[-1.8002376e-01 -2.0496285e-01 4.5422316e-01 ... -4.3900269e-01\\n -4.6030858e-01 4.6964785e-01]\\n [-3.6100924e-02 3.4675357e-01 -4.2266718e-01 ... 2.8900838e-01\\n 4.1658083e-01 -3.8306510e-01]\\n [-1.9750324e-01 2.0457810e-01 -7.0513427e-02 ... -6.4157099e-02\\n 5.8449715e-02 -1.3168067e-02]\\n ...\\n [ 6.2959445e-01 -2.1093359e+00 2.1549742e+00 ... -1.2120504e+00\\n -2.0982387e+00 1.8350079e+00]\\n [ 6.2492168e-01 -2.0984268e+00 2.1452668e+00 ... -1.2076684e+00\\n -2.0888929e+00 1.8272285e+00]\\n [ 8.5536060e+00 -6.7611046e+00 2.7362186e-01 ... 4.8189440e+00\\n 2.2249353e-01 -2.0123446e+00]]\\n\\n [[ 6.2861800e-01 -1.6411757e-01 -4.2067462e-01 ... 6.7764181e-01\\n 4.5295995e-01 -5.5735040e-01]\\n [-5.3797615e-01 6.6255987e-01 -3.3156732e-01 ... -7.2379321e-02\\n 2.9738668e-01 -1.6545282e-01]\\n [ 8.3641267e-01 -3.3535618e-01 -4.0476918e-01 ... 7.8791493e-01\\n 4.4919446e-01 -5.9763640e-01]\\n ...\\n [-1.3243538e-01 4.7922373e-01 -5.0035524e-01 ... 2.8948885e-01\\n 4.8797479e-01 -4.2970586e-01]\\n [ 9.6755476e+00 -7.6963100e+00 3.7359476e-01 ... 5.4039946e+00\\n 1.8820101e-01 -2.2167664e+00]\\n [-3.3448958e-01 1.4144140e-01 1.5216261e-01 ... -3.0797035e-01\\n -1.7002115e-01 2.2998253e-01]]\\n\\n [[-5.7350618e-01 8.3798611e-01 -5.2787340e-01 ... 5.0838351e-02\\n 4.8978353e-01 -3.3839419e-01]\\n [-1.2143147e-01 4.6820188e-01 -4.9692491e-01 ... 2.9342908e-01\\n 4.8521188e-01 -4.2943513e-01]\\n [-4.9926355e-01 5.3426087e-01 -2.0091659e-01 ... -1.4554493e-01\\n 1.7020695e-01 -5.4344445e-02]\\n ...\\n [ 5.0580800e-01 -8.2333684e-02 -4.0435010e-01 ... 5.9358925e-01\\n 4.2970419e-01 -5.0964397e-01]\\n [-6.7172146e-01 9.2875892e-01 -5.4841989e-01 ... 8.2789287e-03\\n 5.0446862e-01 -3.3145565e-01]\\n [ 4.4714332e+00 -3.3583684e+00 -9.0128660e-02 ... 2.6902425e+00\\n 3.4726658e-01 -1.2685575e+00]]]]')\n-| ppo | FAIL | ValueError('Numerical difference: jax_result=[[-2.0793679 -2.079479 -2.0793972 -2.0794969 -2.0793874 -2.0794647\\n -2.0794334 -2.0795062]] vs tflite_result=[[-2.0794415 -2.0794415 -2.0794415 -2.0794415 -2.0794415 -2.0794415\\n -2.0794415 -2.0794415]]')\n+| ppo | FAIL | SUCCESS |\n| seq2seq | SUCCESS |\n| sst2 | SUCCESS |\n| vae | SUCCESS |\n"
}
] | Python | Apache License 2.0 | google/jax | Update PPO shapes fixing numerical diff |
260,496 | 15.11.2021 15:19:19 | -3,600 | 8bb2c766c76c1ac51c1f5bbcac849a68e740a3fa | Change random data and updates table | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"new_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"diff": "@@ -55,7 +55,7 @@ def _get_random_data(dtype: jnp.dtype, shape: Tuple[int, ...]) -> Any:\nif np.issubdtype(dtype, np.integer):\nreturn np.random.randint(0, 100, size=shape, dtype=dtype)\nelif np.issubdtype(dtype, np.floating):\n- return np.array(np.random.uniform(size=shape), dtype=dtype)\n+ return np.array(np.random.uniform(size=shape), dtype=dtype) * 100\nelif dtype == np.bool:\nreturn np.random.choice(a=[False, True], size=shape)\nelse:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"new_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"diff": "# Evaluation Results\n-*Last generated on: 2021-11-11* (YYYY-MM-DD)\n+*Last generated on: 2021-11-15* (YYYY-MM-DD)\n## jax2tf --> TFLite\n@@ -13,14 +13,14 @@ These exampls are representative for what the average ML researcher is intereste\n| Example | Result | Error Message |\n| --- | --- | --- |\n| imagenet | SUCCESS |\n-| lm1b | FAIL | ValueError('Numerical difference: jax_result=[[[ 1.0656209e+00 9.3210316e-01 -7.5562042e-01 5.7160920e-01\\n 4.7576640e-04 -8.3388436e-01 -6.6835815e-01 8.1217813e-01]]\\n\\n [[ 1.0656208e+00 9.3210304e-01 -7.5562042e-01 5.7160914e-01\\n 4.7582600e-04 -8.3388436e-01 -6.6835815e-01 8.1217837e-01]]] vs tflite_result=[[[ 1.0656209e+00 9.3210316e-01 -7.5562030e-01 5.7160920e-01\\n 4.7570679e-04 -8.3388448e-01 -6.6835809e-01 8.1217837e-01]]\\n\\n [[ 1.0656209e+00 9.3210316e-01 -7.5562030e-01 5.7160920e-01\\n 4.7570679e-04 -8.3388448e-01 -6.6835809e-01 8.1217837e-01]]]')\n+| lm1b | SUCCESS |\n| mnist | SUCCESS |\n| nlp_seq | SUCCESS |\n-| pixelcnn++ | FAIL | ValueError('Numerical difference: jax_result=[[[[-1.42588705e-01 4.43906128e-01 -4.43267524e-01 ... 2.41633713e-01\\n 4.30841953e-01 -3.73984545e-01]\\n [-4.39649850e-01 5.52693188e-01 -2.85841674e-01 ... -4.82337102e-02\\n 2.57767290e-01 -1.49030924e-01]\\n [-1.11790448e-01 4.16247308e-01 -4.37891722e-01 ... 2.55762637e-01\\n 4.27294075e-01 -3.77151638e-01]\\n ...\\n [-3.12222362e-01 6.24503791e-01 -5.10304689e-01 ... 1.91281274e-01\\n 4.87456709e-01 -3.91308606e-01]\\n [-5.44569135e-01 6.36496902e-01 -2.90352285e-01 ... -1.06496125e-01\\n 2.56181568e-01 -1.25419632e-01]\\n [-2.74163693e-01 4.84380186e-01 -3.63327265e-01 ... 1.05749786e-01\\n 3.44067216e-01 -2.64860481e-01]]\\n\\n [[-2.40709454e-01 5.66605926e-01 -5.06200612e-01 ... 2.30237216e-01\\n 4.87517625e-01 -4.06445533e-01]\\n [-5.57913125e-01 7.04271495e-01 -3.66582096e-01 ... -5.83822057e-02\\n 3.30919504e-01 -1.92696482e-01]\\n [-5.57003498e-01 7.44562387e-01 -4.20874745e-01 ... -1.80031136e-02\\n 3.84750396e-01 -2.43371978e-01]\\n ...\\n [ 3.23703378e-01 8.85252953e-02 -4.45828974e-01 ... 5.17160952e-01\\n 4.60283160e-01 -4.99921381e-01]\\n [-7.84780085e-02 4.18959796e-01 -4.75297749e-01 ... 3.02764535e-01\\n 4.66267854e-01 -4.20726597e-01]\\n [-3.81832868e-01 2.57512122e-01 4.64698970e-02 ... -2.58186400e-01\\n -6.80610538e-02 1.44345522e-01]]\\n\\n [[-5.36303878e-01 6.82846010e-01 -3.60135853e-01 ... -5.04315346e-02\\n 3.25781107e-01 -1.92434311e-01]\\n [-4.13200080e-01 6.43507600e-01 -4.32981879e-01 ... 7.52745569e-02\\n 4.05040056e-01 -2.92723596e-01]\\n [-5.08693814e-01 7.07601190e-01 -4.20951635e-01 ... 1.04043037e-02\\n 3.87613952e-01 -2.56244481e-01]\\n ...\\n [-4.62354958e-01 6.37909293e-01 -3.75672787e-01 ... 4.36854362e-03\\n 3.45437586e-01 -2.26462051e-01]\\n [-5.25030494e-01 5.88392317e-01 -2.46465072e-01 ... -1.27238512e-01\\n 2.13837355e-01 -8.98284614e-02]\\n [-3.39070499e-01 6.06849134e-01 -4.59667653e-01 ... 1.38362765e-01\\n 4.35750186e-01 -3.37155759e-01]]\\n\\n ...\\n\\n [[-1.80023760e-01 -2.04962850e-01 4.54223275e-01 ... -4.39002693e-01\\n -4.60308641e-01 4.69647795e-01]\\n [-3.61009240e-02 3.46753567e-01 -4.22667176e-01 ... 2.89008379e-01\\n 4.16580796e-01 -3.83065075e-01]\\n [-1.97503224e-01 2.04578102e-01 -7.05133975e-02 ... -6.41571060e-02\\n 5.84497154e-02 -1.31680667e-02]\\n ...\\n [ 6.29594445e-01 -2.10933590e+00 2.15497446e+00 ... -1.21205044e+00\\n -2.09823871e+00 1.83500791e+00]\\n [ 6.24921799e-01 -2.09842682e+00 2.14526725e+00 ... -1.20766854e+00\\n -2.08889318e+00 1.82722878e+00]\\n [ 8.55360699e+00 -6.76110506e+00 2.73621976e-01 ... 4.81894445e+00\\n 2.22493500e-01 -2.01234460e+00]]\\n\\n [[ 6.28618002e-01 -1.64117575e-01 -4.20674622e-01 ... 6.77641809e-01\\n 4.52959955e-01 -5.57350397e-01]\\n [-5.37976146e-01 6.62559867e-01 -3.31567317e-01 ... -7.23793134e-02\\n 2.97386676e-01 -1.65452838e-01]\\n [ 8.36412668e-01 -3.35356057e-01 -4.04769182e-01 ... 7.87914932e-01\\n 4.49194461e-01 -5.97636402e-01]\\n ...\\n [-1.32435262e-01 4.79223609e-01 -5.00355184e-01 ... 2.89488912e-01\\n 4.87974793e-01 -4.29705858e-01]\\n [ 9.67554951e+00 -7.69631195e+00 3.73595059e-01 ... 5.40399551e+00\\n 1.88200951e-01 -2.21676683e+00]\\n [-3.34489554e-01 1.41441345e-01 1.52162671e-01 ... -3.07970345e-01\\n -1.70021206e-01 2.29982585e-01]]\\n\\n [[-5.73506176e-01 8.37986112e-01 -5.27873397e-01 ... 5.08383326e-02\\n 4.89783496e-01 -3.38394195e-01]\\n [-1.21431410e-01 4.68201816e-01 -4.96924907e-01 ... 2.93429136e-01\\n 4.85211879e-01 -4.29435134e-01]\\n [-4.99263555e-01 5.34260869e-01 -2.00916573e-01 ... -1.45544931e-01\\n 1.70206934e-01 -5.43444455e-02]\\n ...\\n [ 5.05807877e-01 -8.23336840e-02 -4.04350072e-01 ... 5.93589127e-01\\n 4.29704130e-01 -5.09643853e-01]\\n [-6.71721458e-01 9.28758919e-01 -5.48419893e-01 ... 8.27892870e-03\\n 5.04468620e-01 -3.31455648e-01]\\n [ 4.47143412e+00 -3.35836935e+00 -9.01285410e-02 ... 2.69024301e+00\\n 3.47266555e-01 -1.26855779e+00]]]] vs tflite_result=[[[[-1.4258870e-01 4.4390613e-01 -4.4326755e-01 ... 2.4163373e-01\\n 4.3084195e-01 -3.7398458e-01]\\n [-4.3964982e-01 5.5269313e-01 -2.8584164e-01 ... -4.8233725e-02\\n 2.5776726e-01 -1.4903089e-01]\\n [-1.1179039e-01 4.1624728e-01 -4.3789172e-01 ... 2.5576267e-01\\n 4.2729408e-01 -3.7715167e-01]\\n ...\\n [-3.1222239e-01 6.2450385e-01 -5.1030469e-01 ... 1.9128124e-01\\n 4.8745668e-01 -3.9130858e-01]\\n [-5.4456913e-01 6.3649696e-01 -2.9035234e-01 ... -1.0649611e-01\\n 2.5618160e-01 -1.2541966e-01]\\n [-2.7416372e-01 4.8438025e-01 -3.6332729e-01 ... 1.0574977e-01\\n 3.4406722e-01 -2.6486048e-01]]\\n\\n [[-2.4070942e-01 5.6660587e-01 -5.0620061e-01 ... 2.3023726e-01\\n 4.8751763e-01 -4.0644553e-01]\\n [-5.5791312e-01 7.0427150e-01 -3.6658210e-01 ... -5.8382221e-02\\n 3.3091947e-01 -1.9269648e-01]\\n [-5.5700350e-01 7.4456239e-01 -4.2087471e-01 ... -1.8003114e-02\\n 3.8475040e-01 -2.4337198e-01]\\n ...\\n [ 3.2370314e-01 8.8525474e-02 -4.4582897e-01 ... 5.1716077e-01\\n 4.6028316e-01 -4.9992132e-01]\\n [-7.8478158e-02 4.1895992e-01 -4.7529775e-01 ... 3.0276448e-01\\n 4.6626785e-01 -4.2072654e-01]\\n [-3.8183290e-01 2.5751221e-01 4.6469748e-02 ... -2.5818634e-01\\n -6.8060935e-02 1.4434543e-01]]\\n\\n [[-5.3630388e-01 6.8284601e-01 -3.6013585e-01 ... -5.0431535e-02\\n 3.2578111e-01 -1.9243431e-01]\\n [-4.1320011e-01 6.4350760e-01 -4.3298191e-01 ... 7.5274557e-02\\n 4.0504006e-01 -2.9272363e-01]\\n [-5.0869381e-01 7.0760125e-01 -4.2095163e-01 ... 1.0404289e-02\\n 3.8761395e-01 -2.5624445e-01]\\n ...\\n [-4.6235496e-01 6.3790929e-01 -3.7567282e-01 ... 4.3685548e-03\\n 3.4543759e-01 -2.2646205e-01]\\n [-5.2503049e-01 5.8839238e-01 -2.4646513e-01 ... -1.2723847e-01\\n 2.1383741e-01 -8.9828506e-02]\\n [-3.3907056e-01 6.0684919e-01 -4.5966765e-01 ... 1.3836275e-01\\n 4.3575019e-01 -3.3715576e-01]]\\n\\n ...\\n\\n [[-1.8002376e-01 -2.0496285e-01 4.5422316e-01 ... -4.3900269e-01\\n -4.6030858e-01 4.6964785e-01]\\n [-3.6100924e-02 3.4675357e-01 -4.2266718e-01 ... 2.8900838e-01\\n 4.1658083e-01 -3.8306510e-01]\\n [-1.9750324e-01 2.0457810e-01 -7.0513427e-02 ... -6.4157099e-02\\n 5.8449715e-02 -1.3168067e-02]\\n ...\\n [ 6.2959445e-01 -2.1093359e+00 2.1549742e+00 ... -1.2120504e+00\\n -2.0982387e+00 1.8350079e+00]\\n [ 6.2492168e-01 -2.0984268e+00 2.1452668e+00 ... -1.2076684e+00\\n -2.0888929e+00 1.8272285e+00]\\n [ 8.5536060e+00 -6.7611046e+00 2.7362186e-01 ... 4.8189440e+00\\n 2.2249353e-01 -2.0123446e+00]]\\n\\n [[ 6.2861800e-01 -1.6411757e-01 -4.2067462e-01 ... 6.7764181e-01\\n 4.5295995e-01 -5.5735040e-01]\\n [-5.3797615e-01 6.6255987e-01 -3.3156732e-01 ... -7.2379321e-02\\n 2.9738668e-01 -1.6545282e-01]\\n [ 8.3641267e-01 -3.3535618e-01 -4.0476918e-01 ... 7.8791493e-01\\n 4.4919446e-01 -5.9763640e-01]\\n ...\\n [-1.3243538e-01 4.7922373e-01 -5.0035524e-01 ... 2.8948885e-01\\n 4.8797479e-01 -4.2970586e-01]\\n [ 9.6755476e+00 -7.6963100e+00 3.7359476e-01 ... 5.4039946e+00\\n 1.8820101e-01 -2.2167664e+00]\\n [-3.3448958e-01 1.4144140e-01 1.5216261e-01 ... -3.0797035e-01\\n -1.7002115e-01 2.2998253e-01]]\\n\\n [[-5.7350618e-01 8.3798611e-01 -5.2787340e-01 ... 5.0838351e-02\\n 4.8978353e-01 -3.3839419e-01]\\n [-1.2143147e-01 4.6820188e-01 -4.9692491e-01 ... 2.9342908e-01\\n 4.8521188e-01 -4.2943513e-01]\\n [-4.9926355e-01 5.3426087e-01 -2.0091659e-01 ... -1.4554493e-01\\n 1.7020695e-01 -5.4344445e-02]\\n ...\\n [ 5.0580800e-01 -8.2333684e-02 -4.0435010e-01 ... 5.9358925e-01\\n 4.2970419e-01 -5.0964397e-01]\\n [-6.7172146e-01 9.2875892e-01 -5.4841989e-01 ... 8.2789287e-03\\n 5.0446862e-01 -3.3145565e-01]\\n [ 4.4714332e+00 -3.3583684e+00 -9.0128660e-02 ... 2.6902425e+00\\n 3.4726658e-01 -1.2685575e+00]]]]')\n-| ppo | FAIL | SUCCESS |\n+| pixelcnn++ | FAIL | ValueError('Numerical difference: jax_result=[[[[-1.42588705e-01 4.43906128e-01 -4.43267524e-01 ... 2.41633713e-01\\n ... ]]]] vs tflite_result=[[[[-1.42588705e-01 4.43906128e-01 -4.43267554e-01 ... 2.41633728e-01\\n ...]]]]')\n+| ppo | SUCCESS |\n| seq2seq | SUCCESS |\n| sst2 | SUCCESS |\n-| vae | SUCCESS |\n+| vae | FAIL | ValueError('Numerical difference: jax_result=[[[[1.00000000e+00 2.50768606e-09 8.24737523e-09 ... 0.00000000e+00\\n ...]]]] vs tflite_result=[[[[1.00000000e+00 2.50769538e-09 8.24742230e-09 ... 2.93873588e-39\\n...]]]]')\n| wmt | SUCCESS |\n## jax2tf --> TFjs\n"
}
] | Python | Apache License 2.0 | google/jax | Change random data and updates table |
260,335 | 15.11.2021 13:24:33 | 28,800 | 57f4fc9bbb68442f0ef0ef27f04a4a14b49bdf7d | update readme to focus on most active libraries | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "| [**Reference docs**](https://jax.readthedocs.io/en/latest/)\n-**News:** [JAX tops largest-scale MLPerf Training 0.7 benchmarks!](https://cloud.google.com/blog/products/ai-machine-learning/google-breaks-ai-performance-records-in-mlperf-with-worlds-fastest-training-supercomputer)\n-\n## What is JAX?\nJAX is [Autograd](https://github.com/hips/autograd) and [XLA](https://www.tensorflow.org/xla),\n@@ -497,19 +495,16 @@ source](https://jax.readthedocs.io/en/latest/developer.html#building-from-source\nMultiple Google research groups develop and share libraries for training neural\nnetworks in JAX. If you want a fully featured library for neural network\ntraining with examples and how-to guides, try\n-[Flax](https://github.com/google/flax). Another option is\n-[Trax](https://github.com/google/trax), a combinator-based framework focused on\n-ease-of-use and end-to-end single-command examples, especially for sequence\n-models and reinforcement learning. Finally,\n-[Objax](https://github.com/google/objax) is a minimalist object-oriented\n-framework with a PyTorch-like interface.\n-\n-DeepMind has open-sourced an\n-[ecosystem of libraries around JAX](https://deepmind.com/blog/article/using-jax-to-accelerate-our-research) including [Haiku](https://github.com/deepmind/dm-haiku) for neural\n-network modules, [Optax](https://github.com/deepmind/optax) for gradient\n-processing and optimization, [RLax](https://github.com/deepmind/rlax) for RL\n-algorithms, and [chex](https://github.com/deepmind/chex) for reliable code and\n-testing. (Watch the NeurIPS 2020 JAX Ecosystem at DeepMind talk [here](https://www.youtube.com/watch?v=iDxJxIyzSiM))\n+[Flax](https://github.com/google/flax).\n+\n+In addition, DeepMind has open-sourced an [ecosystem of libraries around\n+JAX](https://deepmind.com/blog/article/using-jax-to-accelerate-our-research)\n+including [Haiku](https://github.com/deepmind/dm-haiku) for neural network\n+modules, [Optax](https://github.com/deepmind/optax) for gradient processing and\n+optimization, [RLax](https://github.com/deepmind/rlax) for RL algorithms, and\n+[chex](https://github.com/deepmind/chex) for reliable code and testing. (Watch\n+the NeurIPS 2020 JAX Ecosystem at DeepMind talk\n+[here](https://www.youtube.com/watch?v=iDxJxIyzSiM))\n## Citing JAX\n"
}
] | Python | Apache License 2.0 | google/jax | update readme to focus on most active libraries |
260,447 | 15.11.2021 22:36:27 | 28,800 | 21fa3b3f3b05b01938898942e1ae2941de739b9f | Change QR import in lax.linalg.qdwh. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/qdwh.py",
"new_path": "jax/_src/lax/qdwh.py",
"diff": "@@ -37,7 +37,7 @@ def _use_qr(u, params):\na, b, c = params\nm, n = u.shape\ny = jnp.concatenate([jnp.sqrt(c) * u, jnp.eye(n)])\n- q, _ = jnp.linalg.qr(y)\n+ q, _ = lax_linalg.qr(y, full_matrices=False)\nq1 = q[:m, :]\nq2 = (q[m:, :]).T.conj()\ne = b / c\n"
}
] | Python | Apache License 2.0 | google/jax | Change QR import in lax.linalg.qdwh. |
260,335 | 16.11.2021 11:21:27 | 28,800 | 5d35b8a11903f8722519834f3748ee35e4cfee58 | add donated_invars to xla.XlaComputation | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -488,17 +488,21 @@ class Lowered:\nquerying properties of lowered computations across JAX's various\nlowering paths (``jit``, ``pmap``, etc.).\n\"\"\"\n- __slots__ = ['in_tree', 'out_tree', '_lowering', '_no_kwargs']\n+ __slots__ = ['in_tree', 'out_tree', 'donate_argnums', '_lowering',\n+ '_no_kwargs']\nin_tree: PyTreeDef\nout_tree: PyTreeDef\n+ donate_argnums: Tuple[int]\n_lowering: Union[xla.XlaComputation, pxla.MeshComputation]\n_no_kwargs: bool\n- def __init__(self, lowering, in_tree, out_tree, no_kwargs=False):\n+ def __init__(self, lowering, in_tree, out_tree, donate_argnums,\n+ no_kwargs=False):\nself._lowering = lowering\nself.in_tree = in_tree\nself.out_tree = out_tree\n+ self.donate_argnums = donate_argnums\nself._no_kwargs = no_kwargs\ndef _xla_computation(self):\n@@ -508,7 +512,8 @@ class Lowered:\ndef compile(self) -> 'Compiled':\nreturn Compiled(\n- self._lowering.compile(), self.in_tree, self.out_tree, self._no_kwargs)\n+ self._lowering.compile(), self.in_tree, self.out_tree,\n+ self.donate_argnums, self._no_kwargs)\nclass Compiled:\n@@ -519,17 +524,21 @@ class Compiled:\ncommon API for querying properties of compiled computations across\nJAX's various compilation paths and backends.\n\"\"\"\n- __slots__ = ['in_tree', 'out_tree', '_executable', '_no_kwargs']\n+ __slots__ = ['in_tree', 'out_tree', 'donate_argnums', '_executable',\n+ '_no_kwargs']\nin_tree: PyTreeDef\nout_tree: PyTreeDef\n+ donate_argnums: Tuple[int]\n_executable: Union[xla.XlaCompiledComputation, pxla.MeshExecutable]\n_no_kwargs: bool\n- def __init__(self, executable, in_tree, out_tree, no_kwargs=False):\n+ def __init__(self, executable, in_tree, out_tree, donate_argnums,\n+ no_kwargs=False):\nself._executable = executable\nself.in_tree = in_tree\nself.out_tree = out_tree\n+ self.donate_argnums = donate_argnums\nself._no_kwargs = no_kwargs\ndef _xla_executable(self):\n@@ -589,7 +598,7 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\narg_specs = unsafe_map(arg_spec, args_flat)\ncomputation = xla.lower_xla_callable(\nflat_fun, device, backend, name, donated_invars, *arg_specs)\n- return Lowered(computation, in_tree, out_tree())\n+ return Lowered(computation, in_tree, out_tree(), donate_argnums)\nreturn lower\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/pjit.py",
"new_path": "jax/experimental/pjit.py",
"diff": "@@ -229,23 +229,24 @@ def pjit(fun: Callable,\ndonated_invars=donated_invars,\nname=flat_fun.__name__,\npositional_semantics=maps._positional_semantics)\n- return args_flat, params, in_tree, out_tree()\n+ return args_flat, params, in_tree, out_tree(), donate_argnums\n@wraps(fun)\ndef wrapped(*args, **kwargs):\nfor arg in tree_leaves(args):\n_check_arg(arg)\n- args_flat, params, _, out_tree = infer_params(*args, **kwargs)\n+ args_flat, params, _, out_tree, _ = infer_params(*args, **kwargs)\nout = pjit_p.bind(*args_flat, **params)\nreturn tree_unflatten(out_tree, out)\ndef lower(*args, **kwargs):\n- args_flat, params, in_tree, out_tree = infer_params(*args, **kwargs)\n+ args_flat, params, in_tree, out_tree, donate_argnums = \\\n+ infer_params(*args, **kwargs)\nlowering = _pjit_lower(\nparams['jaxpr'], params['in_axis_resources'],\nparams['out_axis_resources'], params['resource_env'],\nparams['donated_invars'], params['name'], maps._positional_semantics)\n- return Lowered(lowering, in_tree, out_tree, no_kwargs=True)\n+ return Lowered(lowering, in_tree, out_tree, donate_argnums, no_kwargs=True)\nwrapped.lower = lower\nreturn wrapped\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1723,15 +1723,16 @@ def lower_mesh_computation(\nbuilt = c.Build(out_tuple)\nreturn MeshComputation(\n- built, mesh, local_in_untiled_avals,\n+ built, donated_invars, mesh, local_in_untiled_avals,\nlocal_out_untiled_avals, (out_jaxpr_avals if spmd_lowering else None),\nin_axes, out_axes, spmd_lowering, tuple_args)\nclass MeshComputation:\n- def __init__(self, hlo, *compile_args):\n+ def __init__(self, hlo, donated_invars, *compile_args):\nself._executable = None\nself._hlo = hlo\n+ self._donated_invars = donated_invars\nself.compile_args = compile_args\ndef hlo(self):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -800,7 +800,7 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\n# and don't need to evaluate their arguments.\nif not jaxpr.eqns:\nreturn XlaComputation(\n- name, None, True, jaxpr, consts, device, abstract_args, out_avals,\n+ name, None, True, None, jaxpr, consts, device, abstract_args, out_avals,\nkept_var_idx)\nif not _on_exit:\n@@ -850,8 +850,8 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\n\", \".join(unused_donations)))\nbuilt = c.build(output)\nreturn XlaComputation(\n- name, built, False, nreps, device, backend, tuple_args, abstract_args,\n- out_avals, kept_var_idx)\n+ name, built, False, donated_invars, nreps, device, backend, tuple_args,\n+ abstract_args, out_avals, kept_var_idx)\ndef compile_or_get_cached(backend, computation, compile_options):\n@@ -875,11 +875,14 @@ class XlaComputation:\nname: str\n_is_trivial: bool\n_executable: Optional['XlaCompiledComputation']\n+ _donated_invars: Optional[Sequence[bool]]\n- def __init__(self, name: str, hlo, is_trivial: bool, *compile_args):\n+ def __init__(self, name: str, hlo, is_trivial: bool,\n+ donated_invars: Optional[Sequence[bool]], *compile_args):\nself.name = name\nself._hlo = hlo\nself._is_trivial = is_trivial\n+ self._donated_invars = donated_invars\nself._executable = None\nself.compile_args = compile_args\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -780,6 +780,14 @@ class CPPJitTest(jtu.BufferDonationTestCase):\nf_exe = self.jit(f).lower(1., 1.).compile()\nself.assertAllClose(f_exe(1., 1.), 1.)\n+ def test_jit_lower_donate_argnums_available(self):\n+ def f(*args):\n+ x, *_ = args\n+ return x\n+ f_low = self.jit(f, donate_argnums=(0,)).lower(1., 1.)\n+ f_com = f_low.compile()\n+ f_low.donate_argnums == f_com.donate_argnums == (0,)\n+\nclass PythonJitTest(CPPJitTest):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pjit_test.py",
"new_path": "tests/pjit_test.py",
"diff": "@@ -385,7 +385,19 @@ class PJitTest(jtu.BufferDonationTestCase):\ndef testLowerWithDuckTyping(self):\nx = jax.ShapeDtypeStruct((2, 2), jnp.float32)\n# Make sure this doesn't crash\n- pjit(lambda x: x + 4, in_axis_resources=P('x'), out_axis_resources=P('x')).lower(x)\n+ pjit(lambda x: x + 4,\n+ in_axis_resources=P('x'), out_axis_resources=P('x')).lower(x)\n+\n+ @jtu.with_mesh([('x', 2)])\n+ def testLowerDonateArgnumsAvailable(self):\n+ x = jax.ShapeDtypeStruct((2, 2), jnp.float32)\n+ def f(*args):\n+ x, *_ = args\n+ return x\n+ f_low = pjit(f, donate_argnums=(0,),\n+ in_axis_resources=P('x'), out_axis_resources=P('x')).lower(x)\n+ f_com = f_low.compile()\n+ f_low.donate_argnums == f_com.donate_argnums == (0,)\ndef testInfeed(self):\ndevices = np.array(jax.local_devices())\n"
}
] | Python | Apache License 2.0 | google/jax | add donated_invars to xla.XlaComputation
Co-authored-by: Brennan Saeta <saeta@google.com> |
260,424 | 25.10.2021 15:53:52 | -3,600 | e14fea3b637ed4a67a2530106e1bf34c38676037 | Overload jnp ops which are polymorphic to an array's value and support PRNGKeys. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -30,7 +30,7 @@ import collections\nfrom functools import partial\nimport operator\nimport types\n-from typing import Sequence, FrozenSet, Optional, Tuple, Union\n+from typing import Sequence, FrozenSet, Optional, Tuple, Union, Set, Type, Callable\nfrom textwrap import dedent as _dedent\nimport warnings\n@@ -553,6 +553,12 @@ def _arraylike(x):\nreturn (isinstance(x, np.ndarray) or isinstance(x, ndarray) or\nhasattr(x, '__jax_array__') or isscalar(x))\n+\n+def _stackable(*args):\n+ return _all(type(arg) in stackables for arg in args)\n+stackables: Set[Type] = set()\n+_register_stackable: Callable[[Type], None] = stackables.add\n+\ndef _check_arraylike(fun_name, *args):\n\"\"\"Check if all args fit JAX's definition of arraylike.\"\"\"\nassert isinstance(fun_name, str), f\"fun_name must be a string. Got {fun_name}\"\n@@ -1718,7 +1724,7 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):\n@_wraps(np.reshape, lax_description=_ARRAY_VIEW_DOC)\ndef reshape(a, newshape, order=\"C\"):\n- _check_arraylike(\"reshape\", a)\n+ _stackable(a) or _check_arraylike(\"reshape\", a)\ntry:\nreturn a.reshape(newshape, order=order) # forward to method for ndarrays\nexcept AttributeError:\n@@ -1761,7 +1767,7 @@ def _transpose(a, *args):\n@_wraps(np.ravel, lax_description=_ARRAY_VIEW_DOC)\n@partial(jit, static_argnames=('order',), inline=True)\ndef ravel(a, order=\"C\"):\n- _check_arraylike(\"ravel\", a)\n+ _stackable(a) or _check_arraylike(\"ravel\", a)\nif order == \"K\":\nraise NotImplementedError(\"Ravel not implemented for order='K'.\")\nreturn reshape(a, (size(a),), order)\n@@ -2224,6 +2230,8 @@ def broadcast_arrays(*args):\nThe JAX version does not necessarily return a view of the input.\n\"\"\")\ndef broadcast_to(arr, shape):\n+ if hasattr(arr, \"broadcast_to\"):\n+ return arr.broadcast_to(shape)\narr = arr if isinstance(arr, ndarray) else array(arr)\nshape = (shape,) if ndim(shape) == 0 else shape\nshape = canonicalize_shape(shape) # check that shape is concrete\n@@ -3361,7 +3369,7 @@ def stack(arrays, axis: int = 0, out=None):\n@_wraps(np.tile)\ndef tile(A, reps):\n- _check_arraylike(\"tile\", A)\n+ _stackable(A) or _check_arraylike(\"tile\", A)\ntry:\niter(reps)\nexcept TypeError:\n@@ -3392,13 +3400,15 @@ def _concatenate_array(arr, axis: int):\ndef concatenate(arrays, axis: int = 0):\nif isinstance(arrays, (np.ndarray, ndarray)):\nreturn _concatenate_array(arrays, axis)\n- _check_arraylike(\"concatenate\", *arrays)\n+ _stackable(*arrays) or _check_arraylike(\"concatenate\", *arrays)\nif not len(arrays):\nraise ValueError(\"Need at least one array to concatenate.\")\nif ndim(arrays[0]) == 0:\nraise ValueError(\"Zero-dimensional arrays cannot be concatenated.\")\nif axis is None:\nreturn concatenate([ravel(a) for a in arrays], axis=0)\n+ if hasattr(arrays[0], \"concatenate\"):\n+ return arrays[0].concatenate(arrays[1:], axis)\naxis = _canonicalize_axis(axis, ndim(arrays[0]))\narrays = _promote_dtypes(*arrays)\n# lax.concatenate can be slow to compile for wide concatenations, so form a\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/prng.py",
"new_path": "jax/_src/prng.py",
"diff": "@@ -30,6 +30,7 @@ from jax.interpreters import xla\nfrom jax._src.api import jit, vmap\nfrom jax._src.lib import xla_client\nfrom jax._src.lib import cuda_prng\n+from jax._src.numpy.lax_numpy import _register_stackable\nimport jax._src.pretty_printer as pp\nfrom jax._src.util import prod\n@@ -189,6 +190,19 @@ class PRNGKeyArray:\ndef _split(self, num: int) -> 'PRNGKeyArray':\nreturn PRNGKeyArray(self.impl, self.impl.split(self._keys, num))\n+ def reshape(self, newshape, order=None):\n+ reshaped_keys = jnp.reshape(self._keys, (*newshape, -1), order=order)\n+ return PRNGKeyArray(self.impl, reshaped_keys)\n+\n+ def concatenate(self, key_arrs, axis):\n+ axis = axis % len(self.shape)\n+ arrs = [self._keys, *[k._keys for k in key_arrs]]\n+ return PRNGKeyArray(self.impl, jnp.stack(arrs, axis))\n+\n+ def broadcast_to(self, shape):\n+ new_shape = tuple(shape)+(self._keys.shape[-1],)\n+ return PRNGKeyArray(self.impl, jnp.broadcast_to(self._keys, new_shape))\n+\ndef __repr__(self):\narr_shape = self._shape\npp_keys = pp.text('shape = ') + pp.text(str(arr_shape))\n@@ -201,6 +215,7 @@ class PRNGKeyArray:\ndef seed_with_impl(impl: PRNGImpl, seed: int) -> PRNGKeyArray:\nreturn PRNGKeyArray(impl, impl.seed(seed))\n+_register_stackable(PRNGKeyArray)\n# -- threefry2x32 PRNG implementation --\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -1237,6 +1237,49 @@ class LaxRandomWithUnsafeRBGPRNGTest(LaxRandomWithRBGPRNGTest):\ndef seed_prng(self, seed):\nreturn prng.seed_with_impl(prng.unsafe_rbg_prng_impl, seed)\n+@skipIf(not config.jax_enable_custom_prng,\n+ 'custom PRNG tests require config.jax_enable_custom_prng')\n+class JnpWithPRNGKeyArrayTest(jtu.JaxTestCase):\n+ def test_reshape(self):\n+ key = random.PRNGKey(123)\n+ keys = random.split(key, 4)\n+ keys = jnp.reshape(keys, (2, 2))\n+ self.assertEqual(keys.shape, (2, 2))\n+\n+ def test_tile(self):\n+ key = random.PRNGKey(123)\n+ keys = jnp.tile(key, 3)\n+ self.assertEqual(keys.shape, (3,))\n+\n+ def test_concatenate(self):\n+ key = random.PRNGKey(123)\n+ keys = random.split(key, 2)\n+ keys = jnp.concatenate([keys, keys, keys], axis=0)\n+ self.assertEqual(keys.shape, (3, 2))\n+\n+ def test_broadcast_to(self):\n+ key = random.PRNGKey(123)\n+ keys = jnp.broadcast_to(key, (3,))\n+ self.assertEqual(keys.shape, (3,))\n+\n+ def test_broadcast_arrays(self):\n+ key = random.PRNGKey(123)\n+ keys = jax.random.split(key, 3)\n+ key, _ = jnp.broadcast_arrays(key, keys)\n+ self.assertEqual(key.shape, (3,))\n+\n+ def test_append(self):\n+ key = random.PRNGKey(123)\n+ keys = jnp.append(key, key)\n+ self.assertEqual(keys.shape, (2, 1))\n+\n+ def test_ravel(self):\n+ key = random.PRNGKey(123)\n+ keys = jax.random.split(key, 4)\n+ keys = jnp.reshape(keys, (2, 2))\n+ keys = jnp.ravel(keys)\n+ self.assertEqual(keys.shape, (4,))\n+\ndef _sampler_unimplemented_with_rbg(*args, **kwargs):\n# TODO(mattjj): enable these tests if/when RngBitGenerator supports them\nraise SkipTest('8- and 16-bit types not supported with RBG PRNG')\n"
}
] | Python | Apache License 2.0 | google/jax | Overload jnp ops which are polymorphic to an array's value and support PRNGKeys. |
260,496 | 17.11.2021 15:09:06 | -3,600 | 06d5e99ddfaf652fc9a4d4ce1f5b4d9c39970075 | Add numerical comparison with TF | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"new_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"diff": "@@ -62,6 +62,22 @@ def _get_random_data(dtype: jnp.dtype, shape: Tuple[int, ...]) -> Any:\nraise ValueError(f\"Unsupported dtype for numerical comparison: {dtype}\")\n+def _all_close(jax_results, tf_results, tf_description, rtol=1e-05):\n+ if len(tf_results) != len(jax_results):\n+ raise ValueError(f\"Numerical difference: returned output tuples lengths do \"\n+ f\"not match: {tf_description} length vs JAX length: \"\n+ f\"{len(tf_results)} != {len(jax_results)}\")\n+\n+ for jax_result, tf_result in zip(jax_results, tf_results):\n+ for jax_array, tf_array in zip(jax_result, tf_result):\n+ jax_array = np.asarray(jax_array)\n+ tf_array = np.asarray(tf_array)\n+ if not np.allclose(jax_array, tf_array, rtol):\n+ raise ValueError(f\"Numerical difference JAX vs {tf_description}: \"\n+ f\"JAX result={jax_result} vs \"\n+ f\"{tf_description} result={tf_result}\")\n+\n+\ndef jax2tf_to_tflite(module: examples_converter.ModuleToConvert):\n\"\"\"Converts the given `module` using the TFLite converter.\"\"\"\napply = functools.partial(module.apply, module.variables)\n@@ -74,10 +90,17 @@ def jax2tf_to_tflite(module: examples_converter.ModuleToConvert):\nname='input')\n],\nautograph=False)\n+ tf_predict_concrete = tf_predict.get_concrete_function()\n+\n+ input_data = _get_random_data(module.dtype, module.input_shape)\n+\n+ # First compare JAX output with TF output.\n+ jax_results = apply(input_data)\n+ _all_close(jax_results, tf_predict_concrete(input_data), \"TF\")\n# Convert TF function to TF Lite format.\nconverter = tf.lite.TFLiteConverter.from_concrete_functions(\n- [tf_predict.get_concrete_function()])\n+ [tf_predict_concrete], tf_predict)\nconverter.target_spec.supported_ops = [\ntf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\ntf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.\n@@ -94,27 +117,12 @@ def jax2tf_to_tflite(module: examples_converter.ModuleToConvert):\noutput_details = interpreter.get_output_details()\noutputs = tuple(interpreter.tensor(out[\"index\"]) for out in output_details)\n- # Generate random data and get outputs from TFLite and JAX.\n- input_data = _get_random_data(module.dtype, module.input_shape)\ninterpreter.set_tensor(inputs['index'], input_data)\ninterpreter.invoke()\ntflite_results = tuple(output() for output in outputs)\n- jax_results = apply(input_data)\n- # If the model returns a single value, put the JAX return value in a tuple so\n- # we can compare it with the TFLite output, which is always a tuple.\nif len(tflite_results) == 1:\n- jax_results = (jax_results,)\n+ # If we only have one result, don't use a tuple since JAX also doesn't.\n+ tflite_results = tflite_results[0]\n- if len(tflite_results) != len(jax_results):\n- raise ValueError(f\"Numerical difference: returned output tuples lengths do \"\n- f\"not match: TFLite length vs JAX length: {len(tflite_results)} != \"\n- f\"{len(jax_results)}\")\n-\n- for jax_result, tflite_result in zip(jax_results, tflite_results):\n- for jax_array, tflite_array in zip(jax_result, tflite_result):\n- jax_array = np.asarray(jax_array)\n- tflite_array = np.asarray(tflite_array)\n- if not np.allclose(jax_array, tflite_array, 1e-05):\n- raise ValueError(f\"Numerical difference: jax_result={jax_result} vs \"\n- f\"tflite_result={tflite_result}\")\n+ _all_close(jax_results, tflite_results, \"TFLite\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"new_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"diff": "# Evaluation Results\n-*Last generated on: 2021-11-15* (YYYY-MM-DD)\n+*Last generated on: 2021-11-17* (YYYY-MM-DD)\n## jax2tf --> TFLite\n@@ -16,11 +16,11 @@ These exampls are representative for what the average ML researcher is intereste\n| lm1b | SUCCESS |\n| mnist | SUCCESS |\n| nlp_seq | SUCCESS |\n-| pixelcnn++ | FAIL | ValueError('Numerical difference: jax_result=[[[[-1.42588705e-01 4.43906128e-01 -4.43267524e-01 ... 2.41633713e-01\\n ... ]]]] vs tflite_result=[[[[-1.42588705e-01 4.43906128e-01 -4.43267554e-01 ... 2.41633728e-01\\n ...]]]]')\n+| pixelcnn++ | FAIL | ValueError('Numerical difference JAX vs TF: JAX result=[[[-1.42588705e-01 4.43906128e-01 -4.43267524e-01 ... 2.41633713e-01\\n 4.30841953e-01 -3.73984545e-01]\\n [-5.50750673e-01 8.27922702e-01 -5.37640810e-01 ... 7.13608935e-02\\n 5.00771403... (CROPPED)\n| ppo | SUCCESS |\n| seq2seq | SUCCESS |\n| sst2 | SUCCESS |\n-| vae | FAIL | ValueError('Numerical difference: jax_result=[[[[1.00000000e+00 2.50768606e-09 8.24737523e-09 ... 0.00000000e+00\\n ...]]]] vs tflite_result=[[[[1.00000000e+00 2.50769538e-09 8.24742230e-09 ... 2.93873588e-39\\n...]]]]')\n+| vae | FAIL | ValueError('Numerical difference JAX vs TF: JAX result=[[[1.00000000e+00 2.96458746e-09 2.83802848e-08 ... 0.00000000e+00\\n 9.99999881e-01 6.08000756e-19]\\n [9.81082678e-01 6.93151236e-01 7.65325581e-08 ... 1.04346945e-07\\n 7.08327889e-01 3.9745... (CROPPED)\n| wmt | SUCCESS |\n## jax2tf --> TFjs\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/examples_converter.py",
"new_path": "jax/experimental/jax2tf/examples_eval/examples_converter.py",
"diff": "@@ -212,6 +212,8 @@ def test_convert(converter_name: str,\nlogging.info('OK!')\nexcept Exception as e: # pylint: disable=broad-except\nerror_msg = repr(e)\n+ if len(error_msg) > 250:\n+ error_msg = error_msg[:250] + \"... (CROPPED)\"\nlogging.info('ERROR %s', error_msg)\nerrors[example_name] = error_msg\n"
}
] | Python | Apache License 2.0 | google/jax | Add numerical comparison with TF |
260,411 | 05.11.2021 17:03:46 | -7,200 | 75155f5eda4b298cbb9ac28a9ff0a2bd0176c24b | [shape_poly] Refactor arange and image_resize for shape polymorphism
Small refactoring to jax.image.resize to make it compatible with
shape polymorphismin jax2tf. In the process added also support for
jnp.arange([dim_poly]). Note that the underlying lax.iota already
supported shape polymorphism. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/image/scale.py",
"new_path": "jax/_src/image/scale.py",
"diff": "@@ -44,7 +44,8 @@ def _fill_triangle_kernel(x):\nreturn jnp.maximum(0, 1 - jnp.abs(x))\n-def compute_weight_mat(input_size: int, output_size: int, scale,\n+def compute_weight_mat(input_size: core.DimSize,\n+ output_size: core.DimSize, scale,\ntranslation,\nkernel: Callable,\nantialias: bool):\n@@ -70,13 +71,15 @@ def compute_weight_mat(input_size: int, output_size: int, scale,\n# Zero out weights where the sample location is completely outside the input\n# range.\n# Note sample_f has already had the 0.5 removed, hence the weird range below.\n+ input_size_minus_0_5 = core.dimension_as_value(input_size) - 0.5\nreturn jnp.where(\njnp.logical_and(sample_f >= -0.5,\n- sample_f <= input_size - 0.5)[jnp.newaxis, :], weights, 0)\n+ sample_f <= input_size_minus_0_5)[jnp.newaxis, :], weights, 0)\n-def _scale_and_translate(x, output_shape, spatial_dims, scale, translation,\n- kernel, antialias, precision):\n+def _scale_and_translate(x, output_shape: core.Shape,\n+ spatial_dims: Sequence[int], scale, translation,\n+ kernel, antialias: bool, precision):\ninput_shape = x.shape\nassert len(input_shape) == len(output_shape)\nassert len(spatial_dims) == len(scale)\n@@ -134,7 +137,7 @@ _kernels = {\n# scale and translation here are scalar elements of an np.array, what is the\n# correct type annotation?\n-def scale_and_translate(image, shape: Sequence[int],\n+def scale_and_translate(image, shape: core.Shape,\nspatial_dims: Sequence[int],\nscale, translation,\nmethod: Union[str, ResizeMethod],\n@@ -221,22 +224,24 @@ def scale_and_translate(image, shape: Sequence[int],\nkernel, antialias, precision)\n-def _resize_nearest(x, output_shape):\n+def _resize_nearest(x, output_shape: core.Shape):\ninput_shape = x.shape\nassert len(input_shape) == len(output_shape)\n- spatial_dims, = np.nonzero(np.not_equal(input_shape, output_shape))\n+ spatial_dims = tuple(i for i in range(len(input_shape))\n+ if not core.symbolic_equal_dim(input_shape[i], output_shape[i]))\nfor d in spatial_dims:\nm = input_shape[d]\nn = output_shape[d]\n- offsets = (np.arange(n) + 0.5) * m / n\n+ offsets = (jnp.arange(n) + 0.5) * core.dimension_as_value(m) / core.dimension_as_value(n)\n+ offsets = jnp.floor(offsets).astype(np.int32)\nindices = [slice(None)] * len(input_shape)\n- indices[d] = np.floor(offsets).astype(np.int32)\n+ indices[d] = offsets\nx = x[tuple(indices)]\nreturn x\n@partial(jit, static_argnums=(1, 2, 3, 4))\n-def _resize(image, shape: Sequence[int], method: Union[str, ResizeMethod],\n+def _resize(image, shape: core.Shape, method: Union[str, ResizeMethod],\nantialias: bool, precision):\nif len(shape) != image.ndim:\nmsg = ('shape must have length equal to the number of dimensions of x; '\n@@ -254,15 +259,16 @@ def _resize(image, shape: Sequence[int], method: Union[str, ResizeMethod],\n# Skip dimensions that have scale=1 and translation=0, this is only possible\n# since all of the current resize methods (kernels) are interpolating, so the\n# output = input under an identity warp.\n- spatial_dims = tuple(np.nonzero(np.not_equal(image.shape, shape))[0])\n- scale = [1.0 if shape[d] == 0 else float(shape[d]) / image.shape[d]\n+ spatial_dims = tuple(i for i in range(len(shape))\n+ if not core.symbolic_equal_dim(image.shape[i], shape[i]))\n+ scale = [1.0 if core.symbolic_equal_dim(shape[d], 0) else core.dimension_as_value(shape[d]) / core.dimension_as_value(image.shape[d])\nfor d in spatial_dims]\nreturn _scale_and_translate(image, shape, spatial_dims,\nscale, [0.] * len(spatial_dims), kernel,\nantialias, precision)\n-def resize(image, shape: Sequence[int], method: Union[str, ResizeMethod],\n+def resize(image, shape: core.Shape, method: Union[str, ResizeMethod],\nantialias: bool = True,\nprecision = lax.Precision.HIGHEST):\n\"\"\"Image resize.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3755,20 +3755,22 @@ def identity(n, dtype=None):\n@_wraps(np.arange)\n-def arange(start, stop=None, step=None, dtype=None):\n+def arange(start: core.DimSize, stop: Optional[core.DimSize]=None,\n+ step: Optional[core.DimSize]=None, dtype=None):\nlax._check_user_dtype_supported(dtype, \"arange\")\nrequire = partial(core.concrete_or_error, _np_asarray)\nmsg = \"It arose in jax.numpy.arange argument `{}`.\".format\n+ dtype = dtype or _dtype(start, *(x for x in [stop, step] if x is not None))\nif stop is None and step is None:\n+ if not core.is_dim_size(start):\nstart = require(start, msg(\"stop\"))\n- dtype = dtype or _dtype(start)\n- return lax.iota(dtype, np.ceil(start).astype(int)) # avoids materializing\n+ start = np.ceil(start).astype(int)\n+\n+ return lax.iota(dtype, start)\nelse:\nstart = require(start, msg(\"start\"))\nstop = None if stop is None else require(stop, msg(\"stop\"))\nstep = None if step is None else require(step, msg(\"step\"))\n- if dtype is None:\n- dtype = _dtype(start, *(x for x in [stop, step] if x is not None))\nreturn array(np.arange(start, stop=stop, step=step, dtype=dtype))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1376,6 +1376,14 @@ def _dim_handler_and_canonical(*dlist: DimSize) -> Tuple[DimensionHandler, Tuple\nraise ValueError(msg)\nreturn next(iter(special_handlers), _dimension_handler_int), tuple(canonical)\n+def is_dim_size(v: Any) -> bool:\n+ \"\"\"Checks if a value is a DimSize.\"\"\"\n+ try:\n+ handler, _ = _dim_handler_and_canonical(v)\n+ return True\n+ except TypeError:\n+ return False\n+\ndef is_constant_dim(d: DimSize) -> bool:\nhandler, ds = _dim_handler_and_canonical(d)\nreturn handler.is_constant(*ds)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -41,10 +41,12 @@ from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, TypeVar, Uni\nimport jax\nfrom jax._src.numpy import lax_numpy\n+from jax._src import dtypes\nimport opt_einsum\nfrom jax import config\nfrom jax import core\n+\nimport numpy as np\nDimSize = core.DimSize\n@@ -448,6 +450,7 @@ class DimensionHandlerPoly(core.DimensionHandler):\nreturn _dim_as_value(d)\ncore._SPECIAL_DIMENSION_HANDLERS[_DimPolynomial] = DimensionHandlerPoly()\n+dtypes.python_scalar_dtypes[_DimPolynomial] = dtypes.python_scalar_dtypes[int]\ndef _einsum_contract_path(*operands, **kwargs):\n\"\"\"Like opt_einsum.contract_path, with support for DimPolynomial shapes.\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": "@@ -1149,6 +1149,28 @@ _POLY_SHAPE_TEST_HARNESSES = [\njax.grad(lambda x: jnp.sum(jnp.sum(x, axis=0, keepdims=0) + x)),\n[RandArg((3, 4), _f32)],\npoly_axes=[0]),\n+ _make_harness(\"arange\", \"start\",\n+ lambda op: jnp.arange(2 * op.shape[0], dtype=_f32),\n+ [RandArg((3,), _f32)],\n+ poly_axes=[0],\n+ enable_and_diable_xla=True),\n+ _make_harness(\"arange\", \"start_no_dtype\",\n+ lambda op: jnp.arange(op.shape[0]),\n+ [RandArg((3,), _f32)],\n+ poly_axes=[0],\n+ enable_and_diable_xla=True),\n+ # Reduce the poly dimension\n+ _make_harness(\"argmax\", \"0\",\n+ lambda op: lax.argmax(op, axis=0, index_dtype=np.int32),\n+ [RandArg((3, 4, 5), _f32)],\n+ poly_axes=[0],\n+ enable_and_diable_xla=True),\n+ # Reduce the non-poly dimension\n+ _make_harness(\"argmax\", \"1\",\n+ lambda op: lax.argmax(op, axis=1, index_dtype=np.int32),\n+ [RandArg((3, 4, 5), _f32)],\n+ poly_axes=[0],\n+ enable_and_diable_xla=True),\n[\n_make_harness(\"average\",\nf\"axis={axis}_weights=None\",\n@@ -1165,18 +1187,6 @@ _POLY_SHAPE_TEST_HARNESSES = [\npoly_axes=[0, 0])\nfor axis in [None, 0, 1]\n],\n- # Reduce the poly dimension\n- _make_harness(\"argmax\", \"0\",\n- lambda op: lax.argmax(op, axis=0, index_dtype=np.int32),\n- [RandArg((3, 4, 5), _f32)],\n- poly_axes=[0],\n- enable_and_diable_xla=True),\n- # Reduce the non-poly dimension\n- _make_harness(\"argmax\", \"1\",\n- lambda op: lax.argmax(op, axis=1, index_dtype=np.int32),\n- [RandArg((3, 4, 5), _f32)],\n- poly_axes=[0],\n- enable_and_diable_xla=True),\n_make_harness(\"broadcast_to\", \"\",\nlambda x: jnp.broadcast_to(x, [x.shape[0], x.shape[0], 4]),\n[RandArg((3, 4), _f32)],\n@@ -1391,8 +1401,23 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[RandArg((3, 4), _f32)],\npoly_axes=[0], enable_and_diable_xla=True,\nexpect_error=(IndexError, \"Array slice indices must have static\")),\n- _make_harness(\"index_in_dim\", \"idx=pos\",\n- lambda x: lax.index_in_dim(x, 0, axis=0, keepdims=False),\n+ _make_harness(\"image_resize\", \"linear_0\",\n+ lambda x: jax.image.resize(x, (x.shape[0], 2 * x.shape[1], 2 * x.shape[2], x.shape[3]),\n+ method=\"linear\"),\n+ [RandArg((3, 16, 32, 3), _f32)],\n+ poly_axes=[(1, 2)]),\n+ _make_harness(\"image_resize\", \"linear_to_fixed_dim\",\n+ lambda x: jax.image.resize(x, (x.shape[0], 64, 64, x.shape[3]),\n+ method=\"linear\"),\n+ [RandArg((3, 16, 32, 3), _f32)],\n+ poly_axes=[(1, 2)]),\n+ _make_harness(\"image_resize\", \"nearest_0\",\n+ lambda x: jax.image.resize(x, (x.shape[0], 2 * x.shape[1], 2 * x.shape[2], x.shape[3]),\n+ method=\"nearest\"),\n+ [RandArg((3, 5, 7, 3), _f32)],\n+ poly_axes=[(1, 2)]),\n+ _make_harness(\"index_in_dim\", \"0\",\n+ lambda x: lax.index_in_dim(x, -1, axis=0, keepdims=False),\n[RandArg((3, 4), _f32)],\npoly_axes=[0]),\n_make_harness(\"index_in_dim\", \"idx=neg\",\n@@ -1734,7 +1759,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# to parameterized below.\n@primitive_harness.parameterized(\n_flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"getitem_op=poly_idx=slice-None-1\"\n+ #one_containing=\"arange_start_no_dtype\"\n)\ndef test_prim(self, harness: Harness):\nargs = harness.dyn_args_maker(self.rng())\n"
}
] | Python | Apache License 2.0 | google/jax | [shape_poly] Refactor arange and image_resize for shape polymorphism
Bug: 8367
Small refactoring to jax.image.resize to make it compatible with
shape polymorphismin jax2tf. In the process added also support for
jnp.arange([dim_poly]). Note that the underlying lax.iota already
supported shape polymorphism. |
260,411 | 18.11.2021 10:23:53 | -7,200 | 3715fcb930d5cd9ef6a454136f442d2317a68536 | Added workaround for bug in XLA | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/image/scale.py",
"new_path": "jax/_src/image/scale.py",
"diff": "@@ -233,7 +233,9 @@ def _resize_nearest(x, output_shape: core.Shape):\nm = input_shape[d]\nn = output_shape[d]\noffsets = (jnp.arange(n) + 0.5) * core.dimension_as_value(m) / core.dimension_as_value(n)\n- offsets = jnp.floor(offsets).astype(np.int32)\n+ # TODO(b/206898375): this computation produces the wrong result on\n+ # CPU and GPU when using float64. Use float32 until the bug is fixed.\n+ offsets = jnp.floor(offsets.astype(np.float32)).astype(np.int32)\nindices = [slice(None)] * len(input_shape)\nindices[d] = offsets\nx = x[tuple(indices)]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3762,7 +3762,7 @@ def arange(start: core.DimSize, stop: Optional[core.DimSize]=None,\nmsg = \"It arose in jax.numpy.arange argument `{}`.\".format\ndtype = dtype or _dtype(start, *(x for x in [stop, step] if x is not None))\nif stop is None and step is None:\n- if not core.is_dim_size(start):\n+ if not core.is_special_dim_size(start):\nstart = require(start, msg(\"stop\"))\nstart = np.ceil(start).astype(int)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1376,13 +1376,10 @@ def _dim_handler_and_canonical(*dlist: DimSize) -> Tuple[DimensionHandler, Tuple\nraise ValueError(msg)\nreturn next(iter(special_handlers), _dimension_handler_int), tuple(canonical)\n-def is_dim_size(v: Any) -> bool:\n- \"\"\"Checks if a value is a DimSize.\"\"\"\n- try:\n- handler, _ = _dim_handler_and_canonical(v)\n- return True\n- except TypeError:\n- return False\n+def is_special_dim_size(v: Any) -> bool:\n+ \"\"\"Checks if a value is a special DimSize.\"\"\"\n+ handler = _SPECIAL_DIMENSION_HANDLERS.get(type(v))\n+ return (handler is not None)\ndef is_constant_dim(d: DimSize) -> bool:\nhandler, ds = _dim_handler_and_canonical(d)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/image_test.py",
"new_path": "tests/image_test.py",
"diff": "@@ -90,6 +90,7 @@ class ImageTest(jtu.JaxTestCase):\n\"target_shape\": target_shape,\n\"method\": method}\nfor dtype in [np.float32]\n+\nfor target_shape, image_shape in itertools.combinations_with_replacement(\n[[3, 2], [6, 4], [33, 17], [50, 39]], 2)\nfor method in [\"nearest\", \"bilinear\", \"lanczos3\", \"bicubic\"]))\n"
}
] | Python | Apache License 2.0 | google/jax | Added workaround for bug in XLA |
260,335 | 18.11.2021 13:40:25 | 28,800 | 2cb235809aeb0ee5b42ef129f7a6179d74905034 | make vmap ppermute consistent with pmap/docstring
This was a bad bug! Unfortunately our tests didn't catch it, in part
because permutations on size-two axes are either trivial or not. The
simplest test might have a size-three axis. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/parallel.py",
"new_path": "jax/_src/lax/parallel.py",
"diff": "@@ -795,7 +795,7 @@ def _ppermute_batcher(axis_size, frame_name, _, vals_in, dims_in, axis_name, per\nassert d is not batching.not_mapped\nperm_indices = np.zeros(axis_size, dtype=int)\nfor src, dst in perm:\n- perm_indices[src] = dst\n+ perm_indices[dst] = src\nreturn lax_numpy.take(v, perm_indices, d), d\ndef _collective_batcher(prim, args, dims, **params):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -1011,7 +1011,7 @@ class BatchingTest(jtu.JaxTestCase):\nrng.shuffle(perm_pairs)\nself.assertAllClose(\nvmap(lambda x: x - lax.ppermute(x, 'i', perm_pairs), axis_name='i')(x),\n- x - x[perm])\n+ x - x[np.argsort(perm)])\n@parameterized.named_parameters(\n{\"testcase_name\": f\"_split={split_axis}_concat={concat_axis}_vmap={vmap_axis}\",\n@@ -1131,8 +1131,6 @@ class BatchingTest(jtu.JaxTestCase):\njnp.ones((3, 4)))\nself.assertIn('HIGHEST', str(vmap_jaxpr))\n-\n-\ndef testPdotJvp(self):\ndef f(x, y):\nreturn lax.pdot(x, y, 'i')\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -1890,6 +1890,26 @@ class VmapPmapCollectivesTest(jtu.JaxTestCase):\nself.assertAllClose(f(jax.pmap, jax.vmap)(x, x), y)\nself.assertAllClose(f(jax.vmap, jax.pmap)(x, x), y)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_collective={}\".format(collective.__name__).replace(\" \", \"\"),\n+ \"collective\": collective}\n+ for collective in [lax.psum, lax.pmean, lax.pmax, lax.pmin])\n+ def testCollectivesWithVmap2(self, collective):\n+ def f(map1, map2):\n+ @partial(map1, axis_name='i')\n+ @partial(map2, axis_name='j')\n+ def f(x, y):\n+ return x + collective(x.dot(y), ('i', 'j'))\n+ return f\n+\n+ if jax.device_count() < 8:\n+ raise SkipTest(\"test requires at least eight devices\")\n+ x = jnp.arange(4*2*64*64).reshape(4, 2, 64, 64)\n+ y = f(jax.pmap, jax.pmap)(x, x)\n+ self.assertAllClose(f(jax.vmap, jax.vmap)(x, x), y)\n+ self.assertAllClose(f(jax.pmap, jax.vmap)(x, x), y)\n+ self.assertAllClose(f(jax.vmap, jax.pmap)(x, x), y)\n+\ndef testPPermuteWithVmap(self):\nperm = [(0, 1), (1, 0)]\n@@ -1905,6 +1925,18 @@ class VmapPmapCollectivesTest(jtu.JaxTestCase):\nx = jnp.ones((2, 2, 64, 64))\nself.assertAllClose(f(jax.pmap)(x, x), f(jax.vmap)(x, x))\n+ def testPPermuteAgreesWithVmap(self):\n+ if jax.device_count() < 3:\n+ raise SkipTest(\"test requires at least three devices\")\n+\n+ def f(x):\n+ return lax.ppermute(x, 'i', [[1, 0], [2, 1], [0, 2]])\n+\n+ xs = jnp.arange(3) * 10\n+ ys = jax.pmap(f, axis_name='i')(xs)\n+ zs = jax.vmap(f, axis_name='i')(xs)\n+ self.assertAllClose(ys, zs, check_dtypes=True)\n+\n@parameterized.named_parameters(\n{\"testcase_name\": f\"_split={split_axis}_concat={concat_axis}_vmap={vmap_axis}\",\n\"split_axis\": split_axis, \"concat_axis\": concat_axis, \"vmap_axis\": vmap_axis}\n"
}
] | Python | Apache License 2.0 | google/jax | make vmap ppermute consistent with pmap/docstring
This was a bad bug! Unfortunately our tests didn't catch it, in part
because permutations on size-two axes are either trivial or not. The
simplest test might have a size-three axis. |
260,631 | 19.11.2021 13:31:29 | 28,800 | cad3fd808d68dd12ad2bb5c32c3114af27aa1b81 | Make it easier to see what are the difference between two structures.
When structures are very large, users can end up with pages and pages describing the two structures, and finding exactly where they differ can be tricky. This change makes these differences more obvious. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow.py",
"new_path": "jax/_src/lax/control_flow.py",
"diff": "@@ -2033,6 +2033,11 @@ def _rng_bit_generator_batching_rule(batched_args, batch_dims, *, shape, dtype,\nbatching.primitive_batchers[lax.rng_bit_generator_p] = _rng_bit_generator_batching_rule\n+def _show_diff(array1, array2):\n+ if core.typematch(array1, array2):\n+ return f\"{array1}\"\n+ return f\"DIFFERENT {array1} vs. {array2}\"\n+\ndef _check_tree_and_avals(what, tree1, avals1, tree2, avals2):\n\"\"\"Raises TypeError if (tree1, avals1) does not match (tree2, avals2).\n@@ -2044,10 +2049,9 @@ def _check_tree_and_avals(what, tree1, avals1, tree2, avals2):\nraise TypeError(\nf\"{what} must have same type structure, got {tree1} and {tree2}.\")\nif not all(_map(core.typematch, avals1, avals2)):\n- raise TypeError(\n- f\"{what} must have identical types, got\\n\"\n- f\"{tree_unflatten(tree1, avals1)}\\nand\\n\"\n- f\"{tree_unflatten(tree2, avals2)}.\")\n+ diff = tree_multimap(_show_diff, tree_unflatten(tree1, avals1),\n+ tree_unflatten(tree2, avals2))\n+ raise TypeError(f\"{what} must have identical types, got\\n{diff}.\")\ndef _check_tree(func_name, expected_name, actual_tree, expected_tree, has_aux=False):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -19,7 +19,6 @@ import itertools\nimport operator\nimport re\nimport unittest\n-import textwrap\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -255,10 +254,11 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nlax.while_loop(lambda c: True, lambda c: (1., 1.), 0.)\nwith self.assertRaisesWithLiteralMatch(TypeError,\n(\"body_fun output and input must have identical types, got\\n\"\n- \"ShapedArray(bool[], weak_type=True)\\n\"\n- \"and\\n\"\n- \"ShapedArray(float32[]).\")):\n- lax.while_loop(lambda c: True, lambda c: True, np.float32(0.))\n+ \"('ShapedArray(bool[], weak_type=True)', \"\n+ \"'DIFFERENT ShapedArray(bool[], weak_type=True) vs. \"\n+ \"ShapedArray(float32[])').\")):\n+ lax.while_loop(lambda c: True, lambda c: (True, True),\n+ (np.bool_(True), np.float32(0.)))\ndef testNestedWhileWithDynamicUpdateSlice(self):\nnum = 5\n@@ -807,12 +807,10 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nf\"got {tree_util.tree_structure(2.)} and {tree_util.tree_structure((3., 3.))}.\")):\nlax.cond(True, lambda top: 2., lambda fop: (3., 3.), 1.)\nwith self.assertRaisesRegex(\n- TypeError, textwrap.dedent(\n- r\"\"\"\n- true_fun and false_fun output must have identical types, got\n- ShapedArray\\(float32\\[1\\]\\)\n- and\n- ShapedArray\\(float32\\[\\].*\\).\"\"\").strip()):\n+ TypeError,\n+ \"true_fun and false_fun output must have identical types, got\\n\"\n+ r\"DIFFERENT ShapedArray\\(float32\\[1\\]\\) vs. \"\n+ r\"ShapedArray\\(float32\\[\\].*\\).\"):\nlax.cond(True,\nlambda top: jnp.array([1.], jnp.float32),\nlambda fop: jnp.float32(1.),\n@@ -837,12 +835,10 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nf\"got {tree_util.tree_structure(2.)} and {tree_util.tree_structure((3., 3.))}.\")):\nlax.switch(1, [lambda _: 2., lambda _: (3., 3.)], 1.)\nwith self.assertRaisesRegex(\n- TypeError, textwrap.dedent(\n- r\"\"\"\n- branch 0 and 1 outputs must have identical types, got\n- ShapedArray\\(float32\\[1\\]\\)\n- and\n- ShapedArray\\(float32\\[\\].*\\).\"\"\").strip()):\n+ TypeError,\n+ \"branch 0 and 1 outputs must have identical types, got\\n\"\n+ r\"DIFFERENT ShapedArray\\(float32\\[1\\]\\) \"\n+ r\"vs. ShapedArray\\(float32\\[\\].*\\).\"):\nlax.switch(1, [lambda _: jnp.array([1.], jnp.float32),\nlambda _: jnp.float32(1.)],\n1.)\n@@ -1688,9 +1684,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nwith self.assertRaisesWithLiteralMatch(\nTypeError,\n\"scan carry output and input must have identical types, got\\n\"\n- \"ShapedArray(int32[])\\n\"\n- \"and\\n\"\n- \"ShapedArray(float32[]).\"):\n+ \"DIFFERENT ShapedArray(int32[]) vs. ShapedArray(float32[]).\"):\nlax.scan(lambda c, x: (np.int32(0), x), np.float32(1.0), a)\nwith self.assertRaisesRegex(TypeError,\nre.escape(\"scan carry output and input must have same type structure, \"\n"
}
] | Python | Apache License 2.0 | google/jax | Make it easier to see what are the difference between two structures.
When structures are very large, users can end up with pages and pages describing the two structures, and finding exactly where they differ can be tricky. This change makes these differences more obvious.
PiperOrigin-RevId: 411131921 |
260,496 | 18.11.2021 11:13:26 | -3,600 | 7b25e05fd1ea7547f165664e7ad29d2818aae8ac | Improve logics for numerical comparison | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/all_examples.py",
"new_path": "jax/experimental/jax2tf/examples_eval/all_examples.py",
"diff": "@@ -117,11 +117,10 @@ def _flax_examples():\n'ppo':\nModuleSpec(\nmodule_path='ppo.models.ActorCritic',\n- # TODO(marcvanzee): We get numerical differences if we run this\n- # for input shapes (1, 8, 8, 4). conv_general_dilated then returns\n+ # TODO(marcvanzee): This fails. conv_general_dilated then returns\n# only zeros for TFLite, but not for JAX. We should investigate\n# and fix this.\n- input_shape=(1, 84, 84, 4),\n+ input_shape=(1, 8, 8, 4),\nmodule_kwargs=dict(num_outputs=8)),\n'seq2seq':\nModuleSpec(\n@@ -139,12 +138,12 @@ def _flax_examples():\nmodule_path='sst2.models.TextClassifier',\ninput_shape=(2, 3),\nmodule_kwargs=dict(\n- # TODO(marcvanzee): TFLite throws a concatenation error when\n+ # TODO(marcvanzee): This fails when\n# `embedding_size != hidden_size`. I suppose some arrays are\n# concatenated with incompatible shapes, which could mean\n# something is going wrong in the translation.\nembedding_size=3,\n- hidden_size=3,\n+ hidden_size=1,\nvocab_size=13,\noutput_size=1,\ndropout_rate=0.,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"new_path": "jax/experimental/jax2tf/examples_eval/converters.py",
"diff": "# limitations under the License.\n\"\"\"Converters for jax2tf.\"\"\"\nimport functools\n+from jax.experimental.jax2tf import examples\nimport numpy as np\nimport tempfile\n-from typing import Any, Tuple\n+from typing import Any, Callable, Tuple\nfrom jax._src import dtypes\nimport jax.numpy as jnp\n@@ -25,82 +26,110 @@ from jax.experimental.jax2tf.examples_eval import examples_converter\nimport tensorflow as tf\nfrom tensorflowjs.converters import converter as tfjs_converter\n+Array = Any\nTempDir = tempfile.TemporaryDirectory\n-def jax2tf_to_tfjs(module: examples_converter.ModuleToConvert):\n- \"\"\"Converts the given `module` using the TFjs converter.\"\"\"\n- with TempDir() as saved_model_path, TempDir() as converted_model_path:\n- # the model must be converted with with_gradient set to True to be able to\n- # convert the saved model to TF.js, as \"PreventGradient\" is not supported\n- saved_model_lib.convert_and_save_model(\n- module.apply,\n- module.variables,\n- saved_model_path,\n- input_signatures=[\n+def _jax2tf(jax_fn: Callable[..., Any], input_shape: Tuple[int, ...], dtype: Any, *, enable_xla: bool = True):\n+ \"\"\"Converts the given `jax_fn` to TF using jax2tf and returns `(tf_fn, concrete_fn)`.\"\"\"\n+ tf_fn = tf.function(\n+ jax2tf.convert(jax_fn, enable_xla=enable_xla),\n+ input_signature=[\ntf.TensorSpec(\n- shape=module.input_shape,\n- dtype=module.dtype,\n+ shape=input_shape,\n+ dtype=dtype,\nname='input')\n],\n- with_gradient=True,\n- compile_model=False,\n- enable_xla=False\n- )\n- tfjs_converter.convert([saved_model_path, converted_model_path])\n+ autograph=False)\n+ concrete_fn = tf_fn.get_concrete_function()\n+ return tf_fn, concrete_fn\n-def _get_random_data(dtype: jnp.dtype, shape: Tuple[int, ...]) -> Any:\n+def _get_random_data(dtype: jnp.dtype, shape: Tuple[int, ...], seed=0) -> Any:\ndtype = dtypes.canonicalize_dtype(dtype)\n+ np.random.seed(seed)\n+ # Adjust the max values of the numbers based on the seed, so different seeds\n+ # result in different ranges.\n+ max_value = max(1, 100*seed)\nif np.issubdtype(dtype, np.integer):\n- return np.random.randint(0, 100, size=shape, dtype=dtype)\n+ return np.random.randint(0, max_value, size=shape, dtype=dtype)\nelif np.issubdtype(dtype, np.floating):\n- return np.array(np.random.uniform(size=shape), dtype=dtype) * 100\n+ return np.array(np.random.uniform(size=shape), dtype=dtype) * max_value\nelif dtype == np.bool:\nreturn np.random.choice(a=[False, True], size=shape)\nelse:\nraise ValueError(f\"Unsupported dtype for numerical comparison: {dtype}\")\n-def _all_close(jax_results, tf_results, tf_description, rtol=1e-05):\n+def _compare(jax_fn: Callable[..., Any], tf_fn: Callable[..., Any],\n+ module: examples_converter.ModuleToConvert, comparison: str,\n+ nr_runs: int = 5, rtol: float = 1e-05):\n+ for i in range(nr_runs):\n+ input_data = _get_random_data(module.dtype, module.input_shape, seed=i)\n+ # A function may return multiple arrays, which may be of different shapes.\n+ # We can't just input the tuple into `np.allclose` since it will cast the\n+ # tuple to an array, which will break if the shapes in the tuple are\n+ # different. Therefore we iterate over the tuple explicitly.\n+ wrap_tuple = lambda x: (x,) if not isinstance(x, tuple) else x\n+ jax_results = wrap_tuple(jax_fn(input_data))\n+ tf_results = wrap_tuple(tf_fn(input_data))\n+\nif len(tf_results) != len(jax_results):\n- raise ValueError(f\"Numerical difference: returned output tuples lengths do \"\n- f\"not match: {tf_description} length vs JAX length: \"\n- f\"{len(tf_results)} != {len(jax_results)}\")\n+ raise ValueError(f\"For {comparison}: returned output tuples lengths do not\"\n+ f\"match: TF length vs JAX length: {len(tf_results)} != \"\n+ f\"{len(jax_results)}\")\nfor jax_result, tf_result in zip(jax_results, tf_results):\n- for jax_array, tf_array in zip(jax_result, tf_result):\n- jax_array = np.asarray(jax_array)\n- tf_array = np.asarray(tf_array)\n- if not np.allclose(jax_array, tf_array, rtol):\n- raise ValueError(f\"Numerical difference JAX vs {tf_description}: \"\n- f\"JAX result={jax_result} vs \"\n- f\"{tf_description} result={tf_result}\")\n+ if not np.allclose(jax_result, tf_result, rtol):\n+ raise ValueError(f\"For {comparison}: Numerical difference \"\n+ f\"jax_result={jax_result} vs \"\n+ f\"tf_result={tf_result}\")\n+ # TFLite doesn't allow existing references to its data when it is\n+ # invoked. We therefore delete TF results so we can run multiple inputs on\n+ # the same interpreter.\n+ del tf_result\n+ del tf_results\n+\n+\n+def jax2tf_xla(module: examples_converter.ModuleToConvert):\n+ \"\"\"Converts the given `module` using the jax2tf emitter with enable_xla=True.\"\"\"\n+ apply = functools.partial(module.apply, module.variables)\n+ _, apply_tf = _jax2tf(apply, module.input_shape, module.dtype)\n+ _compare(apply, apply_tf, module, \"JAX vs TF (enable_xla=True)\")\n-def jax2tf_to_tflite(module: examples_converter.ModuleToConvert):\n- \"\"\"Converts the given `module` using the TFLite converter.\"\"\"\n- apply = functools.partial(module.apply, module.variables)\n- tf_predict = tf.function(\n- jax2tf.convert(apply, enable_xla=False),\n- input_signature=[\n+def jax2tf_to_tfjs(module: examples_converter.ModuleToConvert):\n+ \"\"\"Converts the given `module` using the TFjs converter.\"\"\"\n+ with TempDir() as saved_model_path, TempDir() as converted_model_path:\n+ # the model must be converted with with_gradient set to True to be able to\n+ # convert the saved model to TF.js, as \"PreventGradient\" is not supported\n+ saved_model_lib.convert_and_save_model(\n+ module.apply,\n+ module.variables,\n+ saved_model_path,\n+ input_signatures=[\ntf.TensorSpec(\nshape=module.input_shape,\ndtype=module.dtype,\nname='input')\n],\n- autograph=False)\n- tf_predict_concrete = tf_predict.get_concrete_function()\n+ with_gradient=True,\n+ compile_model=False,\n+ enable_xla=False\n+ )\n+ tfjs_converter.convert([saved_model_path, converted_model_path])\n- input_data = _get_random_data(module.dtype, module.input_shape)\n+\n+def jax2tf_to_tflite(module: examples_converter.ModuleToConvert):\n+ \"\"\"Converts the given `module` using the TFLite converter.\"\"\"\n+ apply = functools.partial(module.apply, module.variables)\n+ tf_fn, apply_tf = _jax2tf(apply, module.input_shape, module.dtype, enable_xla=False)\n# First compare JAX output with TF output.\n- jax_results = apply(input_data)\n- _all_close(jax_results, tf_predict_concrete(input_data), \"TF\")\n+ _compare(apply, apply_tf, module, \"JAX vs TF (enable_xla=False)\")\n# Convert TF function to TF Lite format.\n- converter = tf.lite.TFLiteConverter.from_concrete_functions(\n- [tf_predict.get_concrete_function()], tf_predict)\n+ converter = tf.lite.TFLiteConverter.from_concrete_functions([apply_tf], tf_fn)\nconverter.target_spec.supported_ops = [\ntf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\ntf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.\n@@ -117,12 +146,12 @@ def jax2tf_to_tflite(module: examples_converter.ModuleToConvert):\noutput_details = interpreter.get_output_details()\noutputs = tuple(interpreter.tensor(out[\"index\"]) for out in output_details)\n+ def apply_tflite(input_data):\ninterpreter.set_tensor(inputs['index'], input_data)\ninterpreter.invoke()\n- tflite_results = tuple(output() for output in outputs)\n-\n- if len(tflite_results) == 1:\n- # If we only have one result, don't use a tuple since JAX also doesn't.\n- tflite_results = tflite_results[0]\n+ if len(outputs) > 1:\n+ return tuple(o() for o in outputs)\n+ else:\n+ return outputs[0]()\n- _all_close(jax_results, tflite_results, \"TFLite\")\n+ _compare(apply, apply_tflite, module, \"JAX vs TFLite\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"new_path": "jax/experimental/jax2tf/examples_eval/converters_results.md",
"diff": "# Evaluation Results\n-*Last generated on: 2021-11-17* (YYYY-MM-DD)\n+*Last generated on: 2021-11-22* (YYYY-MM-DD)\n## jax2tf --> TFLite\n@@ -13,14 +13,14 @@ These exampls are representative for what the average ML researcher is intereste\n| Example | Result | Error Message |\n| --- | --- | --- |\n| imagenet | SUCCESS |\n-| lm1b | SUCCESS |\n+| lm1b | FAIL | ValueError('For JAX vs TF (enable_xla=False): Numerical difference jax_result=[[[ 1.0656209e+00 9.3210316e-01 -7.5562042e-01 5.7160920e-01\\n 4.7576640e-04 -8.3388436e-01 -6.6835815e-01 8.1217813e-01]]\\n\\n [[ 1.0656208e+00 9.3210304e-01 -7.5562... (CROPPED)\n| mnist | SUCCESS |\n| nlp_seq | SUCCESS |\n-| pixelcnn++ | FAIL | ValueError('Numerical difference JAX vs TF: JAX result=[[[-1.42588705e-01 4.43906128e-01 -4.43267524e-01 ... 2.41633713e-01\\n 4.30841953e-01 -3.73984545e-01]\\n [-5.50750673e-01 8.27922702e-01 -5.37640810e-01 ... 7.13608935e-02\\n 5.00771403... (CROPPED)\n-| ppo | SUCCESS |\n+| pixelcnn++ | FAIL | ValueError('For JAX vs TF (enable_xla=False): Numerical difference jax_result=[[[[-1.42588705e-01 4.43906128e-01 -4.43267524e-01 ... 2.41633713e-01\\n 4.30841953e-01 -3.73984545e-01]\\n [-4.31387722e-01 5.41435003e-01 -2.79315412e-01 ... -4.81... (CROPPED)\n+| ppo | FAIL | ValueError('For JAX vs TF (enable_xla=False): Numerical difference jax_result=[[-2.0793843 -2.079457 -2.0794344 -2.079432 -2.0793545 -2.0794942\\n -2.079453 -2.0795226]] vs tf_result=[[-2.0794415 -2.0794415 -2.0794415 -2.0794415 -2.0794415 -2.0794... (CROPPED)\n| seq2seq | SUCCESS |\n-| sst2 | SUCCESS |\n-| vae | FAIL | ValueError('Numerical difference JAX vs TF: JAX result=[[[1.00000000e+00 2.96458746e-09 2.83802848e-08 ... 0.00000000e+00\\n 9.99999881e-01 6.08000756e-19]\\n [9.81082678e-01 6.93151236e-01 7.65325581e-08 ... 1.04346945e-07\\n 7.08327889e-01 3.9745... (CROPPED)\n+| sst2 | FAIL | RuntimeError('tensorflow/lite/kernels/concatenation.cc:158 t->dims->data[d] != t0->dims->data[d] (3 != 1)Node number 11 (CONCATENATION) failed to prepare.Node number 7 (WHILE) failed to invoke.')\n+| vae | FAIL | ValueError('For JAX vs TF (enable_xla=False): Numerical difference jax_result=[[[[1.00000000e+00 1.59054339e-10 2.23751954e-06 ... 0.00000000e+00\\n 9.99998808e-01 2.93910057e-12]\\n [1.00000000e+00 1.49735279e-04 1.17003319e-05 ... 2.77897666e-16... (CROPPED)\n| wmt | SUCCESS |\n## jax2tf --> TFjs\n@@ -34,15 +34,36 @@ These exampls are representative for what the average ML researcher is intereste\n| Example | Result | Error Message |\n| --- | --- | --- |\n| imagenet | SUCCESS |\n-| lm1b | FAIL | ValueError(\"in user code:\\n\\n\\n ValueError: Got a non-Tensor value FrozenDict({\\n cache: {\\n decoder: {\\n encoderdecoderblock_0: {\\n SelfAttention_0: {\\n cache_index: <tf.Tensor 'StatefulPartitionedCall:1' shape=() dtype=int32>,\\n cached_key: <tf.Tensor 'StatefulPartitionedCall:2' shape=(2, 1, 1, 2) dtype=float32>,\\n cached_value: <tf.Tensor 'StatefulPartitionedCall:3' shape=(2, 1, 1, 2) dtype=float32>,\\n },\\n },\\n posembed_output: {\\n cache_index: <tf.Tensor 'StatefulPartitionedCall:4' shape=() dtype=uint32>,\\n },\\n },\\n },\\n }) for key 'output_1' in the output of the function __inference_<lambda>_74438 used to generate the SavedModel signature 'serving_default'. Outputs for functions used as signatures must be a single Tensor, a sequence of Tensors, or a dictionary from string to Tensor.\\n\")\n+| lm1b | FAIL | ValueError(\"Error when tracing gradients for SavedModel.\\n\\nCheck the error log to see the error that was raised when converting a gradient function to a concrete function. You may need to update the custom gradient, or disable saving gradients with ... (CROPPED)\n| mnist | SUCCESS |\n-| nlp_seq | FAIL | ValueError(\"Error when tracing gradients for SavedModel.\\n\\nSee the stack trace above to see the error that was raised when converting a gradient function to a concrete function. You may need to update the custom gradient, or disable saving gradients with the option tf.saved_model.SaveOptions(custom_gradients=False).\\n\\tProblematic op name: IdentityN\\n\\tGradient inputs: (<tf.Tensor 'AddV2_12:0' shape=(2, 1, 8) dtype=float32>, <tf.Tensor 'jax2tf_arg_0:0' shape=(8,) dtype=float32>, <tf.Tensor 'jax2tf_arg_1:0' shape=(4, 8) dtype=float32>, <tf.Tensor 'jax2tf_arg_2:0' shape=(4,) dtype=float32>, <tf.Tensor 'jax2tf_arg_3:0' shape=(4,) dtype=float32>, <tf.Tensor 'jax2tf_arg_4:0' shape=(4,) dtype=float32>, <tf.Tensor 'jax2tf_arg_5:0' shape=(4,) dtype=float32>, <tf.Tensor 'jax2tf_arg_6:0' shape=(2,) dtype=float32>, <tf.Tensor 'jax2tf_arg_7:0' shape=(4, 2) dtype=float32>, <tf.Tensor 'jax2tf_arg_8:0' shape=(4,) dtype=float32>, <tf.Tensor 'jax2tf_arg_9:0' shape=(2, 4) dtype=float32>, <tf.Tensor 'jax2tf_arg_10:0' shape=(4, 1, 2) dtype=float32>, <tf.Tensor 'jax2tf_arg_11:0' shape=(1, 2, 4) dtype=float32>, <tf.Tensor 'jax2tf_arg_12:0' shape=(4, 1, 2) dtype=float32>, <tf.Tensor 'jax2tf_arg_13:0' shape=(4, 1, 2) dtype=float32>, <tf.Tensor 'jax2tf_arg_14:0' shape=(4,) dtype=float32>, <tf.Tensor 'jax2tf_arg_15:0' shape=(4,) dtype=float32>, <tf.Tensor 'jax2tf_arg_16:0' shape=(8, 4) dtype=float32>, <tf.Tensor 'jax2tf_arg_17:0' shape=(2, 1) dtype=float32>)\")\n+| nlp_seq | FAIL | ValueError(\"Error when tracing gradients for SavedModel.\\n\\nCheck the error log to see the error that was raised when converting a gradient function to a concrete function. You may need to update the custom gradient, or disable saving gradients with ... (CROPPED)\n| pixelcnn++ | SUCCESS |\n| ppo | SUCCESS |\n-| seq2seq | FAIL | ValueError('Unsupported Ops in the model before optimization\\nBitcast, BitwiseAnd, BitwiseOr, LeftShift, BitwiseXor, RightShift')\n+| seq2seq | FAIL | ValueError('Unsupported Ops in the model before optimization\\nLeftShift, BitwiseOr, Bitcast, BitwiseAnd, RightShift, BitwiseXor')\n| sst2 | FAIL | ValueError('Unsupported Ops in the model before optimization\\nBitwiseAnd')\n| vae | SUCCESS |\n-| wmt | FAIL | ValueError(\"in user code:\\n\\n\\n ValueError: Got a non-Tensor value FrozenDict({\\n cache: {\\n decoder: {\\n encoderdecoderblock_0: {\\n SelfAttention_0: {\\n cache_index: <tf.Tensor 'StatefulPartitionedCall:1' shape=() dtype=int32>,\\n cached_key: <tf.Tensor 'StatefulPartitionedCall:2' shape=(2, 1, 1, 2) dtype=float32>,\\n cached_value: <tf.Tensor 'StatefulPartitionedCall:3' shape=(2, 1, 1, 2) dtype=float32>,\\n },\\n },\\n posembed_output: {\\n cache_index: <tf.Tensor 'StatefulPartitionedCall:4' shape=() dtype=uint32>,\\n },\\n },\\n },\\n }) for key 'output_1' in the output of the function __inference_<lambda>_229578 used to generate the SavedModel signature 'serving_default'. Outputs for functions used as signatures must be a single Tensor, a sequence of Tensors, or a dictionary from string to Tensor.\\n\")\n+| wmt | FAIL | ValueError(\"Error when tracing gradients for SavedModel.\\n\\nCheck the error log to see the error that was raised when converting a gradient function to a concrete function. You may need to update the custom gradient, or disable saving gradients with ... (CROPPED)\n+\n+## jax2tf (enable_xla=True)\n+\n+### The Flax Examples\n+[URL to examples](https://github.com/google/flax/tree/main/examples)\n+\n+Description: List of examples maintained by the Flax team.\n+These exampls are representative for what the average ML researcher is interested in.\n+\n+| Example | Result | Error Message |\n+| --- | --- | --- |\n+| imagenet | SUCCESS |\n+| lm1b | FAIL | TypeError(\"Value passed to parameter 'start_indices' has DataType uint32 not in list of allowed values: int32, int64\")\n+| mnist | SUCCESS |\n+| nlp_seq | SUCCESS |\n+| pixelcnn++ | FAIL | ValueError('For JAX vs TF (enable_xla=True): Numerical difference jax_result=[[[[-1.42588705e-01 4.43906128e-01 -4.43267524e-01 ... 2.41633713e-01\\n 4.30841953e-01 -3.73984545e-01]\\n [-4.31387722e-01 5.41435003e-01 -2.79315412e-01 ... -4.817... (CROPPED)\n+| ppo | SUCCESS |\n+| seq2seq | SUCCESS |\n+| sst2 | SUCCESS |\n+| vae | SUCCESS |\n+| wmt | FAIL | TypeError(\"Value passed to parameter 'start_indices' has DataType uint32 not in list of allowed values: int32, int64\")\n## Table generation\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/converters_results.md.template",
"new_path": "jax/experimental/jax2tf/examples_eval/converters_results.md.template",
"diff": "{{jax2tf_to_tfjs}}\n+## jax2tf (enable_xla=True)\n+\n+{{jax2tf_xla}}\n+\n## Table generation\nSee `examples_test.py` for instructions on how to regenerate this table.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples_eval/examples_test.py",
"new_path": "jax/experimental/jax2tf/examples_eval/examples_test.py",
"diff": "@@ -42,6 +42,7 @@ from jax.experimental.jax2tf.examples_eval import examples_converter\nCONVERTERS = {\n+ 'jax2tf_xla': converters.jax2tf_xla,\n'jax2tf_to_tfjs': converters.jax2tf_to_tfjs,\n'jax2tf_to_tflite': converters.jax2tf_to_tflite\n}\n"
}
] | Python | Apache License 2.0 | google/jax | Improve logics for numerical comparison |
260,411 | 23.11.2021 11:03:10 | -7,200 | 72d9d35555f72b39a415f0b1eb841d3220627a7d | Fix lint and mypy errors | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -875,7 +875,8 @@ class TensorFlowTrace(core.Trace):\nstore_tf_res_avals = None\ndef f_tf(*tf_args):\nnonlocal store_tf_res_avals\n- tf_res_out: Sequence[Tuple[TfVal, core.ShapedArray]] = _call_wrapped_with_new_constant_cache(fun, tf_args,\n+ tf_res_out: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\n+ _call_wrapped_with_new_constant_cache(fun, tf_args,\nfresh_constant_cache=False)\ntf_res_vals, tf_res_avals = util.unzip2(tf_res_out)\nstore_tf_res_avals = tf_res_avals\n@@ -883,7 +884,7 @@ class TensorFlowTrace(core.Trace):\ntf_vals_out = tf.function(f_tf, autograph=False, jit_compile=True)(*vals)\nvals_out = zip(tf_vals_out, store_tf_res_avals)\nelse:\n- vals_out: Sequence[Tuple[TfVal, core.ShapedArray]] = fun.call_wrapped(*vals)\n+ vals_out = fun.call_wrapped(*vals)\nelse:\nvals_out = fun.call_wrapped(*vals)\nreturn [TensorFlowTracer(self, v, a) for v, a in vals_out]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "Specific JAX primitive conversion tests are in primitives_test.\"\"\"\n-import re\nfrom typing import Dict, Tuple\nfrom absl.testing import absltest\n"
}
] | Python | Apache License 2.0 | google/jax | Fix lint and mypy errors |
260,411 | 23.11.2021 11:35:05 | -7,200 | ddc3a126e23fcc33f074632803c95a5ac4c54db7 | Improve error when jnp.arange is used with non-constant arguments | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3761,12 +3761,16 @@ def arange(start: core.DimSize, stop: Optional[core.DimSize]=None,\nlax._check_user_dtype_supported(dtype, \"arange\")\nrequire = partial(core.concrete_or_error, None)\nmsg = \"It arose in jax.numpy.arange argument `{}`.\".format\n+ if _any(core.is_special_dim_size(d) for d in (start, stop, step)):\n+ if stop is not None or step is not None:\n+ raise ValueError(\n+ \"jax.numpy.arange supports non-constant arguments only in single-argument form. \"\n+ f\"Found jax.numpy.arange(start={start}, stop={stop}, step={step})\")\n+ return lax.iota(int_, start)\ndtype = dtype or result_type(start, *(x for x in [stop, step] if x is not None))\nif stop is None and step is None:\n- if not core.is_special_dim_size(start):\nstart = require(start, msg(\"stop\"))\nstart = np.ceil(start).astype(int)\n-\nreturn lax.iota(dtype, start)\nelse:\nstart = require(start, msg(\"start\"))\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": "@@ -1105,6 +1105,9 @@ def _make_harness(group_name: str, name: str,\n`check_result` specifies if we want to check that the result of the shape\npolymorphic conversion produces the same result and the JAX function.\n+ `expect_error` is a pair of an Exception type and a regular expression to\n+ match the expected exception string.\n+\nenable_and_diable_xla=True means that we generate two harnesses,\none with enable_xla=False.\n\"\"\"\n@@ -1157,8 +1160,22 @@ _POLY_SHAPE_TEST_HARNESSES = [\n_make_harness(\"arange\", \"start_no_dtype\",\nlambda op: jnp.arange(op.shape[0]),\n[RandArg((3,), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"arange\", \"error1\",\n+ lambda op: jnp.arange(op.shape[0], 10),\n+ [RandArg((3,), _f32)],\npoly_axes=[0],\n- enable_and_diable_xla=True),\n+ expect_error=(ValueError, \"jax.numpy.arange supports non-constant arguments only in single-argument form\")),\n+ _make_harness(\"arange\", \"error2\",\n+ lambda op: jnp.arange(1, op.shape[0]),\n+ [RandArg((3,), _f32)],\n+ poly_axes=[0],\n+ expect_error=(ValueError, \"jax.numpy.arange supports non-constant arguments only in single-argument form\")),\n+ _make_harness(\"arange\", \"error3\",\n+ lambda op: jnp.arange(1, 5, op.shape[0]),\n+ [RandArg((3,), _f32)],\n+ poly_axes=[0],\n+ expect_error=(ValueError, \"jax.numpy.arange supports non-constant arguments only in single-argument form\")),\n# Reduce the poly dimension\n_make_harness(\"argmax\", \"0\",\nlambda op: lax.argmax(op, axis=0, index_dtype=np.int32),\n@@ -1759,7 +1776,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# to parameterized below.\n@primitive_harness.parameterized(\n_flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"arange_start_no_dtype\"\n+ #one_containing=\"arange_stop_error\"\n)\ndef test_prim(self, harness: Harness):\nargs = harness.dyn_args_maker(self.rng())\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -322,6 +322,7 @@ class DimensionHandlerPoly(core.DimensionHandler):\ncore._SPECIAL_DIMENSION_HANDLERS[Poly] = DimensionHandlerPoly()\n+dtypes.python_scalar_dtypes[Poly] = dtypes.python_scalar_dtypes[int]\nclass Mon(dict):\n# TODO: move this before Poly in the file\n"
}
] | Python | Apache License 2.0 | google/jax | Improve error when jnp.arange is used with non-constant arguments |
260,335 | 23.11.2021 15:51:49 | 28,800 | 8430deda3e1e7a231e2908b721f8165eac675225 | custom pp_eqn rules, simpler xla_call print | [
{
"change_type": "MODIFY",
"old_path": "docs/jaxpr.rst",
"new_path": "docs/jaxpr.rst",
"diff": "@@ -415,7 +415,6 @@ which the computation should run. For example\n{ lambda ; a:f32[]. let\nb:f32[] = sub a 2.0\nc:f32[1] = xla_call[\n- backend=None\ncall_jaxpr={ lambda ; d:f32[] e:f32[]. let\nf:f32[1] = broadcast_in_dim[broadcast_dimensions=() shape=(1,)] 1.0\ng:f32[] = convert_element_type[new_dtype=float32 weak_type=False] d\n@@ -423,9 +422,6 @@ which the computation should run. For example\ni:f32[] = convert_element_type[new_dtype=float32 weak_type=False] e\nj:f32[1] = add i h\nin (j,) }\n- device=None\n- donated_invars=(False, False)\n- inline=False\nname=inner\n] a b\nk:f32[] = convert_element_type[new_dtype=float32 weak_type=False] a\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -2122,12 +2122,16 @@ def pp_eqn(eqn, context: JaxprPpContext, *, print_shapes=True, source_info=False\nlhs = pp_vars(eqn.outvars, context, print_shapes=print_shapes)\nannotation = (source_info_util.summarize(eqn.source_info)\nif source_info else None)\n- return pp.concat([\n- lhs, pp.text(\" = \", annotation=annotation), pp.text(eqn.primitive.name),\n+ rule = pp_eqn_rules.get(eqn.primitive)\n+ if rule:\n+ rhs = rule(eqn, context)\n+ else:\n+ rhs = [pp.text(eqn.primitive.name),\npp_kv_pairs(sorted(eqn.params.items()), context),\n- pp.text(\" \") + pp_vars(eqn.invars, context)\n- ])\n-\n+ pp.text(\" \") + pp_vars(eqn.invars, context)]\n+ return pp.concat([lhs, pp.text(\" = \", annotation=annotation), *rhs])\n+CustomPpEqnRule = Callable[[JaxprEqn, JaxprPpContext], Sequence[pp.Doc]]\n+pp_eqn_rules: Dict[Primitive, CustomPpEqnRule] = {}\ndef pp_eqns(eqns, context: JaxprPpContext, *, print_shapes=True, source_info=False\n) -> pp.Doc:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -717,6 +717,19 @@ pe.partial_eval_jaxpr_custom_rules[xla_call_p] = \\\npe.dce_rules[xla_call_p] = pe.dce_jaxpr_call_rule\n+def _pp_xla_call(eqn: core.JaxprEqn, context: core.JaxprPpContext\n+ ) -> List[pp.Doc]:\n+ printed_params = {k:v for k, v in eqn.params.items() if\n+ k == 'call_jaxpr' or k == 'name' or\n+ k == 'backend' and v is not None or\n+ k == 'device' and v is not None or\n+ k == 'donated_invars' and any(v)}\n+ return [pp.text(eqn.primitive.name),\n+ core.pp_kv_pairs(sorted(printed_params.items()), context),\n+ pp.text(\" \") + core.pp_vars(eqn.invars, context)]\n+core.pp_eqn_rules[xla_call_p] = _pp_xla_call\n+\n+\n### translation tables\nMYPY = False\n"
}
] | Python | Apache License 2.0 | google/jax | custom pp_eqn rules, simpler xla_call print |
260,411 | 24.11.2021 11:47:11 | -7,200 | 277a1d775e871c522144d7c264354e3abe96c18b | [hcb] Cleanup to account for changes in minimum jaxlib version
We can assume now that jaxlib has the support for CustomCall. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -478,19 +478,7 @@ def _inline_host_callback() -> bool:\ndef _use_outfeed(platform: str) -> bool:\n- if platform in (\"tpu\", \"gpu\") or FLAGS.jax_host_callback_outfeed:\n- return True\n-\n- else:\n- backend = xb.get_backend(platform)\n- # TODO: remove this check once we bump the minimum required jaxlib\n- if getattr(backend, \"emit_python_callback\", None) is None:\n- logging.warning(\n- \"jax_host_callback_outfeed is False, but the CustomCall features \"\n- \"for host_callback are not available in this version of jaxlib.\")\n- return True\n- else:\n- return False\n+ return (platform in (\"tpu\", \"gpu\") or FLAGS.jax_host_callback_outfeed)\nxops = xla_client._xla.ops\n"
}
] | Python | Apache License 2.0 | google/jax | [hcb] Cleanup to account for changes in minimum jaxlib version
We can assume now that jaxlib has the support for CustomCall. |
260,562 | 24.11.2021 10:02:35 | 28,800 | e6950dd63ed3c054067c53bd4806dfbb85e0eef7 | [XLA] Adjust the error tolerance of 'lax_control_flow_test.py'
We are about to change the vectorization strategy for XLA:CPU. As a result,
we have to increase the error tolerance of the impacted tests. | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -1453,7 +1453,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nans = scan(f, c, as_)\nexpected = scan_reference(f, c, as_)\n- self.assertAllClose(ans, expected, check_dtypes=False)\n+ self.assertAllClose(\n+ ans,\n+ expected,\n+ check_dtypes=False,\n+ rtol={np.float64: 1.4e-15},\n+ atol={np.float64: 8e-15})\n@parameterized.named_parameters(\n{\"testcase_name\": \"_jit_scan={}_jit_f={}_impl={}\".format(\n@@ -1801,14 +1806,11 @@ class LaxControlFlowTest(jtu.JaxTestCase):\ndef loop(val):\niterations = 10\n+\ndef apply_carry(x, i):\nreturn jax.grad(fn, argnums=(0,))(x)[0], i\n- final_val, _ = lax.scan(\n- apply_carry,\n- val,\n- jnp.arange(iterations)\n- )\n+ final_val, _ = lax.scan(apply_carry, val, jnp.arange(iterations))\nreturn final_val\narg = 0.5\n@@ -2045,8 +2047,8 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(results, inputs ** 1.5, check_dtypes=False)\nresults = jax.jit(sqrt_cubed)(5.0)\n- self.assertAllClose(results, 5.0 ** 1.5, check_dtypes=False,\n- rtol={np.float64:1e-7})\n+ self.assertAllClose(\n+ results, 5.0**1.5, check_dtypes=False, rtol={np.float64: 1e-7})\n@jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\ndef test_custom_root_vector_with_solve_closure(self):\n"
}
] | Python | Apache License 2.0 | google/jax | [XLA] Adjust the error tolerance of 'lax_control_flow_test.py'
We are about to change the vectorization strategy for XLA:CPU. As a result,
we have to increase the error tolerance of the impacted tests.
PiperOrigin-RevId: 412083490 |
260,335 | 23.11.2021 15:03:24 | 28,800 | 17add1ce389ac6470e412ee81f7fd7b6251a184e | sipmlify array_copy implementation
Use nested calls rather than an add-zero. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -83,19 +83,18 @@ Shape = core.Shape\ndef _array_copy(arr):\n\"\"\"Return an on-device copy of a DeviceArray.\n- This is a private method; users can access this via ``jnp.array(x, copy=True)``.\n+ This is a private method; users should write ``jnp.array(x, copy=True)``.\nWhy do we need copies in a purely functional langauge? Well, JAX is *almost*\n- purely functional: the semantics of `donate_argnums` mean that sometimes buffers\n- are consumed, and you actually need to ensure a copy is generated on device.\n+ purely functional: the semantics of ``donate_argnums`` mean that sometimes\n+ buffers are consumed. So we need a way to copy on-device.\n\"\"\"\n- # TODO(jakevdp): There is no XLA copy operation, so for the time being we rely\n- # on an implementation detail: although XLA will optimize away non-operations like\n- # adding zero, it still results in a copied buffer. Eventually, we should move to\n- # a more direct method that avoids inserting a spurious add_p/or_p into the jaxpr.\n- if arr.dtype == bool:\n- return bitwise_or(arr, _const(arr, False))\n- return add(arr, _const(arr, 0))\n+ # This jit-based implementation must avoid hitting _execute_trivial in\n+ # dispatch.py, and so its body needs to be one which JAX optimizations don't\n+ # simplify away (which could evolve!). An alternative would be to have an\n+ # identity primitive with an impl that performs a runtime copy-on-device\n+ # operation, but such an operation doesn't currently exist in the runtime.\n+ return jax.jit(lambda x: x, inline=False)(arr)\ndef _try_broadcast_shapes(shapes):\nassert shapes\n"
}
] | Python | Apache License 2.0 | google/jax | sipmlify array_copy implementation
Use nested calls rather than an add-zero. |
260,335 | 23.11.2021 15:23:28 | 28,800 | cd1655ed30f0a758b1aacb42bc1756c40434fbb9 | re-implement lax._array_copy as a primitive | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -79,23 +79,6 @@ Array = Any\nDType = Any\nShape = core.Shape\n-@functools.partial(jax.jit, inline=True)\n-def _array_copy(arr):\n- \"\"\"Return an on-device copy of a DeviceArray.\n-\n- This is a private method; users should write ``jnp.array(x, copy=True)``.\n-\n- Why do we need copies in a purely functional langauge? Well, JAX is *almost*\n- purely functional: the semantics of ``donate_argnums`` mean that sometimes\n- buffers are consumed. So we need a way to copy on-device.\n- \"\"\"\n- # This jit-based implementation must avoid hitting _execute_trivial in\n- # dispatch.py, and so its body needs to be one which JAX optimizations don't\n- # simplify away (which could evolve!). An alternative would be to have an\n- # identity primitive with an impl that performs a runtime copy-on-device\n- # operation, but such an operation doesn't currently exist in the runtime.\n- return jax.jit(lambda x: x, inline=False)(arr)\n-\ndef _try_broadcast_shapes(shapes):\nassert shapes\nif len(shapes) == 1: return shapes[0]\n@@ -4127,6 +4110,20 @@ RandomAlgorithm = xops.RandomAlgorithm\nRandomAlgorithm.__str__ = lambda algorithm: algorithm.name # type: ignore[assignment]\n+def _array_copy(arr):\n+ return copy_p.bind(arr)\n+\n+# The copy_p primitive exists for expressing making copies of runtime arrays.\n+# For that reason we don't simplify it out of jaxprs (e.g. for jit invariance).\n+# It's used in jnp.array(x, copy=True), which is the user-facing API.\n+copy_p = core.Primitive('copy_p')\n+copy_p.def_impl(partial(xla.apply_primitive, copy_p))\n+copy_p.def_abstract_eval(lambda x: x)\n+xla.register_translation(copy_p, lambda ctx, avals_in, avals_out, x: [x])\n+ad.deflinear(copy_p, lambda t: [copy_p.bind(t)])\n+batching.defvectorized(copy_p)\n+masking.defvectorized(copy_p)\n+\ndef rng_bit_generator(key, shape, dtype=np.uint32,\nalgorithm=RandomAlgorithm.RNG_DEFAULT):\n\"\"\"Stateless PRNG bit generator. Experimental and its use is discouraged.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -3634,6 +3634,27 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself.assertFalse(x_copy.is_deleted())\nself.assertFalse(x_copy_jit.is_deleted())\n+ def testArrayCopyAutodiff(self):\n+ f = lambda x: jnp.array(x, copy=True)\n+\n+ x = jnp.ones(10)\n+ xdot = jnp.ones(10)\n+ y, ydot = jax.jvp(f, (x,), (xdot,))\n+ self.assertIsNot(x, y)\n+ self.assertIsNot(xdot, ydot)\n+\n+ ybar = jnp.ones(10)\n+ y, f_vjp = jax.vjp(f, x)\n+ xbar, = f_vjp(ybar)\n+ self.assertIsNot(x, y)\n+ self.assertIsNot(xbar, ybar)\n+\n+ def testArrayCopyVmap(self):\n+ f = lambda x: jnp.array(x, copy=True)\n+ x = jnp.ones(10)\n+ y = jax.vmap(f)(x)\n+ self.assertIsNot(x, y)\n+\ndef testArrayUnsupportedDtypeError(self):\nwith self.assertRaisesRegex(TypeError,\n\"JAX only supports number and bool dtypes.*\"):\n"
}
] | Python | Apache License 2.0 | google/jax | re-implement lax._array_copy as a primitive |
260,335 | 24.11.2021 14:15:15 | 28,800 | 9a423bb4be4576c81a757009eed65db7601b74c2 | add mlir lowering for copy_p | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -4120,6 +4120,7 @@ copy_p = core.Primitive('copy_p')\ncopy_p.def_impl(partial(xla.apply_primitive, copy_p))\ncopy_p.def_abstract_eval(lambda x: x)\nxla.register_translation(copy_p, lambda ctx, avals_in, avals_out, x: [x])\n+mlir.register_lowering( copy_p, lambda ctx, avals_in, avals_out, x: [x])\nad.deflinear(copy_p, lambda t: [copy_p.bind(t)])\nbatching.defvectorized(copy_p)\nmasking.defvectorized(copy_p)\n"
}
] | Python | Apache License 2.0 | google/jax | add mlir lowering for copy_p |
260,335 | 24.11.2021 14:26:55 | 28,800 | 3d16a32986bc501a33c8fbec1ca1da15992d529d | add option for enabling custom jaxpr pprint rules | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -76,12 +76,14 @@ class Jaxpr:\nself.eqns = list(eqns)\ndef __str__(self):\n- return str(pp_jaxpr(self, JaxprPpContext()))\n+ return str(pp_jaxpr(self, JaxprPpContext(), custom_pp_eqn_rules=True))\n__repr__ = __str__\n- def pretty_print(self, *, source_info=False, print_shapes=True, **kw):\n+ def pretty_print(self, *, source_info=False, print_shapes=True,\n+ custom_pp_eqn_rules=True, **kw):\ndoc = pp_jaxpr(self, JaxprPpContext(), source_info=source_info,\n- print_shapes=print_shapes)\n+ print_shapes=print_shapes,\n+ custom_pp_eqn_rules=custom_pp_eqn_rules)\nreturn doc.format(**kw)\n@@ -151,7 +153,9 @@ class JaxprEqn(NamedTuple):\nparams: Dict[str, Any]\nsource_info: source_info_util.SourceInfo\n- def __repr__(self): return str(pp_eqn(self, JaxprPpContext())).rstrip()\n+ def __repr__(self):\n+ return str(pp_eqn(self, JaxprPpContext(), custom_pp_eqn_rules=False)\n+ ).rstrip()\ndef new_jaxpr_eqn(invars, outvars, primitive, params, source_info=None):\nif primitive.call_primitive:\n@@ -2117,13 +2121,13 @@ def pp_kv_pairs(kv_pairs, context: JaxprPpContext) -> pp.Doc:\n+ pp.brk(\"\") + pp.text(\"]\")\n)\n-def pp_eqn(eqn, context: JaxprPpContext, *, print_shapes=True, source_info=False\n- ) -> pp.Doc:\n+def pp_eqn(eqn, context: JaxprPpContext, *, print_shapes=True,\n+ source_info=False, custom_pp_eqn_rules=True) -> pp.Doc:\nlhs = pp_vars(eqn.outvars, context, print_shapes=print_shapes)\nannotation = (source_info_util.summarize(eqn.source_info)\nif source_info else None)\nrule = pp_eqn_rules.get(eqn.primitive)\n- if rule:\n+ if rule and custom_pp_eqn_rules:\nrhs = rule(eqn, context)\nelse:\nrhs = [pp.text(eqn.primitive.name),\n@@ -2133,12 +2137,13 @@ def pp_eqn(eqn, context: JaxprPpContext, *, print_shapes=True, source_info=False\nCustomPpEqnRule = Callable[[JaxprEqn, JaxprPpContext], Sequence[pp.Doc]]\npp_eqn_rules: Dict[Primitive, CustomPpEqnRule] = {}\n-def pp_eqns(eqns, context: JaxprPpContext, *, print_shapes=True, source_info=False\n+def pp_eqns(eqns, context: JaxprPpContext, *, print_shapes=True,\n+ source_info=False, custom_pp_eqn_rules=True\n) -> pp.Doc:\nreturn pp.join(\npp.brk(\"; \"),\n- map(lambda e: pp_eqn(e, context, print_shapes=print_shapes,\n- source_info=source_info), eqns))\n+ [pp_eqn(e, context, print_shapes=print_shapes, source_info=source_info,\n+ custom_pp_eqn_rules=custom_pp_eqn_rules) for e in eqns])\ndef pp_eqn_compact(primitive_name: str, params: Dict, context: JaxprPpContext\n) -> pp.Doc:\n@@ -2166,9 +2171,10 @@ def pp_jaxpr_skeleton(jaxpr, eqns_fn, context: JaxprPpContext, *,\ndef pp_jaxpr(jaxpr, context: JaxprPpContext, *, print_shapes=True,\n- source_info=False) -> pp.Doc:\n+ source_info=False, custom_pp_eqn_rules=True) -> pp.Doc:\neqns_fn = lambda: pp_eqns(jaxpr.eqns, context, print_shapes=print_shapes,\n- source_info=source_info)\n+ source_info=source_info,\n+ custom_pp_eqn_rules=custom_pp_eqn_rules)\nreturn pp_jaxpr_skeleton(jaxpr, eqns_fn, context, print_shapes=print_shapes)\ndef pp_jaxprs(jaxprs, context: JaxprPpContext) -> pp.Doc:\n"
}
] | Python | Apache License 2.0 | google/jax | add option for enabling custom jaxpr pprint rules |
260,335 | 24.11.2021 14:30:07 | 28,800 | 63a8f62200467ec49231a7bfa3be4673d05922b8 | add copy_p to jax2tf not implemented list | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1003,6 +1003,7 @@ def _add(x: TfVal, y: TfVal) -> TfVal:\ntf_impl[ad_util.add_jaxvals_p] = _add\ntf_impl[dispatch.device_put_p] = lambda x, device=None: x\n+tf_impl[lax_internal.copy_p] = lambda x: x\ndef _neg(x: TfVal) -> TfVal:\nif x.dtype.is_unsigned:\n"
}
] | Python | Apache License 2.0 | google/jax | add copy_p to jax2tf not implemented list |
260,411 | 26.11.2021 09:26:54 | -7,200 | a94a8847c3802521725e08e91587079c6296fc1b | [jax2tf] Implement CLIP mode for scatter.
Also handle a limited form of shape polymorphism, where
the `operand.shape - update.shape` is a constant in the scatter dimensions,
even when the shapes may contain dimension variables. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/slicing.py",
"new_path": "jax/_src/lax/slicing.py",
"diff": "@@ -1430,10 +1430,6 @@ def _scatter_shape_rule(operand, indices, updates, *, update_jaxpr,\ndef _clamp_scatter_indices(operand, indices, updates, *, dnums):\n\"\"\"Clamps `indices` to be in-range for a scatter.\"\"\"\n- intarray = partial(np.array, dtype=np.int64)\n- operand_dims = intarray(operand.shape)\n- upper_bound = operand_dims[intarray(dnums.scatter_dims_to_operand_dims)]\n-\nslice_sizes = []\npos = 0\nfor i in range(len(operand.shape)):\n@@ -1443,7 +1439,9 @@ def _clamp_scatter_indices(operand, indices, updates, *, dnums):\nslice_sizes.append(updates.shape[dnums.update_window_dims[pos]])\npos += 1\n- upper_bound -= intarray(slice_sizes)[intarray(dnums.scatter_dims_to_operand_dims)]\n+ upper_bound = np.array([operand.shape[i] - slice_sizes[i]\n+ for i in dnums.scatter_dims_to_operand_dims],\n+ np.int64)\nupper_bound = np.minimum(upper_bound, np.iinfo(indices.dtype).max)\nupper_bound = lax.broadcast_in_dim(upper_bound, indices.shape,\n(len(indices.shape) - 1,))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -2132,10 +2132,14 @@ def _scatter(operand, scatter_indices, updates, *, update_jaxpr, update_consts,\ndimension_numbers, indices_are_sorted, unique_indices, mode,\n_in_avals: Sequence[core.ShapedArray],\n_out_aval: core.ShapedArray):\n- del unique_indices, _in_avals\n+ del unique_indices\nif mode == lax.GatherScatterMode.CLIP:\n- raise NotImplementedError(\"CLIP scatter mode not implemented in jax2tf\")\n+ clip_fn = _convert_jax_impl(lax_slicing._clamp_scatter_indices,\n+ multiple_results=False)\n+ scatter_indices = clip_fn(\n+ operand, scatter_indices, updates, dnums=dimension_numbers,\n+ _in_avals=_in_avals, _out_aval=_in_avals[1])\nassert len(update_consts) == 0, \"Update computation cannot have constants\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -1133,8 +1133,8 @@ for indices, index_oob, indices_name in [\nlax.gather_p,\nf\"from_take_indices_name={indices_name}_axis={axis}\"\nf\"_enable_xla={enable_xla}_mode={mode}\",\n- lambda a, i, axis: jnp.take(a, i, axis=axis, mode=mode),\n- [_gather_input, indices, StaticArg(axis)],\n+ lambda a, i, axis, mode: jnp.take(a, i, axis=axis, mode=mode),\n+ [_gather_input, indices, StaticArg(axis), StaticArg(mode)],\ndtype=_gather_input.dtype,\nenable_xla=enable_xla,\nindex_oob=index_oob,\n@@ -1232,17 +1232,19 @@ def _make_scatter_harness(name,\nunique_indices=False,\nscatter_indices=np.array([[0], [2]]),\nupdate_shape=(2,),\n+ mode=lax.GatherScatterMode.FILL_OR_DROP,\ndtype=np.float32,\ndimension_numbers=((), (0,), (0,))):\ndimension_numbers = lax.ScatterDimensionNumbers(*dimension_numbers)\ndefine(\nf_lax.__name__,\n- f\"{name}_shape={jtu.format_shape_dtype_string(shape, dtype)}_scatterindices={scatter_indices.tolist()}_updateshape={update_shape}_updatewindowdims={dimension_numbers.update_window_dims}_insertedwindowdims={dimension_numbers.inserted_window_dims}_scatterdimstooperanddims={dimension_numbers.scatter_dims_to_operand_dims}_indicesaresorted={indices_are_sorted}_uniqueindices={unique_indices}\"\n+ f\"{name}_shape={jtu.format_shape_dtype_string(shape, dtype)}_scatterindices={scatter_indices.tolist()}_updateshape={update_shape}_updatewindowdims={dimension_numbers.update_window_dims}_insertedwindowdims={dimension_numbers.inserted_window_dims}_scatterdimstooperanddims={dimension_numbers.scatter_dims_to_operand_dims}_indicesaresorted={indices_are_sorted}_uniqueindices={unique_indices}_mode={mode}\"\n.replace(\" \", \"\"),\npartial(\nf_lax,\nindices_are_sorted=indices_are_sorted,\n- unique_indices=unique_indices), [\n+ unique_indices=unique_indices,\n+ mode=mode), [\nRandArg(shape, dtype),\nStaticArg(scatter_indices),\nRandArg(update_shape, dtype),\n@@ -1261,7 +1263,8 @@ def _make_scatter_harness(name,\nupdate_shape=update_shape,\ndimension_numbers=dimension_numbers,\nindices_are_sorted=indices_are_sorted,\n- unique_indices=unique_indices)\n+ unique_indices=unique_indices,\n+ mode=mode)\n# Validate dtypes\n@@ -1269,8 +1272,6 @@ for dtype in jtu.dtypes.all:\nfor f_lax in [\nlax.scatter_add, lax.scatter_mul, lax.scatter_max, lax.scatter_min\n]:\n- #if f_lax in [lax.scatter_add, lax.scatter_mul] and dtype == np.bool_:\n- # continue\n_make_scatter_harness(\"dtypes\", dtype=dtype, f_lax=f_lax)\n# Validate f_lax/update_jaxpr\n@@ -1278,7 +1279,7 @@ for dtype in jtu.dtypes.all:\n# is lambda x, y: y, which is not commutative and thus makes results\n# non-deterministic when an index into the operand is updated several times.\n-# Validate shapes, dimension numbers and scatter indices\n+# Validate shapes, dimension numbers and scatter indices. All are in bounds.\nfor shape, scatter_indices, update_shape, dimension_numbers in [\n((10,), [[0], [0], [0]], (3, 2), ((1,), (), (0,))),\n((10, 5), [[0], [2], [1]], (3, 3), ((1,), (0,), (0,)))\n@@ -1299,7 +1300,19 @@ _make_scatter_harness(\"indices_are_sorted\", indices_are_sorted=True)\n# regards to the choice of parameters, as the results are only predictable\n# when all the indices to be updated are pairwise non-overlapping. Identifying\n# such cases is non-trivial.\n-_make_scatter_harness(\"unique_indices\", unique_indices=False)\n+# _make_scatter_harness(\"unique_indices\", unique_indices=False)\n+\n+# Validate different out-of-bounds modes\n+for mode in (lax.GatherScatterMode.PROMISE_IN_BOUNDS,\n+ lax.GatherScatterMode.FILL_OR_DROP,\n+ lax.GatherScatterMode.CLIP):\n+ # Test with the indices in bounds\n+ _make_scatter_harness(\"modes_in_bounds\", mode=mode)\n+ _make_scatter_harness(\"modes_out_of_bounds\", mode=mode,\n+ shape=(5,),\n+ scatter_indices=np.array([[4], [77]]),\n+ update_shape=(2,))\n+\nfor dtype in jtu.dtypes.all:\narg_shape = (2, 3)\n@@ -2990,9 +3003,10 @@ if config.jax_enable_x64:\ndefine(\nlax.rng_bit_generator_p,\nf\"shape={jtu.format_shape_dtype_string(shape, dtype)}_algorithm={algorithm}\",\n- lambda key: lax.rng_bit_generator(key, shape, dtype=dtype,\n+ lambda key, shape, dtype, algorithm: lax.rng_bit_generator(key, shape, dtype=dtype,\nalgorithm=algorithm),\n- [RandArg((2,), np.uint64)],\n+ [RandArg((2,), np.uint64),\n+ StaticArg(shape), StaticArg(dtype), StaticArg(algorithm)],\nshape=shape,\ndtype=dtype,\nalgorithm=algorithm)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -100,7 +100,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(\nprimitive_harness.all_harnesses,\ninclude_jax_unimpl=False,\n- # one_containing=\"reduce_window_same_padding\"\n+ #one_containing=\"mode=GatherScatterMode.CLIP\"\n)\n@jtu.ignore_warning(\ncategory=UserWarning, message=\"Using reduced precision for gradient.*\")\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": "@@ -1557,7 +1557,14 @@ _POLY_SHAPE_TEST_HARNESSES = [\npartial(lax.scatter_add, indices_are_sorted=False, unique_indices=True),\n[RandArg((7, 4), _f32),\nnp.array([[1], [2]], np.int32), # indices\n- RandArg((7, 2), _f32), # upd\n+ RandArg((7, 2), _f32), # updates\n+ StaticArg(lax.ScatterDimensionNumbers((0,), (1,), (1,)))],\n+ poly_axes=[0, None, 0]),\n+ _make_harness(\"scatter_add\", \"clip\",\n+ partial(lax.scatter_add, indices_are_sorted=False, unique_indices=True, mode=lax.GatherScatterMode.CLIP),\n+ [RandArg((7, 4), _f32),\n+ np.array([[1], [2]], np.int32), # indices\n+ RandArg((7, 2), _f32), # updates\nStaticArg(lax.ScatterDimensionNumbers((0,), (1,), (1,)))],\npoly_axes=[0, None, 0]),\n_make_harness(\"select\", \"0\",\n@@ -1776,7 +1783,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# to parameterized below.\n@primitive_harness.parameterized(\n_flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"arange_stop_error\"\n+ #one_containing=\"scatter_add_clip_poly_axes\"\n)\ndef test_prim(self, harness: Harness):\nargs = harness.dyn_args_maker(self.rng())\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Implement CLIP mode for scatter.
Also handle a limited form of shape polymorphism, where
the `operand.shape - update.shape` is a constant in the scatter dimensions,
even when the shapes may contain dimension variables. |
260,562 | 29.11.2021 06:26:12 | 28,800 | 4f80e6af6eb6afb68ec68e1bedf4829cabf144e2 | [XLA] More error tolerance adjustments due to incoming change in XLA:CPU
We are about to change the vectorization strategy for XLA:CPU. As a result, we have
to increase the error tolerance of the impacted tests. | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_scipy_test.py",
"new_path": "tests/lax_scipy_test.py",
"diff": "@@ -406,7 +406,7 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nactual = jnp.real(\nlsp_special.sph_harm(jnp.array([0]), jnp.array([1]), theta, phi, n_max))\n- self.assertAllClose(actual, expected, rtol=7e-8, atol=1.5e-8)\n+ self.assertAllClose(actual, expected, rtol=2e-7, atol=6e-8)\ndef testSphHarmOrderOneDegreeOne(self):\n\"\"\"Tests the spherical harmonics of order one and degree one.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | [XLA] More error tolerance adjustments due to incoming change in XLA:CPU
We are about to change the vectorization strategy for XLA:CPU. As a result, we have
to increase the error tolerance of the impacted tests.
PiperOrigin-RevId: 412872724 |
260,424 | 30.11.2021 13:58:52 | 0 | cb6a3f216f814f7687be3e1c4bbb2b5c5e0987cb | Leak checker: garbage collect before collecting hanging references. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -793,6 +793,8 @@ 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+ gc.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)))\nreturn tracers\n"
}
] | Python | Apache License 2.0 | google/jax | Leak checker: garbage collect before collecting hanging references. |
260,447 | 30.11.2021 15:47:50 | 28,800 | 19554e21d3da3d2caf4c1249e1e806d0e786bee5 | Enable QDWH TPU tests. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/qdwh.py",
"new_path": "jax/_src/lax/qdwh.py",
"diff": "@@ -180,6 +180,7 @@ def qdwh(x, is_symmetric, max_iterations=10):\n'`norm(x-x.H) / norm(x)` is {}, which is greater than '\n'the tolerance {}.'.format(relative_diff, tol))\n+ with jax.default_matmul_precision('float32'):\nu, h, num_iters, is_converged = _qdwh(x, is_symmetric, max_iterations)\nreturn u, h, num_iters, is_converged\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/qdwh_test.py",
"new_path": "tests/qdwh_test.py",
"diff": "# limitations under the License\n\"\"\"Tests for the library of QDWH-based polar decomposition.\"\"\"\n+import functools\nfrom jax import test_util as jtu\nfrom jax.config import config\n@@ -28,14 +29,14 @@ from absl.testing import parameterized\nconfig.parse_flags_with_absl()\n_JAX_ENABLE_X64 = config.x64_enabled\n-# Input matrix data type for PolarTest.\n-_POLAR_TEST_DTYPE = np.float64 if _JAX_ENABLE_X64 else np.float32\n+# Input matrix data type for QdwhTest.\n+_QDWH_TEST_DTYPE = np.float64 if _JAX_ENABLE_X64 else np.float32\n-# Machine epsilon used by PolarTest.\n-_POLAR_TEST_EPS = jnp.finfo(_POLAR_TEST_DTYPE).eps\n+# Machine epsilon used by QdwhTest.\n+_QDWH_TEST_EPS = jnp.finfo(_QDWH_TEST_DTYPE).eps\n-# Largest log10 value of condition numbers used by PolarTest.\n-_MAX_LOG_CONDITION_NUM = np.log10(int(1 / _POLAR_TEST_EPS))\n+# Largest log10 value of condition numbers used by QdwhTest.\n+_MAX_LOG_CONDITION_NUM = np.log10(int(1 / _QDWH_TEST_EPS))\ndef _check_symmetry(x: jnp.ndarray) -> bool:\n@@ -50,8 +51,14 @@ def _check_symmetry(x: jnp.ndarray) -> bool:\nreturn is_symmetric\n+def _compute_relative_diff(actual, expected):\n+ \"\"\"Computes relative difference between two matrices.\"\"\"\n+ return np.linalg.norm(actual - expected) / np.linalg.norm(expected)\n-class PolarTest(jtu.JaxTestCase):\n+_dot = functools.partial(jnp.dot, precision=\"highest\")\n+\n+\n+class QdwhTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n{ # pylint:disable=g-complex-comprehension\n@@ -85,38 +92,42 @@ class PolarTest(jtu.JaxTestCase):\n'm': m, 'n': n, 'log_cond': log_cond}\nfor m, n in zip([8, 10, 20], [6, 10, 18])\nfor log_cond in np.linspace(1, _MAX_LOG_CONDITION_NUM, 4)))\n- # TODO(tianjianlu): Fails on A100 GPU and TPU.\n- @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ # TODO(tianjianlu): Fails on A100 GPU.\n+ @jtu.skip_on_devices(\"gpu\")\ndef testQdwhWithUpperTriangularInputAllOnes(self, m, n, log_cond):\n\"\"\"Tests qdwh with upper triangular input of all ones.\"\"\"\n- a = jnp.triu(jnp.ones((m, n)))\n+ a = jnp.triu(jnp.ones((m, n))).astype(_QDWH_TEST_DTYPE)\nu, s, v = jnp.linalg.svd(a, full_matrices=False)\ncond = 10**log_cond\ns = jnp.linspace(cond, 1, min(m, n))\na = (u * s) @ v\nis_symmetric = _check_symmetry(a)\nmax_iterations = 10\n+\nactual_u, actual_h, _, _ = qdwh.qdwh(a, is_symmetric, max_iterations)\nexpected_u, expected_h = osp_linalg.polar(a)\n# Sets the test tolerance.\n- rtol = 1E6 * _POLAR_TEST_EPS\n+ rtol = 1E6 * _QDWH_TEST_EPS\nwith self.subTest('Test u.'):\n- self.assertAllClose(actual_u, expected_u, rtol=rtol)\n+ relative_diff_u = _compute_relative_diff(actual_u, expected_u)\n+ np.testing.assert_almost_equal(relative_diff_u, 1E-6, decimal=5)\nwith self.subTest('Test h.'):\n- self.assertAllClose(actual_h, expected_h, rtol=rtol)\n+ relative_diff_h = _compute_relative_diff(actual_h, expected_h)\n+ np.testing.assert_almost_equal(relative_diff_h, 1E-6, decimal=5)\nwith self.subTest('Test u.dot(h).'):\n- a_round_trip = actual_u.dot(actual_h)\n- self.assertAllClose(a_round_trip, a, rtol=rtol)\n+ a_round_trip = _dot(actual_u, actual_h)\n+ relative_diff_a = _compute_relative_diff(a_round_trip, a)\n+ np.testing.assert_almost_equal(relative_diff_a, 1E-6, decimal=5)\nwith self.subTest('Test orthogonality.'):\n- actual_results = actual_u.T.dot(actual_u)\n+ actual_results = _dot(actual_u.T, actual_u)\nexpected_results = np.eye(n)\nself.assertAllClose(\n- actual_results, expected_results, rtol=rtol, atol=1E-4)\n+ actual_results, expected_results, rtol=rtol, atol=1E-5)\n@parameterized.named_parameters(jtu.cases_from_list(\n{ # pylint:disable=g-complex-comprehension\n@@ -125,12 +136,10 @@ class PolarTest(jtu.JaxTestCase):\n'm': m, 'n': n, 'log_cond': log_cond}\nfor m, n in zip([6, 8], [6, 4])\nfor log_cond in np.linspace(1, 4, 4)))\n- # TODO(tianjianlu): Fails on TPU.\n- @jtu.skip_on_devices(\"gpu\", \"tpu\")\ndef testQdwhWithRandomMatrix(self, m, n, log_cond):\n\"\"\"Tests qdwh with random input.\"\"\"\nrng = jtu.rand_uniform(self.rng(), low=0.3, high=0.9)\n- a = rng((m, n), _POLAR_TEST_DTYPE)\n+ a = rng((m, n), _QDWH_TEST_DTYPE)\nu, s, v = jnp.linalg.svd(a, full_matrices=False)\ncond = 10**log_cond\ns = jnp.linspace(cond, 1, min(m, n))\n@@ -146,7 +155,7 @@ class PolarTest(jtu.JaxTestCase):\nargs_maker = lambda: [a]\n# Sets the test tolerance.\n- rtol = 1E6 * _POLAR_TEST_EPS\n+ rtol = 1E6 * _QDWH_TEST_EPS\nwith self.subTest('Test JIT compatibility'):\nself._CompileAndCheck(lsp_linalg_fn, args_maker)\n@@ -157,15 +166,16 @@ class PolarTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n{ # pylint:disable=g-complex-comprehension\n- 'testcase_name': '_m={}_by_n={}_log_cond={}'.format(m, n, log_cond),\n+ 'testcase_name': '_m={}_by_n={}_log_cond={}'.format(\n+ m, n, log_cond),\n'm': m, 'n': n, 'log_cond': log_cond}\nfor m, n in zip([10, 12], [10, 12])\nfor log_cond in np.linspace(1, 4, 4)))\n- # TODO(tianjianlu): Fails on A100 GPU and TPU.\n- @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ # TODO(tianjianlu): Fails on A100 GPU.\n+ @jtu.skip_on_devices(\"gpu\")\ndef testQdwhWithOnRankDeficientInput(self, m, n, log_cond):\n\"\"\"Tests qdwh with rank-deficient input.\"\"\"\n- a = jnp.triu(jnp.ones((m, n))).astype(_POLAR_TEST_DTYPE)\n+ a = jnp.triu(jnp.ones((m, n))).astype(_QDWH_TEST_DTYPE)\n# Generates a rank-deficient input.\nu, s, v = jnp.linalg.svd(a, full_matrices=False)\n@@ -180,21 +190,23 @@ class PolarTest(jtu.JaxTestCase):\n_, expected_h = osp_linalg.polar(a)\n# Sets the test tolerance.\n- rtol = 1E6 * _POLAR_TEST_EPS\n+ rtol = 1E6 * _QDWH_TEST_EPS\n# For rank-deficient matrix, `u` is not unique.\nwith self.subTest('Test h.'):\n- self.assertAllClose(actual_h, expected_h, rtol=rtol)\n+ relative_diff_h = _compute_relative_diff(actual_h, expected_h)\n+ np.testing.assert_almost_equal(relative_diff_h, 1E-6, decimal=5)\nwith self.subTest('Test u.dot(h).'):\n- a_round_trip = actual_u.dot(actual_h)\n- self.assertAllClose(a_round_trip, a, rtol=rtol)\n+ a_round_trip = _dot(actual_u, actual_h)\n+ relative_diff_a = _compute_relative_diff(a_round_trip, a)\n+ np.testing.assert_almost_equal(relative_diff_a, 1E-6, decimal=5)\nwith self.subTest('Test orthogonality.'):\n- actual_results = actual_u.T.dot(actual_u)\n+ actual_results = _dot(actual_u.T, actual_u)\nexpected_results = np.eye(n)\nself.assertAllClose(\n- actual_results, expected_results, rtol=rtol, atol=1E-5)\n+ actual_results, expected_results, rtol=rtol, atol=1E-3)\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Enable QDWH TPU tests. |
260,411 | 29.11.2021 13:34:47 | -7,200 | 6288d67fefec5dad8b0a42055e071d647ba1be06 | Refactor the lowering of remat.
Replace the XLA-specific lowering with the same logic written
with LAX primitives. Then use this for HLO, MLIR, and jax2tf lowerings. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -281,18 +281,6 @@ def remat_abstract_eval(*args, jaxpr, prevent_cse, differentiated, policy):\ndel args, prevent_cse, differentiated, policy # Unused.\nreturn [v.aval for v in jaxpr.outvars]\n-def remat_translation(ctx, avals_in, avals_out, *in_nodes,\n- jaxpr, prevent_cse, differentiated, policy):\n- del policy # Unused.\n- if differentiated and prevent_cse:\n- if ctx.platform == \"gpu\":\n- return xla._remat_using_while(ctx, in_nodes, \"checkpoint\", jaxpr)\n- else:\n- return xla._remat_using_cond(ctx, in_nodes, \"checkpoint\", jaxpr)\n- else:\n- return xla.jaxpr_subcomp(ctx, jaxpr, (), *in_nodes)\n-xla.register_translation(remat_p, remat_translation)\n-\ndef remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\nassert not jaxpr.constvars\nin_nonzeros = [type(t) is not ad_util.Zero for t in tangents]\n@@ -347,14 +335,14 @@ def remat_partial_eval(trace, *tracers, jaxpr, **params):\nreturn pe._zip_knowns(out_known_tracers, out_jaxpr_tracers, out_unknowns)\npe.custom_partial_eval_rules[remat_p] = remat_partial_eval\n-def remat_paratial_eval_custom_params_updater(_, __, params_known, params_staged):\n+def remat_partial_eval_custom_params_updater(_, __, params_known, params_staged):\njaxpr_known = params_known.pop('call_jaxpr')\njaxpr_staged = params_staged.pop('call_jaxpr')\nreturn (dict(params_known, jaxpr=jaxpr_known),\ndict(params_staged, jaxpr=jaxpr_staged, differentiated=True))\npe.partial_eval_jaxpr_custom_rules[remat_p] = \\\npartial(pe.call_partial_eval_custom_rule, 'jaxpr',\n- remat_paratial_eval_custom_params_updater)\n+ remat_partial_eval_custom_params_updater)\ndef remat_transpose(reduce_axes, out_cts, *in_primals, jaxpr, **params):\nassert not jaxpr.constvars\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow.py",
"new_path": "jax/_src/lax/control_flow.py",
"diff": "@@ -31,6 +31,7 @@ import numpy as np\nimport jax\nfrom jax._src import api\nfrom jax import core\n+from jax._src import ad_checkpoint\nfrom jax._src import dtypes\nfrom jax._src import source_info_util\nfrom jax._src import util\n@@ -51,7 +52,7 @@ from jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.lib import xla_client\nfrom jax._src.traceback_util import api_boundary\nfrom jax._src.util import (unzip2, unzip3, safe_map, safe_zip,\n- split_list, cache, extend_name_stack)\n+ split_list, cache, extend_name_stack, wrap_name)\nfrom jax.tree_util import (tree_flatten, tree_unflatten, treedef_is_leaf,\ntreedef_children, treedef_tuple, tree_multimap,\ntree_leaves, tree_structure)\n@@ -2924,3 +2925,92 @@ def _cumulative_jvp_rule(primals, tangents, *, axis: int, reverse: bool,\nad.primitive_jvps[cumprod_p] = partial(_cumulative_jvp_rule, combine_fn=lax.mul)\nad.primitive_jvps[cummin_p] = partial(_cumulative_jvp_rule, combine_fn=lax.min)\nad.primitive_jvps[cummax_p] = partial(_cumulative_jvp_rule, combine_fn=lax.max)\n+\n+\n+def _dummy_remat_result(aval: core.AbstractValue):\n+ \"\"\"A result that will be discarded\"\"\"\n+ if aval is core.AbstractToken:\n+ return lax.create_token()\n+ elif aval is core.abstract_unit:\n+ return core.unit\n+ else:\n+ return lax.broadcast(np.array(0, dtype=aval.dtype), aval.shape) # type: ignore\n+\n+def _remat_translation_using_cond(*args,\n+ jaxpr: core.Jaxpr):\n+ # Implements:\n+ # if(rng(0, 1) < 2)\n+ # return eval_jaxpr(*args)\n+ # else:\n+ # return 0\n+ avals_out = tuple(ov.aval for ov in jaxpr.outvars)\n+\n+ def remat_comp(*args):\n+ return tuple(core.eval_jaxpr(jaxpr, (), *args))\n+ def dummy_comp(*args):\n+ return tuple(_map(_dummy_remat_result, avals_out))\n+\n+ cond_pred = (lax.rng_uniform(np.int32(0), np.int32(1), shape=()) < np.int32(2))\n+ return cond(cond_pred, remat_comp, dummy_comp, *args)\n+\n+def _remat_translation_using_while(*args,\n+ jaxpr: core.Jaxpr):\n+ # Implements:\n+ # for(counter=0, result=0; counter < rng(1, 2); counter ++) {\n+ # result = eval_jaxpr(*args)\n+ # }\n+ # The loop carry is a tuple: (counter, result, args)\n+ avals_out = tuple(ov.aval for ov in jaxpr.outvars)\n+ dummies_like_result = tuple(_map(_dummy_remat_result, avals_out))\n+ carry_init = (np.int32(0), dummies_like_result, args)\n+ def cond(carry):\n+ counter, _, _ = carry\n+ return counter < lax.rng_uniform(np.int32(1), np.int32(2), shape=())\n+\n+ def body(carry):\n+ counter, _, args = carry\n+ results = core.eval_jaxpr(jaxpr, (), *args)\n+ return (counter + 1, tuple(results), args)\n+\n+ carry_res = while_loop(cond, body, carry_init)\n+ return carry_res[1]\n+\n+def _remat_translation_rule(*args,\n+ call_jaxpr: Optional[core.Jaxpr] = None,\n+ jaxpr: Optional[core.Jaxpr] = None,\n+ platform: str,\n+ prevent_cse: bool, differentiated: bool,\n+ policy,\n+ concrete: bool = False,\n+ name: str = \"checkpoint\"):\n+ # Support either \"jaxpr\" (for remat2) and \"call_jaxpr\" (for remat)\n+ # name is not passed for remat2, defaults to \"checkpoint\"\n+ # TODO: remove call_jaxpr once we drop the remat call primitive\n+ if jaxpr is None:\n+ jaxpr = call_jaxpr\n+ assert jaxpr is not None\n+ assert not jaxpr.constvars\n+\n+ del concrete, policy # Unused.\n+ if differentiated and prevent_cse:\n+ if platform == \"gpu\":\n+ translation_rule = _remat_translation_using_while\n+ else:\n+ translation_rule = _remat_translation_using_cond\n+ else:\n+ translation_rule = lambda *args, jaxpr: core.eval_jaxpr(jaxpr, (), *args)\n+\n+ return jax.named_call(translation_rule, name=wrap_name(name, \"remat\"))(*args, jaxpr=jaxpr)\n+\n+for platform in (\"cpu\", \"gpu\", \"tpu\"):\n+ for remat_primitive in (pe.remat_call_p, ad_checkpoint.remat_p): # type: ignore\n+ xla.register_translation(remat_primitive,\n+ xla.lower_fun(partial(_remat_translation_rule,\n+ platform=platform),\n+ new_style=True, multiple_results=True,\n+ backend=platform),\n+ platform=platform)\n+ mlir.register_lowering(remat_primitive,\n+ mlir.lower_fun(partial(_remat_translation_rule,\n+ platform=platform),\n+ multiple_results=True))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -24,13 +24,14 @@ from jax import lax\nfrom jax._src import ad_util\nfrom jax._src import api_util\nfrom jax import config\n-from jax._src import api\nfrom jax import core, custom_derivatives\n-from jax._src import dispatch\n-from jax._src import dtypes\nfrom jax import linear_util as lu\nfrom jax import random, tree_util\nfrom jax import numpy as jnp\n+from jax._src import ad_checkpoint\n+from jax._src import api\n+from jax._src import dispatch\n+from jax._src import dtypes\nfrom jax._src.lax import control_flow as lax_control_flow\nfrom jax._src.lax import lax as lax_internal\nfrom jax._src.lax import linalg as lax_linalg\n@@ -856,7 +857,7 @@ class TensorFlowTrace(core.Trace):\nassert call_primitive.multiple_results\nvals: Sequence[TfVal] = [t.val for t in tracers]\navals: Sequence[core.ShapedArray] = tuple(t.aval for t in tracers)\n- fun = _interpret_subtrace(fun, self.main, avals)\n+ interpreted_fun = _interpret_subtrace(fun, self.main, avals)\nextra_name_stack = None\nif call_primitive == core.named_call_p:\nextra_name_stack = util.wrap_name(params[\"name\"], \"named\")\n@@ -867,9 +868,9 @@ class TensorFlowTrace(core.Trace):\nif call_primitive == core.named_call_p:\nwith tf.name_scope(_sanitize_scope_name(params[\"name\"])):\nvals_out: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\n- fun.call_wrapped(*vals)\n+ interpreted_fun.call_wrapped(*vals)\nelif call_primitive == sharded_jit.sharded_call_p:\n- vals_out = _sharded_call(fun, vals, **params)\n+ vals_out = _sharded_call(interpreted_fun, vals, **params)\nelif call_primitive == xla.xla_call_p:\nif _WRAP_JAX_JIT_WITH_TF_FUNCTION:\n# Make a nested tf.function(jit_compile=True)\n@@ -877,7 +878,7 @@ class TensorFlowTrace(core.Trace):\ndef f_tf(*tf_args):\nnonlocal store_tf_res_avals\ntf_res_out: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\n- _call_wrapped_with_new_constant_cache(fun, tf_args,\n+ _call_wrapped_with_new_constant_cache(interpreted_fun, tf_args,\nfresh_constant_cache=False)\ntf_res_vals, tf_res_avals = util.unzip2(tf_res_out)\nstore_tf_res_avals = tf_res_avals\n@@ -885,9 +886,9 @@ class TensorFlowTrace(core.Trace):\ntf_vals_out = tf.function(f_tf, autograph=False, jit_compile=True)(*vals)\nvals_out = zip(tf_vals_out, store_tf_res_avals)\nelse:\n- vals_out = fun.call_wrapped(*vals)\n+ vals_out = interpreted_fun.call_wrapped(*vals)\nelse:\n- vals_out = fun.call_wrapped(*vals)\n+ vals_out = interpreted_fun.call_wrapped(*vals)\nreturn [TensorFlowTracer(self, v, a) for v, a in vals_out]\ndef post_process_call(self, call_primitive: core.Primitive,\n@@ -963,13 +964,11 @@ for unexpected in [core.call_p, core.named_call_p, xla.xla_call_p,\n# Primitives that are not yet implemented must be explicitly declared here.\ntf_not_yet_impl = [\n- \"rng_uniform\",\n\"clz\",\n\"igamma_grad_a\",\n\"random_gamma_grad\",\n\"reduce_precision\",\n\"schur\",\n- \"remat2\", # TODO(mattjj,necula): support new remat?\n\"name\",\n# Not high priority?\n@@ -2035,6 +2034,13 @@ def _rng_bit_generator(key: TfVal, *, shape, dtype, algorithm) -> Sequence[TfVal\ntf_impl[lax.rng_bit_generator_p] = _rng_bit_generator\n+def _rng_uniform(minval: TfVal, maxval: TfVal, *, shape) -> TfVal:\n+ shape_tf = _eval_shape(shape)\n+ return tf.random.uniform(shape_tf, minval=minval, maxval=maxval, dtype=minval.dtype)\n+\n+tf_impl[lax.rng_uniform_p] = _rng_uniform\n+\n+\ndef _gather_dimensions_proto(indices_shape, dimension_numbers):\nproto = xla_data_pb2.GatherDimensionNumbers()\nproto.offset_dims.extend(dimension_numbers.offset_dims)\n@@ -2274,6 +2280,12 @@ tf_impl_with_avals[lax.scan_p] = _convert_jax_impl(\nlax_control_flow._scan_impl,\nextra_name_stack=\"scan\")\n+tf_impl_with_avals[ad_checkpoint.remat_p] = \\\n+ _convert_jax_impl(partial(lax_control_flow._remat_translation_rule,\n+ # TODO: jax2tf cannot discriminate by platform\n+ platform=\"tpu\"),\n+ multiple_results=True,\n+ extra_name_stack=\"checkpoint\")\ndef _top_k(operand: TfVal, k: int) -> Tuple[TfVal, TfVal]:\n# Some types originally incompatible with tf.math.top_k can be promoted\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "Specific JAX primitive conversion tests are in primitives_test.\"\"\"\n+import unittest\nfrom typing import Dict, Tuple\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\n+from jax import ad_checkpoint\nfrom jax import dtypes\nfrom jax import lax\nfrom jax import numpy as jnp\n@@ -635,25 +637,33 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.TransformConvertAndCompare(f, arg, \"grad\")\nself.TransformConvertAndCompare(f, arg, \"grad_vmap\")\n- def test_remat1(self):\n- @jax.remat\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"_{flavor}\", flavor=flavor)\n+ for flavor in [\"old\", \"new\"]))\n+ def test_remat(self, flavor=\"old\"):\ndef f(x1):\nx2 = jnp.sin(x1)\nx3 = jnp.sin(x2)\nx4 = jnp.sin(x3)\n- return jnp.sum(x4)\n+ return x4\n+ remat_f = jax.remat(f) if flavor == \"old\" else ad_checkpoint.checkpoint(f)\n# The computation of grad_f computes \"sin\" 5 times, 3 for the forward pass\n# and then to rematerialize \"x2\" and \"x3\" in the backward pass.\n- arg = np.arange(3.)\n- self.TransformConvertAndCompare(f, arg, \"grad\")\n- # TODO: check that the TF code also computes \"sin\" 5 times\n+ arg = np.array(3.)\n+ # Check that we have a Sin under a conditional\n+ f_tf = tf.function(jax2tf.convert(jax.grad(remat_f)), autograph=False)\n+ f_tf_graph = f_tf.get_concrete_function(arg).graph.as_graph_def()\n+ if flavor == \"old\":\n+ raise unittest.SkipTest(\"TODO: CSE widget not yet implemented for old-style remat\")\n+ self.assertRegex(str(f_tf_graph),\n+ r'remat_checkpoint_/switch_case/indexed_case/Sin')\ndef test_remat_free_var(self):\ndef f(x):\ny = 2 * x\n- @jax.remat\n+ @ad_checkpoint.checkpoint\ndef g():\nreturn y\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -640,90 +640,6 @@ def xla_fallback_lowering(prim: core.Primitive, ctx: LoweringContext,\nregister_lowering(ad.custom_lin_p, ad._raise_custom_vjp_error_on_jvp)\n-\n-def _dummy_like_aval(aval: core.AbstractValue) -> Sequence[ir.Value]:\n- if isinstance(aval, core.ShapedArray):\n- return [full_like_aval(0, aval)]\n- elif isinstance(aval, core.AbstractToken):\n- return mhlo.CreateTokenOp(aval_to_ir_type(aval)).results\n- elif isinstance(aval, core.AbstractUnit):\n- return ()\n- else:\n- raise TypeError(f\"Unsupported abstract value {aval}\")\n-\n-def _remat_using_while(ctx, avals_in, avals_out, *args, name, call_jaxpr):\n- input_types = map(aval_to_ir_types, avals_in)\n- output_types = map(aval_to_ir_types, avals_out)\n- flat_output_types = util.flatten(output_types)\n- int32_scalar_type = aval_to_ir_type(core.ShapedArray((), np.dtype(np.int32)))\n- loop_carry_types = [(int32_scalar_type,)] + input_types + output_types\n- flat_loop_carry_types = util.flatten(loop_carry_types)\n- counter_init = ir_constants(np.array(0, np.int32))\n- flat_args = flatten_lowering_ir_args(\n- (counter_init,) + args +\n- tuple(_dummy_like_aval(aval) for aval in avals_out))\n- loop_carry_tuple_type = ir.TupleType.get_tuple(flat_loop_carry_types)\n- init_carry = mhlo.TupleOp(loop_carry_tuple_type, flat_args)\n-\n- one = ir_constant(np.array(1, np.int32))\n- while_op = mhlo.WhileOp([loop_carry_tuple_type], [init_carry.result])\n-\n- # Loop condition\n- cond_block = while_op.regions[0].blocks.append(loop_carry_tuple_type)\n- with ir.InsertionPoint(cond_block):\n- bool_scalar_type = aval_to_ir_type(core.ShapedArray((), np.dtype(np.bool_)))\n- two = ir_constant(np.array(2, np.int32))\n- shape = ir_constant(np.array((), np.int64), canonicalize_types=False)\n- rng = mhlo.RngUniformOp(one, two, shape).result\n- i = mhlo.GetTupleElementOp(int32_scalar_type, cond_block.arguments[0],\n- i32_attr(0))\n- cmp = mhlo.CompareOp(bool_scalar_type, i, rng, ir.StringAttr.get(\"LT\"),\n- ir.StringAttr.get(\"SIGNED\")).result\n- mhlo.ReturnOp([cmp])\n-\n- body_block = while_op.regions[1].blocks.append(loop_carry_tuple_type)\n- with ir.InsertionPoint(body_block):\n- flat_body_args = [\n- mhlo.GetTupleElementOp(input_type, body_block.arguments[0],\n- i32_attr(i)).result\n- for i, input_type in enumerate(flat_loop_carry_types)]\n- body_args = util.unflatten(flat_body_args, map(len, loop_carry_types))\n- ((i,),), y, _ = util.split_list(body_args, [1, len(avals_in)])\n- body_ctx = ctx.replace(\n- name_stack=xla.extend_name_stack(ctx.name_stack,\n- xla.wrap_name(name, 'remat')))\n- z = jaxpr_subcomp(body_ctx, call_jaxpr, (), *y)\n- i_next = mhlo.AddOp(i, one).result\n- new_carry = mhlo.TupleOp(\n- loop_carry_tuple_type,\n- [i_next, *util.flatten(y), *util.flatten(z)])\n- mhlo.ReturnOp([new_carry.result])\n-\n- outputs = [mhlo.GetTupleElementOp(output_type, while_op.result,\n- i32_attr(1 + len(avals_in) + i)\n- ).result\n- for i, output_type in enumerate(flat_output_types)]\n- return util.unflatten(outputs, map(len, output_types))\n-\n-\n-def _remat_lowering(ctx, avals_in, avals_out, *args,\n- name, call_jaxpr,\n- prevent_cse, differentiated, concrete,\n- policy, device=None):\n- del device, concrete, policy # Unused.\n- if differentiated and prevent_cse:\n- if True: # ctx.platform == \"gpu\":\n- return _remat_using_while(ctx, avals_in, avals_out, *args, name=name,\n- call_jaxpr=call_jaxpr)\n- else:\n- assert False\n- #return _remat_using_cond(ctx, args, name, call_jaxpr)\n- else:\n- return jaxpr_subcomp(\n- ctx, call_jaxpr, (), *map(wrap_singleton_ir_values, args))\n-\n-register_lowering(pe.remat_call_p, _remat_lowering)\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": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -657,7 +657,7 @@ def tracers_to_jaxpr(\nreturn jaxpr, const_vals, env_vals\n@cache()\n-def convert_constvars_jaxpr(jaxpr: Jaxpr):\n+def convert_constvars_jaxpr(jaxpr: Jaxpr) -> Jaxpr:\n\"\"\"Moves the constvars to the start of invars.\"\"\"\nconfig.jax_enable_checks and core.check_jaxpr(jaxpr)\nlifted_jaxpr = Jaxpr(constvars=(),\n@@ -666,7 +666,7 @@ def convert_constvars_jaxpr(jaxpr: Jaxpr):\nconfig.jax_enable_checks and core.check_jaxpr(lifted_jaxpr)\nreturn lifted_jaxpr\n-def convert_envvars_to_constvars(jaxpr: Jaxpr, num_env_vars: int):\n+def convert_envvars_to_constvars(jaxpr: Jaxpr, num_env_vars: int) -> Jaxpr:\nconfig.jax_enable_checks and core.check_jaxpr(jaxpr)\nenv_vars, invars = split_list(jaxpr.invars, [num_env_vars])\nconverted_jaxpr = Jaxpr(constvars=jaxpr.constvars + env_vars,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1035,108 +1035,6 @@ def _array_aval_from_xla_shape(xla_shape):\nassert not xla_shape.is_tuple()\nreturn ShapedArray(xla_shape.dimensions(), xla_shape.numpy_dtype())\n-\n-def _zeros(c, xla_shape):\n- if xla_shape.is_array():\n- shape, dtype = xla_shape.dimensions(), xla_shape.numpy_dtype()\n- zero = xops.Constant(c, np.array(0, dtype=dtype))\n- return xops.Broadcast(zero, shape)\n- else:\n- # It is a token\n- return xops.CreateToken(c)\n-\n-\n-def _remat_using_cond(ctx, in_nodes, name, call_jaxpr):\n- \"\"\"Lower remat to a Conditional which always returns true. This:\n- 1. Circumvents common subexpression elimination.\n- 2. In common case of `jax.grad(jax.remat(f))`, ensures the remat blocks\n- occur after the primal blocks, because cotangent is an input to the\n- Conditional.\"\"\"\n- # Fake condition which always selects True branch.\n- c = ctx.builder\n- rng = xops.RngUniform(xops.Constant(c, np.array(0, dtype=np.float32)),\n- xops.Constant(c, np.array(1, dtype=np.float32)),\n- xc.Shape.array_shape(xc.PrimitiveType.F32, []))\n- pred = xops.Lt(rng, xops.Constant(c, np.array(2, dtype=np.float32)))\n-\n- true_op = xops.Tuple(c, in_nodes)\n- remat_subc = xc.XlaBuilder(\"remat_call_subcomputation\")\n- input_op = parameter(remat_subc, 0, c.get_shape(true_op), replicated=[])\n- args = xla_destructure(remat_subc, input_op)\n- sub_ctx = ctx.replace(\n- builder=remat_subc,\n- name_stack=extend_name_stack(ctx.name_stack, wrap_name(name, 'remat')))\n- out_nodes = jaxpr_subcomp(sub_ctx, call_jaxpr, (), *args)\n- out_node_shapes = [remat_subc.get_shape(o) for o in out_nodes]\n- remat_subc = remat_subc.build(xops.Tuple(remat_subc, out_nodes))\n-\n- false_op = true_op\n- dummy_subc = xc.XlaBuilder(\"remat_call_dummy_subcomputation\")\n- parameter(dummy_subc, 0, c.get_shape(false_op), replicated=[])\n- out_nodes = [_zeros(dummy_subc, s) for s in out_node_shapes]\n- dummy_subc = dummy_subc.build(xops.Tuple(dummy_subc, out_nodes))\n-\n- return xla_destructure(\n- c, xops.Conditional(pred, true_op, remat_subc, false_op, dummy_subc))\n-\n-\n-def _remat_using_while(ctx, in_nodes, name, call_jaxpr):\n- \"\"\"Lower remat to a single iteration while loop.\"\"\"\n- c = ctx.builder\n- # Dummy subc for getting subcomp shapes.\n- dummy_inputs = xops.Tuple(c, in_nodes)\n- dummy_subc = xc.XlaBuilder(\"remat_dummy_subcomputation\")\n- dummy_input_op = parameter(dummy_subc, 0, c.get_shape(dummy_inputs), replicated=[])\n- dummy_args = xla_destructure(dummy_subc, dummy_input_op)\n- dummy_ctx = ctx.replace(\n- builder=dummy_subc,\n- name_stack=extend_name_stack(ctx.name_stack, wrap_name(name, 'remat')))\n- dummy_subcomp_outs = jaxpr_subcomp(dummy_ctx, call_jaxpr, (), *dummy_args)\n- out_node_shapes = [dummy_subc.get_shape(o) for o in dummy_subcomp_outs]\n-\n- i_init = xops.Constant(c, np.array(0, dtype=np.int32))\n- zeros_like_outs = [_zeros(c, s) for s in out_node_shapes]\n- inputs = xops.Tuple(c, [i_init] + list(in_nodes) + zeros_like_outs)\n-\n- cond_subc = xc.XlaBuilder(\"remat_cond_subcomputation\")\n- input_op = parameter(cond_subc, 0, c.get_shape(inputs), replicated=[])\n- i = xops.GetTupleElement(input_op, 0)\n- rng = xops.RngUniform(xops.Constant(cond_subc, np.array(1, dtype=np.int32)),\n- xops.Constant(cond_subc, np.array(2, dtype=np.int32)),\n- xc.Shape.array_shape(xc.PrimitiveType.S32, []))\n- cond_subc = cond_subc.build(xops.Lt(i, rng))\n-\n- body_subc = xc.XlaBuilder(\"remat_body_subcomputation\")\n- input_op = parameter(body_subc, 0, c.get_shape(inputs), replicated=[])\n- i, *args = xla_destructure(body_subc, input_op)[:len(in_nodes)+1]\n- i_next = xops.Add(i, xops.Constant(body_subc, np.array(1, dtype=np.int32)))\n- body_ctx = ctx.replace(\n- builder=body_subc,\n- name_stack=extend_name_stack(ctx.name_stack, wrap_name(name, 'remat')))\n- subcomp_outs = jaxpr_subcomp(body_ctx, call_jaxpr, (), *args)\n- out_nodes = [i_next] + args + list(subcomp_outs)\n- body_subc = body_subc.build(xops.Tuple(body_subc, out_nodes))\n- outs = xops.While(cond_subc, body_subc, inputs)\n- return xla_destructure(c, outs)[len(in_nodes)+1:]\n-\n-\n-\n-def _remat_translation_rule(ctx, avals_in, avals_out, *in_nodes,\n- name, call_jaxpr,\n- prevent_cse, differentiated, concrete,\n- policy, device=None):\n- del device, concrete, policy # Unused.\n- if differentiated and prevent_cse:\n- if ctx.platform == \"gpu\":\n- return _remat_using_while(ctx, in_nodes, name, call_jaxpr)\n- else:\n- return _remat_using_cond(ctx, in_nodes, name, call_jaxpr)\n- else:\n- return jaxpr_subcomp(ctx, call_jaxpr, (), *in_nodes)\n-\n-register_translation(pe.remat_call_p, _remat_translation_rule)\n-\n-\nad.primitive_transposes[core.named_call_p] = partial(ad.call_transpose,\ncore.named_call_p)\n"
}
] | Python | Apache License 2.0 | google/jax | Refactor the lowering of remat.
Replace the XLA-specific lowering with the same logic written
with LAX primitives. Then use this for HLO, MLIR, and jax2tf lowerings. |
260,411 | 30.11.2021 11:52:49 | -7,200 | b55e993be3aa2f0f846f6bb0935ae3d7c59a922a | [jax2tf] Add tests for rng_uniform
These tests really only verify which dtypes are supported.
The actual numeric comparison is disabled, because rng_uniform
is statefull and calling multiple times produces different results. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md",
"diff": "# Primitives with limited support for jax2tf\n-*Last generated on (YYYY-MM-DD): 2021-07-31*\n+*Last generated on (YYYY-MM-DD): 2021-11-30*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -98,6 +98,7 @@ More detailed information can be found in the\n| reduce_min | TF error: op not defined for dtype | complex | cpu, gpu, tpu | compiled, eager, graph |\n| regularized_incomplete_beta | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n| rem | TF error: TF integer division fails if divisor contains 0; JAX returns NaN | integer | cpu, gpu, tpu | compiled, eager, graph |\n+| rng_uniform | TF error: op not defined for dtype | uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n| round | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| scatter_add | TF test skipped: Not implemented in JAX: unimplemented | bool | cpu, gpu, tpu | compiled, eager, graph |\n| scatter_mul | TF test skipped: Not implemented in JAX: unimplemented | bool | cpu, gpu, tpu | compiled, eager, graph |\n@@ -142,6 +143,7 @@ with jax2tf. The following table lists that cases when this does not quite hold:\n| max | May return different values when one of the values is NaN. JAX always returns NaN, while TF returns the value NaN is compared with. | all | cpu, gpu, tpu | compiled, eager, graph |\n| min | May return different values when one of the values is NaN. JAX always returns NaN, while TF returns the value NaN is compared with. | all | cpu, gpu, tpu | compiled, eager, graph |\n| pow | custom numeric comparison | complex | cpu, gpu, tpu | eager, graph |\n+| rng_uniform | disabled numeric comparison | all | cpu, gpu, tpu | compiled, eager, graph |\n| sort | Numeric comparison disabled: TODO: TF non-stable multiple-array sort | all | gpu | compiled, eager, graph |\n| svd | custom numeric comparison when compute_uv | all | cpu, gpu | compiled, eager, graph |\n| top_k | Produces different results when the array contains `inf` and `NaN` (they are sorted differently in TF vs. XLA). | floating | cpu, gpu, tpu | eager, graph |\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"diff": "@@ -930,6 +930,24 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndef rng_bit_generator(cls, harness: primitive_harness.Harness):\nreturn []\n+ @classmethod\n+ def rng_uniform(cls, harness: primitive_harness.Harness):\n+ def custom_assert(tst, r_jax, r_tf, *, args, tol, err_msg):\n+ # Since this is using a stateful RNG, we cannot expect to get the\n+ # same result if we call repeatedly.\n+ return True\n+ return [\n+ missing_tf_kernel(\n+ dtypes=[np.uint32, np.uint64],\n+ devices=(\"cpu\", \"gpu\", \"tpu\"),\n+ modes=(\"eager\", \"graph\", \"compiled\")),\n+ custom_numeric(\n+ description=\"disabled numeric comparison\",\n+ custom_assert=custom_assert,\n+ devices=(\"cpu\", \"gpu\", \"tpu\"),\n+ modes=(\"eager\", \"graph\", \"compiled\"))\n+ ]\n+\n@classmethod\ndef round(cls, harness: primitive_harness.Harness):\nreturn [\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -1650,11 +1650,8 @@ for dtype in jtu.dtypes.all_floating + jtu.dtypes.complex:\nlax.linalg.svd_p,\nf\"shape={jtu.format_shape_dtype_string(shape, dtype)}_fullmatrices={full_matrices}_computeuv={compute_uv}\",\nlambda *args: lax.linalg.svd_p.bind(\n- args[0], full_matrices=args[1], compute_uv=args[2]), [\n- RandArg(shape, dtype),\n- StaticArg(full_matrices),\n- StaticArg(compute_uv)\n- ],\n+ args[0], full_matrices=args[1], compute_uv=args[2]),\n+ [ RandArg(shape, dtype), StaticArg(full_matrices), StaticArg(compute_uv)],\njax_unimplemented=[\nLimitation(\n\"unimplemented\",\n@@ -3003,10 +3000,23 @@ if config.jax_enable_x64:\ndefine(\nlax.rng_bit_generator_p,\nf\"shape={jtu.format_shape_dtype_string(shape, dtype)}_algorithm={algorithm}\",\n- lambda key, shape, dtype, algorithm: lax.rng_bit_generator(key, shape, dtype=dtype,\n- algorithm=algorithm),\n- [RandArg((2,), np.uint64),\n- StaticArg(shape), StaticArg(dtype), StaticArg(algorithm)],\n+ partial(lax.rng_bit_generator, shape=shape, dtype=dtype, algorithm=algorithm),\n+ [RandArg((2,), np.uint64)],\nshape=shape,\ndtype=dtype,\nalgorithm=algorithm)\n+\n+for dtype in (set(jtu.dtypes.all) -\n+ set(jtu.dtypes.complex) -\n+ set([np.int16, np.int8, np.uint16, np.uint8, np.bool_])):\n+ for shape in [(), (5, 7), (100, 100)]:\n+ define(\n+ lax.rng_uniform_p,\n+ f\"shape={jtu.format_shape_dtype_string(shape, dtype)}\",\n+ lambda minval, maxval, shape: lax.rng_uniform(minval, maxval, shape=shape),\n+ [StaticArg(np.array(0, dtype=dtype)),\n+ StaticArg(np.array(5, dtype=dtype)),\n+ StaticArg(shape)],\n+ shape=shape,\n+ dtype=dtype,\n+ )\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Add tests for rng_uniform
These tests really only verify which dtypes are supported.
The actual numeric comparison is disabled, because rng_uniform
is statefull and calling multiple times produces different results. |
260,411 | 01.12.2021 11:34:37 | -7,200 | 5b177967e62a25b63092d2a3b7dad146c5b8600b | [jax2tf] Improved error checking for call_tf for functions with dynamic
shapes. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -988,6 +988,7 @@ The zero-copy does not yet work on TPU.\n### Limitations of call_tf\nThe TF function must be compileable (`tf.function(func, jit_compile=True`)\n+and must have static output shapes\nwhen used in a JAX staging context, e.g., `jax.jit`, `lax.scan`, `lax.cond`,\nbut not when used in a JAX op-by-op mode. For example, the following\nfunction uses strings operations that are not supported by XLA:\n@@ -1021,6 +1022,14 @@ f_jax(x)\n# Fails in jit mode\njax.jit(f_jax)(x)\n```\n+Yet another unsupported situation is when the TF function\n+is compileable but with dynamic output shapes:\n+\n+```\n+def f_tf_dynamic_output_shape(x):\n+ return tf.cond(x[0] >= 0, lambda: x, lambda: x[1:])\n+x = np.array([1, 2], dtype=np.int32)\n+```\n``call_tf`` works best with pure TF functions that do not capture\n``tf.Variable``s or tensors from the environment, and all such\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -341,7 +341,7 @@ def _code_generator_and_avals(\nreturn None, result_avals\nmsg = (\"Error compiling TensorFlow function. call_tf can used \" +\n\"in a staged context (under jax.jit, lax.scan, etc.) only with \" +\n- \"compileable functions. \" +\n+ \"compileable functions with static output shapes. \" +\n\"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion.\")\nraise ValueError(msg) from e\n@@ -371,6 +371,14 @@ def _code_generator_and_avals(\n# Canonicalize the results; e.g., makes them x32 if JAX is in 32-bit mode\ndef canonical_res_aval(res_shape: xla.XlaShape) -> core.ShapedArray:\n+ if not res_shape.is_static():\n+ msg = (\"Compiled TensorFlow function has dynamic output shape \" +\n+ f\"{res_shape}. call_tf can used \" +\n+ \"in a staged context (under jax.jit, lax.scan, etc.) only with \" +\n+ \"compileable functions with static output shapes. \" +\n+ \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion.\")\n+ raise ValueError(msg)\n+\nres_dtype = res_shape.numpy_dtype()\njax_res_dtype = dtypes.canonicalize_dtype(res_dtype)\nreturn core.ShapedArray(res_shape.dimensions(), jax_res_dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -52,6 +52,10 @@ _parameterized_jit = parameterized.named_parameters(\n_named_test(with_jit=with_jit)\nfor with_jit in [True, False])\n+_call_tf_non_compileable_error = \"Error compiling TensorFlow function. call_tf can used in a staged context .* only with compileable functions\"\n+_call_tf_dynamic_shape_error = \"Compiled TensorFlow function has dynamic output shape.* call_tf can used in a staged context .* only with compileable functions\"\n+\n+\nclass CallTfTest(tf_test_util.JaxToTfTestCase):\ndef setUp(self):\n@@ -125,7 +129,6 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = fun_jax(x, y)\nself.assertAllClose((np.float32(12.), np.float64(11.)), res)\n- call_tf_non_compileable = \"Error compiling TensorFlow function. call_tf can used in a staged context .* only with compileable functions\"\ndef test_eval_non_compileable_strings(self):\n# Check that in op-by-op we call a function in eager mode.\ndef f_tf_non_compileable(x):\n@@ -135,28 +138,24 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nx = np.float32(0.7)\nself.assertAllClose(f_tf_non_compileable(x).numpy(), f_jax(x))\nwith self.assertRaisesRegex(ValueError,\n- CallTfTest.call_tf_non_compileable):\n+ _call_tf_non_compileable_error):\njax.jit(f_jax)(x)\nwith self.assertRaisesRegex(ValueError,\n- CallTfTest.call_tf_non_compileable):\n+ _call_tf_non_compileable_error):\nlax.cond(True, lambda x: f_jax(x), lambda x: f_jax(x), x)\ndef test_eval_non_compileable_dynamic_shape(self):\n# Check that in op-by-op we call a function in eager mode.\ndef f_tf_non_compileable(x):\n- return tf.where(x)\n+ return tf.cond(x[0], lambda: x[1:], lambda: x)\nf_jax = jax2tf.call_tf(f_tf_non_compileable)\nx = np.array([True, False], dtype=np.bool_)\n- self.assertAllClose(f_tf_non_compileable(x).numpy(), f_jax(x))\n+ self.assertAllClose(f_tf_non_compileable(x), f_jax(x))\n- if jtu.device_under_test() == \"tpu\":\n- # TODO: This works on TPU!!!\n- self.assertAllClose(f_tf_non_compileable(x).numpy(), jax.jit(f_jax)(x))\n- else:\nwith self.assertRaisesRegex(ValueError,\n- CallTfTest.call_tf_non_compileable):\n+ _call_tf_dynamic_shape_error):\njax.jit(f_jax)(x)\n@_parameterized_jit\n@@ -900,31 +899,28 @@ class RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(np.sin(x), res.numpy())\ndef test_function_dynamic_shape(self):\n- if jtu.device_under_test() == \"tpu\":\n- raise unittest.SkipTest(\"TODO: why does this fail on TPU?\")\n# Call a function for which shape inference does not give an output\n# shape.\nx = np.array([-1, 0, 1], dtype=np.int32)\ndef fun_tf(x): # x:i32[3]\n# The shape depends on the value of x\n- res = tf.where(x >= 0)\n- return res\n+ return tf.cond(x[0] >= 0, lambda: x, lambda: x[1:])\n# Call in eager mode. Should work!\nres1 = jax2tf.call_tf(fun_tf)(x)\n- expected = np.array([[1], [2]])\n+ expected = x[1:]\nself.assertAllClose(expected, res1, check_dtypes=False)\n# Now under jit, should fail because the function is not compileable\nwith self.assertRaisesRegex(ValueError,\n- \"Error compiling TensorFlow function. call_tf can used in a staged context\"):\n+ _call_tf_dynamic_shape_error):\nfun_jax = jax.jit(jax2tf.call_tf(fun_tf))\nfun_jax(x)\n# TODO(necula): this should work in op-by-op mode, but it fails because\n# jax2tf.convert does abstract evaluation.\nwith self.assertRaisesRegex(ValueError,\n- \"Error compiling TensorFlow function. call_tf can used in a staged context\"):\n+ _call_tf_dynamic_shape_error):\nfun_tf_rt = jax2tf.convert(jax2tf.call_tf(fun_tf))\nfun_tf_rt(x)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Improved error checking for call_tf for functions with dynamic
shapes. |
260,631 | 01.12.2021 08:42:35 | 28,800 | 610187cd332ee18b40bc9caf90e54db50f4d0659 | Copybara import of the project:
by George Necula
Refactor the lowering of remat.
Replace the XLA-specific lowering with the same logic written
with LAX primitives. Then use this for HLO, MLIR, and jax2tf lowerings. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -281,6 +281,18 @@ def remat_abstract_eval(*args, jaxpr, prevent_cse, differentiated, policy):\ndel args, prevent_cse, differentiated, policy # Unused.\nreturn [v.aval for v in jaxpr.outvars]\n+def remat_translation(ctx, avals_in, avals_out, *in_nodes,\n+ jaxpr, prevent_cse, differentiated, policy):\n+ del policy # Unused.\n+ if differentiated and prevent_cse:\n+ if ctx.platform == \"gpu\":\n+ return xla._remat_using_while(ctx, in_nodes, \"checkpoint\", jaxpr)\n+ else:\n+ return xla._remat_using_cond(ctx, in_nodes, \"checkpoint\", jaxpr)\n+ else:\n+ return xla.jaxpr_subcomp(ctx, jaxpr, (), *in_nodes)\n+xla.register_translation(remat_p, remat_translation)\n+\ndef remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\nassert not jaxpr.constvars\nin_nonzeros = [type(t) is not ad_util.Zero for t in tangents]\n@@ -335,14 +347,14 @@ def remat_partial_eval(trace, *tracers, jaxpr, **params):\nreturn pe._zip_knowns(out_known_tracers, out_jaxpr_tracers, out_unknowns)\npe.custom_partial_eval_rules[remat_p] = remat_partial_eval\n-def remat_partial_eval_custom_params_updater(_, __, params_known, params_staged):\n+def remat_paratial_eval_custom_params_updater(_, __, params_known, params_staged):\njaxpr_known = params_known.pop('call_jaxpr')\njaxpr_staged = params_staged.pop('call_jaxpr')\nreturn (dict(params_known, jaxpr=jaxpr_known),\ndict(params_staged, jaxpr=jaxpr_staged, differentiated=True))\npe.partial_eval_jaxpr_custom_rules[remat_p] = \\\npartial(pe.call_partial_eval_custom_rule, 'jaxpr',\n- remat_partial_eval_custom_params_updater)\n+ remat_paratial_eval_custom_params_updater)\ndef remat_transpose(reduce_axes, out_cts, *in_primals, jaxpr, **params):\nassert not jaxpr.constvars\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow.py",
"new_path": "jax/_src/lax/control_flow.py",
"diff": "@@ -31,7 +31,6 @@ import numpy as np\nimport jax\nfrom jax._src import api\nfrom jax import core\n-from jax._src import ad_checkpoint\nfrom jax._src import dtypes\nfrom jax._src import source_info_util\nfrom jax._src import util\n@@ -52,7 +51,7 @@ from jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.lib import xla_client\nfrom jax._src.traceback_util import api_boundary\nfrom jax._src.util import (unzip2, unzip3, safe_map, safe_zip,\n- split_list, cache, extend_name_stack, wrap_name)\n+ split_list, cache, extend_name_stack)\nfrom jax.tree_util import (tree_flatten, tree_unflatten, treedef_is_leaf,\ntreedef_children, treedef_tuple, tree_multimap,\ntree_leaves, tree_structure)\n@@ -2925,92 +2924,3 @@ def _cumulative_jvp_rule(primals, tangents, *, axis: int, reverse: bool,\nad.primitive_jvps[cumprod_p] = partial(_cumulative_jvp_rule, combine_fn=lax.mul)\nad.primitive_jvps[cummin_p] = partial(_cumulative_jvp_rule, combine_fn=lax.min)\nad.primitive_jvps[cummax_p] = partial(_cumulative_jvp_rule, combine_fn=lax.max)\n-\n-\n-def _dummy_remat_result(aval: core.AbstractValue):\n- \"\"\"A result that will be discarded\"\"\"\n- if aval is core.AbstractToken:\n- return lax.create_token()\n- elif aval is core.abstract_unit:\n- return core.unit\n- else:\n- return lax.broadcast(np.array(0, dtype=aval.dtype), aval.shape) # type: ignore\n-\n-def _remat_translation_using_cond(*args,\n- jaxpr: core.Jaxpr):\n- # Implements:\n- # if(rng(0, 1) < 2)\n- # return eval_jaxpr(*args)\n- # else:\n- # return 0\n- avals_out = tuple(ov.aval for ov in jaxpr.outvars)\n-\n- def remat_comp(*args):\n- return tuple(core.eval_jaxpr(jaxpr, (), *args))\n- def dummy_comp(*args):\n- return tuple(_map(_dummy_remat_result, avals_out))\n-\n- cond_pred = (lax.rng_uniform(np.int32(0), np.int32(1), shape=()) < np.int32(2))\n- return cond(cond_pred, remat_comp, dummy_comp, *args)\n-\n-def _remat_translation_using_while(*args,\n- jaxpr: core.Jaxpr):\n- # Implements:\n- # for(counter=0, result=0; counter < rng(1, 2); counter ++) {\n- # result = eval_jaxpr(*args)\n- # }\n- # The loop carry is a tuple: (counter, result, args)\n- avals_out = tuple(ov.aval for ov in jaxpr.outvars)\n- dummies_like_result = tuple(_map(_dummy_remat_result, avals_out))\n- carry_init = (np.int32(0), dummies_like_result, args)\n- def cond(carry):\n- counter, _, _ = carry\n- return counter < lax.rng_uniform(np.int32(1), np.int32(2), shape=())\n-\n- def body(carry):\n- counter, _, args = carry\n- results = core.eval_jaxpr(jaxpr, (), *args)\n- return (counter + 1, tuple(results), args)\n-\n- carry_res = while_loop(cond, body, carry_init)\n- return carry_res[1]\n-\n-def _remat_translation_rule(*args,\n- call_jaxpr: Optional[core.Jaxpr] = None,\n- jaxpr: Optional[core.Jaxpr] = None,\n- platform: str,\n- prevent_cse: bool, differentiated: bool,\n- policy,\n- concrete: bool = False,\n- name: str = \"checkpoint\"):\n- # Support either \"jaxpr\" (for remat2) and \"call_jaxpr\" (for remat)\n- # name is not passed for remat2, defaults to \"checkpoint\"\n- # TODO: remove call_jaxpr once we drop the remat call primitive\n- if jaxpr is None:\n- jaxpr = call_jaxpr\n- assert jaxpr is not None\n- assert not jaxpr.constvars\n-\n- del concrete, policy # Unused.\n- if differentiated and prevent_cse:\n- if platform == \"gpu\":\n- translation_rule = _remat_translation_using_while\n- else:\n- translation_rule = _remat_translation_using_cond\n- else:\n- translation_rule = lambda *args, jaxpr: core.eval_jaxpr(jaxpr, (), *args)\n-\n- return jax.named_call(translation_rule, name=wrap_name(name, \"remat\"))(*args, jaxpr=jaxpr)\n-\n-for platform in (\"cpu\", \"gpu\", \"tpu\"):\n- for remat_primitive in (pe.remat_call_p, ad_checkpoint.remat_p): # type: ignore\n- xla.register_translation(remat_primitive,\n- xla.lower_fun(partial(_remat_translation_rule,\n- platform=platform),\n- new_style=True, multiple_results=True,\n- backend=platform),\n- platform=platform)\n- mlir.register_lowering(remat_primitive,\n- mlir.lower_fun(partial(_remat_translation_rule,\n- platform=platform),\n- multiple_results=True))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -24,14 +24,13 @@ from jax import lax\nfrom jax._src import ad_util\nfrom jax._src import api_util\nfrom jax import config\n+from jax._src import api\nfrom jax import core, custom_derivatives\n+from jax._src import dispatch\n+from jax._src import dtypes\nfrom jax import linear_util as lu\nfrom jax import random, tree_util\nfrom jax import numpy as jnp\n-from jax._src import ad_checkpoint\n-from jax._src import api\n-from jax._src import dispatch\n-from jax._src import dtypes\nfrom jax._src.lax import control_flow as lax_control_flow\nfrom jax._src.lax import lax as lax_internal\nfrom jax._src.lax import linalg as lax_linalg\n@@ -857,7 +856,7 @@ class TensorFlowTrace(core.Trace):\nassert call_primitive.multiple_results\nvals: Sequence[TfVal] = [t.val for t in tracers]\navals: Sequence[core.ShapedArray] = tuple(t.aval for t in tracers)\n- interpreted_fun = _interpret_subtrace(fun, self.main, avals)\n+ fun = _interpret_subtrace(fun, self.main, avals)\nextra_name_stack = None\nif call_primitive == core.named_call_p:\nextra_name_stack = util.wrap_name(params[\"name\"], \"named\")\n@@ -868,9 +867,9 @@ class TensorFlowTrace(core.Trace):\nif call_primitive == core.named_call_p:\nwith tf.name_scope(_sanitize_scope_name(params[\"name\"])):\nvals_out: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\n- interpreted_fun.call_wrapped(*vals)\n+ fun.call_wrapped(*vals)\nelif call_primitive == sharded_jit.sharded_call_p:\n- vals_out = _sharded_call(interpreted_fun, vals, **params)\n+ vals_out = _sharded_call(fun, vals, **params)\nelif call_primitive == xla.xla_call_p:\nif _WRAP_JAX_JIT_WITH_TF_FUNCTION:\n# Make a nested tf.function(jit_compile=True)\n@@ -878,7 +877,7 @@ class TensorFlowTrace(core.Trace):\ndef f_tf(*tf_args):\nnonlocal store_tf_res_avals\ntf_res_out: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\n- _call_wrapped_with_new_constant_cache(interpreted_fun, tf_args,\n+ _call_wrapped_with_new_constant_cache(fun, tf_args,\nfresh_constant_cache=False)\ntf_res_vals, tf_res_avals = util.unzip2(tf_res_out)\nstore_tf_res_avals = tf_res_avals\n@@ -886,9 +885,9 @@ class TensorFlowTrace(core.Trace):\ntf_vals_out = tf.function(f_tf, autograph=False, jit_compile=True)(*vals)\nvals_out = zip(tf_vals_out, store_tf_res_avals)\nelse:\n- vals_out = interpreted_fun.call_wrapped(*vals)\n+ vals_out = fun.call_wrapped(*vals)\nelse:\n- vals_out = interpreted_fun.call_wrapped(*vals)\n+ vals_out = fun.call_wrapped(*vals)\nreturn [TensorFlowTracer(self, v, a) for v, a in vals_out]\ndef post_process_call(self, call_primitive: core.Primitive,\n@@ -964,11 +963,13 @@ for unexpected in [core.call_p, core.named_call_p, xla.xla_call_p,\n# Primitives that are not yet implemented must be explicitly declared here.\ntf_not_yet_impl = [\n+ \"rng_uniform\",\n\"clz\",\n\"igamma_grad_a\",\n\"random_gamma_grad\",\n\"reduce_precision\",\n\"schur\",\n+ \"remat2\", # TODO(mattjj,necula): support new remat?\n\"name\",\n# Not high priority?\n@@ -2034,13 +2035,6 @@ def _rng_bit_generator(key: TfVal, *, shape, dtype, algorithm) -> Sequence[TfVal\ntf_impl[lax.rng_bit_generator_p] = _rng_bit_generator\n-def _rng_uniform(minval: TfVal, maxval: TfVal, *, shape) -> TfVal:\n- shape_tf = _eval_shape(shape)\n- return tf.random.uniform(shape_tf, minval=minval, maxval=maxval, dtype=minval.dtype)\n-\n-tf_impl[lax.rng_uniform_p] = _rng_uniform\n-\n-\ndef _gather_dimensions_proto(indices_shape, dimension_numbers):\nproto = xla_data_pb2.GatherDimensionNumbers()\nproto.offset_dims.extend(dimension_numbers.offset_dims)\n@@ -2280,12 +2274,6 @@ tf_impl_with_avals[lax.scan_p] = _convert_jax_impl(\nlax_control_flow._scan_impl,\nextra_name_stack=\"scan\")\n-tf_impl_with_avals[ad_checkpoint.remat_p] = \\\n- _convert_jax_impl(partial(lax_control_flow._remat_translation_rule,\n- # TODO: jax2tf cannot discriminate by platform\n- platform=\"tpu\"),\n- multiple_results=True,\n- extra_name_stack=\"checkpoint\")\ndef _top_k(operand: TfVal, k: int) -> Tuple[TfVal, TfVal]:\n# Some types originally incompatible with tf.math.top_k can be promoted\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "Specific JAX primitive conversion tests are in primitives_test.\"\"\"\n-import unittest\nfrom typing import Dict, Tuple\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\n-from jax import ad_checkpoint\nfrom jax import dtypes\nfrom jax import lax\nfrom jax import numpy as jnp\n@@ -637,33 +635,25 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.TransformConvertAndCompare(f, arg, \"grad\")\nself.TransformConvertAndCompare(f, arg, \"grad_vmap\")\n- @parameterized.named_parameters(jtu.cases_from_list(\n- dict(testcase_name=f\"_{flavor}\", flavor=flavor)\n- for flavor in [\"old\", \"new\"]))\n- def test_remat(self, flavor=\"old\"):\n+ def test_remat1(self):\n+ @jax.remat\ndef f(x1):\nx2 = jnp.sin(x1)\nx3 = jnp.sin(x2)\nx4 = jnp.sin(x3)\n- return x4\n- remat_f = jax.remat(f) if flavor == \"old\" else ad_checkpoint.checkpoint(f)\n+ return jnp.sum(x4)\n# The computation of grad_f computes \"sin\" 5 times, 3 for the forward pass\n# and then to rematerialize \"x2\" and \"x3\" in the backward pass.\n- arg = np.array(3.)\n- # Check that we have a Sin under a conditional\n- f_tf = tf.function(jax2tf.convert(jax.grad(remat_f)), autograph=False)\n- f_tf_graph = f_tf.get_concrete_function(arg).graph.as_graph_def()\n- if flavor == \"old\":\n- raise unittest.SkipTest(\"TODO: CSE widget not yet implemented for old-style remat\")\n- self.assertRegex(str(f_tf_graph),\n- r'remat_checkpoint_/switch_case/indexed_case/Sin')\n+ arg = np.arange(3.)\n+ self.TransformConvertAndCompare(f, arg, \"grad\")\n+ # TODO: check that the TF code also computes \"sin\" 5 times\ndef test_remat_free_var(self):\ndef f(x):\ny = 2 * x\n- @ad_checkpoint.checkpoint\n+ @jax.remat\ndef g():\nreturn y\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -640,6 +640,90 @@ def xla_fallback_lowering(prim: core.Primitive, ctx: LoweringContext,\nregister_lowering(ad.custom_lin_p, ad._raise_custom_vjp_error_on_jvp)\n+\n+def _dummy_like_aval(aval: core.AbstractValue) -> Sequence[ir.Value]:\n+ if isinstance(aval, core.ShapedArray):\n+ return [full_like_aval(0, aval)]\n+ elif isinstance(aval, core.AbstractToken):\n+ return mhlo.CreateTokenOp(aval_to_ir_type(aval)).results\n+ elif isinstance(aval, core.AbstractUnit):\n+ return ()\n+ else:\n+ raise TypeError(f\"Unsupported abstract value {aval}\")\n+\n+def _remat_using_while(ctx, avals_in, avals_out, *args, name, call_jaxpr):\n+ input_types = map(aval_to_ir_types, avals_in)\n+ output_types = map(aval_to_ir_types, avals_out)\n+ flat_output_types = util.flatten(output_types)\n+ int32_scalar_type = aval_to_ir_type(core.ShapedArray((), np.dtype(np.int32)))\n+ loop_carry_types = [(int32_scalar_type,)] + input_types + output_types\n+ flat_loop_carry_types = util.flatten(loop_carry_types)\n+ counter_init = ir_constants(np.array(0, np.int32))\n+ flat_args = flatten_lowering_ir_args(\n+ (counter_init,) + args +\n+ tuple(_dummy_like_aval(aval) for aval in avals_out))\n+ loop_carry_tuple_type = ir.TupleType.get_tuple(flat_loop_carry_types)\n+ init_carry = mhlo.TupleOp(loop_carry_tuple_type, flat_args)\n+\n+ one = ir_constant(np.array(1, np.int32))\n+ while_op = mhlo.WhileOp([loop_carry_tuple_type], [init_carry.result])\n+\n+ # Loop condition\n+ cond_block = while_op.regions[0].blocks.append(loop_carry_tuple_type)\n+ with ir.InsertionPoint(cond_block):\n+ bool_scalar_type = aval_to_ir_type(core.ShapedArray((), np.dtype(np.bool_)))\n+ two = ir_constant(np.array(2, np.int32))\n+ shape = ir_constant(np.array((), np.int64), canonicalize_types=False)\n+ rng = mhlo.RngUniformOp(one, two, shape).result\n+ i = mhlo.GetTupleElementOp(int32_scalar_type, cond_block.arguments[0],\n+ i32_attr(0))\n+ cmp = mhlo.CompareOp(bool_scalar_type, i, rng, ir.StringAttr.get(\"LT\"),\n+ ir.StringAttr.get(\"SIGNED\")).result\n+ mhlo.ReturnOp([cmp])\n+\n+ body_block = while_op.regions[1].blocks.append(loop_carry_tuple_type)\n+ with ir.InsertionPoint(body_block):\n+ flat_body_args = [\n+ mhlo.GetTupleElementOp(input_type, body_block.arguments[0],\n+ i32_attr(i)).result\n+ for i, input_type in enumerate(flat_loop_carry_types)]\n+ body_args = util.unflatten(flat_body_args, map(len, loop_carry_types))\n+ ((i,),), y, _ = util.split_list(body_args, [1, len(avals_in)])\n+ body_ctx = ctx.replace(\n+ name_stack=xla.extend_name_stack(ctx.name_stack,\n+ xla.wrap_name(name, 'remat')))\n+ z = jaxpr_subcomp(body_ctx, call_jaxpr, (), *y)\n+ i_next = mhlo.AddOp(i, one).result\n+ new_carry = mhlo.TupleOp(\n+ loop_carry_tuple_type,\n+ [i_next, *util.flatten(y), *util.flatten(z)])\n+ mhlo.ReturnOp([new_carry.result])\n+\n+ outputs = [mhlo.GetTupleElementOp(output_type, while_op.result,\n+ i32_attr(1 + len(avals_in) + i)\n+ ).result\n+ for i, output_type in enumerate(flat_output_types)]\n+ return util.unflatten(outputs, map(len, output_types))\n+\n+\n+def _remat_lowering(ctx, avals_in, avals_out, *args,\n+ name, call_jaxpr,\n+ prevent_cse, differentiated, concrete,\n+ policy, device=None):\n+ del device, concrete, policy # Unused.\n+ if differentiated and prevent_cse:\n+ if True: # ctx.platform == \"gpu\":\n+ return _remat_using_while(ctx, avals_in, avals_out, *args, name=name,\n+ call_jaxpr=call_jaxpr)\n+ else:\n+ assert False\n+ #return _remat_using_cond(ctx, args, name, call_jaxpr)\n+ else:\n+ return jaxpr_subcomp(\n+ ctx, call_jaxpr, (), *map(wrap_singleton_ir_values, args))\n+\n+register_lowering(pe.remat_call_p, _remat_lowering)\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": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -657,7 +657,7 @@ def tracers_to_jaxpr(\nreturn jaxpr, const_vals, env_vals\n@cache()\n-def convert_constvars_jaxpr(jaxpr: Jaxpr) -> Jaxpr:\n+def convert_constvars_jaxpr(jaxpr: Jaxpr):\n\"\"\"Moves the constvars to the start of invars.\"\"\"\nconfig.jax_enable_checks and core.check_jaxpr(jaxpr)\nlifted_jaxpr = Jaxpr(constvars=(),\n@@ -666,7 +666,7 @@ def convert_constvars_jaxpr(jaxpr: Jaxpr) -> Jaxpr:\nconfig.jax_enable_checks and core.check_jaxpr(lifted_jaxpr)\nreturn lifted_jaxpr\n-def convert_envvars_to_constvars(jaxpr: Jaxpr, num_env_vars: int) -> Jaxpr:\n+def convert_envvars_to_constvars(jaxpr: Jaxpr, num_env_vars: int):\nconfig.jax_enable_checks and core.check_jaxpr(jaxpr)\nenv_vars, invars = split_list(jaxpr.invars, [num_env_vars])\nconverted_jaxpr = Jaxpr(constvars=jaxpr.constvars + env_vars,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1035,6 +1035,108 @@ def _array_aval_from_xla_shape(xla_shape):\nassert not xla_shape.is_tuple()\nreturn ShapedArray(xla_shape.dimensions(), xla_shape.numpy_dtype())\n+\n+def _zeros(c, xla_shape):\n+ if xla_shape.is_array():\n+ shape, dtype = xla_shape.dimensions(), xla_shape.numpy_dtype()\n+ zero = xops.Constant(c, np.array(0, dtype=dtype))\n+ return xops.Broadcast(zero, shape)\n+ else:\n+ # It is a token\n+ return xops.CreateToken(c)\n+\n+\n+def _remat_using_cond(ctx, in_nodes, name, call_jaxpr):\n+ \"\"\"Lower remat to a Conditional which always returns true. This:\n+ 1. Circumvents common subexpression elimination.\n+ 2. In common case of `jax.grad(jax.remat(f))`, ensures the remat blocks\n+ occur after the primal blocks, because cotangent is an input to the\n+ Conditional.\"\"\"\n+ # Fake condition which always selects True branch.\n+ c = ctx.builder\n+ rng = xops.RngUniform(xops.Constant(c, np.array(0, dtype=np.float32)),\n+ xops.Constant(c, np.array(1, dtype=np.float32)),\n+ xc.Shape.array_shape(xc.PrimitiveType.F32, []))\n+ pred = xops.Lt(rng, xops.Constant(c, np.array(2, dtype=np.float32)))\n+\n+ true_op = xops.Tuple(c, in_nodes)\n+ remat_subc = xc.XlaBuilder(\"remat_call_subcomputation\")\n+ input_op = parameter(remat_subc, 0, c.get_shape(true_op), replicated=[])\n+ args = xla_destructure(remat_subc, input_op)\n+ sub_ctx = ctx.replace(\n+ builder=remat_subc,\n+ name_stack=extend_name_stack(ctx.name_stack, wrap_name(name, 'remat')))\n+ out_nodes = jaxpr_subcomp(sub_ctx, call_jaxpr, (), *args)\n+ out_node_shapes = [remat_subc.get_shape(o) for o in out_nodes]\n+ remat_subc = remat_subc.build(xops.Tuple(remat_subc, out_nodes))\n+\n+ false_op = true_op\n+ dummy_subc = xc.XlaBuilder(\"remat_call_dummy_subcomputation\")\n+ parameter(dummy_subc, 0, c.get_shape(false_op), replicated=[])\n+ out_nodes = [_zeros(dummy_subc, s) for s in out_node_shapes]\n+ dummy_subc = dummy_subc.build(xops.Tuple(dummy_subc, out_nodes))\n+\n+ return xla_destructure(\n+ c, xops.Conditional(pred, true_op, remat_subc, false_op, dummy_subc))\n+\n+\n+def _remat_using_while(ctx, in_nodes, name, call_jaxpr):\n+ \"\"\"Lower remat to a single iteration while loop.\"\"\"\n+ c = ctx.builder\n+ # Dummy subc for getting subcomp shapes.\n+ dummy_inputs = xops.Tuple(c, in_nodes)\n+ dummy_subc = xc.XlaBuilder(\"remat_dummy_subcomputation\")\n+ dummy_input_op = parameter(dummy_subc, 0, c.get_shape(dummy_inputs), replicated=[])\n+ dummy_args = xla_destructure(dummy_subc, dummy_input_op)\n+ dummy_ctx = ctx.replace(\n+ builder=dummy_subc,\n+ name_stack=extend_name_stack(ctx.name_stack, wrap_name(name, 'remat')))\n+ dummy_subcomp_outs = jaxpr_subcomp(dummy_ctx, call_jaxpr, (), *dummy_args)\n+ out_node_shapes = [dummy_subc.get_shape(o) for o in dummy_subcomp_outs]\n+\n+ i_init = xops.Constant(c, np.array(0, dtype=np.int32))\n+ zeros_like_outs = [_zeros(c, s) for s in out_node_shapes]\n+ inputs = xops.Tuple(c, [i_init] + list(in_nodes) + zeros_like_outs)\n+\n+ cond_subc = xc.XlaBuilder(\"remat_cond_subcomputation\")\n+ input_op = parameter(cond_subc, 0, c.get_shape(inputs), replicated=[])\n+ i = xops.GetTupleElement(input_op, 0)\n+ rng = xops.RngUniform(xops.Constant(cond_subc, np.array(1, dtype=np.int32)),\n+ xops.Constant(cond_subc, np.array(2, dtype=np.int32)),\n+ xc.Shape.array_shape(xc.PrimitiveType.S32, []))\n+ cond_subc = cond_subc.build(xops.Lt(i, rng))\n+\n+ body_subc = xc.XlaBuilder(\"remat_body_subcomputation\")\n+ input_op = parameter(body_subc, 0, c.get_shape(inputs), replicated=[])\n+ i, *args = xla_destructure(body_subc, input_op)[:len(in_nodes)+1]\n+ i_next = xops.Add(i, xops.Constant(body_subc, np.array(1, dtype=np.int32)))\n+ body_ctx = ctx.replace(\n+ builder=body_subc,\n+ name_stack=extend_name_stack(ctx.name_stack, wrap_name(name, 'remat')))\n+ subcomp_outs = jaxpr_subcomp(body_ctx, call_jaxpr, (), *args)\n+ out_nodes = [i_next] + args + list(subcomp_outs)\n+ body_subc = body_subc.build(xops.Tuple(body_subc, out_nodes))\n+ outs = xops.While(cond_subc, body_subc, inputs)\n+ return xla_destructure(c, outs)[len(in_nodes)+1:]\n+\n+\n+\n+def _remat_translation_rule(ctx, avals_in, avals_out, *in_nodes,\n+ name, call_jaxpr,\n+ prevent_cse, differentiated, concrete,\n+ policy, device=None):\n+ del device, concrete, policy # Unused.\n+ if differentiated and prevent_cse:\n+ if ctx.platform == \"gpu\":\n+ return _remat_using_while(ctx, in_nodes, name, call_jaxpr)\n+ else:\n+ return _remat_using_cond(ctx, in_nodes, name, call_jaxpr)\n+ else:\n+ return jaxpr_subcomp(ctx, call_jaxpr, (), *in_nodes)\n+\n+register_translation(pe.remat_call_p, _remat_translation_rule)\n+\n+\nad.primitive_transposes[core.named_call_p] = partial(ad.call_transpose,\ncore.named_call_p)\n"
}
] | Python | Apache License 2.0 | google/jax | Copybara import of the project:
--
6288d67fefec5dad8b0a42055e071d647ba1be06 by George Necula <gcnecula@gmail.com>:
Refactor the lowering of remat.
Replace the XLA-specific lowering with the same logic written
with LAX primitives. Then use this for HLO, MLIR, and jax2tf lowerings.
PiperOrigin-RevId: 413425828 |
260,335 | 29.10.2021 09:23:27 | 25,200 | 659f8b794ff6b64c1264ce6398dfbf4e0a4b19bc | add skeleton checkify transformation | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1631,9 +1631,9 @@ def call_bind(primitive: Union['CallPrimitive', 'MapPrimitive'],\nout_axes_transforms = _IgnoreElemList()\nif primitive.map_primitive:\nout_axes_thunk = params['out_axes_thunk']\n- # The new thunk depends deterministically on the old thunk and the wrapped function.\n- # Any caching already has to include the wrapped function as part of the key, so we\n- # only use the previous thunk for equality checks.\n+ # The new thunk depends deterministically on the old thunk and the wrapped\n+ # function. Any caching already has to include the wrapped function as part\n+ # of the key, so we only use the previous thunk for equality checks.\n@as_hashable_function(closure=out_axes_thunk)\ndef new_out_axes_thunk():\nout_axes = out_axes_thunk()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/checkify.py",
"diff": "+# Copyright 2021 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from dataclasses import dataclass\n+from functools import partial\n+import itertools as it\n+from typing import Union, Optional, Callable, Dict\n+\n+import numpy as np\n+\n+import jax.numpy as jnp\n+\n+from jax import core\n+from jax import linear_util as lu\n+from jax.api_util import flatten_fun\n+from jax.interpreters import partial_eval as pe\n+from jax.tree_util import tree_flatten, tree_unflatten, register_pytree_node\n+from jax._src import source_info_util, traceback_util\n+from jax._src.lax import lax\n+from jax._src.lax import slicing\n+from jax._src.lax import control_flow\n+from jax._src.util import as_hashable_function, unzip2\n+\n+source_info_util.register_exclusion(__file__)\n+traceback_util.register_exclusion(__file__)\n+\n+\n+## Utils\n+\n+def popattr(obj, attrname):\n+ val = getattr(obj, attrname)\n+ delattr(obj, attrname)\n+ return val\n+\n+def setnewattr(obj, name, val):\n+ sentinel = object()\n+ assert getattr(obj, name, sentinel) is sentinel\n+ setattr(obj, name, val)\n+\n+## Error value data type and functional assert.\n+\n+@dataclass(frozen=True)\n+class Error:\n+ err: Union[bool, core.Tracer]\n+ code: Union[int, core.Tracer]\n+ msgs: Dict[int, str]\n+\n+ def get(self) -> Optional[str]:\n+ assert np.shape(self.err) == np.shape(self.code)\n+ if np.size(self.err) == 1:\n+ if self.err:\n+ return self.msgs[int(self.code)]\n+ else:\n+ return '\\n'.join(f'at mapped index {\", \".join(map(str, idx))}: ' # type: ignore\n+ f'{self.msgs[int(self.code[idx])]}' # type: ignore\n+ for idx, e in np.ndenumerate(self.err) if e) or None\n+ return None\n+\n+register_pytree_node(Error,\n+ lambda e: ((e.err, e.code), tuple(sorted(e.msgs.items()))),\n+ lambda msgs, data: Error(*data, dict(msgs))) # type: ignore\n+\n+init_error = Error(False, 0, {})\n+next_code = it.count(1).__next__ # globally unique ids, could be uuid4\n+\n+\n+Bool = Union[bool, core.Tracer]\n+Int = Union[int, core.Tracer]\n+\n+def assert_func(error: Error, pred: Bool, msg: str) -> Error:\n+ code = next_code()\n+ out_err = error.err | jnp.logical_not(pred)\n+ out_code = lax.select(error.err, error.code, code)\n+ return Error(out_err, out_code, {code: msg, **error.msgs})\n+\n+## Checkify transformation for plumbing functional error values.\n+\n+class ErrorTrace(core.Trace):\n+ pure = lift = sublift = lambda self, val: ErrorTracer(self, val)\n+\n+ def process_primitive(self, primitive, tracers, params):\n+ in_vals = [t.val for t in tracers]\n+ rule = error_checks.get(primitive)\n+ if rule:\n+ out, self.main.error = rule(self.main.error, *in_vals, **params)\n+ else:\n+ out = primitive.bind(*in_vals, **params)\n+ if primitive.multiple_results:\n+ return [ErrorTracer(self, x) for x in out]\n+ else:\n+ return ErrorTracer(self, out)\n+\n+ def process_call(self, primitive, f, tracers, params):\n+ in_vals = [t.val for t in tracers]\n+ e = popattr(self.main, 'error')\n+ f, msgs = check_errors_subtrace(f, self.main, tuple(e.msgs.items()))\n+ params_ = dict(params, donated_invars=(False, False, *params['donated_invars']))\n+ err, code, *out_vals = primitive.bind(f, e.err, e.code, *in_vals, **params_)\n+ setnewattr(self.main, 'error', Error(err, code, msgs()))\n+ return [ErrorTracer(self, x) for x in out_vals]\n+\n+ def process_map(self, primitive, f, tracers, params):\n+ in_vals = [t.val for t in tracers]\n+ e = popattr(self.main, 'error')\n+ f, msgs = check_errors_subtrace(f, self.main, tuple(e.msgs.items()))\n+\n+ @as_hashable_function(closure=params['out_axes_thunk'])\n+ def new_out_axes_thunk():\n+ return (0, 0, *params['out_axes_thunk']())\n+\n+ params_ = dict(params, in_axes=(None, None, *params['in_axes']),\n+ out_axes_thunk=new_out_axes_thunk,\n+ donated_invars=(False, False, *params['donated_invars']))\n+ errs, codes, *outs = primitive.bind(f, e.err, e.code, *in_vals, **params_)\n+ err, code = _reduce_any_error(errs, codes)\n+ setnewattr(self.main, 'error', Error(err, code, msgs()))\n+ return [ErrorTracer(self, x) for x in outs]\n+\n+ def post_process_call(self, primitive, tracers, params):\n+ vals = [t.val for t in tracers]\n+ main = self.main\n+ e = popattr(self.main, 'error')\n+ err, code, main.msgs = e.err, e.code, e.msgs\n+ def todo(vals):\n+ trace = main.with_cur_sublevel()\n+ err, code, *vals = vals\n+ return [ErrorTracer(trace, x) for x in vals]\n+ return (err, code, *vals), todo\n+\n+ def post_process_map(self, primitive, tracers, params):\n+ vals = [t.val for t in tracers]\n+ main = self.main\n+ e = popattr(self.main, 'error')\n+ err, code, main.msgs = e.err, e.code, e.msgs\n+ def todo(vals):\n+ trace = main.with_cur_sublevel()\n+ err, code, *vals = vals\n+ return [ErrorTracer(trace, x) for x in vals]\n+ def out_axes_transform(out_axes):\n+ return (0, 0, *out_axes)\n+ return (err, code, *vals), (todo, out_axes_transform)\n+\n+def _reduce_any_error(errs, codes):\n+ errs_, codes_ = lax.sort_key_val(errs, codes, dimension=0)\n+ return errs_[-1], codes_[-1]\n+\n+ErrorCheckRule = Callable\n+error_checks: Dict[core.Primitive, ErrorCheckRule] = {}\n+\n+class ErrorTracer(core.Tracer):\n+ def __init__(self, trace, val):\n+ self._trace = trace\n+ self.val = val\n+ core.get_aval(val), val\n+ aval = property(lambda self: core.get_aval(self.val))\n+ full_lower = lambda self: self\n+\n+def check_errors_flat(fun: lu.WrappedFun, *args):\n+ fun, msgs = check_errors_subtrace(fun)\n+ fun = check_errors_toplevel(fun)\n+ err, code, *out_vals = fun.call_wrapped(*args)\n+ return (err, code, out_vals), msgs()\n+\n+@lu.transformation\n+def check_errors_toplevel(*args):\n+ error = init_error\n+ with core.new_main(ErrorTrace) as main:\n+ msgs = tuple(error.msgs.items())\n+ outs = yield (main, msgs, error.err, error.code, *args), {}\n+ del main\n+ yield outs\n+\n+@lu.transformation_with_aux\n+def check_errors_subtrace(main, msgs, err, code, *args):\n+ setnewattr(main, 'error', Error(err, code, dict(msgs)))\n+ trace = main.with_cur_sublevel()\n+ in_tracers = [ErrorTracer(trace, x) for x in args]\n+ out = yield in_tracers, {}\n+ out_tracers = map(trace.full_raise, out)\n+ out_vals = [t.val for t in out_tracers]\n+ err, code, msgs = main.error.err, main.error.code, main.error.msgs\n+ del main.error\n+ yield (err, code, *out_vals), msgs\n+\n+def checkify_jaxpr(jaxpr, error):\n+ f = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\n+ f, msgs = check_errors_subtrace(f)\n+ f = check_errors_traceable(f, tuple(error.msgs.items()))\n+ err_aval = core.raise_to_shaped(core.get_aval(error.err))\n+ code_aval = core.raise_to_shaped(core.get_aval(error.code))\n+ avals_in = [err_aval, code_aval, *jaxpr.in_avals]\n+ jaxpr_out, _, literals_out = pe.trace_to_jaxpr_dynamic(f, avals_in)\n+ return core.ClosedJaxpr(jaxpr_out, literals_out), msgs()\n+\n+# TODO dedup with check_errors_toplevel\n+@lu.transformation\n+def check_errors_traceable(msgs, err, code, *args):\n+ with core.new_main(ErrorTrace) as main:\n+ outs = yield (main, msgs, err, code, *args), {}\n+ del main\n+ yield outs\n+\n+\n+## checkify rules\n+\n+def nan_error_check(prim, error, *in_vals, **params):\n+ out = prim.bind(*in_vals, **params)\n+ no_nans = jnp.logical_not(jnp.any(jnp.isnan(out)))\n+ summary = source_info_util.summarize(source_info_util.current())\n+ msg = f\"nan generated by primitive {prim.name} at {summary}\"\n+ return out, assert_func(error, no_nans, msg)\n+\n+error_checks[lax.sin_p] = partial(nan_error_check, lax.sin_p)\n+error_checks[lax.cos_p] = partial(nan_error_check, lax.cos_p)\n+\n+def gather_error_check(error, operand, start_indices, *,\n+ dimension_numbers, slice_sizes, unique_indices,\n+ indices_are_sorted, mode, fill_value):\n+ out = slicing.gather_p.bind(\n+ operand, start_indices, dimension_numbers=dimension_numbers,\n+ slice_sizes=slice_sizes, unique_indices=unique_indices,\n+ indices_are_sorted=indices_are_sorted, mode=mode, fill_value=fill_value)\n+\n+ # compare to OOB masking logic in lax._gather_translation_rule\n+ dnums = dimension_numbers\n+ operand_dims = np.array(operand.shape)\n+\n+ upper_bound = operand_dims[np.array(dnums.start_index_map)]\n+ upper_bound -= np.array(slice_sizes)[np.array(dnums.start_index_map)]\n+ all_inbounds = jnp.all((start_indices >= 0) & (start_indices <= upper_bound))\n+\n+ summary = source_info_util.summarize(source_info_util.current())\n+ msg = f\"out-of-bounds indexing at {summary}\"\n+ return out, assert_func(error, all_inbounds, msg)\n+error_checks[slicing.gather_p] = gather_error_check\n+\n+def cond_error_check(error, index, *ops, branches, linear):\n+ new_branches, msgs_ = unzip2(checkify_jaxpr(jxpr, error) for jxpr in branches)\n+ new_linear = (False, False, *linear)\n+ err, code, *outs = control_flow.cond_p.bind(\n+ index, error.err, error.code, *ops,\n+ branches=tuple(new_branches), linear=new_linear)\n+ new_msgs = {k:v for d in it.chain([error.msgs], msgs_) for k, v in d.items()}\n+ return outs, Error(err, code, new_msgs)\n+error_checks[control_flow.cond_p] = cond_error_check\n+\n+\n+## checkify api\n+\n+def checkify(fun: Callable) -> Callable:\n+ @traceback_util.api_boundary\n+ def checked_fun(*args, **kwargs):\n+ args_flat, in_tree = tree_flatten((args, kwargs))\n+ f, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n+ (err, code, out_flat), msgs = check_errors_flat(f, *args_flat)\n+ out = tree_unflatten(out_tree(), out_flat)\n+ return Error(err, code, msgs), out\n+ return checked_fun\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/checkify_test.py",
"diff": "+# Copyright 2021 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import unittest\n+\n+from absl.testing import absltest\n+from absl.testing import parameterized\n+\n+import jax\n+import jax.numpy as jnp\n+from jax import lax\n+from jax.config import config\n+from jax.experimental import checkify\n+import jax._src.test_util as jtu\n+\n+config.parse_flags_with_absl()\n+\n+\n+class CheckifyTransformTests(jtu.JaxTestCase):\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\n+ for jit in [False, True]))\n+ def test_jit_nan(self, jit):\n+ def f(x1, x2):\n+ y1 = jnp.sin(x1)\n+ y2 = jnp.sin(x2)\n+ return y1 + y2\n+\n+ f = jax.jit(f) if jit else f\n+\n+ err, _ = checkify.checkify(f)(3., 4.)\n+ self.assertIs(err.get(), None)\n+\n+ err, _ = checkify.checkify(f)(3., jnp.inf)\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\n+ for jit in [False, True]))\n+ def test_jit_oob(self, jit):\n+ def f(x, i):\n+ y = jnp.sin(x)\n+ z = y[i]\n+ w = jnp.cos(z)\n+ return w\n+\n+ f = jax.jit(f) if jit else f\n+\n+ err, _ = checkify.checkify(f)(jnp.arange(3), 2)\n+ self.assertIs(err.get(), None)\n+\n+ err, _ = checkify.checkify(f)(jnp.arange(3), 5)\n+ self.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\n+ for jit in [False, True]))\n+ def test_jit_multi(self, jit):\n+ def f(x, i):\n+ y = x[i]\n+ z = jnp.cos(y)\n+ return z\n+\n+ f = jax.jit(f) if jit else f\n+\n+ # no error\n+ err, _ = checkify.checkify(f)(jnp.array([0., jnp.inf, 2.]), 2)\n+ self.assertIs(err.get(), None)\n+\n+ # oob error\n+ err, _ = checkify.checkify(f)(jnp.array([0., 1., 2.]), 5)\n+ self.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+\n+ # nan error\n+ err, _ = checkify.checkify(f)(jnp.array([0., 1., jnp.inf]), 2)\n+ self.assertStartsWith(err.get(), 'nan generated by primitive cos')\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\n+ for jit in [False, True]))\n+ def test_jit_ordering(self, jit):\n+ def f(x, i):\n+ y = x[i]\n+ z = jnp.sin(x)\n+ return y * z\n+\n+ f = jax.jit(f) if jit else f\n+\n+ # both oob and nan error, but oob happens first\n+ err, _ = checkify.checkify(f)(jnp.array([0., 1., jnp.inf]), 5)\n+ self.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+\n+ def test_pmap_basic(self):\n+ if len(jax.devices()) < 2:\n+ raise unittest.SkipTest(\"requires at least 2 devices\")\n+\n+ @jax.pmap\n+ def f(x1, x2):\n+ y1 = jnp.sin(x1)\n+ y2 = jnp.sin(x2)\n+ return y1 + y2\n+\n+ xs = jnp.array([0., 2.])\n+ err, _ = checkify.checkify(f)(xs, xs)\n+ self.assertIs(err.get(), None)\n+\n+ ys = jnp.array([3., jnp.inf])\n+ err, _ = checkify.checkify(f)(xs, ys)\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\n+ def test_cond_basic(self):\n+ @jax.jit\n+ def f(x):\n+ return lax.cond(x > 0,\n+ lambda: jnp.sin(x),\n+ lambda: x)\n+\n+ err, y = checkify.checkify(f)(3.)\n+ self.assertIs(err.get(), None)\n+\n+ err, y = checkify.checkify(f)(jnp.inf)\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\n+ err, y = checkify.checkify(f)(-jnp.inf)\n+ self.assertIs(err.get(), None)\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | add skeleton checkify transformation |
260,335 | 02.12.2021 14:26:58 | 28,800 | c1f71d17c0b34fbf987147c095843dc6601b41e0 | generalize assert primitive, allow recharging | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/checkify.py",
"new_path": "jax/experimental/checkify.py",
"diff": "@@ -88,8 +88,19 @@ def assert_func(error: Error, pred: Bool, msg: str) -> Error:\n## Checkify transformation for plumbing functional error values.\n+class ErrorTracer(core.Tracer):\n+ def __init__(self, trace, val):\n+ self._trace = trace\n+ self.val = val\n+ core.get_aval(val), val\n+ aval = property(lambda self: core.get_aval(self.val))\n+ full_lower = lambda self: self\n+\nclass ErrorTrace(core.Trace):\n- pure = lift = sublift = lambda self, val: ErrorTracer(self, val)\n+ pure = lift = lambda self, val: ErrorTracer(self, val)\n+\n+ def sublift(self, tracer):\n+ return ErrorTracer(self, tracer.val)\ndef process_primitive(self, primitive, tracers, params):\nin_vals = [t.val for t in tracers]\n@@ -160,14 +171,6 @@ def _reduce_any_error(errs, codes):\nErrorCheckRule = Callable\nerror_checks: Dict[core.Primitive, ErrorCheckRule] = {}\n-class ErrorTracer(core.Tracer):\n- def __init__(self, trace, val):\n- self._trace = trace\n- self.val = val\n- core.get_aval(val), val\n- aval = property(lambda self: core.get_aval(self.val))\n- full_lower = lambda self: self\n-\ndef check_errors_flat(fun: lu.WrappedFun, *args):\nfun, msgs = check_errors_subtrace(fun)\nfun = check_errors_toplevel(fun)\n@@ -217,28 +220,34 @@ def check_errors_traceable(msgs, err, code, *args):\n## assert primitive\ndef assert_(pred: Bool, msg: str) -> None:\n- return assert_p.bind(pred, msg=msg)\n+ code = next_code()\n+ return assert2_(pred, code, {code: msg})\n+\n+def assert2_(pred: Bool, code: Int, msgs: Dict[int, str]) -> None:\n+ return assert_p.bind(pred, code, msgs=msgs)\nassert_p = core.Primitive('assert')\nassert_p.multiple_results = True # zero results\n@assert_p.def_impl\n-def assert_impl(pred, *, msg):\n- assert pred, msg\n+def assert_impl(pred, code, *, msgs):\n+ assert pred, msgs[int(code)]\nreturn []\n@assert_p.def_abstract_eval\n-def assert_abstract_eval(pred, *, msg):\n+def assert_abstract_eval(pred, code, *, msgs):\nraise Exception(\"can't be staged!\")\n## checkify rules\n+def summary() -> str:\n+ return str(source_info_util.summarize(source_info_util.current()))\n+\ndef nan_error_check(prim, error, *in_vals, **params):\nout = prim.bind(*in_vals, **params)\nno_nans = jnp.logical_not(jnp.any(jnp.isnan(out)))\n- summary = source_info_util.summarize(source_info_util.current())\n- msg = f\"nan generated by primitive {prim.name} at {summary}\"\n+ msg = f\"nan generated by primitive {prim.name} at {summary()}\"\nreturn out, assert_func(error, no_nans, msg)\nerror_checks[lax.sin_p] = partial(nan_error_check, lax.sin_p)\n@@ -260,8 +269,7 @@ def gather_error_check(error, operand, start_indices, *,\nupper_bound -= np.array(slice_sizes)[np.array(dnums.start_index_map)]\nall_inbounds = jnp.all((start_indices >= 0) & (start_indices <= upper_bound))\n- summary = source_info_util.summarize(source_info_util.current())\n- msg = f\"out-of-bounds indexing at {summary}\"\n+ msg = f\"out-of-bounds indexing at {summary()}\"\nreturn out, assert_func(error, all_inbounds, msg)\nerror_checks[slicing.gather_p] = gather_error_check\n@@ -276,10 +284,12 @@ def cond_error_check(error, index, *ops, branches, linear):\nerror_checks[control_flow.cond_p] = cond_error_check\n# TODO(mattjj,lenamartens): currently we bundle effectful-assert-discharging\n-# with the error-check-adding transformation (checkify), but the two could be\n-# made orthogonal.\n-def assert_discharge_rule(err: Error, pred: Bool, *, msg: str):\n- return [], assert_func(err, pred, msg)\n+# with the error-check-adding transformation (checkify), but they could be\n+# separated into two orthogonal transformations.\n+def assert_discharge_rule(error, pred, code, *, msgs):\n+ out_err = error.err | jnp.logical_not(pred)\n+ out_code = lax.select(error.err, error.code, code)\n+ return [], Error(out_err, out_code, {**error.msgs, **msgs})\nerror_checks[assert_p] = assert_discharge_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -185,6 +185,43 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"must be positive\")\n+ def test_assert2(self):\n+ def f(pred): # note: data dependence needed!\n+ checkify.assert2_(pred, 0, {0: \"hi\"})\n+\n+ with self.assertRaisesRegex(AssertionError, \"hi\"):\n+ f(False)\n+\n+ f = checkify.checkify(f)\n+ err, none = f(False)\n+\n+ self.assertIsNone(none)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"hi\")\n+\n+ def test_discharge_recharge(self):\n+ def ejit(f):\n+ f = checkify.checkify(f)\n+ f = jax.jit(f)\n+ def jitted_f(*args):\n+ err, out = f(*args)\n+ checkify.assert2_(~err.err, err.code, err.msgs)\n+ return out\n+ return jitted_f\n+\n+ @ejit\n+ def f(pred):\n+ assert python_should_be_running\n+ checkify.assert_(pred, \"foo\")\n+\n+ python_should_be_running = True\n+ f(True)\n+\n+ python_should_be_running = False\n+ f(True)\n+ with self.assertRaisesRegex(AssertionError, \"foo\"):\n+ f(False)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | generalize assert primitive, allow recharging |
260,303 | 02.12.2021 11:31:42 | 28,800 | 6f9c5abd388d9ad333dac67bb2e8e267f239adfa | Add profiler.annotate_function on some internals | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/device_array.py",
"new_path": "jax/_src/device_array.py",
"diff": "@@ -25,6 +25,7 @@ from jax import core\nfrom jax._src.config import config\nfrom jax._src import dtypes\nfrom jax._src.lib import xla_client as xc\n+from jax._src.profiler import annotate_function\nimport jax._src.util as util\n### device-persistent data\n@@ -125,6 +126,7 @@ class _DeviceArray(DeviceArray): # type: ignore\nif self.device_buffer is deleted_buffer:\nraise RuntimeError(\"DeviceArray has been deleted.\")\n+ @annotate_function\ndef block_until_ready(self):\n\"\"\"Blocks the caller until the buffer's value has been computed on device.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -39,6 +39,7 @@ from jax._src import device_array\nfrom jax._src import dtypes\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\n+from jax._src.profiler import annotate_function\nimport jax._src.util as util\nfrom jax._src import traceback_util\n@@ -157,6 +158,7 @@ def _xla_callable_uncached(fun: lu.WrappedFun, device, backend, name,\n_xla_callable = lu.cache(_xla_callable_uncached)\n+@annotate_function\ndef lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\ndonated_invars, *arg_specs):\nif device is not None and backend is not None:\n@@ -505,6 +507,7 @@ class XlaComputation:\nself.name, self.hlo(), *self.compile_args)\nreturn self._executable\n+@annotate_function\ndef backend_compile(backend, built_c, options):\n# we use a separate function call to ensure that XLA compilation appears\n# separately in Python profiling results\n@@ -601,6 +604,7 @@ def check_arg_avals_for_call(ref_avals, arg_avals):\nf\"called with:\\n {arg_avals_fmt}\")\n+@partial(annotate_function, name=\"dispatch.device_put\")\ndef device_put(x, device: Optional[Device] = None) -> Tuple[Any]:\nx = xla.canonicalize_dtype(x)\ntry:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -30,6 +30,7 @@ from jax._src import dtypes\nfrom jax import linear_util as lu\nfrom jax._src.ad_util import Zero\nfrom jax._src.api_util import flattened_fun_in_tree\n+from jax._src.profiler import annotate_function\nfrom jax._src.tree_util import PyTreeDef, tree_unflatten, tree_leaves\nfrom jax._src.util import (unzip2, safe_zip, safe_map, toposort, split_list,\npartition_list, cache, OrderedSet,\n@@ -463,6 +464,7 @@ class JaxprTracer(Tracer):\nreturn self.pval.is_known()\n# TODO(necula): this could return a ClosedJaxpr with out_pvals\n+@annotate_function\ndef trace_to_jaxpr(fun: lu.WrappedFun, pvals: Sequence[PartialVal],\ninstantiate: Union[bool, Sequence[bool]] = False,\n) -> Tuple[Jaxpr, Tuple[PartialVal, ...], Tuple[core.Value, ...]]:\n@@ -1521,6 +1523,7 @@ def arg_info_flattened(flat_pos: List[int]) -> str:\nreturn f\"the argument passed at flattened position {flat_pos[0]}\"\n+@annotate_function\ndef trace_to_jaxpr_dynamic(fun: lu.WrappedFun,\nin_avals: Sequence[AbstractValue],\ndebug_info: Optional[DebugInfo] = None):\n@@ -1552,6 +1555,7 @@ def extend_jaxpr_stack(main, frame):\nassert frame is main.jaxpr_stack[-1]\nmain.jaxpr_stack = main.jaxpr_stack[:-1]\n+@annotate_function\ndef trace_to_jaxpr_final(fun: lu.WrappedFun,\nin_avals: Sequence[AbstractValue],\ndebug_info: Optional[DebugInfo] = None):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -60,6 +60,7 @@ from jax._src.lib import xla_client as xc\nfrom jax._src.lib import pmap_lib\nfrom jax._src.lib.mlir import ir\nfrom jax._src.lib.mlir.dialects import mhlo\n+from jax._src.profiler import annotate_function\nfrom jax.tree_util import tree_flatten, tree_map\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\n@@ -294,7 +295,7 @@ def _shard_arg(arg, devices, arg_indices):\nreturn shard_arg_handlers[type(arg)](arg, devices, arg_indices)\n-\n+@annotate_function\ndef shard_args(devices: Sequence[xb.xla_client.Device],\nindices: Sequence[Sequence[Index]],\nargs) -> Sequence[Sequence[xb.xla_client.Buffer]]:\n@@ -896,6 +897,7 @@ def _shardings_to_mlir_shardings(\nreturn None\nreturn [xla.sharding_to_proto(s) for s in shardings]\n+@annotate_function\ndef lower_parallel_callable(\nfun: lu.WrappedFun,\nbackend_name: Optional[str],\n@@ -1033,6 +1035,7 @@ class PmapComputation:\n# this is a method for api consistency with dispatch.XlaComputation\nreturn self._hlo\n+ @annotate_function\ndef compile(self):\nif self._executable is None:\nself._executable = PmapExecutable.from_hlo(self._hlo, *self.compile_args)\n@@ -1168,6 +1171,7 @@ class PmapExecutable:\nreturn PmapExecutable(compiled, execute_fun, fingerprint, pci.avals)\n+ @annotate_function\ndef call(self, *args):\n# TODO(frostig): do we need to check sharding and sharded avals?\narg_avals = map(xla.abstractify, args)\n@@ -1384,6 +1388,7 @@ def global_avals_to_results_handler(global_out_avals: Sequence[ShapedArray],\nlocal_out_specs, local_out_untiled_avals)\n+@annotate_function\ndef replicate(val, axis_size, nrep, devices=None, backend=None, in_axis=0):\n\"\"\"Replicates ``val`` across multiple devices.\n@@ -1484,6 +1489,7 @@ def partitioned_sharding_spec(num_partitions: int,\nmesh_mapping=map(ShardedAxis, range(len(partitions))))\n+@annotate_function\ndef execute_replicated(compiled, backend, in_handler, out_handler, *args):\ninput_bufs = in_handler(args)\nout_bufs = compiled.execute_sharded_on_local_devices(input_bufs)\n@@ -1871,6 +1877,7 @@ def vtile_by_mesh(fun: lu.WrappedFun,\nmain_type=SPMDBatchTrace)\nreturn fun\n+@annotate_function\ndef lower_mesh_computation(\nfun: lu.WrappedFun,\ntransformed_name: str,\n@@ -2207,6 +2214,7 @@ class _ThreadLocalState(threading.local):\n_thread_local_state = _ThreadLocalState()\n+@partial(annotate_function, name=\"pxla.device_put\")\ndef device_put(x, devices: Sequence[xb.xla_client.Device], replicate: bool=False) -> List[xb.xla_client.Buffer]:\n\"\"\"Call device_put on a sequence of devices and return a flat sequence of buffers.\"\"\"\nif replicate:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -45,6 +45,7 @@ from jax._src import util\nfrom jax._src.util import (prod, extend_name_stack, wrap_name,\nsafe_zip, safe_map, partition_list)\nfrom jax._src.lib import xla_client as xc\n+from jax._src.profiler import annotate_function\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import ad\n@@ -737,7 +738,7 @@ def set_up_aliases(c, xla_args, out_shape: XlaShape, donated_args, tuple_args):\nreturn tuple(out_donated_args)\n-\n+@annotate_function\ndef lower_jaxpr_to_xla_module(\nfn_name: str, jaxpr: core.ClosedJaxpr, platform: str, axis_env: AxisEnv,\nname_stack: str, tuple_args: bool, donated_invars: Sequence[bool],\n"
}
] | Python | Apache License 2.0 | google/jax | Add profiler.annotate_function on some internals |
260,303 | 02.12.2021 12:11:12 | 28,800 | 643a97c83b424d1903ad6d74e634bb26df34e39a | Add profiler to traceback exclusions | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/profiler.py",
"new_path": "jax/_src/profiler.py",
"diff": "@@ -18,6 +18,9 @@ import threading\nfrom typing import Callable, Optional\nimport warnings\n+from jax._src import traceback_util\n+traceback_util.register_exclusion(__file__)\n+\nfrom jax._src.lib import xla_bridge\nfrom jax._src.lib import xla_client\n"
}
] | Python | Apache License 2.0 | google/jax | Add profiler to traceback exclusions |
260,303 | 02.12.2021 12:33:18 | 28,800 | 6efb1444666d098c00666be6e88310cf4fa73a39 | fix pytype errors | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/device_array.py",
"new_path": "jax/_src/device_array.py",
"diff": "from functools import partial, partialmethod\nimport operator\n-from typing import (Any, Optional, Union)\n+from typing import (Any, List, Optional, Union)\nimport weakref\nimport numpy as np\n@@ -303,7 +303,7 @@ class DeletedBuffer(object): pass\ndeleted_buffer = DeletedBuffer()\n-device_array_types = [xc.Buffer, _DeviceArray]\n+device_array_types: List[type] = [xc.Buffer, _DeviceArray]\nfor _device_array in device_array_types:\ncore.literalable_types.add(_device_array)\ncore.pytype_aval_mappings[device_array] = core.ConcreteArray\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -318,7 +318,7 @@ def shard_args(devices: Sequence[xb.xla_client.Device],\nshard_arg_handlers: Dict[Any, Callable[[Any, Any, Any], Sequence[Any]]] = {}\nshard_arg_handlers[core.Unit] = \\\n- lambda x, devices, _: device_put(core.unit, devices, replicate=True)\n+ lambda x, devices, _: device_put(core.unit, devices, replicate=True) # type: ignore[has-type]\ndef _shard_array(x, devices, indices):\nreturn device_put([x[i] for i in indices], devices)\nfor _t in array_types:\n"
}
] | Python | Apache License 2.0 | google/jax | fix pytype errors |
260,303 | 03.12.2021 10:37:04 | 28,800 | ac0d02743cd43dfc5767eb48d645957193be97e2 | Use profiler.annotate_function | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/device_array.py",
"new_path": "jax/_src/device_array.py",
"diff": "@@ -24,8 +24,8 @@ import numpy as np\nfrom jax import core\nfrom jax._src.config import config\nfrom jax._src import dtypes\n+from jax._src import profiler\nfrom jax._src.lib import xla_client as xc\n-from jax._src.profiler import annotate_function\nimport jax._src.util as util\n### device-persistent data\n@@ -126,7 +126,7 @@ class _DeviceArray(DeviceArray): # type: ignore\nif self.device_buffer is deleted_buffer:\nraise RuntimeError(\"DeviceArray has been deleted.\")\n- @annotate_function\n+ @profiler.annotate_function\ndef block_until_ready(self):\n\"\"\"Blocks the caller until the buffer's value has been computed on device.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -37,9 +37,9 @@ from jax._src.abstract_arrays import array_types\nfrom jax._src.config import config\nfrom jax._src import device_array\nfrom jax._src import dtypes\n+from jax._src import profiler\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\n-from jax._src.profiler import annotate_function\nimport jax._src.util as util\nfrom jax._src import traceback_util\n@@ -158,7 +158,7 @@ def _xla_callable_uncached(fun: lu.WrappedFun, device, backend, name,\n_xla_callable = lu.cache(_xla_callable_uncached)\n-@annotate_function\n+@profiler.annotate_function\ndef lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\ndonated_invars, *arg_specs):\nif device is not None and backend is not None:\n@@ -507,7 +507,7 @@ class XlaComputation:\nself.name, self.hlo(), *self.compile_args)\nreturn self._executable\n-@annotate_function\n+@profiler.annotate_function\ndef backend_compile(backend, built_c, options):\n# we use a separate function call to ensure that XLA compilation appears\n# separately in Python profiling results\n@@ -604,7 +604,7 @@ def check_arg_avals_for_call(ref_avals, arg_avals):\nf\"called with:\\n {arg_avals_fmt}\")\n-@partial(annotate_function, name=\"dispatch.device_put\")\n+@partial(profiler.annotate_function, name=\"dispatch.device_put\")\ndef device_put(x, device: Optional[Device] = None) -> Tuple[Any]:\nx = xla.canonicalize_dtype(x)\ntry:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -28,9 +28,9 @@ import numpy as np\nfrom jax import core\nfrom jax._src import dtypes\nfrom jax import linear_util as lu\n+from jax._src import profiler\nfrom jax._src.ad_util import Zero\nfrom jax._src.api_util import flattened_fun_in_tree\n-from jax._src.profiler import annotate_function\nfrom jax._src.tree_util import PyTreeDef, tree_unflatten, tree_leaves\nfrom jax._src.util import (unzip2, safe_zip, safe_map, toposort, split_list,\npartition_list, cache, OrderedSet,\n@@ -464,7 +464,7 @@ class JaxprTracer(Tracer):\nreturn self.pval.is_known()\n# TODO(necula): this could return a ClosedJaxpr with out_pvals\n-@annotate_function\n+@profiler.annotate_function\ndef trace_to_jaxpr(fun: lu.WrappedFun, pvals: Sequence[PartialVal],\ninstantiate: Union[bool, Sequence[bool]] = False,\n) -> Tuple[Jaxpr, Tuple[PartialVal, ...], Tuple[core.Value, ...]]:\n@@ -1523,7 +1523,7 @@ def arg_info_flattened(flat_pos: List[int]) -> str:\nreturn f\"the argument passed at flattened position {flat_pos[0]}\"\n-@annotate_function\n+@profiler.annotate_function\ndef trace_to_jaxpr_dynamic(fun: lu.WrappedFun,\nin_avals: Sequence[AbstractValue],\ndebug_info: Optional[DebugInfo] = None):\n@@ -1555,7 +1555,7 @@ def extend_jaxpr_stack(main, frame):\nassert frame is main.jaxpr_stack[-1]\nmain.jaxpr_stack = main.jaxpr_stack[:-1]\n-@annotate_function\n+@profiler.annotate_function\ndef trace_to_jaxpr_final(fun: lu.WrappedFun,\nin_avals: Sequence[AbstractValue],\ndebug_info: Optional[DebugInfo] = None):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -55,12 +55,12 @@ from jax._src.util import (unzip3, prod, safe_map, safe_zip,\ntuple_insert, tuple_delete, distributed_debug_log)\nfrom jax.errors import JAXTypeError\nfrom jax._src import dispatch\n+from jax._src import profiler\nfrom 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.lib.mlir import ir\nfrom jax._src.lib.mlir.dialects import mhlo\n-from jax._src.profiler import annotate_function\nfrom jax.tree_util import tree_flatten, tree_map\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\n@@ -295,7 +295,7 @@ def _shard_arg(arg, devices, arg_indices):\nreturn shard_arg_handlers[type(arg)](arg, devices, arg_indices)\n-@annotate_function\n+@profiler.annotate_function\ndef shard_args(devices: Sequence[xb.xla_client.Device],\nindices: Sequence[Sequence[Index]],\nargs) -> Sequence[Sequence[xb.xla_client.Buffer]]:\n@@ -897,7 +897,7 @@ def _shardings_to_mlir_shardings(\nreturn None\nreturn [xla.sharding_to_proto(s) for s in shardings]\n-@annotate_function\n+@profiler.annotate_function\ndef lower_parallel_callable(\nfun: lu.WrappedFun,\nbackend_name: Optional[str],\n@@ -1035,7 +1035,7 @@ class PmapComputation:\n# this is a method for api consistency with dispatch.XlaComputation\nreturn self._hlo\n- @annotate_function\n+ @profiler.annotate_function\ndef compile(self):\nif self._executable is None:\nself._executable = PmapExecutable.from_hlo(self._hlo, *self.compile_args)\n@@ -1171,7 +1171,7 @@ class PmapExecutable:\nreturn PmapExecutable(compiled, execute_fun, fingerprint, pci.avals)\n- @annotate_function\n+ @profiler.annotate_function\ndef call(self, *args):\n# TODO(frostig): do we need to check sharding and sharded avals?\narg_avals = map(xla.abstractify, args)\n@@ -1388,7 +1388,7 @@ def global_avals_to_results_handler(global_out_avals: Sequence[ShapedArray],\nlocal_out_specs, local_out_untiled_avals)\n-@annotate_function\n+@profiler.annotate_function\ndef replicate(val, axis_size, nrep, devices=None, backend=None, in_axis=0):\n\"\"\"Replicates ``val`` across multiple devices.\n@@ -1489,7 +1489,7 @@ def partitioned_sharding_spec(num_partitions: int,\nmesh_mapping=map(ShardedAxis, range(len(partitions))))\n-@annotate_function\n+@profiler.annotate_function\ndef execute_replicated(compiled, backend, in_handler, out_handler, *args):\ninput_bufs = in_handler(args)\nout_bufs = compiled.execute_sharded_on_local_devices(input_bufs)\n@@ -1877,7 +1877,7 @@ def vtile_by_mesh(fun: lu.WrappedFun,\nmain_type=SPMDBatchTrace)\nreturn fun\n-@annotate_function\n+@profiler.annotate_function\ndef lower_mesh_computation(\nfun: lu.WrappedFun,\ntransformed_name: str,\n@@ -2214,7 +2214,7 @@ class _ThreadLocalState(threading.local):\n_thread_local_state = _ThreadLocalState()\n-@partial(annotate_function, name=\"pxla.device_put\")\n+@partial(profiler.annotate_function, name=\"pxla.device_put\")\ndef device_put(x, devices: Sequence[xb.xla_client.Device], replicate: bool=False) -> List[xb.xla_client.Buffer]:\n\"\"\"Call device_put on a sequence of devices and return a flat sequence of buffers.\"\"\"\nif replicate:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -34,6 +34,7 @@ from jax import core\nfrom jax._src import ad_util\nfrom jax._src import device_array\nfrom jax._src import dtypes\n+from jax._src import profiler\nfrom jax import linear_util as lu\nfrom jax._src import source_info_util\nfrom jax._src.abstract_arrays import (make_shaped_array, array_types)\n@@ -45,7 +46,6 @@ from jax._src import util\nfrom jax._src.util import (prod, extend_name_stack, wrap_name,\nsafe_zip, safe_map, partition_list)\nfrom jax._src.lib import xla_client as xc\n-from jax._src.profiler import annotate_function\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import ad\n@@ -738,7 +738,7 @@ def set_up_aliases(c, xla_args, out_shape: XlaShape, donated_args, tuple_args):\nreturn tuple(out_donated_args)\n-@annotate_function\n+@profiler.annotate_function\ndef lower_jaxpr_to_xla_module(\nfn_name: str, jaxpr: core.ClosedJaxpr, platform: str, axis_env: AxisEnv,\nname_stack: str, tuple_args: bool, donated_invars: Sequence[bool],\n"
}
] | Python | Apache License 2.0 | google/jax | Use profiler.annotate_function |
260,424 | 06.12.2021 19:36:35 | 0 | bbf1a9ba9788933db25cd8459ff9a3daa91609b4 | Add checkify rule for scan. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/checkify.py",
"new_path": "jax/experimental/checkify.py",
"diff": "@@ -30,7 +30,7 @@ from jax._src import source_info_util, traceback_util\nfrom jax._src.lax import lax\nfrom jax._src.lax import slicing\nfrom jax._src.lax import control_flow\n-from jax._src.util import as_hashable_function, unzip2\n+from jax._src.util import as_hashable_function, unzip2, split_list\nsource_info_util.register_exclusion(__file__)\ntraceback_util.register_exclusion(__file__)\n@@ -198,6 +198,7 @@ def check_errors_subtrace(main, msgs, err, code, *args):\ndel main.error\nyield (err, code, *out_vals), msgs\n+# TODO take (error_aval, code_aval) instead of error here?\ndef checkify_jaxpr(jaxpr, error):\nf = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\nf, msgs = check_errors_subtrace(f)\n@@ -283,6 +284,20 @@ def cond_error_check(error, index, *ops, branches, linear):\nreturn outs, Error(err, code, new_msgs)\nerror_checks[control_flow.cond_p] = cond_error_check\n+def scan_error_check(error, *in_flat, reverse, length, jaxpr, num_consts, num_carry, linear, unroll):\n+ consts, carry, xs = split_list(in_flat, [num_consts, num_carry])\n+ checked_jaxpr, msgs_ = checkify_jaxpr(jaxpr, error)\n+ new_linear = (False, False, *linear)\n+ new_in_flat = [*consts, error.err, error.code, *carry, *xs]\n+ err, code, *outs = control_flow.scan_p.bind(\n+ *consts, *new_in_flat,\n+ reverse=reverse, length=length, jaxpr=checked_jaxpr,\n+ num_consts=len(consts), num_carry=len(carry)+2,\n+ linear=new_linear, unroll=unroll)\n+ new_msgs = {**error.msgs, **msgs_}\n+ return outs, Error(err, code, new_msgs)\n+error_checks[control_flow.scan_p] = scan_error_check\n+\n# TODO(mattjj,lenamartens): currently we bundle effectful-assert-discharging\n# with the error-check-adding transformation (checkify), but they could be\n# separated into two orthogonal transformations.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -147,6 +147,64 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertIs(err.get(), None)\n+ @jtu.skip_on_devices('tpu')\n+ def test_scan_map(self):\n+ def scan_body(_, x):\n+ return None, jnp.sin(x)\n+\n+ @jax.jit\n+ def f(xs):\n+ return lax.scan(scan_body, None, xs)\n+\n+ xs = jnp.array([0., 2.])\n+ err, (_, ch_outs) = checkify.checkify(f)(xs)\n+ _, outs = f(xs)\n+ self.assertIs(err.get(), None)\n+ self.assertArraysEqual(ch_outs, outs)\n+\n+ xs = jnp.array([3., jnp.inf])\n+ err, (_, ch_outs) = checkify.checkify(f)(xs)\n+ _, outs = f(xs)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertArraysEqual(ch_outs, outs)\n+\n+ @jtu.skip_on_devices('tpu')\n+ def test_scan_carry(self):\n+ def scan_body(carry, x):\n+ carry = carry-1.\n+ possible_nan = jnp.sin(1./carry)\n+ return carry, x+possible_nan\n+\n+ @jax.jit\n+ def f(carry, xs):\n+ return lax.scan(scan_body, carry, xs)\n+\n+ carry, xs = 3., jnp.ones((2,))\n+ err, (ch_out_carry, ch_outs) = checkify.checkify(f)(carry, xs)\n+ out_carry, outs = f(carry, xs)\n+ self.assertIs(err.get(), None)\n+ self.assertArraysEqual(ch_outs, outs)\n+ self.assertArraysEqual(ch_out_carry, out_carry)\n+\n+ # error happens on first iteration\n+ carry, xs = 1., jnp.ones((2,))\n+ err, (ch_out_carry, ch_outs) = checkify.checkify(f)(carry, xs)\n+ out_carry, outs = f(carry, xs)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertArraysEqual(ch_outs, outs)\n+ self.assertArraysEqual(ch_out_carry, out_carry)\n+\n+ # error happens on second iteration\n+ carry, xs = 2., jnp.ones((4,))\n+ err, (ch_out_carry, ch_outs) = checkify.checkify(f)(carry, xs)\n+ out_carry, outs = f(carry, xs)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertArraysEqual(ch_outs, outs)\n+ self.assertArraysEqual(ch_out_carry, out_carry)\n+\nclass AssertPrimitiveTests(jtu.JaxTestCase):\ndef test_assert_primitive_impl(self):\ndef f():\n"
}
] | Python | Apache License 2.0 | google/jax | Add checkify rule for scan. |
260,424 | 08.12.2021 15:07:43 | 0 | 0dc5a33a88cd9f51567ae5e10a2f34172368c166 | Add checkify rule for while_loop. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/checkify.py",
"new_path": "jax/experimental/checkify.py",
"diff": "@@ -198,17 +198,20 @@ def check_errors_subtrace(main, msgs, err, code, *args):\ndel main.error\nyield (err, code, *out_vals), msgs\n-# TODO take (error_aval, code_aval) instead of error here?\n-def checkify_jaxpr(jaxpr, error):\n- f = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\n+def checkify_fun_to_jaxpr(f, error, in_avals):\nf, msgs = check_errors_subtrace(f)\nf = check_errors_traceable(f, tuple(error.msgs.items()))\nerr_aval = core.raise_to_shaped(core.get_aval(error.err))\ncode_aval = core.raise_to_shaped(core.get_aval(error.code))\n- avals_in = [err_aval, code_aval, *jaxpr.in_avals]\n+ avals_in = [err_aval, code_aval, *in_avals]\njaxpr_out, _, literals_out = pe.trace_to_jaxpr_dynamic(f, avals_in)\nreturn core.ClosedJaxpr(jaxpr_out, literals_out), msgs()\n+# TODO take (error_aval, code_aval) instead of error here?\n+def checkify_jaxpr(jaxpr, error):\n+ f = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\n+ return checkify_fun_to_jaxpr(f, error, jaxpr.in_avals)\n+\n# TODO dedup with check_errors_toplevel\n@lu.transformation\ndef check_errors_traceable(msgs, err, code, *args):\n@@ -298,6 +301,42 @@ def scan_error_check(error, *in_flat, reverse, length, jaxpr, num_consts, num_ca\nreturn outs, Error(err, code, new_msgs)\nerror_checks[control_flow.scan_p] = scan_error_check\n+def checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error):\n+ cond_f = core.jaxpr_as_fun(cond_jaxpr)\n+ body_f = core.jaxpr_as_fun(body_jaxpr)\n+ def new_body_f(*vals):\n+ _ = cond_f(*vals)\n+ return body_f(*vals)\n+ return checkify_fun_to_jaxpr(lu.wrap_init(new_body_f), error, body_jaxpr.in_avals)\n+\n+def ignore_errors_jaxpr(jaxpr, error):\n+ \"\"\"Constructs a jaxpr which takes two extra args but ignores them.\"\"\"\n+ err_aval = core.raise_to_shaped(core.get_aval(error.err))\n+ code_aval = core.raise_to_shaped(core.get_aval(error.code))\n+ consts = jaxpr.consts\n+ jaxpr = jaxpr.jaxpr\n+ new_vars = core.gensym([jaxpr])\n+ new_invars = (new_vars(err_aval), new_vars(code_aval), *jaxpr.invars)\n+ new_jaxpr = core.Jaxpr(jaxpr.constvars, new_invars,\n+ jaxpr.outvars, jaxpr.eqns)\n+ return core.ClosedJaxpr(new_jaxpr, consts)\n+\n+def while_loop_error_check(error, *in_flat, cond_nconsts, cond_jaxpr, body_nconsts, body_jaxpr):\n+ # TODO(lenamartens): fix when an error occurs in the cond function and it then returns False.\n+ checked_body_jaxpr, msgs_ = checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error)\n+ compat_cond_jaxpr = ignore_errors_jaxpr(cond_jaxpr, error)\n+ c_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\n+ new_in_flat = [*c_consts, *b_consts, error.err, error.code, *carry]\n+ err, code, *out = control_flow.while_p.bind(\n+ *new_in_flat,\n+ cond_nconsts=cond_nconsts,\n+ cond_jaxpr=compat_cond_jaxpr,\n+ body_nconsts=body_nconsts,\n+ body_jaxpr=checked_body_jaxpr)\n+ new_msgs = {**error.msgs, **msgs_}\n+ return out, Error(err, code, new_msgs)\n+error_checks[control_flow.while_p] = while_loop_error_check\n+\n# TODO(mattjj,lenamartens): currently we bundle effectful-assert-discharging\n# with the error-check-adding transformation (checkify), but they could be\n# separated into two orthogonal transformations.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -205,6 +205,95 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertArraysEqual(ch_outs, outs)\nself.assertArraysEqual(ch_out_carry, out_carry)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_while_loop_body_error(self):\n+ def while_cond(val):\n+ i, _ = val\n+ return i < 2\n+\n+ def while_body(val):\n+ i, x = val\n+ possible_nan = jnp.sin(1./i)\n+ return i+1., x+possible_nan\n+\n+ @jax.jit\n+ def f(init_val):\n+ return lax.while_loop(while_cond, while_body, (init_val, 0.))\n+\n+ init_val = 1.\n+ err, ch_out = checkify.checkify(f)(init_val)\n+ out = f(init_val)\n+ self.assertIs(err.get(), None)\n+ self.assertArraysEqual(ch_out, out)\n+\n+ init_val = 0.\n+ err, ch_out = checkify.checkify(f)(init_val)\n+ out = f(init_val)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertArraysEqual(ch_out, out)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_while_loop_cond_error(self):\n+ def while_cond(val):\n+ _ = jnp.sin(1./val)\n+ return val < 2.\n+\n+ def while_body(val):\n+ return val+1.\n+\n+ @jax.jit\n+ def f(init_val):\n+ return lax.while_loop(while_cond, while_body, init_val)\n+\n+ init_val = 1.\n+ err, ch_out = checkify.checkify(f)(init_val)\n+ out = f(init_val)\n+ self.assertIs(err.get(), None)\n+ self.assertArraysEqual(ch_out, out)\n+\n+ init_val = 0.\n+ err, ch_out = checkify.checkify(f)(init_val)\n+ out = f(init_val)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertArraysEqual(ch_out, out)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_while_loop_body_and_cond_error(self):\n+ def while_cond(val):\n+ i, cond_val, _ = val\n+ _ = jnp.sin(cond_val)\n+ return i < 2\n+\n+ def while_body(val):\n+ i, cond_val, body_val = val\n+ possible_nan = jnp.cos(body_val)\n+ return i+1., cond_val, possible_nan\n+\n+ @jax.jit\n+ def f(cond_val, body_val):\n+ return lax.while_loop(while_cond, while_body, (0., cond_val, body_val))\n+\n+ cond_val = jnp.inf\n+ body_val = 1.\n+ err, _ = checkify.checkify(f)(cond_val, body_val)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+\n+ cond_val = 1.\n+ body_val = jnp.inf\n+ err, _ = checkify.checkify(f)(cond_val, body_val)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive cos\")\n+\n+ cond_val = jnp.inf\n+ body_val = jnp.inf\n+ err, _ = checkify.checkify(f)(cond_val, body_val)\n+ self.assertIsNotNone(err.get())\n+ # first error which occurs is in cond\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+\nclass AssertPrimitiveTests(jtu.JaxTestCase):\ndef test_assert_primitive_impl(self):\ndef f():\n"
}
] | Python | Apache License 2.0 | google/jax | Add checkify rule for while_loop. |
260,496 | 09.12.2021 14:54:23 | -3,600 | 9bd117f44da7dad5934c356e02f1f8a302aa29ce | Finish jax2tf no_xla documentation | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/converters_eval/no_xla_limitations.md",
"new_path": "jax/experimental/jax2tf/converters_eval/no_xla_limitations.md",
"diff": "@@ -17,23 +17,26 @@ are supported in [impl_no_xla.py](../impl_no_xla.py).\n## Summary Table\nThe table below shows for each XLA ops by which JAX primitives it is used, and\n-whether the ops is fully, partially, or not supported by the `jax2tf` emitted.\n+whether the ops is fully, partially, or not supported by the `jax2tf` emitter.\nIn the next section we provide more details on the ops for which we provide\npartial support.\n-| XLA ops | JAX primitive(s) | Supported |\n+For a detailed description of these XLA ops, please see the\n+[XLA Operation Semantics documentation](https://www.tensorflow.org/xla/operation_semantics).\n+\n+| XLA ops ([documentation](https://www.tensorflow.org/xla/operation_semantics)) | JAX primitive(s) ([documentation](https://jax.readthedocs.io/en/latest/jax.lax.html)) | Supported |\n| ------- | ---------------- | ------- |\n-| [XlaDot](https://www.tensorflow.org/xla/operation_semantics#dot) | `lax.dot_general` | Full |\n-| [XlaDynamicSlice](https://www.tensorflow.org/xla/operation_semantics#dynamicslice) | `lax.dynamic_slice` | Full |\n-| [XlaDynamicUpdateSlice](https://www.tensorflow.org/xla/operation_semantics#dynamicupdateslice) | `lax.dynamic_update_slice` | Full |\n-| [XlaPad](https://www.tensorflow.org/xla/operation_semantics#pad) | `lax.pad` | Full |\n-| [XlaConv](https://www.tensorflow.org/xla/operation_semantics#conv_convolution) | `lax.conv_general_dilated` | Partial |\n-| [XlaGather](https://www.tensorflow.org/xla/operation_semantics#gather) | `lax.gather` | Partial |\n-| [XlaReduceWindow](https://www.tensorflow.org/xla/operation_semantics#reducewindow) | `lax.reduce_window_sum_p`, `lax.reduce_window_min_p`, `lax.reduce_window_max_p`, and `lax.reduce_window_p` | Partial |\n-| [XlaScatter](https://www.tensorflow.org/xla/operation_semantics#scatter) | `lax.scatter_p`, `lax.scatter_min_p`, `lax.scatter_max_p`, `lax.scatter_mul_p`, `lax.scatter_add_p` | Unsupported |\n-| [XlaSelectAndScatter](https://www.tensorflow.org/xla/operation_semantics#selectandscatter) | `lax.select_and_scatter_add_p` | Unsupported |\n-| [XlaReduce](https://www.tensorflow.org/xla/operation_semantics#reduce) | `lax.reduce`, `lax.argmin`, `lax.argmax` | Unsupported |\n-| [XlaSort](https://www.tensorflow.org/xla/operation_semantics#sort) | `lax.sort` | Unsupported |\n+| XlaDot | `lax.dot_general` | Full |\n+| XlaDynamicSlice | `lax.dynamic_slice` | Full |\n+| XlaDynamicUpdateSlice | `lax.dynamic_update_slice` | Full |\n+| XlaPad | `lax.pad` | Full |\n+| XlaConv | `lax.conv_general_dilated` | [Partial](#xlaconv) |\n+| XlaGather | `lax.gather` | [Partial](#xlagather) |\n+| XlaReduceWindow | `lax.reduce_window_sum_p`, `lax.reduce_window_min_p`, `lax.reduce_window_max_p`, and `lax.reduce_window_p` | [Partial](#xlareducewindow) |\n+| XlaScatter | `lax.scatter_p`, `lax.scatter_min_p`, `lax.scatter_max_p`, `lax.scatter_mul_p`, `lax.scatter_add_p` | Unsupported |\n+| XlaSelectAndScatter | `lax.select_and_scatter_add_p` | Unsupported |\n+| XlaReduce | `lax.reduce`, `lax.argmin`, `lax.argmax` | Unsupported |\n+| XlaSort | `lax.sort` | Unsupported |\n## Partially Supported JAX Primitives\n@@ -54,34 +57,99 @@ lax.conv_general_dilated(\n)\n```\n+We provide support for convolutions as follows:\n+\n+* Only 2D convolutions, i.e. `lhs.ndim == 4`.\n+* Regular convolutions and atrous convolutions\n+ (i.e., `rhs_dilation != (1, 1, ...)`) are supported through the TF op\n+ [`tf.nn.conv2d`](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d).\n+* Transposed convolutions (i.e., `lhs_dilation != (1, 1, ...)`) are supported\n+ through\n+ [`tf.nn.conv2d_transpose`](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d_transpose).\n+ If using transposed convolutions, then `padding == 'VALID'`.\n+* Depthwise convolutions (i.e.\n+ `in_channels == feature_group_count and feature_group_count > 1`) are\n+ supported through\n+ [`tf.nn.depthwise_conv2d`](https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d).\n+* No support for batch groups, i.e. `batch_group_count == 1`.\n+* No support for feature groups, except for depth-wise convolutions.\n+* Input may be provided in any order (specified using `dimension_numbers`).\n+* Only one of depthwise, atrous and tranposed convolutions may be used at the\n+ same time.\n+\n+### XlaGather\n+\n+XLA's gather op is complex and covers may use cases. It is called from JAX using\n+`lax.gather`, but many other primitives and operations use it as well, for\n+instance, parallelization primitives `vmap` and `pmap` use gather to specify a\n+batch dimension, and it is used for slices or multidimensional indexing as well,\n+e.g. `x[0, 1]`, `x[:, :1]`, or `x[[0], [1]]`.\n+\n+The signature of [`lax.gather`](https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.gather.html#jax.lax.gather)\n+is as follows:\n+\n+```\n+jax.lax.gather(\n+ operand, start_indices, dimension_numbers, slice_sizes,\n+ unique_indices=False, indices_are_sorted=False, mode=None,\n+ fill_value=None\n+)\n+```\n+\nWe provide support for the following cases:\n-* Any stride size (`window_strides`).\n-* Any padding type (`padding`).\n-* Atrous convolutions (`rhs_dilation != (1, 1, ...)`).\n-* Transposed convolutions (`lhs_dilation != (1, 1, ...)`).\n-* Depthwise convolutions (`in_channels == feature_group_count and feature_group_count > 1`).\n-* Provide input in any order (specified using `dimension_numbers`).\n+* *Scalar indexing*. This means we are indexing into a single dimension,\n+ retrieving either a partial slice or a single value from that dimension. For\n+ all other dimensions we retrieve the full slice. Examples include `op[2]`,\n+ `op[:, :5, :]`, and `jnp.take(op, 0, axis=0)`. This means that\n+ `len(start_indices.shape) == 1`. We provide support for this path through the\n+ TF op\n+ [`tf.strided_slice`](https://www.tensorflow.org/api_docs/python/tf/strided_slice).\n-The implementation currently has the following limitations:\n+* *Multi-dimensional indexing*. This means we index into multiple dimensions,\n+ e.g., `jnp.take(op, [[0], [1]], axis=0)` or `op[[0], [4], [1]]`. We currently\n+ only support multi-dimensional indexing if the last dimension is 1, which\n+ means we can only retrieve a single value per dimension, and we can't retrieve\n+ slices. We provide support for this path through the TF op\n+ [`tf.gather`](https://www.tensorflow.org/api_docs/python/tf/gather).\n-* Only 2D convolutions, i.e. `lhs.ndim == 4`.\n-* No batch groups, i.e. `batch_group_count == 1`.\n-* No feature groups, except for depth-wise convolutions (See above).\n-* If using transposed convolutions, then `padding == 'VALID'`.\n-* Only one of depthwise, atrous and tranposed convolutions.\n+* *Gather with a batch dimension*. E.g., when doing\n+ `jax.vmap(lax.dynamic_slice)`, which will result in a call to `lax.gather`\n+ where the first dimension of the input is the batch dimension. This means that\n+ `len(batch_dims) == 1`. We currently only support a single batch dimension\n+ (i.e., `vmap(vmap))` does not work). We provide support for this path through\n+ the TF op [`tf.slice`](https://www.tensorflow.org/api_docs/python/tf/slice).\n-### XlaGather\n+All other cases of `lax.gather` are currently not supported.\n-`TODO(marcvanzee): Write this`\n### XlaReduceWindow\n-`TODO(marcvanzee): Write this`\n-\n+This op is called by `lax.reduce_window_sum_p`, `lax.reduce_window_max_p`,\n+`lax.reduce_window_min_p` and `lax.reduce_window`.\n+Of these ops, we currently only support `lax.reduce_window_sum_p` and\n+`lax.reduce_window_max_p` through respectively the TF ops\n+[`tf.nn.avg_pool`](https://www.tensorflow.org/api_docs/python/tf/nn/avg_pool) and\n+[`tf.nn.max_pool`](https://www.tensorflow.org/api_docs/python/tf/nn/max_pool).\n+Both functions have the following signature:\n+```\n+lax.reduce_window_{sum,max}(\n+ operand, window_dimensions, window_strides,\n+ padding, base_dilation, window_dilation)\n+```\n+We support these ops with the following limitations:\n+* For `reduce_window_sum_p`, dtypes `jnp.bool`, `jnp.uint32`, `jnp.uint64`,\n+ `jnp.complex64`, and `jnp.complex128` are not supported.\n+* For `reduce_window_max_p`, dtype `jnp.float16`, `jnp.float32`, and\n+ `jnp.float64` are not supported.\n+* We support at most 3 spatial dimension.\n+* `base_dilation = (1, 1, ...)`.\n+* `window_dilation == (1, 1, ...)`.\n+* `padding` should either be `VALID` or `SAME`.\n+`lax.reduce_window_min_p` and `lax.reduce_window` are currently not supported.\n"
}
] | Python | Apache License 2.0 | google/jax | Finish jax2tf no_xla documentation |
260,287 | 10.12.2021 11:29:41 | 28,800 | 1b9a9fff0c0c43409ecf34b3821c4e1df59462bd | Clarify a comment in ParsedPartitionSpec.eq_given_rank
Previous one used an overly lax definition of "semantic equality". | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/pjit.py",
"new_path": "jax/experimental/pjit.py",
"diff": "@@ -393,12 +393,22 @@ class ParsedPartitionSpec:\nself.sync == other.sync)\ndef eq_given_rank(self, other, rank):\n- # ParsedPartitionSpecs may contain trailing empty tuples that don't change\n- # the semantic meaning of the spec but are still valid specs. For example,\n- # for a 2D array, (), ((),), and ((), ()) are all valid specs meaning the\n- # array is fully replicated (no dimension partitioned). This method compares\n- # two specs for semantic equivalence and asserts they are valid specs for\n- # the given array rank.\n+ \"\"\"Determines whether the specs are equivalent when considering arrays of a given rank.\n+\n+ ParsedPartitionSpecs may contain trailing empty tuples, that make them\n+ semantically different in general, and yet in some situations we prefer\n+ to regard them as equivalent. For example, partitions of () and ((),)\n+ cannot be always considered equivalent, since the first one is a valid\n+ spec for a scalar value, while the second is not! However, when either of\n+ those are applied to a 2D array, they both mean that the array is fully\n+ replicated.\n+\n+ Because of those subtle differences, we use __eq__ to decide semantic\n+ equality in general, while this method determines whether the two specs\n+ are equivalent when applied to an array of a given rank. Note that this\n+ relation has larger equivalence classes than __eq__ (i.e. x == y implies\n+ x.eq_given_rank(y, rank)).\n+ \"\"\"\nassert len(self.partitions) <= rank and len(other.partitions) <= rank\nmin_length = min(len(self.partitions), len(other.partitions))\nreturn (self.partitions[:min_length] == other.partitions[:min_length] and\n"
}
] | Python | Apache License 2.0 | google/jax | Clarify a comment in ParsedPartitionSpec.eq_given_rank
Previous one used an overly lax definition of "semantic equality".
PiperOrigin-RevId: 415567823 |
260,447 | 10.12.2021 14:08:21 | 28,800 | 8abdd9eceb7bba66de4d3a2554e50b9bbf0b8aec | [sparse] Update bcoo_dot_general GPU translation rule. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcoo.py",
"new_path": "jax/experimental/sparse/bcoo.py",
"diff": "@@ -25,7 +25,7 @@ from jax import lax\nfrom jax import tree_util\nfrom jax import vmap\nfrom jax.experimental.sparse._base import JAXSparse\n-from jax.experimental.sparse.util import _safe_asarray\n+from jax.experimental.sparse.util import _safe_asarray, CuSparseEfficiencyWarning\nfrom jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n@@ -36,8 +36,12 @@ from jax._src.api_util import flatten_axes\nfrom jax._src.lax.lax import (\nranges_like, remaining, _dot_general_batch_dim_nums, _dot_general_shape_rule,\nDotDimensionNumbers)\n+from jax._src.lib import cusparse\n+from jax._src.lib import xla_client as xc\nfrom jax._src.numpy.lax_numpy import _unique\n+xops = xc._xla.ops\n+\nDtype = Any\nShape = Tuple[int, ...]\n@@ -610,6 +614,172 @@ def _bcoo_dot_general_abstract_eval(lhs_data, lhs_indices, rhs, *, dimension_num\nreturn core.ShapedArray(out_shape, lhs_data.dtype)\n+def _bcoo_correct_oob_indices_impl(data, indices, shape):\n+ \"\"\"Replaces out-of-bound indices in a padded representation with zeros.\n+\n+ The BCOO format at times must pad indices to indicate unused entries, and it does this\n+ with out-of-bounds indices. This can cause problems when passing the data to other\n+ backends (like cuSparse) that do not handle this natively. This function converts\n+ out-of-bounds indices to zeros, and also zeros-out associated values in the data array.\n+\n+ Examples:\n+\n+ >>> M = jnp.array([[1, 0, 2, 3, 0], [0, 0, 0, 4, 0]])\n+ >>> bcoo_mat = BCOO.fromdense(M, nse=7)\n+ >>> bcoo_mat\n+ BCOO(int32[2, 5], nse=7)\n+ >>> data = bcoo_mat.data\n+ >>> data\n+ DeviceArray([1, 2, 3, 4, 0, 0, 0], dtype=int32)\n+ >>> indices = bcoo_mat.indices\n+ >>> indices\n+ DeviceArray([[0, 0],\n+ [0, 2],\n+ [0, 3],\n+ [1, 3],\n+ [2, 5],\n+ [2, 5],\n+ [2, 5]], dtype=int32)\n+\n+ After the out-of-bound indices correction:\n+\n+ >>> _, indices = _bcoo_correct_oob_indices_impl(data, indices, shape=(2, 5))\n+ >>> indices\n+ DeviceArray([[0, 0],\n+ [0, 2],\n+ [0, 3],\n+ [1, 3],\n+ [0, 0],\n+ [0, 0],\n+ [0, 0]], dtype=int32)\n+\n+ If the input data contains nonzeros at the corrected indices:\n+ >>> data = jnp.arange(1, 8)\n+ >>> indices = bcoo_mat.indices\n+\n+ After the out-of-bound indices correction:\n+ >>> data, _ = _bcoo_correct_oob_indices_impl(data, indices, shape=(2, 5))\n+\n+ >>> data\n+ DeviceArray([1, 2, 3, 4, 0, 0, 0], dtype=int32)\n+ \"\"\"\n+ # TODO: support batch dimension?\n+ props = _validate_bcoo(data, indices, shape)\n+ if props.n_batch or props.n_dense:\n+ raise NotImplementedError(\"`n_batch` and `n_dense` not yet supported.\")\n+ mask = (indices >= jnp.array(shape)).any(-1)\n+ return jnp.where(mask, 0, data), jnp.where(mask[:, None], 0, indices)\n+\n+_bcoo_correct_oob_indices = xla.lower_fun(\n+ _bcoo_correct_oob_indices_impl, multiple_results=True, new_style=True)\n+\n+_bcoo_dot_general_default_translation_rule = xla.lower_fun(\n+ _bcoo_dot_general_impl, multiple_results=False, new_style=True)\n+\n+def _bcoo_dot_general_cuda_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs, *, dimension_numbers,\n+ lhs_shape):\n+\n+ c = ctx.builder\n+\n+ (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n+ lhs_data_aval, lhs_indices_aval, rhs_aval, = avals_in\n+ props = _validate_bcoo_indices(lhs_indices_aval, lhs_shape)\n+ rhs_ndim = len(c.get_shape(rhs).dimensions())\n+\n+ # Checks the shapes of lhs and rhs.\n+ assert props.n_dense == 0\n+ assert props.n_batch == 0\n+ assert props.n_sparse in [1, 2]\n+ assert rhs_ndim in [1, 2]\n+\n+ # Checks the operation dimensions.\n+ assert len(lhs_batch) == 0\n+ assert len(rhs_batch) == 0\n+ assert len(lhs_contract) == 1\n+\n+ # Checks the dtype.\n+ assert lhs_data_aval.dtype in [np.float32, np.float64, np.complex64, np.complex128]\n+ assert lhs_data_aval.dtype == rhs_aval.dtype\n+ assert lhs_indices_aval.dtype == np.int32\n+\n+ if rhs_ndim == 1:\n+ bcoo_dot_general_fn = cusparse.coo_matvec\n+ elif rhs_ndim == 2:\n+ bcoo_dot_general_fn = cusparse.coo_matmat\n+ if rhs_contract[0] == 1:\n+ rhs = xops.Transpose(rhs, permutation=[1, 0])\n+ else:\n+ raise ValueError(f\"rhs has to be 1d or 2d; get {rhs_ndim}d.\")\n+\n+ lhs_transpose = False\n+ if props.n_sparse == 1:\n+ # Converts lhs to a row vector.\n+ col = xops.Collapse(lhs_indices, dimensions=[0, 1])\n+ row = xops.Broadcast(xops.Constant(c, jnp.array(0, dtype=jnp.int32)),\n+ c.get_shape(col).dimensions())\n+ lhs_shape = (1, lhs_shape[0])\n+ dot_product = bcoo_dot_general_fn(\n+ c, lhs_data, row, col, rhs, shape=lhs_shape, transpose=lhs_transpose)\n+\n+ if rhs_ndim == 1:\n+ # Transforms a single-element array to a scalar.\n+ return [xops.Reshape(dot_product, dimensions=[0], new_sizes=[])]\n+ else:\n+ return [xops.Collapse(dot_product, dimensions=[0, 1])]\n+ elif props.n_sparse == 2:\n+ row = xops.Collapse(\n+ xops.Slice(lhs_indices,\n+ start_indices=[0, 0],\n+ limit_indices=[c.get_shape(lhs_indices).dimensions()[0], 1],\n+ strides=[1, 1]),\n+ dimensions=[0, 1])\n+ col = xops.Collapse(\n+ xops.Slice(lhs_indices,\n+ start_indices=[0, 1],\n+ limit_indices=[c.get_shape(lhs_indices).dimensions()[0], 2],\n+ strides=[1, 1]),\n+ dimensions=[0, 1])\n+\n+ if lhs_contract[0] == 0:\n+ lhs_transpose = True\n+\n+ return [bcoo_dot_general_fn(\n+ c, lhs_data, row, col, rhs, shape=lhs_shape, transpose=lhs_transpose)]\n+ else:\n+ raise ValueError(f\"lhs has to be 1d or 2d; get {props.n_sparse}d.\")\n+\n+def _bcoo_dot_general_gpu_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs, *, dimension_numbers,\n+ lhs_shape):\n+\n+ (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n+ lhs_data_aval, lhs_indices_aval, rhs_aval, = avals_in\n+ n_batch, n_sparse, n_dense, _ = _validate_bcoo(\n+ lhs_data_aval, lhs_indices_aval, lhs_shape)\n+\n+ dtype = lhs_data_aval.dtype\n+ if dtype not in [np.float32, np.float64, np.complex64, np.complex128]:\n+ warnings.warn(f'bcoo_dot_general cusparse lowering not available for '\n+ f'dtype={dtype}. Falling back to default implementation.',\n+ CuSparseEfficiencyWarning)\n+ return _bcoo_dot_general_default_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n+ dimension_numbers=dimension_numbers, lhs_shape=lhs_shape)\n+\n+ if (n_batch or n_dense or\n+ n_sparse not in [1, 2] or rhs_aval.ndim not in [1, 2] or\n+ lhs_batch or rhs_batch or len(lhs_contract) != 1):\n+ return _bcoo_dot_general_default_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n+ dimension_numbers=dimension_numbers, lhs_shape=lhs_shape)\n+ else:\n+ lhs_data, lhs_indices = _bcoo_correct_oob_indices(\n+ ctx, avals_in[:2], avals_in[:2], lhs_data, lhs_indices, shape=lhs_shape)\n+ return _bcoo_dot_general_cuda_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n+ dimension_numbers=dimension_numbers, lhs_shape=lhs_shape)\n+\ndef _bcoo_dot_general_jvp_lhs(lhs_data_dot, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_shape):\nreturn bcoo_dot_general(lhs_data_dot, lhs_indices, rhs, dimension_numbers=dimension_numbers, lhs_shape=lhs_shape)\n@@ -675,8 +845,13 @@ def _bcoo_dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers,\nad.defjvp(bcoo_dot_general_p, _bcoo_dot_general_jvp_lhs, None, _bcoo_dot_general_jvp_rhs)\nad.primitive_transposes[bcoo_dot_general_p] = _bcoo_dot_general_transpose\nbatching.primitive_batchers[bcoo_dot_general_p] = _bcoo_dot_general_batch_rule\n-xla.register_translation(bcoo_dot_general_p, xla.lower_fun(\n- _bcoo_dot_general_impl, multiple_results=False, new_style=True))\n+\n+xla.register_translation(\n+ bcoo_dot_general_p, _bcoo_dot_general_default_translation_rule)\n+if cusparse and cusparse.is_supported:\n+ xla.register_translation(bcoo_dot_general_p,\n+ _bcoo_dot_general_gpu_translation_rule,\n+ platform='gpu')\n#----------------------------------------------------------------------\n# bcoo_dot_general_sampled\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -827,6 +827,108 @@ class BCOOTest(jtu.JaxTestCase):\n# TODO(jakevdp): In rare cases, this fails python_should_be_executing check. Why?\n# self._CompileAndCheck(f_sparse, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_rhs_shape={}_lhs_contracting={}_rhs_contracting={}\"\n+ .format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype),\n+ lhs_contracting, rhs_contracting),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"lhs_contracting\": lhs_contracting, \"rhs_contracting\": rhs_contracting}\n+ for lhs_shape, rhs_shape, lhs_contracting, rhs_contracting in [\n+ [(5,), (5,), [0], [0]],\n+ [(5,), (5, 7), [0], [0]],\n+ [(5,), (7, 5), [0], [1]],\n+ [(5, 7), (5,), [0], [0]],\n+ [(7, 5), (5,), [1], [0]],\n+ [(3, 5), (2, 5), [1], [1]],\n+ [(3, 5), (5, 2), [1], [0]],\n+ [(5, 3), (2, 5), [0], [1]],\n+ [(5, 3), (5, 2), [0], [0]],\n+ ]\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.complex))\n+ def test_bcoo_dot_general_cusparse(\n+ self, lhs_shape, rhs_shape, dtype, lhs_contracting, rhs_contracting):\n+ rng = jtu.rand_small(self.rng())\n+ rng_sparse = rand_sparse(self.rng())\n+ def args_maker():\n+ lhs = rng_sparse(lhs_shape, dtype)\n+ rhs = rng(rhs_shape, dtype)\n+ data, indices = sparse.bcoo_fromdense(lhs, index_dtype=jnp.int32)\n+ return data, indices, lhs, rhs\n+ dimension_numbers = ((lhs_contracting, rhs_contracting), ([], []))\n+\n+ def f_dense(data, indices, lhs, rhs):\n+ return lax.dot_general(lhs, rhs, dimension_numbers=dimension_numbers)\n+\n+ def f_sparse(data, indices, lhs, rhs):\n+ return sparse.bcoo_dot_general(data, indices, rhs,\n+ lhs_shape=lhs.shape,\n+ dimension_numbers=dimension_numbers)\n+\n+ self._CompileAndCheck(f_sparse, args_maker)\n+ self._CheckAgainstNumpy(f_dense, f_sparse, args_maker)\n+\n+ def test_bcoo_correct_oob_indices(self):\n+ dense_2d = jnp.array([[1, 0, 2, 3, 0], [0, 0, 0, 4, 0]])\n+ nse_2d = 7\n+ sparse_2d, indices_2d = sparse.bcoo_fromdense(dense_2d, nse=nse_2d)\n+ corrected_data_2d, corrected_indices_2d = sparse.bcoo._bcoo_correct_oob_indices_impl(\n+ jnp.arange(1, nse_2d + 1), indices_2d, dense_2d.shape)\n+ expected_indices_2d = jnp.array(\n+ [[0, 0], [0, 2], [0, 3], [1, 3], [0, 0], [0, 0], [0, 0]],\n+ dtype=jnp.int32)\n+\n+ with self.subTest(msg=\"Corrected 2D indices\"):\n+ self.assertArraysEqual(corrected_indices_2d, expected_indices_2d)\n+\n+ with self.subTest(msg=\"Corrected 2D data\"):\n+ self.assertArraysEqual(corrected_data_2d, sparse_2d)\n+\n+ dense_1d = jnp.array([0, 1, 0, 2, 3, 0])\n+ nse_1d = 5\n+ sparse_1d, indices_1d = sparse.bcoo_fromdense(dense_1d, nse=nse_1d)\n+ corrected_data_1d, corrected_indices_1d = sparse.bcoo._bcoo_correct_oob_indices_impl(\n+ jnp.arange(1, nse_1d + 1), indices_1d, dense_1d.shape)\n+ expected_indices_1d = jnp.array([[1], [3], [4], [0], [0]], dtype=jnp.int32)\n+\n+ with self.subTest(msg=\"Corrected 1D indices\"):\n+ self.assertArraysEqual(corrected_indices_1d, expected_indices_1d)\n+\n+ with self.subTest(msg=\"Corrected 1D data\"):\n+ self.assertArraysEqual(corrected_data_1d, sparse_1d)\n+\n+ @unittest.skipIf(jtu.device_under_test() != \"gpu\", \"test requires GPU\")\n+ def test_bcoo_dot_general_padding_correction_cusparse(self):\n+ \"\"\"Tests bcoo dot general with index padding coorection and cusparse.\"\"\"\n+\n+ rhs = jnp.ones((5, 3), dtype=jnp.float32)\n+\n+ lhs_2d_dense = jnp.array([[1, 0, 2, 3, 0], [0, 0, 0, 4, 0]],\n+ dtype=jnp.float32)\n+ lhs_2d_sparse, lhs_sparse_2d_indicdes = sparse.bcoo_fromdense(\n+ lhs_2d_dense, nse=7)\n+ dimension_numbers = (([1], [0]), ([], []))\n+ expected_2d = lax.dot_general(\n+ lhs_2d_dense, rhs, dimension_numbers=dimension_numbers)\n+ actual_2d = sparse.bcoo_dot_general(lhs_2d_sparse, lhs_sparse_2d_indicdes,\n+ rhs, lhs_shape=lhs_2d_dense.shape,\n+ dimension_numbers=dimension_numbers)\n+ with self.subTest(msg=\"2D\"):\n+ self.assertAllClose(expected_2d, actual_2d)\n+\n+ lhs_1d_dense = jnp.array([0, 1, 0, 2, 0], dtype=jnp.float32)\n+ lhs_1d_sparse, lhs_sparse_1d_indicdes = sparse.bcoo_fromdense(\n+ lhs_1d_dense, nse=7)\n+ dimension_numbers = (([0], [0]), ([], []))\n+ expected_1d = lax.dot_general(\n+ lhs_1d_dense, rhs, dimension_numbers=dimension_numbers)\n+ actual_1d = sparse.bcoo_dot_general(lhs_1d_sparse, lhs_sparse_1d_indicdes,\n+ rhs, lhs_shape=lhs_1d_dense.shape,\n+ dimension_numbers=dimension_numbers)\n+ with self.subTest(msg=\"1D\"):\n+ self.assertAllClose(expected_1d, actual_1d)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": props.testcase_name(), \"props\": props}\nfor props in _generate_bcoo_dot_general_properties(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparsify_test.py",
"new_path": "tests/sparsify_test.py",
"diff": "@@ -384,5 +384,11 @@ class SparsifyTracerTest(SparsifyTest):\nself.assertIsInstance(x, SparseTracer)\nf(jnp.arange(5))\n+ # TODO(tlu7): check tracer for dot general with `lhs.T` and cusparse.\n+ def testSparsify(self):\n+ if jtu.device_under_test() == 'gpu':\n+ self.skipTest(\"fails on GPU with CuSparse.\")\n+ super().testSparsify()\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Update bcoo_dot_general GPU translation rule.
Co-authored-by: Jake VanderPlas <jakevdp@google.com> |
260,411 | 02.12.2021 08:19:16 | -7,200 | c9691a5c0f5a2a5b256c4c4c3d1c46520e170670 | Refactor the lowering of remat.
Replace the XLA-specific lowering with the same logic written
with LAX primitives. This will allow reusing the logic for
different lowerings, e.g., jax2tf or MLIR.
This is a new attempt at which was rolled-back in
due to test failures. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -291,6 +291,7 @@ def remat_translation(ctx, avals_in, avals_out, *in_nodes,\nreturn xla._remat_using_cond(ctx, in_nodes, \"checkpoint\", jaxpr)\nelse:\nreturn xla.jaxpr_subcomp(ctx, jaxpr, (), *in_nodes)\n+if not xla._USE_LAX_REMAT_LOWERING:\nxla.register_translation(remat_p, remat_translation)\ndef remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\n@@ -347,14 +348,14 @@ def remat_partial_eval(trace, *tracers, jaxpr, **params):\nreturn pe._zip_knowns(out_known_tracers, out_jaxpr_tracers, out_unknowns)\npe.custom_partial_eval_rules[remat_p] = remat_partial_eval\n-def remat_paratial_eval_custom_params_updater(_, __, params_known, params_staged):\n+def remat_partial_eval_custom_params_updater(_, __, params_known, params_staged):\njaxpr_known = params_known.pop('call_jaxpr')\njaxpr_staged = params_staged.pop('call_jaxpr')\nreturn (dict(params_known, jaxpr=jaxpr_known),\ndict(params_staged, jaxpr=jaxpr_staged, differentiated=True))\npe.partial_eval_jaxpr_custom_rules[remat_p] = \\\npartial(pe.call_partial_eval_custom_rule, 'jaxpr',\n- remat_paratial_eval_custom_params_updater)\n+ remat_partial_eval_custom_params_updater)\ndef remat_transpose(reduce_axes, out_cts, *in_primals, jaxpr, **params):\nassert not jaxpr.constvars\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow.py",
"new_path": "jax/_src/lax/control_flow.py",
"diff": "@@ -31,6 +31,7 @@ import numpy as np\nimport jax\nfrom jax._src import api\nfrom jax import core\n+from jax._src import ad_checkpoint\nfrom jax._src import dtypes\nfrom jax._src import source_info_util\nfrom jax._src import util\n@@ -51,7 +52,7 @@ from jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.lib import xla_client\nfrom jax._src.traceback_util import api_boundary\nfrom jax._src.util import (unzip2, unzip3, safe_map, safe_zip,\n- split_list, cache, extend_name_stack)\n+ split_list, cache, extend_name_stack, wrap_name)\nfrom jax.tree_util import (tree_flatten, tree_unflatten, treedef_is_leaf,\ntreedef_children, treedef_tuple, tree_multimap,\ntree_leaves, tree_structure)\n@@ -2924,3 +2925,93 @@ def _cumulative_jvp_rule(primals, tangents, *, axis: int, reverse: bool,\nad.primitive_jvps[cumprod_p] = partial(_cumulative_jvp_rule, combine_fn=lax.mul)\nad.primitive_jvps[cummin_p] = partial(_cumulative_jvp_rule, combine_fn=lax.min)\nad.primitive_jvps[cummax_p] = partial(_cumulative_jvp_rule, combine_fn=lax.max)\n+\n+\n+def _dummy_remat_result(aval: core.AbstractValue):\n+ \"\"\"A result that will be discarded\"\"\"\n+ if aval is core.AbstractToken:\n+ return lax.create_token()\n+ elif aval is core.abstract_unit:\n+ return core.unit\n+ else:\n+ return lax.broadcast(np.array(0, dtype=aval.dtype), aval.shape) # type: ignore\n+\n+def _remat_translation_using_cond(*args,\n+ jaxpr: core.Jaxpr):\n+ # Implements:\n+ # if(rng(0, 1) < 2)\n+ # return eval_jaxpr(*args)\n+ # else:\n+ # return 0\n+ avals_out = tuple(ov.aval for ov in jaxpr.outvars)\n+\n+ def remat_comp(*args):\n+ return tuple(core.eval_jaxpr(jaxpr, (), *args))\n+ def dummy_comp(*args):\n+ return tuple(_map(_dummy_remat_result, avals_out))\n+\n+ cond_pred = (lax.rng_uniform(np.float32(0), np.float32(1), shape=()) < np.float32(2))\n+ return cond(cond_pred, remat_comp, dummy_comp, *args)\n+\n+def _remat_translation_using_while(*args,\n+ jaxpr: core.Jaxpr):\n+ # Implements:\n+ # for(counter=0, result=0; counter < rng(1, 2); counter ++) {\n+ # result = eval_jaxpr(*args)\n+ # }\n+ # The loop carry is a tuple: (counter, result, args)\n+ avals_out = tuple(ov.aval for ov in jaxpr.outvars)\n+ dummies_like_result = tuple(_map(_dummy_remat_result, avals_out))\n+ carry_init = (np.int32(0), dummies_like_result, args)\n+ def cond(carry):\n+ counter, _, _ = carry\n+ return counter < lax.rng_uniform(np.int32(1), np.int32(2), shape=())\n+\n+ def body(carry):\n+ counter, _, args = carry\n+ results = core.eval_jaxpr(jaxpr, (), *args)\n+ return (counter + 1, tuple(results), args)\n+\n+ carry_res = while_loop(cond, body, carry_init)\n+ return carry_res[1]\n+\n+def _remat_translation_rule(*args,\n+ call_jaxpr: Optional[core.Jaxpr] = None,\n+ jaxpr: Optional[core.Jaxpr] = None,\n+ platform: str,\n+ prevent_cse: bool, differentiated: bool,\n+ policy,\n+ concrete: bool = False,\n+ name: str = \"checkpoint\"):\n+ # Support either \"jaxpr\" (for remat2) and \"call_jaxpr\" (for remat)\n+ # name is not passed for remat2, defaults to \"checkpoint\"\n+ # TODO: remove call_jaxpr once we drop the remat call primitive\n+ if jaxpr is None:\n+ jaxpr = call_jaxpr\n+ assert jaxpr is not None\n+ assert not jaxpr.constvars\n+\n+ del concrete, policy # Unused.\n+ if differentiated and prevent_cse:\n+ if platform == \"gpu\":\n+ translation_rule = _remat_translation_using_while\n+ else:\n+ translation_rule = _remat_translation_using_cond\n+ else:\n+ translation_rule = lambda *args, jaxpr: core.eval_jaxpr(jaxpr, (), *args)\n+\n+ return jax.named_call(translation_rule, name=wrap_name(name, \"remat\"))(*args, jaxpr=jaxpr)\n+\n+for platform in (\"cpu\", \"gpu\", \"tpu\"):\n+ for remat_primitive in (pe.remat_call_p, ad_checkpoint.remat_p): # type: ignore\n+ if xla._USE_LAX_REMAT_LOWERING:\n+ xla.register_translation(remat_primitive,\n+ xla.lower_fun(partial(_remat_translation_rule,\n+ platform=platform),\n+ new_style=True, multiple_results=True,\n+ backend=platform),\n+ platform=platform)\n+ mlir.register_lowering(remat_primitive,\n+ mlir.lower_fun(partial(_remat_translation_rule,\n+ platform=platform),\n+ multiple_results=True))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -24,13 +24,14 @@ from jax import lax\nfrom jax._src import ad_util\nfrom jax._src import api_util\nfrom jax import config\n-from jax._src import api\nfrom jax import core, custom_derivatives\n-from jax._src import dispatch\n-from jax._src import dtypes\nfrom jax import linear_util as lu\nfrom jax import random, tree_util\nfrom jax import numpy as jnp\n+from jax._src import ad_checkpoint\n+from jax._src import api\n+from jax._src import dispatch\n+from jax._src import dtypes\nfrom jax._src.lax import control_flow as lax_control_flow\nfrom jax._src.lax import lax as lax_internal\nfrom jax._src.lax import linalg as lax_linalg\n@@ -856,7 +857,7 @@ class TensorFlowTrace(core.Trace):\nassert call_primitive.multiple_results\nvals: Sequence[TfVal] = [t.val for t in tracers]\navals: Sequence[core.ShapedArray] = tuple(t.aval for t in tracers)\n- fun = _interpret_subtrace(fun, self.main, avals)\n+ interpreted_fun = _interpret_subtrace(fun, self.main, avals)\nextra_name_stack = None\nif call_primitive == core.named_call_p:\nextra_name_stack = util.wrap_name(params[\"name\"], \"named\")\n@@ -867,9 +868,9 @@ class TensorFlowTrace(core.Trace):\nif call_primitive == core.named_call_p:\nwith tf.name_scope(_sanitize_scope_name(params[\"name\"])):\nvals_out: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\n- fun.call_wrapped(*vals)\n+ interpreted_fun.call_wrapped(*vals)\nelif call_primitive == sharded_jit.sharded_call_p:\n- vals_out = _sharded_call(fun, vals, **params)\n+ vals_out = _sharded_call(interpreted_fun, vals, **params)\nelif call_primitive == xla.xla_call_p:\nif _WRAP_JAX_JIT_WITH_TF_FUNCTION:\n# Make a nested tf.function(jit_compile=True)\n@@ -877,7 +878,7 @@ class TensorFlowTrace(core.Trace):\ndef f_tf(*tf_args):\nnonlocal store_tf_res_avals\ntf_res_out: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\n- _call_wrapped_with_new_constant_cache(fun, tf_args,\n+ _call_wrapped_with_new_constant_cache(interpreted_fun, tf_args,\nfresh_constant_cache=False)\ntf_res_vals, tf_res_avals = util.unzip2(tf_res_out)\nstore_tf_res_avals = tf_res_avals\n@@ -885,9 +886,9 @@ class TensorFlowTrace(core.Trace):\ntf_vals_out = tf.function(f_tf, autograph=False, jit_compile=True)(*vals)\nvals_out = zip(tf_vals_out, store_tf_res_avals)\nelse:\n- vals_out = fun.call_wrapped(*vals)\n+ vals_out = interpreted_fun.call_wrapped(*vals)\nelse:\n- vals_out = fun.call_wrapped(*vals)\n+ vals_out = interpreted_fun.call_wrapped(*vals)\nreturn [TensorFlowTracer(self, v, a) for v, a in vals_out]\ndef post_process_call(self, call_primitive: core.Primitive,\n@@ -963,13 +964,11 @@ for unexpected in [core.call_p, core.named_call_p, xla.xla_call_p,\n# Primitives that are not yet implemented must be explicitly declared here.\ntf_not_yet_impl = [\n- \"rng_uniform\",\n\"clz\",\n\"igamma_grad_a\",\n\"random_gamma_grad\",\n\"reduce_precision\",\n\"schur\",\n- \"remat2\", # TODO(mattjj,necula): support new remat?\n\"name\",\n# Not high priority?\n@@ -2035,6 +2034,13 @@ def _rng_bit_generator(key: TfVal, *, shape, dtype, algorithm) -> Sequence[TfVal\ntf_impl[lax.rng_bit_generator_p] = _rng_bit_generator\n+def _rng_uniform(minval: TfVal, maxval: TfVal, *, shape) -> TfVal:\n+ shape_tf = _eval_shape(shape)\n+ return tf.random.uniform(shape_tf, minval=minval, maxval=maxval, dtype=minval.dtype)\n+\n+tf_impl[lax.rng_uniform_p] = _rng_uniform\n+\n+\ndef _gather_dimensions_proto(indices_shape, dimension_numbers):\nproto = xla_data_pb2.GatherDimensionNumbers()\nproto.offset_dims.extend(dimension_numbers.offset_dims)\n@@ -2274,6 +2280,12 @@ tf_impl_with_avals[lax.scan_p] = _convert_jax_impl(\nlax_control_flow._scan_impl,\nextra_name_stack=\"scan\")\n+tf_impl_with_avals[ad_checkpoint.remat_p] = \\\n+ _convert_jax_impl(partial(lax_control_flow._remat_translation_rule,\n+ # TODO: jax2tf cannot discriminate by platform\n+ platform=\"tpu\"),\n+ multiple_results=True,\n+ extra_name_stack=\"checkpoint\")\ndef _top_k(operand: TfVal, k: int) -> Tuple[TfVal, TfVal]:\n# Some types originally incompatible with tf.math.top_k can be promoted\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "Specific JAX primitive conversion tests are in primitives_test.\"\"\"\n+import unittest\nfrom typing import Dict, Tuple\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\n+from jax import ad_checkpoint\nfrom jax import dtypes\nfrom jax import lax\nfrom jax import numpy as jnp\n@@ -635,25 +637,33 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.TransformConvertAndCompare(f, arg, \"grad\")\nself.TransformConvertAndCompare(f, arg, \"grad_vmap\")\n- def test_remat1(self):\n- @jax.remat\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"_{flavor}\", flavor=flavor)\n+ for flavor in [\"old\", \"new\"]))\n+ def test_remat(self, flavor=\"old\"):\ndef f(x1):\nx2 = jnp.sin(x1)\nx3 = jnp.sin(x2)\nx4 = jnp.sin(x3)\n- return jnp.sum(x4)\n+ return x4\n+ remat_f = jax.remat(f) if flavor == \"old\" else ad_checkpoint.checkpoint(f)\n# The computation of grad_f computes \"sin\" 5 times, 3 for the forward pass\n# and then to rematerialize \"x2\" and \"x3\" in the backward pass.\n- arg = np.arange(3.)\n- self.TransformConvertAndCompare(f, arg, \"grad\")\n- # TODO: check that the TF code also computes \"sin\" 5 times\n+ arg = np.array(3.)\n+ # Check that we have a Sin under a conditional\n+ f_tf = tf.function(jax2tf.convert(jax.grad(remat_f)), autograph=False)\n+ f_tf_graph = f_tf.get_concrete_function(arg).graph.as_graph_def()\n+ if flavor == \"old\":\n+ raise unittest.SkipTest(\"TODO: CSE widget not yet implemented for old-style remat\")\n+ self.assertRegex(str(f_tf_graph),\n+ r'remat_checkpoint_/switch_case/indexed_case/Sin')\ndef test_remat_free_var(self):\ndef f(x):\ny = 2 * x\n- @jax.remat\n+ @ad_checkpoint.checkpoint\ndef g():\nreturn y\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -752,90 +752,6 @@ def xla_fallback_lowering(prim: core.Primitive, ctx: LoweringContext,\nregister_lowering(ad.custom_lin_p, ad._raise_custom_vjp_error_on_jvp)\n-\n-def _dummy_like_aval(aval: core.AbstractValue) -> Sequence[ir.Value]:\n- if isinstance(aval, core.ShapedArray):\n- return [full_like_aval(0, aval)]\n- elif isinstance(aval, core.AbstractToken):\n- return mhlo.CreateTokenOp(aval_to_ir_type(aval)).results\n- elif isinstance(aval, core.AbstractUnit):\n- return ()\n- else:\n- raise TypeError(f\"Unsupported abstract value {aval}\")\n-\n-def _remat_using_while(ctx, avals_in, avals_out, *args, name, call_jaxpr):\n- input_types = map(aval_to_ir_types, avals_in)\n- output_types = map(aval_to_ir_types, avals_out)\n- flat_output_types = util.flatten(output_types)\n- int32_scalar_type = aval_to_ir_type(core.ShapedArray((), np.dtype(np.int32)))\n- loop_carry_types = [(int32_scalar_type,)] + input_types + output_types\n- flat_loop_carry_types = util.flatten(loop_carry_types)\n- counter_init = ir_constants(np.array(0, np.int32))\n- flat_args = flatten_lowering_ir_args(\n- (counter_init,) + args +\n- tuple(_dummy_like_aval(aval) for aval in avals_out))\n- loop_carry_tuple_type = ir.TupleType.get_tuple(flat_loop_carry_types)\n- init_carry = mhlo.TupleOp(loop_carry_tuple_type, flat_args)\n-\n- one = ir_constant(np.array(1, np.int32))\n- while_op = mhlo.WhileOp([loop_carry_tuple_type], [init_carry.result])\n-\n- # Loop condition\n- cond_block = while_op.regions[0].blocks.append(loop_carry_tuple_type)\n- with ir.InsertionPoint(cond_block):\n- bool_scalar_type = aval_to_ir_type(core.ShapedArray((), np.dtype(np.bool_)))\n- two = ir_constant(np.array(2, np.int32))\n- shape = ir_constant(np.array((), np.int64), canonicalize_types=False)\n- rng = mhlo.RngUniformOp(one, two, shape).result\n- i = mhlo.GetTupleElementOp(int32_scalar_type, cond_block.arguments[0],\n- i32_attr(0))\n- cmp = mhlo.CompareOp(bool_scalar_type, i, rng, ir.StringAttr.get(\"LT\"),\n- ir.StringAttr.get(\"SIGNED\")).result\n- mhlo.ReturnOp([cmp])\n-\n- body_block = while_op.regions[1].blocks.append(loop_carry_tuple_type)\n- with ir.InsertionPoint(body_block):\n- flat_body_args = [\n- mhlo.GetTupleElementOp(input_type, body_block.arguments[0],\n- i32_attr(i)).result\n- for i, input_type in enumerate(flat_loop_carry_types)]\n- body_args = util.unflatten(flat_body_args, map(len, loop_carry_types))\n- ((i,),), y, _ = util.split_list(body_args, [1, len(avals_in)])\n- body_ctx = ctx.replace(\n- name_stack=xla.extend_name_stack(ctx.name_stack,\n- xla.wrap_name(name, 'remat')))\n- z = jaxpr_subcomp(body_ctx, call_jaxpr, (), *y)\n- i_next = mhlo.AddOp(i, one).result\n- new_carry = mhlo.TupleOp(\n- loop_carry_tuple_type,\n- [i_next, *util.flatten(y), *util.flatten(z)])\n- mhlo.ReturnOp([new_carry.result])\n-\n- outputs = [mhlo.GetTupleElementOp(output_type, while_op.result,\n- i32_attr(1 + len(avals_in) + i)\n- ).result\n- for i, output_type in enumerate(flat_output_types)]\n- return util.unflatten(outputs, map(len, output_types))\n-\n-\n-def _remat_lowering(ctx, avals_in, avals_out, *args,\n- name, call_jaxpr,\n- prevent_cse, differentiated, concrete,\n- policy, device=None):\n- del device, concrete, policy # Unused.\n- if differentiated and prevent_cse:\n- if True: # ctx.platform == \"gpu\":\n- return _remat_using_while(ctx, avals_in, avals_out, *args, name=name,\n- call_jaxpr=call_jaxpr)\n- else:\n- assert False\n- #return _remat_using_cond(ctx, args, name, call_jaxpr)\n- else:\n- return jaxpr_subcomp(\n- ctx, call_jaxpr, (), *map(wrap_singleton_ir_values, args))\n-\n-register_lowering(pe.remat_call_p, _remat_lowering)\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": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -659,7 +659,7 @@ def tracers_to_jaxpr(\nreturn jaxpr, const_vals, env_vals\n@cache()\n-def convert_constvars_jaxpr(jaxpr: Jaxpr):\n+def convert_constvars_jaxpr(jaxpr: Jaxpr) -> Jaxpr:\n\"\"\"Moves the constvars to the start of invars.\"\"\"\nconfig.jax_enable_checks and core.check_jaxpr(jaxpr)\nlifted_jaxpr = Jaxpr(constvars=(),\n@@ -668,7 +668,7 @@ def convert_constvars_jaxpr(jaxpr: Jaxpr):\nconfig.jax_enable_checks and core.check_jaxpr(lifted_jaxpr)\nreturn lifted_jaxpr\n-def convert_envvars_to_constvars(jaxpr: Jaxpr, num_env_vars: int):\n+def convert_envvars_to_constvars(jaxpr: Jaxpr, num_env_vars: int) -> Jaxpr:\nconfig.jax_enable_checks and core.check_jaxpr(jaxpr)\nenv_vars, invars = split_list(jaxpr.invars, [num_env_vars])\nconverted_jaxpr = Jaxpr(constvars=jaxpr.constvars + env_vars,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1037,6 +1037,12 @@ def _array_aval_from_xla_shape(xla_shape):\nassert not xla_shape.is_tuple()\nreturn ShapedArray(xla_shape.dimensions(), xla_shape.numpy_dtype())\n+# Backwards compatibility flag. We keep this in for a bit longer to\n+# allow us to turn off the refactoring of the remat lowering if we\n+# run into test failures. A previous attempt at this was rolledback\n+# due to bugs.\n+# TODO(necula): remove this\n+_USE_LAX_REMAT_LOWERING = True\ndef _zeros(c, xla_shape):\nif xla_shape.is_array():\n@@ -1136,6 +1142,7 @@ def _remat_translation_rule(ctx, avals_in, avals_out, *in_nodes,\nelse:\nreturn jaxpr_subcomp(ctx, call_jaxpr, (), *in_nodes)\n+if not _USE_LAX_REMAT_LOWERING:\nregister_translation(pe.remat_call_p, _remat_translation_rule)\n"
}
] | Python | Apache License 2.0 | google/jax | Refactor the lowering of remat.
Replace the XLA-specific lowering with the same logic written
with LAX primitives. This will allow reusing the logic for
different lowerings, e.g., jax2tf or MLIR.
This is a new attempt at #8716, which was rolled-back in #8749
due to test failures. |
260,643 | 13.12.2021 15:27:10 | 0 | bd2724683ccf550bb8d31fc4a76554fabd00f6ee | fix: thread fill_value option | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -2875,8 +2875,8 @@ def nonzero(a, *, size=None, fill_value=None):\nreturn out\n@_wraps(np.flatnonzero, lax_description=_NONZERO_DOC)\n-def flatnonzero(a, *, size=None):\n- return nonzero(ravel(a), size=size)[0]\n+def flatnonzero(a, *, size=None, fill_value=None):\n+ return nonzero(ravel(a), size=size, fill_value=fill_value)[0]\ndef _nan_reduction(a, name, jnp_reduction, init_val, nan_if_all_nan,\n@@ -5212,8 +5212,8 @@ nonzero elements than `size` indicates, the index arrays will be zero-padded.\n\"\"\"\n@_wraps(np.argwhere, lax_description=_ARGWHERE_DOC)\n-def argwhere(a, *, size=None):\n- result = transpose(vstack(nonzero(a, size=size)))\n+def argwhere(a, *, size=None, fill_value=None):\n+ result = transpose(vstack(nonzero(a, size=size, fill_value=fill_value)))\nif ndim(a) == 0:\nreturn result[:0].reshape(result.shape[0], 0)\nreturn result.reshape(result.shape[0], ndim(a))\n"
}
] | Python | Apache License 2.0 | google/jax | fix: thread fill_value option |
260,573 | 13.12.2021 16:24:12 | 0 | c508e04ca51bc1734ed3ae9a1fba3bb55cfcba9b | test: add tests for argwhere, flatnonzero | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -998,6 +998,29 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\njnp_fun = lambda x: jnp.flatnonzero(x, size=np.size(x) // 2)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_size={}_fill_value={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), size, fill_value),\n+ \"shape\": shape, \"dtype\": dtype, \"size\": size, \"fill_value\": fill_value}\n+ for shape in nonempty_array_shapes\n+ for dtype in all_dtypes\n+ for fill_value in [None, -1, shape or (1,)]\n+ for size in [1, 5, 10]))\n+ def testFlatNonzeroSize(self, shape, dtype, size, fill_value):\n+ rng = jtu.rand_some_zero(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+ @jtu.ignore_warning(category=DeprecationWarning, message=\"Calling nonzero on 0d arrays.*\")\n+ def np_fun(x):\n+ result = np.flatnonzero(x)\n+ if size <= len(result):\n+ return result[:size]\n+ else:\n+ fill_val = fill_value or 0\n+ return np.concatenate([result, np.full(size - len(result), fill_val, result.dtype)])\n+ jnp_fun = lambda x: jnp.flatnonzero(x, size=size, fill_value=fill_value)\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)\n+ self._CompileAndCheck(jnp_fun, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}\".format(\njtu.format_shape_dtype_string(shape, dtype)),\n@@ -1017,6 +1040,30 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\njnp_fun = lambda x: jnp.argwhere(x, size=np.size(x) // 2)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_size={}_fill_value={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), size, fill_value),\n+ \"shape\": shape, \"dtype\": dtype, \"size\": size, \"fill_value\": fill_value}\n+ for shape in nonempty_array_shapes\n+ for dtype in all_dtypes\n+ for fill_value in [None, -1, shape or (1,)]\n+ for size in [1, 5, 10]))\n+ def testArgWhereSize(self, shape, dtype, size, fill_value):\n+ rng = jtu.rand_some_zero(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+ @jtu.ignore_warning(category=DeprecationWarning, message=\"Calling nonzero on 0d arrays.*\")\n+ def np_fun(x):\n+ result = np.argwhere(x)\n+ if size <= len(result):\n+ return result[:size]\n+ else:\n+ fillvals = fill_value if np.ndim(fill_value) else len(result) * [fill_value or 0]\n+ return np.stack(np.concatenate([arg, np.full(size - len(arg), fval, arg.dtype)])\n+ for fval, arg in safe_zip(fillvals, result.T)).T\n+ jnp_fun = lambda x: jnp.argwhere(x, size=size, fill_value=fill_value)\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)\n+ self._CompileAndCheck(jnp_fun, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"{}_inshape={}_axis={}\".format(\nrec.test_name.capitalize(),\n"
}
] | Python | Apache License 2.0 | google/jax | test: add tests for argwhere, flatnonzero |
260,335 | 13.12.2021 21:51:08 | 28,800 | 2eb788d3f63c1333e1d4085d66fe44349a6b0a1c | log tracing and compilation times | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "# Primitive dispatch and jit dispatch.\n+import contextlib\nfrom functools import partial\nimport itertools\n+import time\nfrom typing import (\nAny, Callable, Dict, Optional, Sequence, Set, Tuple, Type, Union)\nfrom typing_extensions import Protocol\n@@ -159,6 +161,18 @@ def _xla_callable_uncached(fun: lu.WrappedFun, device, backend, name,\n_xla_callable = lu.cache(_xla_callable_uncached)\n+@contextlib.contextmanager\n+def log_elapsed_time(fmt: str):\n+ if _on_exit:\n+ yield\n+ else:\n+ log_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG\n+ start_time = time.time()\n+ yield\n+ elapsed_time = time.time() - start_time\n+ logging.log(log_priority, fmt.format(elapsed_time=elapsed_time))\n+\n+\n@profiler.annotate_function\ndef lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\ndonated_invars, *arg_specs):\n@@ -167,6 +181,8 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\n\"got device={} and backend={}\".format(device, backend))\nabstract_args, arg_devices = util.unzip2(arg_specs)\n+ with log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n+ \"for jit in {elapsed_time} sec\"):\njaxpr, out_avals, consts = pe.trace_to_jaxpr_final(\nfun, abstract_args, pe.debug_info_final(fun, \"jit\"))\nif any(isinstance(c, core.Tracer) for c in consts):\n@@ -195,8 +211,11 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nif not _on_exit:\nlog_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG\n- logging.log(log_priority, \"Compiling %s (%s) for args %s.\",\n- fun.__name__, id(fun), abstract_args)\n+ if len(abstract_args) > 10:\n+ msg = f\"Compiling {fun.__name__} ({id(fun)}) for {len(abstract_args)} args.\"\n+ else:\n+ msg = f\"Compiling {fun.__name__} ({id(fun)} for args {abstract_args}.\"\n+ logging.log(log_priority, msg)\nif nreps > 1:\nwarnings.warn(\n@@ -584,6 +603,8 @@ class XlaCompiledComputation:\nnum_partitions=1,\ndevice_assignment=(sticky_device.id,) if sticky_device else None)\noptions.parameter_is_tupled_arguments = tuple_args\n+ with log_elapsed_time(f\"Finished XLA compilation of {name} \"\n+ \"in {elapsed_time} sec\"):\ncompiled = compile_or_get_cached(backend, xla_computation, options)\nbuffer_counts = (None if len(out_avals) == 1 else\n[aval_to_num_buffers(aval) for aval in out_avals])\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/maps.py",
"new_path": "jax/experimental/maps.py",
"diff": "@@ -707,6 +707,8 @@ def make_xmap_callable(fun: lu.WrappedFun,\nmapped_in_avals = [_delete_aval_axes(aval, in_axes, global_axis_sizes)\nfor aval, in_axes in zip(in_avals, in_axes)]\nwith core.extend_axis_env_nd(global_axis_sizes.items()):\n+ with dispatch.log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n+ \"for xmap in {elapsed_time} sec\"):\njaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, mapped_in_avals)\nout_axes = out_axes_thunk()\n_check_out_avals_vs_out_axes(out_avals, out_axes, global_axis_sizes)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/pjit.py",
"new_path": "jax/experimental/pjit.py",
"diff": "@@ -25,6 +25,7 @@ from jax.experimental.global_device_array import GlobalDeviceArray as GDA\nfrom jax import core\nfrom jax import linear_util as lu\nfrom jax._src.api import _check_callable, _check_arg, Lowered\n+from jax._src import dispatch\nfrom jax._src import source_info_util\nfrom jax._src.api_util import (argnums_partial_except, flatten_axes,\nflatten_fun_nokwargs, _ensure_index_tuple,\n@@ -324,6 +325,8 @@ def _pjit_jaxpr(fun, mesh, local_in_avals,\nprev_positional = maps._positional_semantics\ntry:\nmaps._positional_semantics = maps._PositionalSemantics.GLOBAL\n+ with dispatch.log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n+ \"for pjit in {elapsed_time} sec\"):\njaxpr, global_out_avals, consts = pe.trace_to_jaxpr_dynamic(fun, global_in_avals)\nfinally:\nmaps._positional_semantics = prev_positional\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -801,6 +801,7 @@ def parallel_callable(fun: lu.WrappedFun,\n@dataclasses.dataclass(frozen=True)\nclass ParallelCallableInfo:\n+ name: str\nbackend: xla.Backend\naxis_name: core.AxisName\naxis_size: int\n@@ -869,6 +870,8 @@ def stage_parallel_callable(\nglobal_sharded_avals = sharded_avals # type: ignore\nwith core.extend_axis_env(pci.axis_name, pci.global_axis_size, None): # type: ignore\n+ with dispatch.log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n+ \"for pmap in {elapsed_time} sec\"):\njaxpr, out_sharded_avals, consts = pe.trace_to_jaxpr_final(\nfun, global_sharded_avals, pe.debug_info_final(fun, \"pmap\"))\njaxpr = dispatch.apply_outfeed_rewriter(jaxpr)\n@@ -960,8 +963,8 @@ def lower_parallel_callable(\nmust_run_on_all_devices = True\npci = ParallelCallableInfo(\n- backend, axis_name, axis_size, global_axis_size, devices, in_axes,\n- out_axes_thunk, avals)\n+ name, backend, axis_name, axis_size, global_axis_size, devices,\n+ in_axes, out_axes_thunk, avals)\njaxpr, consts, replicas, parts, shards = stage_parallel_callable(\npci, fun, global_arg_shapes)\n@@ -1182,6 +1185,8 @@ class PmapExecutable:\n# TODO(frostig): need `compile_replicated` to give us the XLA executable\nreturn PmapExecutable(None, execute_fun, None, pci.avals)\n+ with dispatch.log_elapsed_time(\n+ f\"Finished XLA compilation of {pci.name} in {{elapsed_time}} sec\"):\ncompiled = dispatch.compile_or_get_cached(\npci.backend, xla_computation, compile_options)\nhandle_args = InputsHandler(\n@@ -1915,6 +1920,7 @@ def lower_mesh_computation(\nin_is_gda: Sequence[bool]):\nassert not mesh.empty\nbackend = xb.get_device_backend(mesh.devices.flat[0])\n+ name_stack = extend_name_stack(wrap_name(transformed_name, 'xmap'))\nglobal_axis_sizes = mesh.shape\n@@ -1939,6 +1945,8 @@ def lower_mesh_computation(\nassert tile_by_mesh_axes\nin_jaxpr_avals = in_tiled_avals\nwith core.extend_axis_env_nd(mesh.shape.items()):\n+ with dispatch.log_elapsed_time(f\"Finished tracing + transforming {name_stack} \"\n+ \"in {elapsed_time} sec\"):\njaxpr, out_jaxpr_avals, consts = pe.trace_to_jaxpr_final(fun, in_jaxpr_avals)\nif callable(out_axes):\nout_axes = out_axes()\n@@ -1978,7 +1986,6 @@ def lower_mesh_computation(\nnames=tuple(global_axis_sizes.keys()),\nsizes=tuple(global_axis_sizes.values()))\nclosed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\n- name_stack = extend_name_stack(wrap_name(transformed_name, 'xmap'))\nmodule: Union[str, xc.XlaComputation]\nmodule_name = f\"xmap_{fun.__name__}\"\nwith core.extend_axis_env_nd(mesh.shape.items()):\n@@ -1995,7 +2002,7 @@ def lower_mesh_computation(\npartitions_are_protos=partitions_proto)\nreturn MeshComputation(\n- module, donated_invars, mesh=mesh, global_in_avals=global_in_avals,\n+ name_stack, module, donated_invars, mesh=mesh, global_in_avals=global_in_avals,\nglobal_out_avals=global_out_avals, in_axes=in_axes, out_axes=out_axes,\nspmd_lowering=spmd_lowering, tuple_args=tuple_args, in_is_gda=in_is_gda)\n@@ -2003,8 +2010,9 @@ def lower_mesh_computation(\nclass MeshComputation:\n_executable: Optional['MeshExecutable']\n- def __init__(self, hlo: Union[str, xc.XlaComputation],\n+ def __init__(self, name: str, hlo: Union[str, xc.XlaComputation],\ndonated_invars: Sequence[bool], **compile_args):\n+ self._name = name\nself._hlo = hlo\nself._donated_invars = donated_invars\nself.compile_args = compile_args\n@@ -2028,7 +2036,7 @@ class MeshComputation:\n_allow_compile_replicated : bool = True) -> 'MeshExecutable':\nif self._executable is None:\nself._executable = MeshExecutable.from_hlo(\n- self._hlo, **self.compile_args,\n+ self._name, self._hlo, **self.compile_args,\n_allow_propagation_to_outputs=_allow_propagation_to_outputs,\n_allow_compile_replicated=_allow_compile_replicated) # type: ignore\nreturn self._executable\n@@ -2064,7 +2072,8 @@ class MeshExecutable:\nself._input_avals = input_avals\n@staticmethod\n- def from_hlo(computation: Union[str, xc.XlaComputation],\n+ def from_hlo(name: str,\n+ computation: Union[str, xc.XlaComputation],\nmesh: Mesh,\nglobal_in_avals: Sequence[ShapedArray],\nglobal_out_avals: Sequence[ShapedArray],\n@@ -2105,6 +2114,8 @@ class MeshExecutable:\nhandle_outs)\nxla_executable = None\nelse:\n+ with dispatch.log_elapsed_time(f\"Finished XLA compilation of {name} \"\n+ \"in {elapsed_time} sec\"):\ncompiled = dispatch.compile_or_get_cached(backend, computation, compile_options)\nhandle_args = InputsHandler(compiled.local_devices(), input_specs, input_indices)\nunsafe_call = partial(execute_replicated, compiled, backend, handle_args, handle_outs)\n"
}
] | Python | Apache License 2.0 | google/jax | log tracing and compilation times |
260,573 | 14.12.2021 09:29:07 | 0 | 9280a392fa28eee8e16552ddaff58bac980a2a76 | test: use appropriate args in flatnonzero | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1004,7 +1004,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n\"shape\": shape, \"dtype\": dtype, \"size\": size, \"fill_value\": fill_value}\nfor shape in nonempty_array_shapes\nfor dtype in all_dtypes\n- for fill_value in [None, -1, shape or (1,)]\n+ for fill_value in [None, -1, 10, (-1,), (10,)]\nfor size in [1, 5, 10]))\ndef testFlatNonzeroSize(self, shape, dtype, size, fill_value):\nrng = jtu.rand_some_zero(self.rng())\n"
}
] | Python | Apache License 2.0 | google/jax | test: use appropriate args in flatnonzero |
260,573 | 14.12.2021 09:38:57 | 0 | 83d9a5fe31076844b4c53b46bc43a93c0181d9c3 | tests: pass list to np.stack, not generator | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1058,8 +1058,8 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nreturn result[:size]\nelse:\nfillvals = fill_value if np.ndim(fill_value) else len(result) * [fill_value or 0]\n- return np.stack(np.concatenate([arg, np.full(size - len(arg), fval, arg.dtype)])\n- for fval, arg in safe_zip(fillvals, result.T)).T\n+ return np.stack([np.concatenate([arg, np.full(size - len(arg), fval, arg.dtype)])\n+ for fval, arg in safe_zip(fillvals, result.T)]).T\njnp_fun = lambda x: jnp.argwhere(x, size=size, fill_value=fill_value)\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)\nself._CompileAndCheck(jnp_fun, args_maker)\n"
}
] | Python | Apache License 2.0 | google/jax | tests: pass list to np.stack, not generator |
260,573 | 14.12.2021 10:01:32 | 0 | 7980379dffdb548033d3370b9260544021e57175 | tests: fix shape inference dimension | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1057,7 +1057,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nif size <= len(result):\nreturn result[:size]\nelse:\n- fillvals = fill_value if np.ndim(fill_value) else len(result) * [fill_value or 0]\n+ fillvals = fill_value if np.ndim(fill_value) else result.shape[-1] * [fill_value or 0]\nreturn np.stack([np.concatenate([arg, np.full(size - len(arg), fval, arg.dtype)])\nfor fval, arg in safe_zip(fillvals, result.T)]).T\njnp_fun = lambda x: jnp.argwhere(x, size=size, fill_value=fill_value)\n"
}
] | Python | Apache License 2.0 | google/jax | tests: fix shape inference dimension |
260,573 | 14.12.2021 10:01:54 | 0 | cba9852b91e4d7dd4edea35510fced76a428d334 | tests: cover 0 dim case | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1058,7 +1058,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nreturn result[:size]\nelse:\nfillvals = fill_value if np.ndim(fill_value) else result.shape[-1] * [fill_value or 0]\n- return np.stack([np.concatenate([arg, np.full(size - len(arg), fval, arg.dtype)])\n+ return np.empty((size,0), dtype=int) if np.ndim(x)==0 else np.stack([np.concatenate([arg, np.full(size - len(arg), fval, arg.dtype)])\nfor fval, arg in safe_zip(fillvals, result.T)]).T\njnp_fun = lambda x: jnp.argwhere(x, size=size, fill_value=fill_value)\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)\n"
}
] | Python | Apache License 2.0 | google/jax | tests: cover 0 dim case |
260,540 | 14.12.2021 07:16:10 | 28,800 | b28a1c5240fbf7e433f308d4919d511b320df504 | Tweak documentation on error handling for host_callback.call() | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -393,7 +393,10 @@ in one of the tap functions. This exception will include the text and the\nstack trace of the last exception encountered.\nOne further complication arises for callback functions that must return\n-results to the call origin device. In order to avoid the device computation\n+results to the call origin device, such as :func:`call()`. This is handled\n+differently on CPU/GPU devices compared to TPU devices.\n+\n+On CPU/GPU devices, in order to avoid the device computation\nbeing stuck waiting for a result that will never arrive, in case of any\nerror during the processing of the callback (whether raised by the user-code\nitself or due to a mismatch of the returned value and the expected return_shape)\n@@ -415,8 +418,10 @@ RET_CHECK failure ... Mismatch between infeed source buffer shape s8[12345] ...\nTo debug the underlying cause for these messages, see the Debugging section.\n-On TPU, there is currently no shape check for infeed, so we take the safer\n-route to not send anything in case of errors, and let the computation hang.\n+On TPU devices, there is currently no shape check for infeed, so we take the\n+safer route of not sending this fake result in case of errors. This means\n+that the computation will hang, and no exception will be raised (but any\n+exceptions in the callback functions will still appear in the logs).\nThe current implementation uses the outfeed mechanism provided by XLA. The\nmechanism itself is quite primitive in the sense that a receiver must know\n"
}
] | Python | Apache License 2.0 | google/jax | Tweak documentation on error handling for host_callback.call() |
260,335 | 14.12.2021 10:42:05 | 28,800 | c555f5f0e44224c65b356b63a9d68983ec14e5fa | handle trivial case for ppermute batching rule
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/parallel.py",
"new_path": "jax/_src/lax/parallel.py",
"diff": "@@ -793,7 +793,8 @@ def _ppermute_batcher(axis_size, frame_name, _, vals_in, dims_in, axis_name, per\nraise NotImplementedError(\"ppermute batcher only supports a single axis\")\nassert axis_name[0] == frame_name, \"ppermute batcher called with a wrong axis!\"\nassert len(perm) == axis_size, \"Permutation doesn't match the axis size!\"\n- assert d is not batching.not_mapped\n+ if d is batching.not_mapped:\n+ return v, d\nperm_indices = np.zeros(axis_size, dtype=int)\nfor src, dst in perm:\nperm_indices[dst] = src\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -1267,6 +1267,19 @@ class BatchingTest(jtu.JaxTestCase):\nself.assertEqual(f(jnp.ones(3)).shape, (3,))\nself.assertEqual(jax.vmap(f)(jnp.ones((2, 3))).shape, (2, 3))\n+ def testPpermuteBatcherTrivial(self):\n+ # https://github.com/google/jax/issues/8688\n+ def ppermute(input):\n+ return jax.lax.ppermute(input, axis_name=\"i\", perm=[[0, 1], [1, 0]])\n+\n+ grad_fn = jax.grad(ppermute)\n+\n+ vmapped_gradients_fn = jax.vmap(grad_fn, axis_name=\"i\")\n+\n+ vector = jax.numpy.array([1., 2.])\n+ ans = vmapped_gradients_fn(vector) # doesn't crash\n+ self.assertAllClose(ans, jnp.ones(2), check_dtypes=False)\n+\nArray = Any\nArrayElt = Any\n"
}
] | Python | Apache License 2.0 | google/jax | handle trivial case for ppermute batching rule
fixes #8688 |
260,335 | 14.12.2021 11:02:14 | 28,800 | c8a34fe5cc8de51bbf6aacd30b38453248440f9e | add jax.block_until_ready function
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/__init__.py",
"new_path": "jax/__init__.py",
"diff": "@@ -52,6 +52,7 @@ from jax._src.config import (\n)\nfrom jax._src.api import (\nad, # TODO(phawkins): update users to avoid this.\n+ block_until_ready,\ncheckpoint as checkpoint,\ncheckpoint_policies as checkpoint_policies,\nclosure_convert as closure_convert,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -3138,3 +3138,22 @@ def invertible(fun: Callable) -> Callable:\nfun: The function assumed to be invertible.\n\"\"\"\nreturn iad.invertible(fun)\n+\n+\n+def block_until_ready(x):\n+ \"\"\"\n+ Tries to call a ``block_until_ready`` method on pytree leaves.\n+\n+ Args:\n+ x: a pytree, usually with at least some JAX array instances at its leaves.\n+\n+ Returns:\n+ A pytree with the same structure and values of the input, where the values\n+ of all JAX array leaves are ready.\n+ \"\"\"\n+ def try_to_block(x):\n+ try:\n+ return x.block_until_ready()\n+ except AttributeError:\n+ return x\n+ return jax.tree_util.tree_map(try_to_block, x)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1517,6 +1517,13 @@ class APITest(jtu.JaxTestCase):\n# Tests mostly that block_until_ready() does not produce an error.\nself.assertTrue(y is x)\n+ def test_block_until_ready_function(self):\n+ # Just tests that we don't error...\n+ pytree = (device_put(1.), np.ones(3))\n+ pytree = jax.block_until_ready(pytree)\n+ self.assertAllClose(pytree[0], jnp.array(1.), check_dtypes=False)\n+ self.assertAllClose(pytree[1], np.ones(3), check_dtypes=False)\n+\ndef test_devicearray_weakref_friendly(self):\nx = device_put(1.)\ny = weakref.ref(x)\n"
}
] | Python | Apache License 2.0 | google/jax | add jax.block_until_ready function
fixes #8536 |
260,335 | 14.12.2021 12:57:52 | 28,800 | d8e28400ba80d4d636bde449ac4ae296a5de5cae | fix leak checker interaction with custom_jvp
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1408,8 +1408,9 @@ class DynamicJaxprTrace(core.Trace):\nwith core.new_sublevel():\nfun_jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, self.main, in_avals)\nclosed_fun_jaxpr = core.ClosedJaxpr(convert_constvars_jaxpr(fun_jaxpr), ())\n+ main_ = ref(self.main)\njvp_jaxpr_thunk = _memoize(\n- lambda: trace_to_subjaxpr_dynamic(jvp, self.main, 2 * in_avals)[::2])\n+ lambda: trace_to_subjaxpr_dynamic(jvp, main_(), 2 * in_avals)[::2])\nout_tracers = [DynamicJaxprTracer(self, a) for a in out_avals]\ninvars = map(self.getvar, tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\n@@ -1430,8 +1431,9 @@ class DynamicJaxprTrace(core.Trace):\nwith core.new_sublevel():\nfun_jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, self.main, in_avals)\nclosed_fun_jaxpr = core.ClosedJaxpr(convert_constvars_jaxpr(fun_jaxpr), ())\n+ main_ = ref(self.main)\nfwd_jaxpr_thunk = _memoize(\n- lambda: trace_to_subjaxpr_dynamic(fwd, self.main, in_avals)[::2])\n+ lambda: trace_to_subjaxpr_dynamic(fwd, main_(), in_avals)[::2])\nout_tracers = [DynamicJaxprTracer(self, a) for a in out_avals]\ninvars = map(self.getvar, tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\n@@ -1449,6 +1451,9 @@ class DynamicJaxprTrace(core.Trace):\nassert False # unreachable\ndef _memoize(thunk):\n+ if config.jax_check_tracer_leaks:\n+ return thunk\n+\ncell = []\nsaved_state = core.thread_local_state.trace_state.copy()\ndef memoized():\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/nn_test.py",
"new_path": "tests/nn_test.py",
"diff": "@@ -176,6 +176,22 @@ class NNFunctionsTest(jtu.JaxTestCase):\ndef testTanhExists(self):\nnn.tanh # doesn't crash\n+ def testCustomJVPLeak(self):\n+ # https://github.com/google/jax/issues/8171\n+ @jax.jit\n+ def fwd():\n+ a = jnp.array(1.)\n+\n+ def f(hx, _):\n+ hx = jax.nn.sigmoid(hx + a)\n+ return hx, None\n+\n+ hx = jnp.array(0.)\n+ jax.lax.scan(f, hx, None, length=2)\n+\n+ with jax.checking_leaks():\n+ fwd() # doesn't crash\n+\nInitializerRecord = collections.namedtuple(\n\"InitializerRecord\",\n[\"name\", \"initializer\", \"shapes\", \"dtypes\"])\n"
}
] | Python | Apache License 2.0 | google/jax | fix leak checker interaction with custom_jvp
fixes #8171 |
260,335 | 14.12.2021 13:36:46 | 28,800 | 0c68605bf1af90662472966657d7a489ff3329a2 | add jax.block_until_ready to docs and changelog
also unrelatedly fix a couple of the uses of rst in changelog.md (though
many others remain) | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -21,6 +21,9 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\nAdditionally, added documentation for how to implement the old behavior\nusing JAX custom AD APIs ({jax-issue}`#7839`).\n+* New features:\n+ * add `jax.block_until_ready` ({jax-issue}`#8941)\n+\n## jaxlib 0.1.76 (Unreleased)\n## jaxlib 0.1.75 (Dec 8, 2021)\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax.rst",
"new_path": "docs/jax.rst",
"diff": "@@ -101,6 +101,7 @@ Parallelization (:code:`pmap`)\n.. autofunction:: device_put_replicated\n.. autofunction:: device_put_sharded\n.. autofunction:: device_get\n+.. autofunction:: block_until_ready\n.. autofunction:: default_backend\n.. autofunction:: named_call\n"
}
] | Python | Apache License 2.0 | google/jax | add jax.block_until_ready to docs and changelog
also unrelatedly fix a couple of the uses of rst in changelog.md (though
many others remain) |
260,335 | 14.12.2021 14:40:13 | 28,800 | 984e8d79f0dc45de8d92cbd4a44bf9169ef50ee3 | make ravel_pytree unraveler dtype-polymorphic
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/flatten_util.py",
"new_path": "jax/_src/flatten_util.py",
"diff": "@@ -57,8 +57,24 @@ def _ravel_list(lst):\nsizes, shapes = unzip2((jnp.size(x), jnp.shape(x)) for x in lst)\nindices = np.cumsum(sizes)\n+ if all(dt == to_dtype for dt in from_dtypes):\n+ # Skip any dtype conversion, resulting in a dtype-polymorphic `unravel`.\n+ # See https://github.com/google/jax/issues/7809.\n+ del from_dtypes, to_dtype\ndef unravel(arr):\nchunks = jnp.split(arr, indices[:-1])\n+ return [chunk.reshape(shape) for chunk, shape in zip(chunks, shapes)]\n+ raveled = jnp.concatenate([jnp.ravel(e) for e in lst])\n+ return raveled, unravel\n+\n+ # When there is more than one distinct input dtype, we perform type\n+ # conversions and produce a dtype-specific unravel function.\n+ def unravel(arr):\n+ arr_dtype = dtypes.dtype(arr)\n+ if arr_dtype != to_dtype:\n+ raise TypeError(f\"unravel function given array of dtype {arr_dtype}, \"\n+ f\"but expected dtype {to_dtype}\")\n+ chunks = jnp.split(arr, indices[:-1])\nwith warnings.catch_warnings():\nwarnings.simplefilter(\"ignore\") # ignore complex-to-real cast warning\nreturn [lax.convert_element_type(chunk.reshape(shape), dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/tree_util_test.py",
"new_path": "tests/tree_util_test.py",
"diff": "@@ -379,6 +379,23 @@ class RavelUtilTest(jtu.JaxTestCase):\ntree_ = unravel(raveled)\nself.assertAllClose(tree, tree_, atol=0., rtol=0.)\n+ def testDtypePolymorphicUnravel(self):\n+ # https://github.com/google/jax/issues/7809\n+ x = jnp.arange(10, dtype=jnp.float32)\n+ x_flat, unravel = flatten_util.ravel_pytree(x)\n+ y = x_flat < 5.3\n+ x_ = unravel(y)\n+ self.assertEqual(x_.dtype, y.dtype)\n+\n+ def testDtypeMonomorphicUnravel(self):\n+ # https://github.com/google/jax/issues/7809\n+ x1 = jnp.arange(10, dtype=jnp.float32)\n+ x2 = jnp.arange(10, dtype=jnp.int32)\n+ x_flat, unravel = flatten_util.ravel_pytree((x1, x2))\n+ y = x_flat < 5.3\n+ with self.assertRaisesRegex(TypeError, 'but expected dtype'):\n+ _ = unravel(y)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | make ravel_pytree unraveler dtype-polymorphic
fixes #7809 |
260,411 | 24.11.2021 12:58:16 | -7,200 | 3021d3e2e2e3d8d97e9cba620bf233e807ff20b6 | [hcb] Add support for remat2 to host_callback
A callback under ad_checkpoint.checkpoint will be invoked
twice when taking the gradient: once during the forward pass
and once again during the backward pass when the residuals
for the forward pass are rematerialized. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -19,7 +19,10 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\nobtained (for a limited time) by setting the ``JAX_HOST_CALLBACK_AD_TRANSFORMS``\nenvironment variable, or the ```--flax_host_callback_ad_transforms``` flag.\nAdditionally, added documentation for how to implement the old behavior\n- using JAX custom AD APIs ({jax-issue}`#7839`).\n+ using JAX custom AD APIs ({jax-issue}`#8678`).\n+\n+* Bug fixes:\n+ * host_callback now supports ad_checkpoint.checkpoint ({jax-issue}`#8907`).\n* New features:\n* add `jax.block_until_ready` ({jax-issue}`#8941)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -321,32 +321,6 @@ def apply_outfeed_rewriter(jaxpr: core.Jaxpr) -> core.Jaxpr:\nelse:\nreturn jaxpr\n-outfeed_primitives: Set[core.Primitive] = set()\n-def jaxpr_uses_outfeed(jaxpr: core.Jaxpr) -> bool:\n- \"\"\"Finds if there are outfeed primitives anywhere inside a Jaxpr.\"\"\"\n- return any(primitive_uses_outfeed(eqn.primitive, eqn.params)\n- for eqn in jaxpr.eqns)\n-\n-def _param_uses_outfeed(param):\n- if type(param) is core.Jaxpr:\n- if jaxpr_uses_outfeed(param):\n- return True\n- elif type(param) is core.ClosedJaxpr:\n- if jaxpr_uses_outfeed(param.jaxpr):\n- return True\n- return False\n-\n-def primitive_uses_outfeed(prim: core.Primitive, params: Dict) -> bool:\n- if prim in outfeed_primitives:\n- return True\n- for param in params.values():\n- if isinstance(param, tuple):\n- if any(unsafe_map(_param_uses_outfeed, param)):\n- return True\n- elif _param_uses_outfeed(param):\n- return True\n- return False\n-\ndef jaxpr_replicas(jaxpr) -> int:\n\"\"\"The number of replicas needed for a jaxpr.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1678,6 +1678,32 @@ call_p.def_impl(call_impl)\nnamed_call_p: CallPrimitive = CallPrimitive('named_call')\nnamed_call_p.def_impl(call_impl)\n+outfeed_primitives: Set[Primitive] = set()\n+def jaxpr_uses_outfeed(jaxpr: Jaxpr) -> bool:\n+ \"\"\"Finds if there are outfeed primitives anywhere inside a Jaxpr.\"\"\"\n+ return any(primitive_uses_outfeed(eqn.primitive, eqn.params)\n+ for eqn in jaxpr.eqns)\n+\n+def _param_uses_outfeed(param):\n+ if type(param) is Jaxpr:\n+ if jaxpr_uses_outfeed(param):\n+ return True\n+ elif type(param) is ClosedJaxpr:\n+ if jaxpr_uses_outfeed(param.jaxpr):\n+ return True\n+ return False\n+\n+def primitive_uses_outfeed(prim: Primitive, params: Dict) -> bool:\n+ if prim in outfeed_primitives:\n+ return True\n+ for param in params.values():\n+ if isinstance(param, tuple):\n+ if any(unsafe_map(_param_uses_outfeed, param)):\n+ return True\n+ elif _param_uses_outfeed(param):\n+ return True\n+ return False\n+\n# ------------------- Map -------------------\ndef mapped_aval(size: int, axis: int, aval: AbstractValue) -> AbstractValue:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -313,6 +313,20 @@ its argument::\n# what: x,x^2 : (3., 9.)\n# what: cotangents : (9., 3.)\n+If you use :func:`ad_checkpoint.checkpoint` to rematerialize the residuals\n+for the backward pass, then the callbacks from the primal computation will\n+be called twice::\n+\n+ jax.grad(lambda x: power3(ad_checkpoint.checkpoint(power3)(x)))(3.)\n+ # what: x,x^2 : (3., 9.)\n+ # what: x,x^2 : (27., 729.)\n+ # what: x,x^2 : (3., 9.)\n+\n+The callbacks are, in order from: the primal computation of the inner ``power3``,\n+the primal computation of the outer ``power3``, and the rematerialization\n+of the residuals for the inner ``power3``.\n+\n+\nBehavior under jax.vmap\n-----------------------\n@@ -900,7 +914,7 @@ It takes the following parameters:\n\"\"\"\noutside_call_p = core.Primitive(\"outside_call\")\noutside_call_p.multiple_results = True\n-dispatch.outfeed_primitives.add(outside_call_p)\n+core.outfeed_primitives.add(outside_call_p)\ndef _outside_call_abstract_eval(*args_a: pe.AbstractValue,\n@@ -1385,7 +1399,7 @@ def _rewrite_jaxpr(jaxpr: core.Jaxpr, has_input_token: bool,\n\"\"\"Rewrite a Jaxpr to thread the token, if needed.\"\"\"\nassert has_input_token or not has_output_token\n- if not has_input_token and not dispatch.jaxpr_uses_outfeed(jaxpr):\n+ if not has_input_token and not core.jaxpr_uses_outfeed(jaxpr):\nreturn jaxpr\nmk_new_var = core.gensym([jaxpr])\n@@ -1407,7 +1421,7 @@ def _rewrite_jaxpr(jaxpr: core.Jaxpr, has_input_token: bool,\nlax.create_token_p, {}, source_info_util.current()))\nfor eqn in jaxpr.eqns:\n- if not dispatch.primitive_uses_outfeed(eqn.primitive, eqn.params):\n+ if not core.primitive_uses_outfeed(eqn.primitive, eqn.params):\neqns.append(eqn)\nelse:\noutput_token_var = mk_new_var(last_token_var.aval)\n@@ -1445,7 +1459,7 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\ncond_jaxpr, _, body_jaxpr, _ = util.split_dict(\neqn.params,\n[\"cond_jaxpr\", \"cond_nconsts\", \"body_jaxpr\", \"body_nconsts\"])\n- if dispatch.jaxpr_uses_outfeed(cond_jaxpr.jaxpr):\n+ if core.jaxpr_uses_outfeed(cond_jaxpr.jaxpr):\n_rewrite_while_outfeed_cond(eqn, eqns, input_token_var, output_token_var,\ninput_itoken_var, output_itoken_var,\nmk_new_var)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1029,7 +1029,7 @@ def dce_jaxpr(jaxpr: Jaxpr, used_outputs: List[bool]\nused_outs = map(read, eqn.outvars)\n# If any outputs are used, then we need to keep a version of the eqn and\n# potentially mark some inputs as used. Otherwise mark all inputs as unused.\n- if any(used_outs):\n+ if any(used_outs) or core.primitive_uses_outfeed(eqn.primitive, eqn.params):\n# If there's a rule for modifying the eqn and computing used inputs, apply\n# it. Otherwise, keep the eqn unmodified and mark all inputs as used.\nrule = dce_rules.get(eqn.primitive)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -27,6 +27,7 @@ from absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\n+from jax import ad_checkpoint\nfrom jax import core\nfrom jax.config import config\nfrom jax import dtypes\n@@ -1458,6 +1459,19 @@ class HostCallbackTapTest(jtu.JaxTestCase):\ntransforms: [('batch', {'batch_dims': (0, 0)})] what: cotangents\n( [4. 9.] [2. 3.] )\"\"\"\nself.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+ testing_stream.reset()\n+\n+ print(f\"grad o remat = {jax.grad(lambda x: power3(ad_checkpoint.checkpoint(power3)(x)))(3.)}\")\n+ hcb.barrier_wait()\n+ expected = \"\"\"\n+ what: x,x^2\n+ ( 3. 9. )\n+ what: x,x^2\n+ ( 27. 729. )\n+ what: x,x^2\n+ ( 3. 9. )\"\"\"\n+ self.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+ testing_stream.reset()\ndef test_tap_pmap(self):\nif len(local_devices()) < 2:\n@@ -2024,8 +2038,8 @@ class HostCallbackTapTest(jtu.JaxTestCase):\nuse_result=use_result, use_remat=use_remat, grad_func=grad_func)\nfor use_result in [True, False]\nfor grad_func in [\"grad\", \"value_and_grad\"]\n- for use_remat in [\"old\", \"none\"]))\n- def test_tap_remat(self, use_result=False, grad_func=\"grad\", use_remat=\"old\"):\n+ for use_remat in [\"old\", \"new\", \"none\"]))\n+ def test_tap_remat(self, use_result=False, grad_func=\"grad\", use_remat=\"new\"):\ndef f(x):\nid_print_result = hcb.id_print(x, output_stream=testing_stream)\nif use_result:\n@@ -2034,6 +2048,8 @@ class HostCallbackTapTest(jtu.JaxTestCase):\ngrad_f = jax.grad if grad_func == \"grad\" else jax.value_and_grad\nif use_remat == \"old\":\ntrans_f = jax.remat(f)\n+ elif use_remat == \"new\":\n+ trans_f = ad_checkpoint.checkpoint(f)\nelse:\nassert use_remat == \"none\"\ntrans_f = f\n@@ -2068,8 +2084,14 @@ class HostCallbackTapTest(jtu.JaxTestCase):\n2.\n2.\"\"\"\nelse:\n+ if use_remat == \"old\":\n# TODO: we should see two callbacks\nexpected = \"\"\n+ else:\n+ # Good: we see two callbacks, whether or not we use the result.\n+ expected = \"\"\"\n+ 2.\n+ 2.\"\"\"\nself.assertMultiLineStrippedEqual(expected, testing_stream.output)\ndef test_tap_named_call(self):\n"
}
] | Python | Apache License 2.0 | google/jax | [hcb] Add support for remat2 to host_callback
A callback under ad_checkpoint.checkpoint will be invoked
twice when taking the gradient: once during the forward pass
and once again during the backward pass when the residuals
for the forward pass are rematerialized. |
260,411 | 16.12.2021 11:30:53 | -7,200 | 06ce9b9b1ac25d2fc51e0bee2645ad6027a74e8a | [jax2tf] Simplify the shape_poly support.
The goal is to make is shareable outside of jax2tf. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -50,7 +50,6 @@ from jax.interpreters import xla\nfrom jax._src.lib import xla_client\nfrom jax.experimental.jax2tf import shape_poly\n-from jax.experimental.jax2tf import shape_poly_tf\nfrom jax.experimental.jax2tf import impl_no_xla\nimport numpy as np\n@@ -161,7 +160,7 @@ class _ThreadLocalState(threading.local):\nself.inside_call_tf = False\n# Maps dimension variables to TF expressions\n- self.shape_env: shape_poly.ShapeEnv = {}\n+ self.shape_env: Sequence[Tuple[str, TfVal]] = ()\n# Whether to actually include XLA op metadata in the generated TF ops\nself.include_xla_op_metadata = True\n@@ -320,14 +319,17 @@ def convert(fun: Callable,\nreturn tuple(d.value if isinstance(d, tf.compat.v1.Dimension) else d for d in tf_arg_shape)\nargs_shapes_flat = tuple(fix_tf1_shape(a) for a in args_flat)\n- args_dim_exprs_flat = tuple(shape_poly_tf.DimExprTfVal.for_arg(a) for a in args_flat)\n# Construct the abstract values for the flat arguments, possibly based on\n# the input shapes and the polymorphic_shapes if given. May create new shape\n# variables. May cast the args_flat to JAX types, using JAX's interpretation\n# of types of constants.\n- args_avals_flat, shapeenv = shape_poly.args_avals_and_env(\n- args_shapes_flat, arg_dtypes_flat, polymorphic_shapes_flat,\n- args_dim_exprs_flat)\n+ args_avals_flat = shape_poly.args_avals(\n+ args_shapes_flat, arg_dtypes_flat, polymorphic_shapes_flat)\n+\n+ dim_vars, get_dim_values = shape_poly.prepare_dim_var_env(args_avals_flat)\n+ dim_values, _ = util.unzip2(_interpret_fun(lu.wrap_init(get_dim_values),\n+ args_flat, args_avals_flat, \"\"))\n+ shape_env = zip(dim_vars, dim_values)\n# This function may take pytrees of TfVals. We can only set\n# tf.custom_gradient on functions that take a flat argument list.\n@@ -415,7 +417,7 @@ def convert(fun: Callable,\nprev_include_xla_op_metadata = _thread_local_state.include_xla_op_metadata\n_thread_local_state.include_xla_op_metadata = False\n- _thread_local_state.shape_env = shapeenv\n+ _thread_local_state.shape_env = shape_env\nglobal _has_registered_tf_source_path\nif not _has_registered_tf_source_path:\nsource_info_util.register_exclusion(os.path.dirname(tf.__file__))\n@@ -445,7 +447,7 @@ def convert(fun: Callable,\nfor o in outs\n]\nfinally:\n- _thread_local_state.shape_env = {}\n+ _thread_local_state.shape_env = ()\n_thread_local_state.enable_xla = prev_enable_xla\n_thread_local_state.include_xla_op_metadata = prev_include_xla_op_metadata\n@@ -669,7 +671,11 @@ def _tfval_to_tensor_jax_dtype(val: TfVal,\ndef _eval_shape(shape: Sequence[shape_poly.DimSize]) -> Sequence[TfVal]:\nassert all(map(lambda x: x is not None, shape)), (\nf\"Argument shape should be a valid JAX shape but got {shape}\")\n- return shape_poly.eval_shape(shape, _thread_local_state.shape_env)\n+ dim_vars, dim_values = util.unzip2(_thread_local_state.shape_env)\n+ eval_shape, dim_avals = shape_poly.get_shape_evaluator(dim_vars, shape)\n+ shape_values, _ = util.unzip2(_interpret_fun(lu.wrap_init(eval_shape),\n+ dim_values, dim_avals, \"\")) # type: ignore\n+ return shape_values\n# TODO(b/26854495): pylint doesn't understand slots and inheritance.\n@@ -723,7 +729,7 @@ class TensorFlowTracer(core.Tracer):\n# We have a TF value with known shape, and the abstract shape is a shape variable.\ntry:\naval_int = int(_eval_shape([aval_dim])) # type: ignore\n- except TypeError:\n+ except (TypeError, KeyError):\ncontinue\nassert aval_int == val_dim, f\"expected {self._aval.shape} == {val_shape}. Found {aval_int} != {val_dim}.\" # type: ignore\n@@ -2638,6 +2644,11 @@ def _pjit_sharding_constraint(arg: TfVal, *,\ntf_impl_with_avals[pjit.sharding_constraint_p] = _pjit_sharding_constraint\n+def _dimension_size_jax2tf(op: TfVal, *, dimension):\n+ return tf.shape(op)[dimension]\n+\n+tf_impl[shape_poly.dimension_size_p] = _dimension_size_jax2tf\n+\ndef _dim_as_value_jax2tf(dim: shape_poly.DimSize):\ndim_tf, = _eval_shape((dim,))\nreturn dim_tf\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "# limitations under the License.\n\"\"\"Shape polymorphism support.\n-This was built initially for jax2tf, but it is now customizeable to be\n-independent of TF. The idea is that we introduce a set of dimension variables\n-at the top-level of a `jit` function. They are introduced implicitly by way\n-of specifying for each dimension of each argument a dimension polynomial\n-in terms of some dimension variables. All dimension variables are assumed to\n-range over integers greater or equal to 1.\n+We introduce a set of dimension variables at the top-level of a `jit` function.\n+They are introduced implicitly by way of specifying for each dimension of each\n+argument a dimension polynomial in terms of some dimension variables.\n+All dimension variables are assumed to range over integers greater or equal to 1.\nDimension polynomials overload some integer operations, such as\nadd, multiply, equality, etc. The JAX NumPy layer and the LAX layers have been\n@@ -27,7 +25,8 @@ polynomials. This enables many JAX programs to be traced with dimension\npolynomials in some dimensions. A priority has been to enable the batch\ndimension in neural network examples to be polymorphic.\n-The best documentation at the moment is in the\n+This was built initially for jax2tf, but it is now customizeable to be\n+independent of TF. The best documentation at the moment is in the\njax2tf.convert docstring, and the\n[README](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md).\n\"\"\"\n@@ -37,21 +36,26 @@ import itertools\nimport functools\nimport operator as op\nimport re\n-from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, TypeVar, Union\n+from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Union\nimport jax\nfrom jax._src.numpy import lax_numpy\nfrom jax._src import dtypes\n+from jax._src.lax import lax\nimport opt_einsum\nfrom jax import config\nfrom jax import core\n-\nimport numpy as np\nDimSize = core.DimSize\nShape = core.Shape\nTfVal = Any\n+# A dimension environment maps dimension variables to expressions that\n+# compute the value of the dimension. These expressions refer to the\n+# function arguments.\n+ShapeEnv = Dict[str, Any]\n+DType = Any\nclass InconclusiveDimensionOperation(core.InconclusiveDimensionOperation):\n\"\"\"Raised when we cannot conclusively compute with symbolic dimensions.\"\"\"\n@@ -137,9 +141,9 @@ class _DimMon(dict):\nelif diff > 0: d[key] = diff\nreturn _DimMon(d)\n- def evaluate(self, env: \"ShapeEnv\") -> Union[\"DimExpr\", int]:\n- prod = lambda xs: functools.reduce(_multiply_dim_expr, xs) if xs else 1\n- def pow_opt(v: DimExpr, p: int) -> DimExpr:\n+ def evaluate(self, env: ShapeEnv):\n+ prod = lambda xs: functools.reduce(_multiply, xs) if xs else np.int32(1)\n+ def pow_opt(v, p: int):\nreturn v if p == 1 else prod([v] * p)\nreturn prod([pow_opt(env[id], deg) for id, deg in self.items()])\n@@ -389,10 +393,9 @@ class _DimPolynomial(dict):\n\"\"\"Returns the highest degree term that comes first lexicographically.\"\"\"\nreturn max(self.items())\n- def evaluate(self, env: \"ShapeEnv\") -> Union[\"DimExpr\", int]:\n- terms = [_multiply_dim_expr(mon.evaluate(env), coeff) for mon, coeff in self.items()]\n- return functools.reduce(_add_dim_expr, terms) if len(terms) > 1 else terms[0]\n-\n+ def evaluate(self, env: ShapeEnv):\n+ terms = [_multiply(mon.evaluate(env), np.int32(coeff)) for mon, coeff in self.items()]\n+ return functools.reduce(_add, terms) if len(terms) > 1 else terms[0]\ndef _ensure_poly(p: DimSize) -> _DimPolynomial:\nif isinstance(p, _DimPolynomial): return p\n@@ -638,130 +641,130 @@ def _parse_spec(spec: Optional[Union[str, PolyShape]],\nreturn dims\n-_Expr = TypeVar(\"_Expr\")\n-\n-class DimExpr:\n- \"\"\"Encapsulates an expression that denotes the value of a dimension size\n- for some intermediate value in the computation. It is computed based on the\n- input values for the top-level function arguments and the polymorphic\n- specifications.\n-\n- This class is intedend to be subclassed. An example of DimExpr, is\n- shape_poly_tf.DimExprTfVal which computes dimension sizes using TF ops,\n- e.g., `tf.shape(arg0)[0] + 1`.\n- \"\"\"\n- def __init__(self, raw: _Expr):\n- self._raw = raw\n-\n- @property\n- def raw(self) -> _Expr:\n- \"\"\"Returns the raw value.\"\"\"\n- return self._raw\n-\n- @classmethod\n- def for_arg(cls, arg: _Expr) -> Sequence[\"DimExpr\"]:\n- \"\"\"A list of dimension expressions, one for each dimensionof arg.\"\"\"\n- raise NotImplementedError\n-\n- def is_known_constant(self) -> Optional[int]:\n- \"\"\"Extract the constant if possible.\n-\n- Typically this should work when the input arguments have known shape, but\n- it may not work when we compile code that has dynamic shapes.\n- \"\"\"\n- raise NotImplementedError\n-\n- def add(self, other: Union[\"DimExpr\", int]) -> \"DimExpr\":\n- raise NotImplementedError\n-\n- def subtract(self, other: Union[\"DimExpr\", int]) -> \"DimExpr\":\n- raise NotImplementedError\n+def _add(v1, v2):\n+ if isinstance(v1, int) and v1 == 0:\n+ return v2\n+ elif isinstance(v2, int) and v2 == 0:\n+ return v1\n+ else:\n+ return v1 + v2\n- def multiply(self, other: Union[\"DimExpr\", int]) -> \"DimExpr\":\n- raise NotImplementedError\n+def _multiply(v1, v2):\n+ if isinstance(v1, int) and v1 == 1:\n+ return v2\n+ elif isinstance(v2, int) and v2 == 1:\n+ return v1\n+ else:\n+ return v1 * v2\n- def divmod(self, factor: int) -> Tuple[\"DimExpr\", \"DimExpr\"]:\n- \"\"\"Like Python divmod.\"\"\"\n- raise NotImplementedError\n+def _is_known_constant(v) -> Optional[int]:\n+ try:\n+ return int(v)\n+ except Exception:\n+ # TODO(necula): added this so that in jax2tf, in Eager mode, we can tell\n+ # that a tensor is a constant. We should move this dependency into some\n+ # jax2tf-specific area.\n+ if hasattr(v, \"val\"):\n+ try:\n+ vint = int(v.val)\n+ if isinstance(vint, int): # In TF, int(tf.Tensor) is tf.Tensor!\n+ return vint\n+ except Exception:\n+ pass\n+ return None\n+# dimension_size(operand, dimension=i) get the operand.shape[i] as a\n+# JAX value.\n+dimension_size_p = core.Primitive(\"dimension_size\")\n+def _dimension_size_abstract(aval: core.AbstractValue, **_) -> core.AbstractValue:\n+ return core.ShapedArray((), np.int32)\n-def _add_dim_expr(v1: Union[\"DimExpr\", int],\n- v2: Union[\"DimExpr\", int]) -> Union[\"DimExpr\", int]:\n- if isinstance(v1, DimExpr):\n- return v1.add(v2) if v2 != 0 else v1\n- elif isinstance(v2, DimExpr):\n- return v2.add(v1) if v1 != 0 else v2\n- else:\n- return v1 + v2 # integers\n+dimension_size_p.def_abstract_eval(_dimension_size_abstract)\n+def _dimension_size_impl(arg, *, dimension):\n+ return arg.shape[dimension]\n+dimension_size_p.def_impl(_dimension_size_impl)\n-def _multiply_dim_expr(v1: Union[\"DimExpr\", int],\n- v2: Union[DimExpr, int]) -> Union[DimExpr, int]:\n- if isinstance(v1, DimExpr):\n- return v1.multiply(v2) if v2 != 1 else v1\n- elif isinstance(v2, DimExpr):\n- return v2.multiply(v1) if v1 != 1 else v2\n- else:\n- return v1 * v2 # integers\n-\n+_JaxValue = Any\n@dataclasses.dataclass\nclass DimEquation:\n# Represents poly == _expr\npoly: _DimPolynomial\n- dim_expr: DimExpr\n+ dim_expr: _JaxValue\n-# A dimension environment maps dimension variables to expressions that\n-# compute the value of the dimension. These expressions refer to the\n-# function arguments.\n-ShapeEnv = Dict[str, DimExpr]\n-DType = Any\n-def eval_shape(shape: Sequence[DimSize], shape_env: ShapeEnv) -> Sequence[_Expr]:\n- def eval_dim(d: DimSize) -> Any:\n- d1 = d.evaluate(shape_env) # type: ignore[union-attr]\n- if isinstance(d1, int):\n- return d1\n- else:\n- return d1.raw\n- return tuple(eval_dim(d) if type(d) is _DimPolynomial else d # type: ignore\n+def get_shape_evaluator(dim_vars: Sequence[str], shape: Sequence[DimSize]) ->\\\n+ Tuple[Callable, Sequence[core.AbstractValue]]:\n+ \"\"\"Prepares a shape evaluator.\n+\n+ Returns a pair with the first component a function that given the values\n+ for the dimension variables returns the values for the dimensions of `shape`.\n+ The second component of the returned pair is a tuple of AbstractValues for\n+ the dimension variables.\n+ \"\"\"\n+ def eval_shape(*dim_values: Any) -> Sequence[Any]:\n+ shape_env_jax = dict(zip(dim_vars, dim_values))\n+\n+ def eval_dim(d: DimSize):\n+ return d.evaluate(shape_env_jax) # type: ignore[union-attr]\n+\n+ return tuple(eval_dim(d) if type(d) is _DimPolynomial else np.int32(d) # type: ignore\nfor d in shape)\n+ return (eval_shape,\n+ tuple(core.ShapedArray((), np.int32) for _ in dim_vars))\n-def args_avals_and_env(\n+def args_avals(\narg_shapes: Sequence[Sequence[Optional[int]]],\narg_jax_dtypes: Sequence[DType],\n- polymorphic_shapes: Sequence[Optional[Union[str, PolyShape]]],\n- arg_dim_exprs: Sequence[Sequence[DimExpr]]) -> \\\n- Tuple[Sequence[core.ShapedArray], ShapeEnv]:\n- \"\"\"Computes abstract values and a dimension environment for arguments.\n+ polymorphic_shapes: Sequence[Optional[Union[str, PolyShape]]]) -> \\\n+ Sequence[core.ShapedArray]:\n+ \"\"\"Computes abstract values.\nArgs:\narg_shapes: the shapes for the arguments, possibly having None dimensions.\narg_dtypes: the inferred JAX dtypes for the args.\npolymorphic_shapes: the polymorphic specifications for the arguments.\n- arg_dim_exprs: an expression that represents each dimension of each argument.\n- Returns: a tuple of: a sequence of abstract values corresponding to the\n- arguments, and a dimension variable environment.\n+ Returns: a sequence of abstract values corresponding to the arguments.\n\"\"\"\n- dim_equations: List[DimEquation] = []\ndef input_aval(arg_shape: Sequence[Optional[int]],\narg_jax_dtype: DType,\n- polymorphic_shape: Optional[str],\n- arg_dim_exprs: Sequence[DimExpr]) -> core.ShapedArray:\n+ polymorphic_shape: Optional[str]) -> core.ShapedArray:\n\"\"\"The abstract value for an input.\"\"\"\naval_shape = _parse_spec(polymorphic_shape, arg_shape)\n- for i, d in enumerate(aval_shape):\n- if is_poly_dim(d):\n- dim_equations.append(DimEquation(\n- poly=d, dim_expr=arg_dim_exprs[i])) # type: ignore\n-\nreturn core.ShapedArray(aval_shape, arg_jax_dtype)\n- avals = tuple(map(input_aval, arg_shapes, arg_jax_dtypes, polymorphic_shapes, arg_dim_exprs)) # type: ignore\n+ avals = tuple(map(input_aval, arg_shapes, arg_jax_dtypes, polymorphic_shapes)) # type: ignore\n+ return avals\n- shapeenv = _solve_dim_equations(dim_equations)\n- return avals, shapeenv\n+\n+def prepare_dim_var_env(args_avals: Sequence[core.AbstractValue]) -> \\\n+ Tuple[Sequence[str], Callable]:\n+ \"\"\"Get the dimension variables and the function to compute them.\n+\n+ Returns a tuple of dimension variables that appear in `args_avals` along\n+ with a function that given the actual arguments of the top-level function\n+ returns a tuple of dimension variable values, in the same order as the\n+ dimension variables returns in the first component.\n+ \"\"\"\n+ dim_vars: Set[str] = set()\n+ for a in args_avals:\n+ for d in a.shape:\n+ if is_poly_dim(d):\n+ dim_vars = dim_vars.union(d.get_vars())\n+\n+ def get_dim_var_values(*args: Any) -> Sequence[Any]:\n+ dim_equations: List[DimEquation] = []\n+ for a in args:\n+ for i, d in enumerate(a.shape):\n+ if is_poly_dim(d):\n+ dim_equations.append(DimEquation(\n+ poly=d, dim_expr=dimension_size_p.bind(a, dimension=i)))\n+\n+ dim_env = _solve_dim_equations(dim_equations)\n+ return tuple(dim_env[dv] for dv in dim_vars)\n+ return tuple(dim_vars), get_dim_var_values\ndef _solve_dim_equations(eqns: List[DimEquation]) -> ShapeEnv:\n# Returns a shape environment if it can solve all dimension variables.\n@@ -771,7 +774,7 @@ def _solve_dim_equations(eqns: List[DimEquation]) -> ShapeEnv:\ndef _shapeenv_to_str() -> str:\nif shapeenv:\nreturn (\" Partial solution: \" +\n- \", \".join([f\"{var} = {val.raw}\" for var, val in shapeenv.items()]) + \".\")\n+ \", \".join([f\"{var} = {val}\" for var, val in shapeenv.items()]) + \".\")\nelse:\nreturn \"\"\n@@ -788,7 +791,7 @@ def _solve_dim_equations(eqns: List[DimEquation]) -> ShapeEnv:\n# Perhaps we can already evaluate this monomial (all vars solved)\ntry:\nmon_value = mon.evaluate(shapeenv)\n- dim_expr = dim_expr.subtract(_multiply_dim_expr(mon_value, factor))\n+ dim_expr = dim_expr - _multiply(mon_value, np.int32(factor))\ncontinue\nexcept KeyError:\n# There are some indeterminate variables. We handle only the case of\n@@ -801,32 +804,37 @@ def _solve_dim_equations(eqns: List[DimEquation]) -> ShapeEnv:\nreturn False\nif var is not None:\n- var_value, var_remainder = dim_expr.divmod(factor_var) # type: ignore\n+ if factor_var == 1:\n+ var_value, var_remainder = dim_expr, np.int32(0)\n+ else:\n+ var_value = lax.div(dim_expr, np.int32(factor_var)) # type: ignore\n+ var_remainder = lax.rem(dim_expr, np.int32(factor_var)) # type: ignore\n+\n# Check that the division is even. Works only in eager mode.\n- var_remainder_int = var_remainder.is_known_constant()\n+ var_remainder_int = _is_known_constant(var_remainder)\nif var_remainder_int is not None and var_remainder_int != 0:\n# TODO(necula): check even in graph mode, by embedding the checks in\n# the graph.\nmsg = (f\"Dimension variable {var} must have integer value >= 1. \" # type: ignore\n- f\"Found value {int(dim_expr.is_known_constant()) / factor_var} when solving \"\n+ f\"Found value {int(_is_known_constant(dim_expr)) / factor_var} when solving \"\nf\"{eqn.poly} == {eqn.dim_expr}.{_shapeenv_to_str()}\")\nraise ValueError(msg)\n- var_value_int = var_value.is_known_constant()\n+ var_value_int = _is_known_constant(var_value)\nif var_value_int is not None and var_value_int <= 0:\n- msg = (f\"Dimension variable {var} must have integer value >= 1. \"\n+ msg = (f\"{var_value_int} Dimension variable {var} must have integer value >= 1. \"\nf\"Found value {int(var_value_int)} when solving \"\n- f\"{eqn.poly} == {eqn.dim_expr.raw}.{_shapeenv_to_str()}\")\n+ f\"{eqn.poly} == {eqn.dim_expr}.{_shapeenv_to_str()}\")\nraise ValueError(msg)\nshapeenv[var] = var_value\nreturn True\nelse:\n# All variables are resolved for this equation\n- dim_expr_int = dim_expr.is_known_constant()\n+ dim_expr_int = _is_known_constant(dim_expr)\nif dim_expr_int is not None and dim_expr_int != 0:\nerr_msg = (\n\"Found inconsistency when solving \"\n- f\"{eqn.poly} == {eqn.dim_expr.raw}.{_shapeenv_to_str()}\")\n+ f\"{eqn.poly} == {eqn.dim_expr}.{_shapeenv_to_str()}\")\nraise ValueError(err_msg)\nreturn True\n"
},
{
"change_type": "DELETE",
"old_path": "jax/experimental/jax2tf/shape_poly_tf.py",
"new_path": null,
"diff": "-# Copyright 2021 Google LLC\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\"\"\"Specialized shape polymorphism support for jax2tf.\n-\n-See the shape_poly.py module documentation, the jax2tf.convert docstring, and the\n-[README](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md).\n-\"\"\"\n-from typing import Any, Optional, Sequence, Tuple, Union\n-\n-import numpy as np\n-import tensorflow as tf # type: ignore[import]\n-\n-from jax.experimental.jax2tf import shape_poly\n-\n-TfVal = Any\n-\n-class DimExprTfVal(shape_poly.DimExpr):\n- \"\"\"Express dimensions using tf.shape and the TF arguments.\"\"\"\n- def __init__(self, tfval: TfVal):\n- super(DimExprTfVal, self).__init__(tfval)\n-\n- @classmethod\n- def for_arg(cls, arg: TfVal) -> Sequence[shape_poly.DimExpr]:\n- tf_shape = tf.shape(arg)\n- return tuple(DimExprTfVal(tf_shape[i]) for i in range(len(np.shape(arg))))\n-\n- def is_known_constant(self) -> Optional[int]:\n- # When under TF eager, the dimension expressions should be constants.\n- # Under TF graph, they will not be.\n- try:\n- return self.raw.numpy()\n- except AttributeError as e:\n- assert str(e).find(\"numpy\") > 0, e\n- return None\n-\n- def add(self, other: Union[shape_poly.DimExpr, int]) -> shape_poly.DimExpr:\n- if isinstance(other, shape_poly.DimExpr):\n- other = other.raw # type: ignore[assignment]\n- return DimExprTfVal(tf.math.add(self.raw, other))\n-\n- def subtract(self, other: Union[shape_poly.DimExpr, int]) -> shape_poly.DimExpr:\n- if isinstance(other, shape_poly.DimExpr):\n- other = other.raw # type: ignore[assignment]\n- return DimExprTfVal(tf.math.subtract(self.raw, other))\n-\n- def multiply(self, other: Union[shape_poly.DimExpr, int]) -> shape_poly.DimExpr:\n- if isinstance(other, shape_poly.DimExpr):\n- other = other.raw # type: ignore[assignment]\n- return DimExprTfVal(tf.math.multiply(self.raw, other))\n-\n- def divmod(self, factor: int) -> Tuple[shape_poly.DimExpr, shape_poly.DimExpr]:\n- dividend = DimExprTfVal(tf.math.floordiv(self.raw, factor)) if factor != 1 else self\n- mod = DimExprTfVal(tf.math.floormod(self.raw, factor))\n- return dividend, mod\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": "@@ -26,11 +26,12 @@ import jax\nfrom jax import core\nfrom jax.experimental import jax2tf\nfrom jax.experimental.jax2tf import shape_poly\n-from jax.experimental.jax2tf import shape_poly_tf\nfrom jax import lax\n+from jax import linear_util as lu\nimport jax.numpy as jnp\nfrom jax._src import test_util as jtu\nfrom jax._src.lax import control_flow as lax_control_flow\n+from jax._src import util\nimport numpy as np\nfrom jax.experimental.jax2tf.tests import tf_test_util\n@@ -404,7 +405,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nf_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"b, ...\"])\nf_tf(x, y=y)\n-\ndef test_arg_avals(self):\n\"\"\"Test conversion of actual arguments to abstract values.\"\"\"\n@@ -417,12 +417,14 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# check expected_shapeenv.\narg_dtypes = (_f32,) * len(arg_shapes)\ndef f_tf(*tf_args):\n- avals, shape_env = shape_poly.args_avals_and_env(\n- arg_shapes, arg_dtypes, polymorphic_shapes,\n- tuple(shape_poly_tf.DimExprTfVal.for_arg(a) for a in tf_args)) # The function under test\n+ avals = shape_poly.args_avals(\n+ arg_shapes, arg_dtypes, polymorphic_shapes) # The function under test\n+ dim_vars, get_dim_values = shape_poly.prepare_dim_var_env(avals)\n+ dim_values, _ = util.unzip2(jax2tf.jax2tf._interpret_fun(lu.wrap_init(get_dim_values),\n+ tf_args, avals, \"\"))\nif expected_avals is not None:\nself.assertEqual(expected_avals, avals)\n- return {k: d.raw for k, d in shape_env.items()}\n+ return dict(zip(dim_vars, dim_values))\nif eager_mode:\n# If we want to check the shape_env then all arg_shapes must be known\nassert all(all(d is not None for d in a_s)\n@@ -435,7 +437,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nf_tf = tf.function(autograph=False)(f_tf)\nf_tf.get_concrete_function(*[tf.TensorSpec(a_s, _f32)\nfor a_s in arg_shapes])\n- assert not expected_shapeenv, \"Should use eaager_mode=True\"\n+ assert not expected_shapeenv, \"Should use eager_mode=True\"\ndef shaped_array(shape_spec: str, actual_shape: core.Shape):\nreturn core.ShapedArray(\n@@ -630,9 +632,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\n- re.escape(\n- \"Found inconsistency when solving a == 3. Partial solution: a = 2.\"\n- )):\n+ \"Found inconsistency when solving.*\"):\ncheck_avals(\narg_shapes=[(2, 3)],\npolymorphic_shapes=[\"(a, a)\"],\n@@ -641,9 +641,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# Same error across multiple arguments\nwith self.assertRaisesRegex(\nValueError,\n- re.escape(\n- \"Found inconsistency when solving a == 5. Partial solution: a = 2.\"\n- )):\n+ \"Found inconsistency when solving.*\"):\ncheck_avals(\narg_shapes=[(2, 3), (5,)],\npolymorphic_shapes=[\"a, ...\", \"a\"],\n@@ -952,7 +950,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# eagerly.\n# Raises: ValueError: PolyShape 'b' has dimension variable 'b' corresponding to 0, for argument shape (0,)\nwith self.assertRaisesRegex(ValueError,\n- re.escape(\"Dimension variable b must have integer value >= 1. Found value 0 when solving b == 0\")):\n+ \"Dimension variable b must have integer value >= 1. Found value 0 when solving .*\"):\njax2tf.convert(f_jax, polymorphic_shapes=[\"b\"])(x0)\n# However, if we first trace to a TensorFlow graph, we may miss the broken assumption:\n@@ -972,7 +970,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# function is executed eagerly.\n# Raises: ValueError: PolyShape 'b, b' has dimension variable 'b' corresponding to multiple values ([4, 5]), for argument shape (4, 5)\nwith self.assertRaisesRegex(ValueError,\n- re.escape(\"Found inconsistency when solving b == 5. Partial solution: b = 4.\")):\n+ \"Found inconsistency when solving b == .*\"):\njax2tf.convert(f_jax, polymorphic_shapes=[\"b, b\"])(x45)\n# However, if we first trace to a TensorFlow graph, we may miss the broken assumption.\n@@ -1783,7 +1781,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# to parameterized below.\n@primitive_harness.parameterized(\n_flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"scatter_add_clip_poly_axes\"\n+ #one_containing=\"reshape_1_poly_axes=[(0, 1)]\"\n)\ndef test_prim(self, harness: Harness):\nargs = harness.dyn_args_maker(self.rng())\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Simplify the shape_poly support.
The goal is to make is shareable outside of jax2tf. |
260,424 | 16.12.2021 21:48:37 | 0 | 98a54611323653b70d2bd1eed8e4e993c09950ea | Make sure while_loop cond generates an error even if it returns False. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/checkify.py",
"new_path": "jax/experimental/checkify.py",
"diff": "@@ -305,8 +305,9 @@ def checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error):\ncond_f = core.jaxpr_as_fun(cond_jaxpr)\nbody_f = core.jaxpr_as_fun(body_jaxpr)\ndef new_body_f(*vals):\n- _ = cond_f(*vals)\n- return body_f(*vals)\n+ out = body_f(*vals)\n+ _ = cond_f(*out) # this checks if the next cond application will error\n+ return out\nreturn checkify_fun_to_jaxpr(lu.wrap_init(new_body_f), error, body_jaxpr.in_avals)\ndef ignore_errors_jaxpr(jaxpr, error):\n@@ -322,18 +323,22 @@ def ignore_errors_jaxpr(jaxpr, error):\nreturn core.ClosedJaxpr(new_jaxpr, consts)\ndef while_loop_error_check(error, *in_flat, cond_nconsts, cond_jaxpr, body_nconsts, body_jaxpr):\n- # TODO(lenamartens): fix when an error occurs in the cond function and it then returns False.\n- checked_body_jaxpr, msgs_ = checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error)\n+ checked_cond_jaxpr, msgs_cond = checkify_jaxpr(cond_jaxpr, error)\n+ checked_cond_fun = core.jaxpr_as_fun(checked_cond_jaxpr)\n+ # Check if the first cond application will error.\n+ cond_err, cond_code, _ = checked_cond_fun(error.err, error.code, *in_flat)\n+\n+ checked_body_jaxpr, msgs_body = checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error)\ncompat_cond_jaxpr = ignore_errors_jaxpr(cond_jaxpr, error)\nc_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\n- new_in_flat = [*c_consts, *b_consts, error.err, error.code, *carry]\n+ new_in_flat = [*c_consts, *b_consts, cond_err, cond_code, *carry]\nerr, code, *out = control_flow.while_p.bind(\n*new_in_flat,\ncond_nconsts=cond_nconsts,\ncond_jaxpr=compat_cond_jaxpr,\nbody_nconsts=body_nconsts,\nbody_jaxpr=checked_body_jaxpr)\n- new_msgs = {**error.msgs, **msgs_}\n+ new_msgs = {**error.msgs, **msgs_body, **msgs_cond}\nreturn out, Error(err, code, new_msgs)\nerror_checks[control_flow.while_p] = while_loop_error_check\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -259,6 +259,29 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertStartsWith(err.get(), \"nan generated by primitive sin\")\nself.assertArraysEqual(ch_out, out)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_while_loop_cond_error_and_false(self):\n+ # Tests if an error is generated when cond returns False.\n+ def while_cond(val):\n+ possible_nan = jnp.sin(1./val)\n+ return jnp.logical_not(jnp.isnan(possible_nan))\n+\n+ @jax.jit\n+ def f(init_val):\n+ return lax.while_loop(while_cond, lambda val: val-1, init_val)\n+\n+ # error on first cond\n+ init_val = 0.\n+ err, _ = checkify.checkify(f)(init_val)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+\n+ # error on second cond\n+ init_val = 1.\n+ err, _ = checkify.checkify(f)(init_val)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+\n@jtu.skip_on_devices(\"tpu\")\ndef test_while_loop_body_and_cond_error(self):\ndef while_cond(val):\n"
}
] | Python | Apache License 2.0 | google/jax | Make sure while_loop cond generates an error even if it returns False. |
260,424 | 16.12.2021 22:44:05 | 0 | 03e0deac04f7379f52f93bf879a1d58380182e84 | Add NaN checkify rule to all lax primitives. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/checkify.py",
"new_path": "jax/experimental/checkify.py",
"diff": "@@ -27,9 +27,7 @@ from jax.api_util import flatten_fun\nfrom jax.interpreters import partial_eval as pe\nfrom jax.tree_util import tree_flatten, tree_unflatten, register_pytree_node\nfrom jax._src import source_info_util, traceback_util\n-from jax._src.lax import lax\n-from jax._src.lax import slicing\n-from jax._src.lax import control_flow\n+from jax import lax\nfrom jax._src.util import as_hashable_function, unzip2, split_list\nsource_info_util.register_exclusion(__file__)\n@@ -254,13 +252,10 @@ def nan_error_check(prim, error, *in_vals, **params):\nmsg = f\"nan generated by primitive {prim.name} at {summary()}\"\nreturn out, assert_func(error, no_nans, msg)\n-error_checks[lax.sin_p] = partial(nan_error_check, lax.sin_p)\n-error_checks[lax.cos_p] = partial(nan_error_check, lax.cos_p)\n-\ndef gather_error_check(error, operand, start_indices, *,\ndimension_numbers, slice_sizes, unique_indices,\nindices_are_sorted, mode, fill_value):\n- out = slicing.gather_p.bind(\n+ out = lax.gather_p.bind(\noperand, start_indices, dimension_numbers=dimension_numbers,\nslice_sizes=slice_sizes, unique_indices=unique_indices,\nindices_are_sorted=indices_are_sorted, mode=mode, fill_value=fill_value)\n@@ -275,31 +270,31 @@ def gather_error_check(error, operand, start_indices, *,\nmsg = f\"out-of-bounds indexing at {summary()}\"\nreturn out, assert_func(error, all_inbounds, msg)\n-error_checks[slicing.gather_p] = gather_error_check\n+error_checks[lax.gather_p] = gather_error_check\ndef cond_error_check(error, index, *ops, branches, linear):\nnew_branches, msgs_ = unzip2(checkify_jaxpr(jxpr, error) for jxpr in branches)\nnew_linear = (False, False, *linear)\n- err, code, *outs = control_flow.cond_p.bind(\n+ err, code, *outs = lax.cond_p.bind(\nindex, error.err, error.code, *ops,\nbranches=tuple(new_branches), linear=new_linear)\nnew_msgs = {k:v for d in it.chain([error.msgs], msgs_) for k, v in d.items()}\nreturn outs, Error(err, code, new_msgs)\n-error_checks[control_flow.cond_p] = cond_error_check\n+error_checks[lax.cond_p] = cond_error_check\ndef scan_error_check(error, *in_flat, reverse, length, jaxpr, num_consts, num_carry, linear, unroll):\nconsts, carry, xs = split_list(in_flat, [num_consts, num_carry])\nchecked_jaxpr, msgs_ = checkify_jaxpr(jaxpr, error)\nnew_linear = (False, False, *linear)\nnew_in_flat = [*consts, error.err, error.code, *carry, *xs]\n- err, code, *outs = control_flow.scan_p.bind(\n+ err, code, *outs = lax.scan_p.bind(\n*consts, *new_in_flat,\nreverse=reverse, length=length, jaxpr=checked_jaxpr,\nnum_consts=len(consts), num_carry=len(carry)+2,\nlinear=new_linear, unroll=unroll)\nnew_msgs = {**error.msgs, **msgs_}\nreturn outs, Error(err, code, new_msgs)\n-error_checks[control_flow.scan_p] = scan_error_check\n+error_checks[lax.scan_p] = scan_error_check\ndef checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error):\ncond_f = core.jaxpr_as_fun(cond_jaxpr)\n@@ -332,7 +327,7 @@ def while_loop_error_check(error, *in_flat, cond_nconsts, cond_jaxpr, body_ncons\ncompat_cond_jaxpr = ignore_errors_jaxpr(cond_jaxpr, error)\nc_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\nnew_in_flat = [*c_consts, *b_consts, cond_err, cond_code, *carry]\n- err, code, *out = control_flow.while_p.bind(\n+ err, code, *out = lax.while_p.bind(\n*new_in_flat,\ncond_nconsts=cond_nconsts,\ncond_jaxpr=compat_cond_jaxpr,\n@@ -340,7 +335,7 @@ def while_loop_error_check(error, *in_flat, cond_nconsts, cond_jaxpr, body_ncons\nbody_jaxpr=checked_body_jaxpr)\nnew_msgs = {**error.msgs, **msgs_body, **msgs_cond}\nreturn out, Error(err, code, new_msgs)\n-error_checks[control_flow.while_p] = while_loop_error_check\n+error_checks[lax.while_p] = while_loop_error_check\n# TODO(mattjj,lenamartens): currently we bundle effectful-assert-discharging\n# with the error-check-adding transformation (checkify), but they could be\n@@ -363,3 +358,71 @@ def checkify(fun: Callable) -> Callable:\nout = tree_unflatten(out_tree(), out_flat)\nreturn Error(err, code, msgs), out\nreturn checked_fun\n+\n+## NaN error rule table\n+\n+def add_nan_check(prim):\n+ error_checks[prim] = partial(nan_error_check, prim)\n+\n+add_nan_check(lax.floor_p)\n+add_nan_check(lax.ceil_p)\n+add_nan_check(lax.round_p)\n+add_nan_check(lax.sign_p)\n+add_nan_check(lax.shift_left_p)\n+add_nan_check(lax.shift_right_arithmetic_p)\n+add_nan_check(lax.shift_right_logical_p)\n+add_nan_check(lax.bitcast_convert_type_p)\n+add_nan_check(lax.real_p)\n+add_nan_check(lax.complex_p)\n+add_nan_check(lax.conj_p)\n+add_nan_check(lax.imag_p)\n+add_nan_check(lax.add_p)\n+add_nan_check(lax.sub_p)\n+add_nan_check(lax.convert_element_type_p)\n+add_nan_check(lax.broadcast_in_dim_p)\n+add_nan_check(lax.concatenate_p)\n+add_nan_check(lax.pad_p)\n+add_nan_check(lax.reshape_p)\n+add_nan_check(lax.rev_p)\n+add_nan_check(lax.transpose_p)\n+add_nan_check(lax.slice_p)\n+add_nan_check(lax.reduce_sum_p)\n+add_nan_check(lax.reduce_window_sum_p)\n+add_nan_check(lax.fft_p)\n+add_nan_check(lax.cumsum_p)\n+add_nan_check(lax.cumprod_p)\n+add_nan_check(lax.cummax_p)\n+add_nan_check(lax.cummin_p)\n+add_nan_check(lax.erf_p)\n+add_nan_check(lax.expm1_p)\n+add_nan_check(lax.log1p_p)\n+add_nan_check(lax.sqrt_p)\n+add_nan_check(lax.rsqrt_p)\n+add_nan_check(lax.asinh_p)\n+add_nan_check(lax.acosh_p)\n+add_nan_check(lax.atanh_p)\n+add_nan_check(lax.erfc_p)\n+add_nan_check(lax.rem_p)\n+add_nan_check(lax.clamp_p)\n+add_nan_check(lax.erf_inv_p)\n+add_nan_check(lax.exp_p)\n+add_nan_check(lax.pow_p)\n+add_nan_check(lax.integer_pow_p)\n+add_nan_check(lax.tanh_p)\n+add_nan_check(lax.log_p)\n+add_nan_check(lax.atan2_p)\n+add_nan_check(lax.div_p)\n+add_nan_check(lax.sin_p)\n+add_nan_check(lax.cos_p)\n+add_nan_check(lax.sinh_p)\n+add_nan_check(lax.cosh_p)\n+add_nan_check(lax.dot_general_p)\n+add_nan_check(lax.mul_p)\n+add_nan_check(lax.conv_general_dilated_p)\n+add_nan_check(lax.reduce_max_p)\n+add_nan_check(lax.reduce_min_p)\n+add_nan_check(lax.abs_p)\n+add_nan_check(lax.select_p)\n+add_nan_check(lax.max_p)\n+add_nan_check(lax.min_p)\n+add_nan_check(lax.scatter_add_p)\n"
}
] | Python | Apache License 2.0 | google/jax | Add NaN checkify rule to all lax primitives. |
260,461 | 21.12.2021 20:21:39 | 0 | cd333f0f5b97d1319b5cd3523faccfa0aa256202 | Fix straight-through estimator example in docs | [
{
"change_type": "MODIFY",
"old_path": "docs/jax-101/04-advanced-autodiff.ipynb",
"new_path": "docs/jax-101/04-advanced-autodiff.ipynb",
"diff": "\" return jnp.round(x) # non-differentiable\\n\",\n\"\\n\",\n\"def straight_through_f(x):\\n\",\n- \" return x + jax.lax.stop_gradient(f(x) - x)\\n\",\n+ \" # Create an exactly-zero expression with Sterbenz lemma that has\\n\",\n+ \" # an exactly-one gradient.\\n\",\n+ \" zero = x - jax.lax.stop_gradient(x)\\n\",\n+ \" return zero + jax.lax.stop_gradient(f(x))\\n\",\n\"\\n\",\n\"print(\\\"f(x): \\\", f(3.2))\\n\",\n\"print(\\\"straight_through_f(x):\\\", straight_through_f(3.2))\\n\",\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax-101/04-advanced-autodiff.md",
"new_path": "docs/jax-101/04-advanced-autodiff.md",
"diff": "@@ -250,7 +250,10 @@ def f(x):\nreturn jnp.round(x) # non-differentiable\ndef straight_through_f(x):\n- return x + jax.lax.stop_gradient(f(x) - x)\n+ # Create an exactly-zero expression with Sterbenz lemma that has\n+ # an exactly-one gradient.\n+ zero = x - jax.lax.stop_gradient(x)\n+ return zero + jax.lax.stop_gradient(f(x))\nprint(\"f(x): \", f(3.2))\nprint(\"straight_through_f(x):\", straight_through_f(3.2))\n"
}
] | Python | Apache License 2.0 | google/jax | Fix straight-through estimator example in docs (#9032) |
260,447 | 21.12.2021 14:56:09 | 28,800 | 6a0bfdd637a79edda35356621867dd758705062d | [JAX] Requires indices to be sorted and of int32 in `_sparse_bcoo_matvec` test. | [
{
"change_type": "MODIFY",
"old_path": "benchmarks/api_benchmark.py",
"new_path": "benchmarks/api_benchmark.py",
"diff": "@@ -404,13 +404,10 @@ def sparse_bcoo_todense_compile(state):\ndef _sparse_bcoo_matvec(state, jit: bool = False, compile: bool = False):\nshape = (2000, 2000)\nnse = 10000\n- size = np.prod(shape)\n- rng = np.random.RandomState(1701)\n- data = rng.randn(nse)\n- indices = np.unravel_index(\n- rng.choice(size, size=nse, replace=False), shape=shape)\n- mat = sparse.BCOO((jnp.array(data), jnp.column_stack(indices)), shape=shape)\n- vec = rng.randn(shape[1])\n+ key = jax.random.PRNGKey(1701)\n+ mat = sparse.random_bcoo(key, nse=nse, shape=shape, dtype=jnp.float32,\n+ indices_dtype=jnp.int32, sorted_indices=True)\n+ vec = jax.random.uniform(key, shape=(shape[1],), dtype=jnp.float32)\nf = lambda mat, vec: mat @ vec\nif jit or compile:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/random.py",
"new_path": "jax/experimental/sparse/random.py",
"diff": "@@ -22,14 +22,16 @@ import jax.numpy as jnp\nfrom jax.experimental import sparse\n-def random_bcoo(key, shape, *, dtype=jnp.float_, nse=0.2, n_batch=0, n_dense=0,\n- unique_indices=True, generator=random.uniform, **kwds):\n+def random_bcoo(key, shape, *, dtype=jnp.float_, indices_dtype=jnp.int_,\n+ nse=0.2, n_batch=0, n_dense=0, unique_indices=True,\n+ sorted_indices=False, generator=random.uniform, **kwds):\n\"\"\"Generate a random BCOO matrix.\nArgs:\nkey : random.PRNGKey to be passed to ``generator`` function.\nshape : tuple specifying the shape of the array to be generated.\ndtype : dtype of the array to be generated.\n+ indices_dtype: dtype of the BCOO indicies.\nnse : number of specified elements in the matrix, or if 0 < nse < 1, a\nfraction of sparse dimensions to be specified (default: 0.2).\nn_batch : number of batch dimensions. must satisfy ``n_batch >= 0`` and\n@@ -38,9 +40,11 @@ def random_bcoo(key, shape, *, dtype=jnp.float_, nse=0.2, n_batch=0, n_dense=0,\n``n_batch + n_dense <= len(shape)``.\nunique_indices : boolean specifying whether indices should be unique\n(default: True).\n- generator : function for generating random values accepting a key, shape, and\n- dtype. It defaults to :func:`jax.random.uniform`, and may be any function\n- with a similar signature.\n+ sorted_indices : boolean specifying whether indices should be row-sorted in\n+ lexicographical order (default: False).\n+ generator : function for generating random values accepting a key, shape,\n+ and dtype. It defaults to :func:`jax.random.uniform`, and may be any\n+ function with a similar signature.\n**kwds : additional keyword arguments to pass to ``generator``.\nReturns:\n@@ -74,6 +78,6 @@ def random_bcoo(key, shape, *, dtype=jnp.float_, nse=0.2, n_batch=0, n_dense=0,\nkeys = random.split(key, batch_size + 1)\ndata_key, index_keys = keys[0], keys[1:]\ndata = generator(data_key, shape=data_shape, dtype=dtype, **kwds)\n- indices = _indices(index_keys).reshape(indices_shape)\n-\n- return sparse.BCOO((data, indices), shape=shape)\n+ indices = _indices(index_keys).reshape(indices_shape).astype(indices_dtype)\n+ mat = sparse.BCOO((data, indices), shape=shape)\n+ return mat.sum_duplicates() if sorted_indices else mat\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -1735,20 +1735,25 @@ class SparseObjectTest(jtu.JaxTestCase):\nclass SparseRandomTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_{}_nbatch={}_ndense={}\".format(\n- jtu.format_shape_dtype_string(shape, dtype), n_batch, n_dense),\n- \"shape\": shape, \"dtype\": dtype, \"n_batch\": n_batch, \"n_dense\": n_dense}\n+ {\"testcase_name\": \"_{}_indices_dtype={}_nbatch={}_ndense={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), indices_dtype, n_batch, n_dense),\n+ \"shape\": shape, \"dtype\": dtype, \"indices_dtype\": indices_dtype,\n+ \"n_batch\": n_batch, \"n_dense\": n_dense}\nfor shape in [(5,), (5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]\nfor dtype in jtu.dtypes.floating\n+ for indices_dtype in jtu.dtypes.integer\nfor n_batch in range(len(shape) + 1)\nfor n_dense in range(len(shape) + 1 - n_batch)))\n- def test_random_bcoo(self, shape, dtype, n_batch, n_dense):\n+ def test_random_bcoo(self, shape, dtype, indices_dtype, n_batch, n_dense):\nkey = jax.random.PRNGKey(1701)\n- mat = sparse.random_bcoo(key, shape=shape, dtype=dtype, n_batch=n_batch, n_dense=n_dense)\n+ mat = sparse.random_bcoo(\n+ key, shape=shape, dtype=dtype, indices_dtype=indices_dtype,\n+ n_batch=n_batch, n_dense=n_dense)\nmat_dense = mat.todense()\nself.assertEqual(mat_dense.shape, shape)\nself.assertEqual(mat_dense.dtype, dtype)\n+ self.assertEqual(mat.indices.dtype, indices_dtype)\nn_sparse = len(shape) - n_batch - n_dense\nbatch_shape, sparse_shape, dense_shape = split_list(shape, [n_batch, n_sparse])\n"
}
] | Python | Apache License 2.0 | google/jax | [JAX] Requires indices to be sorted and of int32 in `_sparse_bcoo_matvec` test.
PiperOrigin-RevId: 417695937 |
260,335 | 14.12.2021 13:29:16 | 28,800 | a582fa874807cdc9fba1dbe07d830ac7632b9abb | add limit to number of tracer provenance lines
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1159,11 +1159,13 @@ class DynamicJaxprTracer(core.Tracer):\nmsts = [\" operation \"\nf\"{core.pp_eqn(eqn, core.JaxprPpContext(), print_shapes=True)}\\n\"\nf\" from line {source_info_util.summarize(eqn.source_info)}\"\n- for eqn in progenitor_eqns]\n+ for eqn in progenitor_eqns[:5]] # show at most 5\norigin = (f\"While tracing the function {dbg.func_src_info} \"\nf\"for {dbg.traced_for}, \"\n\"this value became a tracer due to JAX operations on these lines:\"\n\"\\n\\n\" + \"\\n\\n\".join(msts))\n+ if len(progenitor_eqns) > 5:\n+ origin += \"\\n\\n(Additional originating lines are not shown.)\"\nelse:\norigin = (f\"The error occured while tracing the function {dbg.func_src_info} \"\nf\"for {dbg.traced_for}.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2765,6 +2765,16 @@ class APITest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(core.ConcretizationTypeError, msg):\nf()\n+ def test_concrete_error_because_const_2(self):\n+ @jax.jit\n+ def f():\n+ result = sum(jnp.add(1, 1) for _ in range(6))\n+ assert result > 0\n+\n+ msg = \"Additional originating lines are not shown.\"\n+ with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n+ f()\n+\ndef test_xla_computation_zeros_doesnt_device_put(self):\nwith jtu.count_device_put() as count:\napi.xla_computation(lambda: jnp.zeros(3))()\n"
}
] | Python | Apache License 2.0 | google/jax | add limit to number of tracer provenance lines
fixes #8910 |
260,335 | 16.12.2021 10:57:19 | 28,800 | 9e28bd5f4efc59de4c0a93a0b85b96c47d10799d | small changes to checkify | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/checkify.py",
"new_path": "jax/experimental/checkify.py",
"diff": "@@ -222,9 +222,16 @@ def check_errors_traceable(msgs, err, code, *args):\n## assert primitive\ndef assert_(pred: Bool, msg: str) -> None:\n+ if not is_scalar_pred(pred):\n+ raise TypeError(f\"assert_ takes a scalar pred as argument, got {pred}\")\ncode = next_code()\nreturn assert2_(pred, code, {code: msg})\n+def is_scalar_pred(pred) -> bool:\n+ return (isinstance(pred, bool) or\n+ isinstance(pred, jnp.ndarray) and pred.shape == () and\n+ pred.dtype == jnp.dtype('bool'))\n+\ndef assert2_(pred: Bool, code: Int, msgs: Dict[int, str]) -> None:\nreturn assert_p.bind(pred, code, msgs=msgs)\n"
}
] | Python | Apache License 2.0 | google/jax | small changes to checkify
Co-authored-by: Lena Martens <lenamartens@google.com> |
260,377 | 27.12.2021 20:23:29 | -10,800 | f93531b0204914b04217674ef31dd1a29088fd26 | replace deprecated jax.ops.index_* functions with the new index update operators | [
{
"change_type": "MODIFY",
"old_path": "docs/jax-101/01-jax-basics.ipynb",
"new_path": "docs/jax-101/01-jax-basics.ipynb",
"diff": "\"\\u001b[0;31mTypeError\\u001b[0m Traceback (most recent call last)\",\n\"\\u001b[0;32m<ipython-input-12-709e2d7ddd3f>\\u001b[0m in \\u001b[0;36m<module>\\u001b[0;34m()\\u001b[0m\\n\\u001b[0;32m----> 1\\u001b[0;31m \\u001b[0min_place_modify\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mjnp\\u001b[0m\\u001b[0;34m.\\u001b[0m\\u001b[0marray\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mx\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m)\\u001b[0m \\u001b[0;31m# Raises error when we cast input to jnp.ndarray\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[0m\",\n\"\\u001b[0;32m<ipython-input-11-fce65eb843c7>\\u001b[0m in \\u001b[0;36min_place_modify\\u001b[0;34m(x)\\u001b[0m\\n\\u001b[1;32m 4\\u001b[0m \\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 5\\u001b[0m \\u001b[0;32mdef\\u001b[0m \\u001b[0min_place_modify\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mx\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m:\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[0;32m----> 6\\u001b[0;31m \\u001b[0mx\\u001b[0m\\u001b[0;34m[\\u001b[0m\\u001b[0;36m0\\u001b[0m\\u001b[0;34m]\\u001b[0m \\u001b[0;34m=\\u001b[0m \\u001b[0;36m123\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[0m\\u001b[1;32m 7\\u001b[0m \\u001b[0;32mreturn\\u001b[0m \\u001b[0;32mNone\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 8\\u001b[0m \\u001b[0;34m\\u001b[0m\\u001b[0m\\n\",\n- \"\\u001b[0;32m/usr/local/lib/python3.7/dist-packages/jax/_src/numpy/lax_numpy.py\\u001b[0m in \\u001b[0;36m_unimplemented_setitem\\u001b[0;34m(self, i, x)\\u001b[0m\\n\\u001b[1;32m 5116\\u001b[0m \\u001b[0;34m\\\"immutable; perhaps you want jax.ops.index_update or \\\"\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 5117\\u001b[0m \\\"jax.ops.index_add instead?\\\")\\n\\u001b[0;32m-> 5118\\u001b[0;31m \\u001b[0;32mraise\\u001b[0m \\u001b[0mTypeError\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mmsg\\u001b[0m\\u001b[0;34m.\\u001b[0m\\u001b[0mformat\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mtype\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mself\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[0m\\u001b[1;32m 5119\\u001b[0m \\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 5120\\u001b[0m \\u001b[0;32mdef\\u001b[0m \\u001b[0m_operator_round\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mnumber\\u001b[0m\\u001b[0;34m,\\u001b[0m \\u001b[0mndigits\\u001b[0m\\u001b[0;34m=\\u001b[0m\\u001b[0;32mNone\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m:\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\",\n- \"\\u001b[0;31mTypeError\\u001b[0m: '<class 'jax.interpreters.xla._DeviceArray'>' object does not support item assignment. JAX arrays are immutable; perhaps you want jax.ops.index_update or jax.ops.index_add instead?\"\n+ \"\\u001b[0;32m/usr/local/lib/python3.7/dist-packages/jax/_src/numpy/lax_numpy.py\\u001b[0m in \\u001b[0;36m_unimplemented_setitem\\u001b[0;34m(self, i, x)\\u001b[0m\\n\\u001b[1;32m 6594\\u001b[0m \\u001b[0;34m\\\"or another .at[] method: \\\"\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 6595\\u001b[0m \\\"https://jax.readthedocs.io/en/latest/jax.ops.html\\\")\\n\\u001b[0;32m-> 6596\\u001b[0;31m \\u001b[0;32mraise\\u001b[0m \\u001b[0mTypeError\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mmsg\\u001b[0m\\u001b[0;34m.\\u001b[0m\\u001b[0mformat\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mtype\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mself\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[0m\\u001b[1;32m 6597\\u001b[0m \\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 6598\\u001b[0m \\u001b[0;32mdef\\u001b[0m \\u001b[0m_operator_round\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mnumber\\u001b[0m\\u001b[0;34m,\\u001b[0m \\u001b[0mndigits\\u001b[0m\\u001b[0;34m=\\u001b[0m\\u001b[0;32mNone\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m:\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\",\n+ \"\\u001b[0;31mTypeError\\u001b[0m: '<class 'jaxlib.xla_extension.DeviceArray'>' object does not support item assignment. JAX arrays are immutable. Instead of ``x[idx] = y``, use ``x = x.at[idx].set(y)`` or another .at[] method: https://jax.readthedocs.io/en/latest/jax.ops.html\"\n]\n}\n],\n\"id\": \"RGqVfYSpc49s\"\n},\n\"source\": [\n- \"Helpfully, the error points us to JAX's side-effect-free way of doing the same thing via the [`jax.ops.index_*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-operators) ops. They are analogous to in-place modification by index, but create a new array with the corresponding modifications made:\"\n+ \"Helpfully, the error points us to JAX's side-effect-free way of doing the same thing via the [`jax.ops.*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-operators) index update operators (be careful [`jax.ops.index_*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-functions-deprecated) functions are deprecated). They are analogous to in-place modification by index, but create a new array with the corresponding modifications made:\"\n]\n},\n{\n],\n\"source\": [\n\"def jax_in_place_modify(x):\\n\",\n- \" return jax.ops.index_update(x, 0, 123)\\n\",\n+ \" return x.at[0].set(123)\\n\",\n\"\\n\",\n\"y = jnp.array([1, 2, 3])\\n\",\n\"jax_in_place_modify(y)\"\n\"source\": [\n\"Side-effect-free code is sometimes called *functionally pure*, or just *pure*.\\n\",\n\"\\n\",\n- \"Isn't the pure version less efficient? Strictly, yes; we are creating a new array. However, as we will explain in the next guide, JAX computations are often compiled before being run using another program transformation, `jax.jit`. If we don't use the old array after modifying it 'in place' using `jax.ops.index_update()`, the compiler can recognise that it can in fact compile to an in-place modify, resulting in efficient code in the end.\\n\",\n+ \"Isn't the pure version less efficient? Strictly, yes; we are creating a new array. However, as we will explain in the next guide, JAX computations are often compiled before being run using another program transformation, `jax.jit`. If we don't use the old array after modifying it 'in place' using indexed update operators, the compiler can recognise that it can in fact compile to an in-place modify, resulting in efficient code in the end.\\n\",\n\"\\n\",\n\"Of course, it's possible to mix side-effectful Python code and functionally pure JAX code, and we will touch on this more later. As you get more familiar with JAX, you will learn how and when this can work. As a rule of thumb, however, any functions intended to be transformed by JAX should avoid side-effects, and the JAX primitives themselves will try to help you do that.\\n\",\n\"\\n\",\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax-101/01-jax-basics.md",
"new_path": "docs/jax-101/01-jax-basics.md",
"diff": "@@ -254,13 +254,13 @@ in_place_modify(jnp.array(x)) # Raises error when we cast input to jnp.ndarray\n+++ {\"id\": \"RGqVfYSpc49s\"}\n-Helpfully, the error points us to JAX's side-effect-free way of doing the same thing via the [`jax.ops.index_*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-operators) ops. They are analogous to in-place modification by index, but create a new array with the corresponding modifications made:\n+Helpfully, the error points us to JAX's side-effect-free way of doing the same thing via the [`jax.ops.*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-operators) index update operators (be careful [`jax.ops.index_*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-functions-deprecated) functions are deprecated). They are analogous to in-place modification by index, but create a new array with the corresponding modifications made:\n```{code-cell}\n:id: Rmklk6BB2xF0\ndef jax_in_place_modify(x):\n- return jax.ops.index_update(x, 0, 123)\n+ return x.at[0].set(123)\ny = jnp.array([1, 2, 3])\njax_in_place_modify(y)\n@@ -280,7 +280,7 @@ y\nSide-effect-free code is sometimes called *functionally pure*, or just *pure*.\n-Isn't the pure version less efficient? Strictly, yes; we are creating a new array. However, as we will explain in the next guide, JAX computations are often compiled before being run using another program transformation, `jax.jit`. If we don't use the old array after modifying it 'in place' using `jax.ops.index_update()`, the compiler can recognise that it can in fact compile to an in-place modify, resulting in efficient code in the end.\n+Isn't the pure version less efficient? Strictly, yes; we are creating a new array. However, as we will explain in the next guide, JAX computations are often compiled before being run using another program transformation, `jax.jit`. If we don't use the old array after modifying it 'in place' using indexed update operators, the compiler can recognise that it can in fact compile to an in-place modify, resulting in efficient code in the end.\nOf course, it's possible to mix side-effectful Python code and functionally pure JAX code, and we will touch on this more later. As you get more familiar with JAX, you will learn how and when this can work. As a rule of thumb, however, any functions intended to be transformed by JAX should avoid side-effects, and the JAX primitives themselves will try to help you do that.\n"
}
] | Python | Apache License 2.0 | google/jax | replace deprecated jax.ops.index_* functions with the new index update operators |
260,377 | 29.12.2021 12:29:16 | -10,800 | 504728d8b65d3219cb26fc6400f775afac53361b | link directly to the documentation for the jnp.ndarray.at property | [
{
"change_type": "MODIFY",
"old_path": "docs/jax-101/01-jax-basics.ipynb",
"new_path": "docs/jax-101/01-jax-basics.ipynb",
"diff": "\"\\u001b[0;32m<ipython-input-12-709e2d7ddd3f>\\u001b[0m in \\u001b[0;36m<module>\\u001b[0;34m()\\u001b[0m\\n\\u001b[0;32m----> 1\\u001b[0;31m \\u001b[0min_place_modify\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mjnp\\u001b[0m\\u001b[0;34m.\\u001b[0m\\u001b[0marray\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mx\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m)\\u001b[0m \\u001b[0;31m# Raises error when we cast input to jnp.ndarray\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[0m\",\n\"\\u001b[0;32m<ipython-input-11-fce65eb843c7>\\u001b[0m in \\u001b[0;36min_place_modify\\u001b[0;34m(x)\\u001b[0m\\n\\u001b[1;32m 4\\u001b[0m \\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 5\\u001b[0m \\u001b[0;32mdef\\u001b[0m \\u001b[0min_place_modify\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mx\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m:\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[0;32m----> 6\\u001b[0;31m \\u001b[0mx\\u001b[0m\\u001b[0;34m[\\u001b[0m\\u001b[0;36m0\\u001b[0m\\u001b[0;34m]\\u001b[0m \\u001b[0;34m=\\u001b[0m \\u001b[0;36m123\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[0m\\u001b[1;32m 7\\u001b[0m \\u001b[0;32mreturn\\u001b[0m \\u001b[0;32mNone\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 8\\u001b[0m \\u001b[0;34m\\u001b[0m\\u001b[0m\\n\",\n\"\\u001b[0;32m/usr/local/lib/python3.7/dist-packages/jax/_src/numpy/lax_numpy.py\\u001b[0m in \\u001b[0;36m_unimplemented_setitem\\u001b[0;34m(self, i, x)\\u001b[0m\\n\\u001b[1;32m 6594\\u001b[0m \\u001b[0;34m\\\"or another .at[] method: \\\"\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 6595\\u001b[0m \\\"https://jax.readthedocs.io/en/latest/jax.ops.html\\\")\\n\\u001b[0;32m-> 6596\\u001b[0;31m \\u001b[0;32mraise\\u001b[0m \\u001b[0mTypeError\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mmsg\\u001b[0m\\u001b[0;34m.\\u001b[0m\\u001b[0mformat\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mtype\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mself\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[0m\\u001b[1;32m 6597\\u001b[0m \\u001b[0;34m\\u001b[0m\\u001b[0m\\n\\u001b[1;32m 6598\\u001b[0m \\u001b[0;32mdef\\u001b[0m \\u001b[0m_operator_round\\u001b[0m\\u001b[0;34m(\\u001b[0m\\u001b[0mnumber\\u001b[0m\\u001b[0;34m,\\u001b[0m \\u001b[0mndigits\\u001b[0m\\u001b[0;34m=\\u001b[0m\\u001b[0;32mNone\\u001b[0m\\u001b[0;34m)\\u001b[0m\\u001b[0;34m:\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0;34m\\u001b[0m\\u001b[0m\\n\",\n- \"\\u001b[0;31mTypeError\\u001b[0m: '<class 'jaxlib.xla_extension.DeviceArray'>' object does not support item assignment. JAX arrays are immutable. Instead of ``x[idx] = y``, use ``x = x.at[idx].set(y)`` or another .at[] method: https://jax.readthedocs.io/en/latest/jax.ops.html\"\n+ \"\\u001b[0;31mTypeError\\u001b[0m: '<class 'jaxlib.xla_extension.DeviceArray'>' object does not support item assignment. JAX arrays are immutable. Instead of ``x[idx] = y``, use ``x = x.at[idx].set(y)`` or another .at[] method: https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html\"\n]\n}\n],\n\"id\": \"RGqVfYSpc49s\"\n},\n\"source\": [\n- \"Helpfully, the error points us to JAX's side-effect-free way of doing the same thing via the [`jax.ops.*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-operators) index update operators (be careful [`jax.ops.index_*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-functions-deprecated) functions are deprecated). They are analogous to in-place modification by index, but create a new array with the corresponding modifications made:\"\n+ \"Helpfully, the error points us to JAX's side-effect-free way of doing the same thing via the [`jax.numpy.ndarray.at`](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html) index update operators (be careful [`jax.ops.index_*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-functions-deprecated) functions are deprecated). They are analogous to in-place modification by index, but create a new array with the corresponding modifications made:\"\n]\n},\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax-101/01-jax-basics.md",
"new_path": "docs/jax-101/01-jax-basics.md",
"diff": "@@ -254,7 +254,7 @@ in_place_modify(jnp.array(x)) # Raises error when we cast input to jnp.ndarray\n+++ {\"id\": \"RGqVfYSpc49s\"}\n-Helpfully, the error points us to JAX's side-effect-free way of doing the same thing via the [`jax.ops.*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-operators) index update operators (be careful [`jax.ops.index_*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-functions-deprecated) functions are deprecated). They are analogous to in-place modification by index, but create a new array with the corresponding modifications made:\n+Helpfully, the error points us to JAX's side-effect-free way of doing the same thing via the [`jax.numpy.ndarray.at`](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html) index update operators (be careful [`jax.ops.index_*`](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-functions-deprecated) functions are deprecated). They are analogous to in-place modification by index, but create a new array with the corresponding modifications made:\n```{code-cell}\n:id: Rmklk6BB2xF0\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -6669,7 +6669,7 @@ def _unimplemented_setitem(self, i, x):\nmsg = (\"'{}' object does not support item assignment. JAX arrays are \"\n\"immutable. Instead of ``x[idx] = y``, use ``x = x.at[idx].set(y)`` \"\n\"or another .at[] method: \"\n- \"https://jax.readthedocs.io/en/latest/jax.ops.html\")\n+ \"https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html\")\nraise TypeError(msg.format(type(self)))\ndef _operator_round(number, ndigits=None):\n"
}
] | Python | Apache License 2.0 | google/jax | link directly to the documentation for the jnp.ndarray.at property |
260,652 | 29.10.2021 00:33:40 | -19,080 | 03adf8cc8922016d37e6187c1d33203e7597afe9 | support null shape in jax.random.poisson | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/random.py",
"new_path": "jax/_src/random.py",
"diff": "@@ -1109,20 +1109,21 @@ def _poisson(key, lam, shape, dtype):\ndef poisson(key: KeyArray,\nlam: RealArray,\n- shape: Sequence[int] = (),\n+ shape: Optional[Sequence[int]] = None,\ndtype: DTypeLikeInt = dtypes.int_) -> jnp.ndarray:\n\"\"\"Sample Poisson random values with given shape and integer dtype.\nArgs:\nkey: a PRNG key used as the random key.\n- lam: rate parameter (mean of the distribution), must be >= 0.\n+ lam: rate parameter (mean of the distribution), must be >= 0. Must be broadcast-compatible with ``shape``\nshape: optional, a tuple of nonnegative integers representing the result\n- shape. Default ().\n+ shape. Default (None) produces a result shape equal to ``lam.shape``.\ndtype: optional, a integer dtype for the returned values (default int64 if\njax_enable_x64 is true, otherwise int32).\nReturns:\n- A random array with the specified shape and dtype.\n+ A random array with the specified dtype and with shape given by ``shape`` if\n+ ``shape is not None, or else by ``lam.shape``.\n\"\"\"\nkey, _ = _check_prng_key(key)\nif key.impl is not prng.threefry_prng_impl:\n@@ -1130,8 +1131,10 @@ def poisson(key: KeyArray,\n'`poisson` is only implemented for the threefry2x32 RNG, '\nf'not {key.impl}')\ndtype = dtypes.canonicalize_dtype(dtype)\n+ if shape is not None:\nshape = core.canonicalize_shape(shape)\n- if np.shape(lam) != shape:\n+ else:\n+ shape = np.shape(lam)\nlam = jnp.broadcast_to(lam, shape)\nlam = lax.convert_element_type(lam, np.float32)\nreturn _poisson(key, lam, shape, dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -730,6 +730,12 @@ class LaxRandomTest(jtu.JaxTestCase):\nself._CheckChiSquared(samples[:10000], scipy.stats.poisson(2.0).pmf)\nself._CheckChiSquared(samples[10000:], scipy.stats.poisson(20.0).pmf)\n+ def testPoissonWithoutShape(self):\n+ key = self.seed_prng(1)\n+ lam = 2 * jnp.ones(10000)\n+ samples = random.poisson(key, lam)\n+ self._CheckChiSquared(samples, scipy.stats.poisson(2.0).pmf)\n+\ndef testPoissonShape(self):\nkey = self.seed_prng(0)\nx = random.poisson(key, np.array([2.0, 20.0]), shape=(3, 2))\n"
}
] | Python | Apache License 2.0 | google/jax | support null shape in jax.random.poisson |
260,695 | 21.12.2021 13:59:30 | -3,600 | b810e8be88c7bb4459e65ad271e6ca49a1c0b917 | Add `where=` arg to jax.nn.{softmax, log_softmax, normalize}.
This change adds a `where=` argument (analogous to `jnp.sum`) that can be used to specify which elements to include in the calculation. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/nn/functions.py",
"new_path": "jax/_src/nn/functions.py",
"diff": "@@ -261,7 +261,10 @@ def glu(x: Array, axis: int = -1) -> Array:\nlogsumexp = _logsumexp\n-def log_softmax(x: Array, axis: Optional[Union[int, Tuple[int, ...]]] = -1) -> Array:\n+def log_softmax(x: Array,\n+ axis: Optional[Union[int, Tuple[int, ...]]] = -1,\n+ where: Optional[Array] = None,\n+ initial: Optional[Array] = None) -> Array:\nr\"\"\"Log-Softmax function.\nComputes the logarithm of the :code:`softmax` function, which rescales\n@@ -275,11 +278,21 @@ def log_softmax(x: Array, axis: Optional[Union[int, Tuple[int, ...]]] = -1) -> A\nx : input array\naxis: the axis or axes along which the :code:`log_softmax` should be\ncomputed. Either an integer or a tuple of integers.\n+ where: Elements to include in the :code:`log_softmax`.\n+ initial: The minimum value used to shift the input array. Must be present\n+ when :code:`where` is not None.\n\"\"\"\n- shifted = x - lax.stop_gradient(x.max(axis, keepdims=True))\n- return shifted - jnp.log(jnp.sum(jnp.exp(shifted), axis, keepdims=True))\n+ x_max = jnp.max(x, axis, where=where, initial=initial, keepdims=True)\n+ shifted = x - lax.stop_gradient(x_max)\n+ shifted_logsumexp = jnp.log(\n+ jnp.sum(jnp.exp(shifted), axis, where=where, keepdims=True))\n+ return shifted - shifted_logsumexp\n+\n-def softmax(x: Array, axis: Optional[Union[int, Tuple[int, ...]]] = -1) -> Array:\n+def softmax(x: Array,\n+ axis: Optional[Union[int, Tuple[int, ...]]] = -1,\n+ where: Optional[Array] = None,\n+ initial: Optional[Array] = None) -> Array:\nr\"\"\"Softmax function.\nComputes the function which rescales elements to the range :math:`[0, 1]`\n@@ -293,24 +306,30 @@ def softmax(x: Array, axis: Optional[Union[int, Tuple[int, ...]]] = -1) -> Array\naxis: the axis or axes along which the softmax should be computed. The\nsoftmax output summed across these dimensions should sum to :math:`1`.\nEither an integer or a tuple of integers.\n+ where: Elements to include in the :code:`softmax`.\n+ initial: The minimum value used to shift the input array. Must be present\n+ when :code:`where` is not None.\n\"\"\"\n- unnormalized = jnp.exp(x - lax.stop_gradient(x.max(axis, keepdims=True)))\n- return unnormalized / unnormalized.sum(axis, keepdims=True)\n+ x_max = jnp.max(x, axis, where=where, initial=initial, keepdims=True)\n+ unnormalized = jnp.exp(x - lax.stop_gradient(x_max))\n+ return unnormalized / jnp.sum(unnormalized, axis, where=where, keepdims=True)\ndef normalize(x: Array,\naxis: Optional[Union[int, Tuple[int, ...]]] = -1,\nmean: Optional[Array] = None,\nvariance: Optional[Array] = None,\n- epsilon: Array = 1e-5) -> Array:\n+ epsilon: Array = 1e-5,\n+ where: Optional[Array] = None) -> Array:\n\"\"\"Normalizes an array by subtracting mean and dividing by sqrt(var).\"\"\"\nif mean is None:\n- mean = jnp.mean(x, axis, keepdims=True)\n+ mean = jnp.mean(x, axis, keepdims=True, where=where)\nif variance is None:\n# this definition is traditionally seen as less accurate than jnp.var's\n# mean((x - mean(x))**2) but may be faster and even, given typical\n# activation distributions and low-precision arithmetic, more accurate\n# when used in neural network normalization layers\n- variance = jnp.mean(jnp.square(x), axis, keepdims=True) - jnp.square(mean)\n+ variance = jnp.mean(\n+ jnp.square(x), axis, keepdims=True, where=where) - jnp.square(mean)\nreturn (x - mean) * lax.rsqrt(variance + epsilon)\ndef one_hot(x: Array, num_classes: int, *,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/nn_test.py",
"new_path": "tests/nn_test.py",
"diff": "@@ -123,6 +123,28 @@ class NNFunctionsTest(jtu.JaxTestCase):\nwith jax.enable_checks(False): # With checks we materialize the array\njax.make_jaxpr(lambda: nn.hard_tanh(jnp.ones((10 ** 12,)))) # don't oom\n+ @parameterized.parameters([nn.softmax, nn.log_softmax])\n+ def testSoftmaxWhereMask(self, fn):\n+ x = jnp.array([5.5, 1.3, -4.2, 0.9])\n+ m = jnp.array([True, False, True, True])\n+ x_filtered = jnp.take(x, jnp.array([0, 2, 3]))\n+\n+ out_masked = jnp.take(\n+ fn(x, where=m, initial=-jnp.inf), jnp.array([0, 2, 3]))\n+ out_filtered = fn(x_filtered)\n+\n+ self.assertAllClose(out_masked, out_filtered)\n+\n+ def testNormalizeWhereMask(self):\n+ x = jnp.array([5.5, 1.3, -4.2, 0.9])\n+ m = jnp.array([True, False, True, True])\n+ x_filtered = jnp.take(x, jnp.array([0, 2, 3]))\n+\n+ out_masked = jnp.take(nn.normalize(x, where=m), jnp.array([0, 2, 3]))\n+ out_filtered = nn.normalize(x_filtered)\n+\n+ self.assertAllClose(out_masked, out_filtered)\n+\ndef testOneHot(self):\nactual = nn.one_hot(jnp.array([0, 1, 2]), 3)\nexpected = jnp.array([[1., 0., 0.],\n"
}
] | Python | Apache License 2.0 | google/jax | Add `where=` arg to jax.nn.{softmax, log_softmax, normalize}.
This change adds a `where=` argument (analogous to `jnp.sum`) that can be used to specify which elements to include in the calculation. |
260,424 | 20.12.2021 15:56:50 | 0 | bbd127f8fa128bf686d858a6639d6527289891af | Add division by zero check. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/checkify.py",
"new_path": "jax/experimental/checkify.py",
"diff": "@@ -279,6 +279,14 @@ def gather_error_check(error, operand, start_indices, *,\nreturn out, assert_func(error, all_inbounds, msg)\nerror_checks[lax.gather_p] = gather_error_check\n+def div_error_check(error, x, y):\n+ \"\"\"Checks for division by zero and NaN.\"\"\"\n+ all_nonzero = jnp.logical_not(jnp.any(jnp.equal(y, 0)))\n+ msg = f'divided by zero at {summary()}'\n+ div_by_zero_err = assert_func(error, all_nonzero, msg)\n+ return nan_error_check(lax.div_p, div_by_zero_err, x, y)\n+error_checks[lax.div_p] = div_error_check\n+\ndef cond_error_check(error, index, *ops, branches, linear):\nnew_branches, msgs_ = unzip2(checkify_jaxpr(jxpr, error) for jxpr in branches)\nnew_linear = (False, False, *linear)\n@@ -418,7 +426,6 @@ add_nan_check(lax.integer_pow_p)\nadd_nan_check(lax.tanh_p)\nadd_nan_check(lax.log_p)\nadd_nan_check(lax.atan2_p)\n-add_nan_check(lax.div_p)\nadd_nan_check(lax.sin_p)\nadd_nan_check(lax.cos_p)\nadd_nan_check(lax.sinh_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -66,6 +66,26 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\n+ for jit in [False, True]))\n+ def test_jit_div_errors(self, jit):\n+ def f(x, y):\n+ return x/y\n+\n+ f = jax.jit(f) if jit else f\n+\n+ err, _ = checkify.checkify(f)(jnp.ones((3,)), jnp.ones((3,)))\n+ self.assertIs(err.get(), None)\n+\n+ err, _ = checkify.checkify(f)(jnp.ones((3,)), jnp.array([1, 0, 1]))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"divided by zero\")\n+\n+ err, _ = checkify.checkify(f)(jnp.array([1, jnp.inf, 1]), jnp.array([1, jnp.inf, 1]))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), 'nan generated by primitive div')\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\nfor jit in [False, True]))\n@@ -192,7 +212,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, (ch_out_carry, ch_outs) = checkify.checkify(f)(carry, xs)\nout_carry, outs = f(carry, xs)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertStartsWith(err.get(), \"divided by zero\")\nself.assertArraysEqual(ch_outs, outs)\nself.assertArraysEqual(ch_out_carry, out_carry)\n@@ -201,7 +221,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, (ch_out_carry, ch_outs) = checkify.checkify(f)(carry, xs)\nout_carry, outs = f(carry, xs)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertStartsWith(err.get(), \"divided by zero\")\nself.assertArraysEqual(ch_outs, outs)\nself.assertArraysEqual(ch_out_carry, out_carry)\n@@ -230,7 +250,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, ch_out = checkify.checkify(f)(init_val)\nout = f(init_val)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertStartsWith(err.get(), \"divided by zero\")\nself.assertArraysEqual(ch_out, out)\n@jtu.skip_on_devices(\"tpu\")\n@@ -256,7 +276,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, ch_out = checkify.checkify(f)(init_val)\nout = f(init_val)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertStartsWith(err.get(), \"divided by zero\")\nself.assertArraysEqual(ch_out, out)\n@jtu.skip_on_devices(\"tpu\")\n@@ -274,13 +294,13 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ninit_val = 0.\nerr, _ = checkify.checkify(f)(init_val)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertStartsWith(err.get(), \"divided by zero\")\n# error on second cond\ninit_val = 1.\nerr, _ = checkify.checkify(f)(init_val)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertStartsWith(err.get(), \"divided by zero\")\n@jtu.skip_on_devices(\"tpu\")\ndef test_while_loop_body_and_cond_error(self):\n"
}
] | Python | Apache License 2.0 | google/jax | Add division by zero check. |
260,689 | 19.11.2021 21:21:46 | -3,600 | 2c5fe8c40d8b530701c1088ea3446b07d844ce46 | Implement SciPy's RegularGridInterpolator
Resolves . | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/_src/scipy/interpolate/__init__.py",
"diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/_src/third_party/scipy/LICENSE.txt",
"diff": "+Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers.\n+All rights reserved.\n+\n+Redistribution and use in source and binary forms, with or without\n+modification, are permitted provided that the following conditions\n+are met:\n+\n+1. Redistributions of source code must retain the above copyright\n+ notice, this list of conditions and the following disclaimer.\n+\n+2. Redistributions in binary form must reproduce the above\n+ copyright notice, this list of conditions and the following\n+ disclaimer in the documentation and/or other materials provided\n+ with the distribution.\n+\n+3. Neither the name of the copyright holder nor the names of its\n+ contributors may be used to endorse or promote products derived\n+ from this software without specific prior written permission.\n+\n+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n+\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
},
{
"change_type": "ADD",
"old_path": "jax/_src/third_party/scipy/__init__.py",
"new_path": "jax/_src/third_party/scipy/__init__.py",
"diff": ""
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/_src/third_party/scipy/interpolate.py",
"diff": "+from itertools import product\n+import scipy.interpolate as osp_interpolate\n+\n+from jax._src.tree_util import register_pytree_node\n+from jax._src.numpy.lax_numpy import (_check_arraylike, _promote_dtypes_inexact,\n+ asarray, broadcast_arrays, can_cast,\n+ empty, nan, searchsorted, where, zeros)\n+from jax._src.numpy.util import _wraps\n+\n+\n+def _ndim_coords_from_arrays(points, ndim=None):\n+ \"\"\"Convert a tuple of coordinate arrays to a (..., ndim)-shaped array.\"\"\"\n+ if isinstance(points, tuple) and len(points) == 1:\n+ # handle argument tuple\n+ points = points[0]\n+ if isinstance(points, tuple):\n+ p = broadcast_arrays(*points)\n+ for p_other in p[1:]:\n+ if p_other.shape != p[0].shape:\n+ raise ValueError(\"coordinate arrays do not have the same shape\")\n+ points = empty(p[0].shape + (len(points),), dtype=float)\n+ for j, item in enumerate(p):\n+ points = points.at[..., j].set(item)\n+ else:\n+ _check_arraylike(\"_ndim_coords_from_arrays\", points)\n+ points = asarray(points) # SciPy: asanyarray(points)\n+ if points.ndim == 1:\n+ if ndim is None:\n+ points = points.reshape(-1, 1)\n+ else:\n+ points = points.reshape(-1, ndim)\n+ return points\n+\n+\n+@_wraps(\n+ osp_interpolate.RegularGridInterpolator,\n+ lax_description=\"\"\"\n+In the JAX version, `bounds_error` defaults to and must always be `False` since no\n+bound error may be raised under JIT.\n+\n+Furthermore, in contrast to SciPy no input validation is performed.\n+\"\"\")\n+class RegularGridInterpolator:\n+ # Based on SciPy's implementation which in turn is originally based on an\n+ # implementation by Johannes Buchner\n+\n+ def __init__(self,\n+ points,\n+ values,\n+ method=\"linear\",\n+ bounds_error=False,\n+ fill_value=nan):\n+ if method not in (\"linear\", \"nearest\"):\n+ raise ValueError(f\"method {method!r} is not defined\")\n+ self.method = method\n+ self.bounds_error = bounds_error\n+ if self.bounds_error:\n+ raise NotImplementedError(\"`bounds_error` takes no effect under JIT\")\n+\n+ _check_arraylike(\"RegularGridInterpolator\", values)\n+ if len(points) > values.ndim:\n+ ve = f\"there are {len(points)} point arrays, but values has {values.ndim} dimensions\"\n+ raise ValueError(ve)\n+\n+ values, = _promote_dtypes_inexact(values)\n+\n+ if fill_value is not None:\n+ _check_arraylike(\"RegularGridInterpolator\", fill_value)\n+ fill_value = asarray(fill_value)\n+ if not can_cast(fill_value.dtype, values.dtype, casting='same_kind'):\n+ ve = \"fill_value must be either 'None' or of a type compatible with values\"\n+ raise ValueError(ve)\n+ self.fill_value = fill_value\n+\n+ # TODO: assert sanity of `points` similar to SciPy but in a JIT-able way\n+ _check_arraylike(\"RegularGridInterpolator\", *points)\n+ self.grid = tuple(asarray(p) for p in points)\n+ self.values = values\n+\n+ @_wraps(osp_interpolate.RegularGridInterpolator.__call__, update_doc=False)\n+ def __call__(self, xi, method=None):\n+ method = self.method if method is None else method\n+ if method not in (\"linear\", \"nearest\"):\n+ raise ValueError(f\"method {method!r} is not defined\")\n+\n+ ndim = len(self.grid)\n+ xi = _ndim_coords_from_arrays(xi, ndim=ndim)\n+ if xi.shape[-1] != len(self.grid):\n+ raise ValueError(\"the requested sample points xi have dimension\"\n+ f\" {xi.shape[1]}, but this RegularGridInterpolator has\"\n+ f\" dimension {ndim}\")\n+\n+ xi_shape = xi.shape\n+ xi = xi.reshape(-1, xi_shape[-1])\n+\n+ indices, norm_distances, out_of_bounds = self._find_indices(xi.T)\n+ if method == \"linear\":\n+ result = self._evaluate_linear(indices, norm_distances)\n+ elif method == \"nearest\":\n+ result = self._evaluate_nearest(indices, norm_distances)\n+ else:\n+ raise AssertionError(\"method must be bound\")\n+ if not self.bounds_error and self.fill_value is not None:\n+ bc_shp = result.shape[:1] + (1,) * (result.ndim - 1)\n+ result = where(out_of_bounds.reshape(bc_shp), self.fill_value, result)\n+\n+ return result.reshape(xi_shape[:-1] + self.values.shape[ndim:])\n+\n+ def _evaluate_linear(self, indices, norm_distances):\n+ # slice for broadcasting over trailing dimensions in self.values\n+ vslice = (slice(None),) + (None,) * (self.values.ndim - len(indices))\n+\n+ # find relevant values\n+ # each i and i+1 represents a edge\n+ edges = product(*[[i, i + 1] for i in indices])\n+ values = asarray(0.)\n+ for edge_indices in edges:\n+ weight = asarray(1.)\n+ for ei, i, yi in zip(edge_indices, indices, norm_distances):\n+ weight *= where(ei == i, 1 - yi, yi)\n+ values += self.values[edge_indices] * weight[vslice]\n+ return values\n+\n+ def _evaluate_nearest(self, indices, norm_distances):\n+ idx_res = [\n+ where(yi <= .5, i, i + 1) for i, yi in zip(indices, norm_distances)\n+ ]\n+ return self.values[tuple(idx_res)]\n+\n+ def _find_indices(self, xi):\n+ # find relevant edges between which xi are situated\n+ indices = []\n+ # compute distance to lower edge in unity units\n+ norm_distances = []\n+ # check for out of bounds xi\n+ out_of_bounds = zeros((xi.shape[1],), dtype=bool)\n+ # iterate through dimensions\n+ for x, g in zip(xi, self.grid):\n+ i = searchsorted(g, x) - 1\n+ i = where(i < 0, 0, i)\n+ i = where(i > g.size - 2, g.size - 2, i)\n+ indices.append(i)\n+ norm_distances.append((x - g[i]) / (g[i + 1] - g[i]))\n+ if not self.bounds_error:\n+ out_of_bounds += x < g[0]\n+ out_of_bounds += x > g[-1]\n+ return indices, norm_distances, out_of_bounds\n+\n+\n+register_pytree_node(\n+ RegularGridInterpolator,\n+ lambda obj: ((obj.grid, obj.values, obj.fill_value),\n+ (obj.method, obj.bounds_error)),\n+ lambda aux, children: RegularGridInterpolator(\n+ *children[:2], # type: ignore[index]\n+ *aux,\n+ *children[2:]), # type: ignore[index]\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/__init__.py",
"new_path": "jax/scipy/__init__.py",
"diff": "# limitations under the License.\n# flake8: noqa: F401\n+from jax.scipy import interpolate as interpolate\nfrom jax.scipy import linalg as linalg\nfrom jax.scipy import ndimage as ndimage\nfrom jax.scipy import signal as signal\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/scipy/interpolate/__init__.py",
"diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+# flake8: noqa: F401\n+\n+# Already deprecate namespaces that will be removed in SciPy v2.0.0\n+\n+from jax._src.third_party.scipy.interpolate import (RegularGridInterpolator as\n+ RegularGridInterpolator)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/scipy_interpolate.py",
"diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from absl.testing import absltest, parameterized\n+\n+import operator\n+from functools import reduce\n+import numpy as np\n+\n+from jax._src import test_util as jtu\n+import scipy.interpolate as sp_interp\n+import jax.scipy.interpolate as jsp_interp\n+\n+from jax.config import config\n+\n+config.parse_flags_with_absl()\n+\n+\n+class LaxBackedScipyInterpolateTests(jtu.JaxTestCase):\n+ \"\"\"Tests for LAX-backed scipy.interpolate implementations\"\"\"\n+\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\": f\"_spaces={spaces}_method={method}\",\n+ \"spaces\": spaces,\n+ \"method\": method\n+ }\n+ for spaces in (((0., 10., 10),), ((-15., 20., 12),\n+ (3., 4., 24)))\n+ for method in (\"linear\", \"nearest\")))\n+ def testRegularGridInterpolator(self, spaces, method):\n+ rng = jtu.rand_default(self.rng())\n+ scipy_fun = lambda init_args, call_args: sp_interp.RegularGridInterpolator(\n+ *init_args[:2], method, False, *init_args[2:])(*call_args)\n+ lax_fun = lambda init_args, call_args: jsp_interp.RegularGridInterpolator(\n+ *init_args[:2], method, False, *init_args[2:])(*call_args)\n+\n+ def args_maker():\n+ points = tuple(map(lambda x: np.linspace(*x), spaces))\n+ values = rng(reduce(operator.add, tuple(map(np.shape, points))), float)\n+ fill_value = np.nan\n+\n+ init_args = (points, values, fill_value)\n+ n_validation_points = 50\n+ valid_points = tuple(\n+ map(\n+ lambda x: np.linspace(x[0] - 0.2 * (x[1] - x[0]), x[1] + 0.2 *\n+ (x[1] - x[0]), n_validation_points),\n+ spaces))\n+ valid_points = np.squeeze(np.stack(valid_points, axis=1))\n+ call_args = (valid_points,)\n+ return init_args, call_args\n+\n+ self._CheckAgainstNumpy(\n+ scipy_fun, lax_fun, args_maker, check_dtypes=False, tol=1e-4)\n+ self._CompileAndCheck(lax_fun, args_maker, rtol={np.float64: 1e-14})\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Implement SciPy's RegularGridInterpolator
Resolves #8572 . |
260,335 | 10.12.2021 23:22:11 | 28,800 | 4db899007b86f51da18940be35bf77575652e11f | add staging logic for polymorphic shapes in jaxprs | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -105,7 +105,7 @@ def _try_broadcast_shapes(shapes):\nif not rank: return () # scalar case\nresult_shape = [None] * rank\nfor i, sizes in enumerate(zip(*shapes)):\n- non_1s = set([d for d in sizes if not core.symbolic_equal_dim(d, 1)])\n+ non_1s = {d for d in sizes if not core.symbolic_equal_dim(d, 1)}\nif len(non_1s) > 1:\nreturn None # must have equal sizes other than 1-sized axes\nresult_shape[i] = next(iter(non_1s), 1)\n@@ -1355,11 +1355,19 @@ def _broadcasting_shape_rule(name, *avals):\nif len({len(shape) for shape in shapes}) != 1:\nmsg = '{}: arrays must have same number of dimensions, got {}.'\nraise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))\n- result_shape = _try_broadcast_shapes(shapes)\n- if result_shape is None:\n- msg = '{} got incompatible shapes for broadcasting: {}.'\n- raise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))\n- return result_shape\n+ result_shape = []\n+ for ds in zip(*shapes):\n+ if all(d is ds[0] for d in ds):\n+ # if all axes are identical objects, the resulting size is the object\n+ result_shape.append(ds[0])\n+ else:\n+ # if all dims are equal (or 1), the result is the non-1 size\n+ non_1s = {d for d in ds if not core.symbolic_equal_dim(d, 1)}\n+ if len(non_1s) > 1:\n+ raise TypeError(f'{name} got incompatible shapes for broadcasting: '\n+ f'{\", \".join(map(str, map(tuple, shapes)))}.')\n+ result_shape.append(non_1s.pop() if non_1s else 1)\n+ return tuple(result_shape)\ndef _naryop_weak_type_rule(name, *avals, **kwargs):\nif any(aval.dtype is dtypes.float0 for aval in avals):\n@@ -3401,7 +3409,8 @@ def _reduce_op_shape_rule(operand, *, axes, input_shape=None):\nraise ValueError(f\"duplicate value in 'axes' of reduction: {axes}\")\nif not all(0 <= a < operand.ndim for a in axes):\nraise ValueError(f\"reduction axes {axes} contains out-of-bounds indices for {operand}.\")\n- return tuple(np.delete(operand.shape, axes))\n+ axes = frozenset(axes)\n+ return tuple(d for i, d in enumerate(operand.shape) if i not in axes)\ndef _reduce_prod_translation_rule(ctx, avals_in, avals_out, operand, *, axes):\noperand_aval, = avals_in\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/utils.py",
"new_path": "jax/_src/lax/utils.py",
"diff": "@@ -66,6 +66,9 @@ def standard_abstract_eval(prim, shape_rule, dtype_rule, weak_type_rule,\nreturn core.ShapedArray(shape_rule(*avals, **kwargs),\ndtype_rule(*avals, **kwargs), weak_type=weak_type,\nnamed_shape=named_shape_rule(*avals, **kwargs))\n+ elif least_specialized is core.DShapedArray:\n+ return core.DShapedArray(shape_rule(*avals, **kwargs),\n+ dtype_rule(*avals, **kwargs), weak_type)\nelif least_specialized is core.UnshapedArray:\nreturn core.UnshapedArray(dtype_rule(*avals, **kwargs), weak_type=weak_type)\nelse:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1038,7 +1038,7 @@ def _short_dtype_name(dtype):\nclass UnshapedArray(AbstractValue):\n__slots__ = ['dtype', 'weak_type']\n- array_abstraction_level = 2\n+ array_abstraction_level = 3\ndef __init__(self, dtype, weak_type=False):\nself.dtype = np.dtype(dtype)\n@@ -1102,6 +1102,58 @@ class UnshapedArray(AbstractValue):\n\"UnshapedArray instances to ever be produced.\")\nraise TypeError(msg)\n+\n+# We have a convention of reusing AbsractValues as types, in particular reusing\n+# ShapedArrays as types, even though we could make a distinction and use\n+# abstract values during tracing only. This reuse becomes a bit more extreme\n+# with DShapedArrays. A DShapedArray's shape attribute is a tuple which can\n+# contain several different types: ints, other AbstractValues (specifically at\n+# the input and output to pe.trace_to_jaxpr_dynamic), Tracers (while tracing),\n+# or Vars (when used as jaxpr type annotations). We could reduce this\n+# polymorphism if it seems cleaner, though it's kind of convenient!\n+AxisSizeForTracing = Union[int, Tracer]\n+AxisSizeForJaxprType = Union[int, Var]\n+AxisSizeForJaxprTracingSpec = Union[int, AbstractValue]\n+AxisSize = Union[AxisSizeForTracing, AxisSizeForJaxprType,\n+ AxisSizeForJaxprTracingSpec]\n+\n+class DShapedArray(UnshapedArray):\n+ __slots__ = ['shape']\n+ shape: Tuple[AxisSize, ...] # see comment above\n+ array_abstraction_level = 2\n+\n+ def __init__(self, shape, dtype, weak_type):\n+ self.shape = shape\n+ self.dtype = dtype\n+ self.weak_type = weak_type\n+\n+ ndim = property(lambda self: len(self.shape))\n+ size = property(lambda self: prod(self.shape))\n+\n+ def str_short(self, short_dtypes=False) -> str:\n+ del short_dtypes # ignored\n+ shape = f'{\",\".join(str(d) for d in self.shape)}' if self.shape else ''\n+ dtype = _short_dtype_name(self.dtype)\n+ return f'{dtype}[{shape}]'\n+ __str__ = __repr__ = str_short\n+\n+ def __eq__(self, other):\n+ return (type(self) is type(other) and\n+ self.dtype == other.dtype and self.shape == other.shape and\n+ self.weak_type == other.weak_type)\n+\n+ def update(self, shape=None, dtype=None, weak_type=None):\n+ if shape is None:\n+ shape = self.shape\n+ if dtype is None:\n+ dtype = self.dtype\n+ if weak_type is None:\n+ weak_type = self.weak_type\n+ return DShapedArray(shape, dtype, weak_type)\n+\n+del AxisSize, AxisSizeForTracing, AxisSizeForJaxprType, \\\n+ AxisSizeForJaxprTracingSpec\n+\nclass ShapedArray(UnshapedArray):\n__slots__ = ['shape', 'named_shape']\narray_abstraction_level = 1\n@@ -2109,17 +2161,25 @@ class JaxprPpContext:\nself.var_ids = collections.defaultdict(it.count().__next__)\n-def pp_var(v: Var, context: JaxprPpContext):\n+def pp_var(v: Var, context: JaxprPpContext) -> str:\nif isinstance(v, (Literal, DropVar)): return str(v)\nreturn f\"{_encode_digits_alphabetic(context.var_ids[v])}{v.suffix}\"\n+def pp_aval(a: AbstractValue, context: JaxprPpContext) -> str:\n+ if isinstance(a, DShapedArray):\n+ shape = [pp_var(d, context) if type(d) is Var else str(d) for d in a.shape]\n+ dtype = _short_dtype_name(a.dtype)\n+ return f'{dtype}[{\",\".join(shape)}]'\n+ else:\n+ return a.str_short(short_dtypes=True)\n+\ndef pp_vars(vs: Sequence[Any], context: JaxprPpContext,\n*, separator=\"\", print_shapes: bool = False) -> pp.Doc:\nif print_shapes:\nreturn pp.nest(2, pp.group(\npp.join(pp.text(separator) + pp.group(pp.brk()), [\npp.text(pp_var(v, context)) +\n- pp.dim(pp.text(\":\" + v.aval.str_short(short_dtypes=True)))\n+ pp.dim(pp.text(\":\" + pp_aval(v.aval, context)))\nfor v in vs\n])\n))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -20,7 +20,7 @@ import inspect\nimport itertools as it\nimport operator as op\nfrom typing import (Any, Callable, Dict, NamedTuple, Optional, Sequence, Tuple,\n- List, Union, cast)\n+ List, Union, Set, cast)\nfrom weakref import ref\nimport numpy as np\n@@ -38,7 +38,7 @@ from jax._src.util import (unzip2, safe_zip, safe_map, toposort, split_list,\nfrom jax.core import (Trace, Tracer, Jaxpr, Literal, get_aval, AbstractValue,\nunit, unitvar, abstract_unit, ClosedJaxpr, new_jaxpr_eqn,\nConcreteArray, raise_to_shaped, Var, Atom,\n- JaxprEqn, Primitive)\n+ JaxprEqn, Primitive, DShapedArray)\nfrom jax._src import source_info_util\nfrom jax.config import config\n@@ -1188,17 +1188,20 @@ class JaxprStackFrame:\nself.eqns = [] # cleared when we pop frame from main\nself.invars = []\n- def to_jaxpr(self, in_tracers, out_tracers):\n- invars = [self.tracer_to_var[id(t)] for t in in_tracers]\n+ def to_jaxpr(self, out_tracers):\noutvars = [self.tracer_to_var[id(t)] for t in out_tracers]\nconstvars, constvals = unzip2(self.constvar_to_val.items())\n- jaxpr = Jaxpr(constvars, invars, outvars, self.eqns)\n+ jaxpr = Jaxpr(constvars, self.invars, outvars, self.eqns)\njaxpr, constvals = _const_folding_and_forwarding(jaxpr, constvals)\njaxpr, constvals = _inline_literals(jaxpr, constvals)\n- out_avals = [t.aval for t in out_tracers]\n- return jaxpr, out_avals, constvals\n+ return jaxpr, constvals\ndef newvar(self, aval):\n+ if isinstance(aval, DShapedArray):\n+ # this aval may have tracers in it, so we replace those with variables\n+ new_shape = [self.tracer_to_var[id(d)] if isinstance(d, Tracer) else d\n+ for d in aval.shape]\n+ aval = aval.update(shape=tuple(new_shape))\nreturn self.gensym(aval)\ndef find_progenitors(self, tracer):\n@@ -1260,7 +1263,7 @@ def _inline_literals(jaxpr, constvals):\n# prunes unused constants, and inserts `dropvar` symbols.\nconsts = dict(zip(jaxpr.constvars, constvals))\nnewvar = core.gensym()\n- newvars = {}\n+ newvars = {v: v for v in jaxpr.invars}\nvar = lambda v: newvars.get(v) or newvars.setdefault(v, newvar(v.aval))\ndef lit(var: Var) -> Optional[Any]:\n@@ -1274,7 +1277,6 @@ def _inline_literals(jaxpr, constvals):\nnew_constvars = [var(v) for v in jaxpr.constvars if v in used and not lit(v)]\nnew_constvals = [c for v, c in zip(jaxpr.constvars, constvals)\nif v in used and not lit(v)]\n- new_invars = [var(v) for v in jaxpr.invars]\nnew_eqns = []\nfor eqn in jaxpr.eqns:\ninvars = [lit(v) or var(v) for v in eqn.invars]\n@@ -1283,7 +1285,7 @@ def _inline_literals(jaxpr, constvals):\nnew_eqns.append(new_jaxpr_eqn(invars, outvars, eqn.primitive, eqn.params,\neqn.source_info))\nnew_outvars = [lit(v) or var(v) for v in jaxpr.outvars]\n- new_jaxpr = Jaxpr(new_constvars, new_invars, new_outvars, new_eqns)\n+ new_jaxpr = Jaxpr(new_constvars, jaxpr.invars, new_outvars, new_eqns)\nreturn new_jaxpr, new_constvals\nclass DynamicJaxprTrace(core.Trace):\n@@ -1349,22 +1351,29 @@ class DynamicJaxprTrace(core.Trace):\nreturn out_tracers if primitive.multiple_results else out_tracers.pop()\ndef process_call(self, call_primitive, f, tracers, params):\n- in_avals = [t.aval for t in tracers]\n+ dim_tracers = _get_tracers_only_in_shapes(tracers)\n+ in_avals = _tracers_to_avals({}, dim_tracers + tracers)\n+ keep_inputs = [False] * len(dim_tracers) + [True] * len(tracers)\nwith core.new_sublevel():\n- jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(f, self.main, in_avals)\n+ jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(\n+ f, self.main, in_avals, keep_inputs=keep_inputs)\nif params.get('inline', False):\n- return core.eval_jaxpr(jaxpr, consts, *tracers)\n+ return core.eval_jaxpr(jaxpr, consts, *dim_tracers, *tracers)\nsource_info = source_info_util.current()\n- out_tracers = [DynamicJaxprTracer(self, a, source_info) for a in out_avals]\n- invars = map(self.getvar, tracers)\n+ env = {id(t.aval): t for t in _get_tracers_in_shapes(set(), tracers)}\n+ subs = partial(_substitute_tracers_in_aval, env)\n+ out_tracers = [DynamicJaxprTracer(self, subs(a), source_info)\n+ for a in out_avals]\n+ invars = map(self.getvar, dim_tracers + tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\noutvars = map(self.makevar, out_tracers)\nnew_params = dict(params, call_jaxpr=convert_constvars_jaxpr(jaxpr))\nupdate_params = call_param_updaters.get(call_primitive)\nif update_params:\n+ # TODO(mattjj): update donated_invars to work with axis size variables\nnew_params = update_params(new_params, [True] * len(tracers))\n- eqn = new_jaxpr_eqn([*constvars, *invars], outvars, call_primitive,\n- new_params, source_info)\n+ eqn = new_jaxpr_eqn([*constvars, *invars], outvars,\n+ call_primitive, new_params, source_info)\nself.frame.eqns.append(eqn)\nreturn out_tracers\n@@ -1533,23 +1542,58 @@ def arg_info_flattened(flat_pos: List[int]) -> str:\n@profiler.annotate_function\ndef trace_to_jaxpr_dynamic(fun: lu.WrappedFun,\nin_avals: Sequence[AbstractValue],\n- debug_info: Optional[DebugInfo] = None):\n+ debug_info: Optional[DebugInfo] = None,\n+ *,\n+ keep_inputs: Optional[List[bool]] = None):\nwith core.new_main(DynamicJaxprTrace, dynamic=True) as main: # type: ignore\nmain.debug_info = debug_info # type: ignore\nmain.jaxpr_stack = () # type: ignore\n- jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)\n+ jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(\n+ fun, main, in_avals, keep_inputs=keep_inputs)\ndel main, fun\nreturn jaxpr, out_avals, consts\ndef trace_to_subjaxpr_dynamic(fun: lu.WrappedFun, main: core.MainTrace,\n- in_avals: Sequence[AbstractValue]):\n+ in_avals: Sequence[AbstractValue], *,\n+ keep_inputs: Optional[List[bool]] = None):\n+ # In general, the Tracers passed to ther Python callable underlying `fun` may\n+ # correspond to a subset of `in_avals` (i.e. a subset of the input binders in\n+ # the jaxpr). For example:\n+ #\n+ # n = core.DShapedArray((), jnp.dtype('int32'), weak_type=False)\n+ # a = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+ # b = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+ #\n+ # @lu.wrap_init\n+ # def f(x, y):\n+ # return x, y\n+ #\n+ # jaxpr, _, _ = pe.trace_to_jaxpr_dynamic(f, [n, a, b],\n+ # keep_inputs=[False, True, True])\n+ # print(jaxpr)\n+ # # { lambda ; a:i32[] b:f32[a] c:f32[a]. let in (b, c) }\n+ #\n+ # The abstract values passed to trace_to_jaxpr_dynamic are in direct\n+ # correspondence to the input binders (invars) of the jaxpr it returns. But in\n+ # general the Tracers passed to the function f correspond only to a subset of\n+ # those abstract values. That's because axis size variables may not be\n+ # explicit arguments to f, while we make everything explicit in the jaxpr.\n+ keep_inputs = [True] * len(in_avals) if keep_inputs is None else keep_inputs\n+\nframe = JaxprStackFrame()\nwith extend_jaxpr_stack(main, frame):\ntrace = DynamicJaxprTrace(main, core.cur_sublevel())\n- in_tracers = map(trace.new_arg, in_avals)\n- ans = fun.call_wrapped(*in_tracers)\n+ in_tracers = _avals_to_tracers(trace, in_avals)\n+ in_tracers_ = [t for t, keep in zip(in_tracers, keep_inputs) if keep]\n+ ans = fun.call_wrapped(*in_tracers_)\nout_tracers = map(trace.full_raise, ans)\n- jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)\n+ jaxpr, consts = frame.to_jaxpr(out_tracers)\n+\n+ # AbstractValue object id corresponds to a kind of name; we want out_avals\n+ # to refer to names bound in in_avals.\n+ tracerid_to_aval = {id(t): a for t, a in zip(in_tracers, in_avals)}\n+ out_avals = _tracers_to_avals(tracerid_to_aval, out_tracers)\n+\ndel fun, main, trace, frame, in_tracers, out_tracers, ans\nreturn jaxpr, out_avals, consts\n@@ -1581,3 +1625,77 @@ def partial_eval_to_jaxpr_dynamic(fun: lu.WrappedFun, in_pvals: Sequence[Partial\n# TODO(mattjj): alias to trace_to_jaxpr after revising custom_derivatives.py\nwith core.new_main(core.EvalTrace, dynamic=True) as _: # type: ignore\nreturn trace_to_jaxpr(fun, in_pvals)\n+\n+\n+AvalId = int\n+TracerId = int\n+def _avals_to_tracers(\n+ trace: DynamicJaxprTrace, in_avals: Sequence[AbstractValue]\n+ ) -> Sequence[Tracer]:\n+ # Create input Tracers given input abstract values, handling nesting: each\n+ # element `a` of `in_avals` can have abstract values in its shape, which must\n+ # occur to the left of `a`.\n+ env: Dict[AvalId, Tracer] = {}\n+ in_tracers: List[Tracer] = []\n+ for a in in_avals:\n+ t = env[id(a)] = trace.new_arg(_substitute_tracers_in_aval(env, a))\n+ in_tracers.append(t)\n+ return in_tracers\n+\n+def _substitute_tracers_in_aval(\n+ env: Dict[AvalId, Tracer], a: AbstractValue\n+ ) -> AbstractValue:\n+ # Substitute Tracers into a given AbstractValue using the given environment.\n+ # That is, the input is an AbstractValue possibly containing AbstractValues,\n+ # and the output is an aval possibly containing Tracers.\n+ if (isinstance(a, DShapedArray) and\n+ any(isinstance(d, AbstractValue) for d in a.shape)):\n+ shape = [env[id(d)] if isinstance(d, AbstractValue) else d for d in a.shape]\n+ return a.update(shape=tuple(shape))\n+ return a\n+\n+def _tracers_to_avals(\n+ env: Dict[TracerId, AbstractValue], tracers: Sequence[Tracer]\n+ ) -> List[AbstractValue]:\n+ # Replace Tracers with corresponding abstract values, handling Tracers in\n+ # shapes and ensuring each Tracer object is mapped to a single AbstractValue.\n+ avals: List[AbstractValue] = []\n+ for t in tracers:\n+ aval = env.get(id(t))\n+ if aval is None:\n+ aval = env[id(t)] = _subs_avals_in_aval(env, t.aval)\n+ avals.append(aval)\n+ return avals\n+\n+def _subs_avals_in_aval(\n+ env: Dict[TracerId, AbstractValue], a: AbstractValue\n+ ) -> AbstractValue:\n+ # Substitute AbstractValues into given AbstractValue using given environment.\n+ # That is, the input is an AbstractValue possibly containing Tracers and the\n+ # output is an AbstractValue possibly containing AbstractValues.\n+ if (isinstance(a, DShapedArray) and\n+ any(isinstance(d, Tracer) for d in a.shape)):\n+ shape = [env.setdefault(id(d), d.aval) if isinstance(d, Tracer) else d\n+ for d in a.shape]\n+ return a.update(shape=tuple(shape))\n+ else:\n+ return a\n+\n+def _get_tracers_only_in_shapes(in_tracers: Sequence[Tracer]) -> List[Tracer]:\n+ # In DynamicJaxprTrace.process_call (e.g. for handling jit-of-jit) we want to\n+ # extract Tracers from the shapes of arguments so as to elaborate them into\n+ # explicit inputs to the call that appears in the jaxpr. Some of these Tracers\n+ # may already appear as explicit inputs, so we only need to get those present\n+ # exclusively in shapes.\n+ return _get_tracers_in_shapes({id(t) for t in in_tracers}, in_tracers)\n+\n+def _get_tracers_in_shapes(seen: Set[TracerId], in_tracers: Sequence[Tracer]\n+ ) -> List[Tracer]:\n+ dim_tracers: List[Tracer] = []\n+ for t in in_tracers:\n+ if isinstance(t.aval, core.DShapedArray):\n+ for d in t.aval.shape:\n+ if isinstance(d, Tracer) and id(d) not in seen:\n+ seen.add(id(d))\n+ dim_tracers.append(d)\n+ return dim_tracers\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/core_test.py",
"new_path": "tests/core_test.py",
"diff": "@@ -27,6 +27,7 @@ import jax\nfrom jax import core\nfrom jax import lax\nfrom jax import numpy as jnp\n+from jax import linear_util as lu\nfrom jax._src import test_util as jtu\nfrom jax._src.abstract_arrays import make_shaped_array\nfrom jax import jvp, linearize, vjp, jit, make_jaxpr\n@@ -515,5 +516,115 @@ class JaxprTypeChecks(jtu.JaxTestCase):\nself.assertFalse(core.typecompat(aval1, aval3))\n+class DynamicShapesTest(jtu.JaxTestCase):\n+\n+ def test_staging_basic(self):\n+ n = core.ShapedArray((), jnp.dtype('int32'), weak_type=False)\n+ a = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+ b = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+\n+ @lu.wrap_init\n+ def f(x, y):\n+ return x, y\n+\n+ jaxpr, _, _ = pe.trace_to_jaxpr_dynamic(f, [n, a, b],\n+ keep_inputs=[False, True, True])\n+\n+ self.assertLen(jaxpr.invars, 3)\n+ self.assertEqual((jaxpr.invars[0],), jaxpr.invars[1].aval.shape)\n+ self.assertEqual((jaxpr.invars[0],), jaxpr.invars[2].aval.shape)\n+\n+ self.assertLen(jaxpr.outvars, 2)\n+ self.assertEqual((jaxpr.invars[0],), jaxpr.outvars[0].aval.shape)\n+ self.assertEqual((jaxpr.invars[0],), jaxpr.outvars[1].aval.shape)\n+\n+ def test_staging_nested(self):\n+ n = core.DShapedArray((), jnp.dtype('int32'), weak_type=False)\n+ a = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+ b = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+\n+ @lu.wrap_init\n+ def f(x, y):\n+ @jax.jit\n+ def g(x, y, z, w):\n+ return (x, w)\n+ return g(x, y, x, y)\n+\n+ jaxpr, _, _ = pe.trace_to_jaxpr_dynamic(f, [n, a, b],\n+ keep_inputs=[False, True, True])\n+\n+ self.assertLen(jaxpr.invars, 1 + 2) # one axis size var, two other inputs\n+ self.assertEqual((jaxpr.invars[0],), jaxpr.invars[1].aval.shape)\n+ self.assertEqual((jaxpr.invars[0],), jaxpr.invars[2].aval.shape)\n+\n+ self.assertLen(jaxpr.outvars, 2)\n+ self.assertEqual((jaxpr.invars[0],), jaxpr.outvars[0].aval.shape)\n+ self.assertEqual((jaxpr.invars[0],), jaxpr.outvars[1].aval.shape)\n+\n+ self.assertLen(jaxpr.eqns, 1)\n+ eqn = jaxpr.eqns[0]\n+ self.assertIsInstance(eqn.primitive, core.CallPrimitive)\n+ inner_jaxpr, _ = core.extract_call_jaxpr(eqn.primitive, eqn.params)\n+ self.assertIsInstance(inner_jaxpr, core.Jaxpr)\n+\n+ self.assertLen(inner_jaxpr.invars, 1 + 4) # one axis size var\n+ self.assertEqual((inner_jaxpr.invars[0],), inner_jaxpr.invars[1].aval.shape)\n+ self.assertEqual((inner_jaxpr.invars[0],), inner_jaxpr.invars[2].aval.shape)\n+ self.assertEqual((inner_jaxpr.invars[0],), inner_jaxpr.invars[3].aval.shape)\n+ self.assertEqual((inner_jaxpr.invars[0],), inner_jaxpr.invars[4].aval.shape)\n+\n+ def test_staging_nested_including_shape_arg(self):\n+ # This test covers the _get_tracers_only_in_shapes logic in partial_eval.py.\n+ n = core.DShapedArray((), jnp.dtype('int32'), weak_type=False)\n+ a = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+ b = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+\n+ @lu.wrap_init\n+ def f(x, y):\n+ @jax.jit\n+ def g(_, x, y, z, w):\n+ return (x, w)\n+ return g(x.shape[0], x, y, x, y)\n+\n+ jaxpr, _, _ = pe.trace_to_jaxpr_dynamic(f, [n, a, b],\n+ keep_inputs=[False, True, True])\n+\n+ self.assertLen(jaxpr.eqns, 1)\n+ eqn = jaxpr.eqns[0]\n+ self.assertIsInstance(eqn.primitive, core.CallPrimitive)\n+ inner_jaxpr, _ = core.extract_call_jaxpr(eqn.primitive, eqn.params)\n+ self.assertIsInstance(inner_jaxpr, core.Jaxpr)\n+\n+ self.assertLen(inner_jaxpr.invars, 1 + 4) # one axis size var\n+ self.assertEqual((inner_jaxpr.invars[0],), inner_jaxpr.invars[1].aval.shape)\n+ self.assertEqual((inner_jaxpr.invars[0],), inner_jaxpr.invars[2].aval.shape)\n+ self.assertEqual((inner_jaxpr.invars[0],), inner_jaxpr.invars[3].aval.shape)\n+ self.assertEqual((inner_jaxpr.invars[0],), inner_jaxpr.invars[4].aval.shape)\n+\n+ def test_staging_primitive_applications(self):\n+ n = core.DShapedArray((), jnp.dtype('int32'), weak_type=False)\n+ a = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+ b = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n+\n+ @lu.wrap_init\n+ def f(x, y):\n+ z = lax.mul(x, y)\n+ w = lax.sin(z)\n+ u = lax._reduce_sum(w, [0])\n+ return (u,)\n+\n+ jaxpr, _, _ = pe.trace_to_jaxpr_dynamic(f, [n, a, b],\n+ keep_inputs=[False, True, True])\n+\n+ self.assertLen(jaxpr.invars, 1 + 2) # one axis size var, two other inputs\n+ self.assertLen(jaxpr.eqns, 3)\n+ self.assertLen(jaxpr.eqns[0].outvars, 1)\n+ self.assertEqual(jaxpr.eqns[0].outvars[0].aval.shape,\n+ jaxpr.invars[1].aval.shape)\n+\n+ self.assertLen(jaxpr.outvars, 1)\n+ self.assertEqual(jaxpr.outvars[0].aval.shape, ())\n+\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | add staging logic for polymorphic shapes in jaxprs
Co-authored-by: Dougal Maclaurin <dougalm@google.com> |
260,335 | 05.01.2022 13:25:52 | 28,800 | 6ce38acca85791bb6f290cb65e1fdc1170e873e4 | remove axis name logic from Primitive / bind
Instead, just give AxisPrimitive its own bind function. This way the
logic is nicely separated by concerns. In addition, this factorization
will let us more easily experiment with other ways to find the top trace
(e.g. for assert_p in checkify). | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -260,7 +260,6 @@ class Primitive:\nmultiple_results = False # set for multi-output primitives\ncall_primitive = False # set for call primitives processed in final style\nmap_primitive = False # set for map primitives processed in final style\n- _dispatch_on_params = False # whether to include axis names from params in dispatch\ndef __init__(self, name: str):\nself.name = name\n@@ -268,14 +267,13 @@ class Primitive:\ndef __repr__(self):\nreturn '{}'.format(self.name)\n-\ndef bind(self, *args, **params):\nassert (not config.jax_enable_checks or\nall(isinstance(arg, Tracer) or valid_jaxtype(arg) for arg in args)), args\n- top_trace = find_top_trace(\n- args, used_axis_names(self, params) if self._dispatch_on_params else None)\n- tracers = map(top_trace.full_raise, args)\n- out = top_trace.process_primitive(self, tracers, params)\n+ return self.bind_with_trace(find_top_trace(args), args, params)\n+\n+ def bind_with_trace(self, trace, args, params):\n+ out = trace.process_primitive(self, map(trace.full_raise, args), params)\nreturn map(full_lower, out) if self.multiple_results else full_lower(out)\ndef def_impl(self, impl):\n@@ -879,17 +877,14 @@ def full_lower(val):\nelse:\nreturn val\n-def find_top_trace(xs, axis_names=None) -> Trace:\n- top_main: Optional[MainTrace] = None\n- if axis_names:\n- top_main = max((axis_frame(a).main_trace for a in axis_names),\n- default=None, key=lambda t: getattr(t, 'level', -1))\n+def find_top_trace(xs) -> Trace:\ntop_tracer = max((x for x in xs if isinstance(x, Tracer)),\ndefault=None, key=attrgetter('_trace.level'))\nif top_tracer is not None:\ntop_tracer._assert_live()\n- if top_tracer._trace.main.level > getattr(top_main, 'level', -1):\ntop_main = top_tracer._trace.main\n+ else:\n+ top_main = None # type: ignore\ndynamic = thread_local_state.trace_state.trace_stack.dynamic\ntop_main = (dynamic if top_main is None or dynamic.level > top_main.level\nelse top_main)\n@@ -1915,7 +1910,14 @@ axis_substitution_rules: Dict[Primitive, Callable[[ParamDict, AxisSubst, bool],\n# participate in dispatch should subclass AxisPrimitive.\nclass AxisPrimitive(Primitive):\n- _dispatch_on_params = True\n+ def bind(self, *args, **params):\n+ top_trace = find_top_trace(args)\n+ axis_main = max((axis_frame(a).main_trace for a in used_axis_names(self, params)),\n+ default=None, key=lambda t: getattr(t, 'level', -1))\n+ top_trace = (top_trace if not axis_main or axis_main.level < top_trace.level\n+ else axis_main.with_cur_sublevel())\n+ return self.bind_with_trace(top_trace, args, params)\n+\n# ------------------- Jaxpr checking -------------------\n"
}
] | Python | Apache License 2.0 | google/jax | remove axis name logic from Primitive / bind
Instead, just give AxisPrimitive its own bind function. This way the
logic is nicely separated by concerns. In addition, this factorization
will let us more easily experiment with other ways to find the top trace
(e.g. for assert_p in checkify). |
260,315 | 07.01.2022 12:06:23 | -3,600 | 6bf7b0d325c79f2cfede938b7ed1bbf9d0099199 | Fix host_callback docs
There was a missing ':' causing invalid rendering of the docs. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -229,7 +229,7 @@ Behavior under JAX autodiff transformations\n-------------------------------------------\nWhen used under a JAX autodiff transformation, the host callback functions\n-operate on the primal values only. Consider the following example:\n+operate on the primal values only. Consider the following example::\ndef power3(x):\ny = x * x\n"
}
] | Python | Apache License 2.0 | google/jax | Fix host_callback docs
There was a missing ':' causing invalid rendering of the docs. |
260,382 | 01.12.2021 15:29:49 | 18,000 | 38e98d2d7bdd14419a1d668a928f6743c30d3470 | Fix a bug that promoted t to a complex in odeint, and modify a test so it would have caught it
In odeint, raise error if t is not an array of floats | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ode.py",
"new_path": "jax/experimental/ode.py",
"diff": "@@ -92,7 +92,7 @@ def initial_step_size(fun, t0, y0, order, rtol, atol, f0):\ndef runge_kutta_step(func, y0, f0, t0, dt):\n# Dopri5 Butcher tableaux\n- alpha = jnp.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0], dtype=f0.dtype)\n+ alpha = jnp.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0], dtype=dt.dtype)\nbeta = jnp.array(\n[[1 / 5, 0, 0, 0, 0, 0, 0], [3 / 40, 9 / 40, 0, 0, 0, 0, 0],\n[44 / 45, -56 / 15, 32 / 9, 0, 0, 0, 0],\n@@ -165,9 +165,10 @@ def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf):\n\"\"\"\nfor arg in tree_leaves(args):\nif not isinstance(arg, core.Tracer) and not core.valid_jaxtype(arg):\n- msg = (\"The contents of odeint *args must be arrays or scalars, but got \"\n- \"\\n{}.\")\n- raise TypeError(msg.format(arg))\n+ raise TypeError(\n+ f\"The contents of odeint *args must be arrays or scalars, but got {arg}.\")\n+ if not jnp.issubdtype(t.dtype, jnp.floating):\n+ raise TypeError(f\"t must be an array of floats, but got {t}.\")\nconverted, consts = custom_derivatives.closure_convert(func, y0, t[0], *args)\nreturn _odeint_wrapper(converted, rtol, atol, mxstep, y0, t, *args, *consts)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/ode_test.py",
"new_path": "tests/ode_test.py",
"diff": "@@ -235,9 +235,10 @@ class ODETest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_complex_odeint(self):\n# https://github.com/google/jax/issues/3986\n+ # https://github.com/google/jax/issues/8757\ndef dy_dt(y, t, alpha):\n- return alpha * y\n+ return alpha * y * jnp.exp(-t)\ndef f(y0, ts, alpha):\nreturn odeint(dy_dt, y0, ts, alpha).real\n"
}
] | Python | Apache License 2.0 | google/jax | Fix a bug that promoted t to a complex in odeint, and modify a test so it would have caught it
In odeint, raise error if t is not an array of floats |
260,424 | 23.12.2021 15:23:58 | 0 | 7b5b9cefbd928e1f8b8e8ccf50416c0609f78e39 | Add scatter OOB error. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/checkify.py",
"new_path": "jax/experimental/checkify.py",
"diff": "@@ -287,6 +287,52 @@ def div_error_check(error, x, y):\nreturn nan_error_check(lax.div_p, div_by_zero_err, x, y)\nerror_checks[lax.div_p] = div_error_check\n+def scatter_in_bounds(operand, indices, updates, dnums):\n+ # Ref: see clamping code used in scatter_translation_rule\n+ slice_sizes = []\n+ pos = 0\n+ for i in range(len(operand.shape)):\n+ if i in dnums.inserted_window_dims:\n+ slice_sizes.append(1)\n+ else:\n+ slice_sizes.append(updates.shape[dnums.update_window_dims[pos]])\n+ pos += 1\n+\n+ upper_bound = np.array([operand.shape[i] - slice_sizes[i]\n+ for i in dnums.scatter_dims_to_operand_dims],\n+ np.int64)\n+ upper_bound = np.minimum(upper_bound, np.iinfo(indices.dtype).max)\n+ upper_bound = lax.broadcast_in_dim(upper_bound, indices.shape,\n+ (len(indices.shape) - 1,))\n+\n+ lower_in_bounds = jnp.all(jnp.greater_equal(indices, 0))\n+ upper_in_bounds = jnp.all(jnp.less_equal(indices, upper_bound))\n+ return jnp.logical_and(lower_in_bounds, upper_in_bounds)\n+\n+def scatter_error_check(prim, error, operand, indices, updates, *,\n+ update_jaxpr, update_consts,\n+ dimension_numbers, indices_are_sorted,\n+ unique_indices, mode):\n+ \"\"\"Checks if indices are within bounds and update does not generate NaN.\"\"\"\n+ out = prim.bind(\n+ operand, indices, updates, update_jaxpr=update_jaxpr,\n+ update_consts=update_consts, dimension_numbers=dimension_numbers,\n+ indices_are_sorted=indices_are_sorted, unique_indices=unique_indices,\n+ mode=mode)\n+\n+ in_bounds = scatter_in_bounds(operand, indices, updates, dimension_numbers)\n+ oob_msg = f'out-of-bounds indexing while updating at {summary()}'\n+ oob_error = assert_func(error, in_bounds, oob_msg)\n+\n+ no_nans = jnp.logical_not(jnp.any(jnp.isnan(out)))\n+ nan_msg = f'nan generated by primitive {prim.name} at {summary()}'\n+ return out, assert_func(oob_error, no_nans, nan_msg)\n+error_checks[lax.scatter_p] = partial(scatter_error_check, lax.scatter_p)\n+error_checks[lax.scatter_add_p] = partial(scatter_error_check, lax.scatter_add_p)\n+error_checks[lax.scatter_mul_p] = partial(scatter_error_check, lax.scatter_mul_p)\n+error_checks[lax.scatter_min_p] = partial(scatter_error_check, lax.scatter_min_p)\n+error_checks[lax.scatter_max_p] = partial(scatter_error_check, lax.scatter_max_p)\n+\ndef cond_error_check(error, index, *ops, branches, linear):\nnew_branches, msgs_ = unzip2(checkify_jaxpr(jxpr, error) for jxpr in branches)\nnew_linear = (False, False, *linear)\n@@ -439,4 +485,3 @@ add_nan_check(lax.abs_p)\nadd_nan_check(lax.select_p)\nadd_nan_check(lax.max_p)\nadd_nan_check(lax.min_p)\n-add_nan_check(lax.scatter_add_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/checkify_test.py",
"new_path": "tests/checkify_test.py",
"diff": "@@ -66,6 +66,23 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_update={update_fn}\", \"update_fn\": update_fn}\n+ for update_fn in [\"set\", \"add\", \"multiply\", \"divide\", \"power\", \"min\",\n+ \"max\", \"get\"])\n+ def test_jit_oob_update(self, update_fn):\n+ def f(x, i):\n+ return getattr(x.at[i], update_fn)(1.)\n+\n+ f = jax.jit(f)\n+\n+ err, _ = checkify.checkify(f)(jnp.arange(3), 2)\n+ self.assertIs(err.get(), None)\n+\n+ err, _ = checkify.checkify(f)(jnp.arange(3), 3)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\nfor jit in [False, True]))\n"
}
] | Python | Apache License 2.0 | google/jax | Add scatter OOB error. |
260,296 | 07.01.2022 14:54:41 | 28,800 | 8977998b5c8cd8db240e36d87dd8dfd6192d0797 | Update type annotations and use the new `convolution.py` file | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/other.py",
"new_path": "jax/_src/lax/other.py",
"diff": "@@ -122,10 +122,10 @@ def conv_general_dilated_local(\nwindow_strides: Sequence[int],\npadding: Union[str, Sequence[Tuple[int, int]]],\nfilter_shape: Sequence[int],\n- lhs_dilation: Sequence[int] = None,\n- rhs_dilation: Sequence[int] = None,\n- dimension_numbers: lax.ConvGeneralDilatedDimensionNumbers = None,\n- precision: lax.PrecisionLike = None\n+ lhs_dilation: Optional[Sequence[int]] = None,\n+ rhs_dilation: Optional[Sequence[int]] = None,\n+ dimension_numbers: Optional[convolution.ConvGeneralDilatedDimensionNumbers] = None,\n+ precision: Optional[lax.PrecisionLike] = None\n) -> jnp.ndarray:\n\"\"\"General n-dimensional unshared convolution operator with optional dilation.\n@@ -210,7 +210,7 @@ def conv_general_dilated_local(\nprecision=lhs_precision\n)\n- lhs_spec, rhs_spec, out_spec = lax.conv_dimension_numbers(\n+ lhs_spec, rhs_spec, out_spec = convolution.conv_dimension_numbers(\nlhs.shape, (1, 1) + tuple(filter_shape), dimension_numbers)\nlhs_c_dims, rhs_c_dims = [out_spec[1]], [rhs_spec[1]]\n"
}
] | Python | Apache License 2.0 | google/jax | Update type annotations and use the new `convolution.py` file |
260,335 | 08.01.2022 12:57:28 | 28,800 | 15e6098beb5c12f4fe9d8ccc5f3341a099086cb7 | add JAX_BACKEND_TARGET env var, fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lib/xla_bridge.py",
"new_path": "jax/_src/lib/xla_bridge.py",
"diff": "@@ -57,7 +57,8 @@ flags.DEFINE_string(\n'jax_xla_backend', '',\n'Deprecated, please use --jax_platforms instead.')\nflags.DEFINE_string(\n- 'jax_backend_target', '',\n+ 'jax_backend_target',\n+ os.getenv('JAX_BACKEND_TARGET', '').lower(),\n'Either \"local\" or \"rpc:address\" to connect to a remote service target.')\n# TODO(skye): warn when this is used once we test out --jax_platforms a bit\nflags.DEFINE_string(\n"
}
] | Python | Apache License 2.0 | google/jax | add JAX_BACKEND_TARGET env var, fixes #9034 |
260,442 | 08.01.2022 23:36:50 | 28,800 | 4a17c78605e7fc69a69a999e2f6298db79d3837a | [mhlo] Remove tuples from mhlo If/Case op. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow.py",
"new_path": "jax/_src/lax/control_flow.py",
"diff": "@@ -1405,6 +1405,8 @@ xla.register_translation(cond_p, _cond_translation_rule, initial_style=True)\ncore.custom_typechecks[cond_p] = _cond_typecheck\npe.partial_eval_jaxpr_custom_rules[cond_p] = pe.partial_eval_jaxpr_custom_rule_not_implemented\n+if jax._src.lib._xla_extension_version < 51:\n+\ndef _cond_lowering(ctx, index, *args, branches, linear):\ndel linear # Unused.\narg_avals = ctx.avals_in[1:]\n@@ -1423,20 +1425,48 @@ def _cond_lowering(ctx, index, *args, branches, linear):\nfor i, jaxpr in enumerate(branches):\nbranch = case_op.regions[i].blocks.append(input_tuple_type)\nwith ir.InsertionPoint(branch):\n- args = [mhlo.GetTupleElementOp(input_type, branch.arguments[0],\n+ args = [\n+ mhlo.GetTupleElementOp(input_type, branch.arguments[0],\nmlir.i32_attr(i)).result\n- for i, input_type in enumerate(flat_input_types)]\n+ for i, input_type in enumerate(flat_input_types)\n+ ]\nunflattened_args = util.unflatten(args, _map(len, input_types))\nout_vals = mlir.jaxpr_subcomp(ctx.module_context, jaxpr.jaxpr,\njaxpr.consts, *unflattened_args)\nout = mhlo.TupleOp(output_tuple_type, util.flatten(out_vals)).results\nmhlo.ReturnOp(out)\n- results = [mhlo.GetTupleElementOp(output_type, case_op.result,\n+ results = [\n+ mhlo.GetTupleElementOp(output_type, case_op.result,\nmlir.i32_attr(i)).result\n- for i, output_type in enumerate(flat_output_types)]\n+ for i, output_type in enumerate(flat_output_types)\n+ ]\nreturn util.unflatten(results, _map(len, output_types))\n+else:\n+\n+ def _cond_lowering(ctx, index, *args, branches, linear):\n+ del linear # Unused.\n+ output_types = _map(mlir.aval_to_ir_types, ctx.avals_out)\n+ flat_output_types = util.flatten(output_types)\n+\n+ # mhlo.CaseOp takes a single argument 'index' and the corresponding blocks\n+ # have no arguments; the computation within the block uses implicit\n+ # captures.\n+\n+ # TODO(phawkins): avoid build_generic when CaseOp is fixed.\n+ case_op = mhlo.CaseOp.build_generic(\n+ flat_output_types, [index], regions=len(branches))\n+ for i, jaxpr in enumerate(branches):\n+ branch = case_op.regions[i].blocks.append()\n+ with ir.InsertionPoint(branch):\n+ out_vals = mlir.jaxpr_subcomp(\n+ ctx.module_context, jaxpr.jaxpr, jaxpr.consts,\n+ *_map(mlir.wrap_singleton_ir_values, args))\n+ mhlo.ReturnOp(util.flatten(out_vals))\n+\n+ return util.unflatten(case_op.results, _map(len, output_types))\n+\nmlir.register_lowering(cond_p, _cond_lowering)\n"
}
] | Python | Apache License 2.0 | google/jax | [mhlo] Remove tuples from mhlo If/Case op.
PiperOrigin-RevId: 420554920 |
260,574 | 10.01.2022 16:19:57 | -10,800 | 78977d6f5ab33012fa7171bb744190efa4a2e9c8 | fix broken links and update texts in thinking_in_jax.ipynb | [
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/thinking_in_jax.ipynb",
"new_path": "docs/notebooks/thinking_in_jax.ipynb",
"diff": "\"id\": \"yRYF0YgO3F4H\"\n},\n\"source\": [\n- \"For updating individual elements, JAX provides an [indexed update syntax](https://jax.readthedocs.io/en/latest/jax.ops.html#syntactic-sugar-for-indexed-update-operators) that returns an updated copy:\"\n+ \"For updating individual elements, JAX provides an [indexed update syntax](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-operators) that returns an updated copy:\"\n]\n},\n{\n\"id\": \"7mdo6ycczlbd\"\n},\n\"source\": [\n- \"This is a batched convolution operation designed to be efficient for the types of convolutions often used in deep neural nets. It requires much more boilerplate, but is far more flexible and scalable than the convolution provided by NumPy (See [JAX Sharp Bits: Convolutions](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#%F0%9F%94%AA-Convolutions) for more detail on JAX convolutions).\\n\",\n+ \"This is a batched convolution operation designed to be efficient for the types of convolutions often used in deep neural nets. It requires much more boilerplate, but is far more flexible and scalable than the convolution provided by NumPy (See [Convolutions in JAX](https://jax.readthedocs.io/en/latest/notebooks/convolutions.html) for more detail on JAX convolutions).\\n\",\n\"\\n\",\n\"At their heart, all `jax.lax` operations are Python wrappers for operations in XLA; here, for example, the convolution implementation is provided by [XLA:ConvWithGeneralPadding](https://www.tensorflow.org/xla/operation_semantics#convwithgeneralpadding_convolution).\\n\",\n\"Every JAX operation is eventually expressed in terms of these fundamental XLA operations, which is what enables just-in-time (JIT) compilation.\"\n\"id\": \"ZO3GMGrHBZDS\"\n},\n\"source\": [\n- \"This fails with an error specifying that a tracer was found in `jax.numpy.reshape`. Let's add some print statements to the function to understand why this is happening:\"\n+ \"This fails with an error specifying that a tracer was found instead of a 1D sequence of concrete values of integer type. Let's add some print statements to the function to understand why this is happening:\"\n]\n},\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/thinking_in_jax.md",
"new_path": "docs/notebooks/thinking_in_jax.md",
"diff": "@@ -126,7 +126,7 @@ x[0] = 10\n+++ {\"id\": \"yRYF0YgO3F4H\"}\n-For updating individual elements, JAX provides an [indexed update syntax](https://jax.readthedocs.io/en/latest/jax.ops.html#syntactic-sugar-for-indexed-update-operators) that returns an updated copy:\n+For updating individual elements, JAX provides an [indexed update syntax](https://jax.readthedocs.io/en/latest/jax.ops.html#indexed-update-operators) that returns an updated copy:\n```{code-cell} ipython3\n:id: 8zqPEAeP3UK5\n@@ -215,7 +215,7 @@ result[0, 0]\n+++ {\"id\": \"7mdo6ycczlbd\"}\n-This is a batched convolution operation designed to be efficient for the types of convolutions often used in deep neural nets. It requires much more boilerplate, but is far more flexible and scalable than the convolution provided by NumPy (See [JAX Sharp Bits: Convolutions](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#%F0%9F%94%AA-Convolutions) for more detail on JAX convolutions).\n+This is a batched convolution operation designed to be efficient for the types of convolutions often used in deep neural nets. It requires much more boilerplate, but is far more flexible and scalable than the convolution provided by NumPy (See [Convolutions in JAX](https://jax.readthedocs.io/en/latest/notebooks/convolutions.html) for more detail on JAX convolutions).\nAt their heart, all `jax.lax` operations are Python wrappers for operations in XLA; here, for example, the convolution implementation is provided by [XLA:ConvWithGeneralPadding](https://www.tensorflow.org/xla/operation_semantics#convwithgeneralpadding_convolution).\nEvery JAX operation is eventually expressed in terms of these fundamental XLA operations, which is what enables just-in-time (JIT) compilation.\n@@ -456,7 +456,7 @@ f(x)\n+++ {\"id\": \"ZO3GMGrHBZDS\"}\n-This fails with an error specifying that a tracer was found in `jax.numpy.reshape`. Let's add some print statements to the function to understand why this is happening:\n+This fails with an error specifying that a tracer was found instead of a 1D sequence of concrete values of integer type. Let's add some print statements to the function to understand why this is happening:\n```{code-cell} ipython3\n:id: Cb4mbeVZEi_q\n"
}
] | Python | Apache License 2.0 | google/jax | fix broken links and update texts in thinking_in_jax.ipynb |
260,574 | 10.01.2022 17:34:09 | -10,800 | d2c6c06546c7e68cc0e34bc594e9d69bf58db9a4 | Fix DeviceArray class reference | [
{
"change_type": "MODIFY",
"old_path": "docs/glossary.rst",
"new_path": "docs/glossary.rst",
"diff": "@@ -13,7 +13,7 @@ JAX Glossary of Terms\nby JAX to perform computations.\nDeviceArray\n- JAX's analog of the :class:`numpy.ndarray`. See :class:`jax.interpreters.xla.DeviceArray`.\n+ JAX's analog of the :class:`numpy.ndarray`. See :class:`jaxlib.xla_extension.DeviceArray`.\nforward-mode autodiff\nSee :term:`JVP`\n"
}
] | Python | Apache License 2.0 | google/jax | Fix DeviceArray class reference |
260,335 | 10.01.2022 20:57:56 | 28,800 | 1cf7d4ab5dcea4619a2b6c1b471f2be340b6abfc | Copybara import of the project:
by Matthew Johnson
add jax.ensure_compile_time_eval to public api
aka jax.core.eval_context
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/jax/pull/7987 from google:issue7535 | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -32,6 +32,7 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Added a new debugging flag/environment variable `JAX_DUMP_IR_TO=/path`.\nIf set, JAX dumps the MHLO/HLO IR it generates for each computation to a\nfile under the given path.\n+ * Added `jax.ensure_compile_time_eval` to the public api ({jax-issue}`#7987`).\n## jaxlib 0.1.76 (Unreleased)\n* New features\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax.rst",
"new_path": "docs/jax.rst",
"diff": "@@ -38,6 +38,7 @@ Just-in-time compilation (:code:`jit`)\njit\ndisable_jit\n+ ensure_compile_time_eval\nxla_computation\nmake_jaxpr\neval_shape\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/__init__.py",
"new_path": "jax/__init__.py",
"diff": "@@ -50,6 +50,7 @@ from jax._src.config import (\ndefault_prng_impl as default_prng_impl,\nnumpy_rank_promotion as numpy_rank_promotion,\n)\n+from .core import eval_context as ensure_compile_time_eval\nfrom jax._src.api import (\nad, # TODO(phawkins): update users to avoid this.\nblock_until_ready,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -814,9 +814,67 @@ def new_base_main(trace_type: Type[Trace]) -> Generator[MainTrace, None, None]:\nraise Exception(f'Leaked level {t()}. Leaked tracer(s): {leaked_tracers}.')\n@contextmanager\n-def eval_context():\n+def ensure_compile_time_eval():\n+ \"\"\"Context manager to ensure evaluation at trace/compile time (or error).\n+\n+ Some JAX APIs like ``jax.jit`` and ``jax.lax.scan`` involve staging, i.e.\n+ delaying the evaluation of numerical expressions (like jax.numpy function\n+ applications) so that instead of performing those computations eagerly while\n+ evaluating the corresponding Python expressions, their computation is carried\n+ out separately, e.g. after optimized compilation. But this delay can be\n+ undesirable. For example, numerical values might be needed to evaluate Python\n+ control flow and so their evaluation cannot be delayed. As another example, it\n+ may be beneficial to ensure compile time evaluation (or \"constant folding\")\n+ for performance reasons.\n+\n+ This context manager ensures that JAX computations are evaluated eagerly. If\n+ eager evaluation is not possible, a ``ConcretizationError`` is raised.\n+\n+ Here's a contrived example::\n+\n+ import jax\n+ import jax.numpy as jnp\n+\n+ @jax.jit\n+ def f(x):\n+ with jax.ensure_compile_time_eval():\n+ y = jnp.sin(3.0)\n+ z = jnp.sin(y)\n+ if z > 0: # the value of z is availble and can be used in control flow\n+ return jnp.sin(x)\n+ else:\n+ return jnp.cos(x)\n+\n+ Here's a real-world example from https://github.com/google/jax/issues/3974::\n+\n+ import jax\n+ import jax.numpy as jnp\n+ from jax import random\n+\n+ @jax.jit\n+ def jax_fn(x):\n+ with jax.ensure_compile_time_eval():\n+ y = random.randint(random.PRNGKey(0), (1000,1000), 0, 100)\n+ y2 = y @ y\n+ x2 = jnp.sum(y2) * x\n+ return x2\n+\n+ A similar behavior can often be achieved simply by 'hoisting' the constant\n+ expression out of the corresponding staging API::\n+\n+ y = random.randint(random.PRNGKey(0), (1000,1000), 0, 100)\n+\n+ @jax.jit\n+ def jax_fn(x):\n+ y2 = y @ y\n+ x2 = jnp.sum(y2)*x\n+ return x2\n+\n+ But in some cases it can be more convenient to use this context manager.\n+ \"\"\"\nwith new_base_main(EvalTrace):\nyield\n+eval_context = ensure_compile_time_eval # alias, backward compatibility\n@contextmanager\ndef new_sublevel() -> Generator[None, None, None]:\n"
}
] | Python | Apache License 2.0 | google/jax | Copybara import of the project:
--
4fcdadbfb3f4c484fd4432203cf13b88782b9311 by Matthew Johnson <mattjj@google.com>:
add jax.ensure_compile_time_eval to public api
aka jax.core.eval_context
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/jax/pull/7987 from google:issue7535 4fcdadbfb3f4c484fd4432203cf13b88782b9311
PiperOrigin-RevId: 420928687 |
260,335 | 10.01.2022 21:29:12 | 28,800 | 6850833c3a6c94060aaf48a4c26c2cc39cba8ba9 | checkify: tweak some organization and names | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/checkify.py",
"new_path": "jax/experimental/checkify.py",
"diff": "from dataclasses import dataclass\nfrom functools import partial\nimport itertools as it\n-from typing import Union, Optional, Callable, Dict\n+from typing import Union, Optional, Callable, Dict, Tuple, TypeVar\nimport numpy as np\n@@ -86,7 +86,7 @@ def assert_func(error: Error, pred: Bool, msg: str) -> Error:\n## Checkify transformation for plumbing functional error values.\n-class ErrorTracer(core.Tracer):\n+class CheckifyTracer(core.Tracer):\ndef __init__(self, trace, val):\nself._trace = trace\nself.val = val\n@@ -94,11 +94,11 @@ class ErrorTracer(core.Tracer):\naval = property(lambda self: core.get_aval(self.val))\nfull_lower = lambda self: self\n-class ErrorTrace(core.Trace):\n- pure = lift = lambda self, val: ErrorTracer(self, val)\n+class CheckifyTrace(core.Trace):\n+ pure = lift = lambda self, val: CheckifyTracer(self, val)\ndef sublift(self, tracer):\n- return ErrorTracer(self, tracer.val)\n+ return CheckifyTracer(self, tracer.val)\ndef process_primitive(self, primitive, tracers, params):\nin_vals = [t.val for t in tracers]\n@@ -108,23 +108,23 @@ class ErrorTrace(core.Trace):\nelse:\nout = primitive.bind(*in_vals, **params)\nif primitive.multiple_results:\n- return [ErrorTracer(self, x) for x in out]\n+ return [CheckifyTracer(self, x) for x in out]\nelse:\n- return ErrorTracer(self, out)\n+ return CheckifyTracer(self, out)\ndef process_call(self, primitive, f, tracers, params):\nin_vals = [t.val for t in tracers]\ne = popattr(self.main, 'error')\n- f, msgs = check_errors_subtrace(f, self.main, tuple(e.msgs.items()))\n+ f, msgs = checkify_subtrace(f, self.main, tuple(e.msgs.items()))\nparams_ = dict(params, donated_invars=(False, False, *params['donated_invars']))\nerr, code, *out_vals = primitive.bind(f, e.err, e.code, *in_vals, **params_)\nsetnewattr(self.main, 'error', Error(err, code, msgs()))\n- return [ErrorTracer(self, x) for x in out_vals]\n+ return [CheckifyTracer(self, x) for x in out_vals]\ndef process_map(self, primitive, f, tracers, params):\nin_vals = [t.val for t in tracers]\ne = popattr(self.main, 'error')\n- f, msgs = check_errors_subtrace(f, self.main, tuple(e.msgs.items()))\n+ f, msgs = checkify_subtrace(f, self.main, tuple(e.msgs.items()))\n@as_hashable_function(closure=params['out_axes_thunk'])\ndef new_out_axes_thunk():\n@@ -136,7 +136,7 @@ class ErrorTrace(core.Trace):\nerrs, codes, *outs = primitive.bind(f, e.err, e.code, *in_vals, **params_)\nerr, code = _reduce_any_error(errs, codes)\nsetnewattr(self.main, 'error', Error(err, code, msgs()))\n- return [ErrorTracer(self, x) for x in outs]\n+ return [CheckifyTracer(self, x) for x in outs]\ndef post_process_call(self, primitive, tracers, params):\nvals = [t.val for t in tracers]\n@@ -146,7 +146,7 @@ class ErrorTrace(core.Trace):\ndef todo(vals):\ntrace = main.with_cur_sublevel()\nerr, code, *vals = vals\n- return [ErrorTracer(trace, x) for x in vals]\n+ return [CheckifyTracer(trace, x) for x in vals]\nreturn (err, code, *vals), todo\ndef post_process_map(self, primitive, tracers, params):\n@@ -157,7 +157,7 @@ class ErrorTrace(core.Trace):\ndef todo(vals):\ntrace = main.with_cur_sublevel()\nerr, code, *vals = vals\n- return [ErrorTracer(trace, x) for x in vals]\n+ return [CheckifyTracer(trace, x) for x in vals]\ndef out_axes_transform(out_axes):\nreturn (0, 0, *out_axes)\nreturn (err, code, *vals), (todo, out_axes_transform)\n@@ -169,26 +169,24 @@ def _reduce_any_error(errs, codes):\nErrorCheckRule = Callable\nerror_checks: Dict[core.Primitive, ErrorCheckRule] = {}\n-def check_errors_flat(fun: lu.WrappedFun, *args):\n- fun, msgs = check_errors_subtrace(fun)\n- fun = check_errors_toplevel(fun)\n- err, code, *out_vals = fun.call_wrapped(*args)\n- return (err, code, out_vals), msgs()\n+def checkify_flat(fun: lu.WrappedFun, *args):\n+ fun, msgs = checkify_subtrace(fun)\n+ fun = checkify_traceable(fun, tuple(init_error.msgs.items()))\n+ err, code, *outvals = fun.call_wrapped(init_error.err, init_error.code, *args)\n+ return (err, code, outvals), msgs()\n@lu.transformation\n-def check_errors_toplevel(*args):\n- error = init_error\n- with core.new_main(ErrorTrace) as main:\n- msgs = tuple(error.msgs.items())\n- outs = yield (main, msgs, error.err, error.code, *args), {}\n+def checkify_traceable(msgs, err, code, *args):\n+ with core.new_main(CheckifyTrace) as main:\n+ outs = yield (main, msgs, err, code, *args), {}\ndel main\nyield outs\n@lu.transformation_with_aux\n-def check_errors_subtrace(main, msgs, err, code, *args):\n+def checkify_subtrace(main, msgs, err, code, *args):\nsetnewattr(main, 'error', Error(err, code, dict(msgs)))\ntrace = main.with_cur_sublevel()\n- in_tracers = [ErrorTracer(trace, x) for x in args]\n+ in_tracers = [CheckifyTracer(trace, x) for x in args]\nout = yield in_tracers, {}\nout_tracers = map(trace.full_raise, out)\nout_vals = [t.val for t in out_tracers]\n@@ -196,27 +194,20 @@ def check_errors_subtrace(main, msgs, err, code, *args):\ndel main.error\nyield (err, code, *out_vals), msgs\n-def checkify_fun_to_jaxpr(f, error, in_avals):\n- f, msgs = check_errors_subtrace(f)\n- f = check_errors_traceable(f, tuple(error.msgs.items()))\n- err_aval = core.raise_to_shaped(core.get_aval(error.err))\n- code_aval = core.raise_to_shaped(core.get_aval(error.code))\n- avals_in = [err_aval, code_aval, *in_avals]\n- jaxpr_out, _, literals_out = pe.trace_to_jaxpr_dynamic(f, avals_in)\n- return core.ClosedJaxpr(jaxpr_out, literals_out), msgs()\n# TODO take (error_aval, code_aval) instead of error here?\ndef checkify_jaxpr(jaxpr, error):\nf = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\nreturn checkify_fun_to_jaxpr(f, error, jaxpr.in_avals)\n-# TODO dedup with check_errors_toplevel\n-@lu.transformation\n-def check_errors_traceable(msgs, err, code, *args):\n- with core.new_main(ErrorTrace) as main:\n- outs = yield (main, msgs, err, code, *args), {}\n- del main\n- yield outs\n+def checkify_fun_to_jaxpr(f, error, in_avals):\n+ f, msgs = checkify_subtrace(f)\n+ f = checkify_traceable(f, tuple(error.msgs.items()))\n+ err_aval = core.raise_to_shaped(core.get_aval(error.err))\n+ code_aval = core.raise_to_shaped(core.get_aval(error.code))\n+ avals_in = [err_aval, code_aval, *in_avals]\n+ jaxpr_out, _, literals_out = pe.trace_to_jaxpr_dynamic(f, avals_in)\n+ return core.ClosedJaxpr(jaxpr_out, literals_out), msgs()\n## assert primitive\n@@ -398,30 +389,6 @@ def while_loop_error_check(error, *in_flat, cond_nconsts, cond_jaxpr, body_ncons\nreturn out, Error(err, code, new_msgs)\nerror_checks[lax.while_p] = while_loop_error_check\n-# TODO(mattjj,lenamartens): currently we bundle effectful-assert-discharging\n-# with the error-check-adding transformation (checkify), but they could be\n-# separated into two orthogonal transformations.\n-def assert_discharge_rule(error, pred, code, *, msgs):\n- out_err = error.err | jnp.logical_not(pred)\n- out_code = lax.select(error.err, error.code, code)\n- return [], Error(out_err, out_code, {**error.msgs, **msgs})\n-error_checks[assert_p] = assert_discharge_rule\n-\n-\n-## checkify api\n-\n-def checkify(fun: Callable) -> Callable:\n- @traceback_util.api_boundary\n- def checked_fun(*args, **kwargs):\n- args_flat, in_tree = tree_flatten((args, kwargs))\n- f, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n- (err, code, out_flat), msgs = check_errors_flat(f, *args_flat)\n- out = tree_unflatten(out_tree(), out_flat)\n- return Error(err, code, msgs), out\n- return checked_fun\n-\n-## NaN error rule table\n-\ndef add_nan_check(prim):\nerror_checks[prim] = partial(nan_error_check, prim)\n@@ -485,3 +452,23 @@ add_nan_check(lax.abs_p)\nadd_nan_check(lax.select_p)\nadd_nan_check(lax.max_p)\nadd_nan_check(lax.min_p)\n+\n+def assert_discharge_rule(error, pred, code, *, msgs):\n+ out_err = error.err | jnp.logical_not(pred)\n+ out_code = lax.select(error.err, error.code, code)\n+ return [], Error(out_err, out_code, {**error.msgs, **msgs})\n+error_checks[assert_p] = assert_discharge_rule\n+\n+\n+## checkify api\n+\n+Out = TypeVar('Out')\n+def checkify(fun: Callable[..., Out]) -> Callable[..., Tuple[Error, Out]]:\n+ @traceback_util.api_boundary\n+ def checked_fun(*args, **kwargs):\n+ args_flat, in_tree = tree_flatten((args, kwargs))\n+ f, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n+ (err, code, out_flat), msgs = checkify_flat(f, *args_flat)\n+ out = tree_unflatten(out_tree(), out_flat)\n+ return Error(err, code, msgs), out\n+ return checked_fun\n"
}
] | Python | Apache License 2.0 | google/jax | checkify: tweak some organization and names |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.