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,447
03.11.2022 21:39:10
25,200
46368e4e734938bffe7978cb4077923343095abc
[sparse] Update the guard of cusparse SpMM and SpMv algorithms to cusparse version 11.7.1 onwards.
[ { "change_type": "MODIFY", "old_path": "jaxlib/gpu/vendor.h", "new_path": "jaxlib/gpu/vendor.h", "diff": "@@ -224,9 +224,9 @@ typedef cusparseDnVecDescr_t gpusparseDnVecDescr_t;\n// Use CUSPARSE_SPMV_COO_ALG2 and CUSPARSE_SPMV_CSR_ALG2 for SPMV and\n// use CUSPARSE_SPMM_COO_ALG2 and CUSPARSE_SPMM_CSR_ALG3 for SPMM, which\n// provide deterministic (bit-wise) results for each run. These indexing modes\n-// are available in CUSPARSE 11.4 and newer (which was released as part of\n-// CUDA 11.2.1)\n-#if CUSPARSE_VERSION >= 11400\n+// are fully supported (both row- and column-major inputs) in CUSPARSE 11.7.1\n+// and newer (which was released as part of CUDA 11.8)\n+#if CUSPARSE_VERSION > 11700\n#define GPUSPARSE_SPMV_COO_ALG CUSPARSE_SPMV_COO_ALG2\n#define GPUSPARSE_SPMV_CSR_ALG CUSPARSE_SPMV_CSR_ALG2\n#define GPUSPARSE_SPMM_COO_ALG CUSPARSE_SPMM_COO_ALG2\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Update the guard of cusparse SpMM and SpMv algorithms to cusparse version 11.7.1 onwards. PiperOrigin-RevId: 486051658
260,720
27.10.2022 15:33:03
25,200
e3cd9671b93b0235b81ace9d84c3665480107169
Add x86_64 dependency note to pip installation Currently non x86_64 linux architectures are not supported, see for request to change this. This can lead to installation confusion, as jax will install, but jaxlib will not. For example see This adds a note to the install sections for the relevant pip wheels.
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -413,7 +413,7 @@ pip install --upgrade \"jax[cpu]\"\n```\nOn Linux, it is often necessary to first update `pip` to a version that supports\n-`manylinux2014` wheels.\n+`manylinux2014` wheels. Also note that for Linux, we currently release wheels for `x86_64` architectures only, other architectures require building from source. Trying to pip install with other Linux architectures may lead to `jaxlib` not being installed alongside `jax`, although `jax` may successfully install (but fail at runtime).\n**These `pip` installations do not work with Windows, and may fail silently; see\n[above](#installation).**\n@@ -427,7 +427,7 @@ learning systems, JAX does not bundle CUDA or CuDNN as part of the `pip`\npackage.\nJAX provides pre-built CUDA-compatible wheels for **Linux only**,\n-with CUDA 11.1 or newer, and CuDNN 8.0.5 or newer. Other combinations of\n+with CUDA 11.1 or newer, and CuDNN 8.0.5 or newer. Note these existing wheels are currently for `x86_64` architectures only. Other combinations of\noperating system, CUDA, and CuDNN are possible, but require [building from\nsource](https://jax.readthedocs.io/en/latest/developer.html#building-from-source).\n" } ]
Python
Apache License 2.0
google/jax
Add x86_64 dependency note to pip installation Currently non x86_64 linux architectures are not supported, see #7097 for request to change this. This can lead to installation confusion, as jax will install, but jaxlib will not. For example see #12307. This adds a note to the install sections for the relevant pip wheels.
260,283
04.11.2022 20:53:52
0
e6c88f2c58c4eda7192db60646d917a85ac66273
update pytest.ini to print warning message for compilation_cache_test
[ { "change_type": "MODIFY", "old_path": "pytest.ini", "new_path": "pytest.ini", "diff": "@@ -19,5 +19,8 @@ filterwarnings =\n# numpy uses distutils which is deprecated\nignore:The distutils.* is deprecated.*:DeprecationWarning\nignore:`sharded_jit` is deprecated. Please use `pjit` instead.*:DeprecationWarning\n+ # Print message for compilation_cache_test.py::CompilationCacheTest::test_cache_read/write_warning\n+ default:Error reading persistent compilation cache entry for 'jit__lambda_'\n+ default:Error writing persistent compilation cache entry for 'jit__lambda_'\ndoctest_optionflags = NUMBER NORMALIZE_WHITESPACE\naddopts = --doctest-glob=\"*.rst\"\n" } ]
Python
Apache License 2.0
google/jax
update pytest.ini to print warning message for compilation_cache_test
260,335
04.11.2022 19:49:07
25,200
190204ff7d186efd9e4f78d4d49bb3387e3759ab
fix jax.random.logits shape argument fixes
[ { "change_type": "MODIFY", "old_path": "jax/_src/random.py", "new_path": "jax/_src/random.py", "diff": "@@ -1327,10 +1327,12 @@ def categorical(key: KeyArray,\nshape = tuple(shape)\n_check_shape(\"categorical\", shape, batch_shape)\n- sample_shape = shape[:len(shape)-len(batch_shape)]\n+ shape_prefix = shape[:len(shape)-len(batch_shape)]\n+ logits_shape = list(shape[len(shape) - len(batch_shape):])\n+ logits_shape.insert(axis % len(logits_arr.shape), logits_arr.shape[axis])\nreturn jnp.argmax(\n- gumbel(key, sample_shape + logits_arr.shape, logits_arr.dtype) +\n- lax.expand_dims(logits_arr, tuple(range(len(sample_shape)))),\n+ gumbel(key, (*shape_prefix, *logits_shape), logits_arr.dtype) +\n+ lax.expand_dims(logits_arr, tuple(range(len(shape_prefix)))),\naxis=axis)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -1429,6 +1429,19 @@ class LaxRandomTest(jtu.JaxTestCase):\n# just lower, don't run, takes too long\njax.jit(f).lower()\n+ @jtu.sample_product(shape=[(3, 4)],\n+ logits_shape_base=[(3, 4), (3, 1), (1, 4)],\n+ axis=[-3, -2, -1, 0, 1, 2])\n+ def test_categorical_shape_argument(self, shape, logits_shape_base, axis):\n+ # https://github.com/google/jax/issues/13124\n+ logits_shape = list(logits_shape_base)\n+ logits_shape.insert(axis % (len(logits_shape_base) + 1), 10)\n+ assert logits_shape[axis] == 10\n+ logits = jnp.ones(logits_shape)\n+ samples = jax.random.categorical(jax.random.PRNGKey(0), logits=logits,\n+ axis=axis, shape=shape)\n+ self.assertEqual(samples.shape, shape)\n+\nclass KeyArrayTest(jtu.JaxTestCase):\n# Key arrays involve:\n" } ]
Python
Apache License 2.0
google/jax
fix jax.random.logits shape argument fixes #13124
260,335
17.10.2022 11:15:14
25,200
f2f2faa4fa166f40a4a93bc966379cf1ebb720d1
add a basic prototype of piles, behind jax_dynamic_shapes
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -45,6 +45,7 @@ from jax.interpreters import xla\nfrom jax.interpreters import pxla\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\n+from jax.interpreters.batching import ConcatAxis\nimport jax._src.pretty_printer as pp\nfrom jax._src import util\nfrom jax._src.util import (cache, prod, safe_zip, safe_map, canonicalize_axis,\n@@ -2597,6 +2598,21 @@ def _dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers,\nprecision,\npreferred_element_type: Optional[DTypeLike]):\nlhs, rhs = batched_args\n+ lbd, rbd = batch_dims\n+ (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n+ if (type(lbd) is type(rbd) is ConcatAxis and\n+ lbd.axis in lhs_contract and rbd.axis in rhs_contract):\n+ # first handle any other part of the dot with these as batch dims\n+ lhs_contract_ = [d for d in lhs_contract if d != lbd.axis]\n+ rhs_contract_ = [d for d in rhs_contract if d != rbd.axis]\n+ lhs_batch_ = (lbd.axis, *lhs_batch)\n+ rhs_batch_ = (rbd.axis, *rhs_batch)\n+ new_dnums = ((lhs_contract_, rhs_contract_), (lhs_batch_, rhs_batch_))\n+ out = dot_general(lhs, rhs, new_dnums, precision=precision,\n+ preferred_element_type=preferred_element_type)\n+ # now a segment sum along that batch axis\n+ return batching.segment_sum(out, lbd.segment_lengths), 0\n+\nnew_dimension_numbers, result_batch_dim = _dot_general_batch_dim_nums(\n(lhs.ndim, rhs.ndim), batch_dims, dimension_numbers)\nbatched_out = dot_general(lhs, rhs, new_dimension_numbers,\n@@ -2617,31 +2633,52 @@ def _dot_general_batch_dim_nums(ndims, batch_dims, dimension_numbers):\ndef bump_dims(dims, b):\nreturn tuple(np.add(dims, np.greater_equal(dims, b)))\n- if lbd is not None and rbd is not None:\n+ if type(lbd) is type(rbd) is int:\n# adding a batch dimension\nlhs_batch = (lbd,) + bump_dims(lhs_batch, lbd)\nrhs_batch = (rbd,) + bump_dims(rhs_batch, rbd)\nlhs_contract = bump_dims(lhs_contract, lbd)\nrhs_contract = bump_dims(rhs_contract, rbd)\nresult_batch_dim = 0\n+ elif rbd is None and type(lbd) is ConcatAxis and lbd.axis not in lhs_contract:\n+ if lbd.axis in lhs_batch:\n+ axis = int(np.sum(np.less(lhs_batch, lbd.axis)))\nelse:\n- # adding a tensor product dimension\n- if lbd is not None:\n- other = tuple(d for d in range(lhs_ndim)\n- if d not in lhs_batch and d not in lhs_contract)\n- result_batch_dim = (len(lhs_batch) + sum(np.less(other, lbd)))\n+ lhs_tensor = [d for d in range(lhs_ndim)\n+ if d not in lhs_batch and d not in lhs_contract]\n+ axis = len(lhs_batch) + int(np.sum(np.less(lhs_tensor, lbd.axis)))\n+ result_batch_dim = ConcatAxis(axis, lbd.segment_lengths)\n+ elif lbd is None and type(rbd) is ConcatAxis and rbd.axis not in rhs_contract:\n+ if rbd.axis in rhs_batch:\n+ axis = int(np.sum(np.less(rhs_batch, rbd.axis)))\n+ else:\n+ rhs_tensor = [d for d in range(rhs_ndim)\n+ if d not in rhs_batch and d not in rhs_contract]\n+ axis = (lhs_ndim - len(lhs_contract) +\n+ int(sum(np.less(rhs_tensor, rbd.axis))))\n+ result_batch_dim = ConcatAxis(axis, rbd.segment_lengths)\n+ elif (type(lbd) is int and\n+ (rbd is None or type(rbd) is ConcatAxis and\n+ rbd.axis not in rhs_contract)):\n+ lhs_tensor = [d for d in range(lhs_ndim)\n+ if d not in lhs_batch and d not in lhs_contract]\n+ result_batch_dim = len(lhs_batch) + int(sum(np.less(lhs_tensor, lbd)))\nlhs_batch = bump_dims(lhs_batch, lbd)\nlhs_contract = bump_dims(lhs_contract, lbd)\n- else:\n- other = tuple(d for d in range(rhs_ndim)\n- if d not in rhs_batch and d not in rhs_contract)\n+ elif (type(rbd) is int and\n+ (lbd is None or type(lbd) is ConcatAxis and\n+ lbd.axis not in lhs_contract)):\n+ rhs_tensor = [d for d in range(rhs_ndim)\n+ if d not in rhs_batch and d not in rhs_contract]\nresult_batch_dim = (lhs_ndim - len(lhs_contract) +\n- sum(np.less(other, rbd)))\n+ int(sum(np.less(rhs_tensor, rbd))))\nrhs_batch = bump_dims(rhs_batch, rbd)\nrhs_contract = bump_dims(rhs_contract, rbd)\n+ else:\n+ assert False\nnew_dimension_numbers = ((lhs_contract, rhs_contract), (lhs_batch, rhs_batch))\n- return new_dimension_numbers, int(result_batch_dim)\n+ return new_dimension_numbers, result_batch_dim\ndef _dot_general_padding_rule(in_avals, out_avals, lhs, rhs, *,\ndimension_numbers, **params):\n@@ -2782,15 +2819,27 @@ def _broadcast_in_dim_transpose_rule(ct, operand, *dyn_shape,\nreturn ([expand_dims(_reduce_sum(ct, axes), unit_dims)] +\n[None] * len(dyn_shape))\n-def _broadcast_in_dim_batch_rule(batched_args, batch_dims, *dyn_shape, shape,\n+def _broadcast_in_dim_batch_rule(batched_args, batch_dims, shape,\nbroadcast_dimensions):\n- if dyn_shape: raise NotImplementedError # TODO(mattjj)\n- operand, = batched_args\n- bdim, = batch_dims\n- new_operand = batching.moveaxis(operand, bdim, 0)\n- new_shape = (operand.shape[bdim],) + shape\n+ operand, *dyn_shape = batched_args\n+ operand_bdim, *dyn_shape_bdims = batch_dims\n+ if len(dyn_shape) > 1: raise NotImplementedError\n+ if (operand_bdim is not None and\n+ (not dyn_shape_bdims or dyn_shape_bdims[0] is None)):\n+ new_operand = batching.moveaxis(operand, operand_bdim, 0)\n+ new_shape = (operand.shape[operand_bdim],) + shape\nnew_broadcast_dimensions = (0,) + tuple(np.add(1, broadcast_dimensions))\nreturn broadcast_in_dim(new_operand, new_shape, new_broadcast_dimensions), 0\n+ elif (operand_bdim is None and dyn_shape_bdims and\n+ dyn_shape_bdims[0] is not None):\n+ (d,), (d_bdim,) = dyn_shape, dyn_shape_bdims # NotImplementedError above\n+ assert d_bdim == 0 # must be scalar in the program to be batched\n+ new_shape = _merge_dyn_shape(shape, (int(d.sum()),))\n+ out = broadcast_in_dim(operand, new_shape, broadcast_dimensions)\n+ idx, = (i for i, s in enumerate(shape) if s is None)\n+ return out, batching.ConcatAxis(idx, d)\n+ else:\n+ raise NotImplementedError # TODO(mattjj)\ndef _broadcast_in_dim_fwd_rule(eqn):\nv, *dyn = eqn.invars\n@@ -4471,6 +4520,13 @@ def _iota_lower(ctx, *dyn_shape, dtype, shape, dimension):\nmlir.i64_attr(dimension)).results\nmlir.register_lowering(iota_p, _iota_lower)\n+def _iota_batching_rule(in_vals, in_dims, *, dtype, shape, dimension):\n+ (segment_lengths,), (ax,) = in_vals, in_dims\n+ shapes = [_merge_dyn_shape(shape, (d,)) for d in segment_lengths]\n+ iotas = [broadcasted_iota(dtype, s, dimension) for s in shapes]\n+ return concatenate(iotas, dimension), batching.ConcatAxis(ax, segment_lengths)\n+batching.primitive_batchers[iota_p] = _iota_batching_rule\n+\ndef _iota_pp_rule(eqn, context, settings):\nprinted_params = {}\nif len(eqn.params['shape']) > 1:\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -2195,35 +2195,41 @@ def unmapped_aval(size: AxisSize, axis_name, axis: Optional[int],\nelse:\nraise TypeError(f\"no unmapping handler for {aval} of type {type(aval)}\")\n-def _map_shaped_array(size: int, axis: Optional[int], aval: ShapedArray\n- ) -> ShapedArray:\n+\n+def _map_shaped_array(\n+ size: int, axis: Optional[int], aval: ShapedArray) -> ShapedArray:\nassert axis is None or aval.shape[axis] == size\n# TODO: Extend the named shape\nif axis is None: return aval\nreturn ShapedArray(tuple_delete(aval.shape, axis), aval.dtype,\nnamed_shape=aval.named_shape, weak_type=aval.weak_type)\n-def _unmap_shaped_array(size: int, axis_name, axis: Optional[int],\n- aval: ShapedArray) -> ShapedArray:\n+def _unmap_shaped_array(\n+ size: int, axis_name: AxisName, axis: Optional[int], aval: ShapedArray\n+ ) -> ShapedArray:\nnamed_shape = dict(aval.named_shape)\n- # TODO: Make this mandatory\n- named_shape.pop(axis_name, None)\n+ named_shape.pop(axis_name, None) # TODO: make this mandatory\nif axis is None: return aval.update(named_shape=named_shape)\n+ elif type(axis) is int:\nreturn ShapedArray(tuple_insert(aval.shape, axis, size), aval.dtype,\nnamed_shape=named_shape, weak_type=aval.weak_type)\n+ else: raise TypeError(axis)\n-def _map_dshaped_array(size: AxisSize, axis: Optional[int],\n- aval: DShapedArray) -> DShapedArray:\n+def _map_dshaped_array(\n+ size: AxisSize, axis: Optional[int], aval: DShapedArray) -> DShapedArray:\nif axis is None: return aval\nreturn DShapedArray(tuple_delete(aval.shape, axis), aval.dtype,\naval.weak_type)\ndef _unmap_dshaped_array(\n- size: AxisSize, axis_name, axis: Optional[int],\n- aval: DShapedArray) -> DShapedArray:\n+ size: AxisSize, axis_name: AxisName, axis: Optional[int], aval: DShapedArray\n+ ) -> DShapedArray:\nif axis is None: return aval\n+ elif type(axis) is int:\nreturn DShapedArray(tuple_insert(aval.shape, axis, size), aval.dtype,\nweak_type=aval.weak_type)\n+ else:\n+ raise TypeError(axis)\nAvalMapHandlerPair = Tuple[Callable, Callable]\naval_mapping_handlers: Dict[Type, AvalMapHandlerPair] = {\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n+from __future__ import annotations\n+import collections\n+import dataclasses\nfrom functools import partial\nfrom typing import (Any, Callable, Dict, Hashable, Iterable, Optional, Sequence,\nSet, Tuple, Type, Union)\n@@ -23,7 +26,8 @@ from jax.config import config\nfrom jax import core\nfrom jax.core import raise_to_shaped, Trace, Tracer\nfrom jax._src import source_info_util\n-from jax._src.tree_util import tree_unflatten, tree_flatten\n+from jax._src.tree_util import (tree_unflatten, tree_flatten,\n+ register_pytree_node)\nfrom jax._src.ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval,\nzeros_like_p, Zero)\nfrom jax import linear_util as lu\n@@ -33,31 +37,122 @@ from jax._src.util import (unzip2, unzip3, safe_map, safe_zip, wrap_name,\nweakref_lru_cache)\nfrom jax.interpreters import partial_eval as pe\n+Array = Any\nmap, unsafe_map = safe_map, map\nzip, unsafe_zip = safe_zip, zip\n+\n+# Piles\n+\n+# i:(Fin 3) => f32[[3, 1, 4].i]\n+@dataclasses.dataclass(frozen=True)\n+class PileTy:\n+ binder: core.Var\n+ length: Union[int, Tracer, core.Var]\n+ elt_ty: core.DShapedArray\n+ def __repr__(self) -> str:\n+ return f'Var{id(self.binder)}:{self.length} => {self.elt_ty}'\n+ replace = dataclasses.replace\n+\n+# [3, 1, 4].i\n+@dataclasses.dataclass(frozen=True)\n+class IndexedAxisSize:\n+ idx: core.Var\n+ lengths: Union[Array, core.Var, Tracer]\n+ def __repr__(self) -> str:\n+ return f'{str(self.lengths)}.Var{id(self.idx)}'\n+ replace = dataclasses.replace\n+\n+# Pile(aval=a:3 => f32[[3 1 4].a],\n+# data=DeviceArray([0., 1., 2., 0., 0., 1., 2., 3.], dtype=float32))\n+@dataclasses.dataclass(frozen=True)\n+class Pile:\n+ aval: PileTy\n+ data: Array\n+\n+def _pile_flatten(pile):\n+ lengths = []\n+ new_shape = [lengths.append(d.lengths) or d.replace(lengths=len(lengths))\n+ if type(d) is IndexedAxisSize else d\n+ for d in pile.aval.elt_ty.shape]\n+ elt_ty = pile.aval.elt_ty.update(shape=tuple(new_shape))\n+ aval = pile.aval.replace(elt_ty=elt_ty)\n+ return (lengths, pile.data), aval\n+\n+def _pile_unflatten(aval, x):\n+ lengths, data = x\n+ new_shape = [d.replace(lengths=lengths[d.lengths - 1])\n+ if type(d) is IndexedAxisSize else d\n+ for d in aval.elt_ty.shape]\n+ elt_ty = aval.elt_ty.update(shape=tuple(new_shape))\n+ aval = aval.replace(elt_ty=elt_ty)\n+ return Pile(aval, data)\n+\n+register_pytree_node(Pile, _pile_flatten, _pile_unflatten)\n+\n+def _pile_result(axis_size, axis, segment_lens, x):\n+ binder = core.Var(0, '', core.ShapedArray((), np.dtype('int32')))\n+ shape = list(x.shape)\n+ shape[axis] = IndexedAxisSize(binder, segment_lens)\n+ elt_ty = core.DShapedArray(tuple(shape), x.dtype, x.weak_type)\n+ return Pile(PileTy(binder, axis_size, elt_ty), x)\n+\n+@dataclasses.dataclass(frozen=True)\n+class ConcatAxis:\n+ axis: int\n+ segment_lengths: Array\n+\n+\ndef _update_annotation(\nf: lu.WrappedFun, orig_type: Optional[core.InputType],\naxis_size: core.AxisSize, axis_name: core.AxisName,\n- explicit_in_dims: Sequence[Optional[int]]) -> lu.WrappedFun:\n+ explicit_in_dims: Sequence[Optional[Union[int, ConcatAxis]]],\n+ segment_lens: Sequence[Array],\n+ ) -> lu.WrappedFun:\nif orig_type is None: return f\n# By convention, `explicit_in_dims` only accounts for explicit arguments.\nassert len(explicit_in_dims) == sum(explicit for _, explicit in orig_type)\n- # We add a batch dim to each mapped argument type. If `axis_size` is dynamic\n- # (i.e. a Tracer) the added batch dim size is a DBIdx and we add a new leading\n- # implicit argument and increment all other DBIdx.\n- new_arg = isinstance(axis_size, Tracer)\n- sz = core.DBIdx(0) if new_arg else axis_size\n- def unmap(d, a):\n- if isinstance(a, core.DShapedArray):\n- a = a.update(shape=tuple(core.DBIdx(d.val + new_arg)\n- if type(d) is core.DBIdx else d for d in a.shape))\n- return core.unmapped_aval(sz, axis_name, d, a)\n- in_dims = iter(explicit_in_dims)\n- in_type = [(unmap(next(in_dims), a), explicit) if explicit else (a, explicit)\n- for a, explicit in orig_type]\n- if new_arg: in_type = [(axis_size.aval, False), *in_type] # type: ignore\n- return lu.annotate(f, tuple(in_type))\n+ # We need to:\n+ # * if `axis_size` is dynamic, add a new implicit binder (type) for it;\n+ # * for each element of `segment_lengths`, add a new explicit binder for it;\n+ # * drop other implicit binders, replacing DBIdx which refer to them with\n+ # Name objects;\n+ # * for each (aval, in_dim) pair: if int-valued in_dim, add batch axis (int\n+ # size if `axis_size` is int, otherwise Name); if ConcatAxis-valued in_dim,\n+ # add batch axis (int if corresponding segment_lengths is concrete, Name if\n+ # not);\n+ # * generate full in_type with implicit args too.\n+\n+ class Name:\n+ def __init__(self, a): self.a = a\n+ names = [Name(a) for a, _ in orig_type]\n+ avals = [a.update(shape=tuple(names[d.val] if type(d) is pe.DBIdx else d # type: ignore\n+ for d in a.shape))\n+ if type(a) is core.DShapedArray else a for a, e in orig_type if e]\n+\n+ new_avals = [core.raise_to_shaped(core.get_aval(s)) for s in segment_lens]\n+ sz = Name(axis_size.aval) if isinstance(axis_size, Tracer) else axis_size\n+ for a, d in zip(avals, explicit_in_dims):\n+ if isinstance(d, ConcatAxis):\n+ s = segment_lens[d.segment_lengths.val]\n+ if isinstance(core.get_aval(s), core.ConcreteArray):\n+ shape = list(a.shape) # type: ignore\n+ shape[d.axis] = int(s.sum()) # specialize on shape if we can\n+ new_avals.append(a.update(shape=tuple(shape)))\n+ else:\n+ new_avals.append(a)\n+ else:\n+ new_avals.append(core.unmapped_aval(sz, axis_name, d, a)) # type: ignore\n+\n+ mentioned = {d for a in new_avals if type(a) is core.DShapedArray\n+ for d in a.shape if type(d) is Name}\n+ expl_names = set(map(Name, new_avals))\n+ impl_names = mentioned - expl_names # type: ignore\n+ impl_part = [(n.a, False) for n in impl_names] # type: ignore\n+ name_map = {n: pe.DBIdx(i) for i, n in enumerate((*impl_names, *expl_names))}\n+ expl_part = [(a.update(shape=tuple(name_map.get(d, d) for d in a.shape))\n+ if type(a) is core.DShapedArray else a, True) for a in new_avals]\n+ return lu.annotate(f, (*impl_part, *expl_part))\n### vmappable typeclass\n@@ -65,7 +160,6 @@ Vmappable = Any\nElt = Any\nMapSpec = Any\nAxisSize = Any\n-Array = Any\nGetIdx = Callable[[], Tracer] # TODO(mattjj): revise this laziness\nToEltHandler = Callable[[Callable, GetIdx, Vmappable, MapSpec], Elt]\nFromEltHandler = Callable[[Callable, AxisSize, Elt, MapSpec], Vmappable]\n@@ -75,10 +169,16 @@ def to_elt(trace: Trace, get_idx: GetIdx, x: Vmappable, spec: MapSpec) -> Elt:\nhandler = to_elt_handlers.get(type(x))\nif handler:\nreturn handler(partial(to_elt, trace, get_idx), get_idx, x, spec)\n- else:\n+ elif type(x) is Pile:\n+ (d, ias), = ((i, sz) for i, sz in enumerate(x.aval.elt_ty.shape)\n+ if type(sz) is IndexedAxisSize)\n+ return BatchTracer(trace, x.data, ConcatAxis(d, ias.lengths)) # type: ignore\n+ elif isinstance(spec, int) or spec is None:\nspec = spec and canonicalize_axis(spec, len(np.shape(x)))\nreturn (BatchTracer(trace, x, spec, source_info_util.current())\nif spec is not None else x)\n+ else:\n+ assert False\nto_elt_handlers: Dict[Type, ToEltHandler] = {}\ndef from_elt(trace: 'BatchTrace', axis_size: AxisSize, x: Elt, spec: MapSpec\n@@ -86,8 +186,11 @@ def from_elt(trace: 'BatchTrace', axis_size: AxisSize, x: Elt, spec: MapSpec\nhandler = from_elt_handlers.get(type(x))\nif handler:\nreturn handler(partial(from_elt, trace), axis_size, x, spec)\n- else:\nx_ = trace.full_raise(x)\n+ val, bdim = x_.val, x_.batch_dim\n+ if type(bdim) is ConcatAxis:\n+ return _pile_result(axis_size, bdim.axis, bdim.segment_lengths, val)\n+ else:\nreturn matchaxis(trace.axis_name, axis_size, x_.batch_dim, spec, x_.val)\nfrom_elt_handlers: Dict[Type, FromEltHandler] = {}\n@@ -119,7 +222,7 @@ def unregister_vmappable(data_type: Type) -> None:\ndel make_iota_handlers[axis_size_type]\ndef is_vmappable(x: Any) -> bool:\n- return type(x) in vmappables\n+ return type(x) is Pile or type(x) in vmappables\n@lu.transformation_with_aux\ndef flatten_fun_for_vmap(in_tree, *args_flat):\n@@ -133,16 +236,17 @@ def flatten_fun_for_vmap(in_tree, *args_flat):\nNotMapped = type(None)\nnot_mapped = None\n+\nclass BatchTracer(Tracer):\n__slots__ = ['val', 'batch_dim', 'source_info']\n- def __init__(self, trace, val, batch_dim: Optional[int],\n+ def __init__(self, trace, val, batch_dim: Union[NotMapped, int, ConcatAxis],\nsource_info: Optional[source_info_util.SourceInfo] = None):\nif config.jax_enable_checks:\n- assert type(batch_dim) in (int, NotMapped)\n+ assert type(batch_dim) in (NotMapped, int, ConcatAxis)\nif type(batch_dim) is int:\naval = raise_to_shaped(core.get_aval(val))\n- assert batch_dim is not_mapped or 0 <= batch_dim < len(aval.shape) # type: ignore\n+ assert 0 <= batch_dim < len(aval.shape) # type: ignore\nself._trace = trace\nself.val = val\nself.batch_dim = batch_dim\n@@ -153,7 +257,14 @@ class BatchTracer(Tracer):\naval = raise_to_shaped(core.get_aval(self.val))\nif self.batch_dim is not_mapped:\nreturn aval\n+ elif type(self.batch_dim) is int:\nreturn core.mapped_aval(aval.shape[self.batch_dim], self.batch_dim, aval)\n+ elif type(self.batch_dim) is ConcatAxis:\n+ shape = list(aval.shape)\n+ size_tracer = BatchTracer(self._trace, self.batch_dim.segment_lengths, 0)\n+ shape[self.batch_dim.axis] = size_tracer\n+ return core.DShapedArray(shape=tuple(shape), dtype=aval.dtype,\n+ weak_type=aval.weak_type)\ndef full_lower(self):\nif self.batch_dim is not_mapped:\n@@ -170,6 +281,12 @@ class BatchTracer(Tracer):\ndef _contents(self):\nreturn [('val', self.val), ('batch_dim', self.batch_dim)]\n+ def get_referent(self):\n+ if self.batch_dim is None or type(self.batch_dim) is int:\n+ return core.get_referent(self.val)\n+ else: # TODO(mattjj): could handle the ConcatAxis case?\n+ return self\n+\nclass BatchTrace(Trace):\ndef __init__(self, *args, axis_name, spmd_axis_name = None):\n@@ -206,8 +323,9 @@ class BatchTrace(Trace):\nif self.axis_name is core.no_axis_name:\n# If axis name is `no_axis_name` we can't find it via `core.axis_name` so\n# we reconstruct it from the information we have available\n- axis_size, = core.dedup_referents(x.shape[d] for x, d in zip(vals, dims)\n- if d is not not_mapped)\n+ sizes = (x.shape[d] if type(d) is int else len(d.segment_lengths)\n+ for x, d in zip(vals, dims) if d is not not_mapped)\n+ axis_size, = core.dedup_referents(sizes)\nreturn core.AxisEnvFrame(self.axis_name, axis_size, self.main)\nreturn core.axis_frame(self.axis_name)\n@@ -241,14 +359,17 @@ class BatchTrace(Trace):\nvals, dims = unzip2((t.val, t.batch_dim) for t in tracers)\nif all(bdim is not_mapped for bdim in dims):\nreturn call_primitive.bind(f, *vals, **params)\n- else:\n- f_, dims_out = batch_subtrace(f, self.main, dims)\n- axis_size, = core.dedup_referents(x.shape[d] for x, d in zip(vals, dims)\n- if d is not not_mapped)\n- f_ = _update_annotation(f_, f.in_type, axis_size, self.axis_name, dims)\n- vals_out = call_primitive.bind(f_, *vals, **params)\n+ sizes = (x.shape[d] if type(d) is int else len(d.segment_lengths)\n+ for x, d in zip(vals, dims) if d is not not_mapped)\n+ axis_size, = core.dedup_referents(sizes)\n+ segment_lens, dims = unpack_concat_axes(dims)\n+ f_, dims_out = batch_subtrace(f, self.main, tuple(dims))\n+ f_ = _update_annotation(f_, f.in_type, axis_size, self.axis_name, dims,\n+ segment_lens)\n+ vals_out = call_primitive.bind(f_, *segment_lens, *vals, **params)\n+ vals_out, dims_out = reassemble_concat_axes(vals_out, dims_out())\nsrc = source_info_util.current()\n- return [BatchTracer(self, v, d, src) for v, d in zip(vals_out, dims_out())]\n+ return [BatchTracer(self, v, d, src) for v, d in zip(vals_out, dims_out)]\ndef post_process_call(self, call_primitive, out_tracers, params):\nvals, dims, srcs = unzip3((t.val, t.batch_dim, t.source_info)\n@@ -465,15 +586,36 @@ def vtile(f_flat: lu.WrappedFun,\n@lu.transformation_with_aux\ndef batch_subtrace(main, in_dims, *in_vals):\n- # used in e.g. process_call\ntrace = main.with_cur_sublevel()\nin_dims = in_dims() if callable(in_dims) else in_dims\n+ in_vals, in_dims = reassemble_concat_axes(in_vals, in_dims)\nin_tracers = [BatchTracer(trace, x, dim, source_info_util.current())\nif dim is not None else x for x, dim in zip(in_vals, in_dims)]\nouts = yield in_tracers, {}\nout_tracers = map(trace.full_raise, outs)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n- yield out_vals, out_dims\n+ segment_lens, out_dims = unpack_concat_axes(out_dims)\n+ yield (*segment_lens, *out_vals), out_dims\n+\n+def unpack_concat_axes(dims):\n+ if not any(type(d) is ConcatAxis for d in dims):\n+ return [], dims\n+ concat_axis_map = collections.OrderedDict()\n+ def convert(d: ConcatAxis) -> ConcatAxis:\n+ _, dbidx = concat_axis_map.setdefault(\n+ id(core.get_referent(d.segment_lengths)),\n+ (d.segment_lengths, pe.DBIdx(len(concat_axis_map))))\n+ return ConcatAxis(d.axis, dbidx)\n+ new_dims = [convert(d) if isinstance(d, ConcatAxis) else d for d in dims]\n+ segment_lens = [s for s, _ in concat_axis_map.values()]\n+ return segment_lens, new_dims\n+\n+def reassemble_concat_axes(vals, dims):\n+ idxs = {d.segment_lengths.val for d in dims if isinstance(d, ConcatAxis)}\n+ dims = [ConcatAxis(d.axis, vals[d.segment_lengths.val])\n+ if isinstance(d, ConcatAxis) else d for d in dims]\n+ vals = [x for i, x in enumerate(vals) if i not in idxs]\n+ return vals, dims\n### API for batching jaxprs\n@@ -668,11 +810,34 @@ def defreducer(prim):\ndef reducer_batcher(prim, batched_args, batch_dims, axes, **params):\noperand, = batched_args\nbdim, = batch_dims\n+ if isinstance(bdim, int):\naxes = tuple(np.where(np.less(axes, bdim), axes, np.add(axes, 1)))\nbdim_out = int(list(np.delete(np.arange(operand.ndim), axes)).index(bdim))\nif 'input_shape' in params:\nparams = dict(params, input_shape=operand.shape)\nreturn prim.bind(operand, axes=axes, **params), bdim_out\n+ elif isinstance(bdim, ConcatAxis):\n+ if bdim.axis in axes:\n+ other_axes = [i for i in axes if i != bdim.axis]\n+ if other_axes:\n+ operand = prim.bind(operand, axes=other_axes, **params)\n+ c_axis = bdim.axis - sum(d < bdim.axis for d in other_axes)\n+ operand = bdim_at_front(operand, c_axis, operand.shape[c_axis])\n+ return segment_sum(operand, bdim.segment_lengths), 0\n+ else:\n+ raise NotImplementedError # TODO(mattjj)\n+ else:\n+ assert False\n+\n+# TODO(mattjj): replace with jax.lax.ops.segment_sum (once it's easier to trace\n+# under dynamic shapes)\n+def segment_sum(operand, segment_lens):\n+ scat_idx = jax.numpy.cumsum(segment_lens) - segment_lens\n+ segment_ids = jax.numpy.cumsum(\n+ jax.numpy.zeros(operand.shape[0], 'int32').at[scat_idx].set(1)) - 1\n+ out = jax.numpy.zeros((len(segment_lens), *operand.shape[1:]),\n+ operand.dtype).at[segment_ids].add(operand)\n+ return out\n### general utilities for manipulating axes on jaxpr types (not vmappables)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -2224,14 +2224,13 @@ def _add_implicit_outputs(jaxpr: Jaxpr) -> Tuple[Jaxpr, OutputType]:\nclass TracerAsName:\n- tracer: DynamicJaxprTracer\n+ ref: Any\ndef __init__(self, tracer):\n- trace = core.thread_local_state.trace_state.trace_stack.dynamic\n- self.tracer = trace.with_cur_sublevel().full_raise(tracer)\n+ self.ref = core.get_referent(tracer)\ndef __eq__(self, other):\n- return isinstance(other, TracerAsName) and self.tracer is other.tracer\n+ return isinstance(other, TracerAsName) and self.ref is other.ref\ndef __hash__(self):\n- return id(self.tracer)\n+ return id(self.ref)\ndef _extract_implicit_args(\ntrace: DynamicJaxprTrace, in_type: Sequence[Tuple[AbstractValue, bool]],\n" }, { "change_type": "MODIFY", "old_path": "jax/linear_util.py", "new_path": "jax/linear_util.py", "diff": "@@ -245,14 +245,17 @@ def annotate(f: WrappedFun, in_type: core.InputType) -> WrappedFun:\ndef _check_input_type(in_type: core.InputType) -> None:\n# Check that in_type is syntactically well-formed\n- assert (type(in_type) is tuple and all(type(e) is tuple for e in in_type) and\n- all(isinstance(a, core.AbstractValue) and type(b) is bool\n- and not isinstance(a, core.ConcreteArray) for a, b in in_type) and\n- all(isinstance(d, (int, core.DBIdx, core.DArray))\n- and (not isinstance(d, core.DArray) or\n- type(d.dtype) is core.bint and not d.shape)\n- for a, _ in in_type if type(a) is core.DShapedArray\n- for d in a.shape))\n+ assert type(in_type) is tuple and all(type(e) is tuple for e in in_type)\n+ assert all(isinstance(a, core.AbstractValue) and type(b) is bool\n+ and not isinstance(a, core.ConcreteArray) for a, b in in_type)\n+\n+ def valid_size(d) -> bool:\n+ if isinstance(d, core.DBIdx) and type(d.val) is int and d.val >= 0:\n+ return True\n+ return (isinstance(d, (int, core.DBIdx, core.DArray)) and\n+ (not isinstance(d, core.DArray) or type(d) is core.bint and not d.shape))\n+ assert all(valid_size(d) for a, _ in in_type if type(a) is core.DShapedArray\n+ for d in a.shape)\n# Check that all DBIdx point to positions to the left of the input on which\n# they appear.\n" }, { "change_type": "MODIFY", "old_path": "tests/dynamic_api_test.py", "new_path": "tests/dynamic_api_test.py", "diff": "@@ -22,7 +22,9 @@ from absl.testing import absltest\nimport jax\nimport jax.numpy as jnp\n-from jax import core, lax\n+from jax import core\n+from jax import lax\n+from jax.interpreters import batching\nimport jax._src.lib\nfrom jax._src import test_util as jtu\nimport jax._src.util\n@@ -1437,6 +1439,52 @@ class DynamicShapeTest(jtu.JaxTestCase):\ny = jnp.arange(3.0) + 1\njax.make_jaxpr(f)(x, y) # doesn't crash\n+# TODO(https://github.com/google/jax/issues/12291): Enable jax.Array\n+@jtu.with_config(jax_dynamic_shapes=True, jax_numpy_rank_promotion=\"allow\",\n+ jax_array=False)\n+class PileTest(jtu.JaxTestCase):\n+\n+ def test_internal_pile(self):\n+ xs = jax.vmap(lambda n: jnp.arange(n).sum())(jnp.array([3, 1, 4]))\n+ self.assertAllClose(xs, jnp.array([3, 0, 6]), check_dtypes=False)\n+\n+ def test_make_pile_from_dynamic_shape(self):\n+ # We may not want to support returning piles from vmapped functions (instead\n+ # preferring to have a separate API which allows piles). But for now it\n+ # makes for a convenient way to construct piles for the other tests!\n+ p = jax.vmap(partial(jnp.arange, dtype='int32'))(jnp.array([3, 1, 4]))\n+ self.assertIsInstance(p, batching.Pile)\n+ self.assertRegex(str(p.aval), r'Var[0-9]+:3 => i32\\[\\[3 1 4\\]\\.Var[0-9]+\\]')\n+ data = jnp.concatenate([jnp.arange(3), jnp.arange(1), jnp.arange(4)])\n+ self.assertAllClose(p.data, data, check_dtypes=False)\n+\n+ def test_pile_map_eltwise(self):\n+ p = jax.vmap(partial(jnp.arange, dtype='int32'))(jnp.array([3, 1, 4]))\n+ p = pile_map(lambda x: x ** 2)(p)\n+ self.assertIsInstance(p, batching.Pile)\n+ self.assertRegex(str(p.aval), r'Var[0-9]+:3 => i32\\[\\[3 1 4\\]\\.Var[0-9]+\\]')\n+ data = jnp.concatenate([jnp.arange(3), jnp.arange(1), jnp.arange(4)]) ** 2\n+ self.assertAllClose(p.data, data, check_dtypes=False)\n+\n+ def test_pile_map_vector_dot(self):\n+ p = jax.vmap(jnp.arange)(jnp.array([3, 1, 4]))\n+ y = pile_map(jnp.dot)(p, p)\n+ self.assertAllClose(y, jnp.array([5, 0, 14]))\n+\n+ def test_pile_map_matrix_dot(self):\n+ sizes = jnp.array([3, 1, 4])\n+ p1 = jax.vmap(lambda n: jnp.ones((7, n)))(sizes)\n+ p2 = jax.vmap(lambda n: jnp.ones((n, 7)))(sizes)\n+ y = pile_map(jnp.dot)(p1, p2)\n+ self.assertAllClose(y, np.tile(np.array([3, 1, 4])[:, None, None], (7, 7)),\n+ check_dtypes=False)\n+\n+# TODO(mattjj): could just make this vmap, just need to adjust how we infer axis\n+# sizes in api.py's _mapped_axis_size to handle piles. For another day...\n+def pile_map(f):\n+ def mapped(*piles):\n+ return jax.vmap(f, axis_size=piles[0].aval.length)(*piles)\n+ return mapped\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
add a basic prototype of piles, behind jax_dynamic_shapes Co-authored-by: Adam Paszke <apaszke@google.com> Co-authored-by: Dougal Maclaurin <dougalm@google.com>
260,411
07.11.2022 11:18:32
-7,200
d9b1dc336d4759c3ddc08f8c1837b5dd386857bc
[jax2tf] Fixed jax2tf Limitations Improved the documentation, and fixed a dot_general limitations for preferred_element_type on GPU
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "new_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "diff": "# Primitives with limited JAX support\n-*Last generated on: 2022-10-26* (YYYY-MM-DD)\n+*Last generated on: 2022-11-07* (YYYY-MM-DD)\n## Supported data types for primitives\n-We use a set of 7296 test harnesses to test\n-the implementation of 129 numeric JAX primitives.\n+We use a set of 7308 test harnesses to test\n+the implementation of 130 numeric JAX primitives.\nWe consider a JAX primitive supported for a particular data\ntype if it is supported on at least one device type.\nThe following table shows the dtypes at which primitives\n@@ -68,6 +68,7 @@ be updated.\n| convert_element_type | 201 | all | |\n| cos | 6 | inexact | bool, integer |\n| cosh | 6 | inexact | bool, integer |\n+| cumlogsumexp | 12 | float16, float32, float64 | bfloat16, bool, complex, integer |\n| cummax | 34 | inexact, integer | bool |\n| cummin | 34 | inexact, integer | bool |\n| cumprod | 34 | inexact, integer | bool |\n@@ -194,6 +195,7 @@ and search for \"limitation\".\n|cholesky|unimplemented|float16|cpu, gpu|\n|clamp|unimplemented|bool, complex|cpu, gpu, tpu|\n|conv_general_dilated|preferred_element_type not implemented for integers|int16, int32, int8|gpu|\n+|dot_general|preferred_element_type must match dtype for floating point|inexact|gpu|\n|eig|only supported on CPU in JAX|all|tpu, gpu|\n|eig|unimplemented|bfloat16, float16|cpu|\n|eigh|unimplemented|bfloat16, float16|cpu, gpu|\n" }, { "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): 2022-10-26*\n+*Last generated on (YYYY-MM-DD): 2022-11-07*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -70,6 +70,7 @@ More detailed information can be found in the\n| div | TF error: TF integer division fails if divisor contains 0; JAX returns NaN | integer | cpu, gpu, tpu | compiled, eager, graph |\n| dot_general | TF error: Numeric comparison disabled: Large tolerances when upcasting with preferred_element_type on CPU (b/241740367) | all | cpu, gpu, tpu | compiled, eager, graph |\n| dot_general | TF error: Numeric comparison disabled: Non-deterministic NaN for dot_general with preferred_element_type on GPU (b/189287598) | bfloat16, complex64, float16, float32 | gpu | compiled, eager, graph |\n+| dot_general | TF test skipped: Not implemented in JAX: preferred_element_type must match dtype for floating point | inexact | gpu | compiled, eager, graph |\n| dot_general | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n| eig | TF test skipped: Not implemented in JAX: only supported on CPU in JAX | all | gpu, tpu | compiled, eager, graph |\n| eig | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu | compiled, 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": "@@ -38,7 +38,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndescription: str,\n*,\ndevices: Union[str, Sequence[str]] = (\"cpu\", \"gpu\", \"tpu\"),\n- dtypes: Union[DType, Sequence[DType]] = (),\n+ dtypes: Sequence[DType] = (),\nenabled: bool = True,\n# jax2tf specific\nmodes=(\"eager\", \"graph\", \"compiled\"),\n@@ -101,6 +101,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndtype: Optional[DType] = None,\ndevice: Optional[str] = None,\nmode: Optional[str] = None) -> bool:\n+ \"Checks whether this limitation is enabled for dtype and device and mode.\"\nreturn ((mode is None or mode in self.modes) and\nsuper().filter(device=device, dtype=dtype))\n@@ -170,12 +171,12 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndef acos(cls, harness: primitive_harness.Harness):\nreturn [\ncustom_numeric(\n- dtypes=np.complex64,\n+ dtypes=[np.complex64],\ndevices=(\"cpu\", \"gpu\"),\ntol=1e-4,\nmodes=(\"eager\", \"graph\", \"compiled\")),\ncustom_numeric(\n- dtypes=np.complex128,\n+ dtypes=[np.complex128],\ndevices=(\"cpu\", \"gpu\"),\ntol=1e-13,\nmodes=(\"eager\", \"graph\", \"compiled\")),\n@@ -184,8 +185,8 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef acosh(cls, harness: primitive_harness.Harness):\nreturn [\n- custom_numeric(dtypes=np.complex64, devices=(\"cpu\", \"gpu\"), tol=1e-3),\n- custom_numeric(dtypes=np.complex128, devices=(\"cpu\", \"gpu\"), tol=1e-12),\n+ custom_numeric(dtypes=[np.complex64], devices=(\"cpu\", \"gpu\"), tol=1e-3),\n+ custom_numeric(dtypes=[np.complex128], devices=(\"cpu\", \"gpu\"), tol=1e-12),\ncls.helper_get_trig_custom_limitation(np.cosh)\n]\n@@ -219,9 +220,9 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef asin(cls, harness: primitive_harness.Harness):\nreturn [\n- custom_numeric(dtypes=np.complex64, devices=(\"cpu\", \"gpu\"), tol=1e-4,\n+ custom_numeric(dtypes=[np.complex64], devices=(\"cpu\", \"gpu\"), tol=1e-4,\nmodes=(\"eager\", \"graph\", \"compiled\")),\n- custom_numeric(dtypes=np.complex128, devices=(\"cpu\", \"gpu\"), tol=1e-12,\n+ custom_numeric(dtypes=[np.complex128], devices=(\"cpu\", \"gpu\"), tol=1e-12,\nmodes=(\"eager\", \"graph\", \"compiled\")),\ncls.helper_get_trig_custom_limitation(np.sin)\n]\n@@ -229,25 +230,25 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef asinh(cls, harness: primitive_harness.Harness):\nreturn [\n- custom_numeric(dtypes=np.complex64, devices=(\"cpu\", \"gpu\"), tol=1e-3),\n- custom_numeric(dtypes=np.complex128, devices=(\"cpu\", \"gpu\"), tol=1e-12),\n+ custom_numeric(dtypes=[np.complex64], devices=(\"cpu\", \"gpu\"), tol=1e-3),\n+ custom_numeric(dtypes=[np.complex128], devices=(\"cpu\", \"gpu\"), tol=1e-12),\ncls.helper_get_trig_custom_limitation(np.sinh)\n]\n@classmethod\ndef atan(cls, harness: primitive_harness.Harness):\nreturn [\n- custom_numeric(dtypes=np.complex64, devices=(\"cpu\", \"gpu\"), tol=1e-5),\n- custom_numeric(dtypes=np.complex128, devices=(\"cpu\", \"gpu\"), tol=1e-12),\n+ custom_numeric(dtypes=[np.complex64], devices=(\"cpu\", \"gpu\"), tol=1e-5),\n+ custom_numeric(dtypes=[np.complex128], devices=(\"cpu\", \"gpu\"), tol=1e-12),\ncls.helper_get_trig_custom_limitation(np.tan)\n]\n@classmethod\ndef atanh(cls, harness: primitive_harness.Harness):\nreturn [\n- custom_numeric(dtypes=np.float64, tol=1e-14),\n- custom_numeric(dtypes=np.complex64, tol=1e-3),\n- custom_numeric(dtypes=np.complex128, devices=(\"cpu\", \"gpu\"), tol=1e-12),\n+ custom_numeric(dtypes=[np.float64], tol=1e-14),\n+ custom_numeric(dtypes=[np.complex64], tol=1e-3),\n+ custom_numeric(dtypes=[np.complex128], devices=(\"cpu\", \"gpu\"), tol=1e-12),\ncls.helper_get_trig_custom_limitation(np.tanh)\n]\n@@ -305,10 +306,10 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nreturn [\n# Even in compiled mode, for GPU we see a bit of discrepancy but\n# very minor.\n- custom_numeric(dtypes=np.float32, devices=\"gpu\",\n+ custom_numeric(dtypes=[np.float32], devices=\"gpu\",\nmodes=(\"eager\", \"graph\", \"compiled\"),\ntol=1e-5),\n- custom_numeric(dtypes=np.float32, devices=\"cpu\",\n+ custom_numeric(dtypes=[np.float32], devices=\"cpu\",\nmodes=(\"eager\", \"graph\", \"compiled\"),\ntol=1e-4),\ncustom_numeric(description=\"higher numeric inaccuracy when `enable_xla=False`\",\n@@ -356,11 +357,11 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nreturn [\nJax2TfLimitation(\n\"TODO: large numerical discrepancy\",\n- dtypes=np.float32,\n+ dtypes=[np.float32],\ndevices=\"tpu\",\nexpect_tf_error=False,\nskip_comparison=True),\n- custom_numeric(dtypes=np.float32, devices=\"tpu\", tol=0.01),\n+ custom_numeric(dtypes=[np.float32], devices=\"tpu\", tol=0.01),\ncustom_numeric(tol=1e-3),\n]\n@@ -396,10 +397,10 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndtypes=[dtypes.bfloat16],\ndevices=(\"cpu\", \"gpu\"),\nmodes=(\"eager\", \"graph\")),\n- custom_numeric(dtypes=np.float64, tol=1e-13),\n- custom_numeric(dtypes=np.float32, devices=[\"cpu\", \"gpu\"], tol=1e-3),\n+ custom_numeric(dtypes=[np.float64], tol=1e-13),\n+ custom_numeric(dtypes=[np.float32], devices=[\"cpu\", \"gpu\"], tol=1e-3),\ncustom_numeric(\n- dtypes=dtypes.bfloat16,\n+ dtypes=[dtypes.bfloat16],\ncustom_assert=custom_assert,\ndescription=(\n\"May return different results at singularity points 0 and -1.\"\n@@ -567,13 +568,13 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nreturn [\nmissing_tf_kernel(\n- dtypes=dtypes.bfloat16,\n+ dtypes=[dtypes.bfloat16],\ndevices=\"tpu\",\nenabled=(harness.params[\"shape\"] != (0, 0)), # This actually works!\n),\nJax2TfLimitation(\n\"TODO: numeric discrepancies\",\n- dtypes=np.float16,\n+ dtypes=[np.float16],\ndevices=\"tpu\",\nexpect_tf_error=False,\nskip_comparison=True),\n@@ -626,7 +627,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef expm1(cls, harness: primitive_harness.Harness):\n- return [custom_numeric(dtypes=np.float64, tol=1e-5)]\n+ return [custom_numeric(dtypes=[np.float64], tol=1e-5)]\n@classmethod\ndef fft(cls, harness):\n@@ -743,7 +744,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndtypes=[dtypes.bfloat16, np.float16],\ndevices=(\"cpu\", \"gpu\"),\nmodes=(\"eager\", \"graph\")),\n- custom_numeric(dtypes=np.float64, tol=1e-9),\n+ custom_numeric(dtypes=[np.float64], tol=1e-9),\ncustom_numeric(devices=\"gpu\", tol=1e-3),\ncustom_numeric(\ncustom_assert=custom_assert,\n@@ -777,7 +778,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nexpect_tf_error=False,\nmodes=(\"eager\", \"graph\"),\nskip_comparison=True),\n- custom_numeric(dtypes=dtypes.bfloat16, tol=2e-2)\n+ custom_numeric(dtypes=[dtypes.bfloat16], tol=2e-2)\n] + list(cls._pow_test_util(harness))\n@classmethod\n@@ -791,16 +792,16 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndtypes=[dtypes.bfloat16],\ndevices=(\"cpu\", \"gpu\"),\nmodes=(\"eager\", \"graph\")),\n- custom_numeric(dtypes=np.float64, tol=1e-11),\n- custom_numeric(dtypes=np.float32, tol=1e-3)\n+ custom_numeric(dtypes=[np.float64], tol=1e-11),\n+ custom_numeric(dtypes=[np.float32], tol=1e-3)\n]\n@classmethod\ndef log1p(cls, harness: primitive_harness.Harness):\nreturn [\n- custom_numeric(dtypes=np.complex128, tol=3e-14),\n- custom_numeric(dtypes=np.float64, tol=1e-10),\n- custom_numeric(dtypes=np.float32, tol=1e-3)\n+ custom_numeric(dtypes=[np.complex128], tol=3e-14),\n+ custom_numeric(dtypes=[np.float64], tol=1e-10),\n+ custom_numeric(dtypes=[np.float32], tol=1e-3)\n]\n@classmethod\n@@ -958,7 +959,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef regularized_incomplete_beta(cls, harness: primitive_harness.Harness):\nreturn [\n- custom_numeric(dtypes=np.float64, tol=1e-14),\n+ custom_numeric(dtypes=[np.float64], tol=1e-14),\nmissing_tf_kernel(dtypes=[np.float16, dtypes.bfloat16])\n]\n@@ -1240,16 +1241,16 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef tan(cls, harness):\nreturn [\n- custom_numeric(dtypes=np.complex64, devices=\"tpu\", tol=1e-4),\n- custom_numeric(dtypes=np.complex64, devices=(\"cpu\", \"gpu\"), tol=1e-3),\n- custom_numeric(dtypes=np.complex128, devices=(\"cpu\", \"gpu\"), tol=1e-12)\n+ custom_numeric(dtypes=[np.complex64], devices=\"tpu\", tol=1e-4),\n+ custom_numeric(dtypes=[np.complex64], devices=(\"cpu\", \"gpu\"), tol=1e-3),\n+ custom_numeric(dtypes=[np.complex128], devices=(\"cpu\", \"gpu\"), tol=1e-12)\n]\n@classmethod\ndef tanh(cls, harness):\nreturn [\n- custom_numeric(dtypes=np.complex128, tol=1e-7),\n- custom_numeric(dtypes=np.complex64, tol=1e-4)\n+ custom_numeric(dtypes=[np.complex128], tol=1e-7),\n+ custom_numeric(dtypes=[np.complex64], tol=1e-4)\n]\n@classmethod\n@@ -1287,7 +1288,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndtypes=[np.float16],\ndevices=(\"gpu\", \"cpu\"),\nmodes=(\"eager\", \"graph\")),\n- custom_numeric(dtypes=np.float32, tol=5e-3)\n+ custom_numeric(dtypes=[np.float32], tol=5e-3)\n]\n@classmethod\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax_primitives_coverage_test.py", "new_path": "jax/experimental/jax2tf/tests/jax_primitives_coverage_test.py", "diff": "@@ -53,6 +53,8 @@ class JaxPrimitiveTest(jtu.JaxTestCase):\nmessage=\"Using reduced precision for gradient.*\")\ndef test_jax_implemented(self, harness: primitive_harness.Harness):\n\"\"\"Runs all harnesses just with JAX to verify the jax_unimplemented field.\n+\n+ Runs also harnesses that have jax_unimplemented but ignores their errors.\n\"\"\"\njax_unimpl = [l for l in harness.jax_unimplemented\nif l.filter(device=jtu.device_under_test(),\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "# limitations under the License.\n\"\"\"Defines test inputs and invocations for JAX primitives.\n-The idea is that we want to list all the JAX numeric primitives along with\n-a set of inputs that should cover the use cases for each primitive.\n-We want these separate from any particular test suite so we can reuse it\n-to build multiple kinds of tests. For example, we can use the harnesses to check\n+A primitive harness encodes one use case for one JAX numeric primitives. It\n+describes how to generate the inputs and parameters and how to invoke the\n+JAX primitive. A primitive harness can be used in multiple kinds of tests.\n+For example, we can use the harnesses to check\nthat each primitive is compiled correctly, or that we can apply a certain\ntransformation, e.g., `vmap`.\n@@ -25,7 +25,7 @@ use case of one primitive.\nSome use cases are known to be partially implemented\nin JAX, e.g., because of an implementation limitation. We do have harnesses\n-for those cases too, but we filter them out.\n+for those cases too, but there is a mechanism to filter them out.\nInstead of writing this information as conditions inside one\nparticular test, we write them as `Limitation` objects that can be reused in\nmultiple tests and can also be used to generate documentation, e.g.,\n@@ -119,7 +119,6 @@ class Harness:\nharness.dyn_args_maked(rng))`,\nwhere `harness.dyn_fun` is `harness.fun` specialized to the static arguments.\n-\nFor example, a harness for ``lax.take(arr, indices, axis=None)`` may want\nto expose as external (non-static) argument the array and the indices, and\nkeep the axis as a static argument (technically specializing the `take` to\n@@ -310,7 +309,7 @@ class Limitation:\n*,\nenabled: bool = True,\ndevices: Union[str, Sequence[str]] = (\"cpu\", \"gpu\", \"tpu\"),\n- dtypes: Union[DType, Sequence[DType]] = (),\n+ dtypes: Sequence[DType] = (),\nskip_run: bool = False,\n):\n\"\"\"Args:\n@@ -321,10 +320,14 @@ class Limitation:\nit appears. This is only used during testing to know whether to ignore\nharness errors. Use this sparingly, prefer `devices` and\n`dtypes` for enabled conditions that are included in reports.\n- devices: the list of device types for which this applies. Used for\n- filtering during harness execution, and for reports.\n- dtypes: the list of dtypes for which this applies. Used for filtering\n- during harness execution, and for reports.\n+ devices: a device type (string) or a sequence of device types\n+ for which this applies. By default, it applies to all devices types.\n+ Used for filtering during harness execution, and for reports.\n+ dtypes: the sequence of dtypes for which this applies. An empty sequence\n+ denotes all dtypes. Used for filtering during harness execution, and\n+ for reports.\n+ skip_run: this harness should not even be invoked (typically because it\n+ results in a crash). This should be rare.\n\"\"\"\nassert isinstance(description, str), f\"{description}\"\nself.description = description\n@@ -334,9 +337,7 @@ class Limitation:\nelse:\ndevices = tuple(devices)\nself.devices = devices\n- if not isinstance(dtypes, Iterable):\n- dtypes = (dtypes,)\n- else:\n+ assert isinstance(dtypes, Iterable)\ndtypes = tuple(dtypes)\nself.dtypes = dtypes\nself.enabled = enabled # Does it apply to the current harness?\n@@ -1266,7 +1267,7 @@ def _make_scatter_harness(name,\njax_unimplemented=[\nLimitation(\n\"unimplemented\",\n- dtypes=np.bool_,\n+ dtypes=[np.bool_],\nenabled=(f_lax in [lax.scatter_add, lax.scatter_mul])),\n],\nf_lax=f_lax,\n@@ -2738,13 +2739,6 @@ def _make_dot_general_harness(name,\nif preferred_element_type is not None:\nsuffix += f\"_preferred={jtu.dtype_str(preferred_element_type)}\"\n- # Check if dtype/preferred_element_type combination is allowed\n- floating_point_types = [np.float16, dtypes.bfloat16, np.float32, np.float64, np.complex64, np.complex128]\n- limitations = []\n- if preferred_element_type is not None and dtype in floating_point_types and dtype != preferred_element_type:\n- # Create limitation\n- limitations = [Limitation(\"Floating point types must match\", devices=\"gpu\", enabled=False)]\n-\ndefine(\nlax.dot_general_p,\nf\"{name}_lhs={jtu.format_shape_dtype_string(lhs_shape, dtype)}_rhs={jtu.format_shape_dtype_string(rhs_shape, dtype)}_dimensionnumbers={dimension_numbers}{suffix}\"\n@@ -2763,7 +2757,12 @@ def _make_dot_general_harness(name,\ndimension_numbers=dimension_numbers,\nprecision=precision,\npreferred_element_type=preferred_element_type,\n- jax_unimplemented=limitations\n+ jax_unimplemented=[\n+ Limitation(\"preferred_element_type must match dtype for floating point\",\n+ devices=\"gpu\",\n+ dtypes=[np.float16, dtypes.bfloat16, np.float32, np.float64, np.complex64, np.complex128],\n+ enabled=(preferred_element_type is not None and preferred_element_type != dtype))\n+ ]\n)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fixed jax2tf Limitations Improved the documentation, and fixed a dot_general limitations for preferred_element_type on GPU
260,681
07.11.2022 11:54:30
28,800
218305964fcd28690274525f73a7ebdcaf9b695f
Fix GDA error message formatting
[ { "change_type": "MODIFY", "old_path": "jax/experimental/global_device_array.py", "new_path": "jax/experimental/global_device_array.py", "diff": "@@ -288,7 +288,7 @@ class GlobalDeviceArray:\nss = get_shard_shape(self._global_shape, self._global_mesh, self.mesh_axes)\nassert all(db.shape == ss for db in self._device_buffers), (\nf\"Expected shard shape {ss} doesn't match the device buffer \"\n- f\"shape, got: {[db.shape for db in device_buffers]}\")\n+ f\"shape, got: {[db.shape for db in self._device_buffers]}\")\nif self._sharded_buffer is None:\ndtype = device_buffers[0].dtype # type: ignore\n@@ -297,7 +297,7 @@ class GlobalDeviceArray:\nif _enable_checks or config.jax_enable_checks:\nassert all(db.dtype == dtype for db in self._device_buffers), (\n\"Input arrays to GlobalDeviceArray must have matching dtypes, \"\n- f\"got: {[db.dtype for db in device_buffers]}\")\n+ f\"got: {[db.dtype for db in self._device_buffers]}\")\nself.dtype = dtype\ndef _init_buffers(self, device_buffers):\n" } ]
Python
Apache License 2.0
google/jax
Fix GDA error message formatting PiperOrigin-RevId: 486724647
260,424
07.11.2022 15:46:53
0
e80c34d6246e6628544fe22746541e87b765a757
Don't donate arguments in jit/pmap/pjit when debug_nans=True.
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -413,7 +413,9 @@ def _prepare_jit(fun, static_argnums, static_argnames, donate_argnums,\nf, args = argnums_partial_except(f, static_argnums, args, allow_invalid=True)\nf, kwargs = argnames_partial_except(f, static_argnames, kwargs)\nargs_flat, in_tree = tree_flatten((args, kwargs))\n- if donate_argnums:\n+ # Argument donation is incompatible with jax_debug_nans because it re-uses\n+ # donated buffers when rerunning the user's function.\n+ if donate_argnums and not config.jax_debug_nans:\ndonated_invars = donation_vector(donate_argnums, args, kwargs)\nelse:\ndonated_invars = (False,) * len(args_flat)\n@@ -2042,7 +2044,7 @@ def _prepare_pmap(fun, in_axes, out_axes, static_broadcasted_tuple,\ndyn_global_arg_shapes = global_arg_shapes\nargs, in_tree = tree_flatten((dyn_args, kwargs))\n- if donate_tuple:\n+ if donate_tuple and not config.jax_debug_nans:\ndonated_invars = donation_vector(donate_tuple, dyn_args, kwargs)\nelse:\ndonated_invars = (False,) * len(args)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -385,7 +385,7 @@ def pjit(fun: Callable,\nargs_flat, in_tree = tree_flatten(dyn_args)\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\n- if donate_argnums:\n+ if donate_argnums and not config.jax_debug_nans:\ndonated_invars = donation_vector(donate_argnums, dyn_args, ())\nelse:\ndonated_invars = (False,) * len(args_flat)\n" }, { "change_type": "MODIFY", "old_path": "tests/debug_nans_test.py", "new_path": "tests/debug_nans_test.py", "diff": "@@ -24,11 +24,12 @@ from jax._src import api\nfrom jax._src import test_util as jtu\nfrom jax import numpy as jnp\nfrom jax.experimental import pjit\n-import jax._src.lib\n+from jax._src.lib import xla_client\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n+xla_extension_version = getattr(xla_client, \"_version\", 0)\nclass DebugNaNsTest(jtu.JaxTestCase):\n@@ -158,6 +159,44 @@ class DebugNaNsTest(jtu.JaxTestCase):\nans = f(jnp.array([0., 1.]))\nans.block_until_ready()\n+ def testDebugNansJitWithDonation(self):\n+ # https://github.com/google/jax/issues/12514\n+ if jtu.device_under_test() == \"cpu\" and xla_extension_version < 102:\n+ raise SkipTest(\"CPU buffer donation requires jaxlib > 0.3.22\")\n+\n+ a = jnp.array(0.)\n+ with self.assertRaises(FloatingPointError):\n+ ans = jax.jit(lambda x: 0. / x, donate_argnums=(0,))(a)\n+ ans.block_until_ready()\n+\n+ def testDebugNansPmapWithDonation(self):\n+ if jtu.device_under_test() == \"cpu\" and xla_extension_version < 102:\n+ raise SkipTest(\"CPU buffer donation requires jaxlib > 0.3.22\")\n+\n+ a = jnp.zeros((1,))\n+ with self.assertRaises(FloatingPointError):\n+ ans = jax.pmap(lambda x: 0. / x, donate_argnums=(0,))(a)\n+ ans.block_until_ready()\n+\n+ @jtu.ignore_warning(message=\".*is an experimental.*\")\n+ def testDebugNansPjitWithDonation(self):\n+ if jtu.device_under_test() == \"cpu\" and xla_extension_version < 102:\n+ raise SkipTest(\"CPU buffer donation requires jaxlib > 0.3.22\")\n+\n+ if jax.device_count() < 2:\n+ raise SkipTest(\"test requires >=2 devices\")\n+\n+ p = pjit.PartitionSpec('x')\n+ f = pjit.pjit(lambda x: 0. / x,\n+ in_axis_resources=p,\n+ out_axis_resources=p,\n+ donate_argnums=(0,))\n+\n+ with jax.experimental.maps.Mesh(np.array(jax.local_devices()[:2]), ('x',)):\n+ with self.assertRaises(FloatingPointError):\n+ ans = f(jnp.array([0., 1.]))\n+ ans.block_until_ready()\n+\n# TODO(skye): add parallel inf tests, ideally by factoring out test logic\nclass DebugInfsTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Don't donate arguments in jit/pmap/pjit when debug_nans=True.
260,335
06.11.2022 22:56:51
28,800
0b463efb70f6f87feecb38465fb1c977fed2806a
tighten up vmap w/ piles: require pile_axis in_axes/out_axes
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -70,6 +70,15 @@ class Pile:\naval: PileTy\ndata: Array\n+# To vmap over a pile, one must specify the axis as PileAxis.\n+class PileAxis: pass\n+pile_axis = PileAxis()\n+\n+# As a temporary measure before we have more general JITable / ADable interfaces\n+# (analogues to vmappable), to enable Piles to be used with other\n+# transformations and higher-order primitives (primarily jit, though also grad\n+# with allow_int=True) we register them as pytrees.\n+# TODO(mattjj): add JITable / ADable interfaces, remove this pytree registration\ndef _pile_flatten(pile):\nlengths = []\nnew_shape = [lengths.append(d.lengths) or d.replace(lengths=len(lengths))\n@@ -78,7 +87,6 @@ def _pile_flatten(pile):\nelt_ty = pile.aval.elt_ty.update(shape=tuple(new_shape))\naval = pile.aval.replace(elt_ty=elt_ty)\nreturn (lengths, pile.data), aval\n-\ndef _pile_unflatten(aval, x):\nlengths, data = x\nnew_shape = [d.replace(lengths=lengths[d.lengths - 1])\n@@ -87,7 +95,6 @@ def _pile_unflatten(aval, x):\nelt_ty = aval.elt_ty.update(shape=tuple(new_shape))\naval = aval.replace(elt_ty=elt_ty)\nreturn Pile(aval, data)\n-\nregister_pytree_node(Pile, _pile_flatten, _pile_unflatten)\ndef _pile_result(axis_size, axis, segment_lens, x):\n@@ -170,6 +177,8 @@ def to_elt(trace: Trace, get_idx: GetIdx, x: Vmappable, spec: MapSpec) -> Elt:\nif handler:\nreturn handler(partial(to_elt, trace, get_idx), get_idx, x, spec)\nelif type(x) is Pile:\n+ if spec is not pile_axis:\n+ raise TypeError(\"pile input without using pile_axis in_axes spec\")\n(d, ias), = ((i, sz) for i, sz in enumerate(x.aval.elt_ty.shape)\nif type(sz) is IndexedAxisSize)\nreturn BatchTracer(trace, x.data, ConcatAxis(d, ias.lengths)) # type: ignore\n@@ -189,6 +198,9 @@ def from_elt(trace: 'BatchTrace', axis_size: AxisSize, x: Elt, spec: MapSpec\nx_ = trace.full_raise(x)\nval, bdim = x_.val, x_.batch_dim\nif type(bdim) is ConcatAxis:\n+ if spec is not pile_axis:\n+ # TODO(mattjj): improve this error message\n+ raise TypeError(\"ragged output without using pile_axis out_axes spec\")\nreturn _pile_result(axis_size, bdim.axis, bdim.segment_lengths, val)\nelse:\nreturn matchaxis(trace.axis_name, axis_size, x_.batch_dim, spec, x_.val)\n@@ -211,7 +223,7 @@ def register_vmappable(data_type: Type, spec_type: Type, axis_size_type: Type,\nfrom_elt_handlers[data_type] = from_elt\nif make_iota: make_iota_handlers[axis_size_type] = make_iota\nvmappables: Dict[Type, Tuple[Type, Type]] = {}\n-spec_types: Set[Type] = set()\n+spec_types: Set[Type] = {PileAxis}\ndef unregister_vmappable(data_type: Type) -> None:\nspec_type, axis_size_type = vmappables.pop(data_type)\n@@ -848,6 +860,12 @@ def broadcast(x, sz, axis):\nreturn jax.lax.broadcast_in_dim(x, shape, broadcast_dims)\ndef matchaxis(axis_name, sz, src, dst, x, sum_match=False):\n+ if dst == pile_axis:\n+ x = bdim_at_front(x, src, sz)\n+ elt_ty = x.aval.update(shape=x.shape[1:])\n+ aval = PileTy(core.Var(0, '', core.ShapedArray((), np.dtype('int32'))),\n+ x.shape[0], elt_ty)\n+ return Pile(aval, x)\ntry:\n_ = core.get_aval(x)\nexcept TypeError as e:\n" }, { "change_type": "MODIFY", "old_path": "tests/dynamic_api_test.py", "new_path": "tests/dynamic_api_test.py", "diff": "@@ -1452,14 +1452,16 @@ class PileTest(jtu.JaxTestCase):\n# We may not want to support returning piles from vmapped functions (instead\n# preferring to have a separate API which allows piles). But for now it\n# makes for a convenient way to construct piles for the other tests!\n- p = jax.vmap(partial(jnp.arange, dtype='int32'))(jnp.array([3, 1, 4]))\n+ p = jax.vmap(partial(jnp.arange, dtype='int32'), out_axes=batching.pile_axis\n+ )(jnp.array([3, 1, 4]))\nself.assertIsInstance(p, batching.Pile)\nself.assertRegex(str(p.aval), r'Var[0-9]+:3 => i32\\[\\[3 1 4\\]\\.Var[0-9]+\\]')\ndata = jnp.concatenate([jnp.arange(3), jnp.arange(1), jnp.arange(4)])\nself.assertAllClose(p.data, data, check_dtypes=False)\ndef test_pile_map_eltwise(self):\n- p = jax.vmap(partial(jnp.arange, dtype='int32'))(jnp.array([3, 1, 4]))\n+ p = jax.vmap(partial(jnp.arange, dtype='int32'), out_axes=batching.pile_axis\n+ )(jnp.array([3, 1, 4]))\np = pile_map(lambda x: x ** 2)(p)\nself.assertIsInstance(p, batching.Pile)\nself.assertRegex(str(p.aval), r'Var[0-9]+:3 => i32\\[\\[3 1 4\\]\\.Var[0-9]+\\]')\n@@ -1467,23 +1469,26 @@ class PileTest(jtu.JaxTestCase):\nself.assertAllClose(p.data, data, check_dtypes=False)\ndef test_pile_map_vector_dot(self):\n- p = jax.vmap(jnp.arange)(jnp.array([3, 1, 4]))\n+ p = jax.vmap(jnp.arange, out_axes=batching.pile_axis)(jnp.array([3, 1, 4]))\ny = pile_map(jnp.dot)(p, p)\n- self.assertAllClose(y, jnp.array([5, 0, 14]))\n+ self.assertIsInstance(y, batching.Pile)\n+ self.assertAllClose(y.data, jnp.array([5, 0, 14]))\ndef test_pile_map_matrix_dot(self):\nsizes = jnp.array([3, 1, 4])\n- p1 = jax.vmap(lambda n: jnp.ones((7, n)))(sizes)\n- p2 = jax.vmap(lambda n: jnp.ones((n, 7)))(sizes)\n- y = pile_map(jnp.dot)(p1, p2)\n+ p1 = jax.vmap(lambda n: jnp.ones((7, n)), out_axes=batching.pile_axis\n+ )(sizes)\n+ p2 = jax.vmap(lambda n: jnp.ones((n, 7)), out_axes=batching.pile_axis\n+ )(sizes)\n+ y = jax.vmap(jnp.dot, in_axes=batching.pile_axis, out_axes=0,\n+ axis_size=3)(p1, p2)\nself.assertAllClose(y, np.tile(np.array([3, 1, 4])[:, None, None], (7, 7)),\ncheck_dtypes=False)\n-# TODO(mattjj): could just make this vmap, just need to adjust how we infer axis\n-# sizes in api.py's _mapped_axis_size to handle piles. For another day...\ndef pile_map(f):\ndef mapped(*piles):\n- return jax.vmap(f, axis_size=piles[0].aval.length)(*piles)\n+ return jax.vmap(f, in_axes=batching.pile_axis, out_axes=batching.pile_axis,\n+ axis_size=piles[0].aval.length)(*piles)\nreturn mapped\nif __name__ == '__main__':\n" } ]
Python
Apache License 2.0
google/jax
tighten up vmap w/ piles: require pile_axis in_axes/out_axes
260,455
08.11.2022 10:49:22
28,800
96f6c1c9d414e6ebc54ff7f08115a9a9a6d6a8f8
Let is_user_frame ignore frames from stdlib. When using decorators, we found contextlib.py from stdlib sometimes become the most recent non-jax frame. But it's not a user frame.
[ { "change_type": "MODIFY", "old_path": "jax/_src/source_info_util.py", "new_path": "jax/_src/source_info_util.py", "diff": "@@ -17,6 +17,7 @@ import dataclasses\nimport functools\nimport itertools\nimport os.path\n+import sysconfig\nimport threading\nimport types\nfrom typing import Optional, Iterator, NamedTuple, Union, Tuple\n@@ -39,7 +40,13 @@ class Frame(NamedTuple):\nend_column: int\n-_exclude_paths = [os.path.dirname(jax.version.__file__)]\n+_exclude_paths = [\n+ os.path.dirname(jax.version.__file__),\n+ # Also exclude stdlib as user frames. In a non-standard Python runtime,\n+ # the following two may be different.\n+ sysconfig.get_path('stdlib'),\n+ os.path.dirname(sysconfig.__file__)\n+]\ndef register_exclusion(path):\n_exclude_paths.append(path)\n@@ -131,12 +138,12 @@ else:\ndef user_frames(source_info: SourceInfo) -> Iterator[Frame]:\n\"\"\"Iterator over the user's frames, filtering jax-internal frames.\"\"\"\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- # access, which may be slow; we call this function when e.g. adding source\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+ # Guess the user's frame is the innermost frame not in the jax source tree or\n+ # Python stdlib. We don't use traceback_util.path_starts_with because that\n+ # incurs filesystem access, which may be slow; we call this function when\n+ # e.g. adding source provenance annotations to XLA lowerings, so we don't\n+ # want to incur the cost. We consider files that end with _test.py as user\n+ # frames, to allow testing this mechanism from tests.\ntraceback = source_info.traceback\ncode, lasti = traceback.raw_frames() if traceback else ([], [])\nreturn (_raw_frame_to_frame(code[i], lasti[i]) for i in range(len(code)) # type: ignore\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_util_test.py", "new_path": "tests/jaxpr_util_test.py", "diff": "from absl.testing import absltest\n+import os\nimport gzip\nimport json\n+import jax\nfrom jax import jaxpr_util, jit, make_jaxpr, numpy as jnp\nfrom jax._src.lib import xla_client\nfrom jax._src import test_util as jtu\n@@ -82,6 +84,17 @@ class JaxprStatsTest(jtu.JaxTestCase):\nhist = jaxpr_util.source_locations(make_jaxpr(f)(1., 1.).jaxpr)\nself.assertEqual(sum(hist.values()), 4)\n+ def test_source_locations_exclude_contextlib(self):\n+\n+ def f(x):\n+ # This generates a stack where the most recent non-jax frame\n+ # comes from contextlib.\n+ return jax.named_call(jnp.cos, name='test')(x)\n+\n+ hist = jaxpr_util.source_locations(make_jaxpr(f)(1.).jaxpr)\n+ for filename in hist.keys():\n+ self.assertIn(os.path.basename(__file__), filename)\n+\ndef test_print_histogram(self):\ndef f(x, y):\ns = jit(jnp.sin)(x)\n" } ]
Python
Apache License 2.0
google/jax
Let is_user_frame ignore frames from stdlib. When using decorators, we found contextlib.py from stdlib sometimes become the most recent non-jax frame. But it's not a user frame. PiperOrigin-RevId: 486993924
260,447
08.11.2022 23:02:39
28,800
3b1ddf2881cff41ad06276b41e62644bddf9d0a6
[linalg] Add jax.scipy.special.bessel_jn (Bessel function of the first kind).
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/special.py", "new_path": "jax/_src/scipy/special.py", "diff": "# limitations under the License.\nfrom functools import partial\n+import operator\nfrom typing import cast, Any, List, Optional, Tuple\nimport numpy as np\nimport scipy.special as osp_special\nfrom jax._src import api\n-from jax import jit\n+from jax._src import dtypes\n+from jax import jit, vmap\nfrom jax import lax, core\nfrom jax.interpreters import ad\nimport jax.numpy as jnp\nfrom jax._src.lax.lax import _const as _lax_const\n-from jax._src.numpy.lax_numpy import _promote_args_inexact\n+from jax._src.numpy.lax_numpy import moveaxis, _promote_args_inexact, _promote_dtypes_inexact\nfrom jax._src.numpy.util import _wraps\nfrom jax._src.ops import special as ops_special\nfrom jax._src.typing import Array, ArrayLike\n@@ -639,6 +641,83 @@ def i1(x: ArrayLike) -> Array:\nx, = _promote_args_inexact(\"i1\", x)\nreturn lax.mul(lax.exp(lax.abs(x)), lax.bessel_i1e(x))\n+def _bessel_jn_scan_body_fun(carry, k):\n+ f0, f1, bs, z = carry\n+ f = 2.0 * (k + 1.0) * f1 / z - f0\n+\n+ def true_fn_update_bs(u):\n+ bs, f = u\n+ return bs + 2.0 * f\n+\n+ def false_fn_update_bs(u):\n+ bs, _ = u\n+ return bs\n+\n+ bs = lax.cond(jnp.mod(k, 2) == 0, true_fn_update_bs,\n+ false_fn_update_bs, operand=(bs, f))\n+\n+ f0 = f1\n+ f1 = f\n+ return (f0, f1, bs, z), f\n+\n+\n+def _bessel_jn(z: ArrayLike, *, v: int, n_iter: int=50) -> Array:\n+ f0 = _lax_const(z, 0.0)\n+ f1 = _lax_const(z, 1E-16)\n+ f = _lax_const(z, 0.0)\n+ bs = _lax_const(z, 0.0)\n+\n+ (_, _, bs, _), j_vals = lax.scan(\n+ f=_bessel_jn_scan_body_fun, init=(f0, f1, bs, z),\n+ xs=lax.iota(lax.dtype(z), n_iter+1), reverse=True)\n+\n+ f = j_vals[0] # Use the value at the last iteration.\n+ j_vals = j_vals[:v+1]\n+ j_vals = j_vals / (bs - f)\n+\n+ return j_vals\n+\n+\n+@partial(jit, static_argnames=[\"v\", \"n_iter\"])\n+def bessel_jn(z: ArrayLike, *, v: int, n_iter: int=50) -> Array:\n+ \"\"\"Bessel function of the first kind of integer order and real argument.\n+\n+ Reference:\n+ Shanjie Zhang and Jian-Ming Jin. Computation of special functions.\n+ Wiley-Interscience, 1996.\n+\n+ Args:\n+ z: The sampling point(s) at which the Bessel function of the first kind are\n+ computed.\n+ v: The order (int) of the Bessel function.\n+ n_iter: The number of iterations required for updating the function\n+ values. As a rule of thumb, `n_iter` is the smallest nonnegative integer\n+ that satisfies the condition\n+ `int(0.5 * log10(6.28 + n_iter) - n_iter * log10(1.36 + abs(z) / n_iter)) > 20`.\n+ Details in `BJNDD` (https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.f)\n+\n+ Returns:\n+ An array of shape `(v+1, *z.shape)` containing the values of the Bessel\n+ function of orders 0, 1, ..., v. The return type matches the type of `z`.\n+\n+ Raises:\n+ TypeError if `v` is not integer.\n+ ValueError if elements of array `z` are not float.\n+ \"\"\"\n+ z = jnp.asarray(z)\n+ z, = _promote_dtypes_inexact(z)\n+ z_dtype = lax.dtype(z)\n+ if dtypes.issubdtype(z_dtype, complex):\n+ raise ValueError(\"complex input not supported.\")\n+\n+ v = core.concrete_or_error(operator.index, v, 'Argument v of bessel_jn.')\n+ n_iter = core.concrete_or_error(int, n_iter, 'Argument n_iter of bessel_jn.')\n+\n+ bessel_jn_fun = partial(_bessel_jn, v=v, n_iter=n_iter)\n+ for _ in range(z.ndim):\n+ bessel_jn_fun = vmap(bessel_jn_fun)\n+ return moveaxis(bessel_jn_fun(z), -1, 0)\n+\ndef _gen_recurrence_mask(\nl_max: int, is_normalized: bool, dtype: Any\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/special.py", "new_path": "jax/scipy/special.py", "diff": "from jax._src.scipy.special import (\nbetainc as betainc,\nbetaln as betaln,\n+ bessel_jn as bessel_jn,\ndigamma as digamma,\nentr as entr,\nerf as erf,\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -317,6 +317,45 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\npartial_xlog1py = functools.partial(lsp_special.xlog1py, 0.)\nself.assertAllClose(jax.grad(partial_xlog1py)(-1.), 0., check_dtypes=False)\n+ @jtu.sample_product(\n+ [dict(order=order, z=z, n_iter=n_iter)\n+ for order, z, n_iter in zip(\n+ [0, 1, 2, 3, 6], [0.01, 1.1, 11.4, 30.0, 100.6], [5, 20, 50, 80, 200]\n+ )],\n+ )\n+ def testBesselJn(self, order, z, n_iter):\n+ def lax_fun(z):\n+ return lsp_special.bessel_jn(z, v=order, n_iter=n_iter)\n+\n+ def scipy_fun(z):\n+ vals = [osp_special.jv(v, z) for v in range(order+1)]\n+ return np.array(vals)\n+\n+ args_maker = lambda : [z]\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, rtol=1E-6)\n+ self._CompileAndCheck(lax_fun, args_maker, rtol=1E-8)\n+\n+ @jtu.sample_product(\n+ order=[3, 4],\n+ shape=[(2,), (3,), (4,), (3, 5), (2, 2, 3)],\n+ dtype=float_dtypes,\n+ )\n+ def testBesselJnRandomPositiveZ(self, order, shape, dtype):\n+ rng = jtu.rand_default(self.rng(), scale=1)\n+ points = jnp.abs(rng(shape, dtype))\n+\n+ args_maker = lambda: [points]\n+\n+ def lax_fun(z):\n+ return lsp_special.bessel_jn(z, v=order, n_iter=15)\n+\n+ def scipy_fun(z):\n+ vals = [osp_special.jv(v, z) for v in range(order+1)]\n+ return np.stack(vals, axis=0)\n+\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, rtol=1E-6)\n+ self._CompileAndCheck(lax_fun, args_maker, rtol=1E-8)\n+\n@jtu.sample_product(\nl_max=[1, 2, 3, 6],\nshape=[(5,), (10,)],\n" } ]
Python
Apache License 2.0
google/jax
[linalg] Add jax.scipy.special.bessel_jn (Bessel function of the first kind). PiperOrigin-RevId: 487146250
260,424
09.11.2022 12:08:57
0
053b8b5bcd912ad85e23cb9e052f1d903b506ae5
Checkify: fix nan_checks+PRNGKeys - a PRNGKey is never NaN! Add a guard to the nan_error_rule to not call jnp.isnan on keys.
[ { "change_type": "MODIFY", "old_path": "jax/_src/checkify.py", "new_path": "jax/_src/checkify.py", "diff": "@@ -36,6 +36,7 @@ from jax.tree_util import tree_flatten, tree_unflatten, register_pytree_node\nfrom jax._src import source_info_util, traceback_util\nfrom jax._src.lax import control_flow as cf\nfrom jax._src.config import config\n+from jax._src import prng\nfrom jax import lax\nfrom jax._src.typing import Array\nfrom jax._src.util import (as_hashable_function, unzip2, split_list, safe_map,\n@@ -559,7 +560,14 @@ def nan_error_check(prim, error, enabled_errors, *in_vals, **params):\nout = prim.bind(*in_vals, **params)\nif ErrorCategory.NAN not in enabled_errors:\nreturn out, error\n- any_nans = jnp.any(jnp.isnan(out))\n+\n+ def isnan(x):\n+ if isinstance(x, prng.PRNGKeyArray):\n+ return False\n+ return jnp.isnan(x)\n+\n+ any_nans = (jnp.any(isnan(x) for x in out)\n+ if prim.multiple_results else jnp.any(isnan(out)))\nmsg = f'nan generated by primitive {prim.name} at {summary()}'\nreturn out, assert_func(error, any_nans, msg, None)\n@@ -843,7 +851,6 @@ add_nan_check(lax.select_n_p)\nadd_nan_check(lax.max_p)\nadd_nan_check(lax.min_p)\n-\ndef assert_discharge_rule(error, enabled_errors, err, code, payload, *, msgs):\nif ErrorCategory.USER_CHECK not in enabled_errors:\nreturn [], error\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -643,6 +643,12 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertIn(\"division by zero\", errs.get())\nself.assertIn(\"index 100\", errs.get())\n+ def test_checking_key_split_with_nan_check(self):\n+ cf = checkify.checkify(\n+ lambda k: jax.random.permutation(k, jnp.array([0, 1, 2])),\n+ errors=checkify.float_checks)\n+ cf(jax.random.PRNGKey(123)) # does not crash.\n+\nclass AssertPrimitiveTests(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Checkify: fix nan_checks+PRNGKeys - a PRNGKey is never NaN! Add a guard to the nan_error_rule to not call jnp.isnan on keys.
260,368
09.11.2022 11:32:12
28,800
8ac7422e265d2d80491d26611dd6eb6d463eab32
[JAX] Disables large k test cases in ann_test. Will investigate probability properties for the corner cases in the future.
[ { "change_type": "MODIFY", "old_path": "tests/ann_test.py", "new_path": "tests/ann_test.py", "diff": "@@ -60,12 +60,14 @@ def compute_recall(result_neighbors, ground_truth_neighbors) -> float:\nclass AnnTest(jtu.JaxTestCase):\n+ # TODO(b/258315194) Investigate probability property when input is around\n+ # few thousands.\n@jtu.sample_product(\nqy_shape=[(200, 128), (128, 128)],\ndb_shape=[(128, 500), (128, 3000)],\ndtype=jtu.dtypes.all_floating,\n- k=[1, 10, 50],\n- recall=[0.9, 0.95],\n+ k=[1, 10],\n+ recall=[0.95],\n)\ndef test_approx_max_k(self, qy_shape, db_shape, dtype, k, recall):\nrng = jtu.rand_default(self.rng())\n@@ -76,14 +78,14 @@ class AnnTest(jtu.JaxTestCase):\n_, ann_args = lax.approx_max_k(scores, k, recall_target=recall)\nself.assertEqual(k, len(ann_args[0]))\nann_recall = compute_recall(np.asarray(ann_args), np.asarray(gt_args))\n- self.assertGreater(ann_recall, recall)\n+ self.assertGreaterEqual(ann_recall, recall*0.9)\n@jtu.sample_product(\nqy_shape=[(200, 128), (128, 128)],\ndb_shape=[(128, 500), (128, 3000)],\ndtype=jtu.dtypes.all_floating,\n- k=[1, 10, 50],\n- recall=[0.9, 0.95],\n+ k=[1, 10],\n+ recall=[0.95],\n)\ndef test_approx_min_k(self, qy_shape, db_shape, dtype, k, recall):\nrng = jtu.rand_default(self.rng())\n@@ -92,9 +94,8 @@ class AnnTest(jtu.JaxTestCase):\nscores = lax.dot(qy, db)\n_, gt_args = lax.top_k(-scores, k)\n_, ann_args = lax.approx_min_k(scores, k, recall_target=recall)\n- self.assertEqual(k, len(ann_args[0]))\nann_recall = compute_recall(np.asarray(ann_args), np.asarray(gt_args))\n- self.assertGreater(ann_recall, recall * 0.98)\n+ self.assertGreaterEqual(ann_recall, recall*0.9)\n@jtu.sample_product(\ndtype=[np.float32],\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Disables large k test cases in ann_test. Will investigate probability properties for the corner cases in the future. PiperOrigin-RevId: 487302143
260,356
08.11.2022 14:45:58
28,800
cb3762e5dd18a87317eacb833dc2171853a8b947
Consolidate links in JAX documentation Move notes down
[ { "change_type": "MODIFY", "old_path": "docs/index.rst", "new_path": "docs/index.rst", "diff": "@@ -15,7 +15,7 @@ parallelize, Just-In-Time compile to GPU/TPU, and more.\nnotebooks/Common_Gotchas_in_JAX\n.. toctree::\n- :maxdepth: 2\n+ :maxdepth: 1\njax-101/index\n@@ -54,20 +54,9 @@ parallelize, Just-In-Time compile to GPU/TPU, and more.\nnotebooks/xmap_tutorial\nmulti_process\n-.. toctree::\n- :maxdepth: 1\n- :caption: Notes\n-\n- api_compatibility\n- deprecation\n- concurrency\n- gpu_memory_allocation\n- profiling\n- device_memory_profiling\n- rank_promotion_warning\n.. toctree::\n- :maxdepth: 2\n+ :maxdepth: 1\n:caption: Developer documentation\ncontributing\n@@ -77,11 +66,23 @@ parallelize, Just-In-Time compile to GPU/TPU, and more.\njep/index\n.. toctree::\n- :maxdepth: 3\n+ :maxdepth: 1\n:caption: API documentation\njax\n+.. toctree::\n+ :maxdepth: 1\n+ :caption: Notes\n+\n+ api_compatibility\n+ deprecation\n+ concurrency\n+ gpu_memory_allocation\n+ profiling\n+ device_memory_profiling\n+ rank_promotion_warning\n+\nIndices and tables\n==================\n" } ]
Python
Apache License 2.0
google/jax
Consolidate links in JAX documentation Move notes down
260,510
09.11.2022 17:18:19
28,800
3731e446c0fde13b1d1863073ba39db00d92b813
Set default layout for Python callback
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -1544,12 +1544,25 @@ def _emit_tpu_python_callback(\nctx.module_context.add_host_callback(opaque)\nreturn outputs, token, opaque\n+def _layout_to_mlir_layout(minor_to_major: Optional[Sequence[int]]):\n+ if minor_to_major is None:\n+ # Needed for token layouts\n+ layout = np.zeros((0,), dtype=\"int64\")\n+ else:\n+ layout = np.array(minor_to_major, dtype=\"int64\")\n+ return ir.DenseIntElementsAttr.get(layout, type=ir.IndexType.get())\n+\n+def _aval_to_default_layout(aval):\n+ # Row major order is default for `NumPy`.\n+ return list(range(aval.ndim - 1, -1, -1))\ndef emit_python_callback(\nctx: LoweringRuleContext, callback, token: Optional[Any],\noperands: List[ir.Value], operand_avals: List[core.ShapedArray],\nresult_avals: List[core.ShapedArray],\n- has_side_effect: bool, *, sharding: Optional[xc.OpSharding] = None\n+ has_side_effect: bool, *, sharding: Optional[xc.OpSharding] = None,\n+ operand_layouts: Optional[Sequence[Optional[Sequence[int]]]] = None,\n+ result_layouts: Optional[Sequence[Optional[Sequence[int]]]] = None,\n) -> Tuple[List[ir.Value], Any, Any]:\n\"\"\"Emits MHLO that calls back to a provided Python function.\"\"\"\nplatform = ctx.module_context.platform\n@@ -1561,6 +1574,19 @@ def emit_python_callback(\n[xla.aval_to_xla_shapes(result_aval) for result_aval in result_avals])\noperand_shapes = util.flatten(\n[xla.aval_to_xla_shapes(op_aval) for op_aval in operand_avals])\n+ # Handling layouts\n+ if operand_layouts is None:\n+ operand_layouts = map(_aval_to_default_layout, operand_avals)\n+ operand_mlir_layouts = [\n+ _layout_to_mlir_layout(_aval_to_default_layout(layout)) if layout is None\n+ else _layout_to_mlir_layout(layout) for layout, aval\n+ in zip(operand_layouts, operand_avals)]\n+ if result_layouts is None:\n+ result_layouts = map(_aval_to_default_layout, result_avals)\n+ result_mlir_layouts = [\n+ _layout_to_mlir_layout(_aval_to_default_layout(aval)) if layout is None\n+ else _layout_to_mlir_layout(layout) for layout, aval\n+ in zip(result_layouts, result_avals)]\n# First we apply checks to ensure output shapes and dtypes match the expected\n# ones.\n@@ -1600,6 +1626,13 @@ def emit_python_callback(\n]\noperands = [token, *operands]\nresult_types = [token_type()[0], *result_types]\n+ if xla_extension_version >= 105:\n+ operand_mlir_layouts = [_layout_to_mlir_layout(None), *operand_mlir_layouts]\n+ result_mlir_layouts = [_layout_to_mlir_layout(None), *result_mlir_layouts]\n+ else:\n+ # Token layouts aren't converted correctly into HLO in older XLA versions.\n+ operand_mlir_layouts = None # type: ignore\n+ result_mlir_layouts = None # type: ignore\ncallback_descriptor, keepalive = (\nbackend.get_emit_python_callback_descriptor(_wrapped_callback,\noperand_shapes,\n@@ -1607,6 +1640,8 @@ def emit_python_callback(\ndescriptor_operand = ir_constant(\ncallback_descriptor, canonicalize_types=False)\ncallback_operands = [descriptor_operand, *operands]\n+ if operand_mlir_layouts is not None:\n+ operand_mlir_layouts = [_layout_to_mlir_layout([]), *operand_mlir_layouts]\nresult_type = ir.TupleType.get_tuple(result_types)\ncall_target_name = (\"xla_python_gpu_callback\"\nif platform in {\"cuda\", \"rocm\"} else \"xla_python_cpu_callback\")\n@@ -1618,8 +1653,12 @@ def emit_python_callback(\napi_version=i32_attr(2),\ncalled_computations=ir.ArrayAttr.get([]),\nbackend_config=ir.StringAttr.get(str(callback_descriptor)),\n- operand_layouts=None,\n- result_layouts=None)\n+ operand_layouts=(\n+ None if operand_mlir_layouts is None\n+ else ir.ArrayAttr.get(operand_mlir_layouts)),\n+ result_layouts=(\n+ None if result_mlir_layouts is None\n+ else ir.ArrayAttr.get(result_mlir_layouts)))\nif sharding is not None:\nset_sharding(result, sharding)\nresults = [\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -190,6 +190,39 @@ class DebugPrintTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertEqual(output(), f\"x: {str(dict(foo=np.array(2, np.int32)))}\\n\")\n+ def test_debug_print_should_use_default_layout(self):\n+ if xla_bridge.get_backend().runtime_type == 'stream_executor':\n+ raise unittest.SkipTest('Host callback not supported for runtime type: stream_executor.')\n+ data = np.array(\n+ [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14],\n+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14],\n+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14],\n+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14],\n+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14],\n+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14],\n+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14],\n+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14]], dtype=np.int32)\n+ @jax.jit\n+ def f(x):\n+ jax.debug.print(\"{}\", x)\n+\n+ with jtu.capture_stdout() as output:\n+ f(data)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ [[ 1 2 3 4 5 6 7 8 9 10 12 13 14]\n+ [ 1 2 3 4 5 6 7 8 9 10 12 13 14]\n+ [ 1 2 3 4 5 6 7 8 9 10 12 13 14]\n+ [ 1 2 3 4 5 6 7 8 9 10 12 13 14]\n+ [ 1 2 3 4 5 6 7 8 9 10 12 13 14]\n+ [ 1 2 3 4 5 6 7 8 9 10 12 13 14]\n+ [ 1 2 3 4 5 6 7 8 9 10 12 13 14]\n+ [ 1 2 3 4 5 6 7 8 9 10 12 13 14]]\n+ \"\"\"))\n+\n+\n+\n+\nclass DebugPrintTransformationTest(jtu.JaxTestCase):\ndef test_debug_print_batching(self):\n" } ]
Python
Apache License 2.0
google/jax
Set default layout for Python callback PiperOrigin-RevId: 487388682
260,510
10.11.2022 11:59:16
28,800
74b136e62c7ee8f6d29773e470094be129e1559c
Delete `jax_experimental_name_stack` flag
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -3290,20 +3290,8 @@ def named_call(\nif name is None:\nname = fun.__name__\n- _, in_tree = tree_flatten(())\n-\n- if config.jax_experimental_name_stack:\nreturn source_info_util.extend_name_stack(name)(fun)\n- @functools.wraps(fun)\n- def named_call_f(*args, **kwargs):\n- lu_f = lu.wrap_init(lambda: fun(*args, **kwargs))\n- flat_f, out_tree = flatten_fun_nokwargs(lu_f, in_tree)\n- out_flat = core.named_call_p.bind(flat_f, name=name)\n- return tree_unflatten(out_tree(), out_flat)\n-\n- return named_call_f\n-\n@contextmanager\ndef named_scope(\nname: str,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -1001,11 +1001,6 @@ config.define_bool_state(\nupdate_thread_local_hook=lambda val: \\\nupdate_thread_local_jit_state(dynamic_shapes=val))\n-config.define_bool_state(\n- name='jax_experimental_name_stack',\n- default=True,\n- help='Enable using the context manager-based name stack.')\n-\n# This flag is temporary during rollout of the remat barrier.\n# TODO(parkers): Remove if there are no complaints.\nconfig.define_bool_state(\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/util.py", "new_path": "jax/_src/util.py", "diff": "@@ -333,21 +333,16 @@ def wrap_name(name, transform_name):\nreturn transform_name + '(' + name + ')'\ndef new_name_stack(name: str = ''):\n- if config.jax_experimental_name_stack:\nfrom jax._src import source_info_util\nname_stack = source_info_util.NameStack()\nif name:\nname_stack = name_stack.extend(name)\nreturn name_stack\n- return name + '/'\ndef extend_name_stack(stack, name: str):\n- if config.jax_experimental_name_stack:\nfrom jax._src import source_info_util\nassert isinstance(stack, source_info_util.NameStack), stack\nreturn stack.extend(name)\n- assert isinstance(stack, str)\n- return stack + name + '/'\ndef canonicalize_axis(axis, num_dims) -> int:\n\"\"\"Canonicalize an axis in [-num_dims, num_dims) to [0, num_dims).\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -2073,9 +2073,6 @@ call_p: CallPrimitive = CallPrimitive('call')\ncall = call_p.bind\ncall_p.def_impl(call_impl)\n-named_call_p: CallPrimitive = CallPrimitive('named_call')\n-named_call_p.def_impl(call_impl)\n-\nclass ClosedCallPrimitive(CallPrimitive):\ndef get_bind_params(self, params):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -1651,16 +1651,6 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\n# compilation to XLA, which does not use those parameters.\nbwd=\"illegal param\",\nout_trees=\"illegal param\")))\n- elif eqn.primitive is core.named_call_p:\n- call_jaxpr = cast(core.Jaxpr, eqn.params[\"call_jaxpr\"])\n- eqns.append(\n- eqn.replace(\n- invars=eqn.invars + [input_token_var, input_itoken_var],\n- outvars=eqn.outvars + [output_token_var, output_itoken_var],\n- params=dict(\n- eqn.params,\n- call_jaxpr=_rewrite_jaxpr(call_jaxpr, True, True),\n- )))\nelif eqn.primitive is pjit.pjit_p:\njaxpr = cast(core.ClosedJaxpr, eqn.params[\"jaxpr\"])\neqns.append(\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -187,9 +187,7 @@ class _ThreadLocalState(threading.local):\n_thread_local_state = _ThreadLocalState()\ndef _get_current_name_stack() -> Union[NameStack, str]:\n- if config.jax_experimental_name_stack:\nreturn source_info_util.current_name_stack()\n- return _thread_local_state.name_stack\n@contextlib.contextmanager\ndef inside_call_tf():\n@@ -530,24 +528,12 @@ def make_custom_gradient_fn_tf(\n@contextlib.contextmanager\ndef _extended_name_stack(extra_name_stack: Optional[str]):\n- if config.jax_experimental_name_stack:\nname_ctx = (source_info_util.extend_name_stack(extra_name_stack)\nif extra_name_stack\nelse contextlib.nullcontext())\nwith name_ctx:\nyield\nreturn\n- prev_name_stack = _thread_local_state.name_stack\n- if extra_name_stack:\n- if not prev_name_stack:\n- _thread_local_state.name_stack = extra_name_stack\n- else:\n- _thread_local_state.name_stack = util.extend_name_stack(\n- _thread_local_state.name_stack, extra_name_stack)\n- try:\n- yield\n- finally:\n- _thread_local_state.name_stack = prev_name_stack\ndef _interpret_fun_jax(\n@@ -1050,20 +1036,14 @@ class TensorFlowTrace(core.Trace):\nreturn impl(*args_tf, **params)\ncurrent_name_stack = _get_current_name_stack()\n- if config.jax_experimental_name_stack:\n# We don't use `str(name_stack)` because it uses parentheses for\n# transformations, which aren't allowed in `name_scope`.\nscope = '/'.join([s.name for s in current_name_stack.stack]) # type: ignore[union-attr]\n- else:\n- scope = str(current_name_stack)\n# We need to add a '/' to the name stack string to force `tf.name_scope`\n# to interpret it as an absolute scope, not a relative scope.\nscope = scope + '/'\n- name_scope = (\n- tf.name_scope(_sanitize_scope_name(scope)) if\n- config.jax_experimental_name_stack else contextlib.nullcontext())\n- with name_scope:\n+ with tf.name_scope(_sanitize_scope_name(scope)):\nif _thread_local_state.include_xla_op_metadata:\nop_metadata = xla.make_op_metadata(primitive, params,\nname_stack=current_name_stack,\n@@ -1109,17 +1089,11 @@ class TensorFlowTrace(core.Trace):\navals: Sequence[core.ShapedArray] = tuple(t.aval for t in tracers)\ninterpreted_fun = _interpret_subtrace(fun, self.main, avals)\nextra_name_stack = None\n- if call_primitive == core.named_call_p:\n- extra_name_stack = util.wrap_name(params[\"name\"], \"named\")\n- elif call_primitive == xla.xla_call_p:\n+ if call_primitive == xla.xla_call_p:\nextra_name_stack = util.wrap_name(params[\"name\"], \"jit\")\nwith _extended_name_stack(extra_name_stack):\nwith core.new_sublevel():\n- if call_primitive == core.named_call_p:\n- with tf.name_scope(_sanitize_scope_name(params[\"name\"])):\n- vals_out: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\n- interpreted_fun.call_wrapped(*vals)\n- elif call_primitive == xla.xla_call_p:\n+ if call_primitive == xla.xla_call_p:\nif _WRAP_JAX_JIT_WITH_TF_FUNCTION:\n# Make a nested tf.function(jit_compile=True)\nstore_tf_res_avals: Sequence[core.ShapedArray] = []\n@@ -1208,7 +1182,7 @@ def _unexpected_primitive(p: core.Primitive, *args, **kwargs):\n# Call primitives are inlined\n-for unexpected in [core.call_p, core.named_call_p, xla.xla_call_p, maps.xmap_p]:\n+for unexpected in [core.call_p, xla.xla_call_p, maps.xmap_p]:\ntf_impl[unexpected] = partial(_unexpected_primitive, unexpected)\n# Primitives that are not yet implemented must be explicitly declared here.\n@@ -2615,7 +2589,6 @@ def _cond(index: TfVal, *operands: TfVal, branches: Sequence[core.ClosedJaxpr],\nfor jaxpr in branches\nfor i, jaxpr in enumerate(branches)\n]\n- if config.jax_experimental_name_stack:\n# Same name stack as XLA translation of cond_p\n# Note: extend_name_stack is a contextmanager, which is callable as a decorator.\nbranches_tf = list(map(source_info_util.extend_name_stack(\"cond\"), # type: ignore[arg-type]\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -771,12 +771,9 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nf_tf_hlo = self.TfToHlo(f_tf, arg)\nif jax.config.jax_remat_opt_barrier:\nself.assertRegex(f_tf_hlo, r\"opt-barrier\")\n- elif config.jax_experimental_name_stack:\n- self.assertRegex(f_tf_hlo,\n- r'transpose/jax2tf_f_/jvp/checkpoint/cond/branch_1_fun/Sin')\nelse:\nself.assertRegex(f_tf_hlo,\n- r'switch_case/indexed_case/Sin')\n+ r'transpose/jax2tf_f_/jvp/checkpoint/cond/branch_1_fun/Sin')\ndef test_remat_free_var(self):\ndef f(x):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -319,8 +319,6 @@ class JVPTrace(Trace):\nwhich_nz = [ type(t) is not Zero for t in tangents]\ntangents = [t if type(t) is not Zero else None for t in tangents]\nargs, in_tree = tree_flatten((primals, tangents))\n- if 'name' in params and not config.jax_experimental_name_stack:\n- params = dict(params, name=wrap_name(params['name'], 'jvp'))\nf_jvp = jvp_subtrace(f, self.main)\nf_jvp, which_nz_out = nonzero_tangent_outputs(f_jvp)\nif isinstance(call_primitive, core.MapPrimitive):\n@@ -609,8 +607,6 @@ def call_transpose(primitive, params, call_jaxpr, args, ct, _, reduce_axes):\nfun = lu.hashable_partial(lu.wrap_init(backward_pass), call_jaxpr,\nreduce_axes, False)\nfun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\n- if 'name' in params and not config.jax_experimental_name_stack:\n- params = dict(params, name=wrap_name(params['name'], 'transpose'))\nupdate_params = call_transpose_param_updaters.get(primitive)\nif update_params:\nparams = update_params(params, map(is_undefined_primal, args),\n@@ -627,8 +623,6 @@ def call_transpose(primitive, params, call_jaxpr, args, ct, _, reduce_axes):\nout_flat = primitive.bind(fun, *all_args, **params)\nreturn tree_unflatten(out_tree(), out_flat)\nprimitive_transposes[core.call_p] = partial(call_transpose, call_p)\n-primitive_transposes[core.named_call_p] = \\\n- partial(call_transpose, core.named_call_p)\ndef _closed_call_transpose(params, jaxpr, args, ct, cts_in_avals, reduce_axes):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -31,10 +31,9 @@ from jax._src.tree_util import (tree_unflatten, tree_flatten,\nfrom jax._src.ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval,\nzeros_like_p, Zero)\nfrom jax import linear_util as lu\n-from jax._src.util import (unzip2, unzip3, safe_map, safe_zip, wrap_name,\n- split_list, canonicalize_axis, moveaxis,\n- as_hashable_function, curry, memoize,\n- weakref_lru_cache)\n+from jax._src.util import (unzip2, unzip3, safe_map, safe_zip, split_list,\n+ canonicalize_axis, moveaxis, as_hashable_function,\n+ curry, memoize, weakref_lru_cache)\nfrom jax.interpreters import partial_eval as pe\nArray = Any\n@@ -352,10 +351,7 @@ class BatchTrace(Trace):\ndef process_call(self, call_primitive, f, tracers, params):\nassert call_primitive.multiple_results\n- if config.jax_experimental_name_stack:\nparams = dict(params, name=params.get('name', f.__name__))\n- else:\n- params = dict(params, name=wrap_name(params.get('name', f.__name__), 'vmap'))\nvals, dims = unzip2((t.val, t.batch_dim) for t in tracers)\nif all(bdim is not_mapped for bdim in dims):\nreturn call_primitive.bind(f, *vals, **params)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -309,13 +309,9 @@ register_constant_handler(\ndef _source_info_to_location(\nprimitive: core.Primitive, params: Dict,\nsource_info: source_info_util.SourceInfo,\n- name_stack: Union[str, source_info_util.NameStack] = \"\") -> ir.Location:\n- if config.jax_experimental_name_stack:\n+ name_stack: source_info_util.NameStack) -> ir.Location:\neqn_str = (f'{str(source_info.name_stack)}/'\nf'{core.str_eqn_compact(primitive.name, params)}')\n- else:\n- assert isinstance(name_stack, str)\n- eqn_str = name_stack + core.str_eqn_compact(primitive.name, params)\nframe = source_info_util.user_frame(source_info)\nif frame is None:\nloc = ir.Location.unknown()\n@@ -328,8 +324,6 @@ def _source_info_to_location(\n# Translation rules\n-NameStack = Union[str, source_info_util.NameStack]\n-\ndef make_ir_context() -> ir.Context:\n\"\"\"Creates an MLIR context suitable for JAX IR.\"\"\"\ncontext = ir.Context()\n@@ -414,7 +408,7 @@ class ModuleContext:\nbackend_or_name: Optional[Union[str, xb.XlaBackend]]\nplatform: str\naxis_context: AxisContext\n- name_stack: NameStack\n+ name_stack: source_info_util.NameStack\nkeepalives: List[Any]\nchannel_iterator: Iterator[int]\nhost_callbacks: List[Any]\n@@ -432,7 +426,7 @@ class ModuleContext:\nbackend_or_name: Optional[Union[str, xb.XlaBackend]],\nplatform: str,\naxis_context: AxisContext,\n- name_stack: NameStack,\n+ name_stack: source_info_util.NameStack,\nkeepalives: List[Any],\nchannel_iterator: Iterator[int],\nhost_callbacks: List[Any],\n@@ -583,7 +577,7 @@ def lower_jaxpr_to_module(\nbackend_or_name: Optional[Union[str, xb.XlaBackend]],\nplatform: str,\naxis_context: AxisContext,\n- name_stack: NameStack,\n+ name_stack: source_info_util.NameStack,\ndonated_args: Sequence[bool],\nreplicated_args: Optional[Sequence[bool]] = None,\narg_shardings: Optional[Sequence[Optional[xc.OpSharding]]] = None,\n@@ -1007,14 +1001,11 @@ def jaxpr_subcomp(ctx: ModuleContext, jaxpr: core.Jaxpr,\nmap(write, jaxpr.invars, args)\nfor eqn in jaxpr.eqns:\nin_nodes = map(read, eqn.invars)\n- if config.jax_experimental_name_stack:\nassert isinstance(ctx.name_stack, source_info_util.NameStack), type(ctx.name_stack)\nsource_info = eqn.source_info.replace(\nname_stack=ctx.name_stack + eqn.source_info.name_stack)\n- else:\n- source_info = eqn.source_info\nloc = _source_info_to_location(eqn.primitive, eqn.params, source_info,\n- name_stack=ctx.name_stack)\n+ ctx.name_stack)\nwith source_info_util.user_context(eqn.source_info.traceback), loc:\nif eqn.primitive in _platform_specific_lowerings[ctx.platform]:\nrule = _platform_specific_lowerings[ctx.platform][eqn.primitive]\n@@ -1029,8 +1020,7 @@ def jaxpr_subcomp(ctx: ModuleContext, jaxpr: core.Jaxpr,\nf\"MLIR translation rule for primitive '{eqn.primitive.name}' not \"\nf\"found for platform {ctx.platform}\")\n- eqn_ctx = (ctx.replace(name_stack=source_info.name_stack) if\n- config.jax_experimental_name_stack else ctx)\n+ eqn_ctx = ctx.replace(name_stack=source_info.name_stack)\neffects = [eff for eff in eqn.effects if eff in core.ordered_effects]\ntokens_in = tokens.subset(effects)\navals_in = map(aval, eqn.invars)\n@@ -1160,21 +1150,16 @@ def _xla_call_lower(ctx, *args,\nregister_lowering(xla.xla_call_p, _xla_call_lower)\n-def _named_call_lowering(ctx, *args, name, backend=None,\n- call_jaxpr):\n+def _core_call_lowering(ctx, *args, name, backend=None, call_jaxpr):\nout_nodes, tokens = _call_lowering(\nname, name, call_jaxpr, backend, ctx.module_context,\nctx.avals_in, ctx.avals_out, ctx.tokens_in, *args)\nctx.set_tokens_out(tokens)\nreturn out_nodes\n-register_lowering(core.named_call_p, _named_call_lowering)\n-register_lowering(core.call_p, partial(_named_call_lowering, name=\"core_call\"))\n-register_lowering(core.closed_call_p,\n- partial(_named_call_lowering, name=\"core_closed_call\"))\n-\n+register_lowering(core.call_p, partial(_core_call_lowering, name=\"core_call\"))\nregister_lowering(core.closed_call_p,\n- partial(_named_call_lowering, name=\"core_closed_call\"))\n+ partial(_core_call_lowering, name=\"core_closed_call\"))\ndef full_like_aval(value, aval: core.ShapedArray) -> ir.Value:\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1291,9 +1291,6 @@ partial_eval_jaxpr_custom_rules[core.call_p] = \\\nlambda _, __, ___, ____, _____, x, y: (x, y))\npartial_eval_jaxpr_custom_rules[core.closed_call_p] = \\\npartial(closed_call_partial_eval_custom_rule, 'call_jaxpr')\n-partial_eval_jaxpr_custom_rules[core.named_call_p] = \\\n- partial(call_partial_eval_custom_rule, 'call_jaxpr',\n- lambda _, __, ___, ____, _____, x, y: (x, y))\ndef _jaxpr_forwarding(jaxpr: Jaxpr) -> List[Optional[int]]:\n@@ -1394,7 +1391,6 @@ def dce_jaxpr_call_rule(used_outputs: List[bool], eqn: JaxprEqn\neqn.primitive, new_params, new_jaxpr.effects, eqn.source_info)\nreturn used_inputs, new_eqn\ndce_rules[core.call_p] = dce_jaxpr_call_rule\n-dce_rules[core.named_call_p] = dce_jaxpr_call_rule\ndef dce_jaxpr_closed_call_rule(used_outputs: List[bool], eqn: JaxprEqn\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -104,11 +104,8 @@ def make_op_metadata(primitive: core.Primitive,\nsource_info: source_info_util.SourceInfo,\nname_stack: Union[str, source_info_util.NameStack] = \"\",\n) -> xc.OpMetadata:\n- if config.jax_experimental_name_stack:\n- eqn_str = str(source_info.name_stack) + '/' + str_eqn_compact(primitive.name, params)\n- else:\n- assert isinstance(name_stack, str)\n- eqn_str = name_stack + str_eqn_compact(primitive.name, params)\n+ eqn_str = (str(source_info.name_stack) + '/'\n+ + str_eqn_compact(primitive.name, params))\ntracebacks[eqn_str] = source_info.traceback\nframe = source_info_util.user_frame(source_info)\nreturn xc.OpMetadata(\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -9286,12 +9286,9 @@ class NamedCallTest(jtu.JaxTestCase):\nreturn my_test_function(x)\nc = jax.xla_computation(f)(2)\n- if config.jax_experimental_name_stack:\nprint_opts = xla_client._xla.HloPrintOptions.short_parsable()\nprint_opts.print_metadata = True\nhlo_text = c.as_hlo_module().to_string(print_opts)\n- else:\n- hlo_text = c.as_hlo_text()\nself.assertIn(\"my_test_function\", hlo_text)\ndef test_non_jaxtype_arg(self):\n" }, { "change_type": "MODIFY", "old_path": "tests/jax_to_ir_test.py", "new_path": "tests/jax_to_ir_test.py", "diff": "@@ -18,7 +18,6 @@ from absl.testing import absltest\nimport jax.numpy as jnp\nfrom jax.tools import jax_to_ir\nfrom jax._src import test_util as jtu\n-from jax.config import config\ntry:\nimport tensorflow as tf\n@@ -90,14 +89,9 @@ class JaxToIRTest(absltest.TestCase):\n])\n# Check that tf debug txt contains a broadcast, add, and multiply.\n- if config.jax_experimental_name_stack:\nself.assertIn('BroadcastTo', tf_text)\nself.assertIn('AddV2', tf_text)\nself.assertIn('Mul', tf_text)\n- else:\n- self.assertIn('name: \"BroadcastTo\"', tf_text)\n- self.assertIn('name: \"AddV2\"', tf_text)\n- self.assertIn('name: \"Mul\"', tf_text)\n# Check that we can re-import our graphdef.\ngdef = tf.compat.v1.GraphDef()\n" }, { "change_type": "MODIFY", "old_path": "tests/metadata_test.py", "new_path": "tests/metadata_test.py", "diff": "@@ -63,14 +63,9 @@ class MetadataTest(jtu.JaxTestCase):\ndef foo(x):\nreturn jnp.sin(x)\nhlo = jax.xla_computation(jax.grad(foo))(1.).get_hlo_module().to_string()\n- if config.jax_experimental_name_stack:\nself.assertRegex(hlo, 'op_name=\".*jvp\\\\(jit\\\\(foo\\\\)\\\\)/sin\"')\nself.assertRegex(hlo, 'op_name=\".*jvp\\\\(jit\\\\(foo\\\\)\\\\)/cos\"')\nself.assertRegex(hlo, 'op_name=\".*transpose\\\\(jvp\\\\(jit\\\\(foo\\\\)\\\\)\\\\)/mul\"')\n- else:\n- self.assertRegex(hlo, 'op_name=\".*jit\\\\(jvp\\\\(foo\\\\)\\\\)/sin\"')\n- self.assertRegex(hlo, 'op_name=\".*jit\\\\(jvp\\\\(foo\\\\)\\\\)/cos\"')\n- self.assertRegex(hlo, 'op_name=\".*jit\\\\(transpose\\\\(jvp\\\\(foo\\\\)\\\\)\\\\)/mul\"')\ndef test_cond_metadata(self):\ndef true_fun(x):\n" }, { "change_type": "MODIFY", "old_path": "tests/name_stack_test.py", "new_path": "tests/name_stack_test.py", "diff": "@@ -33,17 +33,8 @@ def _get_hlo(f):\nreturn c.as_hlo_module().to_string(print_opts)\nreturn wrapped\n-class _EnableNameStackTestCase(jtu.JaxTestCase):\n- def setUp(self):\n- self.cfg = config._read(\"jax_experimental_name_stack\")\n- config.update(\"jax_experimental_name_stack\", True)\n-\n- def tearDown(self):\n- config.update(\"jax_experimental_name_stack\", self.cfg)\n-\n-\n-class NameStackTest(_EnableNameStackTestCase):\n+class NameStackTest(jtu.JaxTestCase):\ndef test_trivial_name_stack(self):\n@@ -135,7 +126,7 @@ class NameStackTest(_EnableNameStackTestCase):\nself.assertEqual(str(jaxpr.eqns[0].params['call_jaxpr'].eqns[0].source_info.name_stack), 'bar')\n-class NameStackTransformationTest(_EnableNameStackTestCase):\n+class NameStackTransformationTest(jtu.JaxTestCase):\ndef test_vmap_should_transform_name_stack(self):\n@jax.vmap\n@@ -238,7 +229,7 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\nself.assertIn('transpose(jvp(foo))/jit(f)/bar/mul', hlo_text)\n-class NameStackControlFlowTest(_EnableNameStackTestCase):\n+class NameStackControlFlowTest(jtu.JaxTestCase):\ndef test_while_loop_body_should_not_have_name_stack(self):\n" } ]
Python
Apache License 2.0
google/jax
Delete `jax_experimental_name_stack` flag PiperOrigin-RevId: 487601864
260,447
09.11.2022 23:01:24
28,800
311fb24ff96c6be56e3199929be7043cfeb2673d
[sparse] Add BCSR from_scipy_sparse.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcsr.py", "new_path": "jax/experimental/sparse/bcsr.py", "diff": "@@ -348,6 +348,20 @@ class BCSR(JAXSparse):\n\"\"\"Create a dense version of the array.\"\"\"\nreturn bcsr_todense(self)\n+ @classmethod\n+ def from_scipy_sparse(cls, mat, *, index_dtype=None, n_dense=0, n_batch=0):\n+ \"\"\"Create a BCSR array from a :mod:`scipy.sparse` array.\"\"\"\n+ if n_dense != 0 or n_batch != 0:\n+ raise NotImplementedError(\"BCSR from_scipy_sparse with nonzero n_dense/n_batch.\")\n+\n+ if mat.ndim != 2:\n+ raise ValueError(f\"BCSR from_scipy_sparse requires 2D array; {mat.ndim}D is given.\")\n+\n+ mat = mat.tocsr()\n+ data = jnp.asarray(mat.data)\n+ indices = jnp.asarray(mat.indices).astype(index_dtype or jnp.int32)\n+ indptr = jnp.asarray(mat.indptr).astype(index_dtype or jnp.int32)\n+ return cls((data, indices, indptr), shape=mat.shape)\n#--------------------------------------------------------------------\n# vmappable handlers\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -2548,17 +2548,19 @@ class SparseObjectTest(jtu.JaxTestCase):\nself.assertAllClose(M @ x, Msp @ x, rtol=MATMUL_TOL)\n@jtu.sample_product(\n+ cls=[sparse.BCOO, sparse.BCSR],\ninput_type=[scipy.sparse.coo_matrix, scipy.sparse.csr_matrix,\nscipy.sparse.csc_matrix],\nshape=[(5, 8), (8, 5), (5, 5), (8, 8)],\ndtype=jtu.dtypes.floating + jtu.dtypes.complex,\n)\n- def test_bcoo_from_scipy_sparse(self, input_type, shape, dtype):\n+ def test_bcoo_bcsr_from_scipy_sparse(self, cls, input_type, shape, dtype):\n+ \"\"\"Test BCOO and BCSR from_scipy_sparse.\"\"\"\nrng = rand_sparse(self.rng())\nM = rng(shape, dtype)\n- M_sparse = input_type(M)\n- M_bcoo = sparse.BCOO.from_scipy_sparse(M_sparse)\n- self.assertArraysEqual(M, M_bcoo.todense())\n+ M_scipy = input_type(M)\n+ M_jax = cls.from_scipy_sparse(M_scipy)\n+ self.assertArraysEqual(M, M_jax.todense())\ndef test_bcoo_methods(self):\nM = jnp.arange(12).reshape(3, 4)\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Add BCSR from_scipy_sparse. Co-authored-by: Jake Vanderplas <vanderplas@google.com>
260,447
10.11.2022 13:55:35
28,800
332fced0ccc76d4a3d74abf3e6ec833e099ece51
sparse] BCSR batching rule. [Co-authored-by: Jake Vanderplas:
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcsr.py", "new_path": "jax/experimental/sparse/bcsr.py", "diff": "@@ -179,6 +179,21 @@ def _bcoo_fromdense_abstract_eval(mat, *, nse, n_batch, n_dense, index_dtype):\ncore.ShapedArray(indptr_shape, index_dtype))\n+def _bcsr_fromdense_batching_rule(batched_args, batch_dims, *, nse, n_batch,\n+ n_dense, index_dtype):\n+ M, = batched_args\n+ if batch_dims != (0,):\n+ raise NotImplementedError(f\"batch_dims={batch_dims}\")\n+ new_n_batch = n_batch + 1\n+ n_sparse = M.ndim - n_dense - new_n_batch\n+ if n_sparse != 2:\n+ raise ValueError(\"_bcsr_fromdense_batching_rule: must have 2 sparse \"\n+ f\"dimensions but {n_sparse} is given.\")\n+ return _bcsr_fromdense(M, nse=nse, n_batch=new_n_batch, n_dense=n_dense,\n+ index_dtype=index_dtype), (0, 0, 0)\n+\n+\n+batching.primitive_batchers[bcsr_fromdense_p] = _bcsr_fromdense_batching_rule\nmlir.register_lowering(bcsr_fromdense_p, mlir.lower_fun(\n_bcsr_fromdense_impl, multiple_results=True))\n@@ -229,6 +244,20 @@ def _bcsr_todense_abstract_eval(data, indices, indptr, *, shape):\nreturn core.ShapedArray(shape, data.dtype)\n+def _bcsr_todense_batching_rule(batched_args, batch_dims, *, shape):\n+ data, indices, indptr = batched_args\n+ if any(b not in [0, None] for b in batch_dims):\n+ raise NotImplementedError(f\"batch_dims={batch_dims}. \"\n+ \"Only 0 and None are supported.\")\n+ if batch_dims[0] is None:\n+ data = data[None, ...]\n+ if batch_dims[1] is None:\n+ indices = indices[None, ...]\n+ if batch_dims[2] is None:\n+ indptr = indptr[None, ...]\n+ return _bcsr_todense(data, indices, indptr, shape=shape), 0\n+\n+batching.primitive_batchers[bcsr_todense_p] = _bcsr_todense_batching_rule\nmlir.register_lowering(bcsr_todense_p, mlir.lower_fun(\n_bcsr_todense_impl, multiple_results=False))\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -2308,6 +2308,44 @@ class BCSRTest(jtu.JaxTestCase):\nargs_maker_todense = lambda: [data, indices, indptr]\nself._CompileAndCheck(todense, args_maker_todense)\n+ @jtu.sample_product(\n+ [dict(shape=shape, n_batch=n_batch)\n+ for shape in [(5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]\n+ for n_batch in range(len(shape) - 1)\n+ ],\n+ dtype=jtu.dtypes.floating + jtu.dtypes.complex,\n+ )\n+ def test_bcsr_dense_round_trip_batched(self, shape, dtype, n_batch):\n+ n_sparse = 2\n+ n_dense = len(shape) - n_sparse - n_batch\n+ rng = rand_sparse(self.rng())\n+ M = rng(shape, dtype)\n+\n+ nse = sparse.util._count_stored_elements(M, n_batch=n_batch,\n+ n_dense=n_dense)\n+\n+ fromdense = partial(sparse_bcsr._bcsr_fromdense, nse=nse, n_batch=0,\n+ n_dense=n_dense)\n+ todense = partial(sparse_bcsr._bcsr_todense, shape=shape)\n+\n+ for _ in range(n_batch):\n+ fromdense = jax.vmap(fromdense)\n+ todense = jax.vmap(todense)\n+\n+ data, indices, indptr = fromdense(M)\n+\n+ self.assertEqual(data.dtype, dtype)\n+ self.assertEqual(data.shape,\n+ shape[:n_batch] + (nse,) + shape[n_batch + n_sparse:])\n+ self.assertEqual(indices.dtype, jnp.int32)\n+ self.assertEqual(indices.shape, shape[:n_batch] + (nse,))\n+ self.assertEqual(indptr.dtype, jnp.int32)\n+ self.assertEqual(indptr.shape, shape[:n_batch] + (shape[n_batch] + 1,))\n+\n+ self.assertArraysEqual(M, todense(data, indices, indptr))\n+ args_maker_todense = lambda: [data, indices, indptr]\n+ self._CompileAndCheck(todense, args_maker_todense)\n+\n@jtu.sample_product(\n[dict(shape=shape, n_batch=n_batch)\nfor shape in [(5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]\n" } ]
Python
Apache License 2.0
google/jax
sparse] BCSR batching rule. [Co-authored-by: Jake Vanderplas: <vanderplas@google.com>
260,368
11.11.2022 07:08:27
28,800
10e6fe8cde3a26a9c37793ecb4a26f577ff0c0b5
Correct norm in ann.py doc.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/ann.py", "new_path": "jax/_src/lax/ann.py", "diff": "@@ -188,10 +188,10 @@ def approx_min_k(operand: Array,\n>>>\n>>> qy = jax.numpy.array(np.random.rand(50, 64))\n>>> db = jax.numpy.array(np.random.rand(1024, 64))\n- >>> half_db_norms = jax.numpy.linalg.norm(db, axis=1) / 2\n- >>> dists, neighbors = l2_ann(qy, db, half_db_norms, k=10)\n+ >>> half_db_norm_sq = jax.numpy.linalg.norm(db, axis=1)**2 / 2\n+ >>> dists, neighbors = l2_ann(qy, db, half_db_norm_sq, k=10)\n- In the example above, we compute ``db_norms/2 - dot(qy, db^T)`` instead of\n+ In the example above, we compute ``db^2/2 - dot(qy, db^T)`` instead of\n``qy^2 - 2 dot(qy, db^T) + db^2`` for performance reason. The former uses less\narithmetics and produces the same set of neighbors.\n\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
Correct norm in ann.py doc. PiperOrigin-RevId: 487814084
260,516
11.11.2022 08:04:38
28,800
d2afa84a6ef14dc6ffba31bba2e658b808acc6b2
PRNGKeyArray is now a virtual subclass of ndarray
[ { "change_type": "MODIFY", "old_path": "jax/_src/prng.py", "new_path": "jax/_src/prng.py", "diff": "@@ -31,6 +31,7 @@ from jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax.interpreters import pxla\nfrom jax.interpreters import xla\n+from jax._src import basearray\nfrom jax._src.sharding import (\nMeshPspecSharding, PmapSharding, OpShardingSharding)\n@@ -258,6 +259,7 @@ lax_numpy._set_device_array_base_attributes(PRNGKeyArray, include=[\n'__getitem__', 'ravel', 'squeeze', 'swapaxes', 'take', 'reshape',\n'transpose', 'flatten', 'T'])\nlax_numpy._register_stackable(PRNGKeyArray)\n+basearray.Array.register(PRNGKeyArray)\n# TODO(frostig): remove, rerouting callers directly to random_seed\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -476,6 +476,12 @@ class PrngTest(jtu.JaxTestCase):\nself.assertRaisesRegex(IndexError, 'Too many indices.*',\nlambda: keys[0, 1, None, 2])\n+ def test_isinstance(self):\n+ if not config.jax_enable_custom_prng:\n+ self.skipTest(\"test requires config.jax_enable_custom_prng\")\n+ key = random.PRNGKey(0)\n+ self.assertIsInstance(key, jnp.ndarray)\n+\nclass LaxRandomTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
PRNGKeyArray is now a virtual subclass of ndarray
260,510
11.11.2022 14:00:33
28,800
4bdfdd736343f17a774188ec390a3675e6a66cd0
Update changelog w/ info about deleting `jax_experimental_name_stack`
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -15,6 +15,8 @@ Remember to align the itemized text with the first line of an item within a list\n{func}`jax.lax.linalg.tridiagonal`, and\n{func}`jax.lax.linalg.householder_product` were added. Householder and\ntridiagonal reductions are supported on CPU only.\n+* Breaking Changes\n+ * Deleted the `jax_experimental_name_stack` config option.\n## jaxlib 0.3.25\n* Changes\n" } ]
Python
Apache License 2.0
google/jax
Update changelog w/ info about deleting `jax_experimental_name_stack`
260,278
10.11.2022 19:03:04
0
09f62dec3cacf8cb21fb87196a8c62a71486fcbe
Moved abs to inputs of lcm and added specific test
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -4367,11 +4367,12 @@ def gcd(x1: ArrayLike, x2: ArrayLike) -> Array:\ndef lcm(x1: ArrayLike, x2: ArrayLike) -> Array:\n_check_arraylike(\"lcm\", x1, x2)\nx1, x2 = _promote_dtypes(x1, x2)\n+ x1, x2 = abs(x1), abs(x2)\nif not issubdtype(_dtype(x1), integer):\nraise ValueError(\"Arguments to jax.numpy.lcm must be integers.\")\nd = gcd(x1, x2)\nreturn where(d == 0, _lax_const(d, 0),\n- abs(multiply(x1, floor_divide(x2, d))))\n+ multiply(x1, floor_divide(x2, d)))\n@_wraps(np.extract)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_operators_test.py", "new_path": "tests/lax_numpy_operators_test.py", "diff": "@@ -282,6 +282,7 @@ JAX_COMPOUND_OP_RECORDS = [\nall_shapes, jtu.rand_small_positive, []),\nop_record(\"gcd\", 2, int_dtypes_no_uint64, all_shapes, jtu.rand_default, []),\nop_record(\"lcm\", 2, int_dtypes_no_uint64, all_shapes, jtu.rand_default, []),\n+ op_record(\"lcm\", 2, [np.int8], all_shapes, jtu.rand_not_small, [])\n]\nJAX_BITWISE_OP_RECORDS = [\n" } ]
Python
Apache License 2.0
google/jax
Moved abs to inputs of lcm and added specific test
260,294
11.11.2022 22:41:51
0
31d8f62826d019b41f182b56d6d9213da420a93f
Sytrd solver and SytrdDescriptor should NOT be CUDA only
[ { "change_type": "MODIFY", "old_path": "jaxlib/gpu/solver_kernels.h", "new_path": "jaxlib/gpu/solver_kernels.h", "diff": "@@ -160,6 +160,7 @@ struct GesvdjDescriptor {\nvoid Gesvdj(gpuStream_t stream, void** buffers, const char* opaque,\nsize_t opaque_len, XlaCustomCallStatus* status);\n+#endif // JAX_GPU_CUDA\n// sytrd/hetrd: Reduction of a symmetric (Hermitian) matrix to tridiagonal form.\nstruct SytrdDescriptor {\n@@ -171,7 +172,6 @@ struct SytrdDescriptor {\nvoid Sytrd(gpuStream_t stream, void** buffers, const char* opaque,\nsize_t opaque_len, XlaCustomCallStatus* status);\n-#endif // JAX_GPU_CUDA\n} // namespace JAX_GPU_NAMESPACE\n} // namespace jax\n" } ]
Python
Apache License 2.0
google/jax
Sytrd solver and SytrdDescriptor should NOT be CUDA only
260,510
11.11.2022 15:23:44
28,800
e15619ceabfe04a3b9e0d315011240bb3facaf55
Convert string axis name into tuple of strings in Mesh constructor
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -17,6 +17,9 @@ Remember to align the itemized text with the first line of an item within a list\ntridiagonal reductions are supported on CPU only.\n* Breaking Changes\n* Deleted the `jax_experimental_name_stack` config option.\n+ * Convert a string `axis_names` arguments to the\n+ {class}`jax.experimental.maps.Mesh` constructor into a singleton tuple\n+ instead of unpacking the string into a sequence of character axis names.\n## jaxlib 0.3.25\n* Changes\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -2312,9 +2312,11 @@ class Mesh(ContextDecorator):\naxis_names: Tuple[MeshAxisName, ...]\ndef __init__(self, devices: Union[np.ndarray, Sequence[xc.Device]],\n- axis_names: Sequence[MeshAxisName]):\n+ axis_names: Union[str, Sequence[MeshAxisName]]):\nif not isinstance(devices, np.ndarray):\ndevices = np.array(devices)\n+ if isinstance(axis_names, str):\n+ axis_names = (axis_names,)\nassert devices.ndim == len(axis_names)\n# TODO: Make sure that devices are unique? At least with the quick and\n# dirty check that the array size is not larger than the number of\n" }, { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "@@ -3219,6 +3219,10 @@ class UtilTest(jtu.JaxTestCase):\nself.assertIsInstance(mesh.devices, np.ndarray)\nself.assertEqual(mesh.size, jax.device_count())\n+ def test_mesh_with_string_axis_names(self):\n+ mesh = maps.Mesh(jax.devices(), 'dp')\n+ self.assertTupleEqual(mesh.axis_names, ('dp',))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Convert string axis name into tuple of strings in Mesh constructor PiperOrigin-RevId: 487930412
260,496
14.11.2022 14:28:08
-3,600
9fd99edca060ed0aa101e817a1f05246c473403d
[jax2tf] Update link in README.md
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -963,8 +963,8 @@ of shape polymorphism.\n### TensorFlow XLA ops\nFor most JAX primitives there is a natural TensorFlow op that fits the needed semantics.\n-There are a few (listed below) JAX primitives for which there is no\n-single TensorFlow op with matching semantics.\n+There are a few (listed in [no_xla_limitations.md](g3doc/no_xla_limitations.md)) JAX primitives\n+for which there is no single TensorFlow op with matching semantics.\nThis is not so surprising, because JAX primitives have been designed\nto be compiled to [HLO ops](https://www.tensorflow.org/xla/operation_semantics),\nwhile the corresponding TensorFlow ops are sometimes higher-level.\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Update link in README.md
260,310
14.11.2022 10:11:29
28,800
7c6a65bee2e7eb41cc078d6814a75f3e37f8e9cd
Add tf.get_current_name_scope() as prefix of name_stack during tf execution.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1039,9 +1039,14 @@ class TensorFlowTrace(core.Trace):\n# We don't use `str(name_stack)` because it uses parentheses for\n# transformations, which aren't allowed in `name_scope`.\nscope = '/'.join([s.name for s in current_name_stack.stack]) # type: ignore[union-attr]\n+\n+ if tf.get_current_name_scope():\n+ scope = f\"{tf.get_current_name_scope()}/{scope}\"\n+\n# We need to add a '/' to the name stack string to force `tf.name_scope`\n# to interpret it as an absolute scope, not a relative scope.\n- scope = scope + '/'\n+ if not scope.endswith(\"/\"):\n+ scope = scope + \"/\"\nwith tf.name_scope(_sanitize_scope_name(scope)):\nif _thread_local_state.include_xla_op_metadata:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -1369,6 +1369,33 @@ class XlaCallModuleTest(tf_test_util.JaxToTfTestCase):\nres_tf = tf.function(f_tf, jit_compile=True, autograph=False)(x, x)[0]\nself.assertAllClose(res_tf.numpy(), res_jax)\n+ def test_outer_name_scope(self):\n+ if config.jax2tf_default_experimental_native_lowering and not config.jax_dynamic_shapes:\n+ self.skipTest(\"shape polymorphism but --jax_dynamic_shapes is not set.\")\n+\n+ def assertAllOperationStartWith(g: tf.Graph, scope_name):\n+ \"\"\"Assert all operations name start with ```scope_name```.\"\"\"\n+ result = g.get_operations()\n+ if not result:\n+ self.fail(\"result is empty.\")\n+ for op in result:\n+ logging.info(\"op.name = %s\", op.name)\n+ if not op.name.startswith(scope_name):\n+ self.fail(f\"{op.name} does not start with {scope_name}.\")\n+\n+ def func_jax(x, y):\n+ return jnp.sin(x) + jnp.cos(y)\n+\n+ outer_scope = \"output_a\"\n+ g = tf.Graph()\n+ with g.as_default() as g:\n+ with tf.name_scope(outer_scope):\n+ x = tf.Variable(\n+ tf.zeros(shape=(1, 5), dtype=tf.dtypes.float32), name=\"x\")\n+ y = tf.compat.v1.placeholder(tf.dtypes.float32, (None, 5), \"y\")\n+ func_tf = jax2tf.convert(func_jax, polymorphic_shapes=\"(b,...)\")\n+ _ = func_tf(x, y)\n+ assertAllOperationStartWith(g, outer_scope)\nif __name__ == \"__main__\":\n# TODO: Remove once tensorflow is 2.10.0 everywhere.\n" } ]
Python
Apache License 2.0
google/jax
Add tf.get_current_name_scope() as prefix of name_stack during tf execution. PiperOrigin-RevId: 488399560
260,424
15.11.2022 07:35:15
28,800
3116ed52a94eb996db63a67d16109c03b5d94845
Checkify: fix nan check when primitive has multiple results.
[ { "change_type": "MODIFY", "old_path": "jax/_src/checkify.py", "new_path": "jax/_src/checkify.py", "diff": "@@ -568,10 +568,10 @@ def nan_error_check(prim, error, enabled_errors, *in_vals, **params):\ndef isnan(x):\nif isinstance(x, prng.PRNGKeyArray):\nreturn False\n- return jnp.isnan(x)\n+ return jnp.any(jnp.isnan(x))\n- any_nans = (jnp.any(isnan(x) for x in out)\n- if prim.multiple_results else jnp.any(isnan(out)))\n+ any_nans = (jnp.any(jnp.array([isnan(x) for x in out]))\n+ if prim.multiple_results else isnan(out))\nmsg = f'nan generated by primitive {prim.name} at {summary()}'\nreturn out, assert_func(error, any_nans, msg, None)\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -973,6 +973,17 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"hi!\")\n+ def test_psum_nan_check(self):\n+ @partial(jax.vmap, axis_name=\"i\")\n+ def f(x, y):\n+ return lax.psum((x, y), axis_name=\"i\")\n+\n+ cf = checkify.checkify(f, errors=checkify.nan_checks)\n+ err, _ = cf(jnp.array([-jnp.inf, 0, jnp.inf]), jnp.ones((3, 2)))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"nan generated by primitive psum\")\n+\n+\nclass LowerableChecksTest(jtu.JaxTestCase):\ndef setUp(self):\nsuper().setUp()\n" } ]
Python
Apache License 2.0
google/jax
Checkify: fix nan check when primitive has multiple results. PiperOrigin-RevId: 488653856
260,631
15.11.2022 07:36:21
28,800
20f092c916050baab72d7d1da9758aa3c9ea9628
As explained in the JAX FAQ, jax.numpy.where has suprising behavior when its gradient is taken and one of the inputs is NaN. This CL adds a short description of the behavior to the jax.numpy.where docs, which is the logical place that users would look for it.
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1059,7 +1059,16 @@ def where(condition: ArrayLike, x: Optional[ArrayLike] = None,\nof :py:func:`jax.numpy.where` because its output shape is data-dependent. The\nthree-argument form does not have a data-dependent shape and can be JIT-compiled\nsuccessfully. Alternatively, you can use the optional ``size`` keyword to\n- statically specify the expected size of the output.\"\"\"),\n+ statically specify the expected size of the output.\\n\\n\n+\n+ Special care is needed when the ``x`` or ``y`` input to\n+ :py:func:`jax.numpy.where` could have a value of NaN.\n+ Specifically, when a gradient is taken\n+ with :py:func:`jax.grad` (reverse-mode differentiation), a NaN in either\n+ ``x`` or ``y`` will propagate into the gradient, regardless of the value\n+ of ``condition``. More information on this behavior and workarounds\n+ is available in the JAX FAQ:\n+ https://jax.readthedocs.io/en/latest/faq.html#gradients-contain-nan-where-using-where\"\"\"),\nextra_params=_dedent(\"\"\"\nsize : int, optional\nOnly referenced when ``x`` and ``y`` are ``None``. If specified, the indices of the first\n" } ]
Python
Apache License 2.0
google/jax
As explained in the JAX FAQ, jax.numpy.where has suprising behavior when its gradient is taken and one of the inputs is NaN. This CL adds a short description of the behavior to the jax.numpy.where docs, which is the logical place that users would look for it. PiperOrigin-RevId: 488654036
260,287
15.11.2022 11:02:58
28,800
d742e6a41083a98d13edd3c1fa695ccc609181c9
Transpose all_gather to reduce_scatter Also, add support for AD and batching of reduce_scatter (with its transpose being all_gather again).
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -1192,16 +1192,11 @@ def _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_\nreturn x_aval.update(shape=new_shape, named_shape=new_named_shape)\ndef _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):\n- if tiled:\n- raise NotImplementedError(\"Please open a feature request!\")\n- # TODO(cjfj): Use lax.reduce_scatter here\n- concat_axis = 0\n- return (lax_numpy.sum(all_to_all(\n- cts, axis_name=axis_name, split_axis=all_gather_dimension,\n- concat_axis=concat_axis, axis_index_groups=axis_index_groups),\n- axis=concat_axis),)\n- # TODO(sharadmv,apaszke): re-enable this when we can properly detect\n- # replication.\n+ return (psum_scatter(cts, axis_name=axis_name,\n+ scatter_dimension=all_gather_dimension,\n+ axis_index_groups=axis_index_groups,\n+ tiled=tiled),)\n+ # TODO(sharadmv,apaszke): re-enable this when we can properly detect 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):\n@@ -1222,7 +1217,8 @@ def _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, ax\ndef _all_gather_batched_collective(frame_size, frame_name, _, vals_in, dims_in,\nall_gather_dimension, axis_name,\naxis_index_groups, axis_size, tiled):\n- assert axis_index_groups is None, \"axis_index_groups not supported in vmap\"\n+ if axis_index_groups is not None:\n+ raise NotImplementedError(\"axis_index_groups not supported in vmap\")\nassert axis_size == frame_size, \"axis size doesn't match\"\nif not isinstance(axis_name, tuple):\naxis_name = (axis_name,)\n@@ -1349,13 +1345,62 @@ def _reduce_scatter_abstract_eval(x, *, axis_name, scatter_dimension,\nreturn x_aval.update(shape=new_shape, named_shape=new_named_shape)\n+def _reduce_scatter_transpose_rule(cts, x, *, axis_name, scatter_dimension,\n+ axis_index_groups, axis_size, tiled):\n+ return (all_gather(cts, axis_name=axis_name,\n+ axis_index_groups=axis_index_groups,\n+ axis=scatter_dimension, tiled=tiled),)\n+\n+\n+def _reduce_scatter_batcher(vals_in, dims_in, *, scatter_dimension, axis_name,\n+ axis_index_groups, axis_size, tiled):\n+ (x,), (d,) = vals_in, dims_in\n+ if d <= scatter_dimension:\n+ scatter_dimension += 1\n+ elif not tiled: # Tiled all-scatter doesn't change the rank\n+ d += 1\n+ result = reduce_scatter_p.bind(\n+ x,\n+ scatter_dimension=scatter_dimension,\n+ axis_name=axis_name,\n+ axis_index_groups=axis_index_groups,\n+ axis_size=axis_size,\n+ tiled=tiled)\n+ return result, d\n+\n+def _reduce_scatter_collective(frame_size, frame_name, _, vals_in, dims_in,\n+ scatter_dimension, axis_name,\n+ axis_index_groups, axis_size, tiled):\n+ if axis_index_groups is not None:\n+ raise NotImplementedError(\"axis_index_groups not supported in vmap\")\n+ assert axis_size == frame_size, \"axis size doesn't match\"\n+ if not isinstance(axis_name, tuple):\n+ axis_name = (axis_name,)\n+ if len(axis_name) > 1:\n+ raise NotImplementedError(\"Please open a feature request!\")\n+ assert axis_name == (frame_name,), \"batcher called with wrong axis name\"\n+ (x,), (d,) = vals_in, dims_in\n+ if d is batching.not_mapped:\n+ y, dy = x * axis_size, scatter_dimension\n+ else:\n+ y, dy = lax.reduce(x, 0., lax.add, (d,)), scatter_dimension\n+ if tiled:\n+ y = _splitaxis(dy, axis_size, y)\n+ return y, dy\n+\n+\nreduce_scatter_p = core.AxisPrimitive(\"reduce_scatter\")\nreduce_scatter_p.def_abstract_eval(_reduce_scatter_abstract_eval)\n+ad.deflinear2(reduce_scatter_p, _reduce_scatter_transpose_rule)\n+batching.primitive_batchers[reduce_scatter_p] = _reduce_scatter_batcher\n+batching.axis_primitive_batchers[reduce_scatter_p] = _reduce_scatter_collective\nxla.register_collective_primitive(reduce_scatter_p)\nmlir.register_lowering(\nreduce_scatter_p,\npartial(_reduce_scatter_lowering, lax.add_p, psum))\npxla.multi_host_supported_collectives.add(reduce_scatter_p)\n+core.axis_substitution_rules[reduce_scatter_p] = \\\n+ partial(_subst_all_names_in_param, 'axis_name')\ndef psum_scatter(x, axis_name, *, scatter_dimension=0, axis_index_groups=None, tiled=False):\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -1257,6 +1257,11 @@ class BatchingTest(jtu.JaxTestCase):\nexpected = bulk_op(x, axis=axis)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testReduceScatterAutodiff(self):\n+ f = vmap(partial(lax.psum_scatter, axis_name='i'), axis_name='i')\n+ x = self.rng().randn(3, 3, 4)\n+ jtu.check_grads(f, (x,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, eps=1.)\n+\ndef testNonJaxTypedOutput(self):\nwith self.assertRaisesRegex(\nTypeError, \"Output from batched function.*is not a valid JAX type\"):\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -363,6 +363,18 @@ class PythonPmapTest(jtu.JaxTestCase):\nans = f(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @parameterized.named_parameters([\n+ ('Gather', lax.all_gather),\n+ ('ReduceScatter', lax.psum_scatter)\n+ ])\n+ def testVmapOf(self, prim):\n+ f = self.pmap(partial(prim, axis_name='i'), axis_name='i')\n+\n+ device_count = jax.device_count()\n+ shape = (4, device_count, device_count)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ self.assertAllClose(vmap(f)(x), jnp.stack([f(xs) for xs in x], axis=0))\n+\ndef testReduceScatter(self):\nf = self.pmap(lambda x: lax.psum_scatter(x, 'i'), axis_name='i')\n@@ -923,13 +935,30 @@ class PythonPmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @parameterized.named_parameters(it.chain.from_iterable([\n+ (name, prim, False, False),\n+ (name + 'Tiled', prim, True, False),\n+ (name + 'IndexGroups', prim, False, True),\n+ ] for name, prim in\n+ (('Gather', lax.all_gather), ('ReduceScatter', lax.psum_scatter))\n+ ))\n@ignore_slow_all_to_all_warning()\n- def testGradOfGather(self):\n+ def testGradOf(self, prim, tiled, use_axis_index_groups):\n+ axis_index_groups = None\n+ devices = jax.devices()\n+\n+ if use_axis_index_groups:\n+ if len(devices) < 2:\n+ raise SkipTest(\"Need at least two devices\")\n+ axis_index_groups = [(l.id, r.id)\n+ for l, r in np.asarray(devices).reshape(-1, 2)]\n+\n@partial(self.pmap, axis_name='i')\ndef f(x):\n- return lax.all_gather(x, axis_name='i')\n+ return prim(x, axis_name='i', tiled=tiled,\n+ axis_index_groups=axis_index_groups)\n- shape = (jax.device_count(), 4)\n+ shape = (len(devices), 2 if axis_index_groups else jax.device_count())\nx = np.arange(prod(shape), dtype=np.float32).reshape(shape)\njtu.check_grads(f, (x,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, eps=1.)\n@@ -2281,19 +2310,31 @@ class VmapPmapCollectivesTest(jtu.JaxTestCase):\nself.assertAllClose(pmap(pmap(f, axis_name='j'), axis_name='i')(x),\nvmap(vmap(f, axis_name='j'), axis_name='i')(x))\n- def testAllGatherWithVmap(self):\n+ @parameterized.named_parameters([\n+ ('AllGather', lax.all_gather),\n+ ('ReduceScatter', lax.psum_scatter),\n+ ])\n+ def testWithVmap(self, prim):\ndef f(map2):\n- @partial(jax.pmap, axis_name='i')\n- @partial(map2)\n- def f(x):\n- return jax.lax.all_gather(x, 'i')\n- return f\n+ return jax.pmap(map2(partial(prim, axis_name='i')), axis_name='i')\nif jax.device_count() < 4:\nraise SkipTest(\"test requires at least four devices\")\n- x = jnp.ones((2, 2, 64, 64))\n+ x = jnp.ones((2, 2, 2, 64))\nself.assertAllClose(f(jax.pmap)(x), f(jax.vmap)(x))\n+ @parameterized.named_parameters(it.chain.from_iterable([\n+ ('AllGather' + ('Tiled' if tiled else ''), lax.all_gather, tiled),\n+ ('ReduceScatter' + ('Tiled' if tiled else ''), lax.psum_scatter, tiled),\n+ ] for tiled in (False, True)))\n+ def testVsVmap(self, prim, tiled):\n+ if jax.device_count() < 4:\n+ raise SkipTest(\"test requires at least four devices\")\n+ shape = (4, 4, 8)\n+ x = jnp.arange(np.prod(shape)).reshape(shape)\n+ f = partial(prim, axis_name='i', tiled=tiled)\n+ self.assertAllClose(vmap(f, axis_name='i')(x), pmap(f, axis_name='i')(x))\n+\nclass PmapWithDevicesTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Transpose all_gather to reduce_scatter Also, add support for AD and batching of reduce_scatter (with its transpose being all_gather again). PiperOrigin-RevId: 488706478
260,631
15.11.2022 12:41:08
28,800
726b2bc2ee1bbc5690ad2b6ab0e2b77aa88eb868
Add JAX monitoring library that instruments code via events.
[ { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -36,6 +36,7 @@ import jax\nfrom jax import core\nfrom jax import linear_util as lu\nfrom jax.errors import UnexpectedTracerError\n+from jax.monitoring import record_event_duration_secs\nimport jax.interpreters.ad as ad\nimport jax.interpreters.batching as batching\nimport jax.interpreters.mlir as mlir\n@@ -56,6 +57,8 @@ import jax._src.util as util\nfrom jax._src.util import flatten, unflatten\nfrom jax._src import path\n+JAXPR_TRACE_EVENT = \"/jax/core/compile/jaxpr_trace_duration\"\n+BACKEND_COMPILE_EVENT = \"/jax/core/compile/backend_compile_duration\"\nFLAGS = flags.FLAGS\n@@ -370,7 +373,7 @@ def is_single_device_sharding(sharding) -> bool:\n@contextlib.contextmanager\n-def log_elapsed_time(fmt: str):\n+def log_elapsed_time(fmt: str, event: Optional[str] = None):\nif _on_exit:\nyield\nelse:\n@@ -379,6 +382,8 @@ def log_elapsed_time(fmt: str):\nyield\nelapsed_time = time.time() - start_time\nlogger.log(log_priority, fmt.format(elapsed_time=elapsed_time))\n+ if event is not None:\n+ record_event_duration_secs(event, elapsed_time)\ndef should_tuple_args(num_args: int, platform: str):\n@@ -441,7 +446,8 @@ def lower_xla_callable(\nabstract_args = tuple(aval for aval, _ in fun.in_type)\nwith log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n- \"for jit in {elapsed_time} sec\"):\n+ \"for jit in {elapsed_time} sec\",\n+ event=JAXPR_TRACE_EVENT):\njaxpr, out_type, consts = pe.trace_to_jaxpr_final2(\nfun, pe.debug_info_final(fun, \"jit\"))\nout_avals, kept_outputs = util.unzip2(out_type)\n@@ -1190,7 +1196,8 @@ class XlaCompiledComputation(stages.XlaExecutable):\ndevice_assignment=(sticky_device,) if sticky_device else None)\noptions.parameter_is_tupled_arguments = tuple_args\nwith log_elapsed_time(f\"Finished XLA compilation of {name} \"\n- \"in {elapsed_time} sec\"):\n+ \"in {elapsed_time} sec\",\n+ event=BACKEND_COMPILE_EVENT):\ncompiled = compile_or_get_cached(backend, xla_computation, options,\nhost_callbacks)\nbuffer_counts = get_buffer_counts(out_avals, ordered_effects,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -677,7 +677,8 @@ def make_xmap_callable(fun: lu.WrappedFun,\nfor aval, in_axes in zip(in_avals, in_axes)]\nwith core.extend_axis_env_nd(global_axis_sizes.items()):\nwith dispatch.log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n- \"for xmap in {elapsed_time} sec\"):\n+ \"for xmap in {elapsed_time} sec\",\n+ event=dispatch.JAXPR_TRACE_EVENT):\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": "@@ -658,7 +658,8 @@ def _pjit_jaxpr(fun, out_shardings_thunk, global_in_avals, out_tree):\ntry:\nmaps._positional_semantics.val = maps._PositionalSemantics.GLOBAL\nwith dispatch.log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n- \"for pjit in {elapsed_time} sec\"):\n+ \"for pjit in {elapsed_time} sec\",\n+ event=dispatch.JAXPR_TRACE_EVENT):\njaxpr, global_out_avals, consts = pe.trace_to_jaxpr_dynamic(fun, global_in_avals)\nfinally:\nmaps._positional_semantics.val = prev_positional_val\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1296,7 +1296,8 @@ def stage_parallel_callable(\nwith core.extend_axis_env(pci.axis_name, pci.global_axis_size, None): # type: ignore\nwith dispatch.log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n- \"for pmap in {elapsed_time} sec\"):\n+ \"for pmap in {elapsed_time} sec\",\n+ event=dispatch.JAXPR_TRACE_EVENT):\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@@ -1634,7 +1635,8 @@ class PmapExecutable(stages.XlaExecutable):\nordered_effects)\nwith dispatch.log_elapsed_time(\n- f\"Finished XLA compilation of {pci.name} in {{elapsed_time}} sec\"):\n+ f\"Finished XLA compilation of {pci.name} in {{elapsed_time}} sec\",\n+ event=dispatch.BACKEND_COMPILE_EVENT):\ncompiled = dispatch.compile_or_get_cached(\npci.backend, xla_computation, compile_options, host_callbacks)\nhandle_args = InputsHandler(\n@@ -2759,7 +2761,8 @@ def lower_sharding_computation(\nname_stack = new_name_stack(wrap_name(fun_name, api_name))\nwith dispatch.log_elapsed_time(f\"Finished tracing + transforming {name_stack} \"\n- \"in {elapsed_time} sec\"):\n+ \"in {elapsed_time} sec\",\n+ event=dispatch.JAXPR_TRACE_EVENT):\njaxpr, global_out_avals, consts = pe.trace_to_jaxpr_final(\nfun, global_in_avals, debug_info=pe.debug_info_final(fun, api_name))\nkept_outputs = [True] * len(global_out_avals)\n@@ -3015,7 +3018,8 @@ def lower_mesh_computation(\nin_jaxpr_avals = in_tiled_avals\nwith core.extend_axis_env_nd(mesh.shape.items()):\nwith dispatch.log_elapsed_time(f\"Finished tracing + transforming {name_stack} \"\n- \"in {elapsed_time} sec\"):\n+ \"in {elapsed_time} sec\",\n+ event=dispatch.JAXPR_TRACE_EVENT):\njaxpr, out_jaxpr_avals, consts = pe.trace_to_jaxpr_final(fun, in_jaxpr_avals)\nassert len(out_shardings) == len(out_jaxpr_avals)\nif spmd_lowering:\n@@ -3404,7 +3408,8 @@ class UnloadedMeshExecutable:\nkept_var_idx, backend, device_assignment, committed, pmap_nreps)\nelse:\nwith dispatch.log_elapsed_time(f\"Finished XLA compilation of {name} \"\n- \"in {elapsed_time} sec\"):\n+ \"in {elapsed_time} sec\",\n+ event=dispatch.BACKEND_COMPILE_EVENT):\nxla_executable = dispatch.compile_or_get_cached(\nbackend, computation, compile_options, host_callbacks)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/monitoring.py", "diff": "+# Copyright 2022 The JAX Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+\"\"\"Utilities for instrumenting code.\n+\n+Code points can be marked as a named event. Every time an event is reached\n+during program execution, the registered listeners will be invoked.\n+\n+A typical listener callback is to send an event to a metrics collector for\n+aggregation/exporting.\n+\"\"\"\n+from typing import Callable, List\n+\n+_event_listeners: List[Callable[[str], None]] = []\n+_event_duration_secs_listeners: List[Callable[[str, float], None]] = []\n+\n+def record_event(event: str):\n+ \"\"\"Record an event.\"\"\"\n+ for callback in _event_listeners:\n+ callback(event)\n+\n+def record_event_duration_secs(event: str, duration: float):\n+ \"\"\"Record an event duration in seconds (float).\"\"\"\n+ for callback in _event_duration_secs_listeners:\n+ callback(event, duration)\n+\n+def register_event_listener(callback: Callable[[str], None]):\n+ \"\"\"Register a callback to be invoked during record_event().\"\"\"\n+ _event_listeners.append(callback)\n+\n+def register_event_duration_secs_listener(callback : Callable[[str, float], None]):\n+ \"\"\"Register a callback to be invoked during record_event_duration_secs().\"\"\"\n+ _event_duration_secs_listeners.append(callback)\n+\n+def _clear_event_listeners():\n+ \"\"\"Clear event listeners.\"\"\"\n+ global _event_listeners, _event_duration_secs_listeners\n+ _event_listeners = []\n+ _event_duration_secs_listeners = []\n" }, { "change_type": "MODIFY", "old_path": "tests/BUILD", "new_path": "tests/BUILD", "diff": "@@ -504,6 +504,15 @@ jax_test(\n],\n)\n+py_test(\n+ name = \"monitoring_test\",\n+ srcs = [\"monitoring_test.py\"],\n+ deps = [\n+ \"//jax\",\n+ \"//jax:test_util\",\n+ ],\n+)\n+\njax_test(\nname = \"multibackend_test\",\nsrcs = [\"multibackend_test.py\"],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/monitoring_test.py", "diff": "+# Copyright 2022 The JAX Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Tests for jax.monitoring.\n+\n+Verify that callbacks are registered and invoked correctly to record events.\n+\"\"\"\n+from absl.testing import absltest\n+from jax import monitoring\n+\n+class MonitoringTest(absltest.TestCase):\n+\n+ def test_record_event(self):\n+ events = []\n+ counters = {} # Map event names to frequency.\n+ def increment_event_counter(event):\n+ if event not in counters:\n+ counters[event] = 0\n+ counters[event] += 1\n+ # Test that we can register multiple callbacks.\n+ monitoring.register_event_listener(events.append)\n+ monitoring.register_event_listener(increment_event_counter)\n+\n+ monitoring.record_event(\"test_unique_event\")\n+ monitoring.record_event(\"test_common_event\")\n+ monitoring.record_event(\"test_common_event\")\n+\n+ self.assertListEqual(events, [\"test_unique_event\",\n+ \"test_common_event\", \"test_common_event\"])\n+ self.assertDictEqual(counters, {\"test_unique_event\": 1,\n+ \"test_common_event\": 2})\n+\n+ def test_record_event_durations(self):\n+ durations = {} # Map event names to frequency.\n+ def increment_event_duration(event, duration):\n+ if event not in durations:\n+ durations[event] = 0.\n+ durations[event] += duration\n+ monitoring.register_event_duration_secs_listener(increment_event_duration)\n+\n+ monitoring.record_event_duration_secs(\"test_short_event\", 1)\n+ monitoring.record_event_duration_secs(\"test_short_event\", 2)\n+ monitoring.record_event_duration_secs(\"test_long_event\", 10)\n+\n+ self.assertDictEqual(durations, {\"test_short_event\": 3,\n+ \"test_long_event\": 10})\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main()\n" } ]
Python
Apache License 2.0
google/jax
Add JAX monitoring library that instruments code via events. PiperOrigin-RevId: 488731805
260,411
16.11.2022 11:53:43
-3,600
c7031ff369a634ccb5f73cb9cf02f394d4c290ea
[jax2tf] Disable experimental_native_lowering polymorphism tests when not jax_dynamic_shapes
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main_test.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main_test.py", "diff": "@@ -47,6 +47,10 @@ class SavedModelMainTest(tf_test_util.JaxToTfTestCase):\ndef test_train_and_save_full(self,\nmodel=\"mnist_flax\",\nserving_batch_size=-1):\n+ if (serving_batch_size == -1 and\n+ config.jax2tf_default_experimental_native_lowering and\n+ not config.jax_dynamic_shapes):\n+ self.skipTest(\"shape polymorphism but --jax_dynamic_shapes is not set.\")\nFLAGS.model = model\nFLAGS.model_classifier_layer = True\nFLAGS.serving_batch_size = serving_batch_size\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": "@@ -53,6 +53,11 @@ PS = jax2tf.PolyShape\nclass DimPolynomialTest(tf_test_util.JaxToTfTestCase):\n+ def setUp(self):\n+ super().setUp()\n+ if config.jax2tf_default_experimental_native_lowering and not config.jax_dynamic_shapes:\n+ self.skipTest(\"shape polymorphism but --jax_dynamic_shapes is not set.\")\n+\ndef test_parse_poly_spec(self):\nself.assertEqual((2, 3), shape_poly._parse_spec(None, (2, 3)))\n@@ -334,6 +339,11 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\nclass ShapePolyTest(tf_test_util.JaxToTfTestCase):\n+ def setUp(self):\n+ super().setUp()\n+ if config.jax2tf_default_experimental_native_lowering and not config.jax_dynamic_shapes:\n+ self.skipTest(\"shape polymorphism but --jax_dynamic_shapes is not set.\")\n+\ndef test_simple_unary(self):\n\"\"\"Test shape polymorphism for a simple case, unary function.\"\"\"\n@@ -1017,6 +1027,10 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nclass DimAsValueTest(tf_test_util.JaxToTfTestCase):\n\"\"\"Dimension polynomials used as values in the JAX computation.\"\"\"\n+ def setUp(self):\n+ super().setUp()\n+ if config.jax2tf_default_experimental_native_lowering and not config.jax_dynamic_shapes:\n+ self.skipTest(\"shape polymorphism but --jax_dynamic_shapes is not set.\")\ndef test_dynamic_shapes(self):\n# Test dim_as_value with dynamic shapes.\n@@ -1905,6 +1919,11 @@ def _flatten_harnesses(harnesses):\nclass ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n\"\"\"Tests for primitives that take shape values as parameters.\"\"\"\n+ def setUp(self):\n+ super().setUp()\n+ if config.jax2tf_default_experimental_native_lowering and not config.jax_dynamic_shapes:\n+ self.skipTest(\"shape polymorphism but --jax_dynamic_shapes is not set.\")\n+\n# This test runs for all _POLY_SHAPE_PRIMITIVE_HARNESSES.\n# For each primitive \"xxx\" the test will be called \"test_prim_xxx_...\".\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Disable experimental_native_lowering polymorphism tests when not jax_dynamic_shapes
260,631
16.11.2022 08:42:36
28,800
f2bd1afb7e7e9a4bbf733f63077282d926f299d9
Change repr on NamedSharding to match variable names.
[ { "change_type": "MODIFY", "old_path": "jax/_src/sharding.py", "new_path": "jax/_src/sharding.py", "diff": "@@ -265,7 +265,7 @@ class NamedSharding(XLACompatibleSharding):\n_check_mesh_resource_axis(self.mesh, self._parsed_pspec)\ndef __repr__(self):\n- return f'NamedSharding(mesh={dict(self.mesh.shape)}, partition_spec={self.spec})'\n+ return f'NamedSharding(mesh={dict(self.mesh.shape)}, spec={self.spec})'\ndef __hash__(self):\nif not hasattr(self, '_hash'):\n" }, { "change_type": "MODIFY", "old_path": "tests/array_test.py", "new_path": "tests/array_test.py", "diff": "@@ -723,7 +723,7 @@ class ShardingTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(\nValueError,\nr\"Sharding NamedSharding\\(mesh={'replica': 1, 'data': 1, 'mdl': 2}, \"\n- r\"partition_spec=PartitionSpec\\(None, \\('mdl',\\), None, None\\)\\) is only \"\n+ r\"spec=PartitionSpec\\(None, \\('mdl',\\), None, None\\)\\) is only \"\n\"valid for values of rank at least 4, but was applied to a value of rank 2\"):\nnew_mps.is_compatible_aval(shape)\n" }, { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "@@ -1088,7 +1088,7 @@ class PJitTest(jtu.BufferDonationTestCase):\nValueError,\nr\"One of with_sharding_constraint.*Sharding \"\nr\"NamedSharding\\(mesh={'replica': 1, 'data': 1, 'mdl': 2}, \"\n- r\"partition_spec=PartitionSpec\\(None, \\('mdl',\\), None, None\\)\\) is only \"\n+ r\"spec=PartitionSpec\\(None, \\('mdl',\\), None, None\\)\\) is only \"\n\"valid for values of rank at least 4, but was applied to a value of rank 1\"):\npjit_f(jnp.array([1, 2, 3]))\n" } ]
Python
Apache License 2.0
google/jax
Change repr on NamedSharding to match variable names. PiperOrigin-RevId: 488950019
260,503
16.11.2022 09:34:33
28,800
ac2af539d310cc02d4e4e266810719b4ec5cd2e9
Expand XlaExecutable.cost_analysis to call Executable.cost_analysis in case the backend does not implement the "client" attribute on xla_executable.
[ { "change_type": "MODIFY", "old_path": "jax/_src/stages.py", "new_path": "jax/_src/stages.py", "diff": "@@ -208,17 +208,30 @@ class XlaExecutable(Executable):\nxla_ext_exe = self.xla_extension_executable()\nerr_msg = (\"cost analysis unsupported on current XLA backend: \"\nf\"{type(xla_ext_exe)}\")\n- if not hasattr(xla_ext_exe, \"client\"):\n- raise NotImplementedError(err_msg)\n+ # TODO(b/259255524): Unify/merge the two cost_analysis calls below.\n+ if hasattr(xla_ext_exe, \"client\"):\n+ try:\n+ return [\n+ xla_extension.hlo_module_cost_analysis(xla_ext_exe.client, m)\n+ for m in xla_ext_exe.hlo_modules()\n+ ]\n+ except xla_extension.XlaRuntimeError as e:\n+ msg, *_ = e.args\n+ if type(msg) is str and msg.startswith(\"UNIMPLEMENTED\"):\n+ raise NotImplementedError(err_msg) from e\n+ else:\n+ raise\n+ elif hasattr(xla_ext_exe, \"cost_analysis\"):\ntry:\n- return [xla_extension.hlo_module_cost_analysis(xla_ext_exe.client, m)\n- for m in xla_ext_exe.hlo_modules()]\n+ return xla_ext_exe.cost_analysis()\nexcept xla_extension.XlaRuntimeError as e:\nmsg, *_ = e.args\nif type(msg) is str and msg.startswith(\"UNIMPLEMENTED\"):\nraise NotImplementedError(err_msg) from e\nelse:\nraise\n+ else:\n+ raise NotImplementedError(err_msg)\ndef memory_analysis(self) -> Any:\nxla_ext_exe = self.xla_extension_executable()\n" } ]
Python
Apache License 2.0
google/jax
Expand XlaExecutable.cost_analysis to call Executable.cost_analysis in case the backend does not implement the "client" attribute on xla_executable. PiperOrigin-RevId: 488962373
260,447
17.11.2022 17:52:54
28,800
bf21480534296d1fbf5d7a1a4143609d7e8a4add
[sparse] Disable gpu bcoo_matmul test when type promotion is required.
[ { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -2077,6 +2077,14 @@ class BCOOTest(sptu.SparseTestCase):\n)\n@jax.default_matmul_precision(\"float32\")\ndef test_bcoo_matmul(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype):\n+ # TODO(b/259538729): Disable gpu test when type promotion is required.\n+ # BCOO type promotion calls `convert_element_type`, which further calls\n+ # `sum_duplicates` and creates padding with out-of-bound indices.\n+ # `bcoo_dot_general` cusparse lowering is not able to handle out-of-bound\n+ # indices right now.\n+ if jtu.device_under_test() == \"gpu\" and lhs_dtype != rhs_dtype:\n+ raise self.skipTest(\"Disable gpu test when type promotion is required\")\n+\n# Note: currently, batch dimensions in matmul must correspond to batch\n# dimensions in the sparse representation.\nn_batch_lhs = max(0, len(lhs_shape) - 2)\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Disable gpu bcoo_matmul test when type promotion is required. PiperOrigin-RevId: 489351869
260,631
18.11.2022 04:18:11
28,800
7a3dbcf94e7f7f14532dc8f6779302827e92b3e1
Change params to _params to avoid clashes with downstream users.
[ { "change_type": "MODIFY", "old_path": "jax/_src/stages.py", "new_path": "jax/_src/stages.py", "diff": "@@ -458,22 +458,22 @@ class Compiled(Stage):\nreturn tree_util.tree_unflatten(self.out_tree, shardings_flat) # pytype: disable=attribute-error\n@staticmethod\n- def call(params, *args, **kwargs):\n+ def call(_params, *args, **kwargs):\nif jax.config.jax_dynamic_shapes:\nraise NotImplementedError\n- if params.no_kwargs and kwargs:\n+ if _params.no_kwargs and kwargs:\nkws = ', '.join(kwargs.keys())\nraise NotImplementedError(\n\"function was compiled by a transformation that does not support \"\nf\"keyword arguments, but called with keyword arguments: {kws}\")\nargs_flat, in_tree = tree_util.tree_flatten((args, kwargs))\n- if in_tree != params.in_tree:\n+ if in_tree != _params.in_tree:\n# TODO(frostig): provide more info about the source function\n# and transformation\nraise TypeError(\n- f\"function compiled for {params.in_tree}, called with {in_tree}\")\n+ f\"function compiled for {_params.in_tree}, called with {in_tree}\")\ntry:\n- out_flat = params.executable.call(*args_flat)\n+ out_flat = _params.executable.call(*args_flat)\nexcept TypeError as e:\n# We can't transform ahead-of-time compiled calls, since we've\n# lowered and compiled for a fixed function signature, and JAX\n@@ -491,7 +491,7 @@ class Compiled(Stage):\nf\"Tracer type {type(arg)}.\") from e\nelse:\nraise\n- outs = tree_util.tree_unflatten(params.out_tree, out_flat)\n+ outs = tree_util.tree_unflatten(_params.out_tree, out_flat)\nreturn outs, out_flat\ndef __call__(self, *args, **kwargs):\n" } ]
Python
Apache License 2.0
google/jax
Change params to _params to avoid clashes with downstream users. PiperOrigin-RevId: 489441483
260,631
21.11.2022 03:21:33
28,800
7890ec8164289df547a8ceeea4621beb139949e3
Generalize TPU mesh computations.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/mesh_utils.py", "new_path": "jax/experimental/mesh_utils.py", "diff": "@@ -186,14 +186,14 @@ def _get_physical_tpu_mesh(jax_devices: Sequence[Any]) -> np.ndarray:\ndef sort_key(device):\nx, y, z = device.coords\ncore = device.core_on_chip\n- if device_kind == _TPU_V4:\n+ if device_kind in (_TPU_V2, _TPU_V3):\n+ assert z == 0\n+ return (x, y, core)\n+ else:\nif core != 0:\nraise ValueError(\n- 'Creating meshes for TPU v4 requires one device per chip')\n+ 'Creating meshes for TPU >v3 requires one device per chip')\nreturn (x, y, z)\n- elif device_kind in (_TPU_V2, _TPU_V3):\n- assert z == 0\n- return (x, y, core)\nsorted_devices = sorted(jax_devices, key=sort_key)\nx, y, *_ = _bounds_from_last_device(sorted_devices[-1])\nreturn np.array(sorted_devices).reshape((x, y, -1))\n" } ]
Python
Apache License 2.0
google/jax
Generalize TPU mesh computations. PiperOrigin-RevId: 489936718
260,631
22.11.2022 08:30:38
28,800
518fe6656ca2aab66dcfc8cd7866c10f476a17b1
Pickling of Sharding classes: use module level functions when deserializing. This avoids having to pickle the sharding class (which references the module and the Python source file) in the serialized bytes, which happens when deserializing using `classmethod`s.
[ { "change_type": "MODIFY", "old_path": "jax/_src/sharding.py", "new_path": "jax/_src/sharding.py", "diff": "@@ -242,12 +242,8 @@ class NamedSharding(XLACompatibleSharding):\nself._parsed_pspec = _parsed_pspec\nself._preprocess()\n- @classmethod\n- def unpickle(cls, mesh, spec):\n- return cls(mesh, spec)\n-\ndef __reduce__(self):\n- return type(self).unpickle, (self.mesh, self.spec)\n+ return type(self), (self.mesh, self.spec)\ndef _preprocess(self):\n# This split exists because you can pass `_parsed_pspec` that has been\n@@ -352,12 +348,8 @@ class SingleDeviceSharding(XLACompatibleSharding):\ndef __init__(self, device: Device):\nself._device = device\n- @classmethod\n- def unpickle(cls, device: Device):\n- return cls(device)\n-\ndef __reduce__(self):\n- return type(self).unpickle, (self._device,)\n+ return type(self), (self._device,)\ndef __repr__(self):\nreturn f\"SingleDeviceSharding(device={repr(self._device)})\"\n@@ -396,12 +388,8 @@ class PmapSharding(XLACompatibleSharding):\n# The sharding spec should be pmap's sharding spec.\nself.sharding_spec = sharding_spec\n- @classmethod\n- def unpickle(cls, devices: np.ndarray, sharding_spec: pxla.ShardingSpec):\n- return cls(devices, sharding_spec)\n-\ndef __reduce__(self):\n- return type(self).unpickle, (self.devices, self.sharding_spec)\n+ return type(self), (self.devices, self.sharding_spec)\ndef __eq__(self, other):\nif not isinstance(other, PmapSharding):\n@@ -608,12 +596,8 @@ class OpShardingSharding(XLACompatibleSharding):\nself._devices = tuple(devices)\nself._op_sharding = op_sharding\n- @classmethod\n- def unpickle(cls, devices: Sequence[Device], op_sharding: xc.OpSharding):\n- return cls(devices, op_sharding)\n-\ndef __reduce__(self):\n- return type(self).unpickle, (self._devices, self._op_sharding)\n+ return type(self), (self._devices, self._op_sharding)\n@pxla.maybe_cached_property\ndef _op_sharding_hash(self):\n" }, { "change_type": "MODIFY", "old_path": "tests/BUILD", "new_path": "tests/BUILD", "diff": "@@ -548,7 +548,7 @@ jax_test(\nsrcs = [\"pickle_test.py\"],\ndeps = [\n\"//jax:experimental\",\n- ] + py_deps(\"cloudpickle\"),\n+ ] + py_deps(\"cloudpickle\") + py_deps(\"numpy\"),\n)\njax_test(\n" }, { "change_type": "MODIFY", "old_path": "tests/pickle_test.py", "new_path": "tests/pickle_test.py", "diff": "@@ -35,6 +35,8 @@ from jax._src import test_util as jtu\nfrom jax._src.lib import xla_client as xc\nfrom jax._src.lib import xla_extension_version\n+import numpy as np\n+\nconfig.parse_flags_with_absl()\n@@ -48,6 +50,15 @@ def _get_device_by_id(device_id: int) -> xc.Device:\nxc.Device.__reduce__ = lambda d: (_get_device_by_id, (d.id,))\n+if cloudpickle is not None:\n+ def _reduce_mesh(mesh):\n+ # Avoid including mesh._hash in the serialized bytes for Mesh. Without this\n+ # the Mesh would be different among the workers.\n+ return jax.pxla.Mesh, (mesh.devices, mesh.axis_names)\n+\n+ cloudpickle.CloudPickler.dispatch_table[jax.pxla.Mesh] = _reduce_mesh\n+\n+\nclass CloudpickleTest(jtu.JaxTestCase):\n@unittest.skipIf(cloudpickle is None, \"Requires cloudpickle\")\n@@ -188,5 +199,15 @@ class PickleTest(jtu.JaxTestCase):\ns = sharding.OpShardingSharding(jax.devices(), op_sharding)\nself.assertEqual(s, pickle.loads(pickle.dumps(s)))\n+ @unittest.skipIf(xla_extension_version < 104,\n+ 'NamedSharding pickling requires newer jaxlib.')\n+ @unittest.skipIf(cloudpickle is None, \"Requires cloudpickle\")\n+ def test_pickle_named_sharding(self):\n+ s = jax.sharding.NamedSharding(\n+ mesh=pxla.Mesh(np.array(jax.devices()), 'd'),\n+ spec=pxla.PartitionSpec('d'))\n+ self.assertEqual(s, pickle.loads(pickle.dumps(s)))\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Pickling of Sharding classes: use module level functions when deserializing. This avoids having to pickle the sharding class (which references the module and the Python source file) in the serialized bytes, which happens when deserializing using `classmethod`s. PiperOrigin-RevId: 490249959
260,287
23.11.2022 09:14:55
28,800
7dd958947daa1aaaf16f48e85e7d2b5ff8b64e36
Make testManyArgs actually test pmap with many args For some reason the test has always been passing a single array since it was added, which seems contradictory with its purpose.
[ { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -1690,7 +1690,7 @@ class PythonPmapTest(jtu.JaxTestCase):\nvals = list(range(500))\nndevices = jax.device_count()\n- self.assertAllClose(f(jnp.array([vals] * ndevices)),\n+ self.assertAllClose(f([np.array([i] * ndevices) for i in range(500)]),\njnp.array([sum(vals)] * ndevices))\ndef testPostProcessMap2(self):\n" } ]
Python
Apache License 2.0
google/jax
Make testManyArgs actually test pmap with many args For some reason the test has always been passing a single array since it was added, which seems contradictory with its purpose. PiperOrigin-RevId: 490519068
260,403
23.11.2022 12:02:34
28,800
074e4ec813dcaa0a49162117741dd7d3fab3c8d3
Enable faster test-runners for PR/push CI runs.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/ci-build.yaml", "new_path": ".github/workflows/ci-build.yaml", "diff": "@@ -22,7 +22,7 @@ permissions:\njobs:\nlint_and_typecheck:\n- runs-on: ubuntu-latest\n+ runs-on: ubuntu-20.04-16core\ntimeout-minutes: 5\nsteps:\n- name: Cancel previous\n@@ -46,7 +46,7 @@ jobs:\ninclude:\n- name-prefix: \"with 3.8\"\npython-version: \"3.8\"\n- os: ubuntu-latest\n+ os: ubuntu-20.04-16core\nenable-x64: 0\nprng-upgrade: 0\npackage-overrides: \"none\"\n@@ -54,7 +54,7 @@ jobs:\nuse-latest-jaxlib: false\n- name-prefix: \"with numpy-dispatch\"\npython-version: \"3.9\"\n- os: ubuntu-latest\n+ os: ubuntu-20.04-16core\nenable-x64: 1\nprng-upgrade: 1\n# Test experimental NumPy dispatch\n@@ -63,7 +63,7 @@ jobs:\nuse-latest-jaxlib: false\n- name-prefix: \"with 3.10\"\npython-version: \"3.10\"\n- os: ubuntu-latest\n+ os: ubuntu-20.04-16core\nenable-x64: 0\nprng-upgrade: 0\npackage-overrides: \"none\"\n@@ -123,7 +123,7 @@ jobs:\ndocumentation:\n- runs-on: ubuntu-latest\n+ runs-on: ubuntu-20.04-16core\ntimeout-minutes: 5\nstrategy:\nmatrix:\n@@ -159,5 +159,5 @@ jobs:\nXLA_FLAGS: \"--xla_force_host_platform_device_count=8\"\nJAX_ARRAY: 1\nrun: |\n- pytest -n 1 --tb=short docs\n- pytest -n 1 --tb=short --doctest-modules jax --ignore=jax/experimental/jax2tf --ignore=jax/_src/lib/mlir --ignore=jax/interpreters/mlir.py --ignore=jax/_src/iree.py --ignore=jax/experimental/gda_serialization --ignore=jax/collect_profile.py\n+ pytest -n auto --tb=short docs\n+ pytest -n auto --tb=short --doctest-modules jax --ignore=jax/experimental/jax2tf --ignore=jax/_src/lib/mlir --ignore=jax/interpreters/mlir.py --ignore=jax/_src/iree.py --ignore=jax/experimental/gda_serialization --ignore=jax/collect_profile.py\n" } ]
Python
Apache License 2.0
google/jax
Enable faster test-runners for PR/push CI runs.
260,287
24.11.2022 09:13:11
28,800
a71116656956827807baed602cf85c4eef98517a
Make eager pmap take advantage of pmap cache The current strategy of creating a `partial(primitive.bind, **params)` has the downside of completely confusing the pmap cache and resulting in a new compilation for every single primitive. Replacing it with a `HashableFunction` should fix it. Also, pmap_test is now 2x faster!
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -32,7 +32,7 @@ from __future__ import annotations\nimport enum\nfrom contextlib import contextmanager, ContextDecorator\n-from collections import defaultdict, OrderedDict\n+from collections import defaultdict, OrderedDict, namedtuple\nimport dataclasses\nfrom functools import partial, lru_cache\nimport itertools as it\n@@ -40,7 +40,6 @@ import logging\nimport operator as op\nimport sys\nimport threading\n-import types\nfrom typing import (Any, Callable, Dict, List, NamedTuple, Optional, FrozenSet,\nSequence, Set, Tuple, Type, Union, Iterable, Mapping, cast,\nTYPE_CHECKING)\n@@ -82,7 +81,7 @@ from jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.util import (unzip3, prod, safe_map, safe_zip, partition_list,\nnew_name_stack, wrap_name, assert_unreachable,\ntuple_insert, tuple_delete, distributed_debug_log,\n- unzip2)\n+ unzip2, HashableFunction)\nif TYPE_CHECKING:\nfrom jax._src.sharding import NamedSharding, XLACompatibleSharding\n@@ -1047,15 +1046,22 @@ def _emap_impl(fun: lu.WrappedFun, *args,\nnew_outvals.append(out)\nreturn new_outvals\n-def _map_schedule(idx: Tuple[Optional[int], ...]) -> List[Optional[int]]:\n+def _map_schedule(idx: Tuple[Optional[int], ...]) -> Tuple[Optional[int], ...]:\n# In order to do a multi-map (a simultaneous map over several axes), we will\n# nest several maps. Each time we do a map, we \"remove\" an input axis so we\n# need to update the remaining map axes. For example, if we are to map over\n# the axes 0, 3, and 4, we make three calls to pmap with in_axes as 0, 2, 2.\n- return [None if i is None else\n+ return tuple(None if i is None else\ni - sum(j is not None and j < i for j in idx[:l])\n- for l, i in enumerate(idx)]\n+ for l, i in enumerate(idx))\n+\n+# We're often creating `f`s on the fly and we try to carefully make them have\n+# the right __hash__ and __eq__. However, despite our attempts pmap's caching\n+# still ends up not working, because it has a separate cache per\n+# _function object_. Adding this annotation here lets us reuse the same pmap\n+# callable for all equivalent primitive pmaps.\n+@lru_cache()\ndef _multi_pmap(f: Callable, info: EmapInfo, names: List[core.AxisName],\nall_axes: List[Tuple[Optional[int], ...]]\n) -> Tuple[Callable, Dict[core.AxisName, int]]:\n@@ -1074,6 +1080,8 @@ def _multi_pmap(f: Callable, info: EmapInfo, names: List[core.AxisName],\nout_shard_axes = {name: i for i, name in enumerate(reversed(used_names))}\nreturn f, out_shard_axes\n+_FakePrimitive = namedtuple(\"_FakePrimitive\", [\"multiple_results\", \"bind\"])\n+\nclass MapTrace(core.Trace):\ndef __init__(self, *args, emap_info):\n@@ -1089,11 +1097,12 @@ class MapTrace(core.Trace):\ndef process_primitive(self, primitive, tracers, params):\ninfo = self.main.payload[\"emap_info\"]\nvals, shard_axes = unzip2([(t.val, t.shard_axes) for t in tracers])\n- names = [f.name for f in core.thread_local_state.trace_state.axis_env\n- if f.main_trace is self.main]\n- all_axes = [_map_schedule(map(s.get, names)) for s in shard_axes]\n- f_mapped, out_shard_axes = _multi_pmap(partial(primitive.bind, **params),\n- info, names, all_axes)\n+ names = tuple(f.name for f in core.thread_local_state.trace_state.axis_env\n+ if f.main_trace is self.main)\n+ all_axes = tuple(_map_schedule(map(s.get, names)) for s in shard_axes)\n+ f = HashableFunction(lambda *args: primitive.bind(*args, **params),\n+ (primitive, tuple(params.items())))\n+ f_mapped, out_shard_axes = _multi_pmap(f, info, names, all_axes)\nwith core.eval_context(), jax.disable_jit(False):\noutvals = f_mapped(*vals)\nif primitive.multiple_results:\n@@ -1102,16 +1111,20 @@ class MapTrace(core.Trace):\ndef process_call(self, call_primitive, fun, tracers, params):\nif call_primitive is not xla.xla_call_p: raise NotImplementedError\n- fake_primitive = types.SimpleNamespace(\n- multiple_results=True, bind=partial(call_primitive.bind, fun))\n+ bind = HashableFunction(\n+ lambda *args, **kwargs: call_primitive.bind(fun, *args, **kwargs),\n+ (call_primitive, fun))\n+ fake_primitive = _FakePrimitive(multiple_results=True, bind=bind)\nreturn self.process_primitive(fake_primitive, tracers, params)\ndef process_map(self, call_primitive, fun, tracers, params):\nif params['devices'] is not None:\nraise ValueError(\"Nested pmap with explicit devices argument.\")\nif not config.jax_disable_jit:\n- fake_primitive = types.SimpleNamespace(\n- multiple_results=True, bind=partial(call_primitive.bind, fun))\n+ bind = HashableFunction(\n+ lambda *args, **kwargs: call_primitive.bind(fun, *args, **kwargs),\n+ (call_primitive, fun))\n+ fake_primitive = _FakePrimitive(multiple_results=True, bind=bind)\nreturn self.process_primitive(fake_primitive, tracers, params)\naxis_name, in_axes, out_axes_thunk, axis_size = (params[\"axis_name\"],\nparams[\"in_axes\"], params[\"out_axes_thunk\"], params[\"axis_size\"])\n@@ -1131,20 +1144,26 @@ class MapTrace(core.Trace):\nreturn map(partial(MapTracer, self), out, outaxes)\ndef process_custom_jvp_call(self, primitive, fun, jvp, tracers):\n- fake_primitive = types.SimpleNamespace(\n- multiple_results=True, bind=partial(primitive.bind, fun, jvp))\n+ bind = HashableFunction(\n+ lambda *args, **kwargs: primitive.bind(fun, jvp, *args, **kwargs),\n+ (primitive, fun, jvp))\n+ fake_primitive = _FakePrimitive(multiple_results=True, bind=bind)\nreturn self.process_primitive(fake_primitive, tracers, {})\ndef process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers,\nout_trees):\n- fake_primitive = types.SimpleNamespace(\n- multiple_results=True, bind=partial(primitive.bind, fun, fwd, bwd,\n- out_trees=out_trees))\n+ bind = HashableFunction(\n+ lambda *args, **kwargs: primitive.bind(fun, fwd, bwd, *args,\n+ out_trees=out_trees, **kwargs),\n+ (primitive, fun, fwd, bwd))\n+ fake_primitive = _FakePrimitive(multiple_results=True, bind=bind)\nreturn self.process_primitive(fake_primitive, tracers, {})\ndef process_axis_index(self, frame):\n- fake_primitive = types.SimpleNamespace(\n- multiple_results=False, bind=lambda _: jax.lax.axis_index(frame.name))\n+ bind = HashableFunction(\n+ lambda _: jax.lax.axis_index(frame.name),\n+ (jax.lax.axis_index, frame.name))\n+ fake_primitive = _FakePrimitive(multiple_results=False, bind=bind)\nwith core.eval_context():\nrange = jax.lax.iota(np.int32, frame.size)\ndummy_tracer = MapTracer(self, range, {frame.name: 0})\n" } ]
Python
Apache License 2.0
google/jax
Make eager pmap take advantage of pmap cache The current strategy of creating a `partial(primitive.bind, **params)` has the downside of completely confusing the pmap cache and resulting in a new compilation for every single primitive. Replacing it with a `HashableFunction` should fix it. Also, pmap_test is now 2x faster! PiperOrigin-RevId: 490749153
260,589
24.11.2022 09:56:27
28,800
575c2f37837d6e10991544389522cdc1db1b1741
Skip unsupported tests on XLA:CPU MLIR.
[ { "change_type": "MODIFY", "old_path": "jax/_src/test_util.py", "new_path": "jax/_src/test_util.py", "diff": "@@ -303,6 +303,20 @@ def set_host_platform_device_count(nr_devices: int):\nxla_bridge.get_backend.cache_clear()\nreturn undo\n+\n+def skip_on_xla_cpu_mlir(test_method):\n+ \"\"\"A decorator to skip tests when MLIR lowering is enabled.\"\"\"\n+ @functools.wraps(test_method)\n+ def test_method_wrapper(self, *args, **kwargs):\n+ xla_flags = os.getenv('XLA_FLAGS') or ''\n+ if '--xla_cpu_use_xla_runtime' in xla_flags or '--xla_cpu_enable_mlir_lowering' in xla_flags:\n+ test_name = getattr(test_method, '__name__', '[unknown test]')\n+ raise unittest.SkipTest(\n+ f'{test_name} not supported on XLA:CPU MLIR')\n+ return test_method(self, *args, **kwargs)\n+ return test_method_wrapper\n+\n+\ndef skip_on_flag(flag_name, skip_value):\n\"\"\"A decorator for test methods to skip the test when flags are set.\"\"\"\ndef skip(test_method): # pylint: disable=missing-docstring\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1103,12 +1103,14 @@ class CPPJitTest(jtu.BufferDonationTestCase):\nself.assertIsInstance(f.as_text(), (str, type(None)))\nself.assertIsInstance(g.as_text(), (str, type(None)))\n+ @jtu.skip_on_xla_cpu_mlir\ndef test_jit_lower_compile_cost_analysis(self):\nf = self.jit(lambda x: x).lower(1.).compile()\ng = self.jit(lambda x: x + 4).lower(1.).compile()\nf.cost_analysis() # doesn't raise\ng.cost_analysis() # doesn't raise\n+ @jtu.skip_on_xla_cpu_mlir\ndef test_jit_lower_compile_memory_analysis(self):\nf = self.jit(lambda x: x).lower(1.).compile()\ng = self.jit(lambda x: x + 4).lower(1.).compile()\n" } ]
Python
Apache License 2.0
google/jax
Skip unsupported tests on XLA:CPU MLIR. PiperOrigin-RevId: 490754048
260,589
25.11.2022 06:25:11
28,800
cc1d2aaaeda6c0e10ffc66b9fc7f6f446e1bc6db
Disable more {cost,memory}_analysis tests when MLIR lowering is enabled.
[ { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "@@ -998,6 +998,7 @@ class PJitTest(jtu.BufferDonationTestCase):\nself.assertIsInstance(f.as_text(), (str, type(None)))\n@jtu.with_mesh([('x', 2), ('y', 2)])\n+ @jtu.skip_on_xla_cpu_mlir\ndef testLowerCompileCostAnalysis(self):\n@partial(pjit,\nin_axis_resources=P(('x', 'y'),),\n@@ -1011,6 +1012,7 @@ class PJitTest(jtu.BufferDonationTestCase):\nf.cost_analysis() # doesn't raise\n@jtu.with_mesh([('x', 2), ('y', 2)])\n+ @jtu.skip_on_xla_cpu_mlir\ndef testLowerCompileMemoryAnalysis(self):\n@partial(pjit,\nin_axis_resources=P(('x', 'y'),),\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -302,6 +302,7 @@ class PythonPmapTest(jtu.JaxTestCase):\nf = f.lower(x).compile()\nself.assertIsInstance(f.as_text(), (str, type(None)))\n+ @jtu.skip_on_xla_cpu_mlir\ndef testLowerCompileCostAnalysis(self):\nf = self.pmap(lambda x: x - lax.pmean(x, 'i'), axis_name='i')\nshape = (jax.device_count(), 4)\n@@ -309,6 +310,7 @@ class PythonPmapTest(jtu.JaxTestCase):\nf = f.lower(x).compile()\nf.cost_analysis() # doesn't raise\n+ @jtu.skip_on_xla_cpu_mlir\ndef testLowerCompileMemoryAnalysis(self):\nf = self.pmap(lambda x: x - lax.pmean(x, 'i'), axis_name='i')\nshape = (jax.device_count(), 4)\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -767,12 +767,14 @@ class XMapTest(XMapTestCase):\nf = f.lower(x).compile()\nself.assertIsInstance(f.as_text(), (str, type(None)))\n+ @jtu.skip_on_xla_cpu_mlir\ndef testLowerCompileCostAnalysis(self):\nf = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])\nx = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))\nf = f.lower(x).compile()\nf.cost_analysis() # doesn't raise\n+ @jtu.skip_on_xla_cpu_mlir\ndef testLowerCompileMemoryAnalysis(self):\nf = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])\nx = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))\n" } ]
Python
Apache License 2.0
google/jax
Disable more {cost,memory}_analysis tests when MLIR lowering is enabled. PiperOrigin-RevId: 490898616
260,383
27.11.2022 20:05:38
28,800
4011d1796582cf0fc999e72b2df9ebe036640f66
Change documentation to state the correct usage of XLA_PYTHON_CLIENT_MEM_FRACTION
[ { "change_type": "MODIFY", "old_path": "docs/gpu_memory_allocation.rst", "new_path": "docs/gpu_memory_allocation.rst", "diff": "@@ -16,7 +16,7 @@ override the default behavior:\n``XLA_PYTHON_CLIENT_MEM_FRACTION=.XX``\nIf preallocation is enabled, this makes JAX preallocate XX% of\n- currently-available GPU memory, instead of the default 90%. Lowering the\n+ the total GPU memory, instead of the default 90% of currently-available memory. Lowering the\namount preallocated can fix OOMs that occur when the JAX program starts.\n``XLA_PYTHON_CLIENT_ALLOCATOR=platform``\n" } ]
Python
Apache License 2.0
google/jax
Change documentation to state the correct usage of XLA_PYTHON_CLIENT_MEM_FRACTION
260,383
28.11.2022 09:30:25
28,800
7456b66d354160b1cdb07a0c1e7c19bb4dc78a0b
changed both "currently available" to "total" for mem allocation doc
[ { "change_type": "MODIFY", "old_path": "docs/gpu_memory_allocation.rst", "new_path": "docs/gpu_memory_allocation.rst", "diff": "GPU memory allocation\n=====================\n-**JAX will preallocate 90% of currently-available GPU memory when the first JAX\n+**JAX will preallocate 90% of the total GPU memory when the first JAX\noperation is run.** Preallocating minimizes allocation overhead and memory\nfragmentation, but can sometimes cause out-of-memory (OOM) errors. If your JAX\nprocess fails with OOM, the following environment variables can be used to\n@@ -16,7 +16,7 @@ override the default behavior:\n``XLA_PYTHON_CLIENT_MEM_FRACTION=.XX``\nIf preallocation is enabled, this makes JAX preallocate XX% of\n- the total GPU memory, instead of the default 90% of currently-available memory. Lowering the\n+ the total GPU memory, instead of the default 90%. Lowering the\namount preallocated can fix OOMs that occur when the JAX program starts.\n``XLA_PYTHON_CLIENT_ALLOCATOR=platform``\n" } ]
Python
Apache License 2.0
google/jax
changed both "currently available" to "total" for mem allocation doc
260,383
28.11.2022 10:37:42
28,800
5fb0215d4dd2a7fcf031d2f6251634ea46223292
updated jaxlib CHANGELOG
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -21,6 +21,13 @@ Remember to align the itemized text with the first line of an item within a list\n## jaxlib 0.4.0\n+* Changes\n+ * The behavior of `XLA_PYTHON_CLIENT_MEM_FRACTION=.XX` has been changed to allocate XX% of\n+ the total GPU memory instead of the previous behavior of using currently available GPU memory\n+ to calculate preallocation. Please refer to\n+ [GPU memory allocation](https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html) for\n+ more details.\n+\n## jax 0.3.25 (Nov 15, 2022)\n* Changes\n" } ]
Python
Apache License 2.0
google/jax
updated jaxlib CHANGELOG
260,545
16.11.2022 20:26:20
28,800
a35fe206a1d0fbc01eb7d0adb1be7868d371843c
Added more accurate version of the betaln function.
[ { "change_type": "MODIFY", "old_path": "docs/jax.scipy.rst", "new_path": "docs/jax.scipy.rst", "diff": "@@ -107,6 +107,7 @@ jax.scipy.special\n:toctree: _autosummary\nbetainc\n+ betaln\ndigamma\nentr\nerf\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/special.py", "new_path": "jax/_src/scipy/special.py", "diff": "@@ -29,6 +29,7 @@ from jax._src.lax.lax import _const as _lax_const\nfrom jax._src.numpy.lax_numpy import moveaxis, _promote_args_inexact, _promote_dtypes_inexact\nfrom jax._src.numpy.util import _wraps\nfrom jax._src.ops import special as ops_special\n+from jax._src.third_party.scipy.betaln import betaln as _betaln_impl\nfrom jax._src.typing import Array, ArrayLike\n@@ -38,10 +39,11 @@ def gammaln(x: ArrayLike) -> Array:\nreturn lax.lgamma(x)\n-@_wraps(osp_special.betaln, module='scipy.special')\n-def betaln(x: ArrayLike, y: ArrayLike) -> Array:\n- x, y = _promote_args_inexact(\"betaln\", x, y)\n- return lax.lgamma(x) + lax.lgamma(y) - lax.lgamma(x + y)\n+betaln = _wraps(\n+ osp_special.betaln,\n+ module='scipy.special',\n+ update_doc=False\n+)(_betaln_impl)\n@_wraps(osp_special.betainc, module='scipy.special')\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/third_party/scipy/LICENSE.txt", "new_path": "jax/_src/third_party/scipy/LICENSE.txt", "diff": "-Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers.\n+Copyright (c) 2001-2002 Enthought, Inc. 2003-2022, SciPy Developers.\nAll rights reserved.\nRedistribution and use in source and binary forms, with or without\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/third_party/scipy/betaln.py", "diff": "+from jax import lax\n+import jax.numpy as jnp\n+from jax._src.typing import Array, ArrayLike\n+from jax._src.numpy.lax_numpy import _promote_args_inexact\n+\n+def algdiv(a: ArrayLike, b: ArrayLike) -> Array:\n+ \"\"\"\n+ Compute ``log(gamma(a))/log(gamma(a + b))`` when ``b >= 8``.\n+\n+ Derived from scipy's implmentation of `algdiv`_.\n+\n+ This differs from the scipy implementation in that it assumes a <= b\n+ because recomputing ``a, b = jnp.minimum(a, b), jnp.maximum(a, b)`` might\n+ be expensive and this is only called by ``betaln``.\n+\n+ .. _algdiv:\n+ https://github.com/scipy/scipy/blob/c89dfc2b90d993f2a8174e57e0cbc8fbe6f3ee19/scipy/special/cdflib/algdiv.f\n+ \"\"\"\n+ c0 = 0.833333333333333e-01\n+ c1 = -0.277777777760991e-02\n+ c2 = 0.793650666825390e-03\n+ c3 = -0.595202931351870e-03\n+ c4 = 0.837308034031215e-03\n+ c5 = -0.165322962780713e-02\n+ h = a / b\n+ c = h / (1 + h)\n+ x = h / (1 + h)\n+ d = b + (a - 0.5)\n+ # Set sN = (1 - x**n)/(1 - x)\n+ x2 = x * x\n+ s3 = 1.0 + (x + x2)\n+ s5 = 1.0 + (x + x2 * s3)\n+ s7 = 1.0 + (x + x2 * s5)\n+ s9 = 1.0 + (x + x2 * s7)\n+ s11 = 1.0 + (x + x2 * s9)\n+ # Set w = del(b) - del(a + b)\n+ # where del(x) is defined by ln(gamma(x)) = (x - 0.5)*ln(x) - x + 0.5*ln(2*pi) + del(x)\n+ t = (1.0 / b) ** 2\n+ w = ((((c5 * s11 * t + c4 * s9) * t + c3 * s7) * t + c2 * s5) * t + c1 * s3) * t + c0\n+ w = w * (c / b)\n+ # Combine the results\n+ u = d * lax.log1p(a / b)\n+ v = a * (lax.log(b) - 1.0)\n+ return jnp.where(u <= v, (w - v) - u, (w - u) - v)\n+\n+\n+def betaln(a: ArrayLike, b: ArrayLike) -> Array:\n+ \"\"\"Compute the log of the beta function.\n+\n+ Derived from scipy's implementation of `betaln`_.\n+\n+ This implementation does not handle all branches of the scipy implementation, but is still much more accurate\n+ than just doing lgamma(a) + lgamma(b) - lgamma(a + b) when inputs are large (> 1M or so).\n+\n+ .. _betaln:\n+ https://github.com/scipy/scipy/blob/ef2dee592ba8fb900ff2308b9d1c79e4d6a0ad8b/scipy/special/cdflib/betaln.f\n+ \"\"\"\n+ a, b = _promote_args_inexact(\"betaln\", a, b)\n+ a, b = jnp.minimum(a, b), jnp.maximum(a, b)\n+ small_b = lax.lgamma(a) + (lax.lgamma(b) - lax.lgamma(a + b))\n+ large_b = lax.lgamma(a) + algdiv(a, b)\n+ return jnp.where(b < 8, small_b, large_b)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -303,6 +303,18 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nq = np.array([1., 40., 30.], dtype=np.float32)\nself.assertAllClose(np.array([1., 0., 0.], dtype=np.float32), lsp_special.zeta(x, q))\n+ def testIssue13267(self):\n+ \"\"\"Tests betaln(x, 1) across wide range of x.\"\"\"\n+ xs = jnp.geomspace(1, 1e30, 1000)\n+ primals_out, tangents_out = jax.jvp(lsp_special.betaln, primals=[xs, 1.0], tangents=[jnp.ones_like(xs), 0.0])\n+ # Check that betaln(x, 1) = -log(x).\n+ # Betaln is still not perfect for small values, hence the atol (but it's close)\n+ atol = jtu.if_device_under_test(\"tpu\", 1e-3, 1e-5)\n+ self.assertAllClose(primals_out, -jnp.log(xs), atol=atol)\n+ # Check that d/dx betaln(x, 1) = d/dx -log(x) = -1/x.\n+ self.assertAllClose(tangents_out, -1 / xs, atol=atol)\n+\n+\ndef testXlogyShouldReturnZero(self):\nself.assertAllClose(lsp_special.xlogy(0., 0.), 0., check_dtypes=False)\n" } ]
Python
Apache License 2.0
google/jax
Added more accurate version of the betaln function.
260,428
29.11.2022 15:15:40
28,800
92fd8534cda6e464478201879a0d5a5a266dd4d8
Fixes b/259636412, all-gather failing when called within xmap in pjit. Piece by piece making xmap in pjit work with all collectives so that we can use it to write 'manual kernels' safely!
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -1157,6 +1157,9 @@ def _all_gather_lowering(ctx, x, *, all_gather_dimension, axis_name,\n# TODO(jekbradbury): enable for all_gather_dimension > 0\nx_aval, = ctx.avals_in\nout_aval, = ctx.avals_out\n+ axis_context = ctx.module_context.axis_context\n+ is_spmd = isinstance(axis_context,\n+ (mlir.SPMDAxisContext, mlir.ShardingContext))\nif (ctx.module_context.platform == 'tpu' or\nctx.module_context.platform in ('cuda', 'rocm')\nand all_gather_dimension == 0):\n@@ -1169,11 +1172,22 @@ def _all_gather_lowering(ctx, x, *, all_gather_dimension, axis_name,\nmlir.dense_int_elements(broadcast_dimensions))\nreplica_groups = _replica_groups(ctx.module_context.axis_env, axis_name,\naxis_index_groups)\n+ if is_spmd:\n+ # We want to emit the all-gather with global device IDs and a unique\n+ # channel ID, as otherwise it interprets the devices as replicas instead\n+ # of partitions - and XLA is configured with only a single replica.\n+ channel = ctx.module_context.new_channel()\n+ other_args = dict(\n+ channel_handle=mhlo.ChannelHandle.get(\n+ channel, mlir.DEVICE_TO_DEVICE_TYPE),\n+ use_global_device_ids=ir.BoolAttr.get(True))\n+ else:\n+ other_args = {}\nreturn mhlo.AllGatherOp(\nmlir.aval_to_ir_type(out_aval),\nx, all_gather_dim=mlir.i64_attr(all_gather_dimension),\nreplica_groups=_replica_groups_mhlo(replica_groups),\n- channel_handle=None).results\n+ **other_args).results\nelse:\nlowering = mlir.lower_fun(_all_gather_via_psum, multiple_results=False)\nreturn lowering(\n@@ -1288,12 +1302,26 @@ def _reduce_scatter_lowering(prim, reducer, ctx, x,\naxis_index_groups)\nscatter_out_shape = list(x_aval.shape)\nscatter_out_shape[scatter_dimension] //= axis_size\n+ axis_context = ctx.module_context.axis_context\n+ is_spmd = isinstance(axis_context,\n+ (mlir.SPMDAxisContext, mlir.ShardingContext))\n+ if is_spmd:\n+ # We want to emit the all-gather with global device IDs and a unique\n+ # channel ID, as otherwise it interprets the devices as replicas instead\n+ # of partitions - and XLA is configured with only a single replica.\n+ channel = ctx.module_context.new_channel()\n+ other_args = dict(\n+ channel_handle=mhlo.ChannelHandle.get(\n+ channel, mlir.DEVICE_TO_DEVICE_TYPE),\n+ use_global_device_ids=ir.BoolAttr.get(True))\n+ else:\n+ other_args = {}\nop = mhlo.ReduceScatterOp(\nmlir.aval_to_ir_type(x_aval.update(shape=scatter_out_shape)),\nx,\nscatter_dimension=mlir.i64_attr(scatter_dimension),\nreplica_groups=_replica_groups_mhlo(replica_groups),\n- channel_handle=None)\n+ **other_args)\nscalar_type = mlir.aval_to_ir_type(scalar_aval)\nreducer_block = op.regions[0].blocks.append(scalar_type, scalar_type)\nwith ir.InsertionPoint(reducer_block):\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -907,6 +907,43 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\nx = jnp.arange(16, dtype=jnp.float32).reshape(4, 4)\nself.assertAllClose(h(x), (x * x).sum(0))\n+ @parameterized.named_parameters(\n+ {'testcase_name': name, 'mesh': mesh}\n+ for name, mesh in (\n+ ('1d', (('x', 2),)),\n+ ))\n+ @jtu.with_mesh_from_kwargs\n+ def testAllGather(self, mesh):\n+ # try hard_xmap variant, mapping across leading axes\n+ x = jnp.arange(8).reshape(2, 4)\n+ if not config.jax_array:\n+ self.skipTest('Do not test on the cpu+no array test')\n+ f = xmap(lambda x: lax.all_gather(x, 'i', axis=0, tiled=True),\n+ in_axes=['i', None], out_axes=[None],\n+ axis_resources={'i': 'x'})\n+ h = pjit(f, in_axis_resources=P('x', None),\n+ out_axis_resources=P(None))(x)\n+ assert (h.device_buffers[0] == x.reshape(8)).all()\n+\n+ @parameterized.named_parameters(\n+ {'testcase_name': name, 'mesh': mesh}\n+ for name, mesh in (\n+ ('1d', (('x', 2),)),\n+ ))\n+ @jtu.with_mesh_from_kwargs\n+ def testReduceScatter(self, mesh):\n+ # try hard_xmap variant, mapping across leading axes\n+ x = jnp.arange(8).reshape(2, 4)\n+ if not config.jax_array:\n+ self.skipTest('Do not test on the cpu+no array test')\n+ f = xmap(lambda x: lax.psum_scatter(x, 'i', scatter_dimension=0, tiled=True),\n+ in_axes=[None, None], out_axes=['i', None, None], axis_sizes={'i': 2},\n+ axis_resources={'i': 'x'})\n+ h = pjit(lambda x: f(x).reshape((2,4)), in_axis_resources=P(None, None),\n+ out_axis_resources=P('x', None))(x)\n+\n+ assert (h.device_buffers[0].reshape(4) == x[0, :]*2).all()\n+\n@jtu.with_mesh([('x', 2)])\ndef testBareXmapCollective(self):\nx = jnp.arange(20, dtype=jnp.float32).reshape(4, 5)\n" } ]
Python
Apache License 2.0
google/jax
Fixes b/259636412, all-gather failing when called within xmap in pjit. Piece by piece making xmap in pjit work with all collectives so that we can use it to write 'manual kernels' safely! PiperOrigin-RevId: 491749906
260,267
30.11.2022 16:38:27
0
b5dc0638a2b35d9e0e41b49f7c79f402e61d38fa
Fix typo in docs/multi_process.md
[ { "change_type": "MODIFY", "old_path": "docs/multi_process.md", "new_path": "docs/multi_process.md", "diff": "@@ -91,7 +91,7 @@ jax.distributed.initialize()\n```\nOn TPU at present calling {func}`jax.distributed.initialize` is optional, but\n-recommanded since it enables additional checkpointing and health checking features.\n+recommended since it enables additional checkpointing and health checking features.\n### Local vs. global devices\n" } ]
Python
Apache License 2.0
google/jax
Fix typo in docs/multi_process.md
260,455
30.11.2022 09:56:21
28,800
d5a058c7a885208bfd6f23d36e89ccd954795233
doc improvement on initilaizer
[ { "change_type": "MODIFY", "old_path": "jax/_src/nn/initializers.py", "new_path": "jax/_src/nn/initializers.py", "diff": "@@ -241,7 +241,8 @@ def variance_scaling(\n* a uniform interval, if `dtype` is real, or\n* a uniform disk, if `dtype` is complex,\n- with a mean of zero and a standard deviation of ``stddev``.\n+ with a mean of zero and a standard deviation of :math:`\\sqrt{\\frac{scale}{n}}`\n+ where `n` is defined above.\nArgs:\nscale: scaling factor (positive float).\n" } ]
Python
Apache License 2.0
google/jax
doc improvement on initilaizer PiperOrigin-RevId: 491947286
260,411
01.12.2022 11:18:47
-3,600
fcaf7f1169ca94c7dea1b24f298b0e02a98b8d2d
[jax2tf] Fix the handling of jnp.roll for polymorphic shapes
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -3507,7 +3507,7 @@ def _roll(a, shift, axis):\ni = _canonicalize_axis(i, a_ndim)\nx = remainder(x, (a_shape[i] or 1))\na = lax.concatenate((a, a), i)\n- a = lax.dynamic_slice_in_dim(a, a_shape[i] - x, a_shape[i], axis=i)\n+ a = lax.dynamic_slice_in_dim(a, array(a_shape[i]) - x, a_shape[i], axis=i)\nreturn a\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": "@@ -1716,7 +1716,14 @@ _POLY_SHAPE_TEST_HARNESSES = [\nexpect_error=(core.InconclusiveDimensionOperation,\nre.escape(\n\"Cannot divide evenly the sizes of shapes (b0, 2, 4) and (b0, -1, 3)\"))),\n-\n+ _make_harness(\"roll\", \"axis=0\",\n+ lambda x: jnp.roll(x, 2, axis=0),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"roll\", \"axis=None\",\n+ lambda x: jnp.roll(x, 2),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n_make_harness(\"scatter_add\", \"\",\npartial(lax.scatter_add, indices_are_sorted=False, unique_indices=True),\n[RandArg((7, 4), _f32),\n@@ -1932,7 +1939,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=\"repeat_repeats=poly_axis=None_scalar_poly_axes=[None, 0]\",\n+ #one_containing=\"roll_axis=None\",\n)\ndef test_prim(self, harness: Harness):\n_test_one_harness(self, harness)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix the handling of jnp.roll for polymorphic shapes
260,578
01.12.2022 14:27:45
28,800
70d50814b1598e1dbcfb69fb748ea2c2d99ad594
Add cross-linking for the migration guide and the parallelism with JAX tutorial
[ { "change_type": "MODIFY", "old_path": "docs/jax_array_migration.md", "new_path": "docs/jax_array_migration.md", "diff": "+(jax-array-migration)=\n# jax.Array migration\n**yashkatariya@**\n@@ -17,6 +18,8 @@ the unified jax.Array\nAfter the migration is complete `jax.Array` will be the only type of array in\nJAX.\n+This doc explains how to migrate existing codebases to `jax.Array`. For more information on using `jax.Array` and JAX parallelism APIs, see the [Parallelism with JAX](https://jax.readthedocs.io/en/latest/notebooks/Parallelism_with_JAX.html) tutorial.\n+\n### How to enable jax.Array?\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/Parallelism_with_JAX.ipynb", "new_path": "docs/notebooks/Parallelism_with_JAX.ipynb", "diff": "\"source\": [\n\"**This tutorial discusses parallelism via `jax.Array`, the unified array object model available in JAX v0.4.0 and newer.**\\n\",\n\"\\n\",\n+ \"See {ref}`jax-array-migration` guide for migrating existing pre-v0.4.0 codebases to `jax.Array`.\\n\",\n+ \"\\n\",\n\"**The features required by `jax.Array` are not supported by the Colab TPU runtime at this time.**\"\n]\n},\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/Parallelism_with_JAX.md", "new_path": "docs/notebooks/Parallelism_with_JAX.md", "diff": "@@ -19,6 +19,8 @@ kernelspec:\n**This tutorial discusses parallelism via `jax.Array`, the unified array object model available in JAX v0.4.0 and newer.**\n+See {ref}`jax-array-migration` guide for migrating existing pre-v0.4.0 codebases to `jax.Array`.\n+\n**The features required by `jax.Array` are not supported by the Colab TPU runtime at this time.**\n```{code-cell}\n" } ]
Python
Apache License 2.0
google/jax
Add cross-linking for the migration guide and the parallelism with JAX tutorial Co-authored-by: Skye Wanderman-Milne <skyewm@google.com>
260,578
01.12.2022 15:38:38
28,800
a2870a182e1d935442362957087d92a34fa60ae5
Add jax.Array to the index page
[ { "change_type": "MODIFY", "old_path": "docs/index.rst", "new_path": "docs/index.rst", "diff": "@@ -5,6 +5,11 @@ JAX is Autograd_ and XLA_, brought together for high-performance numerical compu\nIt provides composable transformations of Python+NumPy programs: differentiate, vectorize,\nparallelize, Just-In-Time compile to GPU/TPU, and more.\n+.. note::\n+ JAX 0.4.0 introduces new parallelism APIs, including breaking changes to :func:`jax.experimental.pjit` and a new unified ``jax.Array`` type.\n+ Please see `Parallelism with JAX <https://jax.readthedocs.io/en/latest/notebooks/Parallelism_with_JAX.html>`_ tutorial and the :ref:`jax-array-migration`\n+ guide for more information.\n+\n.. toctree::\n:maxdepth: 1\n:caption: Getting Started\n" } ]
Python
Apache License 2.0
google/jax
Add jax.Array to the index page
260,290
03.12.2022 21:22:25
0
542b38a1c232f7c28e8c25ac4d0fd8dd0598ae00
Updated jax.tree_leaves --> jax.tree_util.tree_leaves to remove deprecation notice in jax101-pytrees tutorial
[ { "change_type": "MODIFY", "old_path": "docs/jax-101/05.1-pytrees.ipynb", "new_path": "docs/jax-101/05.1-pytrees.ipynb", "diff": "\"\\n\",\n\"# Let's see how many leaves they have:\\n\",\n\"for pytree in example_trees:\\n\",\n- \" leaves = jax.tree_leaves(pytree)\\n\",\n+ \" leaves = jax.tree_util.tree_leaves(pytree)\\n\",\n\" print(f\\\"{repr(pytree):<45} has {len(leaves)} leaves: {leaves}\\\")\"\n]\n},\n}\n],\n\"source\": [\n- \"jax.tree_leaves([\\n\",\n+ \"jax.tree_util.tree_leaves([\\n\",\n\" MyContainer('Alice', 1, 2, 3),\\n\",\n\" MyContainer('Bob', 4, 5, 6)\\n\",\n\"])\"\n\"jax.tree_util.register_pytree_node(\\n\",\n\" MyContainer, flatten_MyContainer, unflatten_MyContainer)\\n\",\n\"\\n\",\n- \"jax.tree_leaves([\\n\",\n+ \"jax.tree_util.tree_leaves([\\n\",\n\" MyContainer('Alice', 1, 2, 3),\\n\",\n\" MyContainer('Bob', 4, 5, 6)\\n\",\n\"])\"\n\"\\n\",\n\"# Since `tuple` is already registered with JAX, and NamedTuple is a subclass,\\n\",\n\"# this will work out-of-the-box:\\n\",\n- \"jax.tree_leaves([\\n\",\n+ \"jax.tree_util.tree_leaves([\\n\",\n\" MyOtherContainer('Alice', 1, 2, 3),\\n\",\n\" MyOtherContainer('Bob', 4, 5, 6)\\n\",\n\"])\"\n}\n],\n\"source\": [\n- \"jax.tree_leaves([None, None, None])\"\n+ \"jax.tree_util.tree_leaves([None, None, None])\"\n]\n},\n{\n" }, { "change_type": "MODIFY", "old_path": "docs/jax-101/05.1-pytrees.md", "new_path": "docs/jax-101/05.1-pytrees.md", "diff": "@@ -50,7 +50,7 @@ example_trees = [\n# Let's see how many leaves they have:\nfor pytree in example_trees:\n- leaves = jax.tree_leaves(pytree)\n+ leaves = jax.tree_util.tree_leaves(pytree)\nprint(f\"{repr(pytree):<45} has {len(leaves)} leaves: {leaves}\")\n```\n@@ -210,7 +210,7 @@ class MyContainer:\n:id: OPGe2R7ZOXCT\n:outputId: 40db1f41-9df8-4dea-972a-6a7bc44a49c6\n-jax.tree_leaves([\n+jax.tree_util.tree_leaves([\nMyContainer('Alice', 1, 2, 3),\nMyContainer('Bob', 4, 5, 6)\n])\n@@ -258,7 +258,7 @@ def unflatten_MyContainer(\njax.tree_util.register_pytree_node(\nMyContainer, flatten_MyContainer, unflatten_MyContainer)\n-jax.tree_leaves([\n+jax.tree_util.tree_leaves([\nMyContainer('Alice', 1, 2, 3),\nMyContainer('Bob', 4, 5, 6)\n])\n@@ -282,7 +282,7 @@ class MyOtherContainer(NamedTuple):\n# Since `tuple` is already registered with JAX, and NamedTuple is a subclass,\n# this will work out-of-the-box:\n-jax.tree_leaves([\n+jax.tree_util.tree_leaves([\nMyOtherContainer('Alice', 1, 2, 3),\nMyOtherContainer('Bob', 4, 5, 6)\n])\n@@ -331,7 +331,7 @@ sequence a leaf.\n:id: gIwlwo2MJcEC\n:outputId: 1e59f323-a7b7-42be-8603-afa4693c00cc\n-jax.tree_leaves([None, None, None])\n+jax.tree_util.tree_leaves([None, None, None])\n```\n+++ {\"id\": \"pwNz-rp1JvW4\"}\n" } ]
Python
Apache License 2.0
google/jax
Updated jax.tree_leaves --> jax.tree_util.tree_leaves to remove deprecation notice in jax101-pytrees tutorial Signed-off-by: Simon Butt <simonbutt123@gmail.com>
260,310
05.12.2022 18:02:05
28,800
2fc7bbce49bbe8c77deeda24e8118e818b8fe645
Cache the exec time `tf.get_current_name_scope` into `_thread_local_state.exec_time_tf_name_scope` and add it as prefix during tracing. Also move the test cases to right code location.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -160,7 +160,6 @@ _has_registered_tf_source_path = False\nclass _ThreadLocalState(threading.local):\ndef __init__(self):\n- self.name_stack = \"\"\n# XLA is not linked in all environments; when converting a primitive, if this\n# variable is disabled, we try harder to use only standard TF ops if they are\n# applicable to the concrete use case; if the resulting conversion path ends up\n@@ -184,6 +183,12 @@ class _ThreadLocalState(threading.local):\nself.constant_cache = None # None means that we don't use a cache. We\n# may be outside a conversion scope.\n+ # A cache for the outside tf name_scope when the converted\n+ # function is running. We will add this as the prefix to the generated tf op\n+ # name. For example, the tf op name will be like\n+ # \"{tf_outer_name_scope}/JAX_NAME_STACKS\"\n+ self.tf_outer_name_scope = \"\"\n+\n_thread_local_state = _ThreadLocalState()\ndef _get_current_name_stack() -> Union[NameStack, str]:\n@@ -281,47 +286,62 @@ def convert(fun_jax: Callable,\nfun_name = getattr(fun_jax, \"__name__\", \"unknown\")\nname_stack = util.wrap_name(fun_name, \"jax2tf\")\ndef converted_fun_tf(*args_tf: TfVal, **kwargs_tf: TfVal) -> TfVal:\n+\n+ try:\n+ prev_enable_xla = _thread_local_state.enable_xla\n+ prev_include_xla_op_metadata = _thread_local_state.include_xla_op_metadata\n+ prev_tf_outer_name_scope = _thread_local_state.tf_outer_name_scope\n+\n+ _thread_local_state.tf_outer_name_scope = tf.get_current_name_scope()\n+\n# TODO: is there a better way to check if we are inside a transformation?\n- if not core.trace_state_clean() and not _thread_local_state.inside_call_tf:\n+ if not core.trace_state_clean(\n+ ) and not _thread_local_state.inside_call_tf:\n# It is Ok to nest convert when we are inside a call_tf\n- raise ValueError(\"convert must be used outside all JAX transformations.\" +\n+ raise ValueError(\n+ \"convert must be used outside all JAX transformations.\" +\nf\"Trace state: {core.thread_local_state.trace_state.trace_stack}\")\n- fun_flat_jax, args_flat_tf, in_tree, out_tree_thunk = flatten_fun_jax(fun_jax, args_tf, kwargs_tf)\n+ fun_flat_jax, args_flat_tf, in_tree, out_tree_thunk = flatten_fun_jax(\n+ fun_jax, args_tf, kwargs_tf)\n# out_tree_thunk will be ready after we call fun_flat_jax below.\n# Expand the polymorphic_shapes to match the args_flat_tf. The polymorphic_shapes\n# argument refers to positional arguments only.\n- if polymorphic_shapes is None or isinstance(polymorphic_shapes, (PolyShape, str)):\n+ if polymorphic_shapes is None or isinstance(polymorphic_shapes,\n+ (PolyShape, str)):\npolymorphic_shapes_ = (polymorphic_shapes,) * len(args_tf)\nelse:\n- if not (isinstance(polymorphic_shapes, Sequence) and len(polymorphic_shapes) == len(args_tf)):\n- msg = (\"polymorphic_shapes must be a sequence with the same length as the positional argument list \"\n- f\"({len(args_tf)}). Got polymorphic_shapes={repr(polymorphic_shapes)}.\")\n+ if not (isinstance(polymorphic_shapes, Sequence) and\n+ len(polymorphic_shapes) == len(args_tf)):\n+ msg = (\n+ \"polymorphic_shapes must be a sequence with the same length as \"\n+ \"the positional argument list \"\n+ f\"({len(args_tf)}). Got polymorphic_shapes={repr(polymorphic_shapes)}.\"\n+ )\nraise TypeError(msg)\npolymorphic_shapes_ = tuple(polymorphic_shapes)\npolymorphic_shapes_flat = tuple(\n- api_util.flatten_axes(\"jax2tf.convert polymorphic_shapes\",\n- in_tree,\n+ api_util.flatten_axes(\n+ \"jax2tf.convert polymorphic_shapes\", in_tree,\n(polymorphic_shapes_, {k: None for k in kwargs_tf.keys()})))\n- args_and_avals = tuple(map(preprocess_arg_tf,\n- range(len(args_flat_tf)), args_flat_tf, polymorphic_shapes_flat))\n+ args_and_avals = tuple(\n+ map(preprocess_arg_tf, range(len(args_flat_tf)), args_flat_tf,\n+ polymorphic_shapes_flat))\nargs_flat_tf, args_avals_flat = util.unzip2(args_and_avals)\n- dim_vars, get_dim_values_jax = shape_poly.prepare_dim_var_env(args_avals_flat)\n+ dim_vars, get_dim_values_jax = shape_poly.prepare_dim_var_env(\n+ args_avals_flat)\ndim_values, _ = _interpret_fun_jax(get_dim_values_jax, args_flat_tf,\nargs_avals_flat, name_stack)\nshape_env = zip(dim_vars, dim_values)\n- try:\nassert not _thread_local_state.shape_env, f\"Unexpected shape environment {_thread_local_state.shape_env}\"\n- prev_enable_xla = _thread_local_state.enable_xla\n_thread_local_state.enable_xla = enable_xla\n- prev_include_xla_op_metadata = _thread_local_state.include_xla_op_metadata\n# TODO(b/189306134): implement support for XLA metadata\n_thread_local_state.include_xla_op_metadata = False\n@@ -366,6 +386,7 @@ def convert(fun_jax: Callable,\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+ _thread_local_state.tf_outer_name_scope = prev_tf_outer_name_scope\nout_flat_tf = [tf.identity(x, \"jax2tf_out\") for x in out_flat_tf]\nout_tf = tree_util.tree_unflatten(out_tree_thunk(), out_flat_tf)\n@@ -1047,11 +1068,13 @@ class TensorFlowTrace(core.Trace):\n# transformations, which aren't allowed in `name_scope`.\nscope = '/'.join([s.name for s in current_name_stack.stack]) # type: ignore[union-attr]\n- if tf.get_current_name_scope():\n- scope = f\"{tf.get_current_name_scope()}/{scope}\"\n-\n+ # Here we reset the name scope to the memorized TF name scope\n+ # + JAX name stack by using absolute scope.\n# We need to add a '/' to the name stack string to force `tf.name_scope`\n# to interpret it as an absolute scope, not a relative scope.\n+ if _thread_local_state.tf_outer_name_scope:\n+ scope = f\"{_thread_local_state.tf_outer_name_scope}/{scope}\"\n+\nif not scope.endswith(\"/\"):\nscope = scope + \"/\"\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -1208,6 +1208,179 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ninclude_xla_op_metadata=False\n)\n+ # TODO(necula): figure out this failure\n+ @jtu.skip_on_flag(\"jax2tf_default_experimental_native_lowering\", True)\n+ def test_global_device_array(self):\n+\n+ def create_gda(global_shape, global_mesh, mesh_axes, global_data=None):\n+ if global_data is None:\n+ global_data = np.arange(np.prod(global_shape)).reshape(global_shape)\n+ return GlobalDeviceArray.from_callback(\n+ global_shape, global_mesh, mesh_axes,\n+ lambda idx: global_data[idx]), global_data\n+\n+ global_mesh = jtu.create_global_mesh((4, 2), (\"x\", \"y\"))\n+ mesh_axes = P((\"x\", \"y\"))\n+ params, _ = create_gda((8, 2), global_mesh, mesh_axes)\n+ input_data = np.arange(16).reshape(2, 8)\n+\n+ # Test 1: use GDA as constants\n+ def jax_func(input_data):\n+ handle = pjit(\n+ jnp.matmul,\n+ in_axis_resources=(P(\"y\", \"x\"), FROM_GDA),\n+ out_axis_resources=None)\n+ return handle(input_data, params)\n+\n+ with global_mesh:\n+ tf_func = tf.function(\n+ jax2tf.convert(jax_func, enable_xla=True),\n+ jit_compile=True,\n+ )\n+ jax_out = jax_func(input_data=input_data)\n+ tf_out = tf_func(input_data=input_data)\n+ # TODO(b/243146552) We can switch to ConvertAndCompare after this bug fix.\n+ np.array_equal(jax_out._value, np.array(tf_out))\n+\n+ @jtu.with_mesh([(\"x\", 2)])\n+ def test_pjit_basic1D(self):\n+\n+ def func_jax(x, y):\n+ return x + y\n+\n+ shape = (8, 10)\n+ x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n+ in_axis_resources = (P(\"x\"), P(\"x\"))\n+ out_axis_resources = None\n+ res_jax = pjit(\n+ func_jax,\n+ in_axis_resources=in_axis_resources,\n+ out_axis_resources=out_axis_resources)(x, x)\n+ module = get_serialized_computation(\n+ func_jax,\n+ x,\n+ x,\n+ use_pjit=True,\n+ in_axis_resources=in_axis_resources,\n+ out_axis_resources=out_axis_resources)\n+\n+ def f_tf(x_tf, y_tf):\n+ return tfxla.call_module([x_tf, y_tf],\n+ version=2,\n+ module=module,\n+ Tout=[x.dtype],\n+ Sout=[x.shape])\n+\n+ res_tf = tf.function(f_tf, jit_compile=True, autograph=False)(x, x)[0]\n+ self.assertAllClose(res_tf.numpy(), res_jax)\n+\n+ def assertAllOperationStartWith(self, g: tf.Graph, scope_name: str):\n+ \"\"\"Assert all operations name start with ```scope_name```.\n+\n+ Also the scope_name only occur one time.\n+ \"\"\"\n+ result = g.get_operations()\n+ if not result:\n+ self.fail(\"result is empty.\")\n+ for op in result:\n+ logging.info(\"tf op.name = %s\", op.name)\n+ if not op.name.startswith(scope_name):\n+ self.fail(f\"{op.name} does not start with {scope_name}.\")\n+\n+ def test_name_scope_polymorphic(self):\n+ if config.jax2tf_default_experimental_native_lowering and not config.jax_dynamic_shapes:\n+ self.skipTest(\"shape polymorphism but --jax_dynamic_shapes is not set.\")\n+\n+ def func_jax(x, y):\n+ return jnp.sin(x) + jnp.cos(y)\n+\n+ func_tf = jax2tf.convert(\n+ func_jax, polymorphic_shapes=\"(b,...)\", with_gradient=True)\n+\n+ outer_scope = \"output_a\"\n+\n+ g = tf.Graph()\n+ with g.as_default() as g:\n+ with tf.name_scope(outer_scope):\n+ x = tf.Variable(\n+ tf.zeros(shape=(1, 5), dtype=tf.dtypes.float32), name=\"x\")\n+ y = tf.compat.v1.placeholder(tf.dtypes.float32, (None, 5), \"y\")\n+ _ = func_tf(x, y)\n+ self.assertAllOperationStartWith(g, outer_scope)\n+\n+ # wrap tf.function\n+ g2 = tf.Graph()\n+ with g2.as_default() as g:\n+ with tf.name_scope(outer_scope):\n+ x = tf.Variable(\n+ tf.zeros(shape=(1, 5), dtype=tf.dtypes.float32), name=\"x\")\n+ y = tf.compat.v1.placeholder(tf.dtypes.float32, (None, 5), \"y\")\n+ _ = tf.function(func_tf, jit_compile=True, autograph=False)(x, y)\n+ self.assertAllOperationStartWith(g2, outer_scope)\n+\n+ def test_name_scope_cond(self):\n+\n+ def f(x):\n+\n+ def f_pos(x):\n+ with jax.named_scope(\"jax_f_pos\"):\n+ return lax.cond(x < 1., jnp.cos, jnp.sin, x)\n+\n+ with jax.named_scope(\"jax_f_outer\"):\n+ return lax.cond(x > 0., f_pos, lambda x: x, x)\n+\n+ @tf.function(jit_compile=True, autograph=False)\n+ def outer_forward():\n+ with tf.name_scope(\"tf_outer_forward\"):\n+ x = 0.5\n+ f_tf = jax2tf.convert(f)\n+ _ = f_tf(x)\n+\n+ g = outer_forward.get_concrete_function().graph\n+ self.assertAllOperationStartWith(g, \"tf_outer_forward\")\n+ for func in g._functions.values():\n+ self.assertAllOperationStartWith(\n+ func.graph, \"tf_outer_forward/jax2tf_f_/jax_f_outer\")\n+\n+ x = tf.Variable(0.5, name=\"tf_outer_back/x\")\n+\n+ @tf.function(jit_compile=True, autograph=False)\n+ def outer_back():\n+ with tf.name_scope(\"tf_outer_back\"):\n+ f_tf = jax2tf.convert(f)\n+ with tf.GradientTape() as tape:\n+ res_tf = f_tf(x)\n+ _ = tape.gradient(res_tf, x)\n+\n+ g = outer_back.get_concrete_function().graph\n+ self.assertAllOperationStartWith(g, \"tf_outer_back\")\n+ for func in g._functions.values():\n+ self.assertAllOperationStartWith(func.graph, \"tf_outer_back\")\n+\n+ def test_name_scope_while_loop(self):\n+\n+ def f(x):\n+ with tf.name_scope(\"outer_scope\"):\n+\n+ def condition(x):\n+ return jnp.sum(x, keepdims=False) < 100\n+\n+ def body(x):\n+ return jnp.add(x, 2.0)\n+\n+ result = jax.lax.while_loop(condition, body, x)\n+ return result\n+\n+ tf_f = tf.function(jax2tf.convert(f), jit_compile=True, autograph=False)\n+ g = tf_f.get_concrete_function(tf.zeros((1, 3))).graph\n+\n+ for func in g._functions.values():\n+ for op in func.graph.get_operations():\n+ if op.name.count(f\"outer_scope/jax2tf_{f.__name__}_/while\") > 1:\n+ self.fail(\n+ \"tf graph has repeated name issue on when converting lax.while to tf.while.\"\n+ f\"See op.name = : {op.name}\")\n+\ndef get_serialized_computation(\nf_jax: Callable,\n*args,\n@@ -1310,92 +1483,6 @@ class XlaCallModuleTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(\ntf.nest.map_structure(lambda t: t.numpy(), res), jax_res)\n- # TODO(necula): figure out this failure\n- @jtu.skip_on_flag(\"jax2tf_default_experimental_native_lowering\", True)\n- def test_global_device_array(self):\n-\n- def create_gda(global_shape, global_mesh, mesh_axes, global_data=None):\n- if global_data is None:\n- global_data = np.arange(np.prod(global_shape)).reshape(global_shape)\n- return GlobalDeviceArray.from_callback(\n- global_shape, global_mesh, mesh_axes,\n- lambda idx: global_data[idx]), global_data\n-\n- global_mesh = jtu.create_global_mesh((4, 2), (\"x\", \"y\"))\n- mesh_axes = P((\"x\", \"y\"))\n- params, _ = create_gda((8, 2), global_mesh, mesh_axes)\n- input_data = np.arange(16).reshape(2, 8)\n-\n- # Test 1: use GDA as constants\n- def jax_func(input_data):\n- handle = pjit(\n- jnp.matmul,\n- in_axis_resources=(P(\"y\", \"x\"), FROM_GDA),\n- out_axis_resources=None)\n- return handle(input_data, params)\n-\n- with global_mesh:\n- tf_func = tf.function(\n- jax2tf.convert(jax_func, enable_xla=True),\n- jit_compile=True,\n- )\n- jax_out = jax_func(input_data=input_data)\n- tf_out = tf_func(input_data=input_data)\n- # TODO(b/243146552) We can switch to ConvertAndCompare after this bug fix.\n- np.array_equal(jax_out._value, np.array(tf_out))\n-\n- @jtu.with_mesh([(\"x\", 2)])\n- def test_pjit_basic1D(self):\n- def func_jax(x, y):\n- return x + y\n-\n- shape = (8, 10)\n- x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n- in_axis_resources = (P(\"x\"), P(\"x\"))\n- out_axis_resources = None\n- res_jax = pjit(func_jax,\n- in_axis_resources=in_axis_resources,\n- out_axis_resources=out_axis_resources)(x, x)\n- module = get_serialized_computation(func_jax, x, x,\n- use_pjit=True,\n- in_axis_resources=in_axis_resources,\n- out_axis_resources=out_axis_resources)\n- def f_tf(x_tf, y_tf):\n- return tfxla.call_module([x_tf, y_tf],\n- version=2,\n- module=module,\n- Tout=[x.dtype],\n- Sout=[x.shape])\n- res_tf = tf.function(f_tf, jit_compile=True, autograph=False)(x, x)[0]\n- self.assertAllClose(res_tf.numpy(), res_jax)\n-\n- def test_outer_name_scope(self):\n- if config.jax2tf_default_experimental_native_lowering and not config.jax_dynamic_shapes:\n- self.skipTest(\"shape polymorphism but --jax_dynamic_shapes is not set.\")\n-\n- def assertAllOperationStartWith(g: tf.Graph, scope_name):\n- \"\"\"Assert all operations name start with ```scope_name```.\"\"\"\n- result = g.get_operations()\n- if not result:\n- self.fail(\"result is empty.\")\n- for op in result:\n- logging.info(\"op.name = %s\", op.name)\n- if not op.name.startswith(scope_name):\n- self.fail(f\"{op.name} does not start with {scope_name}.\")\n-\n- def func_jax(x, y):\n- return jnp.sin(x) + jnp.cos(y)\n-\n- outer_scope = \"output_a\"\n- g = tf.Graph()\n- with g.as_default() as g:\n- with tf.name_scope(outer_scope):\n- x = tf.Variable(\n- tf.zeros(shape=(1, 5), dtype=tf.dtypes.float32), name=\"x\")\n- y = tf.compat.v1.placeholder(tf.dtypes.float32, (None, 5), \"y\")\n- func_tf = jax2tf.convert(func_jax, polymorphic_shapes=\"(b,...)\")\n- _ = func_tf(x, y)\n- assertAllOperationStartWith(g, outer_scope)\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Cache the exec time `tf.get_current_name_scope` into `_thread_local_state.exec_time_tf_name_scope` and add it as prefix during tracing. Also move the test cases to right code location. PiperOrigin-RevId: 493163018
260,667
07.12.2022 04:24:29
28,800
6e0c8029cc2c108c7fb14d555575403a1556ea46
Fix type annotation for bcoo_update_layout.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcoo.py", "new_path": "jax/experimental/sparse/bcoo.py", "diff": "@@ -1565,7 +1565,7 @@ mlir.register_lowering(bcoo_sum_duplicates_p, _bcoo_sum_duplicates_mhlo)\n# BCOO functions that maybe should be primitives?\ndef bcoo_update_layout(mat: BCOO, *, n_batch: Optional[int] = None, n_dense: Optional[int] = None,\n- on_inefficient: str = 'error') -> BCOO:\n+ on_inefficient: Optional[str] = 'error') -> BCOO:\n\"\"\"Update the storage layout (i.e. n_batch & n_dense) of a BCOO matrix.\nIn many cases this can be done without introducing undue storage overhead. However,\n" } ]
Python
Apache License 2.0
google/jax
Fix type annotation for bcoo_update_layout. PiperOrigin-RevId: 493567424
260,710
15.11.2022 18:40:52
-32,400
1ade5f859210ff5e70f671ed6f468dda9b8cf2ef
Add `jax.scipy.linalg.toeplitz`.
[ { "change_type": "MODIFY", "old_path": "docs/jax.scipy.rst", "new_path": "docs/jax.scipy.rst", "diff": "@@ -45,6 +45,7 @@ jax.scipy.linalg\nsolve_triangular\nsqrtm\nsvd\n+ toeplitz\ntril\ntriu\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/linalg.py", "new_path": "jax/_src/scipy/linalg.py", "diff": "@@ -27,6 +27,7 @@ from jax import lax\nfrom jax._src import dtypes\nfrom jax._src.lax import linalg as lax_linalg\nfrom jax._src.lax import qdwh\n+from jax._src.numpy.lax_numpy import _check_arraylike\nfrom jax._src.numpy.util import _wraps, _promote_dtypes_inexact, _promote_dtypes_complex\nfrom jax._src.numpy import lax_numpy as jnp\nfrom jax._src.numpy import linalg as np_linalg\n@@ -1031,3 +1032,28 @@ def hessenberg(a: ArrayLike, *, calc_q: bool = False, overwrite_a: bool = False,\nreturn h, q\nelse:\nreturn h\n+\n+@_wraps(scipy.linalg.toeplitz)\n+def toeplitz(c: ArrayLike, r: Optional[ArrayLike] = None) -> Array:\n+ if r is None:\n+ _check_arraylike(\"toeplitz\", c)\n+ r = jnp.conjugate(jnp.asarray(c))\n+ else:\n+ _check_arraylike(\"toeplitz\", c, r)\n+\n+ c = jnp.asarray(c).flatten()\n+ r = jnp.asarray(r).flatten()\n+\n+ ncols, = c.shape\n+ nrows, = r.shape\n+\n+ if ncols == 0 or nrows == 0:\n+ return jnp.empty((ncols, nrows), dtype=jnp.promote_types(c.dtype, r.dtype))\n+\n+ nelems = ncols + nrows - 1\n+ elems = jnp.concatenate((c[::-1], r[1:]))\n+ patches = lax.conv_general_dilated_patches(\n+ elems.reshape((1, nelems, 1)),\n+ (nrows,), (1,), 'VALID', dimension_numbers=('NTC', 'IOT', 'NTC'),\n+ precision=lax.Precision.HIGHEST)[0]\n+ return jnp.flip(patches, axis=0)\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/linalg.py", "new_path": "jax/scipy/linalg.py", "diff": "@@ -36,6 +36,7 @@ from jax._src.scipy.linalg import (\nsolve as solve,\nsolve_triangular as solve_triangular,\nsvd as svd,\n+ toeplitz as toeplitz,\ntril as tril,\ntriu as triu,\n)\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -42,6 +42,7 @@ T = lambda x: np.swapaxes(x, -1, -2)\nfloat_types = jtu.dtypes.floating\ncomplex_types = jtu.dtypes.complex\n+int_types = jtu.dtypes.all_integer\nclass NumpyLinalgTest(jtu.JaxTestCase):\n@@ -1571,6 +1572,63 @@ class ScipyLinalgTest(jtu.JaxTestCase):\nself.assertAllClose(root, expected, check_dtypes=False)\n+ @jtu.sample_product(\n+ cshape=[(), (4,), (8,), (3, 7), (0, 5, 1)],\n+ cdtype=float_types + complex_types,\n+ rshape=[(), (3,), (7,), (2, 1, 4), (19, 0)],\n+ rdtype=float_types + complex_types + int_types)\n+ def testToeplitzConstrcution(self, rshape, rdtype, cshape, cdtype):\n+ if ((rdtype in [np.float64, np.complex128]\n+ or cdtype in [np.float64, np.complex128])\n+ and not config.x64_enabled):\n+ self.skipTest(\"Only run float64 testcase when float64 is enabled.\")\n+\n+ int_types_excl_i8 = set(int_types) - {np.int8}\n+ if ((rdtype in int_types_excl_i8 or cdtype in int_types_excl_i8)\n+ and jtu.device_under_test() == \"gpu\"):\n+ self.skipTest(\"Integer (except int8) toeplitz is not supported on GPU yet.\")\n+\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(cshape, cdtype), rng(rshape, rdtype)]\n+ with jtu.strict_promotion_if_dtypes_match([rdtype, cdtype]):\n+ self._CheckAgainstNumpy(jtu.promote_like_jnp(osp.linalg.toeplitz),\n+ jsp.linalg.toeplitz, args_maker)\n+ self._CompileAndCheck(jsp.linalg.toeplitz, args_maker)\n+\n+ @jtu.sample_product(\n+ shape=[(), (3,), (1, 4), (1, 5, 9), (11, 0, 13)],\n+ dtype=float_types + complex_types + int_types)\n+ def testToeplitzSymmetricConstruction(self, shape, dtype):\n+ if (dtype in [np.float64, np.complex128]\n+ and not config.x64_enabled):\n+ self.skipTest(\"Only run float64 testcase when float64 is enabled.\")\n+\n+ int_types_excl_i8 = set(int_types) - {np.int8}\n+ if (dtype in int_types_excl_i8\n+ and jtu.device_under_test() == \"gpu\"):\n+ self.skipTest(\"Integer (except int8) toeplitz is not supported on GPU yet.\")\n+\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+ self._CheckAgainstNumpy(jtu.promote_like_jnp(osp.linalg.toeplitz),\n+ jsp.linalg.toeplitz, args_maker)\n+ self._CompileAndCheck(jsp.linalg.toeplitz, args_maker)\n+\n+ def testToeplitzConstructionWithKnownCases(self):\n+ # Test with examples taken from SciPy doc for the corresponding function.\n+ # https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.toeplitz.html\n+ ret = jsp.linalg.toeplitz(np.array([1.0, 2+3j, 4-1j]))\n+ self.assertAllClose(ret, np.array([\n+ [ 1.+0.j, 2.-3.j, 4.+1.j],\n+ [ 2.+3.j, 1.+0.j, 2.-3.j],\n+ [ 4.-1.j, 2.+3.j, 1.+0.j]]))\n+ ret = jsp.linalg.toeplitz(np.array([1, 2, 3], dtype=np.float32),\n+ np.array([1, 4, 5, 6], dtype=np.float32))\n+ self.assertAllClose(ret, np.array([\n+ [1, 4, 5, 6],\n+ [2, 1, 4, 5],\n+ [3, 2, 1, 4]], dtype=np.float32))\n+\nclass LaxLinalgTest(jtu.JaxTestCase):\n\"\"\"Tests for lax.linalg primitives.\"\"\"\n@@ -1698,5 +1756,6 @@ class LaxLinalgTest(jtu.JaxTestCase):\nTs, Ss = vmap(lax.linalg.schur)(args)\nself.assertAllClose(reconstruct(Ss, Ts), args, atol=1e-4)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add `jax.scipy.linalg.toeplitz`.
260,447
08.12.2022 16:54:15
28,800
942aa7a9070122e63953a1cd7a8f34c3baf6ca97
[sparse] Move _dot_general_validated_shape to sparse util.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcoo.py", "new_path": "jax/experimental/sparse/bcoo.py", "diff": "@@ -31,7 +31,8 @@ from jax import vmap\nfrom jax.config import config\nfrom jax.experimental.sparse._base import JAXSparse\nfrom jax.experimental.sparse.util import (\n- _broadcasting_vmap, _count_stored_elements, _safe_asarray, CuSparseEfficiencyWarning,\n+ _broadcasting_vmap, _count_stored_elements, _safe_asarray,\n+ _dot_general_validated_shape, CuSparseEfficiencyWarning,\nSparseEfficiencyError, SparseEfficiencyWarning)\nfrom jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\n@@ -582,14 +583,6 @@ mlir.register_lowering(bcoo_transpose_p, mlir.lower_fun(\nbcoo_dot_general_p = core.Primitive('bcoo_dot_general')\n-def _dot_general_validated_shape(lhs_shape: Shape, rhs_shape: Shape, dimension_numbers: DotDimensionNumbers) -> Shape:\n- \"\"\"Validate the inputs and return the output shape.\"\"\"\n- lhs = core.ShapedArray(lhs_shape, np.float32)\n- rhs = core.ShapedArray(rhs_shape, np.float32)\n- return _dot_general_shape_rule(\n- lhs, rhs, dimension_numbers=dimension_numbers,\n- precision=None, preferred_element_type=None)\n-\ndef bcoo_dot_general(lhs: Union[BCOO, Array], rhs: Union[BCOO, Array], *, dimension_numbers: DotDimensionNumbers,\nprecision: None = None, preferred_element_type: None = None) -> Union[BCOO, Array]:\n\"\"\"A general contraction operation.\n@@ -611,7 +604,8 @@ def bcoo_dot_general(lhs: Union[BCOO, Array], rhs: Union[BCOO, Array], *, dimens\n# TODO(jakevdp) make use of these?\ndel precision, preferred_element_type # unused\nif isinstance(lhs, BCOO) and isinstance(rhs, BCOO):\n- shape = _dot_general_validated_shape(lhs.shape, rhs.shape, dimension_numbers)\n+ shape = _dot_general_validated_shape(lhs.shape, rhs.shape,\n+ dimension_numbers)\nbufs = _bcoo_spdot_general(lhs.data, lhs.indices, rhs.data, rhs.indices,\nlhs_spinfo=lhs._info, rhs_spinfo=rhs._info,\ndimension_numbers=dimension_numbers)\n@@ -712,7 +706,8 @@ def _bcoo_dot_general_abstract_eval(lhs_data, lhs_indices, rhs, *, dimension_num\n(lhs_contracting, _), (lhs_batch, _) = dimension_numbers\nn_batch, n_sparse, _, _ = _validate_bcoo(lhs_data, lhs_indices, lhs_spinfo.shape)\n- out_shape = _dot_general_validated_shape(lhs_spinfo.shape, rhs.shape, dimension_numbers)\n+ out_shape = _dot_general_validated_shape(lhs_spinfo.shape, rhs.shape,\n+ dimension_numbers)\nif lhs_batch and max(lhs_batch) >= n_batch:\nraise NotImplementedError(\n@@ -1183,7 +1178,8 @@ def _bcoo_spdot_general_impl(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lh\ndata_aval, indices_aval = _bcoo_spdot_general_abstract_eval(\nlhs_data.aval, lhs_indices.aval, rhs_data.aval, rhs_indices.aval,\nlhs_spinfo=lhs_spinfo, rhs_spinfo=rhs_spinfo, dimension_numbers=dimension_numbers)\n- out_shape = _dot_general_validated_shape(lhs_shape, rhs_shape, dimension_numbers)\n+ out_shape = _dot_general_validated_shape(lhs_shape, rhs_shape,\n+ dimension_numbers)\n_validate_bcoo(data_aval, indices_aval, out_shape)\n(lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/util.py", "new_path": "jax/experimental/sparse/util.py", "diff": "@@ -28,6 +28,7 @@ from jax._src import stages\nfrom jax._src.api_util import flatten_axes\nimport jax.numpy as jnp\nfrom jax.util import safe_zip\n+from jax._src.lax.lax import _dot_general_shape_rule, DotDimensionNumbers\nfrom jax._src.typing import Array\nclass SparseEfficiencyError(ValueError):\n@@ -110,3 +111,13 @@ def _safe_asarray(args: Sequence[Any]) -> Iterable[Union[np.ndarray, Array]]:\nif _is_pytree_placeholder(*args) or _is_aval(*args) or _is_arginfo(*args):\nreturn args\nreturn map(_asarray_or_float0, args)\n+\n+def _dot_general_validated_shape(\n+ lhs_shape: Tuple[int, ...], rhs_shape: Tuple[int, ...],\n+ dimension_numbers: DotDimensionNumbers) -> Tuple[int, ...]:\n+ \"\"\"Validate the inputs and return the output shape.\"\"\"\n+ lhs = core.ShapedArray(lhs_shape, np.float32)\n+ rhs = core.ShapedArray(rhs_shape, np.float32)\n+ return _dot_general_shape_rule(\n+ lhs, rhs, dimension_numbers=dimension_numbers,\n+ precision=None, preferred_element_type=None)\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -32,7 +32,7 @@ from jax.experimental.sparse import coo as sparse_coo\nfrom jax.experimental.sparse import bcoo as sparse_bcoo\nfrom jax.experimental.sparse import bcsr as sparse_bcsr\nfrom jax.experimental.sparse.bcoo import BCOOInfo\n-from jax.experimental.sparse.util import _csr_to_coo\n+from jax.experimental.sparse import util as sparse_util\nfrom jax.experimental.sparse import test_util as sptu\nfrom jax import lax\nfrom jax._src.lib import gpu_sparse\n@@ -179,7 +179,7 @@ class cuSparseTest(sptu.SparseTestCase):\nrng = rand_sparse(self.rng(), post=jnp.array)\nM = rng(shape, dtype)\ndata, indices, indptr = sparse.csr_fromdense(M, nse=(M != 0).sum())\n- row, col = sparse.util._csr_to_coo(indices, indptr)\n+ row, col = sparse_util._csr_to_coo(indices, indptr)\nf = lambda data: sparse.csr_todense(data, indices, indptr, shape=M.shape)\n# Forward-mode\n@@ -1531,7 +1531,8 @@ class BCOOTest(sptu.SparseTestCase):\nreturn lax.dot_general(x, y, dimension_numbers=dimension_numbers)\ndef f_sparse(xsp, ysp):\n- shape = sparse.bcoo._dot_general_validated_shape(xsp.shape, ysp.shape, dimension_numbers)\n+ shape = sparse_util._dot_general_validated_shape(xsp.shape, ysp.shape,\n+ dimension_numbers)\ndata, indices = sparse_bcoo._bcoo_spdot_general(\nxsp.data, xsp.indices, ysp.data, ysp.indices, lhs_spinfo=xsp._info,\nrhs_spinfo=ysp._info, dimension_numbers=dimension_numbers)\n@@ -2317,7 +2318,7 @@ class BCSRTest(sptu.SparseTestCase):\nassert bcsr_mat.ndim == 2\nassert bcsr_mat.n_sparse == 2\nx = jnp.empty(bcsr_mat.shape, dtype=bcsr_mat.dtype)\n- row, col = _csr_to_coo(bcsr_mat.indices, bcsr_mat.indptr)\n+ row, col = sparse_util._csr_to_coo(bcsr_mat.indices, bcsr_mat.indptr)\nreturn x.at[row, col].set(bcsr_mat.data)\nwith self.subTest('_bcsr_to_elt'):\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Move _dot_general_validated_shape to sparse util. PiperOrigin-RevId: 494031113
260,411
07.12.2022 10:43:33
-7,200
86a70ab811c2e1dfd124ede7a90887f65eff9822
[jax2tf] Fix for jnp.roll with shape polymorphism There was a partial fix before, in but it was incomplete and the x64 mode was not handled properly. There are no tests added here; this was discovered by running the tests with --jax2tf_default_experimental_native_lowering, which will become default soon.
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -3506,9 +3506,11 @@ def _roll(a, shift, axis):\nfor x, i in zip(broadcast_to(shift, b_shape),\nnp.broadcast_to(axis, b_shape)):\ni = _canonicalize_axis(i, a_ndim)\n- x = remainder(x, (a_shape[i] or 1))\n+ a_shape_i = array(a_shape[i], dtype=np.int32)\n+ x = remainder(lax.convert_element_type(x, np.int32),\n+ lax.max(a_shape_i, np.int32(1)))\na = lax.concatenate((a, a), i)\n- a = lax.dynamic_slice_in_dim(a, array(a_shape[i]) - x, a_shape[i], axis=i)\n+ a = lax.dynamic_slice_in_dim(a, a_shape_i - x, a_shape[i], axis=i)\nreturn a\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix for jnp.roll with shape polymorphism There was a partial fix before, in #13470, but it was incomplete and the x64 mode was not handled properly. There are no tests added here; this was discovered by running the tests with --jax2tf_default_experimental_native_lowering, which will become default soon.
260,424
08.12.2022 16:16:49
0
7fe466c548c603807ac708fa66c76dc774d6c810
Small fix to scan type-check error message.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/loops.py", "new_path": "jax/_src/lax/control_flow/loops.py", "diff": "@@ -965,7 +965,7 @@ def _scan_typecheck(bind_time, *in_atoms, reverse, length, num_consts, num_carry\nif not all(_map(core.typecompat, x_avals_jaxpr, x_avals_mapped)):\nraise core.JaxprTypeError(\nf'scan jaxpr takes input sequence types\\n{_avals_short(x_avals_jaxpr)},\\n'\n- f'called with sequence of type\\n{_avals_short(x_avals)}')\n+ f'called with sequence whose items have type\\n{_avals_short(x_avals_mapped)}')\nreturn [*init_avals, *y_avals], jaxpr.effects\ndef _scan_pp_rule(eqn, context, settings):\n" } ]
Python
Apache License 2.0
google/jax
Small fix to scan type-check error message.
260,447
09.12.2022 10:09:48
28,800
11fbe5542ea7e215bb00de5d1cf38fec385c8f34
[sparse] Add rand_bcsr to generate a random BCSR array.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/test_util.py", "new_path": "jax/experimental/sparse/test_util.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Sparse test utilities.\"\"\"\n+import functools\n+\nfrom typing import Any, Callable, Sequence, Union\nimport numpy as np\n@@ -23,6 +25,7 @@ from jax._src.typing import DTypeLike\nfrom jax import tree_util\nfrom jax.util import split_list\nfrom jax.experimental import sparse\n+from jax.experimental.sparse import bcoo as sparse_bcoo\nimport jax.numpy as jnp\n@@ -84,23 +87,52 @@ class SparseTestCase(jtu.JaxTestCase):\nself.assertSparseArraysEquivalent(python_ans, compiled_ans, check_dtypes=check_dtypes,\natol=atol, rtol=rtol)\n+def _rand_sparse(shape: Sequence[int], dtype: DTypeLike, *,\n+ rng: np.random.RandomState, rand_method: Callable[..., Any],\n+ nse: Union[int, float], n_batch: int, n_dense: int,\n+ sparse_format: str) -> Union[sparse.BCOO, sparse.BCSR]:\n+ if sparse_format not in ['bcoo', 'bcsr']:\n+ raise ValueError(f\"Sparse format {sparse_format} not supported.\")\n-def rand_bcoo(rng: np.random.RandomState,\n- rand_method: Callable[..., Any] = jtu.rand_default,\n- nse: Union[int, float] = 0.5,\n- n_batch: int = 0, n_dense: int = 0) -> Callable[..., sparse.BCOO]:\n- def _rand_sparse(shape: Sequence[int], dtype: DTypeLike, nse: Union[int, float] = nse,\n- n_batch: int = n_batch, n_dense: int = n_dense) -> sparse.BCOO:\nn_sparse = len(shape) - n_batch - n_dense\n+\nif n_sparse < 0 or n_batch < 0 or n_dense < 0:\nraise ValueError(f\"Invalid parameters: {shape=} {n_batch=} {n_sparse=}\")\n- batch_shape, sparse_shape, dense_shape = split_list(shape, [n_batch, n_sparse])\n+\n+ if sparse_format == 'bcsr' and n_sparse != 2:\n+ raise ValueError(\"bcsr array must have 2 sparse dimensions; \"\n+ f\"{n_sparse} is given.\")\n+\n+ batch_shape, sparse_shape, dense_shape = split_list(shape,\n+ [n_batch, n_sparse])\nif 0 <= nse < 1:\nnse = int(np.ceil(nse * np.prod(sparse_shape)))\ndata_rng = rand_method(rng)\nindex_shape = (*batch_shape, nse, n_sparse)\ndata_shape = (*batch_shape, nse, *dense_shape)\n- indices = jnp.array(rng.randint(0, sparse_shape, size=index_shape, dtype=np.int32)) # type: ignore[arg-type]\n+ bcoo_indices = jnp.array(\n+ rng.randint(0, sparse_shape, size=index_shape, dtype=np.int32)) # type: ignore[arg-type]\ndata = jnp.array(data_rng(data_shape, dtype))\n- return sparse.BCOO((data, indices), shape=shape)\n- return _rand_sparse\n+\n+ if sparse_format == 'bcoo':\n+ return sparse.BCOO((data, bcoo_indices), shape=shape)\n+\n+ bcsr_indices, bcsr_indptr = sparse_bcoo._bcoo_to_bcsr(\n+ bcoo_indices, shape=shape)\n+ return sparse.BCSR((data, bcsr_indices, bcsr_indptr), shape=shape)\n+\n+def rand_bcoo(rng: np.random.RandomState,\n+ rand_method: Callable[..., Any]=jtu.rand_default,\n+ nse: Union[int, float]=0.5, n_batch: int=0, n_dense: int=0):\n+ \"\"\"Generates a random BCOO array.\"\"\"\n+ return functools.partial(_rand_sparse, rng=rng, rand_method=rand_method,\n+ nse=nse, n_batch=n_batch, n_dense=n_dense,\n+ sparse_format='bcoo')\n+\n+def rand_bcsr(rng: np.random.RandomState,\n+ rand_method: Callable[..., Any]=jtu.rand_default,\n+ nse: Union[int, float]=0.5, n_batch: int=0, n_dense: int=0):\n+ \"\"\"Generates a random BCSR array.\"\"\"\n+ return functools.partial(_rand_sparse, rng=rng, rand_method=rand_method,\n+ nse=nse, n_batch=n_batch, n_dense=n_dense,\n+ sparse_format='bcsr')\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Add rand_bcsr to generate a random BCSR array. PiperOrigin-RevId: 494201364
260,447
09.12.2022 15:22:15
28,800
a8b90b325a2d90aa0c2ca16cd10feac97f9b51ae
[sparse] Fix a bug in BCSR tree_flatten.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcsr.py", "new_path": "jax/experimental/sparse/bcsr.py", "diff": "@@ -22,6 +22,7 @@ from typing import NamedTuple, Optional, Sequence, Tuple\nimport numpy as np\nfrom jax import core\n+from jax import tree_util\nfrom jax.experimental.sparse._base import JAXSparse\nfrom jax.experimental.sparse import bcoo\nfrom jax.experimental.sparse.util import _broadcasting_vmap, _count_stored_elements, _csr_to_coo, _safe_asarray\n@@ -298,6 +299,7 @@ mlir.register_lowering(bcsr_extract_p, mlir.lower_fun(\n_bcsr_extract_impl, multiple_results=False))\n+@tree_util.register_pytree_node_class\nclass BCSR(JAXSparse):\n\"\"\"Experimental batched CSR matrix implemented in JAX.\"\"\"\n@@ -344,7 +346,7 @@ class BCSR(JAXSparse):\nraise NotImplementedError(\"Tranpose is not implemented.\")\ndef tree_flatten(self):\n- return (self.data, self.indices, self.indptr), {}\n+ return (self.data, self.indices, self.indptr), {'shape': self.shape}\n@classmethod\ndef _empty(cls, shape, *, dtype=None, index_dtype='int32', n_dense=0,\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -2450,6 +2450,7 @@ class SparseObjectTest(sptu.SparseTestCase):\nM = sparse.empty((2, 4), sparse_format=sparse_format)\nself.assertIsInstance(M, cls)\nbuffers, tree = tree_util.tree_flatten(M)\n+ self.assertTrue(all([isinstance(buffer, jax.Array) for buffer in buffers]))\nM_out = tree_util.tree_unflatten(tree, buffers)\nself.assertEqual(M.dtype, M_out.dtype)\nself.assertEqual(M.shape, M_out.shape)\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Fix a bug in BCSR tree_flatten. PiperOrigin-RevId: 494276415
260,424
09.12.2022 14:01:44
0
3db909ee8df4567f1f51670cc2b79fe9191a01a0
Checkify: Add documentation for adding run-time values to error message.
[ { "change_type": "MODIFY", "old_path": "docs/debugging/checkify_guide.md", "new_path": "docs/debugging/checkify_guide.md", "diff": "@@ -8,16 +8,16 @@ import jax\nimport jax.numpy as jnp\ndef f(x, i):\n- checkify.check(i >= 0, \"index needs to be non-negative!\")\n+ checkify.check(i >= 0, \"index needs to be non-negative, got {i}\", i=i)\ny = x[i]\nz = jnp.sin(y)\nreturn z\njittable_f = checkify.checkify(f)\n-err, z = jax.jit(jittable_f)(jnp.ones((5,)), -1)\n+err, z = jax.jit(jittable_f)(jnp.ones((5,)), -2)\nprint(err.get())\n-# >> index needs to be non-negative! (check failed at <...>:6 (f))\n+# >> index needs to be non-negative, got -2! (check failed at <...>:6 (f))\n```\nYou can also use checkify to automatically add common checks:\n@@ -108,19 +108,19 @@ The error is a regular value computed by the function, and the error is raised o\n```python\ndef f(x):\n- checkify.check(x > 0., \"must be positive!\") # convenient but effectful API\n+ checkify.check(x > 0., \"{} must be positive!\", x) # convenient but effectful API\nreturn jnp.log(x)\nf_checked = checkify(f)\n-err, x = jax.jit(f_checked)(0.)\n+err, x = jax.jit(f_checked)(-1.)\nerr.throw()\n-# ValueError: must be positive! (check failed at <...>:2 (f))\n+# ValueError: -1. must be positive! (check failed at <...>:2 (f))\n```\n-We call this functionalizing or discharging the effect introduced by calling check. (In the \"manual\" example above the error value is just a boolean. checkify's error values are conceptually similar but also track error messages and expose throw and get methods; see {mod}`jax.experimental.checkify`).\n+We call this functionalizing or discharging the effect introduced by calling check. (In the \"manual\" example above the error value is just a boolean. checkify's error values are conceptually similar but also track error messages and expose throw and get methods; see {mod}`jax.experimental.checkify`). `checkify.check` also allows you to add run-time values to your error message by providing them as format arguments to the error message.\n-You could now instrument your code with run-time checks, but `checkify` can also automatically add checks for common errors!\n+You could now manually instrument your code with run-time checks, but `checkify` can also automatically add checks for common errors!\nConsider these error cases:\n```python\n@@ -158,8 +158,27 @@ jitted. Here's a few more examples of `checkify` with other JAX\ntransformations. Note that checkified functions are functionally pure, and\nshould trivially compose with all JAX transformations!\n+### `jit`\n+\n+You can safely add `jax.jit` to a checkified function, or `checkify` a jitted\n+function, both will work.\n+\n+```python\n+def f(x, i):\n+ return x[i]\n+\n+checkify_of_jit = checkify.checkify(jax.jit(f))\n+jit_of_checkify = jax.jit(checkify.checkify(f))\n+err, _ = checkify_of_jit(jnp.ones((5,)), 100)\n+err.get()\n+# out-of-bounds indexing at <..>:2 (f)\n+err, _ = jit_of_checkify(jnp.ones((5,)), 100)\n+# out-of-bounds indexing at <..>:2 (f)\n+```\n+\n### `vmap`/`pmap`\n+You can `vmap` and `pmap` checkified functions (or `checkify` mapped functions).\nMapping a checkified function will give you a mapped error, which can contain\ndifferent errors for every element of the mapped dimension.\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/checkify.py", "new_path": "jax/_src/checkify.py", "diff": "@@ -598,7 +598,7 @@ def checkify_fun_to_jaxpr(\n-def check(pred: Bool, msg: str, *args, **kwargs) -> None:\n+def check(pred: Bool, msg: str, *fmt_args, **fmt_kwargs) -> None:\n\"\"\"Check a predicate, add an error with msg if predicate is False.\nThis is an effectful operation, and can't be staged (jitted/scanned/...).\n@@ -606,7 +606,14 @@ def check(pred: Bool, msg: str, *args, **kwargs) -> None:\nArgs:\npred: if False, an error is added.\n- msg: error message if error is added.\n+ msg: error message if error is added. Can be a format string.\n+ fmt_args, fmt_kwargs: Positional and keyword formatting arguments for\n+ `msg`, eg.:\n+ ``check(.., \"check failed on values {} and {named_arg}\", x, named_arg=y)``\n+ Note that these arguments can be traced values allowing you to add\n+ run-time values to the error message.\n+ Note that tracking these run-time arrays will increase your memory usage,\n+ even if no error happens.\nFor example:\n@@ -614,22 +621,23 @@ def check(pred: Bool, msg: str, *args, **kwargs) -> None:\n>>> import jax.numpy as jnp\n>>> from jax.experimental import checkify\n>>> def f(x):\n- ... checkify.check(x!=0, \"cannot be zero!\")\n+ ... checkify.check(x>0, \"{x} needs to be positive!\", x=x)\n... return 1/x\n>>> checked_f = checkify.checkify(f)\n- >>> err, out = jax.jit(checked_f)(0)\n+ >>> err, out = jax.jit(checked_f)(-3.)\n>>> err.throw() # doctest: +IGNORE_EXCEPTION_DETAIL\nTraceback (most recent call last):\n...\n- jax._src.checkify.JaxRuntimeError: cannot be zero!\n+ jax._src.checkify.JaxRuntimeError: -3. needs to be positive!\n\"\"\"\nif not is_scalar_pred(pred):\nraise TypeError(f'check takes a scalar pred as argument, got {pred}')\n- new_error = FailedCheckError(summary(), msg, *args, **kwargs)\n+ new_error = FailedCheckError(summary(), msg, *fmt_args, **fmt_kwargs)\nerror = assert_func(init_error, jnp.logical_not(pred), new_error)\nreturn check_error(error)\n+\ndef is_scalar_pred(pred) -> bool:\nreturn (isinstance(pred, bool) or\nisinstance(pred, jnp.ndarray) and pred.shape == () and\n" } ]
Python
Apache License 2.0
google/jax
Checkify: Add documentation for adding run-time values to error message.
260,464
13.12.2022 13:02:40
28,800
0e254a1f8146f912482f2a2660058b1482d23b01
jupytext version bump
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Custom_Operation_for_GPUs.md", "new_path": "docs/notebooks/Custom_Operation_for_GPUs.md", "diff": "@@ -5,7 +5,7 @@ jupytext:\nextension: .md\nformat_name: myst\nformat_version: 0.13\n- jupytext_version: 1.13.8\n+ jupytext_version: 1.14.1\nkernelspec:\ndisplay_name: Python 3 (ipykernel)\nlanguage: python\n" } ]
Python
Apache License 2.0
google/jax
jupytext version bump
260,424
12.12.2022 17:49:56
0
3134797968011e67168a74068e43606bd10cb89a
Add checkify.debug_check which is a noop outside of checkify.
[ { "change_type": "MODIFY", "old_path": "jax/_src/checkify.py", "new_path": "jax/_src/checkify.py", "diff": "@@ -243,7 +243,7 @@ class Error:\nreturn None\ndef throw(self):\n- check_error(self)\n+ _check_error(self)\ndef __str__(self):\nreturn f'Error({self.get()})'\n@@ -605,7 +605,7 @@ def check(pred: Bool, msg: str, *fmt_args, **fmt_kwargs) -> None:\nBefore staging a function with checks, :func:`~checkify` it!\nArgs:\n- pred: if False, an error is added.\n+ pred: if False, a FailedCheckError error is added.\nmsg: error message if error is added. Can be a format string.\nfmt_args, fmt_kwargs: Positional and keyword formatting arguments for\n`msg`, eg.:\n@@ -631,11 +631,23 @@ def check(pred: Bool, msg: str, *fmt_args, **fmt_kwargs) -> None:\njax._src.checkify.JaxRuntimeError: -3. needs to be positive!\n\"\"\"\n+ _check(pred, msg, False, *fmt_args, **fmt_kwargs)\n+\n+def _check(pred, msg, debug, *fmt_args, **fmt_kwargs):\nif not is_scalar_pred(pred):\n- raise TypeError(f'check takes a scalar pred as argument, got {pred}')\n+ prim_name = 'debug_check' if debug else 'check'\n+ raise TypeError(f'{prim_name} takes a scalar pred as argument, got {pred}')\nnew_error = FailedCheckError(summary(), msg, *fmt_args, **fmt_kwargs)\nerror = assert_func(init_error, jnp.logical_not(pred), new_error)\n- return check_error(error)\n+ _check_error(error, debug=debug)\n+\n+def _check_error(error, *, debug=False):\n+ error = tree_map(core.raise_as_much_as_possible, error)\n+ if any(map(np.shape, error._pred.values())):\n+ error = _reduce_any_error(error)\n+ err_args, tree_def = tree_flatten(error)\n+\n+ return check_p.bind(*err_args, err_tree=tree_def, debug=debug)\ndef is_scalar_pred(pred) -> bool:\n@@ -643,6 +655,44 @@ def is_scalar_pred(pred) -> bool:\nisinstance(pred, jnp.ndarray) and pred.shape == () and\npred.dtype == jnp.dtype('bool'))\n+\n+def debug_check(pred: Bool, msg: str, *fmt_args, **fmt_kwargs) -> None:\n+ \"\"\"Check a predicate when running under checkify, otherwise is a no-op.\n+\n+ A `debug_check` will only be run if it is transformed by :func:`~checkify`,\n+ otherwise the check will be dropped.\n+\n+ Args:\n+ pred: if False, a FailedCheckError error is added.\n+ msg: error message if error is added.\n+ fmt_args, fmt_kwargs: Positional and keyword formatting arguments for\n+ `msg`, eg.:\n+ ``debug_check(.., \"check failed on values {} and {named}\", x, named=y)``\n+ Note that these arguments can be traced values allowing you to add\n+ run-time values to the error message.\n+ Note that tracking these run-time arrays will increase your memory usage,\n+ even if no error happens.\n+\n+ For example:\n+\n+ >>> import jax\n+ >>> import jax.numpy as jnp\n+ >>> from jax.experimental import checkify\n+ >>> def f(x):\n+ ... checkify.debug_check(x!=0, \"cannot be zero!\")\n+ ... return x\n+ >>> _ = f(0) # running without checkify means no debug_check is run.\n+ >>> checked_f = checkify.checkify(f)\n+ >>> err, out = jax.jit(checked_f)(0) # running with checkify runs debug_check.\n+ >>> err.throw() # doctest: +IGNORE_EXCEPTION_DETAIL\n+ Traceback (most recent call last):\n+ ...\n+ jax._src.checkify.JaxRuntimeError: cannot be zero!\n+\n+ \"\"\"\n+ _check(pred, msg, True, *fmt_args, **fmt_kwargs)\n+\n+\ndef check_error(error: Error) -> None:\n\"\"\"Raise an Exception if ``error`` represents a failure. Functionalized by :func:`~checkify`.\n@@ -708,12 +758,8 @@ def check_error(error: Error) -> None:\nraise ValueError('check_error takes an Error as argument, '\nf'got type {type(error)} instead.')\n- error = tree_map(core.raise_as_much_as_possible, error)\n- if any(map(np.shape, error._pred.values())):\n- error = _reduce_any_error(error)\n- err_args, tree_def = tree_flatten(error)\n+ _check_error(error, debug=False)\n- return check_p.bind(*err_args, err_tree=tree_def)\n## check primitive\n@@ -725,7 +771,10 @@ class JaxRuntimeError(ValueError):\npass\n@check_p.def_impl\n-def check_impl(*args, err_tree):\n+def check_impl(*args, err_tree, debug):\n+ if debug:\n+ # NOOP (check will only trigger when discharged)\n+ return []\nerror = tree_unflatten(err_tree, args)\nexc = error.get_exception()\nif exc:\n@@ -733,7 +782,8 @@ def check_impl(*args, err_tree):\nreturn []\n@check_p.def_effectful_abstract_eval\n-def check_abstract_eval(*args, err_tree):\n+def check_abstract_eval(*args, err_tree, debug):\n+ del debug\nreturn [], set(tree_unflatten(err_tree, args)._pred.keys())\n# TODO(lenamartens) add in-depth error explanation to link to in module docs.\n@@ -744,7 +794,10 @@ functionalization_error = ValueError(\n' through `checkify.checkify`.'\n)\n-def check_lowering_rule(ctx, *args, err_tree):\n+def check_lowering_rule(ctx, *args, err_tree, debug):\n+ if debug:\n+ # NOOP (check will only trigger when discharged)\n+ return []\nif not config.jax_experimental_unsafe_xla_runtime_errors:\nraise functionalization_error\n@@ -758,12 +811,14 @@ def check_lowering_rule(ctx, *args, err_tree):\nctx.module_context.add_keepalive(keep_alive)\nreturn out_op\n-def check_lowering_rule_unsupported(*a, **k):\n+def check_lowering_rule_unsupported(*a, debug, **k):\n+ if debug:\n+ return []\nraise functionalization_error\ndef python_err(err_tree, *args):\nerror = tree_unflatten(err_tree, args)\n- check_error(error)\n+ _check_error(error)\nreturn []\nmlir.register_lowering(check_p, check_lowering_rule_unsupported,\n@@ -773,22 +828,20 @@ mlir.register_lowering(check_p, check_lowering_rule,\nmlir.register_lowering(check_p, check_lowering_rule,\nplatform='gpu')\n-def check_batching_rule(batched_args, batch_dims, *, err_tree):\n+def check_batching_rule(batched_args, batch_dims, *, err_tree, debug):\nsize = next(x.shape[dim] for x, dim in zip(batched_args, batch_dims)\nif dim is not batching.not_mapped)\nbatched_args = (batching.bdim_at_front(a, d, size)\nfor a, d in zip(batched_args, batch_dims))\nerr = tree_unflatten(err_tree, batched_args)\n- check_error(err)\n+ _check_error(err, debug=debug)\nreturn [], []\n-\nbatching.primitive_batchers[check_p] = check_batching_rule\n-def check_jvp_rule(primals, _, *, err_tree):\n+def check_jvp_rule(primals, _, *, err_tree, debug):\n# Check primals, discard tangents.\n- check_p.bind(*primals, err_tree=err_tree)\n+ check_p.bind(*primals, err_tree=err_tree, debug=debug)\nreturn [], []\n-\nad.primitive_jvps[check_p] = check_jvp_rule\n## checkify rules\n@@ -1106,7 +1159,8 @@ def pjit_error_check(error, enabled_errors, *vals_in, jaxpr,\nerror_checks[pjit.pjit_p] = pjit_error_check\n-def check_discharge_rule(error, enabled_errors, *args, err_tree):\n+def check_discharge_rule(error, enabled_errors, *args, err_tree, debug):\n+ del debug\nnew_error = tree_unflatten(err_tree, args)\n# Split up new_error into error to be functionalized if it's included in\n# enabled_errors (=discharged_error) and an error to be defunctionalized if\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -21,6 +21,7 @@ from jax._src.checkify import (\ncheck as check,\ncheck_error as check_error,\ncheckify as checkify,\n+ debug_check as debug_check,\ndiv_checks as div_checks,\nfloat_checks as float_checks,\nindex_checks as index_checks,\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -1092,6 +1092,64 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"hi!\")\n+ def test_debug_check_noop(self):\n+ def f(x):\n+ checkify.debug_check(jnp.all(x != x), \"{x} cannot be {x}\", x=x)\n+ return x\n+ x = jnp.ones(())\n+ f(x) # no error.\n+ jax.jit(f)(x) # no error.\n+ jax.vmap(f)(jnp.ones((2,))) # no error.\n+ jax.grad(f)(x) # no error.\n+\n+ @parameterized.named_parameters((\"with_jit\", True), (\"without_jit\", False))\n+ def test_debug_check_nonscalar_pred(self, with_jit):\n+ def f(x):\n+ checkify.debug_check(x != x, \"{x} cannot be {x}\", x=x)\n+ return x\n+ checked_f = checkify.checkify(f)\n+ if with_jit:\n+ checked_f = jax.jit(checked_f)\n+\n+ with self.assertRaisesRegex(TypeError, \"debug_check takes a scalar pred\"):\n+ checked_f(jnp.ones((5,)))\n+\n+\n+ @parameterized.named_parameters((\"with_jit\", True), (\"without_jit\", False))\n+ def test_debug_check(self, with_jit):\n+ def f(x):\n+ checkify.debug_check(jnp.all(x != x), \"{x} cannot be {x}\", x=x)\n+ return x\n+ checked_f = checkify.checkify(f)\n+ if with_jit:\n+ checked_f = jax.jit(checked_f)\n+ err, _ = checked_f(jnp.ones(()))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"1.0 cannot be 1.0\")\n+\n+ @parameterized.named_parameters((\"with_jit\", True), (\"without_jit\", False))\n+ def test_debug_check_disabled_errors(self, with_jit):\n+ def f(x):\n+ checkify.debug_check(jnp.all(x != x), \"{x} cannot be {x}\", x=x)\n+ return x\n+ checked_f = checkify.checkify(f, errors={})\n+ if with_jit:\n+ checked_f = jax.jit(checked_f)\n+ err, _ = checked_f(jnp.ones((1,)))\n+ self.assertIsNone(err.get())\n+\n+ def test_debug_check_jaxpr_roundtrip(self):\n+ def f(x):\n+ checkify.debug_check(jnp.all(x != x), \"{x} cannot be {x}\", x=x)\n+ return x\n+ x = jnp.ones(())\n+ jaxpr = jax.make_jaxpr(f)(x)\n+ roundtrip_f = partial(jax.core.eval_jaxpr, jaxpr.jaxpr, jaxpr.consts)\n+ checked_f = checkify.checkify(jax.jit(roundtrip_f))\n+ err, _ = checked_f(jnp.ones(()))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"1.0 cannot be 1.0\")\n+\nclass LowerableChecksTest(jtu.JaxTestCase):\ndef setUp(self):\n" } ]
Python
Apache License 2.0
google/jax
Add checkify.debug_check which is a noop outside of checkify.
260,411
04.12.2022 09:15:11
-7,200
ac7740513d0b47894d9170af6aaa6b9355fb2059
Raise error for unsupported shape polymorphism for custom call and fallback lowering
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/fft.py", "new_path": "jax/_src/lax/fft.py", "diff": "@@ -19,7 +19,7 @@ from typing import Union, Sequence\nimport numpy as np\nfrom jax._src.api import jit, linear_transpose, ShapeDtypeStruct\n-from jax.core import Primitive\n+from jax.core import Primitive, is_constant_shape\nfrom jax.interpreters import mlir\nfrom jax.interpreters import xla\nfrom jax._src.util import prod\n@@ -103,7 +103,6 @@ def fft_abstract_eval(x, fft_type, fft_lengths):\nreturn x.update(shape=shape, dtype=dtype)\ndef _fft_lowering(ctx, x, *, fft_type, fft_lengths):\n- out_aval, = ctx.avals_out\nreturn [\nmhlo.FftOp(x, mhlo.FftTypeAttr.get(fft_type.name),\nmlir.dense_int_elements(fft_lengths)).result\n@@ -111,6 +110,8 @@ def _fft_lowering(ctx, x, *, fft_type, fft_lengths):\ndef _fft_lowering_cpu(ctx, x, *, fft_type, fft_lengths):\n+ if any(not is_constant_shape(a.shape) for a in (ctx.avals_in + ctx.avals_out)):\n+ raise NotImplementedError(\"Shape polymorphism for custom call is not implemented (fft); b/261671778\")\nx_aval, = ctx.avals_in\nreturn [ducc_fft.ducc_fft_mhlo(x, x_aval.dtype, fft_type=fft_type,\nfft_lengths=fft_lengths)]\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/linalg.py", "new_path": "jax/_src/lax/linalg.py", "diff": "@@ -32,7 +32,7 @@ from jax.interpreters import xla\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax._src.util import prod\n-from jax.core import Primitive, ShapedArray, raise_to_shaped\n+from jax.core import Primitive, ShapedArray, raise_to_shaped, is_constant_shape\nfrom jax._src.lax.lax import (\nstandard_primitive, standard_unop, naryop_dtype_rule, _float, _complex,\n_input_dtype)\n@@ -423,6 +423,8 @@ def _cholesky_lowering(ctx, x):\nmlir.register_lowering(cholesky_p, _cholesky_lowering)\ndef _cholesky_cpu_gpu_lowering(potrf_impl, ctx, operand):\n+ if any(not is_constant_shape(a.shape) for a in (ctx.avals_in + ctx.avals_out)):\n+ raise NotImplementedError(\"Shape polymorphism for custom call is not implemented (cholesky); b/261671778\")\noperand_aval, = ctx.avals_in\nout_aval, = ctx.avals_out\nbatch_dims = operand_aval.shape[:-2]\n@@ -483,6 +485,8 @@ def eig_abstract_eval(operand, *, compute_left_eigenvectors,\ndef _eig_cpu_lowering(ctx, operand, *, compute_left_eigenvectors,\ncompute_right_eigenvectors):\n+ if any(not is_constant_shape(a.shape) for a in (ctx.avals_in + ctx.avals_out)):\n+ raise NotImplementedError(\"Shape polymorphism for custom call is not implemented (eig); b/261671778\")\noperand_aval, = ctx.avals_in\nout_aval = ctx.avals_out[0]\nbatch_dims = operand_aval.shape[:-2]\n@@ -632,6 +636,9 @@ def _eigh_abstract_eval(operand, *, lower, sort_eigenvalues):\ndef _eigh_cpu_gpu_lowering(syevd_impl, ctx, operand, *, lower,\nsort_eigenvalues):\n+ if any(not is_constant_shape(a.shape) for a in (ctx.avals_in + ctx.avals_out)):\n+ raise NotImplementedError(\"Shape polymorphism for custom call is not implemented (eigh); b/261671778\")\n+\ndel sort_eigenvalues # The CPU/GPU implementations always sort.\noperand_aval, = ctx.avals_in\nv_aval, w_aval = ctx.avals_out\n@@ -1171,6 +1178,8 @@ def _lu_batching_rule(batched_args, batch_dims):\nreturn lu_p.bind(x), (0, 0, 0)\ndef _lu_cpu_gpu_lowering(getrf_impl, ctx, operand):\n+ if any(not is_constant_shape(a.shape) for a in (ctx.avals_in + ctx.avals_out)):\n+ raise NotImplementedError(\"Shape polymorphism for custom call is not implemented (lu); b/261671778\")\noperand_aval, = ctx.avals_in\nout_aval, pivot_aval, perm_aval = ctx.avals_out\nbatch_dims = operand_aval.shape[:-2]\n@@ -1315,6 +1324,8 @@ def _geqrf_translation_rule(ctx, avals_in, avals_out, operand):\nreturn xops.QrDecomposition(operand)\ndef _geqrf_cpu_gpu_lowering(geqrf_impl, batched_geqrf_impl, ctx, a):\n+ if any(not is_constant_shape(a.shape) for a in (ctx.avals_in + ctx.avals_out)):\n+ raise NotImplementedError(\"Shape polymorphism for custom call is not implemented (geqrf); b/261671778\")\na_aval, taus_aval = ctx.avals_out\n*batch_dims, m, n = a_aval.shape\nbatch = prod(batch_dims)\n@@ -1404,6 +1415,8 @@ def _householder_product_translation_rule(ctx, avals_in, avals_out, a, taus):\nreturn [xops.ProductOfElementaryHouseholderReflectors(a, taus)]\ndef _householder_product_cpu_gpu_lowering(orgqr_impl, ctx, a, taus):\n+ if any(not is_constant_shape(a.shape) for a in (ctx.avals_in + ctx.avals_out)):\n+ raise NotImplementedError(\"Shape polymorphism for custom call is not implemented (householder product); b/261671778\")\na_aval, _ = ctx.avals_in\n*batch_dims, m, n = a_aval.shape\n@@ -1614,6 +1627,8 @@ def _empty_svd(a, *, full_matrices, compute_uv):\ndef _svd_cpu_gpu_lowering(gesvd_impl, ctx, operand, *, full_matrices,\ncompute_uv):\n+ if any(not is_constant_shape(a.shape) for a in (ctx.avals_in + ctx.avals_out)):\n+ raise NotImplementedError(\"Shape polymorphism for custom call is not implemented (svd); b/261671778\")\noperand_aval, = ctx.avals_in\ns_aval = ctx.avals_out[0]\nm, n = operand_aval.shape[-2:]\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": "@@ -2032,6 +2032,35 @@ def _flatten_harnesses(harnesses):\nres.append(h)\nreturn res\n+# Set of harness.group_name:platform that are implemented with custom call\n+custom_call_harnesses = {\n+ \"cholesky:cpu\", \"cholesky:gpu\", \"eig:cpu\",\n+ \"eigh:cpu\", \"eigh:gpu\", \"fft:cpu\",\n+ \"householder_product:cpu\", \"householder_product:gpu\",\n+ \"geqrf:cpu\", \"geqrf:gpu\", \"lu:cpu\", \"lu:gpu\", \"qr:cpu\", \"qr:gpu\",\n+ \"random_gamma:gpu\", \"random_categorical:gpu\",\n+ \"random_randint:gpu\", \"random_uniform:gpu\", \"random_split:gpu\",\n+ \"svd:cpu\", \"svd:gpu\"}\n+\n+# Set of harness.group_name or harness.group_name:platform that are implemented with HLO fallback lowering rules\n+fallback_lowering_harnesses = {\n+ \"approx_top_k:cpu\", \"bessel_i0e\", \"eigh:tpu\",\n+ \"erf_inv\", \"igamma\", \"igammac\", \"lu\",\n+ \"regularized_incomplete_beta\", \"qr:tpu\",\n+ \"random_gamma:cpu\", \"random_gamma:tpu\", \"svd:tpu\"}\n+\n+def _exclude_native_lowering_harnesses(harness: Harness):\n+ if config.jax2tf_default_experimental_native_lowering and not harness.params.get(\"enable_xla\", True):\n+ raise unittest.SkipTest(\"disabled for experimental_native_lowering and enable_xla=False\")\n+ if config.jax2tf_default_experimental_native_lowering:\n+ if f\"{harness.group_name}:{jtu.device_under_test()}\" in custom_call_harnesses:\n+ raise unittest.SkipTest(\"native lowering with shape polymorphism not implemented for custom calls; b/261671778\")\n+ if (config.jax2tf_default_experimental_native_lowering and\n+ (harness.group_name in fallback_lowering_harnesses or\n+ f\"{harness.group_name}:{jtu.device_under_test()}\" in fallback_lowering_harnesses)):\n+ raise unittest.SkipTest(\n+ \"native lowering with shape polymorphism not implemented for JAX primitives still using HLO fallback lowering; b/261682623\")\n+\nclass ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n\"\"\"Tests for primitives that take shape values as parameters.\"\"\"\n@@ -2043,11 +2072,10 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# to parameterized below.\n@primitive_harness.parameterized(\n_flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"roll_axis=None\",\n+ #one_containing=\"\",\n)\ndef test_prim(self, harness: Harness):\n- if config.jax2tf_default_experimental_native_lowering and not harness.params.get(\"enable_xla\", True):\n- raise unittest.SkipTest(\"disabled for experimental_native_lowering and enable_xla=False\")\n+ _exclude_native_lowering_harnesses(harness)\n_test_one_harness(self, harness)\ndef test_vmap_while(self):\n@@ -2207,6 +2235,7 @@ class ShapePolyVmapPrimitivesTest(tf_test_util.JaxToTfTestCase):\none_containing=\"\"\n)\ndef test_vmap_prim(self, harness: Harness):\n+ _exclude_native_lowering_harnesses(harness)\nreturn _test_one_harness(self, harness)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -1541,6 +1541,12 @@ def xla_fallback_lowering(prim: core.Primitive):\naxis_env = axis_ctx.unsafe_axis_env\nelse:\naxis_env = module_ctx.axis_env\n+\n+ if any(hasattr(a, \"shape\") and\n+ not core.is_constant_shape(a.shape) for a in (ctx.avals_in + ctx.avals_out)):\n+ raise NotImplementedError(\n+ f\"Shape polymorphism for xla_fallback_lowering is not implemented ({ctx.primitive}); b/261682623\")\n+\nxla_computation = xla.primitive_subcomputation(\nmodule_ctx.platform, axis_env, prim, ctx.avals_in,\nctx.avals_out, **params)\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/gpu_prng.py", "new_path": "jaxlib/gpu_prng.py", "diff": "@@ -49,6 +49,8 @@ def _threefry2x32_lowering(prng, platform, keys, data):\nir.IntegerType.get_unsigned(32)), keys[0].type\ntyp = keys[0].type\ndims = ir.RankedTensorType(typ).shape\n+ if any(d < 0 for d in dims):\n+ raise NotImplementedError(\"Shape polymorphism for custom call is not implemented (threefry); b/261671778\")\nfor x in itertools.chain(keys, data):\nassert x.type == typ, (x.type, typ)\n" } ]
Python
Apache License 2.0
google/jax
Raise error for unsupported shape polymorphism for custom call and fallback lowering
260,464
14.12.2022 23:41:57
28,800
3cacb9a35a9e0d144490f31be9576d4279a8f8c6
Remove unnecessary lines with +++
[ { "change_type": "MODIFY", "old_path": "docs/Custom_Operation_for_GPUs.md", "new_path": "docs/Custom_Operation_for_GPUs.md", "diff": "@@ -5,16 +5,12 @@ To accommodate such scenarios, JAX allows users to define custom operations and\nThis tutorial contains information from [Extending JAX with custom C++ and CUDA code](https://github.com/dfm/extending-jax).\n-+++\n-\n# RMS Normalization\nFor this tutorial, we are going to add the RMS normalization as a custom operation in JAX.\nThe CUDA code in `rms_norm_kernels.cu` for this operation has been borrowed from <https://github.com/NVIDIA/apex/blob/master/csrc/layer_norm_cuda_kernel.cu> and adapted to eliminate any dependency on PyTorch.\nSee [`gpu_ops` code listing](#gpu_ops-code-listing) for complete code listing of C++ and CUDA files.\n-+++\n-\n`rms_norm_kernels.cu` defines the following functions, which are declared with the XLA custom function signature.\nThese functions are responsible for launching RMS normalization kernels with the given `buffers` on the specified `stream`.\n@@ -54,8 +50,6 @@ struct RMSNormDescriptor {\n} // namespace gpu_ops\n```\n-+++\n-\nNow, we need to expose these functions as well as `ElementType` and `RMSNormDescriptor` as a Python module, `gpu_ops`, through `pybind11`.\n```cpp\n@@ -86,8 +80,6 @@ PYBIND11_MODULE(gpu_ops, m) {\n}\n```\n-+++\n-\n# Build `gpu_ops` extension module\nWe build the `gpu_ops` Python extension module with the aforementioned code.\n@@ -108,8 +100,6 @@ import sys\n`gpu_ops` is just a Python extension module and we need more work to plug it into JAX.\n-+++\n-\n## Create primitive ops\nWe first create primitive operations, `_rms_norm_fwd_p` and `_rms_norm_bwd_p`, which the custom functions can be mapped to.\n@@ -516,8 +506,6 @@ _rms_norm_bwd_p.def_abstract_eval(_rms_norm_bwd_abstract)\n# Let's test it again\n-+++\n-\n## Test forward function\n```ipython3\n@@ -638,8 +626,6 @@ out = loss_grad(x, weight)\nWe are using `jax.experimental.pjit.pjit` for parallel execution on multiple devices, and we produce reference values with sequential execution on a single device.\n-+++\n-\n## Test forward function\nLet's first test the forward operation on multiple devices. We are creating a simple 1D mesh and sharding `x` on all devices.\n@@ -759,8 +745,6 @@ True\nWith this modification, the `all-gather` operation is eliminated and the custom call is made on each shard of `x`.\n-+++\n-\n## Test backward function\nWe are moving onto the the backward operation using `jax.grad` on multiple devices.\n@@ -925,8 +909,6 @@ return (\n)\n```\n-+++\n-\n# Let's put it together\nHere is the complete code that is functional.\n" } ]
Python
Apache License 2.0
google/jax
Remove unnecessary lines with +++
260,464
14.12.2022 23:43:59
28,800
ef1a0cba6825d96fc78154307291b71a154b16ca
Set code block highlighting with python
[ { "change_type": "MODIFY", "old_path": "docs/Custom_Operation_for_GPUs.md", "new_path": "docs/Custom_Operation_for_GPUs.md", "diff": "@@ -106,7 +106,7 @@ We first create primitive operations, `_rms_norm_fwd_p` and `_rms_norm_bwd_p`, w\nWe set the `multipe_results` attribute to `True` for these operations, which means that the operation produces multipel outputs collected in an list.\nWhen it is set to `False`, the operation produces a single output without a list.\n-```ipython3\n+```python\nfrom functools import partial\nfrom build import gpu_ops\n@@ -150,7 +150,7 @@ The functions `_rms_norm_fwd_cuda_lowering` and `_rms_norm_bwd_cuda_lowering` be\nNote that an `RMSNormDescriptor` object is created in the lowering function, and passed to the custom call as `opaque`.\n-```ipython3\n+```python\nfrom jax.interpreters import mlir\nfrom jax.interpreters.mlir import ir\nfrom jaxlib.mhlo_helpers import custom_call\n@@ -262,7 +262,7 @@ mlir.register_lowering(\n# Let's test it\n-```ipython3\n+```python\nimport jax\n@@ -273,10 +273,10 @@ weight = jax.numpy.ones(norm_shape, dtype=jax.numpy.float16)\n## Test forward function\n-```ipython3\n+```python\nout = rms_norm_fwd(x, weight)\n```\n-```ipython3\n+```python\n---------------------------------------------------------------------------\nNotImplementedError Traceback (most recent call last)\nCell In [5], line 1\n@@ -447,7 +447,7 @@ These functions are passed to `.def_abstract_eval` method to be registered with\nSee [How JAX primitives work](https://jax.readthedocs.io/en/latest/notebooks/How_JAX_primitives_work.html#abstract-evaluation-rules) for more information on abstract evaluation.\n-```ipython3\n+```python\nfrom functools import reduce\nfrom operator import mul\n@@ -508,7 +508,7 @@ _rms_norm_bwd_p.def_abstract_eval(_rms_norm_bwd_abstract)\n## Test forward function\n-```ipython3\n+```python\nout = rms_norm_fwd(x, weight)\n```\n@@ -516,7 +516,7 @@ out = rms_norm_fwd(x, weight)\nNow let's test the backward operation using `jax.grad`.\n-```ipython3\n+```python\ndef loss(x, weight):\npredictions = rms_norm_fwd(x, weight)\nreturn -jax.numpy.mean(predictions**2)\n@@ -525,7 +525,7 @@ def loss(x, weight):\nloss_grad = jax.grad(loss)\nout = loss_grad(x, weight)\n```\n-```ipython3\n+```python\n---------------------------------------------------------------------------\nNotImplementedError Traceback (most recent call last)\nCell In [8], line 7\n@@ -563,7 +563,7 @@ The backward operation failed with the error `NotImplementedError: Differentiati\nWe can teach JAX that `rms_norm_bwd` is the backward operation for `rms_norm_fwd`, using `jax.custom_vjp` and its convention. As the first step, we need to refine the definition of `rms_norm_fwd` and `rms_norm_bwd`.\n-```ipython3\n+```python\n# rms_norm_fwd was previously defined as\n#\n# def rms_norm_fwd(x, weight, eps=1e-05):\n@@ -600,7 +600,7 @@ Now that `rms_norm_fwd` returns the residual data, which is not needed for simpl\nSee [Custom derivative rules for JAX-transformable Python functions](https://jax.readthedocs.io/en/latest/notebooks/Custom_derivative_rules_for_Python_code.html#use-jax-custom-vjp-to-define-custom-reverse-mode-only-rules) for more information on `jax.custom_vjp`.\n-```ipython3\n+```python\n@partial(jax.custom_vjp, nondiff_argnums=(2,))\ndef rms_norm(x, weight, eps=1e-05):\noutput, _ = rms_norm_fwd(x, weight, eps=eps)\n@@ -612,7 +612,7 @@ rms_norm.defvjp(rms_norm_fwd, rms_norm_bwd)\nWith the refinement we have made, the backward operation test works with a modification: `loss` now calls `rms_norm` instead of `rms_norm_fwd`.\n-```ipython3\n+```python\ndef loss(x, weight):\npredictions = rms_norm(x, weight)\nreturn -jax.numpy.mean(predictions**2)\n@@ -630,7 +630,7 @@ We are using `jax.experimental.pjit.pjit` for parallel execution on multiple dev\nLet's first test the forward operation on multiple devices. We are creating a simple 1D mesh and sharding `x` on all devices.\n-```ipython3\n+```python\nimport numpy\nfrom jax.experimental.maps import Mesh\nfrom jax.experimental.pjit import PartitionSpec, pjit\n@@ -650,7 +650,7 @@ with mesh:\nnumpy.allclose(ref, out)\n```\n-```ipython3\n+```python\nHloModule pjit_rms_norm, entry_computation_layout={(f16[4,512,512]{2,1,0},f16[512,512]{1,0})->f16[4,512,512]{2,1,0}}\n%fused_computation (param_1: f16[32,512,512], param_1.3: u32[]) -> f16[4,512,512] {\n@@ -673,7 +673,7 @@ ENTRY %main.7_spmd (param: f16[4,512,512], param.1: f16[512,512]) -> f16[4,512,5\nROOT %fusion = f16[4,512,512]{2,1,0} fusion(f16[32,512,512]{2,1,0} %get-tuple-element, u32[] %partition-id), kind=kLoop, calls=%fused_computation, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n}\n```\n-```ipython3\n+```python\nTrue\n```\n@@ -683,7 +683,7 @@ As XLA does not have enough knowledge about the custom functions to shard input\nTo avoid this overhead, we need to use the xmap manual sharding with the following configuration updates\n-```ipython3\n+```python\njax.config.update(\"experimental_xmap_spmd_lowering\", True)\njax.config.update(\"experimental_xmap_spmd_lowering_manual\", True)\n```\n@@ -694,7 +694,7 @@ We first define a function that wraps `rms_norm` with `xmap`. As the size of th\nAfter running `rms_norm` through `xmap`, we reshape the output to match the shape of `x` to match the expectation from clients.\n-```ipython3\n+```python\nfrom jax.experimental.maps import xmap\n@@ -713,7 +713,7 @@ def xmap_rms_norm(x, weight, *, device_count):\nNow we need to run `xmap_rms_norm`, not `rms_norm` through `pjit`.\n-```ipython3\n+```python\nwith mesh:\npjitted = pjit(\n@@ -729,7 +729,7 @@ with mesh:\nnumpy.allclose(ref, out)\n```\n-```ipython3\n+```python\nHloModule pjit__unnamed_wrapped_function_, entry_computation_layout={(f16[4,512,512]{2,1,0},f16[512,512]{1,0})->f16[4,512,512]{2,1,0}}\nENTRY %main.17_spmd (param: f16[4,512,512], param.1: f16[512,512]) -> f16[4,512,512] {\n@@ -739,7 +739,7 @@ ENTRY %main.17_spmd (param: f16[4,512,512], param.1: f16[512,512]) -> f16[4,512,\nROOT %get-tuple-element = f16[4,512,512]{2,1,0} get-tuple-element((f16[4,512,512]{2,1,0}, f32[4]{0}) %custom-call.0), index=0, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/xmap(rms_norm)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n}\n```\n-```ipython3\n+```python\nTrue\n```\n@@ -753,7 +753,7 @@ Similiarly to the forward operation test, we are creating a simple 1D mesh and s\nWe also define the `loss` function with `xmap_rms_norm` instead of `rms_norm`\n-```ipython3\n+```python\ndef loss_ref(x, weight):\npredictions = rms_norm(x, weight)\nreturn -jax.numpy.mean(predictions**2)\n@@ -786,19 +786,19 @@ with mesh:\nfor r, o in zip(ref, out):\nprint(numpy.allclose(r, o))\n```\n-```ipython3\n+```python\nTrue\nTrue\n```\nWe can inspect the generated jaxpr, which is the JAX internal representation, to make sure `jax.grad` inserts a `psum` for the gradient accumulation across the devices when needed.\n-```ipython3\n+```python\nwith mesh:\nprint(jax.make_jaxpr(pjitted)(x, weight))\n```\n-```ipython3\n+```python\n{ lambda ; a:f16[32,512,512] b:f16[512,512]. let\nc:f16[32,512,512] d:f16[512,512] = pjit[\ndonated_invars=(False, False)\n@@ -913,7 +913,7 @@ return (\nHere is the complete code that is functional.\n-```ipython3\n+```python\nfrom functools import partial, reduce\nfrom operator import mul\n@@ -1199,7 +1199,7 @@ with Mesh(numpy.array(jax.local_devices()).reshape(-1), (\"a\",)):\nfor r, o in zip(ref, out):\nprint(numpy.allclose(r, o))\n```\n-```ipython3\n+```python\nTrue\nTrue\n```\n" } ]
Python
Apache License 2.0
google/jax
Set code block highlighting with python
260,411
16.12.2022 08:50:30
-7,200
fe6418a8a0c3a588a56df6b83ef857b1e33cad85
[jax2tf] Force keep_unused for native lowering when we have shape polymorphism In presence of dimension variables we conservatively do not drop unused inputs because we may drop the only inputs from whose shape we can infer the values of the dimension variables. See b/261971607.
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -742,6 +742,12 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\nif abstracted_axes:\nraise ValueError(\"abstracted_axes must be used with --jax_dynamic_shapes\")\nin_avals, _ = unzip2(arg_specs_and_devices)\n+ if any(not core.is_constant_shape(a.shape) for a in in_avals):\n+ # TODO(b/262808613): Do not drop unused inputs when we have\n+ # shape polymorphism, to ensure that we can always derive\n+ # the dimension variables from the kept inputs.\n+ nonlocal keep_unused\n+ keep_unused = True\nif jax.config.jax_array:\ncomputation = dispatch.sharded_lowering(\nflat_fun, device, backend, flat_fun.__name__, donated_invars, True,\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": "@@ -756,14 +756,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# A polymorphic arg is not used, and the dimension var does not appear\n# elsewhere.\n- if config.jax2tf_default_experimental_native_lowering:\n- with self.assertRaisesRegex(ValueError,\n- \"The following dimension variables cannot be computed\"):\n- self.CheckShapePolymorphism(\n- lambda x_unused, y: y * 2.0,\n- input_signature=[tf.TensorSpec([None]), tf.TensorSpec([None])],\n- polymorphic_shapes=[\"b1\", \"b2\"])\n- else:\nself.CheckShapePolymorphism(\nlambda x_unused, y: y * 2.0,\ninput_signature=[tf.TensorSpec([None]), tf.TensorSpec([None])],\n@@ -771,14 +763,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# A polymorphic arg is not used, and the dimension var does appear\n# elsewhere but not as a trivial monomial.\n- if config.jax2tf_default_experimental_native_lowering:\n- with self.assertRaisesRegex(ValueError,\n- \"The following dimension variables cannot be computed\"):\n- self.CheckShapePolymorphism(\n- lambda x_unused, y: y * 2.0,\n- input_signature=[tf.TensorSpec([None]), tf.TensorSpec([None])],\n- polymorphic_shapes=[\"b1\", \"b1 * b1\"])\n- else:\nself.CheckShapePolymorphism(\nlambda x_unused, y: y * 2.0,\ninput_signature=[tf.TensorSpec([None]), tf.TensorSpec([None])],\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Force keep_unused for native lowering when we have shape polymorphism In presence of dimension variables we conservatively do not drop unused inputs because we may drop the only inputs from whose shape we can infer the values of the dimension variables. See b/261971607.
260,464
16.12.2022 12:27:49
28,800
8a0b4d947d24e7d4dde5c405c7a3983a3ba33c57
inline xmap_axes in the xmap call
[ { "change_type": "MODIFY", "old_path": "docs/Custom_Operation_for_GPUs.md", "new_path": "docs/Custom_Operation_for_GPUs.md", "diff": "@@ -542,11 +542,10 @@ from jax.experimental.maps import xmap\ndef xmap_rms_norm(x, weight, *, device_count):\nreshaped = x.reshape(device_count, x.shape[0] // device_count, *x.shape[1:])\n- xmap_axes = ((\"x\", None, None, None), (None, None))\nxmapped = xmap(\nrms_norm,\n- in_axes=xmap_axes,\n- out_axes=xmap_axes[0],\n+ in_axes=((\"x\", None, None, None), (None, None)),\n+ out_axes=(\"x\", None, None, None),\naxis_resources={\"x\": \"x\"},\n)\nreshaped_out = xmapped(reshaped, weight)\n@@ -989,11 +988,10 @@ jax.config.update(\"experimental_xmap_spmd_lowering_manual\", True)\ndef xmap_rms_norm(x, weight, *, device_count):\nreshaped = x.reshape(device_count, x.shape[0] // device_count, *x.shape[1:])\n- xmap_axes = ((\"x\", None, None, None), (None, None))\nxmapped = xmap(\nrms_norm,\n- in_axes=xmap_axes,\n- out_axes=xmap_axes[0],\n+ in_axes=((\"x\", None, None, None), (None, None)),\n+ out_axes=(\"x\", None, None, None),\naxis_resources={\"x\": \"x\"},\n)\nreshaped_out = xmapped(reshaped, weight)\n" } ]
Python
Apache License 2.0
google/jax
inline xmap_axes in the xmap call
260,447
16.12.2022 15:00:06
28,800
49086e84558c0ae749f6766e731104cffa0d2558
[sparse] Use SparseInfo for both bcoo and bcsr format.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcoo.py", "new_path": "jax/experimental/sparse/bcoo.py", "diff": "@@ -33,7 +33,8 @@ from jax.experimental.sparse._base import JAXSparse\nfrom jax.experimental.sparse.util import (\n_broadcasting_vmap, _count_stored_elements,\n_dot_general_validated_shape, CuSparseEfficiencyWarning,\n- SparseEfficiencyError, SparseEfficiencyWarning)\n+ SparseEfficiencyError, SparseEfficiencyWarning, Shape,\n+ SparseInfo)\nfrom jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import mlir\n@@ -54,10 +55,6 @@ from jax._src.typing import Array, ArrayLike, DType, DTypeLike\nfrom jax._src.util import canonicalize_axis\n-Dtype = Any\n-Shape = Tuple[int, ...]\n-\n-\n#----------------------------------------------------------------------\n# BCOO primitives: batched extension of COO.\n@@ -106,17 +103,11 @@ class BCOOProperties(NamedTuple):\nn_dense: int\nnse: int\n-class BCOOInfo(NamedTuple):\n- shape: Shape\n- indices_sorted: bool = False\n- unique_indices: bool = False\n-\n-\nclass Buffer(Protocol):\n@property\n- def shape(self) -> Tuple[int, ...]: ...\n+ def shape(self) -> Shape: ...\n@property\n- def dtype(self) -> DType: ...\n+ def dtype(self) -> Any: ...\ndef _validate_bcoo(data: Buffer, indices: Buffer, shape: Sequence[int]) -> BCOOProperties:\n@@ -181,13 +172,14 @@ def bcoo_todense(mat: BCOO) -> Array:\n\"\"\"\nreturn _bcoo_todense(mat.data, mat.indices, spinfo=mat._info)\n-def _bcoo_todense(data: Array, indices: Array, *, spinfo: BCOOInfo) -> Array:\n+def _bcoo_todense(data: Array, indices: Array, *, spinfo: SparseInfo\n+ ) -> Array:\n\"\"\"Convert batched sparse matrix to a dense matrix.\nArgs:\ndata : array of shape ``batch_dims + (nse,) + block_dims``.\nindices : array of shape ``batch_dims + (n_sparse, nse)``\n- spinfo : BCOOInfo. In particular, this includes the shape\n+ spinfo : SparseInfo. In particular, this includes the shape\nof the matrix, which is equal to ``batch_dims + sparse_dims + block_dims``\nwhere ``len(sparse_dims) == n_sparse``\n@@ -240,7 +232,7 @@ def _bcoo_todense_batching_rule(batched_args, batch_dims, *, spinfo):\ndata = data[None, ...]\nif batch_dims[1] is None:\nindices = indices[None, ...]\n- new_spinfo = BCOOInfo(\n+ new_spinfo = SparseInfo(\nshape=(max(data.shape[0], indices.shape[0]), *spinfo.shape),\nindices_sorted=spinfo.indices_sorted,\nunique_indices=spinfo.unique_indices)\n@@ -366,7 +358,7 @@ def _bcoo_fromdense_transpose(ct, M, *, nse, n_batch, n_dense, index_dtype):\nif isinstance(indices, ad.Zero):\nraise ValueError(\"Cannot transpose with respect to sparse indices\")\nassert ad.is_undefined_primal(M)\n- return _bcoo_todense(data, indices, spinfo=BCOOInfo(M.aval.shape))\n+ return _bcoo_todense(data, indices, spinfo=SparseInfo(M.aval.shape))\ndef _bcoo_fromdense_batching_rule(batched_args, batch_dims, *, nse, n_batch, n_dense, index_dtype):\nM, = batched_args\n@@ -435,7 +427,7 @@ def _bcoo_extract_transpose(ct, indices, mat):\nif ad.is_undefined_primal(indices):\nraise ValueError(\"Cannot transpose with respect to sparse indices\")\nassert ct.dtype == mat.aval.dtype\n- return indices, _bcoo_todense(ct, indices, spinfo=BCOOInfo(mat.aval.shape))\n+ return indices, _bcoo_todense(ct, indices, spinfo=SparseInfo(mat.aval.shape))\ndef _bcoo_extract_batching_rule(batched_args, batch_dims):\nindices, mat = batched_args\n@@ -491,7 +483,7 @@ def bcoo_transpose(mat: BCOO, *, permutation: Sequence[int]) -> BCOO:\nreturn BCOO(buffers, shape=out_shape, unique_indices=mat.unique_indices)\ndef _bcoo_transpose(data: Array, indices: Array, *,\n- permutation: Sequence[int], spinfo: BCOOInfo) -> Tuple[Array, Array]:\n+ permutation: Sequence[int], spinfo: SparseInfo) -> Tuple[Array, Array]:\npermutation = tuple(permutation)\nif permutation == tuple(range(len(spinfo.shape))):\nreturn data, indices\n@@ -518,7 +510,7 @@ def _validate_permutation(data, indices, permutation, shape):\nreturn batch_perm, sparse_perm, dense_perm\n@bcoo_transpose_p.def_impl\n-def _bcoo_transpose_impl(data, indices, *, permutation: Sequence[int], spinfo: BCOOInfo):\n+def _bcoo_transpose_impl(data, indices, *, permutation: Sequence[int], spinfo: SparseInfo):\nbatch_perm, sparse_perm, dense_perm = _validate_permutation(data, indices, permutation, spinfo.shape)\nn_batch = len(batch_perm)\nindices = indices[..., sparse_perm].transpose(*batch_perm, n_batch, n_batch + 1)\n@@ -526,34 +518,34 @@ def _bcoo_transpose_impl(data, indices, *, permutation: Sequence[int], spinfo: B\nreturn data, indices\n@bcoo_transpose_p.def_abstract_eval\n-def _bcoo_transpose_abstract_eval(data, indices, *, permutation: Sequence[int], spinfo: BCOOInfo):\n+def _bcoo_transpose_abstract_eval(data, indices, *, permutation: Sequence[int], spinfo: SparseInfo):\nbatch_perm, _, dense_perm = _validate_permutation(data, indices, permutation, spinfo.shape)\nn_batch = len(batch_perm)\nindices_shape = np.array(indices.shape)[[*batch_perm, n_batch, n_batch + 1]]\ndata_shape = np.array(data.shape)[[*batch_perm, n_batch, *(d + n_batch + 1 for d in dense_perm)]]\nreturn core.ShapedArray(data_shape, data.dtype), core.ShapedArray(indices_shape, indices.dtype)\n-def _bcoo_transpose_jvp(primals, tangents, *, permutation: Sequence[int], spinfo: BCOOInfo):\n+def _bcoo_transpose_jvp(primals, tangents, *, permutation: Sequence[int], spinfo: SparseInfo):\ndata, indices = primals\ndata_dot, _ = tangents\nprimals_out = _bcoo_transpose(data, indices, permutation=permutation, spinfo=spinfo)\ndata_dot_out, _ = _bcoo_transpose(data_dot, indices, permutation=permutation, spinfo=spinfo)\nreturn primals_out, (data_dot_out, ad.Zero.from_value(indices))\n-def _bcoo_transpose_transpose(ct, data, indices, *, permutation: Sequence[int], spinfo: BCOOInfo):\n+def _bcoo_transpose_transpose(ct, data, indices, *, permutation: Sequence[int], spinfo: SparseInfo):\ndata_ct, indices_ct = ct\nassert isinstance(indices_ct, ad.Zero)\nif ad.is_undefined_primal(indices):\nraise ValueError(\"Cannot transpose with respect to sparse indices\")\nassert data_ct.dtype == data.aval.dtype\n- ct_spinfo = BCOOInfo(tuple(spinfo.shape[p] for p in permutation))\n+ ct_spinfo = SparseInfo(tuple(spinfo.shape[p] for p in permutation))\nrev_permutation = list(np.argsort(permutation))\n# TODO(jakevdp) avoid dummy indices?\ndummy_indices = jnp.zeros([1 for i in range(indices.ndim - 2)] + list(indices.shape[-2:]), dtype=int)\ndata_trans, _ = _bcoo_transpose(data_ct, dummy_indices, permutation=rev_permutation, spinfo=ct_spinfo)\nreturn data_trans, indices_ct\n-def _bcoo_transpose_batch_rule(batched_args, batch_dims, *, permutation: Sequence[int], spinfo: BCOOInfo):\n+def _bcoo_transpose_batch_rule(batched_args, batch_dims, *, permutation: Sequence[int], spinfo: SparseInfo):\ndata, indices = batched_args\nbatch_dims = list(batch_dims)\nbatch_size = max(0 if dim is None else arg.shape[dim]\n@@ -566,7 +558,7 @@ def _bcoo_transpose_batch_rule(batched_args, batch_dims, *, permutation: Sequenc\nindices = indices[None]\nelse:\nassert batch_dims[1] == 0\n- batched_spinfo = BCOOInfo((batch_size, *spinfo.shape))\n+ batched_spinfo = SparseInfo((batch_size, *spinfo.shape))\nbatched_permutation = (0, *(p + 1 for p in permutation))\ndata, indices = _bcoo_transpose(data, indices, permutation=batched_permutation, spinfo=batched_spinfo)\nif batch_dims[0] is None:\n@@ -625,7 +617,7 @@ def bcoo_dot_general(lhs: Union[BCOO, Array], rhs: Union[BCOO, Array], *, dimens\nreturn lax.dot_general(lhs, rhs, dimension_numbers=dimension_numbers)\ndef _bcoo_dot_general(lhs_data: Array, lhs_indices: Array, rhs: Array, *,\n- dimension_numbers: DotDimensionNumbers, lhs_spinfo: BCOOInfo) -> Array:\n+ dimension_numbers: DotDimensionNumbers, lhs_spinfo: SparseInfo) -> Array:\n(lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\ncdims = (api_util._ensure_index_tuple(lhs_contract),\napi_util._ensure_index_tuple(rhs_contract))\n@@ -636,7 +628,7 @@ def _bcoo_dot_general(lhs_data: Array, lhs_indices: Array, rhs: Array, *,\nlhs_spinfo=lhs_spinfo)\ndef _bcoo_rdot_general(lhs: Array, rhs_data: Array, rhs_indices: Array, *,\n- dimension_numbers: DotDimensionNumbers, rhs_spinfo: BCOOInfo) -> Array:\n+ dimension_numbers: DotDimensionNumbers, rhs_spinfo: SparseInfo) -> Array:\n# TODO(jakevdp): perhaps this should be part of the bcoo_dot_general primitive?\ndimension_numbers_reversed: DotDimensionNumbers = tuple(d[::-1] for d in dimension_numbers) # type: ignore[assignment]\nresult = _bcoo_dot_general(rhs_data, rhs_indices, lhs, lhs_spinfo=rhs_spinfo,\n@@ -647,7 +639,7 @@ def _bcoo_rdot_general(lhs: Array, rhs_data: Array, rhs_indices: Array, *,\nreturn lax.transpose(result, permutation)\n@bcoo_dot_general_p.def_impl\n-def _bcoo_dot_general_impl(lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n+def _bcoo_dot_general_impl(lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: SparseInfo):\nlhs_data = jnp.asarray(lhs_data)\nlhs_indices = jnp.asarray(lhs_indices)\nrhs = jnp.asarray(rhs)\n@@ -704,7 +696,7 @@ def _bcoo_dot_general_impl(lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs\nreturn result(out_array, lhs_data, lhs_indices, rhs)\n@bcoo_dot_general_p.def_abstract_eval\n-def _bcoo_dot_general_abstract_eval(lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n+def _bcoo_dot_general_abstract_eval(lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: SparseInfo):\nif lhs_data.dtype != rhs.dtype:\nraise ValueError(\"bcoo_dot_general requires arguments to have matching dtypes; \"\nf\"got lhs.dtype={lhs_data.dtype}, rhs.dtype={rhs.dtype}\")\n@@ -739,7 +731,7 @@ def _collapse_hlo(x, start, end):\ndef _bcoo_dot_general_cuda_lowering(\ncoo_matvec_lowering, coo_matmat_lowering, ctx, lhs_data, lhs_indices, rhs,\n- *, dimension_numbers, lhs_spinfo: BCOOInfo):\n+ *, dimension_numbers, lhs_spinfo: SparseInfo):\n(lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\nlhs_data_aval, lhs_indices_aval, rhs_aval, = ctx.avals_in\nprops = _validate_bcoo_indices(lhs_indices_aval, lhs_spinfo.shape)\n@@ -892,7 +884,7 @@ def _bcoo_dot_general_cuda_lowering(\ndef _bcoo_dot_general_gpu_lowering(\ncoo_matvec_lowering, coo_matmat_lowering,\nctx, lhs_data, lhs_indices, rhs, *, dimension_numbers,\n- lhs_spinfo: BCOOInfo):\n+ lhs_spinfo: SparseInfo):\nif not config.jax_bcoo_cusparse_lowering:\nreturn _bcoo_dot_general_default_lowering(\n@@ -952,13 +944,13 @@ def _bcoo_dot_general_gpu_lowering(\ncoo_matvec_lowering, coo_matmat_lowering, ctx, lhs_data, lhs_indices, rhs,\ndimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n-def _bcoo_dot_general_jvp_lhs(lhs_data_dot, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n+def _bcoo_dot_general_jvp_lhs(lhs_data_dot, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: SparseInfo):\nreturn _bcoo_dot_general(lhs_data_dot, lhs_indices, rhs, dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n-def _bcoo_dot_general_jvp_rhs(rhs_dot, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n+def _bcoo_dot_general_jvp_rhs(rhs_dot, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: SparseInfo):\nreturn _bcoo_dot_general(lhs_data, lhs_indices, rhs_dot, dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n-def _bcoo_dot_general_transpose(ct, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n+def _bcoo_dot_general_transpose(ct, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: SparseInfo):\nassert not ad.is_undefined_primal(lhs_indices)\nif type(ct) is ad.Zero:\nreturn ad.Zero\n@@ -981,7 +973,7 @@ def _bcoo_dot_general_transpose(ct, lhs_data, lhs_indices, rhs, *, dimension_num\n# Instead we (1) un-transpose indices, (2) compute SDDMM, (3) re-transpose result\ndummy_data = jnp.ones([1 for i in range(lhs_indices.ndim - 2)] + [lhs_indices.shape[-2]])\n- dummy_spinfo = BCOOInfo(tuple(lhs_indices.shape[:-2]) + tuple(1 for i in range(lhs_indices.shape[-1])))\n+ dummy_spinfo = SparseInfo(tuple(lhs_indices.shape[:-2]) + tuple(1 for i in range(lhs_indices.shape[-1])))\n_, lhs_indices_T = _bcoo_transpose(dummy_data, lhs_indices, permutation=permutation, spinfo=dummy_spinfo)\nresult_T = bcoo_dot_general_sampled(ct, rhs, lhs_indices_T, dimension_numbers=dims)\nresult, _ = _bcoo_transpose(result_T, lhs_indices_T, permutation=out_axes, spinfo=dummy_spinfo)\n@@ -994,7 +986,7 @@ def _bcoo_dot_general_transpose(ct, lhs_data, lhs_indices, rhs, *, dimension_num\nresult = _bcoo_dot_general(lhs_data, lhs_indices, ct, lhs_spinfo=lhs_spinfo, dimension_numbers=dims)\nreturn lhs_data, lhs_indices, lax.transpose(result, out_axes)\n-def _bcoo_dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers, lhs_spinfo: BCOOInfo):\n+def _bcoo_dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers, lhs_spinfo: SparseInfo):\nlhs_data, lhs_indices, rhs = batched_args\nbatch_dims = list(batch_dims)\nbatch_size = max(0 if dim is None else arg.shape[dim]\n@@ -1010,7 +1002,7 @@ def _bcoo_dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers,\nnew_dimension_numbers, result_batch_dim = _dot_general_batch_dim_nums(\n(len(lhs_spinfo.shape), rhs.ndim), (batch_dims[0], batch_dims[2]), dimension_numbers)\nnew_shape = (batch_size, *lhs_spinfo.shape)\n- batched_out = _bcoo_dot_general(lhs_data, lhs_indices, rhs, lhs_spinfo=BCOOInfo(new_shape),\n+ batched_out = _bcoo_dot_general(lhs_data, lhs_indices, rhs, lhs_spinfo=SparseInfo(new_shape),\ndimension_numbers=new_dimension_numbers)\nreturn batched_out, result_batch_dim\n@@ -1115,7 +1107,7 @@ bcoo_spdot_general_p = core.Primitive('bcoo_spdot_general')\nbcoo_spdot_general_p.multiple_results = True\ndef _bcoo_spdot_general(lhs_data: Array, lhs_indices: Array, rhs_data: Array, rhs_indices: Array, *,\n- lhs_spinfo: BCOOInfo, rhs_spinfo: BCOOInfo, dimension_numbers: DotDimensionNumbers) -> Tuple[Array, Array]:\n+ lhs_spinfo: SparseInfo, rhs_spinfo: SparseInfo, dimension_numbers: DotDimensionNumbers) -> Tuple[Array, Array]:\n(lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\ncdims = (api_util._ensure_index_tuple(lhs_contract),\napi_util._ensure_index_tuple(rhs_contract))\n@@ -1170,10 +1162,10 @@ def _bcoo_spdot_general_unbatched(lhs_data, lhs_indices, rhs_data, rhs_indices,\nout_nse = (lhs.nse if lhs_j.shape[1] else 1) * (rhs.nse if rhs_j.shape[1] else 1)\n# Note: we do not eliminate zeros here, because it can cause issues with autodiff.\n# See https://github.com/google/jax/issues/10163.\n- return _bcoo_sum_duplicates(out_data, out_indices, spinfo=BCOOInfo(shape=out_shape), nse=out_nse)\n+ return _bcoo_sum_duplicates(out_data, out_indices, spinfo=SparseInfo(shape=out_shape), nse=out_nse)\n@bcoo_spdot_general_p.def_impl\n-def _bcoo_spdot_general_impl(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_spinfo: BCOOInfo, rhs_spinfo: BCOOInfo, dimension_numbers):\n+def _bcoo_spdot_general_impl(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_spinfo: SparseInfo, rhs_spinfo: SparseInfo, dimension_numbers):\nlhs_shape = lhs_spinfo.shape\nrhs_shape = rhs_spinfo.shape\n@@ -1199,8 +1191,8 @@ def _bcoo_spdot_general_impl(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lh\n# Implement batched dot product via vmap\nfunc = functools.partial(_bcoo_spdot_general_unbatched,\n- lhs_spinfo=BCOOInfo(lhs_shape[lhs.n_batch:]),\n- rhs_spinfo=BCOOInfo(rhs_shape[rhs.n_batch:]),\n+ lhs_spinfo=SparseInfo(lhs_shape[lhs.n_batch:]),\n+ rhs_spinfo=SparseInfo(rhs_shape[rhs.n_batch:]),\nlhs_contracting=[d - lhs.n_batch for d in lhs_contracting],\nrhs_contracting=[d - rhs.n_batch for d in rhs_contracting])\n@@ -1213,7 +1205,7 @@ def _bcoo_spdot_general_impl(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lh\nreturn func(lhs_data, lhs_indices, rhs_data, rhs_indices)\n@bcoo_spdot_general_p.def_abstract_eval\n-def _bcoo_spdot_general_abstract_eval(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_spinfo: BCOOInfo, rhs_spinfo: BCOOInfo, dimension_numbers):\n+def _bcoo_spdot_general_abstract_eval(lhs_data, lhs_indices, rhs_data, rhs_indices, *, lhs_spinfo: SparseInfo, rhs_spinfo: SparseInfo, dimension_numbers):\nlhs_shape = lhs_spinfo.shape\nrhs_shape = rhs_spinfo.shape\n@@ -1258,7 +1250,7 @@ def _bcoo_spdot_general_abstract_eval(lhs_data, lhs_indices, rhs_data, rhs_indic\nout_nse, lhs.n_sparse + rhs.n_sparse - 2 * len(lhs_contracting))\nreturn core.ShapedArray(data_shape, lhs_data.dtype), core.ShapedArray(indices_shape, lhs_indices.dtype)\n-def _bcoo_spdot_general_batch_rule(batched_args, batch_dims, *, lhs_spinfo: BCOOInfo, rhs_spinfo: BCOOInfo, dimension_numbers):\n+def _bcoo_spdot_general_batch_rule(batched_args, batch_dims, *, lhs_spinfo: SparseInfo, rhs_spinfo: SparseInfo, dimension_numbers):\nlhs_shape = lhs_spinfo.shape\nrhs_shape = rhs_spinfo.shape\n@@ -1288,8 +1280,8 @@ def _bcoo_spdot_general_batch_rule(batched_args, batch_dims, *, lhs_spinfo: BCOO\nnew_rhs_shape = (batch_size, *rhs_shape)\nbatched_out = _bcoo_spdot_general(lhs_data, lhs_indices, rhs_data, rhs_indices,\ndimension_numbers=new_dimension_numbers,\n- lhs_spinfo=BCOOInfo(new_lhs_shape),\n- rhs_spinfo=BCOOInfo(new_rhs_shape))\n+ lhs_spinfo=SparseInfo(new_lhs_shape),\n+ rhs_spinfo=SparseInfo(new_rhs_shape))\nreturn batched_out, (result_batch_dim, result_batch_dim)\n@@ -1374,7 +1366,7 @@ def _bcoo_sort_indices_batching_rule(batched_args, batch_dims, *, spinfo):\ndata = data[None, ...]\nif batch_dims[1] is None:\nindices = indices[None, ...]\n- new_spinfo = BCOOInfo(shape=(max(data.shape[0], indices.shape[0]), *spinfo.shape))\n+ new_spinfo = SparseInfo(shape=(max(data.shape[0], indices.shape[0]), *spinfo.shape))\ndata_out, indices_out = bcoo_sort_indices_p.bind(data, indices, spinfo=new_spinfo)\nout_axes = (0, 0)\n# Note: if data is unbatched on input, it will be batched on output.\n@@ -1438,7 +1430,7 @@ def bcoo_sum_duplicates(mat: BCOO, nse: Optional[int] = None) -> BCOO:\nreturn BCOO((data, indices), shape=mat.shape, indices_sorted=True,\nunique_indices=True)\n-def _bcoo_sum_duplicates(data: Array, indices: Array, *, spinfo: BCOOInfo, nse: Optional[int]) -> Tuple[Array, Array]:\n+def _bcoo_sum_duplicates(data: Array, indices: Array, *, spinfo: SparseInfo, nse: Optional[int]) -> Tuple[Array, Array]:\nif nse is not None:\nnse = core.concrete_or_error(operator.index, nse, \"nse argument of bcoo_sum_duplicates.\")\nreturn bcoo_sum_duplicates_p.bind(data, indices, spinfo=spinfo, nse=nse)\n@@ -1514,7 +1506,7 @@ def _bcoo_sum_duplicates_batching_rule(batched_args, batch_dims, *, spinfo, nse)\ndata = data[None, ...]\nif batch_dims[1] is None:\nindices = indices[None, ...]\n- new_spinfo = BCOOInfo(shape=(max(data.shape[0], indices.shape[0]), *spinfo.shape))\n+ new_spinfo = SparseInfo(shape=(max(data.shape[0], indices.shape[0]), *spinfo.shape))\ndata_out, indices_out = bcoo_sum_duplicates_p.bind(data, indices, spinfo=new_spinfo, nse=nse)\nout_axes = (0, 0)\n# Note: if data is unbatched on input, it will be batched on output.\n@@ -1728,7 +1720,7 @@ def bcoo_broadcast_in_dim(mat: BCOO, *, shape: Shape, broadcast_dimensions: Sequ\nbroadcast_dimensions=broadcast_dimensions),\nshape=shape)\n-def _bcoo_broadcast_in_dim(data: Array, indices: Array, *, spinfo: BCOOInfo, shape: Shape,\n+def _bcoo_broadcast_in_dim(data: Array, indices: Array, *, spinfo: SparseInfo, shape: Shape,\nbroadcast_dimensions: Sequence[int]) -> Tuple[Array, Array]:\n\"\"\"BCOO equivalent of lax.broadcast_in_dim\"\"\"\nif len(spinfo.shape) != len(broadcast_dimensions):\n@@ -1999,7 +1991,7 @@ def bcoo_slice(mat: BCOO, *, start_indices: Sequence[int], limit_indices: Sequen\nnew_nse = int(np.prod(new_shape_sparse))\nif mat.nse > new_nse:\nnew_data, new_indices = _bcoo_sum_duplicates(\n- new_data, new_indices, spinfo=BCOOInfo(shape=new_shape), nse=new_nse)\n+ new_data, new_indices, spinfo=SparseInfo(shape=new_shape), nse=new_nse)\nreturn BCOO((new_data, new_indices), shape=new_shape)\n@@ -2079,7 +2071,7 @@ def bcoo_dynamic_slice(mat: BCOO, start_indices: Sequence[Any], slice_sizes: Seq\nif mat.nse > np.prod(size_sparse):\nnew_nse = int(np.prod(size_sparse))\nnew_data, new_indices = _bcoo_sum_duplicates(\n- new_data, new_indices, spinfo=BCOOInfo(shape=new_shape), nse=new_nse)\n+ new_data, new_indices, spinfo=SparseInfo(shape=new_shape), nse=new_nse)\nreturn BCOO((new_data, new_indices), shape=new_shape)\n@@ -2103,7 +2095,7 @@ def bcoo_reduce_sum(mat: BCOO, *, axes: Sequence[int]) -> BCOO:\nmat.data, mat.indices, spinfo=mat._info, axes=axes)\nreturn BCOO((out_data, out_indices), shape=out_shape)\n-def _bcoo_reduce_sum(data: Array, indices: Array, *, spinfo: BCOOInfo, axes: Sequence[int]) -> Tuple[Array, Array, Shape]:\n+def _bcoo_reduce_sum(data: Array, indices: Array, *, spinfo: SparseInfo, axes: Sequence[int]) -> Tuple[Array, Array, Shape]:\nshape = spinfo.shape\nassert all(0 <= a < len(shape) for a in axes)\nn_batch, n_sparse, _, nse = _validate_bcoo(data, indices, shape)\n@@ -2174,7 +2166,7 @@ def bcoo_multiply_sparse(lhs: BCOO, rhs: BCOO) -> BCOO:\nreturn BCOO((out_data, out_indices), shape=out_shape)\ndef _bcoo_multiply_sparse(lhs_data: Array, lhs_indices: Array, rhs_data: Array, rhs_indices: Array, *,\n- lhs_spinfo: BCOOInfo, rhs_spinfo: BCOOInfo) -> Tuple[Array, Array, Shape]:\n+ lhs_spinfo: SparseInfo, rhs_spinfo: SparseInfo) -> Tuple[Array, Array, Shape]:\nlhs_shape = lhs_spinfo.shape\nrhs_shape = rhs_spinfo.shape\n@@ -2238,7 +2230,7 @@ def bcoo_multiply_dense(sp_mat: BCOO, v: Array) -> Array:\n\"\"\"\nreturn _bcoo_multiply_dense(sp_mat.data, sp_mat.indices, v, spinfo=sp_mat._info)\n-def _bcoo_multiply_dense(data: Array, indices: Array, v: Array, *, spinfo: BCOOInfo) -> Array:\n+def _bcoo_multiply_dense(data: Array, indices: Array, v: Array, *, spinfo: SparseInfo) -> Array:\n\"\"\"Broadcasted elementwise multiplication between a BCOO array and a dense array.\"\"\"\n# TODO(jakevdp): the logic here is similar to bcoo_extract... can we reuse that?\nshape = spinfo.shape\n@@ -2388,7 +2380,7 @@ class BCOO(JAXSparse):\nn_dense = property(lambda self: self.data.ndim - 1 - self.n_batch)\nindices_sorted: bool\nunique_indices: bool\n- _info = property(lambda self: BCOOInfo(self.shape, self.indices_sorted,\n+ _info = property(lambda self: SparseInfo(self.shape, self.indices_sorted,\nself.unique_indices))\n_bufs = property(lambda self: (self.data, self.indices))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcsr.py", "new_path": "jax/experimental/sparse/bcsr.py", "diff": "@@ -25,15 +25,13 @@ from jax import core\nfrom jax import tree_util\nfrom jax.experimental.sparse._base import JAXSparse\nfrom jax.experimental.sparse import bcoo\n-from jax.experimental.sparse.util import _broadcasting_vmap, _count_stored_elements, _csr_to_coo\n+from jax.experimental.sparse.util import _broadcasting_vmap, _count_stored_elements, _csr_to_coo, Shape\nimport jax.numpy as jnp\nfrom jax.util import split_list, safe_zip\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax._src.typing import Array, ArrayLike, DTypeLike\n-Shape = Tuple[int, ...]\n-\nclass BCSRProperties(NamedTuple):\nn_batch: int\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/util.py", "new_path": "jax/experimental/sparse/util.py", "diff": "\"\"\"Sparse utilities.\"\"\"\nimport functools\n-from typing import Any, Iterable, Sequence, Tuple, Union\n+from typing import Any, NamedTuple, Tuple, Union\nimport numpy as np\nimport jax\n@@ -40,6 +40,13 @@ class SparseEfficiencyWarning(UserWarning):\nclass CuSparseEfficiencyWarning(SparseEfficiencyWarning):\npass\n+Shape = Tuple[int, ...]\n+\n+class SparseInfo(NamedTuple):\n+ shape: Shape\n+ indices_sorted: bool = False\n+ unique_indices: bool = False\n+\n#--------------------------------------------------------------------\n# utilities\n# TODO: possibly make these primitives, targeting cusparse rountines\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -31,7 +31,6 @@ from jax.experimental import sparse\nfrom jax.experimental.sparse import coo as sparse_coo\nfrom jax.experimental.sparse import bcoo as sparse_bcoo\nfrom jax.experimental.sparse import bcsr as sparse_bcsr\n-from jax.experimental.sparse.bcoo import BCOOInfo\nfrom jax.experimental.sparse import util as sparse_util\nfrom jax.experimental.sparse import test_util as sptu\nfrom jax import lax\n@@ -741,7 +740,7 @@ class BCOOTest(sptu.SparseTestCase):\nassert indices.dtype == jnp.int32 # TODO: test passing this arg\nassert indices.shape == shape[:n_batch] + (nse, n_sparse)\n- todense = partial(sparse_bcoo._bcoo_todense, spinfo=BCOOInfo(shape))\n+ todense = partial(sparse_bcoo._bcoo_todense, spinfo=sparse_util.SparseInfo(shape))\nself.assertArraysEqual(M, todense(data, indices))\nself.assertArraysEqual(M, jit(todense)(data, indices))\n@@ -760,7 +759,7 @@ class BCOOTest(sptu.SparseTestCase):\nn_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)\n- todense = partial(sparse_bcoo._bcoo_todense, indices=indices, spinfo=BCOOInfo(shape))\n+ todense = partial(sparse_bcoo._bcoo_todense, indices=indices, spinfo=sparse_util.SparseInfo(shape))\nj1 = jax.jacfwd(todense)(data)\nj2 = jax.jacrev(todense)(data)\nhess = jax.hessian(todense)(data)\n@@ -827,7 +826,7 @@ class BCOOTest(sptu.SparseTestCase):\nn_dense=n_dense)\nfromdense = partial(sparse_bcoo._bcoo_fromdense, nse=nse, n_dense=n_dense)\n- todense = partial(sparse_bcoo._bcoo_todense, spinfo=BCOOInfo(shape[n_batch:]))\n+ todense = partial(sparse_bcoo._bcoo_todense, spinfo=sparse_util.SparseInfo(shape[n_batch:]))\nfor i in range(n_batch):\nfromdense = jax.vmap(fromdense)\ntodense = jax.vmap(todense)\n@@ -1001,12 +1000,12 @@ class BCOOTest(sptu.SparseTestCase):\nn_dense=n_dense)\ndata, indices = sparse_bcoo._bcoo_fromdense(M, nse=nse, n_batch=n_batch, n_dense=n_dense)\n- M1 = sparse_bcoo._bcoo_todense(data, indices[:1], spinfo=BCOOInfo(M.shape))\n- M2 = sparse_bcoo._bcoo_todense(data, jnp.stack(shape[0] * [indices[0]]), spinfo=BCOOInfo(M.shape))\n+ M1 = sparse_bcoo._bcoo_todense(data, indices[:1], spinfo=sparse_util.SparseInfo(M.shape))\n+ M2 = sparse_bcoo._bcoo_todense(data, jnp.stack(shape[0] * [indices[0]]), spinfo=sparse_util.SparseInfo(M.shape))\nself.assertAllClose(M1, M2)\n- M3 = sparse_bcoo._bcoo_todense(data[:1], indices, spinfo=BCOOInfo(M.shape))\n- M4 = sparse_bcoo._bcoo_todense(jnp.stack(shape[0] * [data[0]]), indices, spinfo=BCOOInfo(M.shape))\n+ M3 = sparse_bcoo._bcoo_todense(data[:1], indices, spinfo=sparse_util.SparseInfo(M.shape))\n+ M4 = sparse_bcoo._bcoo_todense(jnp.stack(shape[0] * [data[0]]), indices, spinfo=sparse_util.SparseInfo(M.shape))\nself.assertAllClose(M3, M4)\n@jtu.sample_product(\n@@ -1271,11 +1270,11 @@ class BCOOTest(sptu.SparseTestCase):\nreturn lax.dot_general(X, Y, dimension_numbers=dimension_numbers)\ndef f_sparse(data, indices, Y):\n- return sparse_bcoo._bcoo_dot_general(data, indices, Y, lhs_spinfo=BCOOInfo(X.shape),\n+ return sparse_bcoo._bcoo_dot_general(data, indices, Y, lhs_spinfo=sparse_util.SparseInfo(X.shape),\ndimension_numbers=dimension_numbers)\nfor data, indices in itertools.product([data, data[:1]], [indices, indices[:1]]):\n- X = sparse_bcoo._bcoo_todense(data, indices, spinfo=BCOOInfo(X.shape))\n+ X = sparse_bcoo._bcoo_todense(data, indices, spinfo=sparse_util.SparseInfo(X.shape))\nself.assertAllClose(f_dense(X, Y), f_sparse(data, indices, Y))\n@jtu.sample_product(\n@@ -1312,7 +1311,7 @@ class BCOOTest(sptu.SparseTestCase):\nreturn lax.dot_general(X, Y, dimension_numbers=dimension_numbers)\ndef f_sparse(Y):\n- return sparse_bcoo._bcoo_dot_general(data, indices, Y, lhs_spinfo=BCOOInfo(X.shape),\n+ return sparse_bcoo._bcoo_dot_general(data, indices, Y, lhs_spinfo=sparse_util.SparseInfo(X.shape),\ndimension_numbers=dimension_numbers)\njf_dense = jax.jacfwd(f_dense)(Y)\n@@ -1329,7 +1328,7 @@ class BCOOTest(sptu.SparseTestCase):\nreturn lax.dot_general(X, Y, dimension_numbers=dimension_numbers)\ndef g_sparse(data):\n- return sparse_bcoo._bcoo_dot_general(data, indices, Y, lhs_spinfo=BCOOInfo(X.shape),\n+ return sparse_bcoo._bcoo_dot_general(data, indices, Y, lhs_spinfo=sparse_util.SparseInfo(X.shape),\ndimension_numbers=dimension_numbers)\njf_dense = jax.jacfwd(g_dense)(X)\n@@ -1487,7 +1486,7 @@ class BCOOTest(sptu.SparseTestCase):\ndata, indices = sparse_bcoo._bcoo_spdot_general(\nxsp.data, xsp.indices, ysp.data, ysp.indices, lhs_spinfo=xsp._info,\nrhs_spinfo=ysp._info, dimension_numbers=dimension_numbers)\n- return sparse_bcoo._bcoo_todense(data, indices, spinfo=BCOOInfo(shape))\n+ return sparse_bcoo._bcoo_todense(data, indices, spinfo=sparse_util.SparseInfo(shape))\ntol = {\"float64\": 1E-14, \"complex128\": 1E-14}\nif should_error:\n@@ -2128,7 +2127,7 @@ class BCOOTest(sptu.SparseTestCase):\ndef make_bcoo(M):\nreturn sparse_bcoo._bcoo_fromdense(M, nse=np.prod(M.shape[:-1], dtype=int), n_dense=1)\n- todense = partial(sparse_bcoo._bcoo_todense, spinfo=BCOOInfo(shape))\n+ todense = partial(sparse_bcoo._bcoo_todense, spinfo=sparse_util.SparseInfo(shape))\nfor _ in range(3):\nmake_bcoo = jax.vmap(make_bcoo)\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Use SparseInfo for both bcoo and bcsr format. PiperOrigin-RevId: 495968517
260,464
16.12.2022 15:05:55
28,800
40ae0d2b58f63776760e07ac3084998991e6d934
Use bfloat16 instead of float16 and add jtu.check_grads
[ { "change_type": "MODIFY", "old_path": "docs/Custom_Operation_for_GPUs.md", "new_path": "docs/Custom_Operation_for_GPUs.md", "diff": "@@ -112,6 +112,7 @@ from functools import partial\nimport jax\nimport jax.numpy as jnp\n+import jax._src.test_util as jtu\nfrom build import gpu_ops\nfrom jax import core, dtypes\nfrom jax.interpreters import xla\n@@ -272,10 +273,10 @@ emb_dim=512\nx = jax.random.normal(\njax.random.PRNGKey(0),\nshape=(jax.local_device_count() * per_core_batch_size, seq_len, emb_dim),\n- dtype=jnp.float16,\n+ dtype=jnp.bfloat16,\n)\nnorm_shape = x.shape[-2:]\n-weight = jnp.ones(norm_shape, dtype=jnp.float16)\n+weight = jnp.ones(norm_shape, dtype=jnp.bfloat16)\n```\n## Test forward function\n@@ -373,7 +374,7 @@ out = rms_norm_fwd(x, weight)\n## Test backward function\n-Now let's test the backward operation using `jax.grad`.\n+Now let's test the backward operation using `jax.grad` and `jtu.check_grads`.\n```python\ndef loss(x, weight):\n@@ -383,6 +384,7 @@ def loss(x, weight):\nloss_grad = jax.grad(loss)\nout = loss_grad(x, weight)\n+jtu.check_grads(loss, (x, weight), modes=[\"rev\"], order=1)\n```\n```python\n---------------------------------------------------------------------------\n@@ -460,6 +462,7 @@ def loss(x, weight):\nloss_grad = jax.grad(loss)\nout = loss_grad(x, weight)\n+jtu.check_grads(loss, (x, weight), modes=[\"rev\"], order=1)\n```\n# Let's test it on multiple devices\n@@ -471,7 +474,6 @@ We are using [`jax.experimental.pjit.pjit`](https://jax.readthedocs.io/en/latest\nLet's first test the forward operation on multiple devices. We are creating a simple 1D mesh and sharding `x` on all devices.\n```python\n-import numpy as np\nfrom jax.experimental.maps import Mesh\nfrom jax.experimental.pjit import PartitionSpec, pjit\n@@ -490,29 +492,29 @@ with mesh:\nprint(pjitted.lower(x, weight).compile().runtime_executable().hlo_modules()[0].to_string())\nout = pjitted(x, weight)\n-np.allclose(ref, out)\n+jnp.allclose(ref, out, atol=1e-2, rtol=1e-2)\n```\n```python\n-HloModule pjit_rms_norm, entry_computation_layout={(f16[4,512,512]{2,1,0},f16[512,512]{1,0})->f16[4,512,512]{2,1,0}}\n+HloModule pjit_rms_norm, entry_computation_layout={(bf16[4,512,512]{2,1,0},bf16[512,512]{1,0})->bf16[4,512,512]{2,1,0}}\n-%fused_computation (param_1: f16[32,512,512], param_1.3: u32[]) -> f16[4,512,512] {\n- %param_1 = f16[32,512,512]{2,1,0} parameter(0)\n+%fused_computation (param_1: bf16[32,512,512], param_1.3: u32[]) -> bf16[4,512,512] {\n+ %param_1 = bf16[32,512,512]{2,1,0} parameter(0)\n%param_1.3 = u32[] parameter(1)\n%convert.2 = s32[] convert(u32[] %param_1.3), metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n%constant_9 = s32[] constant(4), metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n%multiply.3 = s32[] multiply(s32[] %convert.2, s32[] %constant_9), metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n%constant_8 = s32[] constant(0), metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n- ROOT %dynamic-slice.2 = f16[4,512,512]{2,1,0} dynamic-slice(f16[32,512,512]{2,1,0} %param_1, s32[] %multiply.3, s32[] %constant_8, s32[] %constant_8), dynamic_slice_sizes={4,512,512}, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n+ ROOT %dynamic-slice.2 = bf16[4,512,512]{2,1,0} dynamic-slice(bf16[32,512,512]{2,1,0} %param_1, s32[] %multiply.3, s32[] %constant_8, s32[] %constant_8), dynamic_slice_sizes={4,512,512}, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n}\n-ENTRY %main.7_spmd (param: f16[4,512,512], param.1: f16[512,512]) -> f16[4,512,512] {\n- %param = f16[4,512,512]{2,1,0} parameter(0), sharding={devices=[8,1,1]0,1,2,3,4,5,6,7}\n- %all-gather = f16[32,512,512]{2,1,0} all-gather(f16[4,512,512]{2,1,0} %param), channel_id=1, replica_groups={{0,1,2,3,4,5,6,7}}, dimensions={0}, use_global_device_ids=true, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n- %param.1 = f16[512,512]{1,0} parameter(1), sharding={replicated}\n- %custom-call.0 = (f16[32,512,512]{2,1,0}, f32[32]{0}) custom-call(f16[32,512,512]{2,1,0} %all-gather, f16[512,512]{1,0} %param.1), custom_call_target=\"rms_forward_affine_mixed_dtype\", operand_layout_constraints={f16[32,512,512]{2,1,0}, f16[512,512]{1,0}}, api_version=API_VERSION_STATUS_RETURNING, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}, backend_config=\" \\000\\000\\000\\000\\000\\004\\000\\361h\\343\\210\\265\\370\\344>\\001\\000\\000\\000\\001\\000\\000\\000\\000\\000\\000\\000\\206\\177\\000\\000\"\n- %get-tuple-element = f16[32,512,512]{2,1,0} get-tuple-element((f16[32,512,512]{2,1,0}, f32[32]{0}) %custom-call.0), index=0, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n+ENTRY %main.7_spmd (param: bf16[4,512,512], param.1: bf16[512,512]) -> bf16[4,512,512] {\n+ %param = bf16[4,512,512]{2,1,0} parameter(0), sharding={devices=[8,1,1]0,1,2,3,4,5,6,7}\n+ %all-gather = bf16[32,512,512]{2,1,0} all-gather(bf16[4,512,512]{2,1,0} %param), channel_id=1, replica_groups={{0,1,2,3,4,5,6,7}}, dimensions={0}, use_global_device_ids=true, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n+ %param.1 = bf16[512,512]{1,0} parameter(1), sharding={replicated}\n+ %custom-call.0 = (bf16[32,512,512]{2,1,0}, f32[32]{0}) custom-call(bf16[32,512,512]{2,1,0} %all-gather, bf16[512,512]{1,0} %param.1), custom_call_target=\"rms_forward_affine_mixed_dtype\", operand_layout_constraints={bf16[32,512,512]{2,1,0}, bf16[512,512]{1,0}}, api_version=API_VERSION_STATUS_RETURNING, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}, backend_config=\" \\000\\000\\000\\000\\000\\004\\000\\361h\\343\\210\\265\\370\\344>\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\255\\177\\000\\000\"\n+ %get-tuple-element = bf16[32,512,512]{2,1,0} get-tuple-element((bf16[32,512,512]{2,1,0}, f32[32]{0}) %custom-call.0), index=0, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n%partition-id = u32[] partition-id(), metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n- ROOT %fusion = f16[4,512,512]{2,1,0} fusion(f16[32,512,512]{2,1,0} %get-tuple-element, u32[] %partition-id), kind=kLoop, calls=%fused_computation, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n+ ROOT %fusion = bf16[4,512,512]{2,1,0} fusion(bf16[32,512,512]{2,1,0} %get-tuple-element, u32[] %partition-id), kind=kLoop, calls=%fused_computation, metadata={op_name=\"pjit(rms_norm)/jit(main)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n}\n```\n```python\n@@ -570,16 +572,16 @@ with mesh:\nprint(pjitted.lower(x, weight).compile().runtime_executable().hlo_modules()[0].to_string())\nout = pjitted(x, weight)\n-np.allclose(ref, out)\n+jnp.allclose(ref, out, atol=1e-2, rtol=1e-2)\n```\n```python\n-HloModule pjit__unnamed_wrapped_function_, entry_computation_layout={(f16[4,512,512]{2,1,0},f16[512,512]{1,0})->f16[4,512,512]{2,1,0}}\n+HloModule pjit__unnamed_wrapped_function_, entry_computation_layout={(bf16[4,512,512]{2,1,0},bf16[512,512]{1,0})->bf16[4,512,512]{2,1,0}}\n-ENTRY %main.17_spmd (param: f16[4,512,512], param.1: f16[512,512]) -> f16[4,512,512] {\n- %param = f16[4,512,512]{2,1,0} parameter(0), sharding={devices=[8,1,1]0,1,2,3,4,5,6,7}, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/xmap(rms_norm)/squeeze[dimensions=(0,)]\" source_file=\"/tmp/ipykernel_25235/3123505662.py\" source_line=13}\n- %param.1 = f16[512,512]{1,0} parameter(1), sharding={replicated}, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/xmap(rms_norm)/full_to_shard[axes=OrderedDict() mesh=Mesh(device_ids=array([0, 1, 2, 3, 4, 5, 6, 7]), axis_names=(\\'a\\',)) manual_axes=(\\'a\\',)]\" source_file=\"/tmp/ipykernel_25235/3123505662.py\" source_line=13}\n- %custom-call.0 = (f16[4,512,512]{2,1,0}, f32[4]{0}) custom-call(f16[4,512,512]{2,1,0} %param, f16[512,512]{1,0} %param.1), custom_call_target=\"rms_forward_affine_mixed_dtype\", operand_layout_constraints={f16[4,512,512]{2,1,0}, f16[512,512]{1,0}}, api_version=API_VERSION_STATUS_RETURNING, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/xmap(rms_norm)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}, backend_config=\"\\004\\000\\000\\000\\000\\000\\004\\000\\361h\\343\\210\\265\\370\\344>\\001\\000\\000\\000\\001\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\"\n- ROOT %get-tuple-element = f16[4,512,512]{2,1,0} get-tuple-element((f16[4,512,512]{2,1,0}, f32[4]{0}) %custom-call.0), index=0, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/xmap(rms_norm)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n+ENTRY %main.17_spmd (param: bf16[4,512,512], param.1: bf16[512,512]) -> bf16[4,512,512] {\n+ %param = bf16[4,512,512]{2,1,0} parameter(0), sharding={devices=[8,1,1]0,1,2,3,4,5,6,7}, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/xmap(rms_norm)/squeeze[dimensions=(0,)]\" source_file=\"/tmp/ipykernel_25235/3123505662.py\" source_line=13}\n+ %param.1 = bf16[512,512]{1,0} parameter(1), sharding={replicated}, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/xmap(rms_norm)/full_to_shard[axes=OrderedDict() mesh=Mesh(device_ids=array([0, 1, 2, 3, 4, 5, 6, 7]), axis_names=(\\'x\\',)) manual_axes=(\\'x\\',)]\" source_file=\"/tmp/ipykernel_25235/3123505662.py\" source_line=13}\n+ %custom-call.0 = (bf16[4,512,512]{2,1,0}, f32[4]{0}) custom-call(bf16[4,512,512]{2,1,0} %param, bf16[512,512]{1,0} %param.1), custom_call_target=\"rms_forward_affine_mixed_dtype\", operand_layout_constraints={bf16[4,512,512]{2,1,0}, bf16[512,512]{1,0}}, api_version=API_VERSION_STATUS_RETURNING, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/xmap(rms_norm)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}, backend_config=\"\\004\\000\\000\\000\\000\\000\\004\\000\\361h\\343\\210\\265\\370\\344>\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\027\\177\\000\\000\"\n+ ROOT %get-tuple-element = bf16[4,512,512]{2,1,0} get-tuple-element((bf16[4,512,512]{2,1,0}, f32[4]{0}) %custom-call.0), index=0, metadata={op_name=\"pjit(<unnamed wrapped function>)/jit(main)/xmap(rms_norm)/rms_norm_fwd[eps=1e-05]\" source_file=\"/tmp/ipykernel_25235/3343076723.py\" source_line=8}\n}\n```\n```python\n@@ -629,7 +631,7 @@ with mesh:\nout = pjitted(x, weight)\nfor r, o in zip(ref, out):\n- print(np.allclose(r, o))\n+ print(jnp.allclose(r, o, atol=1e-2, rtol=1e-2))\n```\n```python\nTrue\n@@ -644,21 +646,21 @@ with mesh:\nprint(jax.make_jaxpr(pjitted)(x, weight))\n```\n```python\n-{ lambda ; a:f16[32,512,512] b:f16[512,512]. let\n- c:f16[32,512,512] d:f16[512,512] = pjit[\n+{ lambda ; a:bf16[32,512,512] b:bf16[512,512]. let\n+ c:bf16[32,512,512] d:bf16[512,512] = pjit[\ndonated_invars=(False, False)\nin_positional_semantics=(<_PositionalSemantics.GLOBAL: 1>, <_PositionalSemantics.GLOBAL: 1>)\nin_shardings=(OpShardingSharding({devices=[8,1,1]0,1,2,3,4,5,6,7}), OpShardingSharding({replicated}))\n- jaxpr={ lambda ; e:f16[32,512,512] f:f16[512,512]. let\n- g:f16[8,4,512,512] = reshape[\n+ jaxpr={ lambda ; e:bf16[32,512,512] f:bf16[512,512]. let\n+ g:bf16[8,4,512,512] = reshape[\ndimensions=None\nnew_sizes=(8, 4, 512, 512)\n] e\n- h:f16[8,4,512,512] i:f32[8,4] j:f16[8,4,512,512] k:f16[512,512] = xmap[\n+ h:bf16[8,4,512,512] i:f32[8,4] j:bf16[8,4,512,512] k:bf16[512,512] = xmap[\naxis_resources=FrozenDict({'x': ('x',)})\nbackend=None\n- call_jaxpr={ lambda ; l:f16[4,512,512;a:8] m:f16[512,512]. let\n- n:f16[4,512,512;a:8] o:f32[4;a:8] = rms_norm_fwd[eps=1e-05] l m\n+ call_jaxpr={ lambda ; l:bf16[4,512,512;x:8] m:bf16[512,512]. let\n+ n:bf16[4,512,512;x:8] o:f32[4;x:8] = rms_norm_fwd[eps=1e-05] l m\nin (n, o, l, m) }\ndonated_invars=(False, False)\nglobal_axis_sizes=FrozenDict({'x': 8})\n@@ -671,43 +673,43 @@ with mesh:\nspmd_in_axes=None\nspmd_out_axes=None\n] g f\n- p:f16[32,512,512] = reshape[dimensions=None new_sizes=(32, 512, 512)] h\n- q:f16[32,512,512] = integer_pow[y=2] p\n- r:f16[32,512,512] = integer_pow[y=1] p\n- s:f16[32,512,512] = mul 2.0 r\n+ p:bf16[32,512,512] = reshape[dimensions=None new_sizes=(32, 512, 512)] h\n+ q:bf16[32,512,512] = integer_pow[y=2] p\n+ r:bf16[32,512,512] = integer_pow[y=1] p\n+ s:bf16[32,512,512] = mul 2 r\nt:f32[32,512,512] = convert_element_type[\nnew_dtype=float32\nweak_type=False\n] q\nu:f32[] = reduce_sum[axes=(0, 1, 2)] t\n- v:f16[] = convert_element_type[new_dtype=float16 weak_type=False] u\n- w:f16[] = div v inf\n- _:f16[] = neg w\n- x:f16[] = neg 1.0\n- y:f16[] = div x inf\n+ v:bf16[] = convert_element_type[new_dtype=bfloat16 weak_type=False] u\n+ w:bf16[] = div v 8.38861e+06\n+ _:bf16[] = neg w\n+ x:bf16[] = neg 1\n+ y:bf16[] = div x 8.38861e+06\nz:f32[] = convert_element_type[new_dtype=float32 weak_type=False] y\nba:f32[32,512,512] = broadcast_in_dim[\nbroadcast_dimensions=()\nshape=(32, 512, 512)\n] z\n- bb:f16[32,512,512] = convert_element_type[\n- new_dtype=float16\n+ bb:bf16[32,512,512] = convert_element_type[\n+ new_dtype=bfloat16\nweak_type=False\n] ba\n- bc:f16[32,512,512] = mul bb s\n- bd:f16[8,4,512,512] = reshape[\n+ bc:bf16[32,512,512] = mul bb s\n+ bd:bf16[8,4,512,512] = reshape[\ndimensions=None\nnew_sizes=(8, 4, 512, 512)\n] bc\n- be:f16[8,4,512,512] bf:f16[512,512] = xmap[\n+ be:bf16[8,4,512,512] bf:bf16[512,512] = xmap[\naxis_resources=FrozenDict({'x': ('x',)})\nbackend=None\n- call_jaxpr={ lambda ; bg:f32[4;a:8] bh:f16[4,512,512;a:8] bi:f16[512,512]\n- bj:f16[4,512,512;a:8]. let\n- bk:f16[4,512,512;a:8] bl:f16[512,512;a:8] _:f32[16,262144;a:8] = rms_norm_bwd[\n+ call_jaxpr={ lambda ; bg:f32[4;x:8] bh:bf16[4,512,512;x:8] bi:bf16[512,512]\n+ bj:bf16[4,512,512;x:8]. let\n+ bk:bf16[4,512,512;x:8] bl:bf16[512,512;x:8] _:f32[16,262144;x:8] = rms_norm_bwd[\neps=1e-05\n] bj bg bh bi\n- bm:f16[512,512] = psum[axes=('x',) axis_index_groups=None] bl\n+ bm:bf16[512,512] = psum[axes=('x',) axis_index_groups=None] bl\nin (bk, bm) }\ndonated_invars=(False, False, False, False)\nglobal_axis_sizes=FrozenDict({'x': 8})\n@@ -720,7 +722,10 @@ with mesh:\nspmd_in_axes=None\nspmd_out_axes=None\n] i j k bd\n- bn:f16[32,512,512] = reshape[dimensions=None new_sizes=(32, 512, 512)] be\n+ bn:bf16[32,512,512] = reshape[\n+ dimensions=None\n+ new_sizes=(32, 512, 512)\n+ ] be\nin (bn, bf) }\nname=<unnamed function>\nout_positional_semantics=_PositionalSemantics.GLOBAL\n@@ -730,7 +735,7 @@ with mesh:\nin (c, d) }\n```\n-We see that `bm:f16[512,512] = psum[axes=('x',) axis_index_groups=None] bl` has been added after the call to `rms_norm_bwd` to reduce `grad_weight` across the devices on the axis `\"x\"`, but there is no `psum` for `grad_input`.\n+We see that `bm:bf16[512,512] = psum[axes=('x',) axis_index_groups=None] bl` has been added after the call to `rms_norm_bwd` to reduce `grad_weight` across the devices on the axis `\"x\"`, but there is no `psum` for `grad_input`.\nThis is controlled by `named_shape` passed to the `ShapedArray` construction in abstract evaluation and the axes given to `xmap`.\n@@ -1004,7 +1009,6 @@ def xmap_rms_norm(x, weight, *, device_count):\nimport jax\n-import numpy as np\nper_core_batch_size=4\n@@ -1013,10 +1017,10 @@ emb_dim=512\nx = jax.random.normal(\njax.random.PRNGKey(0),\nshape=(jax.local_device_count() * per_core_batch_size, seq_len, emb_dim),\n- dtype=jnp.float16,\n+ dtype=jnp.bfloat16,\n)\nnorm_shape = x.shape[-2:]\n-weight = jnp.ones(norm_shape, dtype=jnp.float16)\n+weight = jnp.ones(norm_shape, dtype=jnp.bfloat16)\ndef loss_ref(x, weight):\n@@ -1050,7 +1054,7 @@ with Mesh(jax.local_devices(), (\"x\",)):\nout = pjitted(x, weight)\nfor r, o in zip(ref, out):\n- print(np.allclose(r, o))\n+ print(jnp.allclose(r, o, atol=1e-2, rtol=1e-2))\n```\n```python\nTrue\n" } ]
Python
Apache License 2.0
google/jax
Use bfloat16 instead of float16 and add jtu.check_grads
260,464
16.12.2022 17:06:43
28,800
4a63488825f39bf4b5a198370f854e2803385b50
Add a hyperlink to jax.numpy`
[ { "change_type": "MODIFY", "old_path": "docs/Custom_Operation_for_GPUs.md", "new_path": "docs/Custom_Operation_for_GPUs.md", "diff": "@@ -8,11 +8,11 @@ This tutorial contains information from [Extending JAX with custom C++ and CUDA\n# RMS Normalization\nFor this tutorial, we are going to add the RMS normalization as a custom operation in JAX.\n-Although the RMS normalization can be expressed with `jax.numpy` directly, we are using it as an example to show the process of creating a custom operation for GPUs.\n-The CUDA code in `rms_norm_kernels.cu` for this operation has been borrowed from <https://github.com/NVIDIA/apex/blob/master/csrc/layer_norm_cuda_kernel.cu> and adapted to eliminate any dependency on PyTorch.\n+It is to be noted that the RMS normalization can be expressed with [`jax.numpy`](https://jax.readthedocs.io/en/latest/jax.numpy.html) directly, however, we are using it as an example to show the process of creating a custom operation for GPUs.\n+The CUDA code in `gpu_ops/rms_norm_kernels.cu` for this operation has been borrowed from <https://github.com/NVIDIA/apex/blob/master/csrc/layer_norm_cuda_kernel.cu> and adapted to eliminate any dependency on PyTorch.\nSee [`gpu_ops` code listing](#gpu_ops-code-listing) for complete code listing of C++ and CUDA files.\n-`rms_norm_kernels.cu` defines the following functions, which are declared with the XLA custom function signature.\n+`gpu_ops/rms_norm_kernels.cu` defines the following functions, which are declared with the XLA custom function signature.\nThese functions are responsible for launching RMS normalization kernels with the given `buffers` on the specified `stream`.\n```cpp\n" } ]
Python
Apache License 2.0
google/jax
Add a hyperlink to jax.numpy`
260,411
17.12.2022 22:43:58
-7,200
63a9e71b4e7cacbca71a490fcc53eff527bd3a35
[jax2tf] Update the select_and_gather_add lowering for dynamic shapes This enables lowering of select_and_gather_add for GPU when we have dynamic shapes. The main change is to carry the abstract values and to use them for broadcast, using mlir.broadcast_in_dim, which can general BroadcastInDimOp or DynamicBroadcastInDimOp. This requires some passing around of abstract values.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/windowed_reductions.py", "new_path": "jax/_src/lax/windowed_reductions.py", "diff": "@@ -654,7 +654,8 @@ def _select_and_gather_add_shape_rule(\nwindow_dilation)\ndef _select_and_gather_add_lowering(\n- ctx, tangents, operand, *, select_prim,\n+ ctx: mlir.LoweringRuleContext,\n+ tangents, operand, *, select_prim,\nwindow_dimensions, window_strides, padding, base_dilation, window_dilation,\nmax_bits=64):\n_, operand_aval, = ctx.avals_in\n@@ -669,8 +670,10 @@ def _select_and_gather_add_lowering(\nconst = lambda dtype, x: mlir.ir_constant(np.array(x, dtype=dtype),\ncanonicalize_types=False)\n- def _broadcast(x, dims):\n- return hlo.BroadcastOp(x, mlir.dense_int_elements(dims))\n+ def _broadcast_scalar_const(x, aval_out):\n+ return mlir.broadcast_in_dim(ctx, const(aval_out.dtype, x),\n+ aval_out,\n+ broadcast_dimensions=())\nif double_word_reduction:\n# TODO(b/73062247): XLA doesn't yet implement ReduceWindow on tuples, so\n@@ -678,35 +681,33 @@ def _select_and_gather_add_lowering(\n# 2k-bit unsigned integer using bit tricks.\nword_dtype = lax._UINT_DTYPES[nbits]\ndouble_word_dtype = lax._UINT_DTYPES[nbits * 2]\n- word_type = mlir.dtype_to_ir_type(word_dtype)\n- double_word_type = mlir.dtype_to_ir_type(double_word_dtype)\n-\n- # Packs two values into a tuple.\n- def pack(a, b):\n- a_dims = ir.RankedTensorType(a.type).shape\n- b_dims = ir.RankedTensorType(b.type).shape\n- a = hlo.BitcastConvertOp(ir.RankedTensorType.get(a_dims, word_type), a)\n- b = hlo.BitcastConvertOp(ir.RankedTensorType.get(b_dims, word_type), b)\n- a = hlo.ConvertOp(ir.RankedTensorType.get(a_dims, double_word_type), a)\n- b = hlo.ConvertOp(ir.RankedTensorType.get(b_dims, double_word_type), b)\n+ word_type = mlir.dtype_to_ir_type(word_dtype) # type: ignore\n+ double_word_type = mlir.dtype_to_ir_type(double_word_dtype) # type: ignore\n+ # Packs two values into a double_word_type.\n+ def pack(a, b, ab_aval):\n+ word_type_ab_aval = ab_aval.update(dtype=word_dtype)\n+ double_word_type_ab_aval = ab_aval.update(dtype=double_word_dtype)\n+ a = hlo.BitcastConvertOp(mlir.aval_to_ir_type(word_type_ab_aval), a)\n+ b = hlo.BitcastConvertOp(mlir.aval_to_ir_type(word_type_ab_aval), b)\n+ a = hlo.ConvertOp(mlir.aval_to_ir_type(double_word_type_ab_aval), a)\n+ b = hlo.ConvertOp(mlir.aval_to_ir_type(double_word_type_ab_aval), b)\na = hlo.ShiftLeftOp(a,\n- _broadcast(const(double_word_dtype, nbits), a_dims))\n+ _broadcast_scalar_const(nbits, double_word_type_ab_aval))\nreturn hlo.OrOp(a, b)\n- # Unpacks the first element of a tuple.\n+ # Unpacks the first element of a double_word_type.\ndef fst(t):\n- dims = ir.RankedTensorType(t.type).shape\n+ assert not ir.RankedTensorType(t.type).shape\nst = hlo.ShiftRightLogicalOp(t, const(double_word_dtype, nbits))\nreturn hlo.BitcastConvertOp(\n- ir.RankedTensorType.get(dims, etype),\n- hlo.ConvertOp(ir.RankedTensorType.get(dims, word_type), st)).result\n+ ir.RankedTensorType.get([], etype),\n+ hlo.ConvertOp(ir.RankedTensorType.get([], word_type), st)).result\n- # Unpacks the second element of a tuple.\n- def snd(t):\n- dims = ir.RankedTensorType(t.type).shape\n+ # Unpacks the second element of a double_word_type.\n+ def snd(t, t_aval):\nreturn hlo.BitcastConvertOp(\n- ir.RankedTensorType.get(dims, etype),\n- hlo.ConvertOp(ir.RankedTensorType.get(dims, word_type), t)).result\n+ mlir.aval_to_ir_type(t_aval.update(dtype=dtype)),\n+ hlo.ConvertOp(mlir.aval_to_ir_type(t_aval.update(dtype=word_dtype)), t)).result\nelse:\n# The double-word trick above only works if we have a sufficiently large\n@@ -723,42 +724,42 @@ def _select_and_gather_add_lowering(\nnmant = r_nbits - nexp - 1\ndouble_word_dtype = word_dtype = lax._UINT_DTYPES[nbits]\n- double_word_type = word_type = mlir.dtype_to_ir_type(word_dtype)\n+ double_word_type = word_type = mlir.dtype_to_ir_type(word_dtype) # type: ignore\n- # Packs two values into a tuple.\n- def pack(a, b):\n- a_dims = ir.RankedTensorType(a.type).shape\n- b_dims = ir.RankedTensorType(b.type).shape\n+ # Packs two values into a double_word_type.\n+ def pack(a, b, ab_aval):\n+ word_type_ab_aval = ab_aval.update(dtype=word_dtype)\na = hlo.ReducePrecisionOp(a, exponent_bits=mlir.i32_attr(nexp),\nmantissa_bits=mlir.i32_attr(nmant))\nb = hlo.ReducePrecisionOp(b, exponent_bits=mlir.i32_attr(nexp),\nmantissa_bits=mlir.i32_attr(nmant))\n- a = hlo.BitcastConvertOp(ir.RankedTensorType.get(a_dims, word_type), a)\n- b = hlo.BitcastConvertOp(ir.RankedTensorType.get(b_dims, word_type), b)\n+ a = hlo.BitcastConvertOp(mlir.aval_to_ir_type(word_type_ab_aval), a)\n+ b = hlo.BitcastConvertOp(mlir.aval_to_ir_type(word_type_ab_aval), b)\nb = hlo.ShiftRightLogicalOp(\n- b, _broadcast(const(word_dtype, r_nbits), b_dims))\n+ b, _broadcast_scalar_const(r_nbits, word_type_ab_aval))\nreturn hlo.OrOp(a, b)\n- # Unpacks the first element of a tuple.\n+ # Unpacks the first element of a double_word_type.\ndef fst(t):\n+ assert not ir.RankedTensorType(t.type).shape\nst = hlo.AndOp(t, const(word_dtype, ((1 << r_nbits) - 1) << r_nbits))\nreturn hlo.BitcastConvertOp(ir.RankedTensorType.get([], etype),\nst).result\n- # Unpacks the second element of a tuple.\n- def snd(t):\n- dims = ir.RankedTensorType(t.type).shape\n+ # Unpacks the second element of a double_word_type.\n+ def snd(t, t_aval):\nreturn hlo.BitcastConvertOp(\n- ir.RankedTensorType.get(dims, etype),\n- hlo.ShiftLeftOp(t, _broadcast(const(word_dtype, r_nbits), dims))\n+ mlir.aval_to_ir_type(t_aval.update(dtype=dtype)),\n+ hlo.ShiftLeftOp(t, _broadcast_scalar_const(r_nbits, t_aval.update(dtype=word_dtype)))\n).result\nassert select_prim is lax.ge_p or select_prim is lax.le_p, select_prim\ninit = -np.inf if select_prim is lax.ge_p else np.inf\n+ double_word_out_aval = out_aval.update(dtype=double_word_dtype)\nrw = hlo.ReduceWindowOp(\n- [ir.RankedTensorType.get(out_aval.shape, double_word_type)],\n- pack(operand, tangents),\n- pack(const(dtype, init), const(dtype, 0)),\n+ [mlir.aval_to_ir_type(double_word_out_aval)],\n+ pack(operand, tangents, operand_aval),\n+ pack(const(dtype, init), const(dtype, 0), core.ShapedArray((), dtype)),\nmlir.dense_int_elements(window_dimensions),\nwindow_strides=mlir.dense_int_elements(window_strides),\nbase_dilations=mlir.dense_int_elements(base_dilation),\n@@ -770,10 +771,10 @@ def _select_and_gather_add_lowering(\nwith ir.InsertionPoint(reducer):\nx, y = reducer.arguments\nassert select_prim is lax.ge_p or select_prim is lax.le_p\n- which = \"GE\" if select_prim is lax.ge_p else \"LE\"\n- out = hlo.SelectOp(mlir.compare_hlo(fst(x), fst(y), which), x, y)\n+ cmp_op = \"GE\" if select_prim is lax.ge_p else \"LE\"\n+ out = hlo.SelectOp(mlir.compare_hlo(fst(x), fst(y), cmp_op), x, y)\nhlo.ReturnOp(out)\n- return [snd(rw.result)]\n+ return [snd(rw.result, double_word_out_aval)]\n# TODO(phawkins): use this translation rule on all platforms.\ndef _select_and_gather_add_using_variadic_reducewindow(\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Update the select_and_gather_add lowering for dynamic shapes This enables lowering of select_and_gather_add for GPU when we have dynamic shapes. The main change is to carry the abstract values and to use them for broadcast, using mlir.broadcast_in_dim, which can general BroadcastInDimOp or DynamicBroadcastInDimOp. This requires some passing around of abstract values.
260,294
19.12.2022 21:05:17
0
3391a5e3850a2aed8e189c04fe0624fcb0f9f301
[ROCm]: Disable some tests on ROCm platform
[ { "change_type": "MODIFY", "old_path": "tests/experimental_rnn_test.py", "new_path": "tests/experimental_rnn_test.py", "diff": "@@ -33,7 +33,7 @@ class RnnTest(jtu.JaxTestCase):\nnum_layers=[1, 4],\nbidirectional=[True, False],\n)\n- @jtu.skip_on_devices(\"cpu\", \"tpu\")\n+ @jtu.skip_on_devices(\"cpu\", \"tpu\",\"rocm\")\ndef test_lstm(self, batch_size: int, seq_len: int, input_size: int,\nhidden_size: int, num_layers: int, bidirectional: bool):\nbatch_size = 6\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -337,6 +337,7 @@ class NumpyLinalgTest(jtu.JaxTestCase):\ndtype=float_types + complex_types,\nlower=[True, False],\n)\n+ @jtu.skip_on_devices(\"rocm\")\ndef testEighIdentity(self, n, dtype, lower):\ntol = 1e-3\nuplo = \"L\" if lower else \"U\"\n@@ -1337,7 +1338,7 @@ class ScipyLinalgTest(jtu.JaxTestCase):\ndtype=float_types + complex_types,\nlower=[False, True],\n)\n- @jtu.skip_on_devices(\"tpu\")\n+ @jtu.skip_on_devices(\"tpu\",\"rocm\")\ndef testTridiagonal(self, shape, dtype, lower):\nrng = jtu.rand_default(self.rng())\ndef jax_func(a):\n@@ -1594,6 +1595,7 @@ class ScipyLinalgTest(jtu.JaxTestCase):\n@jtu.sample_product(\nshape=[(), (3,), (1, 4), (1, 5, 9), (11, 0, 13)],\ndtype=float_types + complex_types + int_types)\n+ @jtu.skip_on_devices(\"rocm\")\ndef testToeplitzSymmetricConstruction(self, shape, dtype):\nif (dtype in [np.float64, np.complex128]\nand not config.x64_enabled):\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -861,7 +861,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nalpha=[np.array([0.2, 1., 5.]),],\ndtype=jtu.dtypes.floating,\n)\n- @jtu.skip_on_devices(\"tpu\") # TODO(mattjj): slow compilation times\n+ @jtu.skip_on_devices(\"tpu\",\"rocm\") # TODO(mattjj): slow compilation times\ndef testDirichlet(self, alpha, dtype):\nkey = self.seed_prng(0)\nrand = lambda key, alpha: random.dirichlet(key, alpha, (10000,), dtype)\n@@ -876,6 +876,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor i, a in enumerate(alpha):\nself._CheckKolmogorovSmirnovCDF(samples[..., i], scipy.stats.beta(a, alpha_sum - a).cdf)\n+ @jtu.skip_on_devices(\"rocm\")\ndef testDirichletSmallAlpha(self, dtype=np.float32):\n# Regression test for https://github.com/google/jax/issues/9896\nkey = self.seed_prng(0)\n" } ]
Python
Apache License 2.0
google/jax
[ROCm]: Disable some tests on ROCm platform
260,447
19.12.2022 14:16:50
28,800
bc34af9f30e03ac34b7424dd979b35107ae11190
[sparse] Add bcsr dot_general
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/__init__.py", "new_path": "jax/experimental/sparse/__init__.py", "diff": "@@ -223,6 +223,8 @@ from jax.experimental.sparse.bcoo import (\n)\nfrom jax.experimental.sparse.bcsr import (\n+ bcsr_dot_general as bcsr_dot_general,\n+ bcsr_dot_general_p as bcsr_dot_general_p,\nbcsr_extract as bcsr_extract,\nbcsr_extract_p as bcsr_extract_p,\nbcsr_fromdense as bcsr_fromdense,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcsr.py", "new_path": "jax/experimental/sparse/bcsr.py", "diff": "@@ -17,17 +17,24 @@ from __future__ import annotations\nimport operator\n-from typing import NamedTuple, Optional, Sequence, Tuple\n+from typing import NamedTuple, Optional, Sequence, Tuple, Union\nimport numpy as np\nfrom jax import core\n+from jax import lax\nfrom jax import tree_util\nfrom jax.experimental.sparse._base import JAXSparse\nfrom jax.experimental.sparse import bcoo\n-from jax.experimental.sparse.util import _broadcasting_vmap, _count_stored_elements, _csr_to_coo, Shape\n+from jax.experimental.sparse.util import (\n+ _broadcasting_vmap, _count_stored_elements,\n+ _csr_to_coo, _dot_general_validated_shape,\n+ SparseInfo, Shape)\nimport jax.numpy as jnp\n+from jax._src import api_util\n+from jax._src.lax.lax import DotDimensionNumbers\nfrom jax.util import split_list, safe_zip\n+from jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax._src.typing import Array, ArrayLike, DTypeLike\n@@ -297,6 +304,150 @@ mlir.register_lowering(bcsr_extract_p, mlir.lower_fun(\n_bcsr_extract_impl, multiple_results=False))\n+#----------------------------------------------------------------------\n+# bcsr_dot_general\n+\n+\n+bcsr_dot_general_p = core.Primitive('bcsr_dot_general')\n+\n+\n+def bcsr_dot_general(lhs: Union[BCSR, Array], rhs: Array, *,\n+ dimension_numbers: DotDimensionNumbers,\n+ precision: None = None,\n+ preferred_element_type: None = None) -> Array:\n+ \"\"\"A general contraction operation.\n+\n+ Args:\n+ lhs: An ndarray or BCSR-format sparse array.\n+ rhs: An ndarray or BCSR-format sparse array..\n+ dimension_numbers: a tuple of tuples of the form\n+ `((lhs_contracting_dims, rhs_contracting_dims),\n+ (lhs_batch_dims, rhs_batch_dims))`.\n+ precision: unused\n+ preferred_element_type: unused\n+\n+ Returns:\n+ An ndarray or BCSR-format sparse array containing the result. If both inputs\n+ are sparse, the result will be sparse, of type BCSR. If either input is\n+ dense, the result will be dense, of type ndarray.\n+ \"\"\"\n+ del precision, preferred_element_type # unused\n+ if isinstance(rhs, (np.ndarray, jnp.ndarray)):\n+ if isinstance(lhs, (np.ndarray, jnp.ndarray)):\n+ return lax.dot_general(lhs, rhs, dimension_numbers=dimension_numbers)\n+\n+ if isinstance(lhs, BCSR):\n+ lhs_data, lhs_indices, lhs_indptr = lhs._bufs\n+ return _bcsr_dot_general(lhs_data, lhs_indices, lhs_indptr, rhs,\n+ dimension_numbers=dimension_numbers,\n+ lhs_spinfo=lhs._info)\n+\n+ raise NotImplementedError(\"bcsr_dot_general currently implemented for BCSR \"\n+ \"lhs and ndarray rhs.\")\n+\n+\n+def _bcsr_dot_general(lhs_data: jnp.ndarray, lhs_indices: jnp.ndarray,\n+ lhs_indptr: jnp.ndarray, rhs: Array, *,\n+ dimension_numbers: DotDimensionNumbers,\n+ lhs_spinfo: SparseInfo) -> Array:\n+ (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n+ cdims = (api_util._ensure_index_tuple(lhs_contract),\n+ api_util._ensure_index_tuple(rhs_contract))\n+ bdims = (api_util._ensure_index_tuple(lhs_batch),\n+ api_util._ensure_index_tuple(rhs_batch))\n+ return bcsr_dot_general_p.bind(jnp.asarray(lhs_data),\n+ jnp.asarray(lhs_indices),\n+ jnp.asarray(lhs_indptr), jnp.asarray(rhs),\n+ dimension_numbers=(cdims, bdims),\n+ lhs_spinfo=lhs_spinfo)\n+\n+\n+@bcsr_dot_general_p.def_impl\n+def _bcsr_dot_general_impl(lhs_data, lhs_indices, lhs_indptr, rhs, *,\n+ dimension_numbers, lhs_spinfo):\n+ lhs_data = jnp.asarray(lhs_data)\n+ lhs_bcsr_indices = jnp.asarray(lhs_indices)\n+ lhs_bcsr_indptr = jnp.asarray(lhs_indptr)\n+ rhs = jnp.asarray(rhs)\n+ lhs_bcoo_indices = _bcsr_to_bcoo(lhs_bcsr_indices, lhs_bcsr_indptr,\n+ shape=lhs_spinfo.shape)\n+ return bcoo._bcoo_dot_general_impl(lhs_data, lhs_bcoo_indices, rhs,\n+ dimension_numbers=dimension_numbers,\n+ lhs_spinfo=lhs_spinfo)\n+\n+\n+@bcsr_dot_general_p.def_abstract_eval\n+def _bcsr_dot_general_abstract_eval(lhs_data, lhs_indices, lhs_indptr, rhs, *,\n+ dimension_numbers, lhs_spinfo):\n+ if lhs_data.dtype != rhs.dtype:\n+ raise ValueError(\"bcsr_dot_general requires arguments to have matching \"\n+ f\"dtypes; got lhs.dtype={lhs_data.dtype}, \"\n+ f\"rhs.dtype={rhs.dtype}\")\n+\n+ (lhs_contracting, _), (lhs_batch, _) = dimension_numbers\n+ props = _validate_bcsr_indices(lhs_indices, lhs_indptr, lhs_spinfo.shape)\n+ out_shape = _dot_general_validated_shape(lhs_spinfo.shape, rhs.shape,\n+ dimension_numbers)\n+\n+ if lhs_batch and max(lhs_batch) >= props.n_batch:\n+ raise NotImplementedError(\n+ \"bcsr_dot_general batch dimensions must be among the batch dimensions in the sparse representtaion.\\n\"\n+ f\"got {lhs_batch=}, {props.n_batch=}\")\n+\n+ # TODO: support contraction of dense dimensions?\n+ if any(d >= props.n_batch + 2 for d in lhs_contracting):\n+ raise NotImplementedError(\"bcsr_dot_general: contracting over dense dimensions.\")\n+\n+ return core.ShapedArray(out_shape, lhs_data.dtype)\n+\n+\n+# def _bcsr_dot_general_jvp_lhs(lhs_data_dot, lhs_data, lhs_indices, lhs_indptr,\n+# rhs, *, dimension_numbers, lhs_spinfo):\n+# del lhs_data\n+# return _bcsr_dot_general(lhs_data_dot, lhs_indices, lhs_indptr, rhs,\n+# dimension_numbers=dimension_numbers,\n+# lhs_spinfo=lhs_spinfo)\n+\n+\n+# def _bcsr_dot_general_jvp_rhs(rhs_dot, lhs_data, lhs_indices, lhs_indptr, rhs,\n+# *, dimension_numbers, lhs_spinfo):\n+# del rhs\n+# return _bcsr_dot_general(lhs_data, lhs_indices, lhs_indptr, rhs_dot,\n+# dimension_numbers=dimension_numbers,\n+# lhs_spinfo=lhs_spinfo)\n+\n+\n+# def _bcsr_dot_general_transpose(ct, lhs_data, lhs_indices, lhs_inptr, rhs, *,\n+# dimension_numbers, lhs_spinfo):\n+# lhs_bcoo_indices = _bcsr_to_bcoo(\n+# lhs_indices, lhs_inptr, shape=lhs_spinfo.shape)\n+# return bcoo._bcoo_dot_general_transpose(\n+# ct, lhs_data, lhs_bcoo_indices, rhs, dimension_numbers=dimension_numbers,\n+# lhs_spinfo=lhs_spinfo)\n+\n+\n+# def _bcsr_dot_general_batch_rule(batched_args, batch_dims, *,\n+# dimension_numbers, lhs_spinfo):\n+# lhs_data, lhs_indices, lhs_indptr, rhs = batched_args\n+# lhs_bcoo_indices = _bcsr_to_bcoo(\n+# lhs_indices, lhs_indptr, shape=lhs_spinfo.shape)\n+# return bcoo._bcoo_dot_general_batch_rule(\n+# (lhs_data, lhs_bcoo_indices, rhs), batch_dims,\n+# dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n+\n+\n+# ad.defjvp(bcsr_dot_general_p, _bcsr_dot_general_jvp_lhs, None,\n+# _bcsr_dot_general_jvp_rhs)\n+# ad.primitive_transposes[bcsr_dot_general_p] = _bcsr_dot_general_transpose\n+# batching.primitive_batchers[bcsr_dot_general_p] = _bcsr_dot_general_batch_rule\n+\n+\n+_bcsr_dot_general_default_lowering = mlir.lower_fun(\n+ _bcsr_dot_general_impl, multiple_results=False)\n+mlir.register_lowering(\n+ bcsr_dot_general_p, _bcsr_dot_general_default_lowering)\n+\n+\n@tree_util.register_pytree_node_class\nclass BCSR(JAXSparse):\n\"\"\"Experimental batched CSR matrix implemented in JAX.\"\"\"\n@@ -310,6 +461,8 @@ class BCSR(JAXSparse):\nn_batch = property(lambda self: self.indices.ndim - 1)\nn_sparse = property(lambda _: 2)\nn_dense = property(lambda self: self.data.ndim - self.indices.ndim)\n+ _bufs = property(lambda self: (self.data, self.indices, self.indptr))\n+ _info = property(lambda self: SparseInfo(self.shape))\n@property\ndef _sparse_shape(self):\n@@ -345,6 +498,7 @@ class BCSR(JAXSparse):\nraise NotImplementedError(\"Tranpose is not implemented.\")\ndef tree_flatten(self):\n+ # TODO(tianjianlu): Unflatten SparseInfo with self._info._asdict().\nreturn (self.data, self.indices, self.indptr), {'shape': self.shape}\n@classmethod\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -74,13 +74,15 @@ COMPATIBLE_SHAPE_PAIRS = [\n[(2,), (2,)]\n]\n-class BcooDotGeneralProperties(NamedTuple):\n+\n+class BatchedDotGeneralProperties(NamedTuple):\nlhs_shape: Tuple[int, ...]\nrhs_shape: Tuple[int, ...]\nn_batch: int\nn_dense: int\ndimension_numbers: DotDimensionNumbers\n+\ndef _iter_subsets(s: Sequence) -> Iterable[Tuple]:\n\"\"\"Return an iterator over all subsets of a sequence s\"\"\"\nreturn itertools.chain.from_iterable(itertools.combinations(s, n) for n in range(len(s) + 1))\n@@ -99,12 +101,19 @@ def iter_sparse_layouts(shape: Sequence[int], min_n_batch=0) -> Iterator[SparseL\nyield SparseLayout(n_batch=n_batch, n_sparse=n_sparse, n_dense=n_dense)\n-def _generate_bcoo_dot_general_properties(shapes=((5,), (2, 3), (2, 3, 4), (2, 3, 4, 4))) -> BcooDotGeneralProperties:\n+def _generate_batched_dot_general_properties(\n+ shapes=((5,), (2, 3), (2, 3, 4), (2, 3, 4, 4)),\n+ sparse_format='bcoo') -> BatchedDotGeneralProperties:\n\"\"\"Generator of properties for bcoo_dot_general tests.\"\"\"\nrng = random.Random(0)\n+ if sparse_format not in ['bcoo', 'bcsr']:\n+ raise ValueError(f\"Sparse format {sparse_format} not supported.\")\n+\nfor shape in shapes:\nfor layout in iter_sparse_layouts(shape):\n+ if sparse_format == \"bcsr\" and layout.n_sparse != 2:\n+ continue\nsubsets = split_list(range(len(shape)), [layout.n_batch, layout.n_sparse])\nfor batch_dims in _iter_subsets(range(layout.n_batch)):\nfor contracting_dims in _iter_subsets(remaining(range(layout.n_batch + layout.n_sparse), batch_dims)):\n@@ -113,7 +122,7 @@ def _generate_bcoo_dot_general_properties(shapes=((5,), (2, 3), (2, 3, 4), (2, 3\nrhs_permute = rng.sample(range(len(shape)), len(shape))\nlhs_permute = list(itertools.chain.from_iterable(\nrng.sample(subset, len(subset)) for subset in subsets))\n- yield BcooDotGeneralProperties(\n+ yield BatchedDotGeneralProperties(\nlhs_shape=tuple(shape[p] for p in lhs_permute),\nrhs_shape=tuple(shape[p] for p in rhs_permute),\nn_batch=layout.n_batch,\n@@ -141,6 +150,7 @@ def rand_sparse(rng, nse=0.5, post=lambda x: x, rand_method=jtu.rand_default):\nreturn post(M)\nreturn _rand_sparse\n+\ndef _is_required_cuda_version_satisfied(cuda_version):\nversion = xla_bridge.get_backend().platform_version\nif version == \"<unknown>\" or version.split()[0] == \"rocm\":\n@@ -995,11 +1005,11 @@ class BCOOTest(sptu.SparseTestCase):\nself.assertAllClose(M3, M4)\n@jtu.sample_product(\n- props=_generate_bcoo_dot_general_properties(),\n+ props=_generate_batched_dot_general_properties(),\ndtype=jtu.dtypes.floating + jtu.dtypes.complex,\n)\n@jax.default_matmul_precision(\"float32\")\n- def test_bcoo_dot_general(self, dtype: np.dtype, props: BcooDotGeneralProperties):\n+ def test_bcoo_dot_general(self, dtype: np.dtype, props: BatchedDotGeneralProperties):\nrng = jtu.rand_default(self.rng())\nsprng = sptu.rand_bcoo(self.rng(), n_batch=props.n_batch, n_dense=props.n_dense)\nargs_maker = lambda: [sprng(props.lhs_shape, dtype),\n@@ -1204,11 +1214,11 @@ class BCOOTest(sptu.SparseTestCase):\nself.assertArraysEqual(vecmat_expected, vecmat_unsorted_fallback)\n@jtu.sample_product(\n- props=_generate_bcoo_dot_general_properties(),\n+ props=_generate_batched_dot_general_properties(),\ndtype=jtu.dtypes.floating + jtu.dtypes.complex,\n)\n@jax.default_matmul_precision(\"float32\")\n- def test_bcoo_rdot_general(self, dtype: np.dtype, props: BcooDotGeneralProperties):\n+ def test_bcoo_rdot_general(self, dtype: np.dtype, props: BatchedDotGeneralProperties):\nrng = jtu.rand_default(self.rng())\nsprng = sptu.rand_bcoo(self.rng(), n_batch=props.n_batch, n_dense=props.n_dense)\nargs_maker = lambda: [rng(props.rhs_shape, dtype),\n@@ -2266,6 +2276,27 @@ class BCSRTest(sptu.SparseTestCase):\nargs_maker_bcsr_extract = lambda: [indices, indptr, M]\nself._CompileAndCheck(sparse.bcsr_extract, args_maker_bcsr_extract)\n+ @jtu.sample_product(\n+ props=_generate_batched_dot_general_properties(\n+ shapes=((2, 3), (2, 3, 4), (2, 3, 4, 4)), sparse_format='bcsr'),\n+ dtype=jtu.dtypes.floating + jtu.dtypes.complex,\n+ )\n+ @jax.default_matmul_precision(\"float32\")\n+ def test_bcsr_dot_general(self, dtype: np.dtype, props: BatchedDotGeneralProperties):\n+ rng = jtu.rand_default(self.rng())\n+ sprng = sptu.rand_bcsr(self.rng(), n_batch=props.n_batch, n_dense=props.n_dense)\n+ args_maker = lambda: [sprng(props.lhs_shape, dtype),\n+ rng(props.rhs_shape, dtype)]\n+ dense_fun = partial(lax.dot_general,\n+ dimension_numbers=props.dimension_numbers)\n+ sparse_fun = partial(sparse.bcsr_dot_general,\n+ dimension_numbers=props.dimension_numbers)\n+\n+ tol = {np.float64: 1E-12, np.complex128: 1E-12,\n+ np.float32: 1E-5, np.complex64: 1E-5}\n+\n+ self._CheckAgainstDense(dense_fun, sparse_fun, args_maker, tol=tol)\n+ self._CompileAndCheckSparse(sparse_fun, args_maker, atol=tol, rtol=tol)\nclass SparseGradTest(sptu.SparseTestCase):\ndef test_sparse_grad(self):\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Add bcsr dot_general PiperOrigin-RevId: 496489368
260,411
20.12.2022 15:29:51
-7,200
61505d11d2b4512b613a73013cf27476dbfe3d08
[jax2tf] More improvements to shape_poly_test * Small cleanup inside PolyHarness.run_test to use contextlib.ExitContext, and to run the TF eager mode conversion before the tf.function mode, because the latter is unfriendly to breakpoints and makes debugging harder. * Cleanup of the code to exclude some tests for native serialization.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for the shape-polymorphic jax2tf conversion.\"\"\"\n+import contextlib\nimport unittest\nfrom absl.testing import absltest, parameterized\n@@ -465,24 +466,23 @@ class PolyHarness(Harness):\nf_jax = self.fun\nelse:\nf_jax = self.dyn_fun\n+\n+ with contextlib.ExitStack() as stack:\nif expect_error_type is not None:\n- with tst.assertRaisesRegex(expect_error_type, expect_error_regex):\n- f_tf = jax2tf.convert(f_jax, polymorphic_shapes=polymorphic_shapes,\n- enable_xla=self.enable_xla)\n- f_tf_func = tf.function(\n- f_tf, autograph=False, input_signature=input_signature)\n- # Create tf.ConcreteFunction and check inferred output signature\n- f_tf_func.get_concrete_function(*input_signature)\n+ stack.enter_context(tst.assertRaisesRegex(expect_error_type, expect_error_regex))\n- return\n- else:\nf_tf = jax2tf.convert(f_jax, polymorphic_shapes=polymorphic_shapes,\nenable_xla=self.enable_xla)\n+ # Run in tf.Eager mode first, because it is friendlier to debuggers\n+ res_tf = f_tf(*args) if not self.skip_jax_run else None\nf_tf_func = tf.function(\nf_tf, autograph=False, input_signature=input_signature)\n# Create tf.ConcreteFunction and check inferred output signature\nconcrete_f_tf = f_tf_func.get_concrete_function(*input_signature)\n+ if expect_error_type is not None:\n+ return\n+\nif self.expected_output_signature:\n# Strangely, output_shapes can be a single shape for a function with a\n# single result, or a list/tuple of shapes.\n@@ -499,7 +499,6 @@ class PolyHarness(Harness):\n# Run the JAX and the TF functions and compare the results\nif not self.skip_jax_run:\nres_jax = f_jax(*args)\n- res_tf = f_tf(*args)\nif self.check_result:\ntst.assertAllClose(res_jax, res_tf, atol=self.tol, rtol=self.tol)\n@@ -1725,12 +1724,13 @@ _POLY_SHAPE_TEST_HARNESSES = [\npoly_axes=[1, 0]),\nPolyHarness(\"einsum\", \"multiple_contractions\",\nlambda x, y, z: jnp.einsum(\"ab,bc,cd->ad\", x, y, z),\n- arg_descriptors=[RandArg((3, 2), _f32), RandArg((2, 3), _f32), RandArg((3, 4), _f32),],\n+ arg_descriptors=[RandArg((3, 2), _f32), RandArg((2, 3), _f32), RandArg((3, 4), _f32)],\npoly_axes=[0, None, None]),\nPolyHarness(\"einsum\", \"incompatible_contractions_error\",\nlambda x, y: jnp.einsum(\"ab,cb->ac\", x, y),\narg_descriptors=[RandArg((2, 3), _f32), RandArg((2, 3), _f32)],\n- poly_axes=[1, (0, 1)],\n+ polymorphic_shapes=[\"(2, b0)\", \"(2, b1)\"],\n+ input_signature=[tf.TensorSpec((2, None)), tf.TensorSpec((2, None))],\nexpect_error=(core.InconclusiveDimensionOperation,\n\"Dimension polynomial comparison 'b1' == 'b0' is inconclusive\")),\nPolyHarness(\"eye\", \"N=poly_M=None\",\n@@ -2227,22 +2227,6 @@ def _flatten_harnesses(harnesses):\nres.append(h)\nreturn res\n-# Set of harness.group_name:platform that are implemented with custom call\n-custom_call_harnesses = {\n- \"cholesky:cpu\", \"cholesky:gpu\", \"eig:cpu\",\n- \"eigh:cpu\", \"eigh:gpu\", \"fft:cpu\",\n- \"householder_product:cpu\", \"householder_product:gpu\",\n- \"geqrf:cpu\", \"geqrf:gpu\", \"lu:cpu\", \"lu:gpu\", \"qr:cpu\", \"qr:gpu\",\n- \"random_gamma:gpu\", \"random_categorical:gpu\",\n- \"random_randint:gpu\", \"random_uniform:gpu\", \"random_split:gpu\",\n- \"svd:cpu\", \"svd:gpu\"}\n-\n-# Set of harness.group_name or harness.group_name:platform that are implemented with HLO fallback lowering rules\n-fallback_lowering_harnesses = {\n- \"approx_top_k:cpu\", \"bessel_i0e\", \"eigh:tpu\",\n- \"erf_inv\", \"igamma\", \"igammac\", \"lu\",\n- \"regularized_incomplete_beta\", \"qr:tpu\",\n- \"random_gamma:cpu\", \"random_gamma:tpu\", \"svd:tpu\"}\nclass ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n\"\"\"Tests for primitives that take shape values as parameters.\"\"\"\n@@ -2258,18 +2242,49 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n#one_containing=\"\",\n)\ndef test_harness(self, harness: PolyHarness):\n- # Exclude some harnesses that are known to fail\n- if config.jax2tf_default_experimental_native_lowering and not harness.params.get(\"enable_xla\", True):\n- raise unittest.SkipTest(\"disabled for experimental_native_lowering and enable_xla=False\")\n+ # Exclude some harnesses that are known to fail for native serialization\nif config.jax2tf_default_experimental_native_lowering:\n+ if not harness.enable_xla:\n+ raise unittest.SkipTest(\"disabled for experimental_native_lowering and enable_xla=False\")\n+\n+ # Set of harness.group_name:platform that are implemented with custom call\n+ custom_call_harnesses = {\n+ \"vmap_cholesky:cpu\", \"vmap_cholesky:gpu\", \"vmap_eig:cpu\",\n+ \"vmap_eigh:cpu\", \"vmap_eigh:gpu\", \"vmap_fft:cpu\",\n+ \"householder_product:cpu\", \"householder_product:gpu\",\n+ \"vmap_geqrf:cpu\", \"vmap_geqrf:gpu\",\n+ \"vmap_lu:cpu\", \"vmap_lu:gpu\", \"vmap_qr:cpu\", \"vmap_qr:gpu\",\n+ \"random_gamma:gpu\", \"random_categorical:gpu\",\n+ \"random_randint:gpu\", \"random_uniform:gpu\", \"random_split:gpu\",\n+ \"vmap_svd:cpu\", \"vmap_svd:gpu\"}\nif f\"{harness.group_name}:{jtu.device_under_test()}\" in custom_call_harnesses:\nraise unittest.SkipTest(\"native lowering with shape polymorphism not implemented for custom calls; b/261671778\")\n- if (config.jax2tf_default_experimental_native_lowering and\n- (harness.group_name in fallback_lowering_harnesses or\n- f\"{harness.group_name}:{jtu.device_under_test()}\" in fallback_lowering_harnesses)):\n+\n+ # Set of harness.group_name or harness.group_name:platform that are implemented with HLO fallback lowering rules\n+ fallback_lowering_harnesses = {\n+ \"vmap_approx_top_k:cpu\", \"vmap_bessel_i0e\", \"vmap_eigh:tpu\",\n+ \"vmap_erf_inv\", \"vmap_igamma\", \"vmap_igammac\", \"vmap_lu\",\n+ \"vmap_regularized_incomplete_beta\", \"vmap_qr:tpu\",\n+ \"vmap_random_gamma:cpu\", \"vmap_random_gamma:tpu\", \"vmap_svd:tpu\"}\n+ if (harness.group_name in fallback_lowering_harnesses or\n+ f\"{harness.group_name}:{jtu.device_under_test()}\" in fallback_lowering_harnesses):\nraise unittest.SkipTest(\n\"native lowering with shape polymorphism not implemented for JAX primitives still using HLO fallback lowering; b/261682623\")\n+ # Disable these tests because they crash in MHLO\n+ _dynamic_gather_failures = [\n+ # In mlir::mhlo::simplifyDynamicGatherToGather(): LLVM ERROR: Failed to infer result type(s)\n+ \"getitem_op=poly_idx=slice-ct-2\",\n+ \"image_resize_nearest_0\",\n+ \"take__enable_xla=True\",\n+ \"vmap_gather_from_slicing\",\n+ \"vmap_random_randint\",\n+ \"vmap_random_uniform\",\n+ ]\n+ for s in _dynamic_gather_failures:\n+ if harness.fullname.find(s) != -1:\n+ raise unittest.SkipTest(\"TODO(necula): crashes in simplifyDynamicGatherToGather\")\n+\nharness.run_test(self)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] More improvements to shape_poly_test * Small cleanup inside PolyHarness.run_test to use contextlib.ExitContext, and to run the TF eager mode conversion before the tf.function mode, because the latter is unfriendly to breakpoints and makes debugging harder. * Cleanup of the code to exclude some tests for native serialization.
260,411
20.12.2022 15:42:09
-7,200
a51b1744607479906f5dfbdada3cf368db21d817
[jax2tf] Improved error checking for jnp.squeeze with shape polymorphism
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -908,6 +908,9 @@ def squeeze(a: ArrayLike, axis: Optional[Union[int, Tuple[int, ...]]] = None) ->\ndef _squeeze(a: Array, axis: Tuple[int]) -> Array:\nif axis is None:\na_shape = shape(a)\n+ if not core.is_constant_shape(a_shape):\n+ # We do not even know the rank of the output if the input shape is not known\n+ raise ValueError(\"jnp.squeeze with axis=None is not supported with shape polymorphism\")\naxis = tuple(i for i, d in enumerate(a_shape) if d == 1)\nreturn lax.squeeze(a, axis)\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": "@@ -2032,10 +2032,15 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda x: lax.slice_in_dim(x, 0, -1, stride=1, axis=0),\narg_descriptors=[RandArg((3, 4), _f32)],\npoly_axes=[0]),\n- PolyHarness(\"squeeze\", \"axis=None\",\n+ PolyHarness(\"squeeze\", \"axis=empty\",\njnp.squeeze,\narg_descriptors=[RandArg((5,), _f32), StaticArg(())],\npoly_axes=[0]),\n+ PolyHarness(\"squeeze\", \"axis=None\",\n+ jnp.squeeze,\n+ arg_descriptors=[RandArg((5,), _f32), StaticArg(None)],\n+ poly_axes=[0],\n+ expect_error=(ValueError, \"jnp.squeeze with axis=None is not supported with shape polymorphism\")),\nPolyHarness(\"squeeze\", \"axis=1\",\njnp.squeeze,\narg_descriptors=[RandArg((4, 1), _f32), StaticArg((1,))],\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Improved error checking for jnp.squeeze with shape polymorphism
260,335
20.12.2022 12:00:46
28,800
580fdb6e15728acffbda0b863e76f46d3f997134
tweak print_saved_residuals
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_checkpoint.py", "new_path": "jax/_src/ad_checkpoint.py", "diff": "@@ -396,8 +396,12 @@ def saved_residuals(f, *args, **kwargs) -> List[Tuple[core.AbstractValue, str]]:\nif v in res_vars:\nif eqn.primitive is name_p:\nresults.append((v.aval, f\"named '{eqn.params['name']}' from {src}\"))\n+ elif str(eqn.primitive) == 'xla_call':\n+ results.append((v.aval,\n+ f\"output of jitted function '{eqn.params['name']}' \"\n+ f\"from {src}\"))\nelse:\n- results.append((v.aval, f'from {src}'))\n+ results.append((v.aval, f'output of {eqn.primitive.name} from {src}'))\nassert len(results) == len(jaxpr.outvars)\nreturn results\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -33,6 +33,7 @@ import weakref\nimport functools\nimport itertools as it\nimport operator as op\n+import gc\nfrom absl import logging\nfrom absl.testing import absltest, parameterized\n@@ -479,11 +480,14 @@ class CPPJitTest(jtu.BufferDonationTestCase):\ndef f(x, y): return x + y\nclient = jax.devices()[0].client\n+ gc.collect()\nnum_live_initial = len(client.live_executables())\nf(1, 2).block_until_ready()\n+ gc.collect()\nnum_live = len(client.live_executables())\nself.assertEqual(num_live_initial + 1, num_live)\nf.clear_cache()\n+ gc.collect()\nnum_live = len(client.live_executables())\nself.assertEqual(num_live_initial, num_live)\n" } ]
Python
Apache License 2.0
google/jax
tweak print_saved_residuals
260,335
20.12.2022 21:06:09
28,800
6ba0ef650558086322d4b1380d3650732ece9dd3
relax tanh test tols for upcoming xla change
[ { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -281,7 +281,8 @@ class JetTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_cosh(self): self.unary_check(jnp.cosh)\n@jtu.skip_on_devices(\"tpu\")\n- def test_tanh(self): self.unary_check(jnp.tanh, lims=[-500, 500], order=5)\n+ def test_tanh(self): self.unary_check(jnp.tanh, lims=[-500, 500], order=5,\n+ atol=5e-3)\n@jtu.skip_on_devices(\"tpu\")\ndef test_logistic(self): self.unary_check(lax.logistic, lims=[-100, 100], order=5)\n@jtu.skip_on_devices(\"tpu\")\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_autodiff_test.py", "new_path": "tests/lax_autodiff_test.py", "diff": "@@ -170,7 +170,7 @@ LAX_GRAD_SPECIAL_VALUE_TESTS = [\ngrad_special_values_test_spec(\nlax.cosh, [0.],\ntol={np.float32: 1e-2} if jtu.device_under_test() == \"tpu\" else None),\n- grad_special_values_test_spec(lax.tanh, [0., 1000.]),\n+ grad_special_values_test_spec(lax.tanh, [0., 1000.], tol=5e-3),\ngrad_special_values_test_spec(lax.sin, [0., np.pi, np.pi/2., np.pi/4.]),\ngrad_special_values_test_spec(lax.cos, [0., np.pi, np.pi/2., np.pi/4.]),\ngrad_special_values_test_spec(lax.tan, [0.]),\n" } ]
Python
Apache License 2.0
google/jax
relax tanh test tols for upcoming xla change
260,411
20.12.2022 16:20:14
-7,200
0a0ee7873801b64d4da2d01ca1eddc9013c0ae6c
[jax2tf] Fixes for handling of opaque dtypes for slice/update_slice/gather
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -857,8 +857,10 @@ def _jax_physical_aval(aval: core.ShapedArray) -> core.ShapedArray:\nthere is only one and return it.\n\"\"\"\nif core.is_opaque_dtype(aval.dtype):\n- aval, = aval.dtype._rules.physical_avals(aval)\n- return aval\n+ physical_aval, = aval.dtype._rules.physical_avals(aval)\n+ assert (len(physical_aval.shape) >= len(aval.shape) and\n+ physical_aval.shape[:len(aval.shape)] == aval.shape), (physical_aval, aval)\n+ return physical_aval\nreturn aval\ndef _jax_physical_dtype(dtype):\n@@ -2566,9 +2568,16 @@ def _gather(operand, start_indices, *, dimension_numbers, slice_sizes: core.Shap\nindices_are_sorted=indices_are_sorted, fill_value=fill_value,\noutput_shape=_out_aval.shape, _in_avals=_in_avals, _out_aval=_out_aval)\n+ operand_aval = _in_avals[0]\nstart_indices = _maybe_cast_to_int64(start_indices)\n+ if core.is_opaque_dtype(operand_aval.dtype):\n+ opaque_shape = _jax_physical_aval(operand_aval).shape[len(operand_aval.shape):]\n+ trailing_offset_dims = [len(_out_aval.shape) + i for i in range(len(opaque_shape))]\n+ dimension_numbers = dimension_numbers._replace(\n+ offset_dims=(*dimension_numbers.offset_dims, *trailing_offset_dims))\n+ slice_sizes = (*slice_sizes, *opaque_shape)\nproto = _gather_dimensions_proto(start_indices.shape, dimension_numbers)\n- slice_sizes_tf = _eval_shape(slice_sizes, _in_avals[0].dtype)\n+ slice_sizes_tf = _eval_shape(slice_sizes)\nout = tfxla.gather(operand, start_indices, proto, slice_sizes_tf,\nindices_are_sorted)\nout.set_shape(_aval_to_tf_shape(_out_aval))\n@@ -2601,8 +2610,15 @@ def _dynamic_slice(operand, *start_indices, slice_sizes: core.Shape,\n_in_avals: Sequence[core.ShapedArray],\n_out_aval: core.ShapedArray):\nstart_indices = _maybe_cast_to_int64(tf.stack(start_indices))\n- slice_sizes_tf = _eval_shape(slice_sizes, dtype=_in_avals[0].dtype)\n-\n+ operand_aval = _in_avals[0]\n+ if core.is_opaque_dtype(operand_aval.dtype):\n+ opaque_shape = _jax_physical_aval(operand_aval).shape[len(operand_aval.shape):]\n+ slice_sizes = (*slice_sizes, *opaque_shape)\n+ start_indices = tf.concat([start_indices, tf.zeros((len(opaque_shape),),\n+ dtype=start_indices.dtype)],\n+ axis=0)\n+\n+ slice_sizes_tf = _eval_shape(slice_sizes)\nres = tfxla.dynamic_slice(operand, start_indices, size_indices=slice_sizes_tf)\nif _WRAP_JAX_JIT_WITH_TF_FUNCTION:\nres = tf.stop_gradient(res) # See #7839\n@@ -2616,6 +2632,12 @@ def _dynamic_update_slice(operand, update, *start_indices,\n_in_avals: Sequence[core.ShapedArray],\n_out_aval: core.ShapedArray):\nstart_indices = _maybe_cast_to_int64(tf.stack(start_indices))\n+ operand_aval = _in_avals[0]\n+ if core.is_opaque_dtype(operand_aval.dtype):\n+ opaque_shape = _jax_physical_aval(operand_aval).shape[len(operand_aval.shape):]\n+ start_indices = tf.concat([start_indices, tf.zeros((len(opaque_shape),),\n+ dtype=start_indices.dtype)],\n+ axis=0)\nout = tfxla.dynamic_update_slice(operand, update, start_indices)\nif _WRAP_JAX_JIT_WITH_TF_FUNCTION:\nout = tf.stop_gradient(out) # See #7839\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": "@@ -1150,7 +1150,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(g_tf[1], np.zeros_like(zb))\ndef test_prng(self):\n- raise unittest.SkipTest(\"TODO(necula): investigate\")\n# The PRNG implementation uses opaque types, test shape polymorphism\ntry:\nprev_custom_prng = config.jax_enable_custom_prng\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fixes for handling of opaque dtypes for slice/update_slice/gather
260,411
21.12.2022 09:14:46
-7,200
5812957186dd8024fe20f3cba08b2be7b098ceb8
[jax2tf] Add autograph=False everywhere we use tf.function
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -87,7 +87,8 @@ f_tf_graph = tf.function(f_tf, autograph=False)\nThe Autograph feature of `tf.function` cannot be expected to work on\nfunctions lowered from JAX as above, so it is recommended to\n-set `autograph=False` in order to avoid warnings or outright errors.\n+set `autograph=False` in order to speed up the execution\n+and to avoid warnings and outright errors.\nIt is a good idea to use XLA to compile the lowered function; that is\nthe scenario for which we are optimizing for numerical and performance\n@@ -186,7 +187,7 @@ prediction_tf = lambda inputs: jax2tf.convert(model_jax)(params_vars, inputs)\nmy_model = tf.Module()\n# Tell the model saver what are the variables.\nmy_model._variables = tf.nest.flatten(params_vars)\n-my_model.f = tf.function(prediction_tf, jit_compile=True)\n+my_model.f = tf.function(prediction_tf, jit_compile=True, autograph=False)\ntf.saved_model.save(my_model)\n```\n@@ -685,7 +686,7 @@ jax2tf.convert(jnp.sin)(3.14) # Has type float32\njax2tf.convert(jnp.sin)(np.float64(3.14)) # Has type float32\n# The following will still compute `sin` in float32 (with a tf.cast on the argument).\n-tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, dtype=tf.float64))\n+tf.function(jax2tf.convert(jnp.sin), autograph=False)(tf.Variable(3.14, dtype=tf.float64))\n```\nWhen the `JAX_ENABLE_X64` flas is set, JAX uses 64-bit types\n@@ -700,10 +701,10 @@ tf.math.sin(3.14) # Has type float32\njax2tf.convert(jnp.sin)(3.14) # Has type float64\n# The following will compute `sin` in float64.\n-tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, dtype=tf.float64))\n+tf.function(jax2tf.convert(jnp.sin), autograph=False)(tf.Variable(3.14, dtype=tf.float64))\n# The following will compute `sin` in float32.\n-tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14))\n+tf.function(jax2tf.convert(jnp.sin), autograph=False)(tf.Variable(3.14))\n```\nThis is achieved by inserting `tf.cast` operations\n@@ -1087,7 +1088,8 @@ jax2tf.convert(f_jax, polymorphic_shapes=[\"b\"])(x0)\n# However, if we first trace to a TensorFlow graph, we may miss the broken assumption:\nf_tf = tf.function(\n- jax2tf.convert(f_jax, polymorphic_shapes=[\"b\"])).get_concrete_function(tf.TensorSpec([None], dtype=np.float32))\n+ jax2tf.convert(f_jax, polymorphic_shapes=[\"b\"]), autograph=False\n+ ).get_concrete_function(tf.TensorSpec([None], dtype=np.float32))\nself.assertEqual(1, f_tf(x0))\n```\n@@ -1110,7 +1112,8 @@ jax2tf.convert(f_jax, polymorphic_shapes=[\"b, b\"])(x45)\n# However, if we first trace to a TensorFlow graph, we may miss the broken assumption.\nf_tf = tf.function(\n- jax2tf.convert(f_jax, polymorphic_shapes=[\"b, b\"])).get_concrete_function(tf.TensorSpec([None, None], dtype=np.float32))\n+ jax2tf.convert(f_jax, polymorphic_shapes=[\"b, b\"]),\n+ autograph=False).get_concrete_function(tf.TensorSpec([None, None], dtype=np.float32))\nself.assertEqual(1, f_tf(x45))\n```\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": "@@ -544,7 +544,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nbegin = 0\nreturn x[begin:5] # x must be a compile-time constant\n- hlo = tf.function(fun_tf, jit_compile=True).experimental_get_compiler_ir(x)()\n+ hlo = tf.function(fun_tf, jit_compile=True, autograph=False).experimental_get_compiler_ir(x)()\nself.assertIn(\"(arg0.1: s32[10]) -> s32[5]\", hlo)\n# Non-constant slice, but compile-time constant depending only on values.\n@@ -554,10 +554,10 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nbegin = x[0]\nreturn x[begin:5] # x must be a compile-time constant\n- hlo = tf.function(fun_tf, jit_compile=True).experimental_get_compiler_ir(x)()\n+ hlo = tf.function(fun_tf, jit_compile=True, autograph=False).experimental_get_compiler_ir(x)()\nself.assertIn(\"() -> s32[5]\", hlo)\nx = np.ones((10,), dtype=np.int32)\n- hlo = tf.function(fun_tf, jit_compile=True).experimental_get_compiler_ir(x)()\n+ hlo = tf.function(fun_tf, jit_compile=True, autograph=False).experimental_get_compiler_ir(x)()\nself.assertIn(\"() -> s32[4]\", hlo)\n# Non-constant slice, but compile-time constant depending only on shapes.\n@@ -567,7 +567,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nbegin = tf.shape(x)[0] - 2 # begin is a compile-time constant, even if x is not\nreturn x[begin:]\n- hlo = tf.function(fun_tf, jit_compile=True).experimental_get_compiler_ir(x)()\n+ hlo = tf.function(fun_tf, jit_compile=True, autograph=False).experimental_get_compiler_ir(x)()\nself.assertIn(\"(arg0.1: s32[10]) -> s32[2]\", hlo)\n# Capture a variable\n@@ -577,7 +577,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\ndef fun_tf(x):\nreturn x * tf.broadcast_to(outer_var, x.shape) + 1.\n- hlo = tf.function(fun_tf, jit_compile=True).experimental_get_compiler_ir(x)()\n+ hlo = tf.function(fun_tf, jit_compile=True, autograph=False).experimental_get_compiler_ir(x)()\nself.assertIn(\"(arg0.1: f32[3], arg1.2: f32[1]) -> f32[3]\", hlo)\n# Capture a constant\n@@ -587,7 +587,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\ndef fun_tf(x):\nreturn x * tf.broadcast_to(outer_ct, x.shape) + 1.\n- hlo = tf.function(fun_tf, jit_compile=True).experimental_get_compiler_ir(x)()\n+ hlo = tf.function(fun_tf, jit_compile=True, autograph=False).experimental_get_compiler_ir(x)()\nself.assertIn(\"(arg0.1: f32[3]) -> f32[3]\", hlo)\n# Call get_compiler_ir in a function context\n@@ -596,7 +596,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\ndef fun_tf_outer(x):\nx_const = tf.constant(0, shape=x.shape, dtype=x.dtype)\n- _ = tf.function(tf.math.sin, jit_compile=True).experimental_get_compiler_ir(x_const)()\n+ _ = tf.function(tf.math.sin, jit_compile=True, autograph=False).experimental_get_compiler_ir(x_const)()\n# TODO(b/193754660)\n# with self.assertRaisesRegex(\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -165,7 +165,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\n@jtu.skip_on_devices(\"gpu\")\ndef test_bfloat16_passed_by_tf(self):\nf_jax = lambda a, b: a + b\n- f_tf = tf.function(jax2tf.convert(f_jax),\n+ f_tf = tf.function(jax2tf.convert(f_jax), autograph=False,\ninput_signature=[tf.TensorSpec([512, 512], tf.bfloat16),\ntf.TensorSpec([512, 512], tf.bfloat16)])\nself.assertIsNotNone(f_tf.get_concrete_function())\n@@ -186,7 +186,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nresult = jax2tf.convert(f_jax)(a, b)\nreturn result, tape.gradient(result, a)\n- f_tf = tf.function(_tf_grad,\n+ f_tf = tf.function(_tf_grad, autograph=False,\ninput_signature=[tf.TensorSpec([512, 512], tf.bfloat16),\ntf.TensorSpec([512, 512], tf.bfloat16)])\n@@ -203,7 +203,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(jnp.sin, big_const)\nf_conv = jax2tf.convert(jnp.sin)\nif with_function:\n- f_conv = tf.function(f_conv)\n+ f_conv = tf.function(f_conv, autograph=False)\n# We check also when we pass tf.Variable or tf.Tensor into the\n# converted function\nself.assertAllClose(jnp.sin(big_const),\n@@ -223,10 +223,10 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\n# jax2tf.convert has the same behavior as JAX\nself.assertEqual(jax2tf.convert(jnp.sin)(3.14).dtype, tf.float64)\n# The following will compute `sin` in float64.\n- self.assertEqual(tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, dtype=tf.float64)).dtype, tf.float64)\n+ self.assertEqual(tf.function(jax2tf.convert(jnp.sin), autograph=False)(tf.Variable(3.14, dtype=tf.float64)).dtype, tf.float64)\n# The following will compute `sin` in float32.\n- self.assertEqual(tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14)).dtype, tf.float32)\n+ self.assertEqual(tf.function(jax2tf.convert(jnp.sin), autograph=False)(tf.Variable(3.14)).dtype, tf.float32)\ndef test_64bit_behavior_not_enable_x64_readme(self):\n# Tests some of the examples from the README\n@@ -244,7 +244,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\n# jax2tf.convert has the same behavior as JAX\nself.assertEqual(jax2tf.convert(jnp.sin)(3.14).dtype, tf.float32)\nself.assertEqual(jax2tf.convert(jnp.sin)(np.float64(3.14)).dtype, tf.float32)\n- self.assertEqual(tf.function(jax2tf.convert(jnp.sin))(tf.Variable(3.14, dtype=tf.float64)).dtype, tf.float32)\n+ self.assertEqual(tf.function(jax2tf.convert(jnp.sin), autograph=False)(tf.Variable(3.14, dtype=tf.float64)).dtype, tf.float32)\ndef test_function(self):\nf_jax = jax.jit(lambda x: jnp.sin(jnp.cos(x)))\n@@ -988,7 +988,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nreturn jnp.sum(x)\nf_tf = jax2tf.convert(f_jax)\nif with_function:\n- f_tf = tf.function(f_tf)\n+ f_tf = tf.function(f_tf, autograph=False)\nself.assertAllClose(\nf_tf(x=np.zeros(3, dtype=np.float32)), # Call with kwargs.\nnp.zeros((), dtype=np.float32))\n@@ -1002,7 +1002,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nreturn jnp.sum(x[0]) + 2. * jnp.sum(x[1])\nf_tf = jax2tf.convert(f_jax)\nif with_function:\n- f_tf = tf.function(f_tf)\n+ f_tf = tf.function(f_tf, autograph=False)\nxv = tf.nest.map_structure(tf.Variable, x)\nwith tf.GradientTape() as tape:\nres = f_tf(x=xv)\n@@ -1257,7 +1257,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nwith global_mesh:\ntf_func = tf.function(\njax2tf.convert(jax_func, enable_xla=True),\n- jit_compile=True,\n+ jit_compile=True, autograph=False\n)\njax_out = jax_func(input_data=input_data)\ntf_out = tf_func(input_data=input_data)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/savedmodel_test.py", "new_path": "jax/experimental/jax2tf/tests/savedmodel_test.py", "diff": "@@ -166,7 +166,7 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\nmodel = tf.Module()\nmodel._variables = tf.nest.flatten(params_vars)\n- model.f = tf.function(prediction_tf, jit_compile=True)\n+ model.f = tf.function(prediction_tf, jit_compile=True, autograph=False)\nx = np.array(0.7, dtype=jnp.float32)\nself.assertAllClose(model.f(x), model_jax(params, x))\n@@ -306,13 +306,13 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nException,\n\"Detected unsupported operations when trying to compile graph\"):\n- tf.function(tf_fn, jit_compile=True)(x_str)\n+ tf.function(tf_fn, jit_compile=True, autograph=False)(x_str)\n# Plug in the TF-compiled JAX-converted `compute_jax_fn`.\ncomposed_fn = lambda x_str: tf_fn(\nx_str,\ncompute_tf_fn=tf.function(jax2tf.convert(jnp.sin),\n- autograph=True,\n+ autograph=False,\njit_compile=True))\nres_tf = composed_fn(x_str)\nself.assertAllClose(res_tf.numpy(),\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/sharding_test.py", "new_path": "jax/experimental/jax2tf/tests/sharding_test.py", "diff": "@@ -134,7 +134,7 @@ class ShardedJitHloTest(tf_test_util.JaxToTfTestCase):\nlogging.info(\"[%s] got TF HLO %s\", self._testMethodName, tf_hlo)\nself._assert_sharding_annotations(\"TF before optimizations\", tf_hlo, expected)\ntf_optimized_hlo = (\n- tf.function(f_tf, jit_compile=True)\n+ tf.function(f_tf, jit_compile=True, autograph=False)\n.experimental_get_compiler_ir(*args)(stage=\"optimized_hlo\",\ndevice_name=device_name))\nlogging.info(\"[%s] got TF optimized HLO for %s: %s\", self._testMethodName,\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Add autograph=False everywhere we use tf.function
260,411
21.12.2022 10:22:12
-7,200
a74c74c25572eec23c28e08dbe67781a23be19fb
Fix scatter in CLIP mode with uint32 and uint64 indices Clipping uses np.iinfo(indices.dtype).max and those values are too large to be converted to Python or C constants.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/slicing.py", "new_path": "jax/_src/lax/slicing.py", "diff": "@@ -1562,7 +1562,8 @@ def _clamp_scatter_indices(operand, indices, updates, *, dnums):\nfor i in dnums.scatter_dims_to_operand_dims)\n# Stack upper_bounds into a Array[n]\nupper_bound = lax.shape_as_value(upper_bounds)\n- upper_bound = lax.min(upper_bound, np.iinfo(indices.dtype).max)\n+ upper_bound = lax.min(upper_bound,\n+ lax.convert_element_type(np.uint64(np.iinfo(indices.dtype).max), np.int64))\nupper_bound = lax.broadcast_in_dim(upper_bound, indices.shape,\n(len(indices.shape) - 1,))\nreturn lax.clamp(np.int64(0), lax.convert_element_type(indices, np.int64),\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -2200,7 +2200,7 @@ class LaxTest(jtu.JaxTestCase):\n((10,), np.array([[0], [0], [0]]), (3, 2), lax.ScatterDimensionNumbers(\nupdate_window_dims=(1,), inserted_window_dims=(),\nscatter_dims_to_operand_dims=(0,))),\n- ((10, 5,), np.array([[0], [2], [1]]), (3, 3), lax.ScatterDimensionNumbers(\n+ ((10, 5,), np.array([[0], [2], [1]], dtype=np.uint64), (3, 3), lax.ScatterDimensionNumbers(\nupdate_window_dims=(1,), inserted_window_dims=(0,),\nscatter_dims_to_operand_dims=(0,))),\n]],\n" } ]
Python
Apache License 2.0
google/jax
Fix scatter in CLIP mode with uint32 and uint64 indices Clipping uses np.iinfo(indices.dtype).max and those values are too large to be converted to Python or C constants.
260,447
21.12.2022 09:54:38
28,800
e89b60e3832d2ee16b1ae31cd73a23b8bc4f64d5
[sparse] Propagate SparseInfo to BCSR todense() and tree_(un)flatten().
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcsr.py", "new_path": "jax/experimental/sparse/bcsr.py", "diff": "@@ -173,7 +173,7 @@ def _bcsr_fromdense_impl(mat, *, nse, n_batch, n_dense, index_dtype):\n@bcsr_fromdense_p.def_abstract_eval\n-def _bcoo_fromdense_abstract_eval(mat, *, nse, n_batch, n_dense, index_dtype):\n+def _bcsr_fromdense_abstract_eval(mat, *, nse, n_batch, n_dense, index_dtype):\nn_sparse = mat.ndim - n_batch - n_dense\nif n_sparse != 2:\nraise ValueError(\"bcsr_fromdense: must have 2 sparse dimensions.\")\n@@ -218,39 +218,43 @@ def bcsr_todense(mat: BCSR) -> Array:\nReturns:\nThe dense version of ``mat``.\n\"\"\"\n- return _bcsr_todense(mat.data, mat.indices, mat.indptr,\n- shape=tuple(mat.shape))\n+ return _bcsr_todense(mat.data, mat.indices, mat.indptr, spinfo=mat._info)\n-def _bcsr_todense(data: ArrayLike, indices: ArrayLike, indptr: ArrayLike, *, shape: Shape) -> Array:\n+def _bcsr_todense(data: ArrayLike, indices: ArrayLike, indptr: ArrayLike, *,\n+ spinfo: SparseInfo) -> Array:\n\"\"\"Convert batched sparse matrix to a dense matrix.\nArgs:\ndata : array of shape ``batch_dims + (nse,) + dense_dims``.\nindices : array of shape ``batch_dims + (nse,)``.\nindptr : array of shape ``batch_dims + (shape[len(batch_dims)] + 1,).\n- shape : tuple; the shape of the (batched) matrix. Equal to\n- ``batch_dims + 2(sparse_dims) + dense_dims``\n+ spinfo : SparseInfo. In particular, this includes the shape\n+ of the matrix, which is equal to\n+ ``batch_dims + 2(sparse_dims) + block_dims`` where\n+ ``len(sparse_dims) == 2``.\nReturns:\nmat : array with specified shape and dtype matching ``data``\n\"\"\"\nreturn bcsr_todense_p.bind(jnp.asarray(data), jnp.asarray(indices),\n- jnp.asarray(indptr), shape=shape)\n+ jnp.asarray(indptr), spinfo=spinfo)\n@bcsr_todense_p.def_impl\n-def _bcsr_todense_impl(data, indices, indptr, *, shape):\n+def _bcsr_todense_impl(data, indices, indptr, *, spinfo):\n+ shape = spinfo.shape\nbcoo_indices = _bcsr_to_bcoo(indices, indptr, shape=shape)\nreturn (bcoo.BCOO((data, bcoo_indices), shape=shape)).todense()\n@bcsr_todense_p.def_abstract_eval\n-def _bcsr_todense_abstract_eval(data, indices, indptr, *, shape):\n+def _bcsr_todense_abstract_eval(data, indices, indptr, *, spinfo):\n+ shape = spinfo.shape\n_validate_bcsr(data, indices, indptr, shape)\nreturn core.ShapedArray(shape, data.dtype)\n-def _bcsr_todense_batching_rule(batched_args, batch_dims, *, shape):\n+def _bcsr_todense_batching_rule(batched_args, batch_dims, *, spinfo):\ndata, indices, indptr = batched_args\nif any(b not in [0, None] for b in batch_dims):\nraise NotImplementedError(f\"{batch_dims=}. Only 0 and None are supported.\")\n@@ -260,7 +264,7 @@ def _bcsr_todense_batching_rule(batched_args, batch_dims, *, shape):\nindices = indices[None, ...]\nif batch_dims[2] is None:\nindptr = indptr[None, ...]\n- return _bcsr_todense(data, indices, indptr, shape=shape), 0\n+ return _bcsr_todense(data, indices, indptr, spinfo=spinfo), 0\nbatching.primitive_batchers[bcsr_todense_p] = _bcsr_todense_batching_rule\nmlir.register_lowering(bcsr_todense_p, mlir.lower_fun(\n@@ -498,14 +502,13 @@ class BCSR(JAXSparse):\nraise NotImplementedError(\"Tranpose is not implemented.\")\ndef tree_flatten(self):\n- # TODO(tianjianlu): Unflatten SparseInfo with self._info._asdict().\n- return (self.data, self.indices, self.indptr), {'shape': self.shape}\n+ return (self.data, self.indices, self.indptr), self._info._asdict()\n@classmethod\ndef tree_unflatten(cls, aux_data, children):\nobj = object.__new__(cls)\nobj.data, obj.indices, obj.indptr = children\n- if aux_data.keys() != {'shape'}:\n+ if aux_data.keys() != {'shape', 'indices_sorted', 'unique_indices'}:\nraise ValueError(f\"BCSR.tree_unflatten: invalid {aux_data=}\")\nobj.__dict__.update(**aux_data)\nreturn obj\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -2172,7 +2172,8 @@ class BCSRTest(sptu.SparseTestCase):\nself.assertEqual(indptr.dtype, jnp.int32)\nself.assertEqual(indptr.shape, shape[:n_batch] + (shape[n_batch] + 1,))\n- todense = partial(sparse_bcsr._bcsr_todense, shape=shape)\n+ todense = partial(sparse_bcsr._bcsr_todense,\n+ spinfo=sparse_util.SparseInfo(shape=shape))\nself.assertArraysEqual(M, todense(data, indices, indptr))\nargs_maker_todense = lambda: [data, indices, indptr]\nself._CompileAndCheck(todense, args_maker_todense)\n@@ -2195,7 +2196,8 @@ class BCSRTest(sptu.SparseTestCase):\nfromdense = partial(sparse_bcsr._bcsr_fromdense, nse=nse, n_batch=0,\nn_dense=n_dense)\n- todense = partial(sparse_bcsr._bcsr_todense, shape=shape)\n+ todense = partial(sparse_bcsr._bcsr_todense,\n+ spinfo=sparse_util.SparseInfo(shape))\nfor _ in range(n_batch):\nfromdense = jax.vmap(fromdense)\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Propagate SparseInfo to BCSR todense() and tree_(un)flatten(). PiperOrigin-RevId: 496945167
260,335
21.12.2022 10:16:18
28,800
c2d9b5cee6b5eaa94618c2bef73866182a583e5a
tweak dot_general pretty-printing rule to suppress default params
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -2566,7 +2566,8 @@ def _dot_general_transpose_lhs(g, y, *, dimension_numbers, precision,\ndims = ((ans_y, y_kept), (ans_batch, y_batch))\nx_contract_sorted_by_y = list(np.take(x_contract, np.argsort(y_contract))) # type: ignore[arg-type]\nout_axes = np.argsort(list(x_batch) + x_kept + x_contract_sorted_by_y)\n- return transpose(dot_general(g, y, dims, precision=precision, preferred_element_type=preferred_element_type),\n+ return transpose(dot_general(g, y, dims, precision=precision,\n+ preferred_element_type=preferred_element_type),\ntuple(out_axes))\ndef _dot_general_transpose_rhs(g, x, *, dimension_numbers, precision,\n@@ -2675,8 +2676,8 @@ def _dot_general_padding_rule(in_avals, out_avals, lhs, rhs, *,\nreturn [dot_general(lhs_, rhs, dimension_numbers=dimension_numbers, **params)]\ndef _dot_general_pp_rule(eqn, context, settings):\n- # suppress printing precision or preferred_element_type when None.\n- # print dimension_numbers as list-of-lists to be shorter.\n+ # * suppress printing precision or preferred_element_type when None.\n+ # * print dimension_numbers as list-of-lists to be shorter.\nprinted_params = {k: v for k, v in eqn.params.items() if v is not None}\n(lhs_cont, rhs_cont), (lhs_batch, rhs_batch) = eqn.params['dimension_numbers']\nprinted_params['dimension_numbers'] = (\n@@ -2696,8 +2697,7 @@ ad.defbilinear(dot_general_p,\n_dot_general_transpose_lhs, _dot_general_transpose_rhs)\nbatching.primitive_batchers[dot_general_p] = _dot_general_batch_rule\npe.padding_rules[dot_general_p] = _dot_general_padding_rule\n-# TODO(mattjj): un-comment the next line\n-# core.pp_eqn_rules[dot_general_p] = _dot_general_pp_rule\n+core.pp_eqn_rules[dot_general_p] = _dot_general_pp_rule\ndef precision_attr(precision: PrecisionType) -> ir.ArrayAttr:\nif precision is None:\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3777,7 +3777,8 @@ class APITest(jtu.JaxTestCase):\nwith jax.default_matmul_precision(None):\njnp.dot(x, x) # doesn't crash\njaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n- self.assertIn('precision=None', str(jaxpr))\n+ # self.assertIn('precision=None', str(jaxpr))\n+ self.assertIs(jaxpr.jaxpr.eqns[0].params['precision'], None)\nwith jax.default_matmul_precision(\"bfloat16\"):\nx @ x # doesn't crash\n" } ]
Python
Apache License 2.0
google/jax
tweak dot_general pretty-printing rule to suppress default params
260,599
16.12.2022 10:12:40
0
c0d4ae0cc3252811861b65036f247a583c50bdff
Added scipy.stats.bernoulli cdf and ppf.
[ { "change_type": "MODIFY", "old_path": "docs/jax.scipy.rst", "new_path": "docs/jax.scipy.rst", "diff": "@@ -159,6 +159,8 @@ jax.scipy.stats.bernoulli\nlogpmf\npmf\n+ cdf\n+ ppf\njax.scipy.stats.beta\n~~~~~~~~~~~~~~~~~~~~\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/stats/bernoulli.py", "new_path": "jax/_src/scipy/stats/bernoulli.py", "diff": "@@ -36,3 +36,26 @@ def logpmf(k: ArrayLike, p: ArrayLike, loc: ArrayLike = 0) -> Array:\n@_wraps(osp_stats.bernoulli.pmf, update_doc=False)\ndef pmf(k: ArrayLike, p: ArrayLike, loc: ArrayLike = 0) -> Array:\nreturn jnp.exp(logpmf(k, p, loc))\n+\n+@_wraps(osp_stats.bernoulli.cdf, update_doc=False)\n+def cdf(k: ArrayLike, p: ArrayLike) -> Array:\n+ k, p = jnp._promote_args_inexact('bernoulli.cdf', k, p)\n+ zero, one = _lax_const(k, 0), _lax_const(k, 1)\n+ conds = [\n+ jnp.isnan(k) | jnp.isnan(p) | (p < zero) | (p > one),\n+ lax.lt(k, zero),\n+ jnp.logical_and(lax.ge(k, zero), lax.lt(k, one)),\n+ lax.ge(k, one)\n+ ]\n+ vals = [jnp.nan, zero, one - p, one]\n+ return jnp.select(conds, vals)\n+\n+@_wraps(osp_stats.bernoulli.ppf, update_doc=False)\n+def ppf(q: ArrayLike, p: ArrayLike) -> Array:\n+ q, p = jnp._promote_args_inexact('bernoulli.ppf', q, p)\n+ zero, one = _lax_const(q, 0), _lax_const(q, 1)\n+ return jnp.where(\n+ jnp.isnan(q) | jnp.isnan(p) | (p < zero) | (p > one) | (q < zero) | (q > one),\n+ jnp.nan,\n+ jnp.where(lax.le(q, one - p), zero, one)\n+ )\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/bernoulli.py", "new_path": "jax/scipy/stats/bernoulli.py", "diff": "from jax._src.scipy.stats.bernoulli import (\nlogpmf as logpmf,\npmf as pmf,\n+ cdf as cdf,\n+ ppf as ppf\n)\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_stats_test.py", "new_path": "tests/scipy_stats_test.py", "diff": "@@ -155,6 +155,43 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\ntol=1e-4)\nself._CompileAndCheck(lax_fun, args_maker)\n+ @genNamedParametersNArgs(2)\n+ def testBernoulliCdf(self, shapes, dtypes):\n+ rng_int = jtu.rand_int(self.rng(), -100, 100)\n+ rng_uniform = jtu.rand_uniform(self.rng())\n+ scipy_fun = osp_stats.bernoulli.cdf\n+ lax_fun = lsp_stats.bernoulli.cdf\n+\n+ def args_maker():\n+ x = rng_int(shapes[0], dtypes[0])\n+ p = rng_uniform(shapes[1], dtypes[1])\n+ return [x, p]\n+\n+ with jtu.strict_promotion_if_dtypes_match(dtypes):\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n+ tol=5e-4)\n+ self._CompileAndCheck(lax_fun, args_maker)\n+\n+ @genNamedParametersNArgs(2)\n+ def testBernoulliPpf(self, shapes, dtypes):\n+ rng = jtu.rand_default(self.rng())\n+ scipy_fun = osp_stats.bernoulli.ppf\n+ lax_fun = lsp_stats.bernoulli.ppf\n+\n+ if scipy_version < (1, 9, 2):\n+ self.skipTest(\"Scipy 1.9.2 needed for fix https://github.com/scipy/scipy/pull/17166.\")\n+\n+ def args_maker():\n+ q, p = map(rng, shapes, dtypes)\n+ q = expit(q)\n+ p = expit(p)\n+ return [q, p]\n+\n+ with jtu.strict_promotion_if_dtypes_match(dtypes):\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n+ tol=5e-4)\n+ self._CompileAndCheck(lax_fun, args_maker)\n+\n@genNamedParametersNArgs(3)\ndef testGeomLogPmf(self, shapes, dtypes):\nrng = jtu.rand_default(self.rng())\n" } ]
Python
Apache License 2.0
google/jax
Added scipy.stats.bernoulli cdf and ppf.
260,631
23.12.2022 22:46:21
28,800
398aaaacc7eb40337d097ff0b4ff53d46f7f76ea
Add support for Ellipsis as an index for stateful operations.
[ { "change_type": "MODIFY", "old_path": "jax/_src/state/primitives.py", "new_path": "jax/_src/state/primitives.py", "diff": "@@ -65,9 +65,12 @@ def _get_impl(ref: Ref, *idx: int, **_):\nget_p.def_impl(_get_impl)\nIndexer = Tuple[Union[int, slice, Array], ...]\n+# or Ellipsis, but that can't be annotated until Python 3.10? (types.EllipsisType)\ndef _unpack_idx(idx: Indexer, ndim: int\n) -> Tuple[Tuple[Array, ...], Tuple[bool, ...]]:\n+ if idx is ... or (type(idx) is tuple and len(idx) == 1 and idx[0] is ...):\n+ idx = tuple(slice(None) for _ in range(ndim))\nindexed_dims_ = [type(i) != slice for i in idx]\n_, non_slice_idx = partition_list(indexed_dims_, idx)\nindexed_dims = indexed_dims_ + [False] * (ndim - len(indexed_dims_))\n@@ -83,7 +86,7 @@ def _get_slice_output_shape(in_shape: Tuple[int, ...],\nshape = (*shape_prefix, *shape_suffix)\nreturn shape\n-def ref_get(ref: Ref, idx: Tuple[Union[int, slice], ...]) -> Array:\n+def ref_get(ref: Ref, idx: Indexer) -> Array:\n\"\"\"Reads a value from a `Ref`, a.k.a. value <- ref[idx].\"\"\"\nnon_slice_idx, indexed_dims = _unpack_idx(idx, ref.ndim)\nreturn get_p.bind(ref, *non_slice_idx, indexed_dims=indexed_dims)\n@@ -111,12 +114,12 @@ def _swap_impl(ref: Ref, value: Array, *idx: int, **_):\nraise ValueError(\"Cannot run stateful primitive.\")\nswap_p.def_impl(_swap_impl)\n-def ref_swap(ref: Ref, idx: Tuple[int, ...], value: Array) -> Array:\n+def ref_swap(ref: Ref, idx: Indexer, value: Array) -> Array:\n\"\"\"Sets a `Ref`'s value and returns the original value.\"\"\"\nnon_slice_idx, indexed_dims = _unpack_idx(idx, ref.ndim)\nreturn swap_p.bind(ref, value, *non_slice_idx, indexed_dims=indexed_dims)\n-def ref_set(ref: Ref, idx: Tuple[int, ...], value: Array) -> None:\n+def ref_set(ref: Ref, idx: Indexer, value: Array) -> None:\n\"\"\"Sets a `Ref`'s value, a.k.a. ref[idx] <- value.\"\"\"\nref_swap(ref, idx, value)\n@@ -139,7 +142,7 @@ def _addupdate_impl(ref: Ref, value: Array, *idx: int):\nraise ValueError(\"Can't evaluate `addupdate` outside a stateful context.\")\naddupdate_p.def_impl(_addupdate_impl)\n-def ref_addupdate(ref: Ref, idx: Tuple[int, ...], x: Array) -> None:\n+def ref_addupdate(ref: Ref, idx: Indexer, x: Array) -> None:\n\"\"\"Mutates a ref with an additive update i.e. `ref[idx] += x`.\"\"\"\nnon_slice_idx, indexed_dims = _unpack_idx(idx, ref.ndim)\nreturn addupdate_p.bind(ref, x, *non_slice_idx, indexed_dims=indexed_dims)\n" }, { "change_type": "MODIFY", "old_path": "tests/state_test.py", "new_path": "tests/state_test.py", "diff": "@@ -648,6 +648,17 @@ class StateDischargeTest(jtu.JaxTestCase):\nself.assertEqual(discharged_jaxpr.effects,\n{state.WriteEffect(discharged_jaxpr.invars[0].aval)})\n+ def test_ellipsis_index(self):\n+ def f(ref):\n+ state.ref_set(ref, ..., jnp.array(0., dtype=jnp.float32))\n+ state.ref_get(ref, ...)\n+ ref[...] = jnp.array(0., dtype=jnp.float32)\n+ ref[...]\n+ return []\n+\n+ in_avals = [state.ShapedArrayRef((), jnp.float32)]\n+ pe.trace_to_jaxpr_dynamic(lu.wrap_init(f), in_avals)\n+\nif CAN_USE_HYPOTHESIS:\n" } ]
Python
Apache License 2.0
google/jax
Add support for Ellipsis as an index for stateful operations. PiperOrigin-RevId: 497466879
260,411
27.12.2022 15:28:04
-7,200
0752655ff0338b6842fafb6c888f6da8d50a6e63
[jax2tf] Move pjit test into the right TestCase class This test uses tfxla.call_module directly, belongs to XlaCallModuleTest.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -1264,38 +1264,6 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\n# TODO(b/243146552) We can switch to ConvertAndCompare after this bug fix.\nnp.array_equal(jax_out._value, np.array(tf_out))\n- @jtu.with_mesh([(\"x\", 2)])\n- def test_pjit_basic1D(self):\n-\n- def func_jax(x, y):\n- return x + y\n-\n- shape = (8, 10)\n- x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n- in_axis_resources = (P(\"x\"), P(\"x\"))\n- out_axis_resources = None\n- res_jax = pjit(\n- func_jax,\n- in_axis_resources=in_axis_resources,\n- out_axis_resources=out_axis_resources)(x, x)\n- module = get_serialized_computation(\n- func_jax,\n- x,\n- x,\n- use_pjit=True,\n- in_axis_resources=in_axis_resources,\n- out_axis_resources=out_axis_resources)\n-\n- def f_tf(x_tf, y_tf):\n- return tfxla.call_module([x_tf, y_tf],\n- version=2,\n- module=module,\n- Tout=[x.dtype],\n- Sout=[x.shape])\n-\n- res_tf = tf.function(f_tf, jit_compile=True, autograph=False)(x, x)[0]\n- self.assertAllClose(res_tf.numpy(), res_jax)\n-\ndef assertAllOperationStartWith(self, g: tf.Graph, scope_name: str):\n\"\"\"Assert all operations name start with ```scope_name```.\n@@ -1505,6 +1473,38 @@ class XlaCallModuleTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(\ntf.nest.map_structure(lambda t: t.numpy(), res), jax_res)\n+ @jtu.with_mesh([(\"x\", 2)])\n+ def test_pjit_basic1D(self):\n+\n+ def func_jax(x, y):\n+ return x + y\n+\n+ shape = (8, 10)\n+ x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n+ in_axis_resources = (P(\"x\"), P(\"x\"))\n+ out_axis_resources = None\n+ res_jax = pjit(\n+ func_jax,\n+ in_axis_resources=in_axis_resources,\n+ out_axis_resources=out_axis_resources)(x, x)\n+ module = get_serialized_computation(\n+ func_jax,\n+ x,\n+ x,\n+ use_pjit=True,\n+ in_axis_resources=in_axis_resources,\n+ out_axis_resources=out_axis_resources)\n+\n+ def f_tf(x_tf, y_tf):\n+ return tfxla.call_module([x_tf, y_tf],\n+ version=2,\n+ module=module,\n+ Tout=[x.dtype],\n+ Sout=[x.shape])\n+\n+ res_tf = tf.function(f_tf, jit_compile=True, autograph=False)(x, x)[0]\n+ self.assertAllClose(res_tf.numpy(), res_jax)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Move pjit test into the right TestCase class This test uses tfxla.call_module directly, belongs to XlaCallModuleTest.
260,411
28.12.2022 12:07:46
-7,200
1e09602c08e31ef7e9c210013b0bb89ee2b437d6
[jax2tf] Improve handling of dimension polynomials used with JAX arrays. See new description in README.md.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -518,11 +518,16 @@ def reshape_tf(x):\nreturn tf.reshape(x, [tf.math.multiply(4, b)])\n```\n-While operations among dimension polynomials and constants are handled\n-by the overloading described above, a different mechanism is used\n-for operations between JAX arrays and dimension polynomials.\n-In these cases,\n-`jax2tf` will try to convert dimension polynomials implicitly.\n+The following is the behavior of arithmetic operations involving\n+dimension polynomials depending on the type of the other operand:\n+\n+ * with another dimension polynomial or a constant convertible\n+ by `operator.index` will produce dimension polynomials or constants\n+ and can be used as dimension parameters, e.g., for `jnp.reshape`.\n+ * with a JAX array will involve an implicit cast to `jnp.array`\n+ and will produce JAX arrays, which cannot be used as dimension parameters.\n+ * with another type, e.g, `float`, will raise an error.\n+\nIn the function below the two occurrences of `x.shape[0]`\nare converted implicitly to `jnp.array(x.shape[0])` because\nthey are involved in JAX array operations:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/shape_poly.py", "new_path": "jax/experimental/jax2tf/shape_poly.py", "diff": "@@ -212,6 +212,24 @@ class _DimPolynomial():\nacc.update(mon.get_vars())\nreturn acc\n+ def eq(self, other: DimSize) -> bool:\n+ lb, ub = _ensure_poly(self - other, \"eq\").bounds()\n+ if lb == ub == 0:\n+ return True\n+ if lb is not None and lb > 0:\n+ return False\n+ if ub is not None and ub < 0:\n+ return False\n+ raise InconclusiveDimensionOperation(f\"Dimension polynomial comparison '{self}' == '{other}' is inconclusive\")\n+\n+ def ge(self, other: DimSize) -> bool:\n+ lb, ub = _ensure_poly(self - other, \"ge\").bounds()\n+ if lb is not None and lb >= 0:\n+ return True\n+ if ub is not None and ub < 0:\n+ return False\n+ raise InconclusiveDimensionOperation(f\"Dimension polynomial comparison '{self}' >= '{other}' is inconclusive\")\n+\ndef __hash__(self):\nreturn hash(tuple(sorted(self.monomials())))\n@@ -229,26 +247,49 @@ class _DimPolynomial():\nreturn str(self)\n# We overload , -, *, because they are fully defined for _DimPolynomial.\n- def __add__(self, other: DimSize) -> DimSize:\n+ def __add__(self, other):\n+ if isinstance(other, core.Tracer):\n+ return self.__jax_array__().__add__(other)\n+\n+ other = _ensure_poly(other, \"add\")\ncoeffs = self._coeffs.copy()\n- for mon, coeff in _ensure_poly(other).monomials():\n+ for mon, coeff in other.monomials():\ncoeffs[mon] = coeffs.get(mon, 0) + coeff\nreturn _DimPolynomial.from_coeffs(coeffs)\n- def __sub__(self, other: DimSize) -> DimSize:\n- return self + -other\n+ def __radd__(self, other):\n+ if isinstance(other, core.Tracer):\n+ return self.__jax_array__().__radd__(other)\n+ return _ensure_poly(other, \"add\").__add__(self)\n+\n+ def __sub__(self, other):\n+ if isinstance(other, core.Tracer):\n+ return self.__jax_array__().__sub__(other)\n+ return self + -_ensure_poly(other, \"sub\")\n+\n+ def __rsub__(self, other):\n+ if isinstance(other, core.Tracer):\n+ return self.__jax_array__().__rsub__(other)\n+ return _ensure_poly(other, \"sub\").__sub__(self)\ndef __neg__(self) -> '_DimPolynomial':\nreturn _DimPolynomial({mon: -coeff for mon, coeff in self.monomials()})\n- def __mul__(self, other: DimSize) -> DimSize:\n- other = _ensure_poly(other)\n+ def __mul__(self, other):\n+ if isinstance(other, core.Tracer):\n+ return self.__jax_array__().__mul__(other)\n+ other = _ensure_poly(other, \"mul\")\ncoeffs: Dict[_DimMon, int] = {}\nfor (mon1, coeff1), (mon2, coeff2) in itertools.product(self.monomials(), other.monomials()):\nmon = mon1.mul(mon2)\ncoeffs[mon] = coeffs.get(mon, 0) + coeff1 * coeff2\nreturn _DimPolynomial.from_coeffs(coeffs)\n+ def __rmul__(self, other):\n+ if isinstance(other, core.Tracer):\n+ return self.__jax_array__().__rmul__(other)\n+ return _ensure_poly(other, \"mul\").__mul__(self)\n+\ndef __pow__(self, power, modulo=None):\nassert modulo is None\ntry:\n@@ -257,44 +298,72 @@ class _DimPolynomial():\nraise InconclusiveDimensionOperation(f\"Dimension polynomial cannot be raised to non-integer power '{self}' ^ '{power}'\")\nreturn functools.reduce(op.mul, [self] * power)\n- def __rmul__(self, other: DimSize) -> DimSize:\n- return self * other # multiplication commutes\n+ def __floordiv__(self, divisor):\n+ if isinstance(divisor, core.Tracer):\n+ return self.__jax_array__().__floordiv__(divisor)\n+ return self.divmod(_ensure_poly(divisor, \"floordiv\"))[0]\n- def __radd__(self, other: DimSize) -> DimSize:\n- return self + other # addition commutes\n+ def __rfloordiv__(self, other):\n+ if isinstance(other, core.Tracer):\n+ return self.__jax_array__().__rfloordiv__(other)\n+ return _ensure_poly(other, \"floordiv\").__floordiv__(self)\n- def __rsub__(self, other: DimSize) -> DimSize:\n- return _ensure_poly(other) - self\n+ def __truediv__(self, divisor):\n+ # Used for \"/\"\n+ if isinstance(divisor, core.Tracer):\n+ return self.__jax_array__().__truediv__(divisor)\n+ q, r = self.divmod(_ensure_poly(divisor, \"truediv\"))\n+ if r != 0:\n+ raise InconclusiveDimensionOperation(\n+ self._division_error_msg(self, divisor,\n+ f\"Remainder is not zero: {r}\"))\n+ return q\n- def eq(self, other: DimSize) -> bool:\n- lb, ub = _ensure_poly(self - other).bounds()\n- if lb == ub == 0:\n- return True\n- if lb is not None and lb > 0:\n- return False\n- if ub is not None and ub < 0:\n- return False\n- raise InconclusiveDimensionOperation(f\"Dimension polynomial comparison '{self}' == '{other}' is inconclusive\")\n+ def __rtruediv__(self, dividend):\n+ # Used for \"/\", when dividend is not a _DimPolynomial\n+ if isinstance(dividend, core.Tracer):\n+ return self.__jax_array__().__rtruediv__(dividend)\n+ raise InconclusiveDimensionOperation(\n+ self._division_error_msg(dividend, self, \"Dividend must be a polynomial\"))\n+\n+ def __mod__(self, divisor):\n+ if isinstance(divisor, core.Tracer):\n+ return self.__jax_array__().__mod__(divisor)\n+ return self.divmod(_ensure_poly(divisor, \"mod\"))[1]\n+\n+ def __rmod__(self, dividend):\n+ if isinstance(dividend, core.Tracer):\n+ return self.__jax_array__().__rmod__(dividend)\n+ return _ensure_poly(dividend, \"mod\").__mod__(self)\n+\n+ def __divmod__(self, divisor):\n+ if isinstance(divisor, core.Tracer):\n+ return self.__jax_array__().__divmod__(divisor)\n+ return self.divmod(_ensure_poly(divisor, \"divmod\"))\n+\n+ def __rdivmod__(self, dividend):\n+ if isinstance(dividend, core.Tracer):\n+ return self.__jax_array__().__rdivmod__(dividend)\n+ return _ensure_poly(dividend, \"divmod\").__divmod__(self)\n+\n+ def __int__(self):\n+ if self.is_constant:\n+ return op.index(next(iter(self._coeffs.values())))\n+ else:\n+ raise InconclusiveDimensionOperation(f\"Dimension polynomial '{self}' used in a context that requires a constant\")\n# We must overload __eq__ and __ne__, or else we get unsound defaults.\n__eq__ = eq\ndef __ne__(self, other: DimSize) -> bool:\nreturn not self.eq(other)\n- def ge(self, other: DimSize) -> bool:\n- lb, ub = _ensure_poly(self - other).bounds()\n- if lb is not None and lb >= 0:\n- return True\n- if ub is not None and ub < 0:\n- return False\n- raise InconclusiveDimensionOperation(f\"Dimension polynomial comparison '{self}' >= '{other}' is inconclusive\")\n__ge__ = ge\ndef __le__(self, other: DimSize):\n- return _ensure_poly(other).__ge__(self)\n+ return _ensure_poly(other, \"le\").__ge__(self)\ndef __gt__(self, other: DimSize):\n- return not _ensure_poly(other).__ge__(self)\n+ return not _ensure_poly(other, \"gt\").__ge__(self)\ndef __lt__(self, other: DimSize):\nreturn not self.__ge__(other)\n@@ -306,7 +375,7 @@ class _DimPolynomial():\nmsg += \"\\nSee https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#division-of-shape-polynomials-is-partially-supported.\"\nreturn msg\n- def divmod(self, divisor: DimSize) -> Tuple[DimSize, int]:\n+ def divmod(self, divisor: \"_DimPolynomial\") -> Tuple[DimSize, int]:\n\"\"\"\nFloor division with remainder (divmod) generalized to polynomials.\nIf the `divisor` is not a constant, the remainder must be 0.\n@@ -315,7 +384,7 @@ class _DimPolynomial():\n:return: Quotient resulting from polynomial division and integer remainder.\n\"\"\"\n- divisor = _ensure_poly(divisor)\n+ assert isinstance(divisor, _DimPolynomial)\ndmon, dcount = divisor.leading_term\ndividend, quotient = self, 0\n# invariant: self = dividend + divisor * quotient\n@@ -351,40 +420,6 @@ class _DimPolynomial():\nassert self == divisor * quotient + remainder\nreturn quotient, remainder\n- def __floordiv__(self, divisor: DimSize) -> DimSize:\n- return self.divmod(divisor)[0]\n-\n- def __rfloordiv__(self, other):\n- return _ensure_poly(other).__floordiv__(self)\n-\n- def __truediv__(self, divisor: DimSize):\n- # Used for \"/\"\n- q, r = self.divmod(divisor)\n- if r != 0:\n- raise InconclusiveDimensionOperation(\n- self._division_error_msg(self, divisor,\n- f\"Remainder is not zero: {r}\"))\n- return q\n-\n- def __rtruediv__(self, dividend: DimSize):\n- # Used for \"/\", when dividend is not a _DimPolynomial\n- raise InconclusiveDimensionOperation(\n- self._division_error_msg(dividend, self, \"Dividend must be a polynomial\"))\n-\n- def __mod__(self, divisor: DimSize) -> int:\n- return self.divmod(divisor)[1]\n-\n- __divmod__ = divmod\n-\n- def __rdivmod__(self, other: DimSize) -> Tuple[DimSize, int]:\n- return _ensure_poly(other).divmod(self)\n-\n- def __int__(self):\n- if self.is_constant:\n- return op.index(next(iter(self._coeffs.values())))\n- else:\n- raise InconclusiveDimensionOperation(f\"Dimension polynomial '{self}' used in a context that requires a constant\")\n-\ndef bounds(self) -> Tuple[Optional[int], Optional[int]]:\n\"\"\"Returns the lower and upper bounds, if defined.\"\"\"\nlb = ub = self._coeffs.get(_DimMon(), 0) # The free coefficient\n@@ -424,9 +459,14 @@ class _DimPolynomial():\ncore.pytype_aval_mappings[_DimPolynomial] = _DimPolynomial.get_aval\nxla.pytype_aval_mappings[_DimPolynomial] = _DimPolynomial.get_aval\n-def _ensure_poly(p: DimSize) -> _DimPolynomial:\n+def _ensure_poly(p: DimSize,\n+ operation_name: str) -> _DimPolynomial:\nif isinstance(p, _DimPolynomial): return p\n+ try:\n+ p = op.index(p)\nreturn _DimPolynomial({_DimMon(): p})\n+ except:\n+ raise TypeError(f\"Dimension polynomial {operation_name} not supported for {p}\")\ndef is_poly_dim(p: DimSize) -> bool:\nreturn isinstance(p, _DimPolynomial)\n@@ -444,12 +484,12 @@ class DimensionHandlerPoly(core.DimensionHandler):\ndef symbolic_equal(self, d1: core.DimSize, d2: core.DimSize) -> bool:\ntry:\n- return _ensure_poly(d1) == d2\n+ return _ensure_poly(d1, \"equal\") == d2\nexcept InconclusiveDimensionOperation:\nreturn False\ndef greater_equal(self, d1: DimSize, d2: DimSize):\n- return _ensure_poly(d1) >= d2\n+ return _ensure_poly(d1, \"ge\") >= d2\ndef divide_shape_sizes(self, s1: Shape, s2: Shape) -> DimSize:\nsz1 = np.prod(s1)\n@@ -458,7 +498,7 @@ class DimensionHandlerPoly(core.DimensionHandler):\nreturn 1\nerr_msg = f\"Cannot divide evenly the sizes of shapes {tuple(s1)} and {tuple(s2)}\"\ntry:\n- q, r = _ensure_poly(sz1).divmod(sz2)\n+ q, r = _ensure_poly(sz1, \"divide_shape\").divmod(_ensure_poly(sz2, \"divide_shape\"))\nexcept InconclusiveDimensionOperation as e:\nraise InconclusiveDimensionOperation(err_msg + f\"\\nDetails: {e}\")\nif r != 0:\n@@ -469,7 +509,7 @@ class DimensionHandlerPoly(core.DimensionHandler):\n\"\"\"Implements `(d - window_size) // window_stride + 1`\"\"\"\ntry:\n# TODO(necula): check for d == 0 or window_size > d and return 0.\n- q, r = _ensure_poly(d - window_size).divmod(window_stride)\n+ q, r = _ensure_poly(d - window_size, \"stride\").divmod(_ensure_poly(window_stride, \"stride\"))\nreturn q + 1\nexcept InconclusiveDimensionOperation as e:\nraise InconclusiveDimensionOperation(\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": "@@ -1356,46 +1356,82 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[\"b1, b2, ...\"])(xv)\nself.assertAllClose(res_iter, res_vmap_tf.numpy())\n- def test_mean0(self):\n+ @parameterized.named_parameters([\n+ dict(testcase_name=f\"_{op_name}\",\n+ op=op)\n+ for op, op_name in [\n+ (jnp.array, \"array\"),\n+ (jnp.sin, \"sin\"),\n+ (lambda x: x, \"id\"),\n+ ]\n- def f_jax(x):\n- return jnp.sum(x, axis=0) / x.shape[0]\n+ ])\n+ def test_poly_unary_op(self, *, op=jnp.array):\n+ if config.jax_enable_x64:\n+ raise unittest.SkipTest(\"TODO(necula): dim_as_value in x64 mode\")\n+ if config.jax2tf_default_experimental_native_lowering:\n+ raise unittest.SkipTest(\"TODO(necula): dim_as_value in native mode\")\n+ def f_jax(x): # x: f32[b]\n+ poly = 2 * x.shape[0]\n+ return op(poly)\ncheck_shape_poly(self,\nf_jax,\n- arg_descriptors=[RandArg((3, 4), _f32)],\n+ arg_descriptors=[RandArg((3,), _f32)],\npoly_axes=[0],\n- expected_output_signature=tf.TensorSpec([4]))\n+ expected_output_signature=tf.TensorSpec([]))\n- def test_dimension_used_as_value(self):\n+ @parameterized.named_parameters([\n+ dict(testcase_name=f\"_{op.__name__}_order={order}\",\n+ op=op, order=order)\n+ for order in [\"poly_array\", \"array_poly\", \"poly_float\", \"float_poly\"]\n+ for op in [operator.add, operator.mul, operator.sub,\n+ operator.mod, operator.floordiv, operator.truediv]\n+ ])\n+ def test_poly_binary_op(self, *, op=operator.truediv, order=\"float_poly\"):\n+ # Test arithmetic operations with poly\nif config.jax2tf_default_experimental_native_lowering:\nraise unittest.SkipTest(\"TODO(necula): dim_as_value in native mode\")\n- def f_jax(x):\n- poly = x.shape[0]\n- x1 = jnp.array(poly) # Try explicit jnp.array on poly\n- x2 = x1 + poly # And implicit in binary operation\n- x3 = x2 + jnp.sin(poly) # In jnp operations # A list or tuple of poly in jnp operations\n- return x3.astype(np.float32)\n+ def f_jax(x): # x: f32[b]\n+ poly = 2 * x.shape[0]\n+ if order == \"poly_array\":\n+ return op(poly, jnp.array(3, dtype=np.int32))\n+ elif order == \"array_poly\":\n+ return op(jnp.array(3, dtype=np.int32), poly)\n+ elif order == \"poly_float\":\n+ return op(poly, 5.)\n+ elif order == \"float_poly\":\n+ return op(5., poly)\n+ else:\n+ assert False, order\n+\n+ with contextlib.ExitStack() as stack:\n+ if order in [\"poly_float\", \"float_poly\"]:\n+ if op.__name__ == \"truediv\" and order == \"float_poly\":\n+ stack.enter_context(\n+ self.assertRaisesRegex(shape_poly.InconclusiveDimensionOperation,\n+ \"Dividend must be a polynomial\"))\n+ else:\n+ stack.enter_context(\n+ self.assertRaisesRegex(TypeError,\n+ f\"Dimension polynomial {op.__name__} not supported for\"))\ncheck_shape_poly(self,\nf_jax,\narg_descriptors=[RandArg((3,), np.int32)],\npoly_axes=[0],\nexpected_output_signature=tf.TensorSpec([]))\n- def test_dimension_used_as_result(self):\n- if config.jax_enable_x64:\n- raise unittest.SkipTest(\"TODO(necula): dim_as_value in x64 mode\")\n- if config.jax2tf_default_experimental_native_lowering:\n- raise unittest.SkipTest(\"TODO(necula): dim_as_value in native mode\")\n- def f_jax(x):\n- return 2 * x.shape[0]\n+ def test_mean0(self):\n+ def f_jax(x): # x: f32[b, 4]\n+ return jnp.sum(x, axis=0) / x.shape[0]\ncheck_shape_poly(self,\nf_jax,\n- arg_descriptors=[RandArg((3,), np.int32)],\n+ arg_descriptors=[RandArg((3, 4), _f32)],\npoly_axes=[0],\n- expected_output_signature=tf.TensorSpec([]))\n+ expected_output_signature=tf.TensorSpec([4]))\n+\ndef test_shape_as_array(self):\ndef f_jax(x):\n@@ -1406,6 +1442,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nf_jax,\narg_descriptors=[RandArg((3, 4), _f32)],\npoly_axes=[0])\n+\ndef test_vmap_while(self):\ndef cond_func(x): # x: f32[3]\nreturn jnp.sum(x) >= 0.\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Improve handling of dimension polynomials used with JAX arrays. See new description in README.md.
260,411
28.12.2022 17:53:13
-7,200
9593741b731841cbf494409daf6630e2c939093d
[jax2tf] Fix lowering for tf.while_loop Sometimes TF infers more specific shapes for the init_carry, and this has led to errors: "enters the loop with shape (1,), but has shape (None,) after one iteration" Unfortunately, I cannot construct a small test.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -2751,7 +2751,12 @@ def _while(*args: TfVal, cond_nconsts: int, cond_jaxpr: core.ClosedJaxpr,\nbody_tf_func = partial(_interpret_jaxpr, body_jaxpr, *body_consts,\nextra_name_stack=\"while/body\")\n- return tf.while_loop(cond_tf_func, body_tf_func, init_carry)\n+ # Sometimes TF infers more specific shapes for the init_carry, and this has\n+ # led to errors: \"enters the loop with shape (1,), but has shape (None,) after one iteration\"\n+ shape_invariants = [tf.TensorShape(_aval_to_tf_shape(_out_aval))\n+ for _out_aval in body_jaxpr.out_avals]\n+ return tf.while_loop(cond_tf_func, body_tf_func, init_carry,\n+ shape_invariants=shape_invariants)\ndef _batched_cond_while(*args: TfVal, cond_nconsts: int,\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix lowering for tf.while_loop Sometimes TF infers more specific shapes for the init_carry, and this has led to errors: "enters the loop with shape (1,), but has shape (None,) after one iteration" Unfortunately, I cannot construct a small test.
260,411
20.12.2022 11:01:51
-7,200
71ce60012747bd4f4945a0c0c82ed57993c6d198
[jax2tf] Ensure that dim_as_value returns int64 in x64 mode and int32 otherwise Changes all the computations with dimensions to work in int64 if JAX_ENABLE_X64 and int32 otherwise.
[ { "change_type": "MODIFY", "old_path": "jax/_src/core.py", "new_path": "jax/_src/core.py", "diff": "@@ -1871,7 +1871,10 @@ def stride_shape(s: Shape, window_size: Shape, window_stride: Shape) -> Shape:\ndef dimension_as_value(d: DimSize):\n\"\"\"Turns a dimension size into a JAX value that we can compute with.\n- This is the identity function for constant dimensions.\"\"\"\n+ This is the identity function for constant dimensions.\n+\n+ Has the same abstract value as Python constants.\n+ \"\"\"\nif isinstance(d, Tracer): return d\nhandler, ds = _dim_handler_and_canonical(d)\nreturn handler.as_value(*ds)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "\"\"\"Experimental module transforms JAX functions to be executed by TensorFlow.\"\"\"\nfrom functools import partial, reduce\nimport contextlib\n+import operator\nimport os\nimport re\nimport threading\n@@ -962,6 +963,7 @@ def _tfval_to_tensor_jax_dtype(val: TfVal,\ndef _eval_shape(shape: Sequence[shape_poly.DimSize], dtype=None) -> Sequence[TfVal]:\n+ # Returns a tuple of shape_poly.dim_as_value_dtype\nassert all(map(lambda x: x is not None, shape)), (\nf\"Argument shape should be a valid JAX shape but got {shape}\")\nif dtype is not None:\n@@ -970,11 +972,12 @@ def _eval_shape(shape: Sequence[shape_poly.DimSize], dtype=None) -> Sequence[TfV\nreturn tuple(int(d) for d in shape)\ndim_vars, dim_values = util.unzip2(_thread_local_state.shape_env)\n- eval_shape_jax, dim_avals = shape_poly.get_shape_evaluator(dim_vars, shape)\n+ eval_shape_jax = shape_poly.get_shape_evaluator(dim_vars, shape)\n+ dim_aval = shape_poly.dim_as_value_abstract(1)\nshape_values_tf, _ = _interpret_fun_jax(eval_shape_jax,\n- dim_values, dim_avals, \"\") # type: ignore\n+ dim_values, [dim_aval] * len(dim_values), \"\") # type: ignore\n# Keep only the non-constant dimensions\n- return tuple(int(d) if core.is_constant_dim(d) else d_tf\n+ return tuple(operator.index(d) if core.is_constant_dim(d) else d_tf\nfor d, d_tf in zip(shape, shape_values_tf))\ndef _assert_matching_abstract_shape(x: TfVal, shape: Sequence[shape_poly.DimSize]):\n@@ -3179,10 +3182,15 @@ 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+def _dimension_size_jax2tf(op: TfVal, *, dimension, _in_avals, _out_aval):\n+ dim_tf = tf.shape(op)[dimension]\n+ if dim_tf.dtype != _to_tf_dtype(_out_aval.dtype):\n+ return _convert_element_type(dim_tf, new_dtype=_out_aval.dtype,\n+ weak_type=_out_aval.weak_type)\n+ else:\n+ return dim_tf\n-tf_impl[shape_poly.dimension_size_p] = _dimension_size_jax2tf\n+tf_impl_with_avals[shape_poly.dimension_size_p] = _dimension_size_jax2tf\ndef _dim_as_value_jax2tf(dim: shape_poly.DimSize):\ndim_tf, = _eval_shape((dim,))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/shape_poly.py", "new_path": "jax/experimental/jax2tf/shape_poly.py", "diff": "@@ -53,8 +53,8 @@ import numpy as np\nTfVal = Any\n# A dimension environment maps dimension variables to expressions that\n-# compute the value of the dimension. An expression must support addition\n-# and multiplication with other expressions or with np.int32, e.g.,\n+# compute the values of the dimension. An expression must support addition\n+# and multiplication with other expressions or with int32/int64, e.g.,\n# by overloading __add__, __radd__, __mul__, __rmul__.\nShapeEnv = Dict[str, Any]\nDType = Any\n@@ -144,7 +144,7 @@ class _DimMon(dict):\nreturn _DimMon(d)\ndef evaluate(self, env: ShapeEnv):\n- prod = lambda xs: functools.reduce(_evaluate_multiply, xs) if xs else np.int32(1)\n+ prod = lambda xs: functools.reduce(_evaluate_multiply, xs) if xs else dim_constant(1)\ndef 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@@ -443,14 +443,13 @@ class _DimPolynomial():\nreturn max(self.monomials())\ndef evaluate(self, env: ShapeEnv):\n- terms = [_evaluate_multiply(mon.evaluate(env), np.int32(coeff)) for mon, coeff in self.monomials()]\n+ # Evaluates as a value of dtype=dim_as_value_dtype()\n+ terms = [_evaluate_multiply(mon.evaluate(env), dim_constant(coeff)) for mon, coeff in self.monomials()]\nreturn functools.reduce(_evaluate_add, terms) if len(terms) > 1 else terms[0]\n@staticmethod\n- def get_aval(_: \"_DimPolynomial\"):\n- return core.ShapedArray((),\n- dtypes.canonicalize_dtype(np.int64),\n- weak_type=True)\n+ def get_aval(dim: \"_DimPolynomial\"):\n+ return dim_as_value_abstract(dim)\ndef __jax_array__(self):\n# Used for implicit coercions of polynomials as JAX arrays\n@@ -568,21 +567,32 @@ def _einsum_contract_path(*operands, **kwargs):\nlax_numpy._poly_einsum_handlers[_DimPolynomial] = _einsum_contract_path\n# A JAX primitive with no array arguments but with a dimension parameter\n-# that is a DimPoly. The value of the primitive is the value of the dimension.\n-# This primitive is used only in the context of jax2tf, so it does not need\n-# XLA translation rules.\n+# that is a DimPoly. The value of the primitive is the value of the dimension,\n+# using int64 in x64 mode or int32 otherwise (dim_as_value_dtype())\ndim_as_value_p = core.Primitive(\"dim_as_value\")\n-def _dim_as_value_abstract(dim: DimSize) -> core.AbstractValue:\n- return core.ShapedArray((), np.int32)\n+def dim_as_value_dtype():\n+ return dtypes.canonicalize_dtype(np.int64)\n-dim_as_value_p.def_abstract_eval(_dim_as_value_abstract)\n+def dim_constant(ct: int):\n+ return np.array(ct, dtype=dim_as_value_dtype())\n+\n+def dim_as_value_abstract(dim: DimSize) -> core.AbstractValue:\n+ return core.ShapedArray((), dim_as_value_dtype(), weak_type=True)\n+\n+dim_as_value_p.def_abstract_eval(dim_as_value_abstract)\ndef _dim_as_value(dim: DimSize):\nreturn dim_as_value_p.bind(dim=dim)\ndef _dim_as_value_lowering(ctx: mlir.LoweringRuleContext, *,\ndim):\n- return mlir.eval_dynamic_shape(ctx, (dim,))\n+ res, = mlir.eval_dynamic_shape(ctx, (dim,))\n+ out_type = mlir.aval_to_ir_type(ctx.avals_out[0])\n+ if out_type != res.type: # type: ignore\n+ return mlir.hlo.ConvertOp(out_type, res).results\n+ else:\n+ return [res]\n+\nmlir.register_lowering(dim_as_value_p, _dim_as_value_lowering)\n@@ -721,17 +731,17 @@ def _parse_spec(spec: Optional[Union[str, PolyShape]],\ndef _evaluate_add(v1, v2):\n- if isinstance(v1, (int, np.int32)) and v1 == 0:\n+ if isinstance(v1, (int, np.int32, np.int64)) and v1 == 0:\nreturn v2\n- elif isinstance(v2, (int, np.int32)) and v2 == 0:\n+ elif isinstance(v2, (int, np.int32, np.int64)) and v2 == 0:\nreturn v1\nelse:\nreturn v1 + v2\ndef _evaluate_multiply(v1, v2):\n- if isinstance(v1, (int, np.int32)) and v1 == 1:\n+ if isinstance(v1, (int, np.int32, np.int64)) and v1 == 1:\nreturn v2\n- elif isinstance(v2, (int, np.int32)) and v2 == 1:\n+ elif isinstance(v2, (int, np.int32, np.int64)) and v2 == 1:\nreturn v1\nelse:\nreturn v1 * v2\n@@ -753,15 +763,15 @@ def _is_known_constant(v) -> Optional[int]:\nreturn None\n# dimension_size(operand, dimension=i) get the operand.shape[i] as a\n-# JAX value.\n+# value of type shape_poly.dim_as_value_dtype().\ndimension_size_p = core.Primitive(\"dimension_size\")\ndef _dimension_size_abstract(aval: core.AbstractValue, **_) -> core.AbstractValue:\n- return core.ShapedArray((), np.int32)\n+ return dim_as_value_abstract(aval)\ndimension_size_p.def_abstract_eval(_dimension_size_abstract)\ndef _dimension_size_impl(arg, *, dimension):\n- return arg.shape[dimension]\n+ return dim_constant(arg.shape[dimension])\ndimension_size_p.def_impl(_dimension_size_impl)\n_JaxValue = Any\n@@ -770,17 +780,15 @@ _JaxValue = Any\nclass DimEquation:\n# Represents poly == _expr\npoly: _DimPolynomial\n- dim_expr: _JaxValue\n+ dim_expr: _JaxValue # Of type dim_as_value_dtype()\ndef get_shape_evaluator(dim_vars: Sequence[str], shape: Sequence[DimSize]) ->\\\n- Tuple[Callable, Sequence[core.AbstractValue]]:\n+ Callable[..., TfVal]:\n\"\"\"Prepares a shape evaluator.\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+ Returns a JAX function that given the values for the dimension variables\n+ returns the values for the dimensions of `shape`.\n\"\"\"\ndef eval_shape(*dim_values: Any) -> Sequence[Any]:\nshape_env_jax = dict(zip(dim_vars, dim_values))\n@@ -788,10 +796,9 @@ def get_shape_evaluator(dim_vars: Sequence[str], shape: Sequence[DimSize]) ->\\\ndef eval_dim(d: DimSize):\nreturn d.evaluate(shape_env_jax) # type: ignore[union-attr]\n- return tuple(eval_dim(d) if type(d) is _DimPolynomial else np.int32(d) # type: ignore\n+ return tuple(eval_dim(d) if type(d) is _DimPolynomial else np.array(d, dtype=dim_as_value_dtype()) # type: ignore\nfor d in shape)\n- return (eval_shape,\n- tuple(core.ShapedArray((), np.int32) for _ in dim_vars))\n+ return eval_shape\ndef arg_aval(\narg_shape: Sequence[Optional[int]],\n@@ -809,13 +816,15 @@ def arg_aval(\nreturn core.ShapedArray(aval_shape, arg_jax_dtype)\ndef prepare_dim_var_env(args_avals: Sequence[core.AbstractValue]) -> \\\n- Tuple[Sequence[str], Callable]:\n+ Tuple[Sequence[str],\n+ Callable[..., Sequence[TfVal]]]:\n\"\"\"Get the dimension variables and the function to compute them.\nReturns a tuple of dimension variables that appear in `args_avals` along\nwith a function that given the actual arguments of the top-level function\nreturns a tuple of dimension variable values, in the same order as the\n- dimension variables returns in the first component.\n+ dimension variables returned in the first component.\n+ The dimension variables are TfVal with type dim_as_value_dtype().\n\"\"\"\ndim_vars: Set[str] = set()\nfor a in args_avals:\n@@ -832,6 +841,7 @@ def prepare_dim_var_env(args_avals: Sequence[core.AbstractValue]) -> \\\npoly=d, dim_expr=dimension_size_p.bind(a, dimension=i)))\ndim_env = _solve_dim_equations(dim_equations)\n+ assert all(dim_env[dv].dtype == dim_as_value_dtype() for dv in dim_vars)\nreturn tuple(dim_env[dv] for dv in dim_vars)\nreturn tuple(dim_vars), get_dim_var_values\n@@ -860,7 +870,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 - _evaluate_multiply(mon_value, np.int32(factor))\n+ dim_expr = dim_expr - _evaluate_multiply(mon_value, dim_constant(factor))\ncontinue\nexcept KeyError:\n# There are some indeterminate variables. We handle only the case of\n@@ -874,10 +884,10 @@ def _solve_dim_equations(eqns: List[DimEquation]) -> ShapeEnv:\nif var is not None:\nif factor_var == 1:\n- var_value, var_remainder = dim_expr, np.int32(0)\n+ var_value, var_remainder = dim_expr, dim_constant(0)\nelse:\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+ var_value = lax.div(dim_expr, dim_constant(factor_var)) # type: ignore\n+ var_remainder = lax.rem(dim_expr, dim_constant(factor_var)) # type: ignore\n# Check that the division is even. Works only in eager mode.\nvar_remainder_int = _is_known_constant(var_remainder)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -21,6 +21,7 @@ import functools\nfrom functools import partial\nimport io\nimport itertools\n+import operator\nimport re\nimport typing\nfrom typing import (Any, Callable, Dict, Iterator, List, NamedTuple, Optional,\n@@ -576,20 +577,20 @@ class DimPolyEvaluator:\ndef __init__(self, value: ir.Value):\nself.value = value\n- def __add__(self, other: Union[np.int32, DimPolyEvaluator]):\n+ def __add__(self, other: Union[np.int32, np.int64, DimPolyEvaluator]):\nif not isinstance(other, DimPolyEvaluator):\nother = DimPolyEvaluator(ir_constant(other))\nreturn DimPolyEvaluator(hlo.AddOp(self.value, other.value).result)\n- def __radd__(self, other: np.int32):\n+ def __radd__(self, other: Union[np.int32, np.int64]):\nreturn DimPolyEvaluator(hlo.AddOp(ir_constant(other), self.value).result)\n- def __mul__(self, other: Union[np.int32, DimPolyEvaluator]):\n+ def __mul__(self, other: Union[np.int32, np.int64, DimPolyEvaluator]):\nif not isinstance(other, DimPolyEvaluator):\nother = DimPolyEvaluator(ir_constant(other))\nreturn DimPolyEvaluator(hlo.MulOp(self.value, other.value).result)\n- def __rmul__(self, other: np.int32):\n+ def __rmul__(self, other: Union[np.int32, np.int64]):\nreturn DimPolyEvaluator(hlo.MulOp(ir_constant(other), self.value).result)\n@@ -603,7 +604,7 @@ def eval_dynamic_shape(ctx: LoweringRuleContext,\nfor dv_name, dv_val in zip(ctx.module_context.dim_vars, ctx.dim_var_values)}\ndef eval_dim(d: core.DimSize) -> Union[int, ir.Value]:\ntry:\n- return int(d)\n+ return operator.index(d)\nexcept:\nif isinstance(d, ir.Value):\nreturn d\n@@ -866,7 +867,7 @@ def lower_jaxpr_to_fun(\nreturn aval_to_ir_types(aval)\nnum_dim_vars = len(ctx.dim_vars)\n- dim_var_types = map(aval_to_types, [core.ShapedArray((), np.int32)] * num_dim_vars)\n+ dim_var_types = map(aval_to_types, [core.ShapedArray((), dtypes.canonicalize_dtype(np.int64))] * num_dim_vars)\n# Function inputs: *dim_var_values, *tokens, *actual_inputs\ninput_types = map(aval_to_types, jaxpr.in_avals)\n@@ -1020,7 +1021,7 @@ def _emit_lowering_rule_as_fun(lowering_rule,\n\"\"\"Emits the contents of a lowering rule as a private function.\"\"\"\nnum_dim_vars = len(ctx.module_context.dim_vars)\n# TODO(necula) maybe only pass the dim_vars if they are needed?\n- dim_var_types = map(aval_to_ir_types, [core.ShapedArray((), np.int32)] * num_dim_vars)\n+ dim_var_types = map(aval_to_ir_types, [core.ShapedArray((), dtypes.canonicalize_dtype(np.int64))] * num_dim_vars)\ninput_types = map(aval_to_ir_types, ctx.avals_in)\noutput_types = map(aval_to_ir_types, ctx.avals_out)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Ensure that dim_as_value returns int64 in x64 mode and int32 otherwise Changes all the computations with dimensions to work in int64 if JAX_ENABLE_X64 and int32 otherwise.
260,510
28.12.2022 22:55:13
28,800
48eb39a9b893bede0d072eaf6bca5b51cb6c4f2a
Remove dummy recv in TPU callback lowering, seems like it is no longer necessary
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -1705,26 +1705,6 @@ def _emit_tpu_python_callback(\nrecv_channels = []\noutputs = []\n- # `send-to-host`s can be interleaved by the transfer manager so we add in a\n- # dummy recv to sequence them (the recv can only happen after all the sends\n- # are done). We'd like to send back a 0-shaped array to avoid unnecessary\n- # copies but that currently doesn't work with the transfer\n- # manager as well.\n- # TODO(b/238239458): enable sending back a 0-dim array\n- # TODO(b/238239928): avoid interleaving sends in the transfer manager\n- if not result_avals:\n- callback_without_return_values = _wrapped_callback\n- def _wrapped_callback(*args): # pylint: disable=function-redefined\n- callback_without_return_values(*args)\n- return (np.zeros(1, np.float32),)\n- recv_channel = ctx.module_context.new_channel()\n- dummy_recv_aval = core.ShapedArray((1,), np.float32)\n- result_shapes = [*result_shapes,\n- xla.aval_to_xla_shapes(dummy_recv_aval)[0]]\n- token, _ = receive_from_host(recv_channel, token, dummy_recv_aval,\n- callback.__name__, sharding=sharding)\n- recv_channels.append(recv_channel)\n- else:\nfor result_aval in result_avals:\nif any(s == 0 for s in result_aval.shape):\nraise NotImplementedError(\n" } ]
Python
Apache License 2.0
google/jax
Remove dummy recv in TPU callback lowering, seems like it is no longer necessary PiperOrigin-RevId: 498318923
260,511
30.12.2022 22:42:45
18,000
8df97ff2a304b20bd9730dc1aba4cd0e581314ed
Add `Optional` to `boundary` arg of `stft`.
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/signal.py", "new_path": "jax/_src/scipy/signal.py", "diff": "@@ -439,7 +439,7 @@ def _spectral_helper(x: Array, y: Optional[ArrayLike], fs: ArrayLike = 1.0,\n@_wraps(osp_signal.stft)\ndef stft(x: Array, fs: ArrayLike = 1.0, window: str = 'hann', nperseg: int = 256,\nnoverlap: Optional[int] = None, nfft: Optional[int] = None,\n- detrend: bool = False, return_onesided: bool = True, boundary: str = 'zeros',\n+ detrend: bool = False, return_onesided: bool = True, boundary: Optional[str] = 'zeros',\npadded: bool = True, axis: int = -1) -> Tuple[Array, Array, Array]:\nreturn _spectral_helper(x, None, fs, window, nperseg, noverlap,\nnfft, detrend, return_onesided,\n" } ]
Python
Apache License 2.0
google/jax
Add `Optional` to `boundary` arg of `stft`.
260,335
04.01.2023 08:25:57
28,800
4f7cf622d4410d88b600feadd3224c48fa0ba0ed
tweak remat named policies
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_checkpoint.py", "new_path": "jax/_src/ad_checkpoint.py", "diff": "@@ -71,8 +71,17 @@ def dot_with_no_batch_dims(prim, *_, **params) -> bool:\nname_p = core.Primitive('name')\n+def save_anything_except_these_names(*names_not_to_save):\n+ \"\"\"Save any values (not just named ones) excluding the names given.\"\"\"\n+ names_not_to_save = frozenset(names_not_to_save)\n+ def policy(prim, *_, **params):\n+ if prim is name_p:\n+ return params['name'] not in names_not_to_save\n+ return True # allow saving anything which is not named\n+ return policy\n+\ndef save_any_names_but_these(*names_not_to_save):\n- # Save named values, excluding the names given.\n+ \"\"\"Save only named values, excluding the names given.\"\"\"\nnames_not_to_save = frozenset(names_not_to_save)\ndef policy(prim, *_, **params):\nif prim is name_p:\n@@ -81,7 +90,7 @@ def save_any_names_but_these(*names_not_to_save):\nreturn policy\ndef save_only_these_names(*names_which_can_be_saved):\n- # Save named values, only among the names given.\n+ \"\"\"Save only named values, and only among the names given.\"\"\"\nnames_which_can_be_saved = set(names_which_can_be_saved)\ndef policy(prim, *_, **params):\nif prim is name_p:\n@@ -103,6 +112,7 @@ checkpoint_policies = types.SimpleNamespace(\nnothing_saveable=nothing_saveable,\ncheckpoint_dots=checkpoint_dots,\ncheckpoint_dots_with_no_batch_dims=dot_with_no_batch_dims,\n+ save_anything_except_these_names=save_anything_except_these_names,\nsave_any_names_but_these=save_any_names_but_these,\nsave_only_these_names=save_only_these_names,\nsave_from_both_policies=save_from_both_policies)\n" } ]
Python
Apache License 2.0
google/jax
tweak remat named policies
260,287
05.01.2023 03:09:22
28,800
f1635ca8757b72a0099ff586fb1719038c9599d5
Skip flaky test on TPU
[ { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -597,6 +597,7 @@ class EffectOrderingTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertListEqual(log, [2., 3.])\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_ordered_effect_remains_ordered_across_multiple_devices(self):\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n# supported\n" } ]
Python
Apache License 2.0
google/jax
Skip flaky test on TPU PiperOrigin-RevId: 499794466
260,287
05.01.2023 05:19:32
28,800
6655f2ba8d37a0d5ef59c30f732abddd10e8e996
Skip gather and reduce scatter grad tests on GPU Recent changes in XLA:GPU seem to be causing deadlocks.
[ { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -974,6 +974,8 @@ class PythonPmapTest(jtu.JaxTestCase):\n))\n@ignore_slow_all_to_all_warning()\ndef testGradOf(self, prim, tiled, use_axis_index_groups):\n+ if jtu.device_under_test() == \"gpu\":\n+ raise SkipTest(\"XLA:GPU with ReduceScatter deadlocks\") # b/264516146\naxis_index_groups = None\ndevices = jax.devices()\n" } ]
Python
Apache License 2.0
google/jax
Skip gather and reduce scatter grad tests on GPU Recent changes in XLA:GPU seem to be causing deadlocks. PiperOrigin-RevId: 499832080
260,424
05.01.2023 14:27:17
0
0fe159b67e4fda1921fd6124ea166365c532ed36
Make Shard.device and Shard.data read-only properties.
[ { "change_type": "MODIFY", "old_path": "jax/_src/array.py", "new_path": "jax/_src/array.py", "diff": "@@ -55,10 +55,10 @@ class Shard:\ndef __init__(self, device: Device, sharding: Sharding, global_shape: Shape,\ndata: Optional[ArrayImpl] = None):\n- self.device = device\n+ self._device = device\nself._sharding = sharding\nself._global_shape = global_shape\n- self.data = data\n+ self._data = data\ndef __repr__(self):\ntry:\n@@ -83,6 +83,14 @@ class Shard:\ndef replica_id(self) -> int:\nreturn device_replica_id_map(self._sharding, self._global_shape)[self.device]\n+ @property\n+ def device(self):\n+ return self._device\n+\n+ @property\n+ def data(self):\n+ return self._data\n+\ndef _reconstruct_array(fun, args, arr_state, aval_state):\n\"\"\"Method to reconstruct a device array from a serialized state.\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
Make Shard.device and Shard.data read-only properties.
260,424
05.01.2023 17:04:53
0
8a4b9d6aad72da965bbce52ffd8dba4ab740746f
Fix typo in checkify guide.
[ { "change_type": "MODIFY", "old_path": "docs/debugging/checkify_guide.md", "new_path": "docs/debugging/checkify_guide.md", "diff": "@@ -187,7 +187,7 @@ def f(x, i):\ncheckify.check(i >= 0, \"index needs to be non-negative!\")\nreturn x[i]\n-checked_f = checkify.checkify(f, errors=checkify.all_errors)\n+checked_f = checkify.checkify(f, errors=checkify.all_checks)\nerrs, out = jax.vmap(checked_f)(jnp.ones((3, 5)), jnp.array([-1, 2, 100]))\nerrs.throw()\n\"\"\"\n@@ -205,7 +205,7 @@ def f(x, i):\ncheckify.check(i >= 0, \"index needs to be non-negative!\")\nreturn x[i]\n-checked_f = checkify.checkify(f, errors=checkify.all_errors)\n+checked_f = checkify.checkify(f, errors=checkify.all_checks)\nerr, out = checked_f(jnp.ones((3, 5)), jnp.array([-1, 2, 100]))\nerr.throw()\n# ValueError: index needs to be non-negative! (check failed at <...>:2 (f))\n" } ]
Python
Apache License 2.0
google/jax
Fix typo in checkify guide.
260,411
08.01.2023 05:57:35
-7,200
2844f506492c0202dab5d085953c9452cf81c799
[jax2tf] Add more pjit tests In particular, add a test with a closed-over constant, to test for a pjit lowering behavior that will change soon.
[ { "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.\"\"\"\nimport collections\n+from functools import partial\nimport os\nfrom typing import Callable, Dict, Optional, Tuple\nimport unittest\n@@ -1230,6 +1231,25 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ninclude_xla_op_metadata=False\n)\n+ @jtu.with_mesh([(\"x\", 1)])\n+ def test_pjit_simple(self):\n+ @partial(pjit, in_axis_resources=(P(\"x\"), None), out_axis_resources=None)\n+ def func_jax(x, y):\n+ return x + y\n+\n+ self.ConvertAndCompare(func_jax, jnp.ones((3, 4), dtype=np.float32),\n+ jnp.ones((1, 1), dtype=np.float32))\n+\n+ @jtu.with_mesh([(\"x\", 1)])\n+ def test_pjit_closed_over_const(self):\n+ const = jnp.full((3, 4), 7, dtype=np.float32)\n+ @partial(pjit, in_axis_resources=(P(\"x\"), None), out_axis_resources=None)\n+ def func_jax(x, y):\n+ return x + y * const\n+\n+ self.ConvertAndCompare(func_jax, jnp.ones((3, 4), dtype=np.float32),\n+ jnp.ones((1, 1), dtype=np.float32))\n+\n# TODO(necula): figure out this failure\n@jtu.skip_on_flag(\"jax2tf_default_experimental_native_lowering\", True)\ndef test_global_device_array(self):\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Add more pjit tests In particular, add a test with a closed-over constant, to test for a pjit lowering behavior that will change soon.
260,717
10.01.2023 18:11:08
-32,400
41b9c5e8cdb1d4bf65b643c3f0a07922a74812cc
[docs] donate_argnums FAQ link to rst format
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -228,7 +228,7 @@ def jit(\narguments will not be donated.\nFor more details on buffer donation see the\n- [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\n+ `FAQ <https://jax.readthedocs.io/en/latest/faq.html#buffer-donation>`_.\ninline: Specify whether this function should be inlined into enclosing\njaxprs (rather than being represented as an application of the xla_call\n@@ -1774,7 +1774,7 @@ def pmap(\narguments will not be donated.\nFor more details on buffer donation see the\n- [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\n+ `FAQ <https://jax.readthedocs.io/en/latest/faq.html#buffer-donation>`_.\nglobal_arg_shapes: Optional, must be set when using pmap(sharded_jit) and\nthe partitioned values span multiple processes. The global cross-process\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/pjit.py", "new_path": "jax/_src/pjit.py", "diff": "@@ -283,7 +283,7 @@ def pjit(\nfor example recycling one of your input buffers to store a result. You\nshould not reuse buffers that you donate to a computation, JAX will raise\nan error if you try to.\n- For more details on buffer donation see the [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\n+ For more details on buffer donation see the `FAQ <https://jax.readthedocs.io/en/latest/faq.html#buffer-donation>`_.\nkeep_unused: If `False` (the default), arguments that JAX determines to be\nunused by `fun` *may* be dropped from resulting compiled XLA executables.\nSuch arguments will not be transferred to the device nor provided to the\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -371,7 +371,7 @@ def xmap(fun: Callable,\nshould not reuse buffers that you donate to a computation, JAX will raise\nan error if you try to.\n- For more details on buffer donation see the [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\n+ For more details on buffer donation see the `FAQ <https://jax.readthedocs.io/en/latest/faq.html#buffer-donation>`_.\nbackend: This is an experimental feature and the API is likely to change.\nOptional, a string representing the XLA backend. 'cpu', 'gpu', or 'tpu'.\n" } ]
Python
Apache License 2.0
google/jax
[docs] donate_argnums FAQ link to rst format
260,539
10.01.2023 09:14:10
28,800
7e395c9bbec6e9faa22eb4d553f57c20743fdaa0
DOC: add note about localhost & friends in jax.distributed.initialize
[ { "change_type": "MODIFY", "old_path": "jax/_src/distributed.py", "new_path": "jax/_src/distributed.py", "diff": "@@ -131,6 +131,8 @@ def initialize(coordinator_address: Optional[str] = None,\nport does not matter, so long as the port is available on the coordinator\nand all processes agree on the port.\nMay be ``None`` only on supported environments, in which case it will be chosen automatically.\n+ Note that special addresses like ``localhost`` or ``127.0.0.1`` usually mean that the program\n+ will bind to a local interface and are not suited when running in a multi-node environment.\nnum_processes: Number of processes. May be ``None`` only on supported environments, in\nwhich case it will be chosen automatically.\nprocess_id: The ID number of the current process. The ``process_id`` values across\n" } ]
Python
Apache License 2.0
google/jax
DOC: add note about localhost & friends in jax.distributed.initialize