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,411 | 31.08.2020 10:26:32 | -10,800 | b6b1f5e349a9e264324321f80bd3c16bf2ef71b7 | [jax2tf] Turn on with_gradient by default
As I was writing the demo I realized that it makes more sense for
with_gradient to be set to True by default.
I have also fixed a bug with tie_in in omnistaging. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -134,7 +134,7 @@ def _tfval_add_unit(vals: Sequence[TfValOrUnit],\ntf_impl: Dict[core.Primitive,\nCallable[..., Any]] = {}\n-def convert(fun, with_gradient=False):\n+def convert(fun, with_gradient=True):\n\"\"\"Transforms `fun` to be executed by TensorFlow.\nArgs:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -120,7 +120,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nwith_function=with_function)\nfor with_function in [False, True]))\ndef test_gradients_disabled(self, with_function=False):\n- f_tf = jax2tf.convert(jnp.tan)\n+ f_tf = jax2tf.convert(jnp.tan, with_gradient=False)\nif with_function:\nf_tf = tf.function(f_tf, autograph=False)\nx = tf.ones([])\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -73,7 +73,8 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nall_primitives = tuple(sorted(all_primitives, key=str))\nfor p in all_primitives:\n- if p.name == \"axis_index\":\n+ # TODO: remove tie_in once omnistaging is on by default\n+ if p.name == \"axis_index\" or p.name == \"tie_in\":\ncontinue\nif p in tf_not_yet_impl:\nself.assertNotIn(p, tf_impl) # Should not be in both tf_impl and tf_not_yet_impl\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"new_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"diff": "@@ -54,7 +54,7 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\ndef test_gradient_disabled(self):\nf_jax = lambda x: x * x\nmodel = tf.Module()\n- model.f = tf.function(jax2tf.convert(f_jax),\n+ model.f = tf.function(jax2tf.convert(f_jax, with_gradient=False),\nautograph=False,\ninput_signature=[tf.TensorSpec([], tf.float32)])\nx = np.array(0.7)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Turn on with_gradient by default (#4180)
As I was writing the demo I realized that it makes more sense for
with_gradient to be set to True by default.
I have also fixed a bug with tie_in in omnistaging. |
260,417 | 31.08.2020 17:00:34 | -10,800 | 44bcf7e776ad2dd0636db534905708293ea21ad6 | Fix axis checking and remove extra print statement
A series of PRs renaming the frame entries have been submitted, one of them introducing a bug when using omnistaging. This PR fixes that and removes a print comment (assuming added for debugging purposes). | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -142,7 +142,7 @@ class BatchTrace(Trace):\naxis_names = (axis_names,)\nfor i, axis_name in enumerate(axis_names):\nframe = core.axis_frame(axis_name)\n- if frame.tag is not self.main:\n+ if frame.main_trace is not self.main:\ncontinue\n# We run the split_axis rule with tracers, which is supposed to never\n# mix this axis name with another one. We will handle any invocations\n@@ -151,7 +151,6 @@ class BatchTrace(Trace):\nreturn split_axis(primitive, axis_name, tracers, params)\nvals_out, dims_out = collective_rules[primitive](vals_in, dims_in, frame.size, **params)\nresults = map(partial(BatchTracer, self), vals_out, dims_out)\n- print(results)\nreturn results if primitive.multiple_results else results[0]\n# TODO(mattjj,phawkins): if no rule implemented, could vmap-via-map here\nbatched_primitive = get_primitive_batcher(primitive)\n"
}
] | Python | Apache License 2.0 | google/jax | Fix axis checking and remove extra print statement (#4184)
A series of PRs renaming the frame entries have been submitted, one of them introducing a bug when using omnistaging. This PR fixes that and removes a print comment (assuming added for debugging purposes). |
260,298 | 01.09.2020 09:35:25 | -7,200 | 0cdb1f7ee603b9ac1764192355e6111a939c6d8b | [jax2tf] Indicate the version of TF used in tests in README. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -8,6 +8,8 @@ primitives using TensorFlow operations. In practice this means that you can take\nsome code written in JAX and execute it using TensorFlow eager mode, or stage it\nout as a TensorFlow graph.\n+As of today, the tests are run using `tf_nightly==2.4.0.dev20200829`.\n+\nMost commonly people want to use this tool in order to:\n1. Serialize JAX programs (and state) to disk as `tf.Graph`s.\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Indicate the version of TF used in tests in README. (#4185) |
260,335 | 01.09.2020 18:16:20 | 25,200 | 04f9a7e53db3eb0eb6d5d08a5f2a967bf9712048 | better jax.numpy.tile implementation
Use reshape, broadcast_to, reshape. | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2148,14 +2148,11 @@ def stack(arrays, axis=0):\ndef tile(A, reps):\nif isinstance(reps, int):\nreps = (reps,)\n- A = reshape(A, (1,) * (len(reps) - ndim(A)) + shape(A))\n- reps = (1,) * (ndim(A) - len(reps)) + tuple(reps)\n- for i, rep in enumerate(reps):\n- if rep == 0:\n- A = A[tuple(slice(0 if j == i else None) for j in range(A.ndim))]\n- elif rep != 1:\n- A = concatenate([A] * int(rep), axis=i)\n- return A\n+ A_shape = (1,) * (len(reps) - ndim(A)) + shape(A)\n+ reps = (1,) * (len(A_shape) - len(reps)) + tuple(reps)\n+ result = broadcast_to(reshape(A, [j for i in A_shape for j in [1, i]]),\n+ [k for pair in zip(reps, A_shape) for k in pair])\n+ return reshape(result, tuple(np.multiply(A_shape, reps)))\n@_wraps(np.concatenate)\ndef concatenate(arrays, axis=0):\n"
}
] | Python | Apache License 2.0 | google/jax | better jax.numpy.tile implementation (#4190)
Use reshape, broadcast_to, reshape. |
260,475 | 03.09.2020 00:13:17 | -3,600 | 708d07d5ff0f7910865ec179b1cef76f873ce3f0 | Add jax.numpy.array_split | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -67,6 +67,7 @@ Not every function in NumPy is implemented; contributions are welcome!\narray\narray_equal\narray_repr\n+ array_split\narray_str\nasarray\natleast_1d\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -22,7 +22,7 @@ from .lax_numpy import (\nComplexWarning, NINF, NZERO, PZERO, abs, absolute, add, all, allclose,\nalltrue, amax, amin, angle, any, append, arange, arccos, arccosh, arcsin,\narcsinh, arctan, arctan2, arctanh, argmax, argmin, argsort, argwhere, around,\n- array, array_equal, array_repr, array_str, asarray, atleast_1d, atleast_2d,\n+ array, array_equal, array_repr, array_split, array_str, asarray, atleast_1d, atleast_2d,\natleast_3d, average, bartlett, bfloat16, bincount, bitwise_and, bitwise_not,\nbitwise_or, bitwise_xor, blackman, block, bool_, broadcast_arrays,\nbroadcast_to, can_cast, cbrt, cdouble, ceil, character, clip, column_stack,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1486,27 +1486,34 @@ def broadcast_to(arr, shape):\nkept_dims = tuple(np.delete(np.arange(len(shape)), new_dims))\nreturn lax.broadcast_in_dim(squeeze(arr, tuple(diff)), shape, kept_dims)\n-\n-@_wraps(np.split)\n-def split(ary, indices_or_sections, axis=0):\n- axis = core.concrete_or_error(int, axis, \"in jax.numpy.split argument `axis`\")\n+def _split(op, ary, indices_or_sections, axis=0):\n+ axis = core.concrete_or_error(int, axis, f\"in jax.numpy.{op} argument `axis`\")\nsize = ary.shape[axis]\nif isinstance(indices_or_sections, (tuple, list) + _arraylike_types):\n- indices_or_sections = [core.concrete_or_error(int, i_s, \"in jax.numpy.split argument 1\")\n+ indices_or_sections = [core.concrete_or_error(int, i_s, f\"in jax.numpy.{op} argument 1\")\nfor i_s in indices_or_sections]\nsplit_indices = np.concatenate([[0], indices_or_sections, [size]])\nelse:\nindices_or_sections = core.concrete_or_error(int, indices_or_sections,\n- \"in jax.numpy.split argument 1\")\n+ f\"in jax.numpy.{op} argument 1\")\npart_size, r = _divmod(size, indices_or_sections)\n- if r != 0:\n- raise ValueError(\"array split does not result in an equal division\")\n+ if r == 0:\nsplit_indices = np.arange(indices_or_sections + 1) * part_size\n+ elif op == \"array_split\":\n+ split_indices = np.concatenate([np.arange(r + 1) * (part_size + 1),\n+ np.arange(indices_or_sections - r) * part_size\n+ + ((r + 1) * (part_size + 1) - 1)])\n+ else:\n+ raise ValueError(\"array split does not result in an equal division\")\nstarts, ends = [0] * ndim(ary), shape(ary)\n_subval = lambda x, i, v: subvals(x, [(i, v)])\nreturn [lax.slice(ary, _subval(starts, axis, start), _subval(ends, axis, end))\nfor start, end in zip(split_indices[:-1], split_indices[1:])]\n+@_wraps(np.split)\n+def split(ary, indices_or_sections, axis=0):\n+ return _split(\"split\", ary, indices_or_sections, axis=axis)\n+\ndef _split_on_axis(np_fun, axis):\n@_wraps(np_fun, update_doc=False)\ndef f(ary, indices_or_sections):\n@@ -1517,6 +1524,9 @@ vsplit = _split_on_axis(np.vsplit, axis=0)\nhsplit = _split_on_axis(np.hsplit, axis=1)\ndsplit = _split_on_axis(np.dsplit, axis=2)\n+@_wraps(np.array_split)\n+def array_split(ary, indices_or_sections, axis=0):\n+ return _split(\"array_split\", ary, indices_or_sections, axis=axis)\n@_wraps(np.clip)\ndef clip(a, a_min=None, a_max=None):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -2154,6 +2154,23 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_axis={}_{}sections\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), axis, num_sections),\n+ \"shape\": shape, \"num_sections\": num_sections, \"axis\": axis, \"dtype\": dtype}\n+ # All testcases split the specified axis unequally\n+ for shape, axis, num_sections in [\n+ ((3,), 0, 2), ((12,), 0, 5), ((12, 4), 0, 7), ((12, 4), 1, 3),\n+ ((2, 3, 5), -1, 2), ((2, 4, 4), -2, 3), ((7, 2, 2), 0, 3)]\n+ for dtype in default_dtypes))\n+ def testArraySplitStaticInt(self, shape, num_sections, axis, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ np_fun = lambda x: np.array_split(x, num_sections, axis=axis)\n+ jnp_fun = lambda x: jnp.array_split(x, num_sections, axis=axis)\n+ args_maker = lambda: [rng(shape, dtype)]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n+ self._CompileAndCheck(jnp_fun, args_maker)\n+\ndef testSplitTypeError(self):\n# If we pass an ndarray for indices_or_sections -> no error\nself.assertEqual(3, len(jnp.split(jnp.zeros(3), jnp.array([1, 2]))))\n"
}
] | Python | Apache License 2.0 | google/jax | Add jax.numpy.array_split (#4197) |
260,411 | 03.09.2020 14:18:35 | -10,800 | 5eac47726b4e02db4b909b56f97d8e1f767a14b4 | [jax2tf] Implementation of random_gamma
* [jax2tf] implementation of random_gamma
The simplest implementation is by converting the JAX own impl_rule,
which rewrites gamma into other JAX primitives.
On TPU with use_vmap=True the performance is the same for JAX and TF, provided
we use tf.function(compile=True). | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -134,7 +134,7 @@ def _tfval_add_unit(vals: Sequence[TfValOrUnit],\ntf_impl: Dict[core.Primitive,\nCallable[..., Any]] = {}\n-def convert(fun, with_gradient=True):\n+def convert(fun, with_gradient=False):\n\"\"\"Transforms `fun` to be executed by TensorFlow.\nArgs:\n@@ -218,6 +218,30 @@ def _interpret_fun(fun: lu.WrappedFun,\ndel main\nreturn out_vals\n+def _convert_jax_impl(jax_impl: Callable, multiple_results=True) -> Callable:\n+ \"\"\"Convert the JAX implementation of a primitive.\n+\n+ Args:\n+ jax_impl: typically the impl-rule for a primitive, with signature\n+ `(*args: JaxVal, **kwargs) -> Sequence[JaxVal]`. This function implements\n+ a primitive in terms of other primitives.\n+ multiple_results: whether `jax_impl` returns a sequence of results.\n+\n+ Returns:\n+ a function with signature `(*args: TfValOrUnit, **kwargs) -> Sequence[TfValOrUnit]`.\n+ \"\"\"\n+ def wrapped(*tf_args: TfValOrUnit, **kwargs) -> Union[TfValOrUnit, Sequence[TfValOrUnit]]:\n+\n+ # We wrap the jax_impl under _interpret_fun to abstract the TF values\n+ # from jax_impl and turn them into JAX abstract values.\n+ def jax_impl_jax_args(*jax_args):\n+ jax_results = jax_impl(*jax_args, **kwargs)\n+ return jax_results if multiple_results else [jax_results]\n+\n+ tf_results = _interpret_fun(lu.wrap_init(jax_impl_jax_args), tf_args)\n+ return tf_results if multiple_results else tf_results[0]\n+ return wrapped\n+\n@lu.transformation\ndef _interpret_subtrace(main: core.MainTrace, *in_vals: TfValOrUnit):\n@@ -402,7 +426,6 @@ tf_not_yet_impl = [\nlax_linalg.triangular_solve_p,\nlax.igamma_grad_a_p,\n- random.random_gamma_p,\nlax.random_gamma_grad_p,\n# Not high priority?\n@@ -1077,6 +1100,11 @@ def _threefry2x32(key1, key2, x1, x2):\ntf_impl[jax.random.threefry2x32_p] = _threefry2x32\n+# Use the vmap implementation, otherwise on TPU the performance is really bad\n+# With use_vmap=True on, we get about the same performance for JAX and jax2tf.\n+tf_impl[random.random_gamma_p] = _convert_jax_impl(\n+ functools.partial(random._gamma_impl, use_vmap=True),\n+ multiple_results=False)\ndef _gather_dimensions_proto(indices_shape, dimension_numbers):\nproto = xla_data_pb2.GatherDimensionNumbers()\n@@ -1326,16 +1354,8 @@ def _batched_cond_while(*args: TfValOrUnit,\ntf_impl[lax.while_p] = _while\n-\n-def _scan(*tf_args : TfValOrUnit, **kwargs) -> Sequence[TfValOrUnit]:\n- # We use the scan impl rule to rewrite in terms of while. We wrap it under\n- # _interpret_fun to abstract the TF values from scan_impl.\n- def func1(*jax_args):\n- return lax_control_flow._scan_impl(*jax_args, **kwargs)\n-\n- return _interpret_fun(lu.wrap_init(func1), tf_args)\n-\n-tf_impl[lax.scan_p] = _scan\n+# We use the scan impl rule to rewrite in terms of while.\n+tf_impl[lax.scan_p] = _convert_jax_impl(lax_control_flow._scan_impl)\ndef _top_k(operand: TfVal, k: int) -> Tuple[TfVal, TfVal]:\n# Some types originally incompatible with tf.math.top_k can be promoted\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -631,6 +631,14 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nvalues = np.array([True, False, True], dtype=np.bool_)\nself.ConvertAndCompare(f_jax, values)\n+ def test_random_gamma(self):\n+ f_jax = jax.jit(jax.random.gamma)\n+ for alpha in [1.0,\n+ np.array([1.0, 0.2, 1.2], np.float32),\n+ np.array([1.0, 0.2, 1.2], np.float64)]:\n+ for rng_key in [jax.random.PRNGKey(42)]:\n+ self.ConvertAndCompare(f_jax, rng_key, alpha)\n+\ndef test_prngsplit(self):\nf_jax = jax.jit(lambda key: jax.random.split(key, 2))\nfor rng_key in [jax.random.PRNGKey(42),\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -988,7 +988,7 @@ def _gamma_grad(sample, a):\ngrads = vmap(lax.random_gamma_grad)(alphas, samples)\nreturn grads.reshape(np.shape(a))\n-def _gamma_impl(key, a):\n+def _gamma_impl(key, a, use_vmap=False):\na_shape = jnp.shape(a)\n# split key to match the shape of a\nkey_ndim = jnp.ndim(key) - 1\n@@ -996,10 +996,11 @@ def _gamma_impl(key, a):\nkey = vmap(split, in_axes=(0, None))(key, prod(a_shape[key_ndim:]))\nkeys = jnp.reshape(key, (-1, 2))\nalphas = jnp.reshape(a, -1)\n- if xla_bridge.get_backend().platform == 'cpu':\n- samples = lax.map(lambda args: _gamma_one(*args), (keys, alphas))\n- else:\n+ if use_vmap:\nsamples = vmap(_gamma_one)(keys, alphas)\n+ else:\n+ samples = lax.map(lambda args: _gamma_one(*args), (keys, alphas))\n+\nreturn jnp.reshape(samples, a_shape)\ndef _gamma_batching_rule(batched_args, batch_dims):\n@@ -1014,7 +1015,12 @@ random_gamma_p = core.Primitive('random_gamma')\nrandom_gamma_p.def_impl(_gamma_impl)\nrandom_gamma_p.def_abstract_eval(lambda key, a: abstract_arrays.raise_to_shaped(a))\nad.defjvp2(random_gamma_p, None, lambda tangent, ans, key, a: tangent * _gamma_grad(ans, a))\n-xla.translations[random_gamma_p] = xla.lower_fun(_gamma_impl, multiple_results=False)\n+xla.translations[random_gamma_p] = xla.lower_fun(\n+ partial(_gamma_impl, use_vmap=True),\n+ multiple_results=False)\n+xla.backend_specific_translations['cpu'][random_gamma_p] = xla.lower_fun(\n+ partial(_gamma_impl, use_vmap=False),\n+ multiple_results=False)\nbatching.primitive_batchers[random_gamma_p] = _gamma_batching_rule\ndef gamma(key, a, shape=None, dtype=dtypes.float_):\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Implementation of random_gamma (#4192)
* [jax2tf] implementation of random_gamma
The simplest implementation is by converting the JAX own impl_rule,
which rewrites gamma into other JAX primitives.
On TPU with use_vmap=True the performance is the same for JAX and TF, provided
we use tf.function(compile=True). |
260,411 | 03.09.2020 14:24:04 | -10,800 | abdd13884b066a54413af1627f8e490cd4642306 | [jax2tf] Flip the with_gradient=True; was flipped back by mistake | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -134,7 +134,7 @@ def _tfval_add_unit(vals: Sequence[TfValOrUnit],\ntf_impl: Dict[core.Primitive,\nCallable[..., Any]] = {}\n-def convert(fun, with_gradient=False):\n+def convert(fun, with_gradient=True):\n\"\"\"Transforms `fun` to be executed by TensorFlow.\nArgs:\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Flip the with_gradient=True; was flipped back by mistake (#4200) |
260,298 | 03.09.2020 15:56:22 | -7,200 | bcf9777baca50d22f99b8adc45c472aecceaf33a | [jax2tf] Generator for the documentation of operations with limited support (WIP)
* [jax2tf] Draft of a generator for the documentation of operations
with limited support. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "import functools\nimport string\n-from typing import Any, Callable, Dict, Iterable, Sequence, Tuple, Union\n+from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, Union\nimport jax\nfrom jax import abstract_arrays\n@@ -126,6 +126,110 @@ def _tfval_add_unit(vals: Sequence[TfValOrUnit],\nreturn core.unit if aval is core.abstract_unit else v\nreturn util.safe_map(add_unit, vals, avals)\n+\n+Limitation = NamedTuple(\"Limitation\", [ (\"PrimitiveName\", str)\n+ , (\"ErrorType\", str)\n+ , (\"ErrorString\", str)\n+ , (\"Devices\", Tuple[str,...])\n+ ])\n+\n+def categorize(prim: core.Primitive, *args: TfVal, **kwargs) \\\n+ -> List[Limitation]:\n+ \"\"\"\n+ Given a primitive and a set of parameters one would like to pass to it,\n+ categorize identifies the potential limitations the call would encounter when\n+ converted to TF through jax2tf.\n+\n+ Args:\n+ prim: the primitive to call.\n+ args: the arguments to pass to prim.\n+ kwargs: the keyword arguments to pass to prim.\n+\n+ Returns:\n+ A list of limitations\n+ \"\"\"\n+ limitations: List[Limitation] = []\n+ all_devices = [\"CPU\", \"GPU\", \"TPU\"]\n+\n+ def _report_failure(error_type: str, msg: str,\n+ devs: Sequence[str] = all_devices) -> None:\n+ limitations.append(Limitation(prim.name, error_type, msg, tuple(devs)))\n+\n+ tf_unimpl = functools.partial(_report_failure, \"Missing TF support\")\n+\n+ def _to_np_dtype(dtype):\n+ try:\n+ dtype = to_jax_dtype(dtype)\n+ except:\n+ pass\n+ return np.dtype(dtype)\n+\n+ if prim in [lax.min_p, lax.max_p]:\n+ np_dtype = _to_np_dtype(args[0].dtype)\n+ if np_dtype in [np.bool_, np.int8, np.uint16, np.uint32, np.uint64,\n+ np.complex64, np.complex128]:\n+ tf_unimpl(f\"{prim.name} is unimplemented for dtype {np_dtype}\")\n+\n+ if prim in [lax.rem_p, lax.atan2_p]:\n+ # b/158006398: TF kernels are missing for 'rem' and 'atan2'\n+ np_dtype = _to_np_dtype(args[0].dtype)\n+ if np_dtype in [np.float16, dtypes.bfloat16]:\n+ tf_unimpl(f\"Missing TF kernels for {prim.name} with dtype {np_dtype}\")\n+\n+ if prim is lax.nextafter_p:\n+ np_dtype = _to_np_dtype(args[0].dtype)\n+ if np_dtype in [np.float16, dtypes.bfloat16]:\n+ tf_unimpl(f\"{prim.name} is unimplemented for dtype {np_dtype}\")\n+\n+ return limitations\n+\n+def prettify(limitations: Sequence[Limitation]) -> str:\n+ \"\"\"Constructs a summary .md file based on a list of limitations.\"\"\"\n+ limitations = sorted(list(set(limitations)))\n+\n+ def _pipewrap(columns):\n+ return '| ' + ' | '.join(columns) + ' |'\n+\n+ title = '# Primitives with limited support'\n+\n+ column_names = [ 'Affected primitive'\n+ , 'Type of limitation'\n+ , 'Description'\n+ , 'Devices affected' ]\n+\n+ table = [column_names, ['---'] * len(column_names)]\n+\n+ for lim in limitations:\n+ table.append([ lim.PrimitiveName\n+ , lim.ErrorType\n+ , lim.ErrorString\n+ , ', '.join(lim.Devices)\n+ ])\n+\n+ return title + '\\n\\n' + '\\n'.join(line for line in map(_pipewrap, table))\n+\n+def pprint_limitations(limitations: Sequence[Limitation],\n+ output_file: Optional[str] = None) -> None:\n+ output = prettify(limitations)\n+ if output_file:\n+ with open(output_file, 'w') as f:\n+ f.write(output)\n+ else:\n+ print(output)\n+\n+all_limitations: Sequence[Limitation] = []\n+pprint_all_limitations = functools.partial(pprint_limitations, all_limitations)\n+\n+def collect_limitations(prim: core.Primitive, func: Callable) -> Callable:\n+ \"\"\"\n+ Wraps a primitive and its corresponding TF implementation with `categorize`.\n+ \"\"\"\n+ def wrapper(*args, **kwargs):\n+ global all_limitations\n+ all_limitations += categorize(prim, *args, **kwargs)\n+ return func(*args, **kwargs)\n+ return wrapper\n+\n# The implementation rules for primitives. The rule will be called with the\n# arguments (TfValOrUnit) and must return TfValOrUnit (or a sequence thereof,\n# if primitive.multiple_results). The vast majority of primitives do not need\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "+# Primitives with limited support\n+\n+| Affected primitive | Type of limitation | Description | Devices affected |\n+| --- | --- | --- | --- |\n+| atan2 | Missing TF support | Missing TF kernels for atan2 with dtype bfloat16 | CPU, GPU, TPU |\n+| atan2 | Missing TF support | Missing TF kernels for atan2 with dtype float16 | CPU, GPU, TPU |\n+| max | Missing TF support | max is unimplemented for dtype bool | CPU, GPU, TPU |\n+| max | Missing TF support | max is unimplemented for dtype complex64 | CPU, GPU, TPU |\n+| max | Missing TF support | max is unimplemented for dtype int8 | CPU, GPU, TPU |\n+| max | Missing TF support | max is unimplemented for dtype uint16 | CPU, GPU, TPU |\n+| max | Missing TF support | max is unimplemented for dtype uint32 | CPU, GPU, TPU |\n+| min | Missing TF support | min is unimplemented for dtype bool | CPU, GPU, TPU |\n+| min | Missing TF support | min is unimplemented for dtype complex64 | CPU, GPU, TPU |\n+| min | Missing TF support | min is unimplemented for dtype int8 | CPU, GPU, TPU |\n+| min | Missing TF support | min is unimplemented for dtype uint16 | CPU, GPU, TPU |\n+| min | Missing TF support | min is unimplemented for dtype uint32 | CPU, GPU, TPU |\n+| nextafter | Missing TF support | nextafter is unimplemented for dtype bfloat16 | CPU, GPU, TPU |\n+| nextafter | Missing TF support | nextafter is unimplemented for dtype float16 | CPU, GPU, TPU |\n+| rem | Missing TF support | Missing TF kernels for rem with dtype bfloat16 | CPU, GPU, TPU |\n+| rem | Missing TF support | Missing TF kernels for rem with dtype float16 | CPU, GPU, TPU |\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -402,25 +402,11 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_min_max)\ndef test_min_max(self, harness: primitive_harness.Harness):\n- expect_tf_exceptions = False\n- dtype = harness.params[\"dtype\"]\n-\n- if dtype in [np.bool_, np.int8, np.uint16, np.uint32, np.uint64,\n- np.complex64, np.complex128]:\n- # TODO(bchetioui): tf.math.maximum and tf.math.minimum are not defined for\n- # the above types.\n- expect_tf_exceptions = True\n-\n- self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n- expect_tf_exceptions=expect_tf_exceptions)\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@primitive_harness.parameterized(primitive_harness.lax_binary_elementwise)\ndef test_binary_elementwise(self, harness):\nlax_name, dtype = harness.params[\"lax_name\"], harness.params[\"dtype\"]\n- if lax_name in (\"rem\", \"atan2\"):\n- # b/158006398: TF kernels are missing for 'rem' and 'atan2'\n- if dtype in [np.float16, dtypes.bfloat16]:\n- raise unittest.SkipTest(\"TODO: TF kernels are missing for {lax_name}.\")\nif lax_name in (\"igamma\", \"igammac\"):\n# TODO(necula): fix bug with igamma/f16\nif dtype in [np.float16, dtypes.bfloat16]:\n@@ -428,12 +414,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# TODO(necula): fix bug with igamma/f32 on TPU\nif dtype is np.float32 and jtu.device_under_test() == \"tpu\":\nraise unittest.SkipTest(\"TODO: fix bug: nan vs not-nan\")\n- # TODO(necula): fix bug with nextafter/f16\n- # See https://www.tensorflow.org/api_docs/python/tf/math/nextafter, params to\n- # nextafter can only be float32/float64.\n- if (lax_name == \"nextafter\" and\n- dtype in [np.float16, dtypes.bfloat16]):\n- raise unittest.SkipTest(\"TODO: nextafter not supported for (b)float16 in TF\")\narg1, arg2 = harness.dyn_args_maker(self.rng())\ncustom_assert = None\nif lax_name == \"igamma\":\n@@ -474,6 +454,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ndef test_betainc(self, harness: primitive_harness.Harness):\n# TODO: https://www.tensorflow.org/api_docs/python/tf/math/betainc only supports\n# float32/64 tests.\n+ # TODO(bchetioui): investigate why the test actually fails in JAX.\nif harness.params[\"dtype\"] in [np.float16, dtypes.bfloat16]:\nraise unittest.SkipTest(\"(b)float16 not implemented in TF\")\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"new_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import atexit\nimport contextlib\nimport logging\nimport numpy as np\n@@ -25,8 +26,21 @@ from jax.experimental import jax2tf\nfrom jax import test_util as jtu\nfrom jax import numpy as jnp\n-class JaxToTfTestCase(jtu.JaxTestCase):\n+import os\n+\n+# Monkey-patch jax2tf.TensorFlowTrace.get_primitive_impl to wrap the\n+# resulting primitive in the categorizer.\n+original_impl = jax2tf.jax2tf.TensorFlowTrace.get_primitive_impl\n+wrapper = jax2tf.jax2tf.collect_limitations\n+jax2tf.jax2tf.TensorFlowTrace.get_primitive_impl = ( # type: ignore\n+ lambda s, p: wrapper(p, original_impl(s, p)))\n+if os.getenv('JAX2TF_CATEGORIZE_OUT'):\n+ output_file = os.path.join(os.path.dirname(__file__),\n+ '../primitives_with_limited_support.md')\n+ atexit.register(jax2tf.jax2tf.pprint_all_limitations, output_file)\n+\n+class JaxToTfTestCase(jtu.JaxTestCase):\ndef setUp(self):\nsuper().setUp()\n# Ensure that all TF ops are created on the proper device (TPU or GPU or CPU)\n@@ -111,14 +125,27 @@ class JaxToTfTestCase(jtu.JaxTestCase):\nelse:\nassert False\n+ def is_tf_exception(lim: jax2tf.jax2tf.Limitation):\n+ return (lim.ErrorType == 'Missing TF support' and\n+ self.tf_default_device.device_type in lim.Devices)\n+\nresult_tf = None\nfor mode in (\"eager\", \"graph\", \"compiled\"):\n+ current_limitations = jax2tf.jax2tf.all_limitations[:]\ntry:\nresult_tf = run_tf(mode)\nexcept Exception as e:\n- if not expect_tf_exceptions:\n+ new_limitations = (\n+ jax2tf.jax2tf.all_limitations[len(current_limitations):])\n+ detected_tf_exception = any(map(is_tf_exception, new_limitations))\n+\n+ if not (expect_tf_exceptions or detected_tf_exception):\nraise e\nelse:\n+ for lim in new_limitations:\n+ print(\"Detected limitation: {} for {} devices.\"\n+ .format(lim.ErrorString, ', '.join(lim.Devices)))\n+\nprint(f\"Encountered expected exception for mode={mode}: {e}\")\ncontinue\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Generator for the documentation of operations with limited support (WIP) (#4193)
* [jax2tf] Draft of a generator for the documentation of operations
with limited support. |
260,680 | 04.09.2020 19:21:43 | -10,800 | 96278e67a23c3c43afa790c4ec58c7923e0003b7 | Add reverse flag in associative scan
Add optional 'reverse' argument in associative scan | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -2324,7 +2324,7 @@ def _interleave(a, b):\nreturn jnp.reshape(jnp.stack([a, b], axis=1),\n(2 * half_num_elems,) + a.shape[1:])\n-def associative_scan(fn, elems):\n+def associative_scan(fn, elems, reverse=False):\n\"\"\"Perform a scan with an associative binary operation, in parallel.\nArgs:\n@@ -2338,6 +2338,8 @@ def associative_scan(fn, elems):\nshape (and structure) as the two inputs ``a`` and ``b``.\nelems: A (possibly nested structure of) array(s), each with leading\ndimension ``num_elems``.\n+ reverse: A boolean stating if the scan should be reversed with respect to\n+ the leading dimension.\nReturns:\nresult: A (possibly nested structure of) array(s) of the same shape\n@@ -2357,9 +2359,17 @@ def associative_scan(fn, elems):\n>>> partial_prods = lax.associative_scan(jnp.matmul, mats)\n>>> partial_prods.shape\n(4, 2, 2)\n+\n+ Example 3: reversed partial sums of an array of numbers\n+\n+ >>> lax.associative_scan(jnp.add, jnp.arange(0, 4), reverse=True)\n+ [ 6, 6, 5, 3]\n\"\"\"\nelems_flat, tree = tree_flatten(elems)\n+ if reverse:\n+ elems_flat = [lax.rev(elem, [0]) for elem in elems_flat]\n+\ndef lowered_fn(a_flat, b_flat):\n# Lower `fn` to operate on flattened sequences of elems.\na = tree_unflatten(tree, a_flat)\n@@ -2434,6 +2444,9 @@ def associative_scan(fn, elems):\nscans = _scan(elems_flat)\n+ if reverse:\n+ scans = [lax.rev(scanned, [0]) for scanned in scans]\n+\nreturn tree_unflatten(tree, scans)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -2386,6 +2386,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nresult = lax.associative_scan(operator.add, data)\nself.assertAllClose(result, expected, check_dtypes=False)\n+ def testAssociativeScanUnstructured1000Reverse(self):\n+ data = np.arange(1000)\n+ expected = np.cumsum(data[::-1])[::-1]\n+ result = lax.associative_scan(operator.add, data, reverse=True)\n+ self.assertAllClose(result, expected, check_dtypes=False)\n+\ndef testAssociativeScanStructured3(self):\npair = collections.namedtuple('pair', ('first', 'second'))\ndata = pair(first=np.array([0., 1., 2.]),\n"
}
] | Python | Apache License 2.0 | google/jax | Add reverse flag in associative scan (#4181)
Add optional 'reverse' argument in associative scan |
260,411 | 07.09.2020 14:41:50 | -10,800 | 1e84cbe9cc68ec893e789afa00948971f5b01ff0 | [jax2tf] Fix random.split when jax_exable_x64
Since we do the threefry with signed integers when converting to TF,
we run into the type promotion 'uint32 - int32 = int64', which
then results in lax.shift_right_logical(uint32, int64), which fails. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -617,8 +617,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\nrtol=1e-5)\n- @primitive_harness.parameterized(primitive_harness.random_split,\n- one_containing=\"i=0\")\n+ @primitive_harness.parameterized(primitive_harness.random_split)\ndef test_random_split(self, harness: primitive_harness.Harness):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -112,8 +112,10 @@ def _make_rotate_left(dtype):\nnbits = np.array(jnp.iinfo(dtype).bits, dtype)\ndef _rotate_left(x, d):\n- if lax.dtype(d) != lax.dtype(x):\n- d = lax.convert_element_type(d, x.dtype)\n+ if lax.dtype(d) != dtype:\n+ d = lax.convert_element_type(d, dtype)\n+ if lax.dtype(x) != dtype:\n+ x = lax.convert_element_type(x, dtype)\nreturn lax.shift_left(x, d) | lax.shift_right_logical(x, nbits - d)\nreturn _rotate_left\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix random.split when jax_exable_x64 (#4208)
Since we do the threefry with signed integers when converting to TF,
we run into the type promotion 'uint32 - int32 = int64', which
then results in lax.shift_right_logical(uint32, int64), which fails. |
260,411 | 07.09.2020 17:13:11 | -10,800 | 4413bb8a4f0bd8fb5ffd6ace5ca09f63fe3eac28 | [jax2tf] Do not use jax.random.PRNGKey before in primitive harness
We cannot execute JAX functions before the program is initialized | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -848,7 +848,7 @@ lax_reduce_window = tuple(\nrandom_gamma = tuple(\nHarness(f\"_shape={jtu.format_shape_dtype_string(shape, dtype)}\",\njax.jit(jax.random.gamma),\n- [jax.random.PRNGKey(42), RandArg(shape, dtype)])\n+ [np.array([42, 43], dtype=np.uint32), RandArg(shape, dtype)])\nfor shape in ((), (3,))\nfor dtype in (np.float32, np.float64)\n)\n@@ -857,8 +857,8 @@ random_split = tuple(\nHarness(f\"_i={key_i}\",\njax.jit(lambda key: jax.random.split(key, 2)),\n[key])\n- for key_i, key in enumerate([jax.random.PRNGKey(42),\n- np.array([0, 0], dtype=np.uint32),\n+ for key_i, key in enumerate([np.array([0, 0], dtype=np.uint32),\n+ np.array([42, 43], dtype=np.uint32),\nnp.array([0xFFFFFFFF, 0], dtype=np.uint32),\nnp.array([0, 0xFFFFFFFF], dtype=np.uint32),\nnp.array([0xFFFFFFFF, 0xFFFFFFFF], dtype=np.uint32)])\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Do not use jax.random.PRNGKey before in primitive harness (#4211)
We cannot execute JAX functions before the program is initialized |
260,287 | 07.09.2020 12:31:58 | 0 | 0aed1f4ddf1863f151cb7e4a2c5473df8dddba50 | Add more context to the axis_frame error message.
Some of the vmap and gmap collective tests have been failing on master
and I can't seem to be able to reproduce them locally. Hopefully, if
this happens again, this extra bit of information will be useful in
debugging the problem. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1588,4 +1588,5 @@ def omnistaging_enabler() -> None:\nif frame.name == axis_name:\nreturn frame\nelse:\n- raise NameError(\"unbound axis name: {}\".format(axis_name))\n+ raise NameError(f\"Unbound axis name: {axis_name}.\\n\"\n+ f\"The currently bound axes are: {[f.name for f in frames]}\")\n"
}
] | Python | Apache License 2.0 | google/jax | Add more context to the axis_frame error message.
Some of the vmap and gmap collective tests have been failing on master
and I can't seem to be able to reproduce them locally. Hopefully, if
this happens again, this extra bit of information will be useful in
debugging the problem. |
260,298 | 07.09.2020 17:12:35 | -7,200 | e1340f3495619d260c31c41e45418e41165937f0 | [jax2tf] Fix missing complex64 TPU corner case of scatter_{add,mul} | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "| reduce_window_sum | Missing TF support | reduce_window_sum is unimplemented for dtype uint32 | CPU, GPU, TPU |\n| rem | Missing TF support | rem is unimplemented for dtype bfloat16 | CPU, GPU, TPU |\n| rem | Missing TF support | rem is unimplemented for dtype float16 | CPU, GPU, TPU |\n+| scatter-add | Missing TF support | scatter-add is unimplemented for dtype complex64 | TPU |\n+| scatter-mul | Missing TF support | scatter-mul is unimplemented for dtype complex64 | TPU |\n| select_and_gather_add | Missing TF support | select_and_gather_add is unimplemented for dtype float32 | TPU |\n| svd | Missing TF support | svd is unimplemented for dtype complex64; this works on JAX because JAX uses a custom implementation | CPU, GPU |\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "@@ -129,6 +129,11 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\n# TODO(bchetioui): tf.math.multiply is not defined for the above types.\ntf_unimpl(np_dtype)\n+ if prim in [lax.scatter_mul_p, lax.scatter_add_p]:\n+ np_dtype = _to_np_dtype(args[0].dtype)\n+ if np_dtype == np.complex64:\n+ tf_unimpl(np_dtype, devs=[\"TPU\"])\n+\nreturn limitations\ndef prettify(limitations: Sequence[Limitation]) -> str:\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix missing complex64 TPU corner case of scatter_{add,mul} (#4213) |
260,298 | 08.09.2020 10:32:53 | -7,200 | 798a2648f55fc35bf58e2022cd38a1cf03229309 | [jax2tf] Fix bug in population count and move expect_tf_exception
into correctness stats.
The code was using `tf.bitcast` instead of `tf.cast`, but using
`expect_tf_exception` in every case was hiding the errors. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -454,7 +454,7 @@ tf_impl[lax.nextafter_p] = tf.math.nextafter\ndef _population_count(x):\norig_dtype = x.dtype\n- return tf.bitcast(tf.raw_ops.PopulationCount(x=x), orig_dtype)\n+ return tf.cast(tf.raw_ops.PopulationCount(x=x), orig_dtype)\ntf_impl[lax.population_count_p] = _population_count\ntf_impl[lax.is_finite_p] = tf.math.is_finite\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "| mul | Missing TF support | mul is unimplemented for dtype uint32 | CPU, GPU, TPU |\n| nextafter | Missing TF support | nextafter is unimplemented for dtype bfloat16 | CPU, GPU, TPU |\n| nextafter | Missing TF support | nextafter is unimplemented for dtype float16 | CPU, GPU, TPU |\n+| population_count | Missing TF support | population_count is unimplemented for dtype uint32 | CPU, GPU, TPU |\n| qr | Missing TF support | qr is unimplemented for dtype complex64 | CPU, GPU, TPU |\n| reduce_window_sum | Missing TF support | reduce_window_sum is unimplemented for dtype uint16 | CPU, GPU, TPU |\n| reduce_window_sum | Missing TF support | reduce_window_sum is unimplemented for dtype uint32 | CPU, GPU, TPU |\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "@@ -134,6 +134,11 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nif np_dtype == np.complex64:\ntf_unimpl(np_dtype, devs=[\"TPU\"])\n+ if prim is lax.population_count_p:\n+ np_dtype = _to_np_dtype(args[0].dtype)\n+ if np_dtype == np.uint32:\n+ tf_unimpl(np_dtype)\n+\nreturn limitations\ndef prettify(limitations: Sequence[Limitation]) -> str:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -330,8 +330,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_population_count)\ndef test_population_count(self, harness: primitive_harness.Harness):\n- self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n- expect_tf_exceptions=True)\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@primitive_harness.parameterized(primitive_harness.lax_add_mul)\ndef test_add_mul(self, harness: primitive_harness.Harness):\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix bug in population count and move expect_tf_exception (#4214)
into correctness stats.
The code was using `tf.bitcast` instead of `tf.cast`, but using
`expect_tf_exception` in every case was hiding the errors. |
260,335 | 08.09.2020 08:27:41 | 25,200 | ed0d8c02f6860139347f5d3347b9e2f33f67977e | tweak lax.py shape broadcasting logic
This new implementation is faster, and works for polymorphic shapes without weird tricks. (This new implementation is faster even if we remove the weird tricks for polymorphism.) | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -60,12 +60,13 @@ DType = Any\nShape = Sequence[int]\ndef _try_broadcast_shapes(shapes):\n- # Replace 1 with 0 to avoid inconclusive comparisons for polymorphic dims:\n- out_shape = np.max(np.where(shapes == 1, 0, shapes), axis=0)\n- out_shape = np.where(np.all(shapes == 1, axis=0), 1, out_shape)\n- if not np.all((shapes == out_shape) | (shapes == 1)):\n- return None\n- return canonicalize_shape(out_shape)\n+ for sizes in zip(*shapes):\n+ sizes = [d for d in sizes if d != 1]\n+ if sizes[:-1] != sizes[1:]:\n+ break\n+ else:\n+ return tuple(next((d for d in sizes if d != 1), 1)\n+ for sizes in zip(*shapes))\n@cache()\ndef broadcast_shapes(*shapes):\n@@ -73,7 +74,7 @@ def broadcast_shapes(*shapes):\nif len(shapes) == 1:\nreturn shapes[0]\nndim = _max(len(shape) for shape in shapes)\n- shapes = np.array([(1,) * (ndim - len(shape)) + shape for shape in shapes])\n+ shapes = [(1,) * (ndim - len(shape)) + shape for shape in shapes]\nresult_shape = _try_broadcast_shapes(shapes)\nif result_shape is None:\nraise ValueError(\"Incompatible shapes for broadcasting: {}\"\n"
}
] | Python | Apache License 2.0 | google/jax | tweak lax.py shape broadcasting logic (#4217)
This new implementation is faster, and works for polymorphic shapes without weird tricks. (This new implementation is faster even if we remove the weird tricks for polymorphism.) |
260,335 | 08.09.2020 08:54:13 | 25,200 | 7f3078b70d0ed9bea6228efa420879c56f72ef69 | updtate version and changelog for pypi | [
{
"change_type": "MODIFY",
"old_path": "docs/CHANGELOG.rst",
"new_path": "docs/CHANGELOG.rst",
"diff": "@@ -9,6 +9,10 @@ Change Log\nThese are the release notes for JAX.\n+jax 0.1.76 (September 8, 2020)\n+--------------------------\n+* `GitHub commits <https://github.com/google/jax/compare/jax-v0.1.75...jax-v0.1.76>`_.\n+\njax 0.1.75 (July 30, 2020)\n--------------------------\n* `GitHub commits <https://github.com/google/jax/compare/jax-v0.1.74...jax-v0.1.75>`_.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/version.py",
"new_path": "jax/version.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-__version__ = \"0.1.75\"\n+__version__ = \"0.1.76\"\n"
}
] | Python | Apache License 2.0 | google/jax | updtate version and changelog for pypi (#4224) |
260,335 | 08.09.2020 21:14:25 | 25,200 | 745d90d03662453e64c2177134f4c0975e4d0987 | improve lax.pad shape rule
It's now:
* better tested
* better at catching errors
* faster
* easier to read | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3206,11 +3206,16 @@ def _pad_dtype_rule(operand, padding_value, *, padding_config):\nreturn _input_dtype(operand, padding_value)\ndef _pad_shape_rule(operand, padding_value, *, padding_config):\n- lo, hi, interior = zip(*padding_config)\n- out_shape = np.add(\n- np.add(np.add(lo, hi), operand.shape),\n- np.maximum(0, np.multiply(interior, np.subtract(operand.shape, 1))))\n- return tuple(out_shape)\n+ del padding_value\n+ if not len(padding_config) == np.ndim(operand):\n+ raise ValueError(\"length of padding_config must equal the number of axes \"\n+ f\"of operand, got padding_config {padding_config} \"\n+ f\"for operand shape {np.shape(operand)}\")\n+ if not all(i >= 0 for _, _, i in padding_config):\n+ raise ValueError(\"interior padding in padding_config must be nonnegative, \"\n+ f\"got padding_config {padding_config}\")\n+ return tuple(l + h + d + (_max(0, d - 1) * i if i > 0 else 0)\n+ for (l, h, i), d in zip(padding_config, np.shape(operand)))\ndef _pad_transpose(t, operand, padding_value, *, padding_config):\nif type(t) is ad_util.Zero:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -995,9 +995,21 @@ class LaxTest(jtu.JaxTestCase):\n{\"testcase_name\": \"_inshape={}_pads={}\"\n.format(jtu.format_shape_dtype_string(shape, dtype), pads),\n\"shape\": shape, \"dtype\": dtype, \"pads\": pads, \"rng_factory\": jtu.rand_small}\n- for shape in [(0, 2), (2, 3)]\nfor dtype in default_dtypes\n- for pads in [[(1, 2, 1), (0, 1, 0)]]))\n+ for shape, pads in [\n+ ((0, 2), [(1, 2, 1), (0, 1, 0)]),\n+ ((2, 3), [(1, 2, 1), (0, 1, 0)]),\n+ ((2,), [(1, 2, 0)]),\n+ ((1, 2), [(1, 2, 0), (3, 4, 0)]),\n+ ((1, 2), [(0, 0, 0), (0, 0, 0)]),\n+ ((2,), [(1, 2, 3),]),\n+ ((3, 2), [(1, 2, 1), (3, 4, 2)]),\n+ ((2,), [(-1, 2, 0),]),\n+ ((4, 2), [(-1, -2, 0), (1, 2, 0)]),\n+ ((4, 2), [(-1, 2, 0), (1, 2, 2)]),\n+ ((5,), [(-1, -2, 2),]),\n+ ((4, 2), [(-1, -2, 1), (1, 2, 2)])\n+ ]))\ndef testPad(self, shape, dtype, pads, rng_factory):\nrng = rng_factory(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\n@@ -1025,6 +1037,12 @@ class LaxTest(jtu.JaxTestCase):\nnumpy_op = lambda x: lax_reference.pad(x, np.array(0, dtype), pads)\nself._CheckAgainstNumpy(numpy_op, op, args_maker)\n+ def testPadErrors(self):\n+ with self.assertRaisesRegex(ValueError, \"padding_config\"):\n+ lax.pad(np.zeros(2), 0., [(0, 1, 0), (0, 1, 0)])\n+ with self.assertRaisesRegex(ValueError, \"padding_config\"):\n+ lax.pad(np.zeros(2), 0., [(0, 1, -1)])\n+\ndef testReverse(self):\nrev = api.jit(lambda operand: lax.rev(operand, dimensions))\n"
}
] | Python | Apache License 2.0 | google/jax | improve lax.pad shape rule (#4234)
It's now:
* better tested
* better at catching errors
* faster
* easier to read |
260,411 | 09.09.2020 11:34:22 | -10,800 | ee38e7166c6ac2f7d5f5cb39d39cdc672e8224d4 | [jax2tf] Clean up code for XlaGather, experimental_compile not necessary
* [jax2tf] Clean up code for XlaGather, experimental_compile not necessary
Now that XlaGather has been fixed in XLA, we do not need to use
experimental_compile workaround (which was not working anyway when
put in a SavedModel).
This fix requires a recent tf-nightly installation. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Experimental module transforms JAX functions to be executed by TensorFlow.\"\"\"\n-\nimport functools\nimport string\nfrom typing import Any, Callable, Dict, Iterable, Sequence, Tuple, Union\n@@ -25,22 +24,19 @@ from jax import core\nfrom jax import custom_derivatives\nfrom jax import dtypes\nfrom jax import lax\n+from jax import lax_linalg\nfrom jax import linear_util as lu\nfrom jax import numpy as jnp\nfrom jax import random\nfrom jax import tree_util\nfrom jax import util\nfrom jax.api_util import flatten_fun\n-from jax.lax import lax_control_flow\n-from jax.lax import lax_fft\n-from jax import lax_linalg\nfrom jax.interpreters import ad\nfrom jax.interpreters import partial_eval as pe\n-from jax.interpreters import xla\nfrom jax.interpreters import pxla\n-\n-from jaxlib import xla_client\n-\n+from jax.interpreters import xla\n+from jax.lax import lax_control_flow\n+from jax.lax import lax_fft\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n@@ -49,6 +45,9 @@ import tensorflow as tf # type: ignore[import]\nfrom tensorflow.compiler.tf2xla.python import xla as tfxla # type: ignore[import]\nfrom tensorflow.compiler.xla import xla_data_pb2 # type: ignore[import]\n+from jaxlib import xla_client\n+\n+\n# A value suitable in a TF tracing context: tf.Tensor, tf.Variable,\n# or Python scalar or numpy.ndarray. (A tf.EagerTensor is a tf.Tensor.)\nTfVal = Any\n@@ -1073,66 +1072,13 @@ def _gather_shape(operand, start_indices, dimension_numbers, slice_sizes):\nslice_sizes=slice_sizes)\nreturn out.shape\n-\n-def _try_tf_gather(operand, start_indices, dimension_numbers, slice_sizes):\n- # TODO: this function is not used (see comment for dynamic_slice).\n-\n- # Handle only the case when batch_dims=0.\n-\n- # Find axis to match the tf.gather semantics\n- # Let I = len(start_indices_shape)\n- # let O = len(op_shape)\n- # slice_sizes == op_shape[:axis] + (1,) + op_shape[axis+1:]\n- # collapsed_slice_dims == (axis,)\n- # start_index_map == (axis,)\n- # offset_dims == (0, 1, ..., axis - 1, axis + I, ..., O + I - 1)\n- op_shape = np.shape(operand)\n- assert len(op_shape) == len(slice_sizes)\n- if not (len(op_shape) >= 1 and\n- len(dimension_numbers.start_index_map) == 1 and\n- len(dimension_numbers.collapsed_slice_dims) == 1 and\n- dimension_numbers.collapsed_slice_dims[0] == dimension_numbers.start_index_map[0] and\n- len(dimension_numbers.offset_dims) == len(op_shape) - 1):\n- return None\n- # We added a trailing dimension of size 1\n- if start_indices.shape[-1] != 1:\n- return None\n- # Guess the axis\n- axis = dimension_numbers.collapsed_slice_dims[0]\n- index_dims = len(np.shape(start_indices)) - 1\n- expected_offset_dims = tuple(\n- list(range(axis)) +\n- list(range(axis + index_dims, len(op_shape) + index_dims - 1)))\n- if dimension_numbers.offset_dims != expected_offset_dims:\n- return None\n- expected_slice_sizes = op_shape[:axis] + (1,) + op_shape[axis + 1:]\n- if slice_sizes != expected_slice_sizes:\n- return None\n- # TODO: should we allow ourselves to add a reshape, or should we strictly\n- # convert 1:1, or go to TFXLA when not possible?\n- start_indices_reshaped = tf.reshape(start_indices, start_indices.shape[0:-1])\n- # We do not use tf.gather directly because in the non-compiled version it\n- # rejects indices that are out of bounds, while JAX and XLA clamps them.\n- # We fix this by ensuring that we always compile tf.gather, to use XLA.\n- # TODO: see comment for dynamic_slice\n- return tf.function(lambda o, s: tf.gather(o, s, axis=axis, batch_dims=0),\n- experimental_compile=True)(operand, start_indices_reshaped)\n-\n@functools.partial(bool_to_int8, argnums=0)\ndef _gather(operand, start_indices, dimension_numbers, slice_sizes):\n\"\"\"Tensorflow implementation of gather.\"\"\"\n- # TODO: see comment for dynamic_slice\n- #res = _try_tf_gather(operand, start_indices, dimension_numbers, slice_sizes)\n- #if res is not None:\n- # return res\nout_shape = _gather_shape(\noperand, start_indices, dimension_numbers, slice_sizes)\nproto = _gather_dimensions_proto(start_indices.shape, dimension_numbers)\n- # We compile because without it we run into a TF bug:\n- # tfxla.gather fails on constant inputs with \"must be a compile-time constant\"\n- # b/153556869\n- out = tf.function(lambda o, s: tfxla.gather(o, s, proto, slice_sizes, False),\n- experimental_compile=True)(operand, start_indices)\n+ out = tfxla.gather(operand, start_indices, proto, slice_sizes, False)\nout.set_shape(out_shape)\nreturn out\ntf_impl[lax.gather_p] = _gather\n@@ -1156,7 +1102,7 @@ def _dynamic_slice(operand, *start_indices, slice_sizes):\n# and gather ops.\nres = tfxla.dynamic_slice(operand, tf.stack(start_indices),\nsize_indices=slice_sizes)\n- # TODO: implement shape inference for XlaShape\n+ # TODO: implement shape inference for XlaDynamicSlice\nres.set_shape(tuple(slice_sizes))\nreturn res\n@@ -1202,13 +1148,9 @@ def _scatter(operand, scatter_indices, updates, update_jaxpr, update_consts,\no_spec = tf.TensorSpec((), dtype=operand.dtype)\nxla_update_computation = (\ntf.function(update_computation).get_concrete_function(o_spec, o_spec))\n-\n- out = tf.function(\n- lambda o, s, u: tfxla.scatter(o, s, u, xla_update_computation, proto,\n- indices_are_sorted=indices_are_sorted),\n- experimental_compile=True\n- )(operand, scatter_indices, updates)\n-\n+ out = tfxla.scatter(operand, scatter_indices, updates, xla_update_computation, proto,\n+ indices_are_sorted=indices_are_sorted)\n+ # TODO: implement shape analysis for XlaScatter\nout.set_shape(out_shape)\nreturn out\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -155,6 +155,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@primitive_harness.parameterized(primitive_harness.lax_fft)\n+ @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\ndef test_fft(self, harness: primitive_harness.Harness):\nif len(harness.params[\"fft_lengths\"]) > 3:\nwith self.assertRaisesRegex(RuntimeError, \"FFT only supports ranks 1-3\"):\n@@ -200,6 +201,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\natol=1e-5, rtol=1e-5)\n@primitive_harness.parameterized(primitive_harness.lax_linalg_svd)\n+ @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\ndef test_svd(self, harness: primitive_harness.Harness):\nif jtu.device_under_test() == \"tpu\":\nraise unittest.SkipTest(\"TODO: test crashes the XLA compiler for some TPU variants\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"new_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"diff": "@@ -21,7 +21,6 @@ from jax import lax\nimport jax.numpy as jnp\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n-import unittest\nfrom jax.experimental import jax2tf\nfrom jax.experimental.jax2tf.tests import tf_test_util\n@@ -125,15 +124,9 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\nself._compare_with_saved_model(f_jax, arr)\ndef test_xla_context_preserved_gather(self):\n- raise unittest.SkipTest(\"Disable in preparation for fixing b/153556869\")\ndef f_jax(arr):\nreturn arr[100] # out of bounds, should return the last element\narr = np.arange(10, dtype=np.float32)\n- if jtu.device_under_test() != \"tpu\":\n- # TODO(b/153556869): the compilation attributes are not saved in savedmodel\n- with self.assertRaisesRegex(BaseException, \"Input 2 to .* XlaGather must be a compile-time constant\"):\n- self._compare_with_saved_model(f_jax, arr)\n- else:\nself._compare_with_saved_model(f_jax, arr)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Clean up code for XlaGather, experimental_compile not necessary (#4030)
* [jax2tf] Clean up code for XlaGather, experimental_compile not necessary
Now that XlaGather has been fixed in XLA, we do not need to use
experimental_compile workaround (which was not working anyway when
put in a SavedModel).
This fix requires a recent tf-nightly installation. |
260,298 | 09.09.2020 12:20:59 | -7,200 | f908f6f25c82bb2dcc8b54104083af43821e4d21 | [jax2tf] Updated test_pad to test all dtypes and remove old
skipped test. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -440,7 +440,7 @@ lax_pad = tuple(\nrng_factory=jtu.rand_small,\narg_shape=arg_shape, dtype=dtype, pads=pads)\nfor arg_shape in [(2, 3)]\n- for dtype in jtu.dtypes.all_floating + jtu.dtypes.all_integer\n+ for dtype in jtu.dtypes.all\nfor pads in [\n[(0, 0, 0), (0, 0, 0)], # no padding\n[(1, 1, 0), (2, 2, 0)], # only positive edge padding\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -107,9 +107,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_pad)\ndef test_pad(self, harness: primitive_harness.Harness):\n- # TODO: fix pad with negative padding in XLA (fixed on 06/16/2020)\n- if any([lo < 0 or hi < 0 for lo, hi, mid in harness.params[\"pads\"]]):\n- raise unittest.SkipTest(\"pad with negative pad not supported\")\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@primitive_harness.parameterized(primitive_harness.lax_top_k)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Updated test_pad to test all dtypes and remove old (#4235)
skipped test. |
260,380 | 09.09.2020 13:02:45 | -3,600 | bff24bddbbb3822b94eb63b804ac844a26a7386b | Add axis_index_groups support to all_gather. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -579,17 +579,17 @@ ad.deflinear(all_to_all_p, _all_to_all_transpose_rule)\npxla.multi_host_supported_collectives.add(all_to_all_p)\n-def _expand(dim, size, axis_name, x):\n+def _expand(dim, size, index, x):\nshape = list(x.shape)\nshape.insert(dim, size)\nout = lax.full(shape, lax._const(x, 0))\n- return lax.dynamic_update_index_in_dim(out, x, axis_index(axis_name), dim)\n+ return lax.dynamic_update_index_in_dim(out, x, index, dim)\n-def _allgather(x, dim, size, axis_name):\n- outs = tree_util.tree_map(partial(_expand, dim, size, axis_name), x)\n- return psum(outs, axis_name)\n+def _allgather(x, dim, size, index, axis_name, axis_index_groups=None):\n+ outs = tree_util.tree_map(partial(_expand, dim, size, index), x)\n+ return psum(outs, axis_name, axis_index_groups=axis_index_groups)\n-def all_gather(x, axis_name):\n+def all_gather(x, axis_name, *, axis_index_groups=None):\n\"\"\"Gather values of x across all replicas.\nIf ``x`` is a pytree then the result is equivalent to mapping this function to\n@@ -601,13 +601,17 @@ def all_gather(x, axis_name):\nx: array(s) with a mapped axis named ``axis_name``.\naxis_name: hashable Python object used to name a pmapped axis (see the\n:func:`jax.pmap` documentation for more details).\n+ axis_index_groups: optional list of lists containing axis indices (e.g. for\n+ an axis of size 4, [[0, 1], [2, 3]] would run all gather over the first\n+ two and last two replicas). Groups must cover all axis indices exactly\n+ once, and all groups must be the same size.\nReturns:\nArray(s) representing the result of an all-gather along the axis\n``axis_name``. Shapes are the same as ``x.shape``, but with a leading\ndimension of the axis_size.\n- For example, with 2 XLA devices available:\n+ For example, with 4 XLA devices available:\n>>> x = np.arange(4)\n>>> y = jax.pmap(lambda x: jax.lax.all_gather(x, 'i'), axis_name='i')(x)\n@@ -616,8 +620,37 @@ def all_gather(x, axis_name):\n[0 1 2 3]\n[0 1 2 3]\n[0 1 2 3]]\n+\n+ An example of using axis_index_groups, groups split by even & odd device ids:\n+\n+ >>> x = np.arange(16).reshape(4, 4)\n+ >>> print(x)\n+ [[ 0. 1. 2. 3.]\n+ [ 4. 5. 6. 7.]\n+ [ 8. 9. 10. 11.]\n+ [12. 13. 14. 15.]]\n+ >>> y = jax.pmap(lambda x: jax.lax.all_gather(\n+ ... x, 'i', axis_index_groups=[[0, 2], [3, 1]]))(x)\n+ >>> print(y)\n+ [[[ 0. 1. 2. 3.]\n+ [ 8. 9. 10. 11.]]\n+ [[12. 13. 14. 15.]\n+ [ 4. 5. 6. 7.]]\n+ [[ 0. 1. 2. 3.]\n+ [ 8. 9. 10. 11.]]\n+ [[12. 13. 14. 15.]\n+ [ 4. 5. 6. 7.]]\n\"\"\"\n- return _allgather(x, 0, psum(1, axis_name), axis_name)\n+\n+ index = axis_index(axis_name)\n+ if axis_index_groups is not None:\n+ indices = np.array(axis_index_groups).flatten()\n+ axis_index_to_group_index = indices.argsort() % len(axis_index_groups[0])\n+ index = lax_numpy.array(axis_index_to_group_index)[index]\n+\n+ axis_size = psum(1, axis_name, axis_index_groups=axis_index_groups)\n+\n+ return _allgather(x, 0, axis_size, index, axis_name, axis_index_groups)\ndef _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -494,6 +494,53 @@ class PmapTest(jtu.JaxTestCase):\nans = f(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testGatherReplicaGroups(self):\n+ replicas = xla_bridge.device_count()\n+ if replicas % 2 != 0:\n+ raise SkipTest(\"Test expected an even number of devices greater than 1.\")\n+\n+ axis_index_groups = np.arange(replicas).reshape(\n+ 2, replicas // 2).tolist()\n+\n+ f = lambda x: lax.all_gather(x, 'i', axis_index_groups=axis_index_groups)\n+ f = pmap(f, 'i')\n+\n+ shape = (replicas, 4)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+\n+ ans = f(x)\n+\n+ expected_1 = np.broadcast_to(\n+ x[:replicas // 2], (replicas // 2, replicas // 2, x.shape[1]))\n+ expected_2 = np.broadcast_to(\n+ x[replicas // 2:], (replicas // 2, replicas // 2, x.shape[1]))\n+ expected = np.concatenate([expected_1, expected_2], 0)\n+\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testGatherReplicaGroupsInterleaved(self):\n+ replicas = xla_bridge.device_count()\n+ if replicas % 2 != 0:\n+ raise SkipTest(\"Test expected an even number of devices greater than 1.\")\n+\n+ indexes = np.arange(replicas)\n+ indexes = np.concatenate([indexes[::2], indexes[1::2]])\n+ axis_index_groups = indexes.reshape(2, replicas // 2).tolist()\n+\n+ f = lambda x: lax.all_gather(x, 'i', axis_index_groups=axis_index_groups)\n+ f = pmap(f, 'i')\n+\n+ shape = (replicas, 4)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+\n+ ans = f(x)\n+\n+ expected = np.zeros((replicas, replicas // 2, x.shape[1]))\n+ expected[::2] = x[::2]\n+ expected[1::2] = x[1::2]\n+\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef testNestedPmapReplicaGroups(self):\nreplicas = xla_bridge.device_count()\nif replicas % 4 != 0:\n"
}
] | Python | Apache License 2.0 | google/jax | Add axis_index_groups support to all_gather. (#4194) |
260,298 | 09.09.2020 14:43:36 | -7,200 | 053cd5aa391905772428e2a5b19af651f6e2d636 | [jax2tf] Clean up test_dynamic_slice.
* [jax2tf] Clean up test_dynamic_slice.
With the XLA nested compilation bug fixed, this should now work
fine. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -428,7 +428,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ndef test_dynamic_slice(self, harness):\n# JAX.dynamic_slice rejects slice sizes too big; check this, and skip jax2tf\nargs = harness.dyn_args_maker(self.rng())\n- expect_tf_exceptions = False\nif any(li - si < 0 or li - si >= sh\nfor sh, si, li in zip(harness.params[\"shape\"],\nharness.params[\"start_indices\"],\n@@ -437,15 +436,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nharness.dyn_fun(*args)\nreturn\n- # TF sometimes gives errors for out-of-bounds accesses\n- if any(si < 0 or li >= sh\n- for sh, si, li in zip(harness.params[\"shape\"],\n- harness.params[\"start_indices\"],\n- harness.params[\"limit_indices\"])):\n- expect_tf_exceptions = True\n-\n- self.ConvertAndCompare(harness.dyn_fun, *args,\n- expect_tf_exceptions=expect_tf_exceptions)\n+ self.ConvertAndCompare(harness.dyn_fun, *args)\n@primitive_harness.parameterized(primitive_harness.lax_dynamic_update_slice)\ndef test_dynamic_update_slice(self, harness):\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Clean up test_dynamic_slice. (#4236)
* [jax2tf] Clean up test_dynamic_slice.
With the XLA nested compilation bug fixed, this should now work
fine. |
260,298 | 09.09.2020 16:48:00 | -7,200 | 70891f46cdf42d0c9d3c6c5d2527a56a9500774e | [jax2tf] Add a template file for documentation generation.
* [jax2tf] Add a template file for documentation generation.
The documentation now gives instructions about how to
regenerate it, as well as when it was last generated.
* Added a list of conversions that are not yet implemented. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "# Primitives with limited support\n+*Last generated on (YYYY-MM-DD): 2020-09-09*\n+\n+## Updating the documentation\n+\n+This file is automatically generated by running the jax2tf tests in\n+`jax/experimental/jax2tf/tests/primitives_test.py` with the\n+`JAX2TF_CATEGORIZE_OUT` environment variable set.\n+\n+## Generated summary of primitives with limited support\n+\n+The following JAX primitives are converted to Tensorflow but the result of the\n+conversion may trigger runtime errors when run on certain devices and with\n+certain data types.\n+\n| Affected primitive | Type of limitation | Description | Devices affected |\n| --- | --- | --- | --- |\n| add | Missing TF support | add is unimplemented for dtype uint16 | CPU, GPU, TPU |\n| scatter-mul | Missing TF support | scatter-mul is unimplemented for dtype complex64 | TPU |\n| select_and_gather_add | Missing TF support | select_and_gather_add is unimplemented for dtype float32 | TPU |\n| svd | Missing TF support | svd is unimplemented for dtype complex64; this works on JAX because JAX uses a custom implementation | CPU, GPU |\n+\n+## Not yet implemented primitive conversions\n+\n+The conversion of the following JAX primitives is not yet implemented:\n+\n+`after_all`, `all_to_all`, `axis_index`, `cholesky`, `create_token`, `cummax`, `cummin`, `custom_linear_solve`, `eig`, `eigh`, `igamma_grad_a`, `infeed`, `lu`, `outfeed`, `pmax`, `pmin`, `ppermute`, `psum`, `random_gamma_grad`, `reduce`, `rng_uniform`, `triangular_solve`, `xla_pmap`\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md.template",
"diff": "+# Primitives with limited support\n+\n+*Last generated on (YYYY-MM-DD): {{generation-date}}*\n+\n+## Updating the documentation\n+\n+This file is automatically generated by running the jax2tf tests in\n+`jax/experimental/jax2tf/tests/primitives_test.py` with the\n+`JAX2TF_CATEGORIZE_OUT` environment variable set.\n+\n+## Generated summary of primitives with limited support\n+\n+The following JAX primitives are converted to Tensorflow but the result of the\n+conversion may trigger runtime errors when run on certain devices and with\n+certain data types.\n+\n+{{limited-support-table}}\n+\n+## Not yet implemented primitive conversions\n+\n+The conversion of the following JAX primitives is not yet implemented:\n+\n+{{not-yet-impl-primitives-list}}\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import datetime\nimport functools\nimport numpy as np\nfrom typing import Any, Callable, List, NamedTuple, Optional, Tuple, Sequence\n@@ -20,6 +21,7 @@ from jax import core\nfrom jax import dtypes\nfrom jax import lax\nfrom jax import lax_linalg\n+from jax.experimental.jax2tf.jax2tf import tf_not_yet_impl\ndef to_jax_dtype(tf_dtype):\nif tf_dtype.name == 'bfloat16':\n@@ -142,14 +144,12 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nreturn limitations\ndef prettify(limitations: Sequence[Limitation]) -> str:\n- \"\"\"Constructs a summary .md file based on a list of limitations.\"\"\"\n+ \"\"\"Constructs a summary markdown table based on a list of limitations.\"\"\"\nlimitations = sorted(list(set(limitations)))\ndef _pipewrap(columns):\nreturn '| ' + ' | '.join(columns) + ' |'\n- title = '# Primitives with limited support'\n-\ncolumn_names = [ 'Affected primitive'\n, 'Type of limitation'\n, 'Description'\n@@ -164,16 +164,33 @@ def prettify(limitations: Sequence[Limitation]) -> str:\n, ', '.join(lim.devices)\n])\n- return title + '\\n\\n' + '\\n'.join(line for line in map(_pipewrap, table))\n+ return '\\n'.join(line for line in map(_pipewrap, table))\n+\n+def prettify_not_yet_implemented() -> str:\n+ \"\"\"Constructs a summary markdown list of the unimplemented primitives.\"\"\"\n+ ordered_unimpl: List[str]\n+ ordered_unimpl = sorted(list(map(lambda prim: prim.name, tf_not_yet_impl)))\n+\n+ backtick_wrap = lambda prim_name: f'`{prim_name}`'\n+ return ', '.join(list(map(backtick_wrap, ordered_unimpl)))\n+\n+def pprint_limitations(limitations: Sequence[Limitation], output_file: str,\n+ template_file: str) -> None:\n+\n+ limited_support_table = prettify(limitations)\n+ not_yet_impl_primitives_list = prettify_not_yet_implemented()\n+ generation_date = str(datetime.date.today())\n+\n+ with open(template_file, 'r') as f:\n+ output = f.read()\n+\n+ output = (output\n+ .replace('{{limited-support-table}}', limited_support_table)\n+ .replace('{{generation-date}}', generation_date)\n+ .replace('{{not-yet-impl-primitives-list}}', not_yet_impl_primitives_list))\n-def pprint_limitations(limitations: Sequence[Limitation],\n- output_file: Optional[str] = None) -> None:\n- output = prettify(limitations)\n- if output_file:\nwith open(output_file, 'w') as f:\nf.write(output)\n- else:\n- print(output)\nall_limitations: Sequence[Limitation] = []\npprint_all_limitations = functools.partial(pprint_limitations, all_limitations)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"new_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"diff": "@@ -29,10 +29,13 @@ from jax import numpy as jnp\nimport os\n-if os.getenv('JAX2TF_CATEGORIZE_OUT'):\n+if os.getenv('JAX2TF_CATEGORIZE_OUT') is not None:\noutput_file = os.path.join(os.path.dirname(__file__),\n'../primitives_with_limited_support.md')\n- atexit.register(correctness_stats.pprint_all_limitations, output_file)\n+ template_file = os.path.join(os.path.dirname(__file__),\n+ '../primitives_with_limited_support.md.template')\n+ atexit.register(correctness_stats.pprint_all_limitations,\n+ output_file, template_file)\nclass JaxToTfTestCase(jtu.JaxTestCase):\ndef setUp(self):\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Add a template file for documentation generation. (#4219)
* [jax2tf] Add a template file for documentation generation.
The documentation now gives instructions about how to
regenerate it, as well as when it was last generated.
* Added a list of conversions that are not yet implemented. |
260,411 | 10.09.2020 12:19:22 | -10,800 | f0a3fd4a8687baf348ca70fe168e43389bf7506e | [jax2tf] Moved the limitations for XlaSort to correctness_stats | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "@@ -42,6 +42,11 @@ certain data types.\n| scatter-add | Missing TF support | scatter-add is unimplemented for dtype complex64 | TPU |\n| scatter-mul | Missing TF support | scatter-mul is unimplemented for dtype complex64 | TPU |\n| select_and_gather_add | Missing TF support | select_and_gather_add is unimplemented for dtype float32 | TPU |\n+| sort | Missing TF support | sort is unimplemented for dtype bool; sorting 2 arrays where the first one is an array of booleans is not supported for XlaSort | CPU, GPU, TPU |\n+| sort | Missing TF support | sort is unimplemented for dtype complex64 | CPU, GPU, TPU |\n+| sort | Missing TF support | sort is unimplemented; only sorting on last dimension is supported for XlaSort | CPU, GPU, TPU |\n+| sort | Missing TF support | sort is unimplemented; sorting more than 2 arrays is not supported for XlaSort | CPU, GPU, TPU |\n+| sort | Missing TF support | sort is unimplemented; stable sort not implemented for XlaSort | CPU, GPU, TPU |\n| svd | Missing TF support | svd is unimplemented for dtype complex64; this works on JAX because JAX uses a custom implementation | CPU, GPU |\n## Not yet implemented primitive conversions\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "@@ -58,9 +58,12 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\ndevs: Sequence[str] = all_devices) -> None:\nlimitations.append(Limitation(prim.name, error_type, msg, tuple(devs)))\n- def tf_unimpl(np_dtype: NpDType, additional_msg: Optional[str] = None,\n+ def tf_unimpl(np_dtype: Optional[NpDType] = None,\n+ additional_msg: Optional[str] = None,\ndevs: Sequence[str] = all_devices) -> None:\n- msg = f\"{prim.name} is unimplemented for dtype {np_dtype}\"\n+ msg = f\"{prim.name} is unimplemented\"\n+ if np_dtype is not None:\n+ msg += f\" for dtype {np_dtype}\"\nif additional_msg:\nmsg += '; ' + additional_msg\n_report_failure(\"Missing TF support\", msg, devs=devs)\n@@ -136,6 +139,22 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nif np_dtype == np.complex64:\ntf_unimpl(np_dtype, devs=[\"TPU\"])\n+ if prim is lax.sort_p:\n+ np_dtype = _to_np_dtype(args[0].dtype)\n+ if np_dtype in [np.complex64, np.complex128]:\n+ tf_unimpl(np_dtype)\n+ if np_dtype == np.bool_ and len(args) == 2:\n+ tf_unimpl(np_dtype, additional_msg=(\n+ \"sorting 2 arrays where the first one is an array of booleans is not \"\n+ \"supported for XlaSort\"))\n+ if kwargs[\"is_stable\"]:\n+ tf_unimpl(additional_msg=\"stable sort not implemented for XlaSort\")\n+ if kwargs[\"dimension\"] != len(np.shape(args[0])) - 1:\n+ tf_unimpl(additional_msg=\"only sorting on last dimension is supported for XlaSort\")\n+ if len(args) > 2:\n+ tf_unimpl(additional_msg=(\n+ \"sorting more than 2 arrays is not supported for XlaSort\"))\n+\nif prim is lax.population_count_p:\nnp_dtype = _to_np_dtype(args[0].dtype)\nif np_dtype == np.uint32:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -510,8 +510,8 @@ lax_sort = tuple( # one array, random data, all axes, all dtypes\n[np.array([+np.inf, np.nan, -np.nan, -np.inf, 2, 4, 189], dtype=np.float32), -1]\n]\nfor is_stable in [False, True]\n-) + tuple( # several arrays, random data, all axes, all dtypes\n- Harness(f\"multi_array_shape={jtu.format_shape_dtype_string(shape, dtype)}_axis={dimension}_isstable={is_stable}\",\n+) + tuple( # 2 arrays, random data, all axes, all dtypes\n+ Harness(f\"two_arrays_shape={jtu.format_shape_dtype_string(shape, dtype)}_axis={dimension}_isstable={is_stable}\",\nlambda *args: lax.sort_p.bind(*args[:-2], dimension=args[-2], is_stable=args[-1], num_keys=1),\n[RandArg(shape, dtype), RandArg(shape, dtype), StaticArg(dimension), StaticArg(is_stable)],\nshape=shape,\n@@ -522,6 +522,19 @@ lax_sort = tuple( # one array, random data, all axes, all dtypes\nfor shape in [(5,), (5, 7)]\nfor dimension in range(len(shape))\nfor is_stable in [False, True]\n+) + tuple( # 3 arrays, random data, all axes, all dtypes\n+ Harness(f\"three_arrays_shape={jtu.format_shape_dtype_string(shape, dtype)}_axis={dimension}_isstable={is_stable}\",\n+ lambda *args: lax.sort_p.bind(*args[:-2], dimension=args[-2], is_stable=args[-1], num_keys=1),\n+ [RandArg(shape, dtype), RandArg(shape, dtype), RandArg(shape, dtype),\n+ StaticArg(dimension), StaticArg(is_stable)],\n+ shape=shape,\n+ dimension=dimension,\n+ dtype=dtype,\n+ is_stable=is_stable)\n+ for dtype in jtu.dtypes.all\n+ for shape in [(5,)]\n+ for dimension in (0,)\n+ for is_stable in [False, True]\n)\nlax_linalg_qr = tuple(\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -129,21 +129,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_sort)\ndef test_sort(self, harness: primitive_harness.Harness):\n- if harness.params[\"dtype\"] in jtu.dtypes.complex:\n- # TODO: implement complex support in XlaSort\n- raise unittest.SkipTest(\"complex support not implemented\")\n- if harness.params[\"dtype\"] is dtypes.bool_ and len(harness.arg_descriptors) == 4:\n- # TODO: _sort uses tfxla.key_value_sort to handle 2 operandes, but the operation is not compatible with boolean keys.\n- raise unittest.SkipTest(\"boolean key key value sort not implemented\")\n- if harness.params[\"is_stable\"]:\n- # TODO: implement stable sort support in XlaSort\n- raise unittest.SkipTest(\"stable sort not implemented\")\n- if harness.params[\"dimension\"] != len(harness.params[\"shape\"]) - 1:\n- # TODO: implement sort on all axes\n- raise unittest.SkipTest(\"conversion not implemented for axis != -1\")\n- if len(harness.arg_descriptors) > 4:\n- # TODO: implement variable number of operands to XlaSort\n- raise unittest.SkipTest(\"conversion not implemented for #operands > 2\")\nif (jtu.device_under_test() == \"gpu\" and\nlen(harness.arg_descriptors) == 4 and\nnot harness.params[\"is_stable\"]):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"new_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"diff": "@@ -29,7 +29,8 @@ from jax import numpy as jnp\nimport os\n-if os.getenv('JAX2TF_CATEGORIZE_OUT') is not None:\n+\n+if os.getenv('JAX2TF_OUTPUT_LIMITATIONS') is not None:\noutput_file = os.path.join(os.path.dirname(__file__),\n'../primitives_with_limited_support.md')\ntemplate_file = os.path.join(os.path.dirname(__file__),\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Moved the limitations for XlaSort to correctness_stats (#4237) |
260,411 | 10.09.2020 13:55:57 | -10,800 | 0962ceb05722beb26ee42100384095551d0bda9a | [jax2tf] Fix test failure on TPUs | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "This file is automatically generated by running the jax2tf tests in\n`jax/experimental/jax2tf/tests/primitives_test.py` with the\n-`JAX2TF_CATEGORIZE_OUT` environment variable set.\n+`JAX2TF_OUTPUT_LIMITATIONS` environment variable set.\n## Generated summary of primitives with limited support\nThe following JAX primitives are converted to Tensorflow but the result of the\nconversion may trigger runtime errors when run on certain devices and with\n-certain data types.\n+certain data types. Note that some of these primitives have unimplemented\n+cases even for JAX, e.g., sort does not work for complex numbers on TPUs.\n+This table includes only those cases that **work** in JAX but **fail** after\n+conversion to Tensorflow.\n| Affected primitive | Type of limitation | Description | Devices affected |\n| --- | --- | --- | --- |\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md.template",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md.template",
"diff": "This file is automatically generated by running the jax2tf tests in\n`jax/experimental/jax2tf/tests/primitives_test.py` with the\n-`JAX2TF_CATEGORIZE_OUT` environment variable set.\n+`JAX2TF_OUTPUT_LIMITATIONS` environment variable set.\n## Generated summary of primitives with limited support\nThe following JAX primitives are converted to Tensorflow but the result of the\nconversion may trigger runtime errors when run on certain devices and with\n-certain data types.\n+certain data types. Note that some of these primitives have unimplemented\n+cases even for JAX, e.g., sort does not work for complex numbers on TPUs.\n+This table includes only those cases that **work** in JAX but **fail** after\n+conversion to Tensorflow.\n{{limited-support-table}}\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -134,6 +134,8 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nnot harness.params[\"is_stable\"]):\n# TODO: fix the TF GPU test\nraise unittest.SkipTest(\"GPU tests are running TF on CPU\")\n+ if jtu.device_under_test() == \"tpu\" and harness.params[\"dtype\"] in jtu.dtypes.complex:\n+ raise unittest.SkipTest(\"JAX sort is not implemented on TPU for complex\")\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@primitive_harness.parameterized(primitive_harness.lax_fft)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix test failure on TPUs (#4247) |
260,423 | 11.09.2020 18:51:42 | -3,600 | ca1d8f41090e2befba903c4b20a1121f39ecf833 | Fixing weird behavior in segment_sum when num_segments is None | [
{
"change_type": "MODIFY",
"old_path": "jax/ops/scatter.py",
"new_path": "jax/ops/scatter.py",
"diff": "@@ -316,8 +316,10 @@ def segment_sum(data, segment_ids, num_segments=None,\nneed not be sorted. Values outside of the range [0, num_segments) are\nwrapped into that range by applying jnp.mod.\nnum_segments: optional, an int with positive value indicating the number of\n- segments. The default is ``max(segment_ids % data.shape[0]) + 1`` but\n- since `num_segments` determines the size of the output, a static value\n+ segments. The default is set to be the minimum number of segments that\n+ would support all positive and negative indices in `segment_ids`\n+ calculated as ``max(max(segment_ids) + 1, max(-segment_ids))``.\n+ Since `num_segments` determines the size of the output, a static value\nmust be provided to use `segment_sum` in a `jit`-compiled function.\nindices_are_sorted: whether `segment_ids` is known to be sorted\nunique_indices: whether `segment_ids` is known to be free of duplicates\n@@ -327,7 +329,7 @@ def segment_sum(data, segment_ids, num_segments=None,\nsegment sums.\n\"\"\"\nif num_segments is None:\n- num_segments = jnp.max(jnp.mod(segment_ids, data.shape[0])) + 1\n+ num_segments = max(jnp.max(segment_ids) + 1, jnp.max(-segment_ids))\nnum_segments = int(num_segments)\nout = jnp.zeros((num_segments,) + data.shape[1:], dtype=data.dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_indexing_test.py",
"new_path": "tests/lax_numpy_indexing_test.py",
"diff": "@@ -1058,11 +1058,30 @@ class IndexedUpdateTest(jtu.JaxTestCase):\nexpected = np.array([13, 2, 7, 4])\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ # test with explicit num_segments larger than the higher index.\n+ ans = ops.segment_sum(data, segment_ids, num_segments=5)\n+ expected = np.array([13, 2, 7, 4, 0])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n# test without explicit num_segments\nans = ops.segment_sum(data, segment_ids)\nexpected = np.array([13, 2, 7, 4])\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ # test with negative segment ids and segment ids larger than num_segments,\n+ # that will be wrapped with the `mod`.\n+ segment_ids = np.array([0, 4, 8, 1, 2, -6, -1, 3])\n+ ans = ops.segment_sum(data, segment_ids, num_segments=4)\n+ expected = np.array([13, 2, 7, 4])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ # test with negative segment ids and without without explicit num_segments\n+ # such as num_segments is defined by the smaller index.\n+ segment_ids = np.array([3, 3, 3, 4, 5, 5, -7, -6])\n+ ans = ops.segment_sum(data, segment_ids)\n+ expected = np.array([1, 3, 0, 13, 2, 7, 0])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef testIndexDtypeError(self):\n# https://github.com/google/jax/issues/2795\njnp.array(1) # get rid of startup warning\n"
}
] | Python | Apache License 2.0 | google/jax | Fixing weird behavior in segment_sum when num_segments is None (#4034)
Co-authored-by: alvarosg <alvarosg@google.com> |
260,335 | 11.09.2020 22:40:12 | 25,200 | f039f6daf96f2e0abdd27f13142a97dc1dea2229 | thread backend in pxla.replicate
* thread backend in pxla.replicate
fixes
* add test for | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -925,7 +925,7 @@ def replicate(val, axis_size, nrep, devices=None, backend=None):\nA ShardedDeviceArray of length `axis_size` where each shard is equal to\n``val``.\n\"\"\"\n- device_count = (len(devices) if devices else xb.local_device_count())\n+ device_count = (len(devices) if devices else xb.local_device_count(backend))\nif nrep > device_count:\nmsg = (\"Cannot replicate across %d replicas because only %d local devices \"\n\"are available.\" % (nrep, device_count))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -1481,6 +1481,15 @@ class PmapTest(jtu.JaxTestCase):\nu = np.ones((device_count, 100))\nmulti_step_pmap(u) # doesn't crash\n+ @jtu.skip_on_devices(\"cpu\")\n+ def test_replicate_backend(self):\n+ # https://github.com/google/jax/issues/4223\n+ def fn(indices):\n+ return jnp.equal(indices, jnp.arange(3)).astype(jnp.float32)\n+ mapped_fn = jax.pmap(fn, axis_name='i', backend='cpu')\n+ mapped_fn = jax.pmap(mapped_fn, axis_name='j', backend='cpu')\n+ indices = np.array([[[2], [1]], [[0], [0]]])\n+ mapped_fn(indices) # doesn't crash\nclass VmapOfPmapTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | thread backend in pxla.replicate (#4272)
* thread backend in pxla.replicate
fixes #4223
* add test for #4223 |
260,639 | 12.09.2020 16:10:01 | 14,400 | 64bead2093b705820be0dcb46e27edcfd8b50d34 | fixing typo
I assume "...one of more type parameters..." was intended to read "...one or more type parameters..." | [
{
"change_type": "MODIFY",
"old_path": "docs/jaxpr.rst",
"new_path": "docs/jaxpr.rst",
"diff": "@@ -21,7 +21,7 @@ will apply transformations incrementally during tracing.\nNevertheless, if one wants to understand how JAX works internally, or to\nmake use of the result of JAX tracing, it is useful to understand jaxpr.\n-A jaxpr instance represents a function with one of more typed parameters (input variables)\n+A jaxpr instance represents a function with one or more typed parameters (input variables)\nand one or more typed results. The results depend only on the input\nvariables; there are no free variables captured from enclosing scopes.\nThe inputs and outputs have types, which in JAX are represented as abstract\n"
}
] | Python | Apache License 2.0 | google/jax | fixing typo (#4273)
I assume "...one of more type parameters..." was intended to read "...one or more type parameters..." |
260,296 | 13.09.2020 19:20:31 | 25,200 | 38b43ef95d0c445168ce416f0e7997b8b838c06e | Avoid rank promotion in np.outer | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -3198,7 +3198,7 @@ def outer(a, b, out=None):\nif out:\nraise NotImplementedError(\"The 'out' argument to outer is not supported.\")\na, b = _promote_dtypes(a, b)\n- return ravel(a)[:, None] * ravel(b)\n+ return ravel(a)[:, None] * ravel(b)[None, :]\n@partial(jit, static_argnums=(2, 3, 4))\ndef _cross(a, b, axisa, axisb, axisc):\n"
}
] | Python | Apache License 2.0 | google/jax | Avoid rank promotion in np.outer (#4276) |
260,298 | 14.09.2020 11:34:31 | -7,200 | 2ff3479239bc172ccdd764ae579dae60e96d079e | [jax2tf] Fix tests when running with JAX_ENABLE_X64=1.
Fixed tests:
test_binary_elementwise
dynamic_update_slice
fft
population_count
test_unary_elementwise
top_k
select_and_gather_add | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "# Primitives with limited support\n-*Last generated on (YYYY-MM-DD): 2020-09-10*\n+*Last generated on (YYYY-MM-DD): 2020-09-11*\n## Updating the documentation\nThis file is automatically generated by running the jax2tf tests in\n`jax/experimental/jax2tf/tests/primitives_test.py` and\n`jax/experimental/jax2tf/tests/control_flow_ops_test.py` with the\n-`JAX2TF_OUTPUT_LIMITATIONS` environment variable set.\n+`JAX2TF_OUTPUT_LIMITATIONS` and `JAX_ENABLE_X64` environment variables set.\n## Generated summary of primitives with limited support\n@@ -24,6 +24,7 @@ conversion to Tensorflow.\n| acosh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n| add | Missing TF support | Primitive is unimplemented for dtype uint16 | CPU, GPU, TPU |\n| add | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n+| add | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n| asinh | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n| asinh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n| atan2 | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU, TPU |\n@@ -38,24 +39,34 @@ conversion to Tensorflow.\n| erf_inv | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n| erf_inv | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n| erfc | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n+| fft | Missing TF support | Primitive is unimplemented for dtype complex128; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n+| fft | Missing TF support | Primitive is unimplemented for dtype float64; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n| lgamma | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n| max | Missing TF support | Primitive is unimplemented for dtype bool | CPU, GPU, TPU |\n+| max | Missing TF support | Primitive is unimplemented for dtype complex128 | CPU, GPU, TPU |\n| max | Missing TF support | Primitive is unimplemented for dtype complex64 | CPU, GPU, TPU |\n| max | Missing TF support | Primitive is unimplemented for dtype int8 | CPU, GPU, TPU |\n| max | Missing TF support | Primitive is unimplemented for dtype uint16 | CPU, GPU, TPU |\n| max | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n+| max | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n| min | Missing TF support | Primitive is unimplemented for dtype bool | CPU, GPU, TPU |\n+| min | Missing TF support | Primitive is unimplemented for dtype complex128 | CPU, GPU, TPU |\n| min | Missing TF support | Primitive is unimplemented for dtype complex64 | CPU, GPU, TPU |\n| min | Missing TF support | Primitive is unimplemented for dtype int8 | CPU, GPU, TPU |\n| min | Missing TF support | Primitive is unimplemented for dtype uint16 | CPU, GPU, TPU |\n| min | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n+| min | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n| mul | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n+| mul | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n| nextafter | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU, TPU |\n| nextafter | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n| population_count | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n+| population_count | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n+| qr | Missing TF support | Primitive is unimplemented for dtype complex128 | CPU, GPU, TPU |\n| qr | Missing TF support | Primitive is unimplemented for dtype complex64 | CPU, GPU, TPU |\n| reduce_window_sum | Missing TF support | Primitive is unimplemented for dtype uint16 | CPU, GPU, TPU |\n| reduce_window_sum | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n+| reduce_window_sum | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n| rem | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU, TPU |\n| rem | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n| round | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n@@ -63,13 +74,20 @@ conversion to Tensorflow.\n| scatter-add | Missing TF support | Primitive is unimplemented for dtype complex64 | TPU |\n| scatter-mul | Missing TF support | Primitive is unimplemented for dtype complex64 | TPU |\n| select_and_gather_add | Missing TF support | Primitive is unimplemented for dtype float32 | TPU |\n+| select_and_gather_add | Missing TF support | Primitive is unimplemented for dtype float64 | CPU, GPU |\n+| select_and_gather_add | Missing TF support | Primitive is unimplemented for dtype float64 | TPU |\n| sinh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n| sort | Missing TF support | Primitive is unimplemented for dtype bool; sorting 2 arrays where the first one is an array of booleans is not supported for XlaSort | CPU, GPU, TPU |\n+| sort | Missing TF support | Primitive is unimplemented for dtype complex128 | CPU, GPU, TPU |\n| sort | Missing TF support | Primitive is unimplemented for dtype complex64 | CPU, GPU, TPU |\n| sort | Missing TF support | Primitive is unimplemented; only sorting on last dimension is supported for XlaSort | CPU, GPU, TPU |\n| sort | Missing TF support | Primitive is unimplemented; sorting more than 2 arrays is not supported for XlaSort | CPU, GPU, TPU |\n| sort | Missing TF support | Primitive is unimplemented; stable sort not implemented for XlaSort | CPU, GPU, TPU |\n+| svd | Missing TF support | Primitive is unimplemented for dtype complex128; this works on JAX because JAX uses a custom implementation | CPU, GPU |\n| svd | Missing TF support | Primitive is unimplemented for dtype complex64; this works on JAX because JAX uses a custom implementation | CPU, GPU |\n+| top_k | Missing TF support | Primitive is unimplemented for dtype float64; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n+| top_k | Missing TF support | Primitive is unimplemented for dtype int64; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n+| top_k | Missing TF support | Primitive is unimplemented for dtype uint64; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n## Not yet implemented primitive conversions\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md.template",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md.template",
"diff": "This file is automatically generated by running the jax2tf tests in\n`jax/experimental/jax2tf/tests/primitives_test.py` and\n`jax/experimental/jax2tf/tests/control_flow_ops_test.py` with the\n-`JAX2TF_OUTPUT_LIMITATIONS` environment variable set.\n+`JAX2TF_OUTPUT_LIMITATIONS` and `JAX_ENABLE_X64` environment variables set.\n## Generated summary of primitives with limited support\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "@@ -173,7 +173,7 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nif prim is lax.population_count_p:\nnp_dtype = _to_np_dtype(args[0].dtype)\n- if np_dtype == np.uint32:\n+ if np_dtype in [np.uint32, np.uint64]:\ntf_unimpl(np_dtype)\nif prim in [lax.acosh_p, lax.asinh_p, lax.atanh_p, lax.bessel_i0e_p,\n@@ -191,6 +191,17 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\n# operations.\ntf_unimpl(np_dtype)\n+ if prim is lax.lax_fft.fft_p:\n+ np_dtype = _to_np_dtype(args[0].dtype)\n+ if np_dtype in [np.float64, np.complex128]:\n+ tf_unimpl(np_dtype, additional_msg=(\"this is a problem only in compiled \"\n+ \"mode (experimental_compile=True))\"))\n+\n+ if prim is lax.top_k_p:\n+ np_dtype = _to_np_dtype(args[0].dtype)\n+ if np_dtype in [np.float64, np.int64, np.uint64]:\n+ tf_unimpl(np_dtype, additional_msg=(\"this is a problem only in compiled \"\n+ \"mode (experimental_compile=True))\"))\nreturn limitations\ndef prettify(limitations: Sequence[Limitation]) -> str:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -336,8 +336,7 @@ lax_betainc = tuple(\nfor arg1, arg2, arg3 in [\n(np.array([-1.6, -1.4, -1.0, 0.0, 0.1, 0.3, 1, 1.4, 1.6], dtype=dtype),\nnp.array([-1.6, 1.4, 1.0, 0.0, 0.2, 0.1, 1, 1.4, -1.6], dtype=dtype),\n- np.array([1.0, -1.0, 2.0, 1.0, 0.3, 0.3, -1.0, 2.4, 1.6],\n- dtype=np.float32))\n+ np.array([1.0, -1.0, 2.0, 1.0, 0.3, 0.3, -1.0, 2.4, 1.6], dtype=dtype))\n]\n)\n@@ -667,7 +666,7 @@ lax_dynamic_update_slice = tuple(\n]\nfor dtype, update_dtype in [\n(np.float32, np.float32),\n- (np.float64, np.float32)\n+ (np.float64, np.float64)\n])\nlax_squeeze = tuple(\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -144,9 +144,11 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nif len(harness.params[\"fft_lengths\"]) > 3:\nwith self.assertRaisesRegex(RuntimeError, \"FFT only supports ranks 1-3\"):\nharness.dyn_fun(*harness.dyn_args_maker(self.rng()))\n- elif jtu.device_under_test() == \"tpu\" and len(harness.params[\"fft_lengths\"]) > 1:\n+ elif (jtu.device_under_test() == \"tpu\" and\n+ len(harness.params[\"fft_lengths\"]) > 1):\n# TODO(b/140351181): FFT is mostly unimplemented on TPU, even for JAX\n- with self.assertRaisesRegex(RuntimeError, \"only 1D FFT is currently supported.\"):\n+ with self.assertRaisesRegex(RuntimeError,\n+ \"only 1D FFT is currently supported.\"):\nharness.dyn_fun(*harness.dyn_args_maker(self.rng()))\nelse:\ntol = None\n@@ -155,7 +157,8 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ntol = 0.01\nelse:\ntol = 1e-3\n- self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ self.ConvertAndCompare(harness.dyn_fun,\n+ *harness.dyn_args_maker(self.rng()),\natol=tol, rtol=tol)\n@primitive_harness.parameterized(primitive_harness.lax_linalg_qr)\n@@ -235,6 +238,8 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nalways_custom_assert=True)\n@primitive_harness.parameterized(primitive_harness.lax_select_and_gather_add)\n+ @jtu.ignore_warning(category=UserWarning,\n+ message=\"Using reduced precision for gradient.*\")\ndef test_select_and_gather_add(self, harness: primitive_harness.Harness):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n@@ -278,8 +283,8 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# TODO(necula): fix erf_inv bug on TPU\nif jtu.device_under_test() == \"tpu\":\nraise unittest.SkipTest(\"erf_inv bug on TPU: nan vs non-nan\")\n- # TODO: investigate: in the (b)float16 cases, TF and lax both return the same\n- # result in undefined cases.\n+ # TODO: investigate: in the (b)float16 cases, TF and lax both return the\n+ # same result in undefined cases.\nif not dtype in [np.float16, dtypes.bfloat16]:\n# erf_inv is not defined for arg <= -1 or arg >= 1\ndef custom_assert(result_jax, result_tf): # noqa: F811\n@@ -287,10 +292,12 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# lax.erf_inv returns NaN; tf.math.erf_inv return +/- inf\nspecial_cases = (arg < -1.) | (arg > 1.)\nnr_special_cases = np.count_nonzero(special_cases)\n- self.assertAllClose(np.full((nr_special_cases,), dtype(np.nan)),\n+ self.assertAllClose(np.full((nr_special_cases,), dtype(np.nan),\n+ dtype=dtype),\nresult_jax[special_cases])\nsigns = np.where(arg[special_cases] < 0., -1., 1.)\n- self.assertAllClose(np.full((nr_special_cases,), signs * dtype(np.inf)),\n+ self.assertAllClose(np.full((nr_special_cases,),\n+ signs * dtype(np.inf), dtype=dtype),\nresult_tf[special_cases])\n# non-special cases are equal\nself.assertAllClose(result_jax[~ special_cases],\n@@ -320,6 +327,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_binary_elementwise)\ndef test_binary_elementwise(self, harness):\n+ tol = None\nlax_name, dtype = harness.params[\"lax_name\"], harness.params[\"dtype\"]\nif lax_name in (\"igamma\", \"igammac\"):\n# TODO(necula): fix bug with igamma/f16\n@@ -336,28 +344,36 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# lax.igamma returns NaN when arg1 == arg2 == 0; tf.math.igamma returns 0\nspecial_cases = (arg1 == 0.) & (arg2 == 0.)\nnr_special_cases = np.count_nonzero(special_cases)\n- self.assertAllClose(np.full((nr_special_cases,), np.nan),\n+ self.assertAllClose(np.full((nr_special_cases,), np.nan, dtype=dtype),\nresult_jax[special_cases])\n- self.assertAllClose(np.full((nr_special_cases,), 0.),\n+ self.assertAllClose(np.full((nr_special_cases,), 0., dtype=dtype),\nresult_tf[special_cases])\n# non-special cases are equal\nself.assertAllClose(result_jax[~ special_cases],\nresult_tf[~ special_cases])\nif lax_name == \"igammac\":\n+ # On GPU, tolerance also needs to be adjusted in compiled mode\n+ if dtype == np.float64 and jtu.device_under_test() == 'gpu':\n+ tol = 1e-14\n# igammac is not defined when the first argument is <=0\ndef custom_assert(result_jax, result_tf): # noqa: F811\n# lax.igammac returns 1. when arg1 <= 0; tf.math.igammac returns NaN\nspecial_cases = (arg1 <= 0.) | (arg2 <= 0)\nnr_special_cases = np.count_nonzero(special_cases)\n- self.assertAllClose(np.full((nr_special_cases,), 1.),\n+ self.assertAllClose(np.full((nr_special_cases,), 1., dtype=dtype),\nresult_jax[special_cases])\n- self.assertAllClose(np.full((nr_special_cases,), np.nan),\n+ self.assertAllClose(np.full((nr_special_cases,), np.nan, dtype=dtype),\nresult_tf[special_cases])\n+ # On CPU, tolerance only needs to be adjusted in eager & graph modes\n+ tol = None\n+ if dtype == np.float64:\n+ tol = 1e-14\n+\n# non-special cases are equal\nself.assertAllClose(result_jax[~ special_cases],\n- result_tf[~ special_cases])\n+ result_tf[~ special_cases], atol=tol, rtol=tol)\nself.ConvertAndCompare(harness.dyn_fun, arg1, arg2,\n- custom_assert=custom_assert)\n+ custom_assert=custom_assert, atol=tol, rtol=tol)\n@primitive_harness.parameterized(primitive_harness.lax_binary_elementwise_logical)\ndef test_binary_elementwise_logical(self, harness):\n@@ -366,12 +382,19 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_betainc)\ndef test_betainc(self, harness: primitive_harness.Harness):\n- # TODO: https://www.tensorflow.org/api_docs/python/tf/math/betainc only supports\n- # float32/64 tests.\n+ dtype = harness.params[\"dtype\"]\n+ # TODO: https://www.tensorflow.org/api_docs/python/tf/math/betainc only\n+ # supports float32/64 tests.\n# TODO(bchetioui): investigate why the test actually fails in JAX.\n- if harness.params[\"dtype\"] in [np.float16, dtypes.bfloat16]:\n+ if dtype in [np.float16, dtypes.bfloat16]:\nraise unittest.SkipTest(\"(b)float16 not implemented in TF\")\n- self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n+\n+ tol = None\n+ if dtype is np.float64:\n+ tol = 1e-14\n+\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ atol=tol, rtol=tol)\n# TODO(necula): combine tests that are identical except for the harness\n# wait until we get more experience with using harnesses.\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix tests when running with JAX_ENABLE_X64=1. (#4261)
Fixed tests:
- test_binary_elementwise
- dynamic_update_slice
- fft
- population_count
- test_unary_elementwise
- top_k
- select_and_gather_add |
260,335 | 14.09.2020 12:31:51 | 25,200 | 7569e800146982bd4084599fc2f3cd95daa2a846 | revert (google failure)
* revert (google failure)
Some downstream user is relying on the rank of stax's biases being 1.
* only revert one change | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -49,8 +49,7 @@ def Dense(out_dim, W_init=glorot_normal(), b_init=normal()):\ndef init_fun(rng, input_shape):\noutput_shape = input_shape[:-1] + (out_dim,)\nk1, k2 = random.split(rng)\n- b_shape = (1,) * (len(output_shape) - 1) + (out_dim,)\n- W, b = W_init(k1, (input_shape[-1], out_dim)), b_init(k2, b_shape)\n+ W, b = W_init(k1, (input_shape[-1], out_dim)), b_init(k2, (out_dim,))\nreturn output_shape, (W, b)\ndef apply_fun(params, inputs, **kwargs):\nW, b = params\n"
}
] | Python | Apache License 2.0 | google/jax | revert #4277 (google failure) (#4281)
* revert #4277 (google failure)
Some downstream user is relying on the rank of stax's biases being 1.
* only revert one change |
260,298 | 15.09.2020 08:35:35 | -7,200 | 4e04d4eaf36da15e9c14f4d5ea41850334607dc3 | [jax2tf] Build a primitive harness for test_type_promotion.
* [jax2tf] Build a primitive harness for test_type_promotion.
We were previously generating the cases using `jtu.cases_from_list`,
which by default dropped 2 test cases (JAX_NUM_GENERATED_CASES=10,
number of generated cases = 12).
* [jax2tf] Fix the generated test cases for test_type_promotion. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -81,13 +81,13 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nelse:\nself.assertIn(p, tf_impl)\n- @parameterized.named_parameters(jtu.cases_from_list(\n+ @parameterized.named_parameters(\ndict(testcase_name=f\"_{f_jax.__name__}\",\nf_jax=f_jax)\nfor f_jax in [jnp.add, jnp.subtract, jnp.multiply, jnp.divide,\njnp.less, jnp.less_equal, jnp.equal, jnp.greater,\njnp.greater_equal, jnp.not_equal, jnp.maximum,\n- jnp.minimum]))\n+ jnp.minimum])\ndef test_type_promotion(self, f_jax=jnp.add):\n# We only test a few types here, as tensorflow does not support many\n# types like uint* or bool in binary ops.\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Build a primitive harness for test_type_promotion. (#4279)
* [jax2tf] Build a primitive harness for test_type_promotion.
We were previously generating the cases using `jtu.cases_from_list`,
which by default dropped 2 test cases (JAX_NUM_GENERATED_CASES=10,
number of generated cases = 12).
* [jax2tf] Fix the generated test cases for test_type_promotion. |
260,298 | 15.09.2020 10:40:07 | -7,200 | a5c2c4729e8e2a69b704df63d88311c50e6fe4ce | [jax2tf] Added support for x64 for the remaining test files
* [jax2tf] Added support for x64 in other test files.
This includes:
control_flow_ops_test.py
jax2tf_test.py
saved_model_test.py
stax_test | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"new_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"diff": "@@ -33,29 +33,29 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\ndef f_jax(pred, x):\nreturn lax.cond(pred, lambda t: t + 1., lambda f: f, x)\n- self.ConvertAndCompare(f_jax, True, 1.)\n- self.ConvertAndCompare(f_jax, False, 1.)\n+ self.ConvertAndCompare(f_jax, True, jnp.float_(1.))\n+ self.ConvertAndCompare(f_jax, False, jnp.float_(1.))\ndef test_cond_multiple_results(self):\ndef f_jax(pred, x):\nreturn lax.cond(pred, lambda t: (t + 1., 1.), lambda f: (f + 2., 2.), x)\n- self.ConvertAndCompare(f_jax, True, 1.)\n- self.ConvertAndCompare(f_jax, False, 1.)\n+ self.ConvertAndCompare(f_jax, True, jnp.float_(1.))\n+ self.ConvertAndCompare(f_jax, False, jnp.float_(1.))\ndef test_cond_partial_eval(self):\ndef f(x):\nres = lax.cond(True, lambda op: op * x, lambda op: op + x, x)\nreturn res\n- self.ConvertAndCompare(jax.grad(f), 1.)\n+ self.ConvertAndCompare(jax.grad(f), jnp.float_(1.))\ndef test_cond_units(self, with_function=True):\ndef g(x):\nreturn lax.cond(True, lambda x: x, lambda y: y, x)\n- self.ConvertAndCompare(g, 0.7)\n- self.ConvertAndCompare(jax.grad(g), 0.7)\n+ self.ConvertAndCompare(g, jnp.float_(0.7))\n+ self.ConvertAndCompare(jax.grad(g), jnp.float_(0.7))\ndef test_cond_custom_jvp(self):\n@@ -76,7 +76,7 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\ndef g(x):\nreturn lax.cond(True, f, lambda y: y, x)\n- arg = 0.7\n+ arg = jnp.float_(0.7)\nself.TransformConvertAndCompare(g, arg, None)\nself.TransformConvertAndCompare(g, arg, \"jvp\")\nself.TransformConvertAndCompare(g, arg, \"vmap\")\n@@ -104,7 +104,7 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\ndef g(x):\nreturn lax.cond(True, f, lambda y: y, x)\n- arg = 0.7\n+ arg = jnp.float_(0.7)\nself.TransformConvertAndCompare(g, arg, None)\nself.TransformConvertAndCompare(g, arg, \"vmap\")\nself.TransformConvertAndCompare(g, arg, \"grad_vmap\")\n@@ -117,7 +117,7 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\n# for(i=x; i < 4; i++);\nreturn lax.while_loop(lambda c: c < 4, lambda c: c + 1, x)\n- self.ConvertAndCompare(func, 0)\n+ self.ConvertAndCompare(func, jnp.int_(0))\ndef test_while(self):\n# Some constants to capture in the conditional branches\n@@ -188,7 +188,7 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\nreturn lax.while_loop(lambda carry: carry[0] < 10,\nlambda carry: (carry[0] + 1, f(carry[1])),\n(0, x))\n- arg = 0.7\n+ arg = jnp.float_(0.7)\nself.TransformConvertAndCompare(g, arg, None)\nself.TransformConvertAndCompare(g, arg, \"jvp\")\nself.TransformConvertAndCompare(g, arg, \"vmap\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -21,6 +21,7 @@ from absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\n+from jax import dtypes\nfrom jax import numpy as jnp\nfrom jax import test_util as jtu\nfrom jax.config import config\n@@ -36,7 +37,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ndef test_basics(self):\nf_jax = lambda x: jnp.sin(jnp.cos(x))\n- _, res_tf = self.ConvertAndCompare(f_jax, 0.7)\n+ _, res_tf = self.ConvertAndCompare(f_jax, jnp.float_(0.7))\nself.assertIsInstance(res_tf, tf.Tensor)\ndef test_pytrees(self):\n@@ -45,19 +46,19 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nx_a, x_dict = x\nreturn x_a * 2., {k : v * 3. for k, v in x_dict.items()}\n- x = (.7, {\"a\": .8, \"b\": .9})\n+ x = (jnp.float_(.7), {\"a\": jnp.float_(.8), \"b\": jnp.float_(.9)})\nself.ConvertAndCompare(f_jax, x)\ndef test_variable_input(self):\nf_jax = lambda x: jnp.sin(jnp.cos(x))\nf_tf = jax2tf.convert(f_jax)\n- v = tf.Variable(0.7)\n+ v = tf.Variable(0.7, dtype=dtypes.canonicalize_dtype(jnp.float_))\nself.assertIsInstance(f_tf(v), tf.Tensor)\nself.assertAllClose(f_jax(0.7), f_tf(v))\ndef test_jit(self):\nf_jax = jax.jit(lambda x: jnp.sin(jnp.cos(x)))\n- self.ConvertAndCompare(f_jax, 0.7)\n+ self.ConvertAndCompare(f_jax, jnp.float_(0.7))\ndef test_nested_jit(self):\nf_jax = jax.jit(lambda x: jnp.sin(jax.jit(jnp.cos)(x)))\n@@ -113,7 +114,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ndef test_function(self):\nf_jax = jax.jit(lambda x: jnp.sin(jnp.cos(x)))\n- self.ConvertAndCompare(f_jax, 0.7)\n+ self.ConvertAndCompare(f_jax, jnp.float_(0.7))\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"function={with_function}\",\n@@ -144,8 +145,9 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nf_tf = jax2tf.convert(f, with_gradient=True)\nif with_function:\nf_tf = tf.function(f_tf, autograph=False)\n- x = tf.Variable(4.)\n- y = tf.Variable(5.)\n+ default_float_type = dtypes.canonicalize_dtype(jnp.float_)\n+ x = tf.Variable(4., dtype=default_float_type)\n+ y = tf.Variable(5., dtype=default_float_type)\nwith tf.GradientTape(persistent=True) as tape:\nu, v = f_tf(x, y)\n@@ -166,8 +168,9 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nf_tf = jax2tf.convert(f, with_gradient=True)\nif with_function:\nf_tf = tf.function(f_tf, autograph=False)\n- x = tf.Variable(4.)\n- y = tf.Variable(5.)\n+ default_float_dtype = dtypes.canonicalize_dtype(jnp.float_)\n+ x = tf.Variable(4., dtype=default_float_dtype)\n+ y = tf.Variable(5., dtype=default_float_dtype)\nwith tf.GradientTape(persistent=True) as tape:\nuv = f_tf((x, y))\n@@ -201,8 +204,8 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nf_tf = jax2tf.convert(f, with_gradient=True)\nif with_function:\nf_tf = tf.function(f_tf, autograph=False)\n- self.assertAllClose(4. * 4., f_tf(4.))\n- x = tf.Variable(4.)\n+ self.assertAllClose(4. * 4., f_tf(jnp.float_(4.)))\n+ x = tf.Variable(4., dtype=dtypes.canonicalize_dtype(jnp.float_))\nwith tf.GradientTape() as tape:\ntape.watch(x)\ny = f_tf(x)\n@@ -235,8 +238,8 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nf_tf = jax2tf.convert(f, with_gradient=True)\nif with_function:\nf_tf = tf.function(f_tf, autograph=False)\n- self.assertAllClose(4. * 4., f_tf(4.))\n- x = tf.Variable(4.)\n+ self.assertAllClose(4. * 4., f_tf(jnp.float_(4.)))\n+ x = tf.Variable(4., dtype=dtypes.canonicalize_dtype(jnp.float_))\nwith tf.GradientTape() as tape:\ntape.watch(x)\ny = f_tf(x)\n@@ -283,7 +286,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ntangent_out = 3. * x * x_dot\nreturn primal_out, tangent_out\n- arg = 0.7\n+ arg = jnp.float_(0.7)\nself.TransformConvertAndCompare(f, arg, None)\nself.TransformConvertAndCompare(f, arg, \"jvp\")\nself.TransformConvertAndCompare(f, arg, \"vmap\")\n@@ -305,7 +308,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nreturn residual * ct_b,\nf.defvjp(f_fwd, f_bwd)\n- arg = 0.7\n+ arg = jnp.float_(0.7)\nself.TransformConvertAndCompare(f, arg, None)\nself.TransformConvertAndCompare(f, arg, \"vmap\")\nself.TransformConvertAndCompare(f, arg, \"grad\")\n@@ -335,7 +338,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nreturn y\nreturn g()\n- arg = 3.\n+ arg = jnp.float_(3.)\nself.TransformConvertAndCompare(f, arg, None)\nself.TransformConvertAndCompare(f, arg, \"grad\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"new_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"diff": "@@ -45,21 +45,22 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\nmodel.f = tf.function(jax2tf.convert(f_jax),\nautograph=False,\ninput_signature=[tf.TensorSpec([], tf.float32)])\n- x = np.array(0.7)\n+ x = np.array(0.7, dtype=jnp.float32)\nself.assertAllClose(model.f(x), f_jax(x))\nrestored_model = self.save_and_load_model(model)\nself.assertAllClose(restored_model.f(x), f_jax(x))\ndef test_gradient_disabled(self):\nf_jax = lambda x: x * x\n+\nmodel = tf.Module()\nmodel.f = tf.function(jax2tf.convert(f_jax, with_gradient=False),\nautograph=False,\ninput_signature=[tf.TensorSpec([], tf.float32)])\n- x = np.array(0.7)\n+ x = np.array(0.7, dtype=jnp.float32)\nself.assertAllClose(model.f(x), f_jax(x))\nrestored_model = self.save_and_load_model(model)\n- xv = tf.Variable(0.7)\n+ xv = tf.Variable(0.7, dtype=jnp.float32)\nself.assertAllClose(restored_model.f(x), f_jax(x))\nwith self.assertRaisesRegex(LookupError,\n@@ -86,10 +87,10 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\nmodel.f = tf.function(jax2tf.convert(f_jax, with_gradient=True),\nautograph=False,\ninput_signature=[tf.TensorSpec([], tf.float32)])\n- x = np.array(0.7)\n+ x = np.array(0.7, dtype=jnp.float32)\nself.assertAllClose(model.f(x), f_jax(x))\nrestored_model = self.save_and_load_model(model)\n- xv = tf.Variable(0.7)\n+ xv = tf.Variable(0.7, dtype=jnp.float32)\nself.assertAllClose(restored_model.f(x), f_jax(x))\nwith tf.GradientTape() as tape:\ny = restored_model.f(xv)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/stax_test.py",
"new_path": "jax/experimental/jax2tf/tests/stax_test.py",
"diff": "@@ -18,6 +18,7 @@ import jax\nfrom jax import test_util as jtu\nimport numpy as np\nimport os\n+import unittest\nimport sys\nfrom jax.experimental.jax2tf.tests import tf_test_util\n@@ -43,11 +44,12 @@ from jax.config import config\nconfig.parse_flags_with_absl()\n-\nclass StaxTest(tf_test_util.JaxToTfTestCase):\n@jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\ndef test_res_net(self):\n+ if config.FLAGS.jax_enable_x64:\n+ raise unittest.SkipTest(\"ResNet test fails on JAX when X64 is enabled\")\nkey = jax.random.PRNGKey(0)\nshape = (224, 224, 3, 1)\ninit_fn, apply_fn = resnet50.ResNet50(1000)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Added support for x64 for the remaining test files (#4282)
* [jax2tf] Added support for x64 in other test files.
This includes:
- control_flow_ops_test.py
- jax2tf_test.py
- saved_model_test.py
- stax_test |
260,335 | 15.09.2020 12:36:53 | 25,200 | 5520948b0cb4e7390e6039f9a7cb65ed1a5f95a5 | tweak traceback for unbound axis names | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -456,7 +456,7 @@ def axis_read(axis_env, axis_name):\ntry:\nreturn max(i for i, name in enumerate(axis_env.names) if name == axis_name)\nexcept ValueError:\n- raise NameError(\"unbound axis name: {}\".format(axis_name))\n+ raise NameError(\"unbound axis name: {}\".format(axis_name)) from None\ndef axis_groups(axis_env, name):\nif isinstance(name, (list, tuple)):\n"
}
] | Python | Apache License 2.0 | google/jax | tweak traceback for unbound axis names (#4295) |
260,411 | 16.09.2020 11:44:07 | -10,800 | a9430561604c0547729911ef55b176c0550b110d | [jax2tf] Enable testing for SVD on TPU for float16 | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "@@ -105,7 +105,7 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nif prim is lax_linalg.svd_p:\nnp_dtype = _to_np_dtype(args[0].dtype)\n- if np_dtype in [np.float16, dtypes.bfloat16]:\n+ if np_dtype in [dtypes.bfloat16]:\n# TODO: SVD on TPU for bfloat16 seems to work for JAX but fails for TF\ntf_unimpl(np_dtype, devs=[\"TPU\"])\nelif np_dtype in [np.complex64, np.complex128]:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -190,8 +190,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_linalg_svd)\n@jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\ndef test_svd(self, harness: primitive_harness.Harness):\n- if jtu.device_under_test() == \"tpu\":\n- raise unittest.SkipTest(\"TODO: test crashes the XLA compiler for some TPU variants\")\nif harness.params[\"dtype\"] in [np.float16, dtypes.bfloat16]:\nif jtu.device_under_test() != \"tpu\":\n# Does not work in JAX\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Enable testing for SVD on TPU for float16 (#4288) |
260,298 | 16.09.2020 10:46:32 | -7,200 | 1f95414f94ce5ed3f0b47c78c7d24e750f1af15f | [jax2tf] Add tests for the conversion of conv_general_dilated
* [jax2tf] Add tests for the conversion of conv_general_dilated.
This also adds the precision argument to the tfxla call which
was previously ignored.
* Separate orthogonal tests. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -625,7 +625,7 @@ def _concatenate(*operands, dimension=None):\ntf_impl[lax.concatenate_p] = _concatenate\n-def _conv_general_proto(dimension_numbers):\n+def _conv_general_dimension_numbers_proto(dimension_numbers):\n\"\"\"Converts a ConvDimensionNumbers to an XLA ConvolutionDimensionNumbers.\"\"\"\nassert isinstance(dimension_numbers, lax.ConvDimensionNumbers)\nlhs_spec, rhs_spec, out_spec = dimension_numbers\n@@ -664,6 +664,14 @@ def _conv_general_dilated_shape(lhs, rhs, window_strides, padding, lhs_dilation,\nprecision=precision)\nreturn out.shape\n+def _conv_general_precision_config_proto(precision):\n+ \"\"\"Convert an integer to an XLA.PrecisionConfig.\"\"\"\n+ if precision is None:\n+ return None\n+\n+ proto = xla_data_pb2.PrecisionConfig()\n+ proto.operand_precision.append(precision)\n+ return proto\ndef _conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation,\nrhs_dilation, dimension_numbers, feature_group_count,\n@@ -673,12 +681,13 @@ def _conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation,\nlhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\ndimension_numbers, feature_group_count, batch_group_count, lhs_shape,\nrhs_shape, precision)\n- # TODO(phawkins): handle precision\n- dnums_proto = _conv_general_proto(dimension_numbers)\n+ dnums_proto = _conv_general_dimension_numbers_proto(dimension_numbers)\n+ precision_config_proto = _conv_general_precision_config_proto(precision)\nassert batch_group_count == 1 # TODO(phawkins): implement batch_group_count\nout = tfxla.conv(\nlhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dnums_proto, feature_group_count)\n+ dnums_proto, feature_group_count=feature_group_count,\n+ precision_config=precision_config_proto)\n# TODO(tomhennigan): tf2xla should have a shape inference function.\nout.set_shape(out_shape)\nreturn out\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "# Primitives with limited support\n-*Last generated on (YYYY-MM-DD): 2020-09-11*\n+*Last generated on (YYYY-MM-DD): 2020-09-14*\n## Updating the documentation\n@@ -33,6 +33,9 @@ conversion to Tensorflow.\n| atanh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n| bessel_i0e | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n| bessel_i1e | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n+| conv_general_dilated | Missing TF support | Primitive is unimplemented for dtype complex128; likely bug in the HLO -> LLVM IR lowering of XlaConv | CPU, GPU, TPU |\n+| conv_general_dilated | Missing TF support | Primitive is unimplemented for dtype complex64; likely bug in the HLO -> LLVM IR lowering of XlaConv | CPU, GPU, TPU |\n+| conv_general_dilated | Missing TF support | Primitive is unimplemented; batch_group_count != 1 unsupported | CPU, GPU, TPU |\n| cosh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n| digamma | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n| erf | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n@@ -100,4 +103,4 @@ The conversion of the following JAX primitives is not yet implemented:\nThe following JAX primitives have a defined conversion but are known to be\nmissing tests:\n-`argmax`, `argmin`, `broadcast`, `clamp`, `complex`, `conj`, `conv_general_dilated`, `custom_lin`, `dot_general`, `fft`, `imag`, `integer_pow`, `real`, `rev`, `select_and_scatter`, `select_and_scatter_add`, `stop_gradient`\n+`argmax`, `argmin`, `broadcast`, `clamp`, `complex`, `conj`, `custom_lin`, `dot_general`, `imag`, `integer_pow`, `real`, `rev`, `select_and_scatter`, `select_and_scatter_add`, `stop_gradient`\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "@@ -65,12 +65,14 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\ndef tf_unimpl(np_dtype: Optional[NpDType] = None,\nadditional_msg: Optional[str] = None,\ndevs: Sequence[str] = all_devices) -> None:\n+\n+ missing_tf_support = \"Missing TF support\"\nmsg = \"Primitive is unimplemented\"\nif np_dtype is not None:\nmsg += f\" for dtype {np_dtype}\"\nif additional_msg:\nmsg += '; ' + additional_msg\n- _report_failure(\"Missing TF support\", msg, devs=devs)\n+ _report_failure(missing_tf_support, msg, devs=devs)\ndef _to_np_dtype(dtype) -> NpDType:\ntry:\n@@ -176,6 +178,15 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nif np_dtype in [np.uint32, np.uint64]:\ntf_unimpl(np_dtype)\n+ if prim is lax.conv_general_dilated_p:\n+ np_dtype = _to_np_dtype(args[0].dtype)\n+ batch_group_count = kwargs['batch_group_count']\n+ if batch_group_count != 1:\n+ tf_unimpl(additional_msg=\"batch_group_count != 1 unsupported\")\n+ if np_dtype in [np.complex64, np.complex128]:\n+ tf_unimpl(np_dtype, additional_msg=\"likely bug in the HLO -> LLVM IR \"\n+ \"lowering of XlaConv\")\n+\nif prim in [lax.acosh_p, lax.asinh_p, lax.atanh_p, lax.bessel_i0e_p,\nlax.bessel_i1e_p, lax.digamma_p, lax.erf_p, lax.erf_inv_p,\nlax.erfc_p, lax.lgamma_p, lax.round_p, lax.rsqrt_p]:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -875,3 +875,77 @@ random_split = tuple(\nnp.array([0, 0xFFFFFFFF], dtype=np.uint32),\nnp.array([0xFFFFFFFF, 0xFFFFFFFF], dtype=np.uint32)])\n)\n+\n+def _make_conv_harness(name, *, lhs_shape=(2, 3, 9, 10), rhs_shape=(3, 3, 4, 5),\n+ dtype=np.float32, window_strides=(1, 1), precision=None,\n+ padding=((0, 0), (0, 0)), lhs_dilation=(1, 1),\n+ rhs_dilation=(1, 1), feature_group_count=1,\n+ dimension_numbers=(\"NCHW\", \"OIHW\", \"NCHW\"),\n+ batch_group_count=1):\n+ return Harness(f\"_{name}_lhs={jtu.format_shape_dtype_string(lhs_shape, dtype)}_rhs={jtu.format_shape_dtype_string(rhs_shape, dtype)}_windowstrides={window_strides}_padding={padding}_lhsdilation={lhs_dilation}_rhsdilation={rhs_dilation}_dimensionnumbers={dimension_numbers}_featuregroupcount={feature_group_count}_batchgroupcount={batch_group_count}_precision={precision}\".replace(' ', ''),\n+ lax.conv_general_dilated,\n+ [RandArg(lhs_shape, dtype), RandArg(rhs_shape, dtype),\n+ StaticArg(window_strides), StaticArg(padding),\n+ StaticArg(lhs_dilation), StaticArg(rhs_dilation),\n+ StaticArg(dimension_numbers), StaticArg(feature_group_count),\n+ StaticArg(batch_group_count), StaticArg(precision)],\n+ lhs_shape=lhs_shape,\n+ rhs_shape=rhs_shape,\n+ dtype=dtype,\n+ window_strides=window_strides,\n+ padding=padding,\n+ lhs_dilation=lhs_dilation,\n+ rhs_dilation=rhs_dilation,\n+ dimension_numbers=dimension_numbers,\n+ feature_group_count=feature_group_count,\n+ batch_group_count=batch_group_count,\n+ precision=precision)\n+\n+lax_conv_general_dilated = tuple( # Validate dtypes and precision\n+ # This first harness runs the tests for all dtypes and precisions using\n+ # default values for all the other parameters. Variations of other parameters\n+ # can thus safely skip testing their corresponding default value.\n+ _make_conv_harness(\"dtype_precision\", dtype=dtype, precision=precision)\n+ for dtype in jtu.dtypes.all_inexact\n+ for precision in [None, lax.Precision.DEFAULT, lax.Precision.HIGH,\n+ lax.Precision.HIGHEST]\n+) + tuple( # Validate variations of feature_group_count and batch_group_count\n+ _make_conv_harness(\"group_counts\", lhs_shape=lhs_shape, rhs_shape=rhs_shape,\n+ feature_group_count=feature_group_count,\n+ batch_group_count=batch_group_count)\n+ for batch_group_count, feature_group_count in [\n+ (1, 2), # feature_group_count != 1\n+ (2, 1), # batch_group_count != 1\n+ ]\n+ for lhs_shape, rhs_shape in [\n+ ((2 * batch_group_count, 3 * feature_group_count, 9, 10),\n+ (3 * feature_group_count * batch_group_count, 3, 4, 5))\n+ ]\n+) + tuple( # Validate variations of window_strides\n+ _make_conv_harness(\"window_strides\", window_strides=window_strides)\n+ for window_strides in [\n+ (2, 3) # custom window\n+ ]\n+) + tuple( # Validate variations of padding\n+ _make_conv_harness(\"padding\", padding=padding)\n+ for padding in [\n+ ((1, 2), (0, 0)), # padding only one spatial axis\n+ ((1, 2), (2, 1)) # padding on both spatial axes\n+ ]\n+) + tuple( # Validate variations of dilations\n+ _make_conv_harness(\"dilations\", lhs_dilation=lhs_dilation,\n+ rhs_dilation=rhs_dilation)\n+ for lhs_dilation, rhs_dilation in [\n+ ((2, 2), (1, 1)), # dilation only on LHS (transposed)\n+ ((1, 1), (2, 3)), # dilation only on RHS (atrous)\n+ ((2, 3), (3, 2)) # dilation on both LHS and RHS (transposed & atrous)\n+ ]\n+) + tuple(\n+ _make_conv_harness(\"dimension_numbers\", lhs_shape=lhs_shape,\n+ rhs_shape=rhs_shape, dimension_numbers=dimension_numbers)\n+ # Dimension numbers and corresponding permutation\n+ for dimension_numbers, lhs_shape, rhs_shape in [\n+ ((\"NHWC\", \"HWIO\", \"NHWC\"), (2, 9, 10, 3), (4, 5, 3, 3)), # TF default\n+ ((\"NCHW\", \"HWIO\", \"NHWC\"), (2, 3, 9, 10), (4, 5, 3, 3)), # custom\n+ ]\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -453,6 +453,18 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ndef test_squeeze(self, harness: primitive_harness.Harness):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n+ @primitive_harness.parameterized(primitive_harness.lax_conv_general_dilated)\n+ def test_conv_general_dilated(self, harness: primitive_harness.Harness):\n+ tol = None\n+ # TODO(bchetioui): significant discrepancies in some float16 cases.\n+ if harness.params[\"dtype\"] is np.float16:\n+ tol = 1.\n+ # TODO(bchetioui): slight occasional discrepancy in float32 cases.\n+ elif harness.params[\"dtype\"] is np.float32:\n+ tol = 1e-5\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ atol=tol, rtol=tol)\n+\n@primitive_harness.parameterized(primitive_harness.lax_gather)\ndef test_gather(self, harness: primitive_harness.Harness):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Add tests for the conversion of conv_general_dilated (#4222)
* [jax2tf] Add tests for the conversion of conv_general_dilated.
This also adds the precision argument to the tfxla call which
was previously ignored.
* Separate orthogonal tests. |
260,411 | 16.09.2020 15:08:46 | -10,800 | a433c16feb2bc0703a160ad931b13dc65b93760d | [jax2tf] Disable some convolution tests | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -905,10 +905,10 @@ lax_conv_general_dilated = tuple( # Validate dtypes and precision\n# This first harness runs the tests for all dtypes and precisions using\n# default values for all the other parameters. Variations of other parameters\n# can thus safely skip testing their corresponding default value.\n- _make_conv_harness(\"dtype_precision\", dtype=dtype, precision=precision)\n- for dtype in jtu.dtypes.all_inexact\n- for precision in [None, lax.Precision.DEFAULT, lax.Precision.HIGH,\n- lax.Precision.HIGHEST]\n+ # _make_conv_harness(\"dtype_precision\", dtype=dtype, precision=precision)\n+ # for dtype in jtu.dtypes.all_inexact\n+ # for precision in [None, lax.Precision.DEFAULT, lax.Precision.HIGH,\n+ # lax.Precision.HIGHEST]\n) + tuple( # Validate variations of feature_group_count and batch_group_count\n_make_conv_harness(\"group_counts\", lhs_shape=lhs_shape, rhs_shape=rhs_shape,\nfeature_group_count=feature_group_count,\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Disable some convolution tests (#4303) |
260,411 | 16.09.2020 15:29:14 | -10,800 | dcaa28c624ef3402529786a5aa6dd3891f8779b0 | [jax2tf] More convolution test disabling | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -455,6 +455,8 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_conv_general_dilated)\ndef test_conv_general_dilated(self, harness: primitive_harness.Harness):\n+ if jtu.device_under_test() == \"gpu\":\n+ raise unittest.SkipTest(\"TODO: test failures on GPU\")\ntol = None\n# TODO(bchetioui): significant discrepancies in some float16 cases.\nif harness.params[\"dtype\"] is np.float16:\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] More convolution test disabling (#4304) |
260,298 | 17.09.2020 07:41:38 | -7,200 | 504e28278822fd683cd4aa96d1bf38cedae7c22b | [jax2tf] Fix precision casting problem in convolution.
In Python 3.6 (maybe 3.7 too?), the lax.Precision enumeration
was not implicitly casted to int, which made the construction
of the xla_data_pb2.PrecisionConfig object fail in the conversion
of convolution. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -670,7 +670,7 @@ def _conv_general_precision_config_proto(precision):\nreturn None\nproto = xla_data_pb2.PrecisionConfig()\n- proto.operand_precision.append(precision)\n+ proto.operand_precision.append(int(precision))\nreturn proto\ndef _conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -905,10 +905,10 @@ lax_conv_general_dilated = tuple( # Validate dtypes and precision\n# This first harness runs the tests for all dtypes and precisions using\n# default values for all the other parameters. Variations of other parameters\n# can thus safely skip testing their corresponding default value.\n- # _make_conv_harness(\"dtype_precision\", dtype=dtype, precision=precision)\n- # for dtype in jtu.dtypes.all_inexact\n- # for precision in [None, lax.Precision.DEFAULT, lax.Precision.HIGH,\n- # lax.Precision.HIGHEST]\n+ _make_conv_harness(\"dtype_precision\", dtype=dtype, precision=precision)\n+ for dtype in jtu.dtypes.all_inexact\n+ for precision in [None, lax.Precision.DEFAULT, lax.Precision.HIGH,\n+ lax.Precision.HIGHEST]\n) + tuple( # Validate variations of feature_group_count and batch_group_count\n_make_conv_harness(\"group_counts\", lhs_shape=lhs_shape, rhs_shape=rhs_shape,\nfeature_group_count=feature_group_count,\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix precision casting problem in convolution. (#4306)
In Python 3.6 (maybe 3.7 too?), the lax.Precision enumeration
was not implicitly casted to int, which made the construction
of the xla_data_pb2.PrecisionConfig object fail in the conversion
of convolution. |
260,285 | 17.09.2020 08:58:32 | -7,200 | c6b7269480c773eb312e3fe3f15938110927db20 | Support non-fragmenting mask of reshape | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -403,6 +403,8 @@ class MaskTrace(Trace):\nout_aval = primitive.abstract_eval(*(t.aval for t in tracers), **params)\nvals, polymorphic_shapes = unzip2((t.val, t.polymorphic_shape) for t in tracers)\nlogical_shapes = map(shape_as_value, polymorphic_shapes)\n+ # TODO(mattjj): generalize mask rule signature\n+ if primitive.name == 'reshape': params['polymorphic_shapes'] = polymorphic_shapes\nout = masking_rule(vals, logical_shapes, **params)\nif primitive.multiple_results:\nreturn map(partial(MaskTracer, self), out, (o.shape for o in out_aval))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3393,12 +3393,30 @@ def _reshape_batch_rule(batched_args, batch_dims, *, new_sizes, dimensions):\ndimensions = (0,) + tuple(np.add(1, dimensions))\nreturn reshape(operand, operand.shape[:1] + new_sizes, dimensions), 0\n+def _reshape_masking_rule(padded_args, logical_shapes, polymorphic_shapes,\n+ new_sizes, dimensions):\n+ operand, = padded_args\n+ old_shape, = polymorphic_shapes\n+ def is_poly(size): return type(size) is masking.Poly and not size.is_constant\n+ def merge_const_sizes(shape):\n+ \"\"\"Merges all nonpolymorphic sizes into the previous polymorphic size.\"\"\"\n+ poly_dims = [i for i, size in enumerate(shape) if is_poly(size)]\n+ return [prod(shape[start:stop])\n+ for start, stop in zip([0] + poly_dims, poly_dims + [len(shape)])]\n+ if merge_const_sizes(old_shape) != merge_const_sizes(new_sizes):\n+ raise NotImplementedError(\n+ \"Reshape on padded dimensions causing fragmentation is not supported.\")\n+\n+ return reshape(operand,\n+ new_sizes=masking.padded_shape_as_value(new_sizes),\n+ dimensions=dimensions)\n+\nreshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,\n'reshape', _reshape_translation_rule)\nreshape_p.def_impl(_reshape_impl)\nad.deflinear2(reshape_p, _reshape_transpose_rule)\nbatching.primitive_batchers[reshape_p] = _reshape_batch_rule\n-\n+masking.masking_rules[reshape_p] = _reshape_masking_rule\ndef _rev_shape_rule(operand, *, dimensions):\n_check_shapelike('rev', 'dimensions', dimensions)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1130,14 +1130,11 @@ def _compute_newshape(a, newshape):\ntry: iter(newshape)\nexcept: iterable = False\nelse: iterable = True\n- if iterable:\n- newshape = [core.concrete_or_error(int, d,\n- \"The error arose in jax.numpy.reshape.\")\n- for d in newshape]\n- else:\n- newshape = core.concrete_or_error(int, newshape,\n- \"The error arose in jax.numpy.reshape.\")\n- newsize = _prod(newshape)\n+ def check(size):\n+ return size if type(size) is Poly else core.concrete_or_error(\n+ int, size, \"The error arose in jax.numpy.reshape.\")\n+ newshape = [check(size) for size in newshape] if iterable else check(newshape)\n+ newsize = _prod((newshape,) if type(newshape) is Poly else newshape)\nif newsize < 0:\nfix = a.size // -newsize\nreturn [d if d != -1 else fix for d in newshape]\n@@ -1166,7 +1163,8 @@ def _reshape_method(a, *newshape, **kwargs):\ninvalid_kwargs = \"'{}'\".format(\"'\".join(kwargs))\nmsg = \"{} are invalid keyword arguments for this function\"\nraise TypeError(msg.format(invalid_kwargs)) # different from NumPy error\n- if len(newshape) == 1 and not isinstance(newshape[0], int):\n+ if (len(newshape) == 1 and not isinstance(newshape[0], int) and\n+ type(newshape[0]) is not Poly):\nnewshape = newshape[0]\nreturn _reshape(a, newshape, order=order)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -597,7 +597,47 @@ class MaskingTest(jtu.JaxTestCase):\n# TODO: self.check(lambda x: lax.slice(x, (x.shape[0] // 2,), (x.shape[0],)), ['2*n'], dict(n=jnp.array([2, 3])), 'n')\ndef test_reshape(self):\n- raise SkipTest\n+ self.check(lambda x: jnp.reshape(x, (x.shape[1], 2, 4, 1)),\n+ ['1, n, 4, 2'], 'n, 2, 4, 1', dict(n=2), [(1, 3, 4, 2)],\n+ ['float_'], jtu.rand_default(self.rng()))\n+\n+ self.check(lambda x: jnp.reshape(x, (x.shape[0] * 2,)),\n+ ['n, 2'], '2 * n', dict(n=2), [(3, 2)],\n+ ['float_'], jtu.rand_default(self.rng()))\n+\n+ self.check(lambda x: jnp.reshape(x, (x.shape[0] // 2, 2)),\n+ ['2 * n'], 'n, 2', dict(n=2), [(6,)],\n+ ['float_'], jtu.rand_default(self.rng()))\n+\n+ self.check(lambda x: jnp.reshape(x, (x.shape[0] * 4, 2)),\n+ ['n, 2, 4'], '4 * n, 2', dict(n=2), [(3, 2, 4)],\n+ ['float_'], jtu.rand_default(self.rng()))\n+\n+ self.check(lambda x: jnp.reshape(x, ((x.shape[0] - 1) // 4 + 1, 2, 4)),\n+ ['4 * n + 4, 2'], 'n + 1, 2, 4', dict(n=2), [(12, 2)],\n+ ['float_'], jtu.rand_default(self.rng()))\n+\n+ msg = \"Reshape on padded dimensions causing fragmentation is not supported.\"\n+ with self.assertRaisesRegex(NotImplementedError, msg):\n+ self.check(lambda x: jnp.reshape(x, np.prod(x.shape)),\n+ ['a, b'], 'a*b', dict(a=2, b=3), [(3, 4)],\n+ ['float_'], jtu.rand_default(self.rng()))\n+\n+ with self.assertRaisesRegex(NotImplementedError, msg):\n+ self.check(lambda x: jnp.reshape(x, (x.shape[1], x.shape[0])),\n+ ['a, b'], 'b, a', dict(a=2, b=3), [(3, 4)],\n+ ['float_'], jtu.rand_default(self.rng()))\n+\n+ with self.assertRaisesRegex(NotImplementedError, msg):\n+ self.check(lambda x: jnp.reshape(x, (x.shape[1] * 2,)),\n+ ['2, n'], '2 * n', dict(n=2), [(2, 3)],\n+ ['float_'], jtu.rand_default(self.rng()))\n+\n+ if False:\n+ # TODO fix lax._compute_newshape on polymorphic shapes:\n+ self.check(lambda x: jnp.reshape(x, (x.shape[0], -1)),\n+ ['n, 3, 1, 2'], 'n, 6', dict(n=1), [(2, 3, 1, 2)],\n+ ['float_'], jtu.rand_default(self.rng()))\ndef test_transpose(self):\nself.check(lambda x: lax.transpose(x, (1, 0, 2)),\n"
}
] | Python | Apache License 2.0 | google/jax | Support non-fragmenting mask of reshape (#4264) |
260,335 | 16.09.2020 23:59:58 | 25,200 | b81c246a182a9be7df376f79b3b6a5d4e3add1bd | move the trace liveness check from | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -365,6 +365,7 @@ class Trace:\ndef full_raise(self, val) -> 'Tracer':\nif not isinstance(val, Tracer):\nreturn self.pure(val)\n+ val._assert_live()\nlevel = self.level\nsublevel = self.sublevel\nif val._trace.main is self.main:\n@@ -742,8 +743,8 @@ def full_lower(val):\nreturn val\ndef find_top_trace(xs) -> Trace:\n- traces = [x._assert_live() or x._trace.main for x in xs if isinstance(x, Tracer)] # type: ignore\n- top_main = max(traces, default=None, key=attrgetter('level'))\n+ top_main = max((x._trace.main for x in xs if isinstance(x, Tracer)),\n+ default=None, key=attrgetter('level'))\ndynamic = thread_local_state.trace_state.trace_stack.dynamic\ntop_main = (dynamic if top_main is None or dynamic.level > top_main.level\nelse top_main)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1662,13 +1662,10 @@ class APITest(jtu.JaxTestCase):\nself._saved_tracer = x\nreturn x\n- def test_escaped_tracers_diffent_top_level_traces(self):\n+ def test_escaped_tracers_different_top_level_traces(self):\napi.jit(self.helper_save_tracer)(0.)\nwith self.assertRaisesRegex(\n- core.UnexpectedTracerError,\n- re.compile(\n- \"Encountered an unexpected tracer.*Different traces at same level\",\n- re.DOTALL)):\n+ core.UnexpectedTracerError, \"Encountered an unexpected tracer\"):\napi.jit(lambda x: self._saved_tracer)(0.)\ndef test_escaped_tracers_cant_lift_sublevels(self):\n"
}
] | Python | Apache License 2.0 | google/jax | move the trace liveness check from #4312 (#4315) |
260,298 | 17.09.2020 10:03:31 | -7,200 | b1d0f87648f73b06091ea3929a52b5d572391088 | [jax2tf] Group error messages by dtype in pprint_limitations.
* [jax2tf] Group error messages by dtype in pprint_limitations.
This makes the output of the categorizer more synthetic in cases
when the error is exactly the same for a given primitive on a set
of devices for different dtypes. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "# Primitives with limited support\n-*Last generated on (YYYY-MM-DD): 2020-09-14*\n+*Last generated on (YYYY-MM-DD): 2020-09-17*\n## Updating the documentation\n@@ -18,79 +18,50 @@ cases even for JAX, e.g., sort does not work for complex numbers on TPUs.\nThis table includes only those cases that **work** in JAX but **fail** after\nconversion to Tensorflow.\n-| Affected primitive | Type of limitation | Description | Devices affected |\n-| --- | --- | --- | --- |\n-| acosh | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| acosh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n-| add | Missing TF support | Primitive is unimplemented for dtype uint16 | CPU, GPU, TPU |\n-| add | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n-| add | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n-| asinh | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| asinh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n-| atan2 | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU, TPU |\n-| atan2 | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n-| atanh | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| atanh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n-| bessel_i0e | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| bessel_i1e | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| conv_general_dilated | Missing TF support | Primitive is unimplemented for dtype complex128; likely bug in the HLO -> LLVM IR lowering of XlaConv | CPU, GPU, TPU |\n-| conv_general_dilated | Missing TF support | Primitive is unimplemented for dtype complex64; likely bug in the HLO -> LLVM IR lowering of XlaConv | CPU, GPU, TPU |\n-| conv_general_dilated | Missing TF support | Primitive is unimplemented; batch_group_count != 1 unsupported | CPU, GPU, TPU |\n-| cosh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n-| digamma | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| erf | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| erf_inv | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| erf_inv | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n-| erfc | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| fft | Missing TF support | Primitive is unimplemented for dtype complex128; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n-| fft | Missing TF support | Primitive is unimplemented for dtype float64; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n-| lgamma | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| max | Missing TF support | Primitive is unimplemented for dtype bool | CPU, GPU, TPU |\n-| max | Missing TF support | Primitive is unimplemented for dtype complex128 | CPU, GPU, TPU |\n-| max | Missing TF support | Primitive is unimplemented for dtype complex64 | CPU, GPU, TPU |\n-| max | Missing TF support | Primitive is unimplemented for dtype int8 | CPU, GPU, TPU |\n-| max | Missing TF support | Primitive is unimplemented for dtype uint16 | CPU, GPU, TPU |\n-| max | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n-| max | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n-| min | Missing TF support | Primitive is unimplemented for dtype bool | CPU, GPU, TPU |\n-| min | Missing TF support | Primitive is unimplemented for dtype complex128 | CPU, GPU, TPU |\n-| min | Missing TF support | Primitive is unimplemented for dtype complex64 | CPU, GPU, TPU |\n-| min | Missing TF support | Primitive is unimplemented for dtype int8 | CPU, GPU, TPU |\n-| min | Missing TF support | Primitive is unimplemented for dtype uint16 | CPU, GPU, TPU |\n-| min | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n-| min | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n-| mul | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n-| mul | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n-| nextafter | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU, TPU |\n-| nextafter | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n-| population_count | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n-| population_count | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n-| qr | Missing TF support | Primitive is unimplemented for dtype complex128 | CPU, GPU, TPU |\n-| qr | Missing TF support | Primitive is unimplemented for dtype complex64 | CPU, GPU, TPU |\n-| reduce_window_sum | Missing TF support | Primitive is unimplemented for dtype uint16 | CPU, GPU, TPU |\n-| reduce_window_sum | Missing TF support | Primitive is unimplemented for dtype uint32 | CPU, GPU, TPU |\n-| reduce_window_sum | Missing TF support | Primitive is unimplemented for dtype uint64 | CPU, GPU, TPU |\n-| rem | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU, TPU |\n-| rem | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n-| round | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| rsqrt | Missing TF support | Primitive is unimplemented for dtype bfloat16 | CPU, GPU |\n-| scatter-add | Missing TF support | Primitive is unimplemented for dtype complex64 | TPU |\n-| scatter-mul | Missing TF support | Primitive is unimplemented for dtype complex64 | TPU |\n-| select_and_gather_add | Missing TF support | Primitive is unimplemented for dtype float32 | TPU |\n-| select_and_gather_add | Missing TF support | Primitive is unimplemented for dtype float64 | CPU, GPU |\n-| select_and_gather_add | Missing TF support | Primitive is unimplemented for dtype float64 | TPU |\n-| sinh | Missing TF support | Primitive is unimplemented for dtype float16 | CPU, GPU, TPU |\n-| sort | Missing TF support | Primitive is unimplemented for dtype bool; sorting 2 arrays where the first one is an array of booleans is not supported for XlaSort | CPU, GPU, TPU |\n-| sort | Missing TF support | Primitive is unimplemented for dtype complex128 | CPU, GPU, TPU |\n-| sort | Missing TF support | Primitive is unimplemented for dtype complex64 | CPU, GPU, TPU |\n-| sort | Missing TF support | Primitive is unimplemented; only sorting on last dimension is supported for XlaSort | CPU, GPU, TPU |\n-| sort | Missing TF support | Primitive is unimplemented; sorting more than 2 arrays is not supported for XlaSort | CPU, GPU, TPU |\n-| sort | Missing TF support | Primitive is unimplemented; stable sort not implemented for XlaSort | CPU, GPU, TPU |\n-| svd | Missing TF support | Primitive is unimplemented for dtype complex128; this works on JAX because JAX uses a custom implementation | CPU, GPU |\n-| svd | Missing TF support | Primitive is unimplemented for dtype complex64; this works on JAX because JAX uses a custom implementation | CPU, GPU |\n-| top_k | Missing TF support | Primitive is unimplemented for dtype float64; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n-| top_k | Missing TF support | Primitive is unimplemented for dtype int64; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n-| top_k | Missing TF support | Primitive is unimplemented for dtype uint64; this is a problem only in compiled mode (experimental_compile=True)) | CPU, GPU, TPU |\n+| Affected primitive | Type of limitation | Description | Affected dtypes | Affected devices |\n+| --- | --- | --- | --- | --- |\n+| acosh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n+| acosh | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| add | Missing TF support | Primitive is unimplemented | uint16, uint32, uint64 | CPU, GPU, TPU |\n+| asinh | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| asinh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n+| atan2 | Missing TF support | Primitive is unimplemented | bfloat16, float16 | CPU, GPU, TPU |\n+| atanh | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| atanh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n+| bessel_i0e | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| bessel_i1e | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| conv_general_dilated | Missing TF support | Primitive is unimplemented; likely bug in the HLO -> LLVM IR lowering of XlaConv | complex64, complex128 | CPU, GPU, TPU |\n+| conv_general_dilated | Missing TF support | Primitive is unimplemented; batch_group_count != 1 unsupported | ALL | CPU, GPU, TPU |\n+| cosh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n+| digamma | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| erf | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| erf_inv | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| erf_inv | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n+| erfc | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| fft | Missing TF support | Primitive is unimplemented; this is a problem only in compiled mode (experimental_compile=True)) | complex128, float64 | CPU, GPU, TPU |\n+| lgamma | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| max | Missing TF support | Primitive is unimplemented | bool, complex128, complex64, int8, uint16, uint32, uint64 | CPU, GPU, TPU |\n+| min | Missing TF support | Primitive is unimplemented | bool, complex128, complex64, int8, uint16, uint32, uint64 | CPU, GPU, TPU |\n+| mul | Missing TF support | Primitive is unimplemented | uint32, uint64 | CPU, GPU, TPU |\n+| nextafter | Missing TF support | Primitive is unimplemented | bfloat16, float16 | CPU, GPU, TPU |\n+| population_count | Missing TF support | Primitive is unimplemented | uint32, uint64 | CPU, GPU, TPU |\n+| qr | Missing TF support | Primitive is unimplemented | complex128, complex64 | CPU, GPU, TPU |\n+| reduce_window_sum | Missing TF support | Primitive is unimplemented | uint16, uint32, uint64 | CPU, GPU, TPU |\n+| rem | Missing TF support | Primitive is unimplemented | bfloat16, float16 | CPU, GPU, TPU |\n+| round | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| rsqrt | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| scatter-add | Missing TF support | Primitive is unimplemented | complex64 | TPU |\n+| scatter-mul | Missing TF support | Primitive is unimplemented | complex64 | TPU |\n+| select_and_gather_add | Missing TF support | Primitive is unimplemented | float32, float64 | TPU |\n+| select_and_gather_add | Missing TF support | Primitive is unimplemented | float64 | CPU, GPU |\n+| sinh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n+| sort | Missing TF support | Primitive is unimplemented | complex128, complex64 | CPU, GPU, TPU |\n+| sort | Missing TF support | Primitive is unimplemented; only sorting on last dimension is supported for XlaSort | ALL | CPU, GPU, TPU |\n+| sort | Missing TF support | Primitive is unimplemented; sorting 2 arrays where the first one is an array of booleans is not supported for XlaSort | bool | CPU, GPU, TPU |\n+| sort | Missing TF support | Primitive is unimplemented; sorting more than 2 arrays is not supported for XlaSort | ALL | CPU, GPU, TPU |\n+| sort | Missing TF support | Primitive is unimplemented; stable sort not implemented for XlaSort | ALL | CPU, GPU, TPU |\n+| svd | Missing TF support | Primitive is unimplemented; this works on JAX because JAX uses a custom implementation | complex128, complex64 | CPU, GPU |\n+| top_k | Missing TF support | Primitive is unimplemented; this is a problem only in compiled mode (experimental_compile=True)) | float64, int64, uint64 | CPU, GPU, TPU |\n## Not yet implemented primitive conversions\n@@ -103,4 +74,4 @@ The conversion of the following JAX primitives is not yet implemented:\nThe following JAX primitives have a defined conversion but are known to be\nmissing tests:\n-`argmax`, `argmin`, `broadcast`, `clamp`, `complex`, `conj`, `custom_lin`, `dot_general`, `imag`, `integer_pow`, `real`, `rev`, `select_and_scatter`, `select_and_scatter_add`, `stop_gradient`\n+`argmax`, `argmin`, `broadcast`, `clamp`, `complex`, `conj`, `custom_lin`, `device_put`, `dot_general`, `imag`, `integer_pow`, `real`, `rev`, `select_and_scatter`, `select_and_scatter_add`, `stop_gradient`, `tie_in`\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+from collections import defaultdict\nimport datetime\nimport functools\nimport numpy as np\n-from typing import Any, Callable, Collection, List, NamedTuple, Optional, \\\n+from typing import Any, Callable, Collection, Dict, List, NamedTuple, Optional,\\\nTuple, Sequence, Set\nfrom jax import core\n@@ -32,14 +33,15 @@ def to_jax_dtype(tf_dtype):\nreturn dtypes.bfloat16\nreturn tf_dtype.as_numpy_dtype\n+NpDType = Any\n+\nLimitation = NamedTuple(\"Limitation\", [ (\"primitive_name\", str)\n, (\"error_type\", str)\n, (\"error_string\", str)\n+ , (\"affected_dtypes\", Tuple[NpDType,...])\n, (\"devices\", Tuple[str,...])\n])\n-NpDType = Any\n-\ndef categorize(prim: core.Primitive, *args, **kwargs) \\\n-> List[Limitation]:\n\"\"\"\n@@ -59,8 +61,12 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nall_devices = [\"CPU\", \"GPU\", \"TPU\"]\ndef _report_failure(error_type: str, msg: str,\n+ affected_dtype: Optional[NpDType] = None,\ndevs: Sequence[str] = all_devices) -> None:\n- limitations.append(Limitation(prim.name, error_type, msg, tuple(devs)))\n+ affected_dtypes = (\n+ tuple([affected_dtype]) if affected_dtype is not None else tuple())\n+ limitations.append(Limitation(prim.name, error_type, msg,\n+ affected_dtypes, tuple(devs)))\ndef tf_unimpl(np_dtype: Optional[NpDType] = None,\nadditional_msg: Optional[str] = None,\n@@ -68,11 +74,9 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nmissing_tf_support = \"Missing TF support\"\nmsg = \"Primitive is unimplemented\"\n- if np_dtype is not None:\n- msg += f\" for dtype {np_dtype}\"\nif additional_msg:\nmsg += '; ' + additional_msg\n- _report_failure(missing_tf_support, msg, devs=devs)\n+ _report_failure(missing_tf_support, msg, np_dtype, devs=devs)\ndef _to_np_dtype(dtype) -> NpDType:\ntry:\n@@ -215,6 +219,22 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\n\"mode (experimental_compile=True))\"))\nreturn limitations\n+def merge_similar_limitations(limitations: Sequence[Limitation]) \\\n+ -> Sequence[Limitation]:\n+ \"\"\"Merges similar limitations together.\"\"\"\n+ merged_limitations: Dict[Limitation, Set[NpDType]] = defaultdict(set)\n+\n+ for lim in limitations:\n+ key = Limitation(lim.primitive_name, lim.error_type, lim.error_string,\n+ tuple(), lim.devices)\n+ value = lim.affected_dtypes\n+ merged_limitations[key].update(value)\n+\n+ def _perform_merge(key: Limitation, values: Set[NpDType]) -> Limitation:\n+ return key._replace(affected_dtypes=tuple(values))\n+\n+ return list(map(lambda kvp: _perform_merge(*kvp), merged_limitations.items()))\n+\ndef prettify(limitations: Sequence[Limitation]) -> str:\n\"\"\"Constructs a summary markdown table based on a list of limitations.\"\"\"\nlimitations = sorted(list(set(limitations)))\n@@ -225,7 +245,8 @@ def prettify(limitations: Sequence[Limitation]) -> str:\ncolumn_names = [ 'Affected primitive'\n, 'Type of limitation'\n, 'Description'\n- , 'Devices affected' ]\n+ , 'Affected dtypes'\n+ , 'Affected devices' ]\ntable = [column_names, ['---'] * len(column_names)]\n@@ -233,6 +254,8 @@ def prettify(limitations: Sequence[Limitation]) -> str:\ntable.append([ lim.primitive_name\n, lim.error_type\n, lim.error_string\n+ , ('ALL' if len(lim.affected_dtypes) == 0 else\n+ ', '.join(sorted(list(map(str, lim.affected_dtypes)))))\n, ', '.join(lim.devices)\n])\n@@ -262,6 +285,7 @@ def pprint_limitations(limitations: Sequence[Limitation],\ncovered_primitives: Set[core.Primitive],\noutput_file: str, template_file: str) -> None:\n+ limitations = merge_similar_limitations(limitations)\nlimited_support_table = prettify(limitations)\nnot_yet_impl_primitives = prettify_not_yet_implemented()\nnot_yet_covered_primitives = prettify_not_yet_covered(covered_primitives)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Group error messages by dtype in pprint_limitations. (#4307)
* [jax2tf] Group error messages by dtype in pprint_limitations.
This makes the output of the categorizer more synthetic in cases
when the error is exactly the same for a given primitive on a set
of devices for different dtypes. |
260,411 | 17.09.2020 11:45:11 | -10,800 | 2ff593747e16651521f84de67e762c17ca34363d | [jax2tf] Change precision of test_conv to fix TPU tests | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -455,15 +455,19 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_conv_general_dilated)\ndef test_conv_general_dilated(self, harness: primitive_harness.Harness):\n- if jtu.device_under_test() == \"gpu\":\n- raise unittest.SkipTest(\"TODO: test failures on GPU\")\ntol = None\n+ if jtu.device_under_test() == \"gpu\":\n+ tol = 1e-4\n+ elif jtu.device_under_test() == \"tpu\":\n+ tol = 1e-3\n# TODO(bchetioui): significant discrepancies in some float16 cases.\n- if harness.params[\"dtype\"] is np.float16:\n+ if harness.params[\"dtype\"] == np.float16:\ntol = 1.\n# TODO(bchetioui): slight occasional discrepancy in float32 cases.\n- elif harness.params[\"dtype\"] is np.float32:\n- tol = 1e-5\n+ elif harness.params[\"dtype\"] == np.float32:\n+ tol = 0.5 if jtu.device_under_test() == \"tpu\" else 1e-4\n+ elif harness.params[\"dtype\"] == np.complex64 and jtu.device_under_test() == \"tpu\":\n+ tol = 0.1\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\natol=tol, rtol=tol)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Change precision of test_conv to fix TPU tests (#4317) |
260,411 | 17.09.2020 16:31:17 | -10,800 | d74e81cc8b66260000bbe1f3fe90a0bfc2b9777d | [jax2tf] Disable complex convolution test on GPU: crash in TF | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -455,6 +455,9 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_conv_general_dilated)\ndef test_conv_general_dilated(self, harness: primitive_harness.Harness):\n+ if jtu.device_under_test() == \"gpu\" and harness.params[\"dtype\"] in [np.complex64, np.complex128]:\n+ raise unittest.SkipTest(\"TODO: crash on GPU in TF\")\n+\ntol = None\nif jtu.device_under_test() == \"gpu\":\ntol = 1e-4\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Disable complex convolution test on GPU: crash in TF (#4319) |
260,604 | 17.09.2020 21:39:18 | -19,080 | 40e20242db0ed1d8cceb1d93b78d07c248e693a6 | Fix code quality issues
Changes:
Fix unnecessary generator
Iterate dictionary directly instead of calling .keys()
Remove global statement at the module level
Use list() instead of a list comprehension
Use with statement to open the file
Merge isinstance calls | [
{
"change_type": "MODIFY",
"old_path": "build/build.py",
"new_path": "build/build.py",
"diff": "@@ -112,9 +112,9 @@ def download_and_verify_bazel():\nsys.stdout.write(\"\\n\")\n# Verify that the downloaded Bazel binary has the expected SHA256.\n- downloaded_file = open(tmp_path, \"rb\")\n+ with open(tmp_path, \"rb\") as downloaded_file:\ncontents = downloaded_file.read()\n- downloaded_file.close()\n+\ndigest = hashlib.sha256(contents).hexdigest()\nif digest != package.sha256:\nprint(\n@@ -123,9 +123,8 @@ def download_and_verify_bazel():\nsys.exit(-1)\n# Write the file as the bazel file name.\n- out_file = open(package.file, \"wb\")\n+ with open(package.file, \"wb\") as out_file:\nout_file.write(contents)\n- out_file.close()\n# Mark the file as executable.\nst = os.stat(package.file)\n@@ -223,7 +222,7 @@ build:short_logs --output_filter=DONT_MATCH_ANYTHING\ndef write_bazelrc(cuda_toolkit_path=None, cudnn_install_path=None, **kwargs):\n- f = open(\"../.bazelrc\", \"w\")\n+ with open(\"../.bazelrc\", \"w\") as f:\nf.write(BAZELRC_TEMPLATE.format(**kwargs))\nif cuda_toolkit_path:\nf.write(\"build --action_env CUDA_TOOLKIT_PATH=\\\"{cuda_toolkit_path}\\\"\\n\"\n@@ -231,7 +230,6 @@ def write_bazelrc(cuda_toolkit_path=None, cudnn_install_path=None, **kwargs):\nif cudnn_install_path:\nf.write(\"build --action_env CUDNN_INSTALL_PATH=\\\"{cudnn_install_path}\\\"\\n\"\n.format(cudnn_install_path=cudnn_install_path))\n- f.close()\nBANNER = r\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "build/setup.py",
"new_path": "build/setup.py",
"diff": "@@ -16,7 +16,6 @@ from setuptools import setup\nfrom glob import glob\nimport os\n-global __version__\n__version__ = None\nwith open('jaxlib/version.py') as f:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/abstract_arrays.py",
"new_path": "jax/abstract_arrays.py",
"diff": "@@ -67,7 +67,7 @@ def _make_concrete_python_scalar(t, x):\nnp.array(x, dtype=dtypes.python_scalar_dtypes[t]),\nweak_type=True)\n-for t in dtypes.python_scalar_dtypes.keys():\n+for t in dtypes.python_scalar_dtypes:\ncore.pytype_aval_mappings[t] = partial(_make_concrete_python_scalar, t)\nad_util.jaxval_zeros_likers[t] = partial(_zeros_like_python_scalar, t)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1197,7 +1197,7 @@ def axis_frame(axis_name):\nfor frame in reversed(frames):\nif frame.name == axis_name:\nreturn frame\n- else:\n+\nraise NameError(\"unbound axis name: {}\".format(axis_name))\ndef axis_index(axis_name):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -785,7 +785,7 @@ def get_num_partitions(*partitions):\nif len(partition_specs) == 0:\n# Everything is specified as replicated (all Nones).\nreturn None\n- num_partitions_set = set(np.prod(spec) for spec in partition_specs)\n+ num_partitions_set = {np.prod(spec) for spec in partition_specs}\nif len(num_partitions_set) > 1:\nraise ValueError(\nf\"All partition specs must use the same number of total partitions, \"\n@@ -1291,8 +1291,8 @@ class DynamicAxisEnv(list):\nfor frame in reversed(self):\nif frame.name == axis_name:\nreturn frame\n- else:\n- assert False\n+\n+ raise AssertionError\n@property\ndef sizes(self):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -278,7 +278,7 @@ def _device_from_arg_devices(devices: Sequence[Optional[Device]]) -> Optional[De\nValueError if input devices are inconsistent.\n\"\"\"\ntry:\n- device, = set(d for d in devices if d is not None) or (None,)\n+ device, = {d for d in devices if d is not None} or (None,)\nreturn device\nexcept ValueError as err:\nmsg = \"primitive arguments must be colocated on the same device, got {}\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3125,7 +3125,7 @@ def _concatenate_shape_rule(*operands, **kwargs):\nmsg = \"All objects to concatenate must be arrays, got {}.\"\nop = next(op for op in operands if not isinstance(op, UnshapedArray))\nraise TypeError(msg.format(type(op)))\n- if len(set(operand.ndim for operand in operands)) != 1:\n+ if len({operand.ndim for operand in operands}) != 1:\nmsg = \"Cannot concatenate arrays with different ranks, got {}.\"\nraise TypeError(msg.format(\", \".join(str(o.ndim) for o in operands)))\nshapes = np.array([operand.shape for operand in operands])\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -2413,8 +2413,7 @@ def associative_scan(fn, elems, reverse=False):\nresults = lowered_fn([odd_elem[:-1] for odd_elem in odd_elems],\n[elem[2::2] for elem in elems])\nelse:\n- results = lowered_fn([odd_elem for odd_elem in odd_elems],\n- [elem[2::2] for elem in elems])\n+ results = lowered_fn(list(odd_elems), [elem[2::2] for elem in elems])\n# The first element of a scan is the same as the first element\n# of the original `elems`.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -167,7 +167,7 @@ def _validate_axis_index_groups(axis_index_groups):\nif any(len(g) != len_0 for g in axis_index_groups):\nraise ValueError(\"axis_index_groups must all be the same size\")\naxis_space = range(len_0 * len(axis_index_groups))\n- if set(i for g in axis_index_groups for i in g) != set(axis_space):\n+ if {i for g in axis_index_groups for i in g} != set(axis_space):\nraise ValueError(\"axis_index_groups must cover all indices exactly once\")\ndef ppermute(x, axis_name, perm):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -263,7 +263,7 @@ def host_id(backend: str = None):\ndef host_ids(backend: str = None):\n\"\"\"Returns a sorted list of all host IDs.\"\"\"\n- return sorted(list(set(d.host_id for d in devices(backend))))\n+ return sorted({d.host_id for d in devices(backend)})\ndef host_count(backend: str = None):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/fft.py",
"new_path": "jax/numpy/fft.py",
"diff": "@@ -176,12 +176,12 @@ def irfft2(a, s=None, axes=(-2,-1), norm=None):\n@_wraps(np.fft.fftfreq)\ndef fftfreq(n, d=1.0):\n- if isinstance(n, list) or isinstance(n, tuple):\n+ if isinstance(n, (list, tuple)):\nraise ValueError(\n\"The n argument of jax.numpy.fft.fftfreq only takes an int. \"\n\"Got n = %s.\" % list(n))\n- elif isinstance(d, list) or isinstance(d, tuple):\n+ elif isinstance(d, (list, tuple)):\nraise ValueError(\n\"The d argument of jax.numpy.fft.fftfreq only takes a single value. \"\n\"Got d = %s.\" % list(d))\n@@ -208,12 +208,12 @@ def fftfreq(n, d=1.0):\n@_wraps(np.fft.rfftfreq)\ndef rfftfreq(n, d=1.0):\n- if isinstance(n, list) or isinstance(n, tuple):\n+ if isinstance(n, (list, tuple)):\nraise ValueError(\n\"The n argument of jax.numpy.fft.rfftfreq only takes an int. \"\n\"Got n = %s.\" % list(n))\n- elif isinstance(d, list) or isinstance(d, tuple):\n+ elif isinstance(d, (list, tuple)):\nraise ValueError(\n\"The d argument of jax.numpy.fft.rfftfreq only takes a single value. \"\n\"Got d = %s.\" % list(d))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -3346,7 +3346,7 @@ def lexsort(keys, axis=-1):\nkeys = tuple(keys)\nif len(keys) == 0:\nraise TypeError(\"need sequence of keys with len > 0 in lexsort\")\n- if len(set(shape(key) for key in keys)) > 1:\n+ if len({shape(key) for key in keys}) > 1:\nraise ValueError(\"all keys need to be the same shape\")\nif ndim(keys[0]) == 0:\nreturn np.int64(0)\n@@ -3769,7 +3769,7 @@ def _index_to_gather(x_shape, idx):\nidx_no_nones = [(i, d) for i, d in enumerate(idx) if d is not None]\nadvanced_pairs = (\n(asarray(e), i, j) for j, (i, e) in enumerate(idx_no_nones)\n- if (isinstance(e, Sequence) or isinstance(e, ndarray)))\n+ if isinstance(e, (Sequence, ndarray)))\nadvanced_pairs = ((_normalize_index(e, x_shape[j]), i, j)\nfor e, i, j in advanced_pairs)\nadvanced_indexes, idx_advanced_axes, x_advanced_axes = zip(*advanced_pairs)\n@@ -3838,8 +3838,7 @@ def _index_to_gather(x_shape, idx):\nexcept TypeError:\nabstract_i = None\n# Handle basic int indexes.\n- if (isinstance(abstract_i, ConcreteArray) or\n- isinstance(abstract_i, ShapedArray)) and _int(abstract_i):\n+ if isinstance(abstract_i, (ConcreteArray,ShapedArray)) and _int(abstract_i):\nif x_shape[x_axis] == 0:\n# XLA gives error when indexing into an axis of size 0\nraise IndexError(f\"index is out of bounds for axis {x_axis} with size 0\")\n@@ -3939,8 +3938,8 @@ def _index_to_gather(x_shape, idx):\ndef _should_unpack_list_index(x):\n\"\"\"Helper for _eliminate_deprecated_list_indexing.\"\"\"\nreturn (isinstance(x, ndarray) and np.ndim(x) != 0\n- or isinstance(x, Sequence)\n- or isinstance(x, slice) or x is Ellipsis or x is None)\n+ or isinstance(x, (Sequence, slice))\n+ or x is Ellipsis or x is None)\ndef _eliminate_deprecated_list_indexing(idx):\n# \"Basic slicing is initiated if the selection object is a non-array,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -140,7 +140,7 @@ def _normalize_tolerance(tol):\nif isinstance(tol, dict):\nreturn {np.dtype(k): v for k, v in tol.items()}\nelse:\n- return {k: tol for k in _default_tolerance.keys()}\n+ return {k: tol for k in _default_tolerance}\ndef join_tolerance(tol1, tol2):\ntol1 = _normalize_tolerance(tol1)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/tools/jax_to_hlo.py",
"new_path": "jax/tools/jax_to_hlo.py",
"diff": "@@ -94,7 +94,7 @@ def jax_to_hlo(fn, input_shapes, constants=None):\nif not constants:\nconstants = {}\n- overlapping_args = set(arg_name for arg_name, _ in input_shapes) & set(\n+ overlapping_args = {arg_name for arg_name, _ in input_shapes} & set(\nconstants.keys())\nif overlapping_args:\nraise ValueError(\n"
},
{
"change_type": "MODIFY",
"old_path": "setup.py",
"new_path": "setup.py",
"diff": "from setuptools import setup, find_packages\n-global __version__\n__version__ = None\nwith open('jax/version.py') as f:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -329,7 +329,7 @@ class BatchingTest(jtu.JaxTestCase):\n# test modeling the code in https://github.com/google/jax/issues/54\ndef func(xs):\n- return jnp.array([x for x in xs])\n+ return jnp.array(list(xs))\nxs = jnp.ones((5, 1))\njacrev(func)(xs) # don't crash\n"
}
] | Python | Apache License 2.0 | google/jax | Fix code quality issues (#4302)
Changes:
- Fix unnecessary generator
- Iterate dictionary directly instead of calling .keys()
- Remove global statement at the module level
- Use list() instead of a list comprehension
- Use with statement to open the file
- Merge isinstance calls |
260,335 | 17.09.2020 09:57:43 | 25,200 | 11007ba0e3577dab0c19ac37f60061fdccecb016 | test eval_context works w/ and w/o omnistaging | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1493,7 +1493,8 @@ def pp_kv_pairs(kv_pairs):\n@config.register_omnistaging_disabler\ndef omnistaging_disabler() -> None:\nglobal thread_local_state, call_bind, find_top_trace, initial_style_staging, \\\n- new_main, reset_trace_state, TraceStack, TraceState, extend_axis_env\n+ new_main, reset_trace_state, TraceStack, TraceState, extend_axis_env, \\\n+ eval_context\nclass TraceStack:\nupward: List[MainTrace]\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1784,6 +1784,14 @@ class APITest(jtu.JaxTestCase):\njaxpr = api.make_jaxpr(lambda: jnp.add(1, 1))()\nself.assertLen(jaxpr.jaxpr.eqns, 0)\n+ def test_eval_context(self):\n+ @jit\n+ def f():\n+ with core.eval_context():\n+ assert jnp.add(1, 1) == 2\n+\n+ f() # doesn't crash\n+\nclass RematTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | test eval_context works w/ and w/o omnistaging (#4325) |
260,298 | 17.09.2020 19:37:40 | -7,200 | 8a4ee3d8516662b6f6fd95046f4d28119b3c1db2 | Fix shape checking rule for conv_general_dilated.
* Fix shape checking rule for conv_general_dilated.
This closes google/jax#4316.
* Added test based on google/jax#4316.
* Change test name to be more accurate. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2471,6 +2471,10 @@ def _conv_general_dilated_shape_rule(\nlhs_dilation, rhs_dilation, dimension_numbers, feature_group_count,\nbatch_group_count, **unused_kwargs) -> Tuple[int, ...]:\nassert type(dimension_numbers) is ConvDimensionNumbers\n+ if len(lhs.shape) != len(rhs.shape):\n+ msg = (\"conv_general_dilated lhs and rhs must have the same number of \"\n+ \"dimensions, but got {} and {}.\")\n+ raise ValueError(msg.format(lhs.shape, rhs.shape))\nif not feature_group_count > 0:\nmsg = (\"conv_general_dilated feature_group_count \"\n\"must be a positive integer, got {}.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -2011,6 +2011,26 @@ class LaxTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(TypeError, msg):\nlax.population_count(True)\n+ def test_conv_general_dilated_different_input_ranks_error(self):\n+ # https://github.com/google/jax/issues/4316\n+ msg = (\"conv_general_dilated lhs and rhs must have the same number of \"\n+ \"dimensions\")\n+ dimension_numbers = lax.ConvDimensionNumbers(lhs_spec=(0, 1, 2),\n+ rhs_spec=(0, 1, 2),\n+ out_spec=(0, 1, 2))\n+ kwargs = { 'window_strides': (1,)\n+ , 'padding': ((0, 0),)\n+ , 'lhs_dilation': (1,)\n+ , 'rhs_dilation': (1,)\n+ , 'dimension_numbers': dimension_numbers\n+ , 'feature_group_count': 1\n+ , 'batch_group_count': 1\n+ , 'precision': None\n+ }\n+ lhs, rhs = np.ones((1, 1, 1)), np.ones((1, 1, 1, 1))\n+ with self.assertRaisesRegex(ValueError, msg):\n+ lax.conv_general_dilated(lhs, rhs, **kwargs)\n+\nclass LazyConstantTest(jtu.JaxTestCase):\ndef _Check(self, make_const, expected):\n"
}
] | Python | Apache License 2.0 | google/jax | Fix shape checking rule for conv_general_dilated. (#4318)
* Fix shape checking rule for conv_general_dilated.
This closes google/jax#4316.
* Added test based on google/jax#4316.
* Change test name to be more accurate. |
260,411 | 18.09.2020 10:30:45 | -10,800 | 0ac25c760af2788ba0a14f8a0f5827035e4c29e0 | [jax2tf] Replace tf.math.add with tf.raw_ops.AddV2
* [jax2tf] Replace tf.math.add with tf.raw_ops.AddV2
We now fixed tf.raw_ops.AddV2 to support uint32. It was already supporting uint8,
so it is a better choice now than tf.math.add. This allowed us to use
the threefry implementation using uint32. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -8,7 +8,7 @@ primitives using TensorFlow operations. In practice this means that you can take\nsome code written in JAX and execute it using TensorFlow eager mode, or stage it\nout as a TensorFlow graph.\n-As of today, the tests are run using `tf_nightly==2.4.0.dev20200829`.\n+As of today, the tests are run using `tf_nightly==2.4.0.dev20200916`.\nMost commonly people want to use this tool in order to:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -441,7 +441,14 @@ except AttributeError:\npass\ntf_impl[ad_util.stop_gradient_p] = tf.stop_gradient\ntf_impl[ad_util.zeros_like_p] = tf.zeros_like\n-tf_impl[ad_util.add_jaxvals_p] = wrap_binary_op(tf.math.add)\n+\n+def _add(*operands: TfVal) -> TfVal:\n+ \"\"\"Add unsigned integer support for add.\"\"\"\n+ x, y = promote_types(*operands)\n+ # Only AddV2 supports uint8 and uint32 addition.\n+ return tf.raw_ops.AddV2(x=x, y=y)\n+\n+tf_impl[ad_util.add_jaxvals_p] = _add\ntf_impl[xla.device_put_p] = lambda x, device=None: x\ntf_impl[lax.neg_p] = tf.math.negative\n@@ -494,7 +501,7 @@ tf_impl[lax.conj_p] = tf.math.conj\ntf_impl[lax.real_p] = tf.math.real\ntf_impl[lax.imag_p] = tf.math.imag\n-tf_impl[lax.add_p] = wrap_binary_op(tf.math.add)\n+tf_impl[lax.add_p] = _add\ntf_impl[lax.sub_p] = wrap_binary_op(tf.math.subtract)\ntf_impl[lax.mul_p] = wrap_binary_op(tf.math.multiply)\n@@ -811,7 +818,7 @@ tf_impl[lax.argmin_p] = functools.partial(_argminmax, tf.math.argmin)\ntf_impl[lax.argmax_p] = functools.partial(_argminmax, tf.math.argmax)\n-_add_fn = tf.function(tf.math.add)\n+_add_fn = tf.function(_add)\n_ge_fn = tf.function(tf.math.greater_equal)\ntf_impl[lax.cumsum_p] = tf.math.cumsum\n@@ -1016,7 +1023,7 @@ def _get_min_identity(tf_dtype):\n# pylint: disable=protected-access\ntf_impl[lax.reduce_window_sum_p] = (\n- functools.partial(_specialized_reduce_window, tf.math.add, lambda x: 0))\n+ functools.partial(_specialized_reduce_window, _add, lambda x: 0))\ntf_impl[lax.reduce_window_min_p] = (\nfunctools.partial(_specialized_reduce_window, tf.math.minimum,\n_get_min_identity))\n@@ -1047,15 +1054,12 @@ def _select_and_scatter_add(\ntf_impl[lax.select_and_scatter_add_p] = _select_and_scatter_add\ndef _threefry2x32_jax_impl(*args: TfValOrUnit):\n- # We use the random._threefry2x32_lowering, but since add is not implemented\n- # for uint32, we cast to int32 and back.\n- args = tuple([tf.cast(a, tf.int32) for a in args])\n- res = _convert_jax_impl(\n+ # We use the random._threefry2x32_lowering\n+ return _convert_jax_impl(\nfunctools.partial(random._threefry2x32_lowering,\nuse_rolled_loops=False),\nmultiple_results=True)(*args)\n- res = tuple([tf.cast(r, tf.uint32) for r in res])\n- return res\n+\ntf_impl[jax.random.threefry2x32_p] = _threefry2x32_jax_impl\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "This file is automatically generated by running the jax2tf tests in\n`jax/experimental/jax2tf/tests/primitives_test.py` and\n`jax/experimental/jax2tf/tests/control_flow_ops_test.py` with the\n-`JAX2TF_OUTPUT_LIMITATIONS` and `JAX_ENABLE_X64` environment variables set.\n+`JAX2TF_OUTPUT_LIMITATIONS` and `JAX_ENABLE_X64` environment variables set, e.g.,\n+\n+```\n+JAX2TF_OUTPUT_LIMITATIONS=true JAX_ENABLE_X64=true pytest -r a --verbosity=1 jax/experimental/jax2tf/tests/primitives_test.py jax/experimental/jax2tf/tests/control_flow_ops_test.py\n+```\n## Generated summary of primitives with limited support\n@@ -20,9 +24,9 @@ conversion to Tensorflow.\n| Affected primitive | Type of limitation | Description | Affected dtypes | Affected devices |\n| --- | --- | --- | --- | --- |\n-| acosh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n| acosh | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n-| add | Missing TF support | Primitive is unimplemented | uint16, uint32, uint64 | CPU, GPU, TPU |\n+| acosh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n+| add | Missing TF support | Primitive is unimplemented | uint16, uint64 | CPU, GPU, TPU |\n| asinh | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| asinh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n| atan2 | Missing TF support | Primitive is unimplemented | bfloat16, float16 | CPU, GPU, TPU |\n@@ -30,8 +34,8 @@ conversion to Tensorflow.\n| atanh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n| bessel_i0e | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| bessel_i1e | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n-| conv_general_dilated | Missing TF support | Primitive is unimplemented; likely bug in the HLO -> LLVM IR lowering of XlaConv | complex64, complex128 | CPU, GPU, TPU |\n| conv_general_dilated | Missing TF support | Primitive is unimplemented; batch_group_count != 1 unsupported | ALL | CPU, GPU, TPU |\n+| conv_general_dilated | Missing TF support | Primitive is unimplemented; likely bug in the HLO -> LLVM IR lowering of XlaConv | complex128, complex64 | CPU, GPU, TPU |\n| cosh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n| digamma | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| erf | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n@@ -46,14 +50,14 @@ conversion to Tensorflow.\n| nextafter | Missing TF support | Primitive is unimplemented | bfloat16, float16 | CPU, GPU, TPU |\n| population_count | Missing TF support | Primitive is unimplemented | uint32, uint64 | CPU, GPU, TPU |\n| qr | Missing TF support | Primitive is unimplemented | complex128, complex64 | CPU, GPU, TPU |\n-| reduce_window_sum | Missing TF support | Primitive is unimplemented | uint16, uint32, uint64 | CPU, GPU, TPU |\n+| reduce_window_sum | Missing TF support | Primitive is unimplemented | uint16, uint64 | CPU, GPU, TPU |\n| rem | Missing TF support | Primitive is unimplemented | bfloat16, float16 | CPU, GPU, TPU |\n| round | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| rsqrt | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| scatter-add | Missing TF support | Primitive is unimplemented | complex64 | TPU |\n| scatter-mul | Missing TF support | Primitive is unimplemented | complex64 | TPU |\n-| select_and_gather_add | Missing TF support | Primitive is unimplemented | float32, float64 | TPU |\n| select_and_gather_add | Missing TF support | Primitive is unimplemented | float64 | CPU, GPU |\n+| select_and_gather_add | Missing TF support | Primitive is unimplemented | float32, float64 | TPU |\n| sinh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n| sort | Missing TF support | Primitive is unimplemented | complex128, complex64 | CPU, GPU, TPU |\n| sort | Missing TF support | Primitive is unimplemented; only sorting on last dimension is supported for XlaSort | ALL | CPU, GPU, TPU |\n@@ -74,4 +78,4 @@ The conversion of the following JAX primitives is not yet implemented:\nThe following JAX primitives have a defined conversion but are known to be\nmissing tests:\n-`argmax`, `argmin`, `broadcast`, `clamp`, `complex`, `conj`, `custom_lin`, `device_put`, `dot_general`, `imag`, `integer_pow`, `real`, `rev`, `select_and_scatter`, `select_and_scatter_add`, `stop_gradient`, `tie_in`\n+`argmax`, `argmin`, `bitcast_convert_type`, `broadcast`, `clamp`, `complex`, `conj`, `custom_lin`, `device_put`, `dot_general`, `imag`, `integer_pow`, `pow`, `real`, `rev`, `select_and_scatter`, `select_and_scatter_add`, `stop_gradient`, `tie_in`\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md.template",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md.template",
"diff": "This file is automatically generated by running the jax2tf tests in\n`jax/experimental/jax2tf/tests/primitives_test.py` and\n`jax/experimental/jax2tf/tests/control_flow_ops_test.py` with the\n-`JAX2TF_OUTPUT_LIMITATIONS` and `JAX_ENABLE_X64` environment variables set.\n+`JAX2TF_OUTPUT_LIMITATIONS` and `JAX_ENABLE_X64` environment variables set, e.g.,\n+\n+```\n+JAX2TF_OUTPUT_LIMITATIONS=true JAX_ENABLE_X64=true pytest -r a --verbosity=1 jax/experimental/jax2tf/tests/primitives_test.py jax/experimental/jax2tf/tests/control_flow_ops_test.py\n+```\n## Generated summary of primitives with limited support\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "@@ -145,7 +145,7 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nif prim in [lax.add_p, lax.reduce_window_sum_p]:\nnp_dtype = _to_np_dtype(args[0].dtype)\n- if np_dtype in [np.uint16, np.uint32, np.uint64]:\n+ if np_dtype in [np.uint16, np.uint64]:\n# TODO(bchetioui): tf.math.add is not defined for the above types.\ntf_unimpl(np_dtype)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Replace tf.math.add with tf.raw_ops.AddV2 (#4278)
* [jax2tf] Replace tf.math.add with tf.raw_ops.AddV2
We now fixed tf.raw_ops.AddV2 to support uint32. It was already supporting uint8,
so it is a better choice now than tf.math.add. This allowed us to use
the threefry implementation using uint32. |
260,411 | 18.09.2020 11:37:34 | -10,800 | ded7b3854c37f93652e7eed4f4cd50522f3be70f | [jax2tf] Revert '[jax2tf] Replace tf.math.add with tf.raw_ops.AddV2 (#4278)'
Generates errors due to Grappler replacing AddV2 with AddN, which is not implemented for uint32 | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -441,14 +441,7 @@ except AttributeError:\npass\ntf_impl[ad_util.stop_gradient_p] = tf.stop_gradient\ntf_impl[ad_util.zeros_like_p] = tf.zeros_like\n-\n-def _add(*operands: TfVal) -> TfVal:\n- \"\"\"Add unsigned integer support for add.\"\"\"\n- x, y = promote_types(*operands)\n- # Only AddV2 supports uint8 and uint32 addition.\n- return tf.raw_ops.AddV2(x=x, y=y)\n-\n-tf_impl[ad_util.add_jaxvals_p] = _add\n+tf_impl[ad_util.add_jaxvals_p] = wrap_binary_op(tf.math.add)\ntf_impl[xla.device_put_p] = lambda x, device=None: x\ntf_impl[lax.neg_p] = tf.math.negative\n@@ -501,7 +494,7 @@ tf_impl[lax.conj_p] = tf.math.conj\ntf_impl[lax.real_p] = tf.math.real\ntf_impl[lax.imag_p] = tf.math.imag\n-tf_impl[lax.add_p] = _add\n+tf_impl[lax.add_p] = wrap_binary_op(tf.math.add)\ntf_impl[lax.sub_p] = wrap_binary_op(tf.math.subtract)\ntf_impl[lax.mul_p] = wrap_binary_op(tf.math.multiply)\n@@ -818,7 +811,7 @@ tf_impl[lax.argmin_p] = functools.partial(_argminmax, tf.math.argmin)\ntf_impl[lax.argmax_p] = functools.partial(_argminmax, tf.math.argmax)\n-_add_fn = tf.function(_add)\n+_add_fn = tf.function(tf.math.add)\n_ge_fn = tf.function(tf.math.greater_equal)\ntf_impl[lax.cumsum_p] = tf.math.cumsum\n@@ -1023,7 +1016,7 @@ def _get_min_identity(tf_dtype):\n# pylint: disable=protected-access\ntf_impl[lax.reduce_window_sum_p] = (\n- functools.partial(_specialized_reduce_window, _add, lambda x: 0))\n+ functools.partial(_specialized_reduce_window, tf.math.add, lambda x: 0))\ntf_impl[lax.reduce_window_min_p] = (\nfunctools.partial(_specialized_reduce_window, tf.math.minimum,\n_get_min_identity))\n@@ -1054,12 +1047,15 @@ def _select_and_scatter_add(\ntf_impl[lax.select_and_scatter_add_p] = _select_and_scatter_add\ndef _threefry2x32_jax_impl(*args: TfValOrUnit):\n- # We use the random._threefry2x32_lowering\n- return _convert_jax_impl(\n+ # We use the random._threefry2x32_lowering, but since add is not implemented\n+ # for uint32, we cast to int32 and back.\n+ args = tuple([tf.cast(a, tf.int32) for a in args])\n+ res = _convert_jax_impl(\nfunctools.partial(random._threefry2x32_lowering,\nuse_rolled_loops=False),\nmultiple_results=True)(*args)\n-\n+ res = tuple([tf.cast(r, tf.uint32) for r in res])\n+ return res\ntf_impl[jax.random.threefry2x32_p] = _threefry2x32_jax_impl\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md",
"diff": "@@ -24,9 +24,9 @@ conversion to Tensorflow.\n| Affected primitive | Type of limitation | Description | Affected dtypes | Affected devices |\n| --- | --- | --- | --- | --- |\n-| acosh | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| acosh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n-| add | Missing TF support | Primitive is unimplemented | uint16, uint64 | CPU, GPU, TPU |\n+| acosh | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| add | Missing TF support | Primitive is unimplemented | uint16, uint32, uint64 | CPU, GPU, TPU |\n| asinh | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| asinh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n| atan2 | Missing TF support | Primitive is unimplemented | bfloat16, float16 | CPU, GPU, TPU |\n@@ -34,8 +34,8 @@ conversion to Tensorflow.\n| atanh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n| bessel_i0e | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| bessel_i1e | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n+| conv_general_dilated | Missing TF support | Primitive is unimplemented; likely bug in the HLO -> LLVM IR lowering of XlaConv | complex64, complex128 | CPU, GPU, TPU |\n| conv_general_dilated | Missing TF support | Primitive is unimplemented; batch_group_count != 1 unsupported | ALL | CPU, GPU, TPU |\n-| conv_general_dilated | Missing TF support | Primitive is unimplemented; likely bug in the HLO -> LLVM IR lowering of XlaConv | complex128, complex64 | CPU, GPU, TPU |\n| cosh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n| digamma | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| erf | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n@@ -50,14 +50,14 @@ conversion to Tensorflow.\n| nextafter | Missing TF support | Primitive is unimplemented | bfloat16, float16 | CPU, GPU, TPU |\n| population_count | Missing TF support | Primitive is unimplemented | uint32, uint64 | CPU, GPU, TPU |\n| qr | Missing TF support | Primitive is unimplemented | complex128, complex64 | CPU, GPU, TPU |\n-| reduce_window_sum | Missing TF support | Primitive is unimplemented | uint16, uint64 | CPU, GPU, TPU |\n+| reduce_window_sum | Missing TF support | Primitive is unimplemented | uint16, uint32, uint64 | CPU, GPU, TPU |\n| rem | Missing TF support | Primitive is unimplemented | bfloat16, float16 | CPU, GPU, TPU |\n| round | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| rsqrt | Missing TF support | Primitive is unimplemented | bfloat16 | CPU, GPU |\n| scatter-add | Missing TF support | Primitive is unimplemented | complex64 | TPU |\n| scatter-mul | Missing TF support | Primitive is unimplemented | complex64 | TPU |\n-| select_and_gather_add | Missing TF support | Primitive is unimplemented | float64 | CPU, GPU |\n| select_and_gather_add | Missing TF support | Primitive is unimplemented | float32, float64 | TPU |\n+| select_and_gather_add | Missing TF support | Primitive is unimplemented | float64 | CPU, GPU |\n| sinh | Missing TF support | Primitive is unimplemented | float16 | CPU, GPU, TPU |\n| sort | Missing TF support | Primitive is unimplemented | complex128, complex64 | CPU, GPU, TPU |\n| sort | Missing TF support | Primitive is unimplemented; only sorting on last dimension is supported for XlaSort | ALL | CPU, GPU, TPU |\n@@ -78,4 +78,4 @@ The conversion of the following JAX primitives is not yet implemented:\nThe following JAX primitives have a defined conversion but are known to be\nmissing tests:\n-`argmax`, `argmin`, `bitcast_convert_type`, `broadcast`, `clamp`, `complex`, `conj`, `custom_lin`, `device_put`, `dot_general`, `imag`, `integer_pow`, `pow`, `real`, `rev`, `select_and_scatter`, `select_and_scatter_add`, `stop_gradient`, `tie_in`\n+`argmax`, `argmin`, `broadcast`, `clamp`, `complex`, `conj`, `custom_lin`, `device_put`, `dot_general`, `imag`, `integer_pow`, `real`, `rev`, `select_and_scatter`, `select_and_scatter_add`, `stop_gradient`, `tie_in`\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/primitives_with_limited_support.md.template",
"new_path": "jax/experimental/jax2tf/primitives_with_limited_support.md.template",
"diff": "This file is automatically generated by running the jax2tf tests in\n`jax/experimental/jax2tf/tests/primitives_test.py` and\n`jax/experimental/jax2tf/tests/control_flow_ops_test.py` with the\n-`JAX2TF_OUTPUT_LIMITATIONS` and `JAX_ENABLE_X64` environment variables set, e.g.,\n-\n-```\n-JAX2TF_OUTPUT_LIMITATIONS=true JAX_ENABLE_X64=true pytest -r a --verbosity=1 jax/experimental/jax2tf/tests/primitives_test.py jax/experimental/jax2tf/tests/control_flow_ops_test.py\n-```\n+`JAX2TF_OUTPUT_LIMITATIONS` and `JAX_ENABLE_X64` environment variables set.\n## Generated summary of primitives with limited support\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"new_path": "jax/experimental/jax2tf/tests/correctness_stats.py",
"diff": "@@ -145,7 +145,7 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\nif prim in [lax.add_p, lax.reduce_window_sum_p]:\nnp_dtype = _to_np_dtype(args[0].dtype)\n- if np_dtype in [np.uint16, np.uint64]:\n+ if np_dtype in [np.uint16, np.uint32, np.uint64]:\n# TODO(bchetioui): tf.math.add is not defined for the above types.\ntf_unimpl(np_dtype)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Revert '[jax2tf] Replace tf.math.add with tf.raw_ops.AddV2 (#4278)' (#4332)
Generates errors due to Grappler replacing AddV2 with AddN, which is not implemented for uint32 |
260,411 | 18.09.2020 11:55:26 | -10,800 | 8376d92049624bf0784647b17b1f09015acd0947 | Disable testExpmGrad on TPU, pending investigation of compiler error | [
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -1346,7 +1346,10 @@ class ScipyLinalgTest(jtu.JaxTestCase):\na = rng((n, n), dtype)\ndef expm(x):\nreturn jsp.linalg.expm(x, upper_triangular=False, max_squarings=16)\n- jtu.check_grads(expm, (a,), modes=[\"fwd\", \"rev\"], order=2)\n+ if jtu.device_under_test() != \"tpu\":\n+ # TODO(b/168865439): Fails with internal error on TPUs\n+ jtu.check_grads(expm, (a,), modes=[\"fwd\", \"rev\"], order=2,\n+ atol=1e-1, rtol=1e-1)\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Disable testExpmGrad on TPU, pending investigation of compiler error (#4333) |
260,335 | 18.09.2020 10:49:04 | 25,200 | 92c9713593df177501f6861afdcfe786f2d79738 | add tests for new error message info | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -829,12 +829,12 @@ class DynamicJaxprTracer(core.Tracer):\n\"for `jit` to avoid tracing particular arguments of transformed \"\n\"functions, though at the cost of more recompiles.\")\nelif progenitor_eqns:\n- const_msgs = [f\" operation {core.pp_eqn(eqn, print_shapes=True)}\\n\"\n+ msts = [f\" operation {core.pp_eqn(eqn, print_shapes=True)}\\n\"\nf\" from line {source_info_util.summarize(eqn.source_info)}\"\nfor eqn in progenitor_eqns]\norigin = (f\"While tracing the function {self._trace.main.source_info}, \"\n\"this value became a tracer due to JAX operations on these lines:\"\n- \"\\n\\n\" + \"\\n\\n\".join(msgs))\n+ \"\\n\\n\" + \"\\n\\n\".join(msts))\nelse:\norigin = (\"The error occured while tracing the function \"\nf\"{self._trace.main.source_info}.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1792,6 +1792,27 @@ class APITest(jtu.JaxTestCase):\nf() # doesn't crash\n+ def test_concrete_error_because_arg(self):\n+ @jax.jit\n+ def f(x, y):\n+ if x > y:\n+ return x\n+ else:\n+ return y\n+\n+ msg = \"at positions \\[0, 1\\]\"\n+ with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n+ f(1, 2)\n+\n+ def test_concrete_error_because_const(self):\n+ @jax.jit\n+ def f():\n+ assert jnp.add(1, 1) > 0\n+\n+ msg = \"on these lines\"\n+ with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n+ f()\n+\nclass RematTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | add tests for new error message info |
260,335 | 18.09.2020 11:09:03 | 25,200 | be6cae35b7177a9a2c1fba9e35d46038fd44c055 | only enable new tests with omnistaging | [
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1793,6 +1793,9 @@ class APITest(jtu.JaxTestCase):\nf() # doesn't crash\ndef test_concrete_error_because_arg(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test is omnistaging-specific\")\n+\n@jax.jit\ndef f(x, y):\nif x > y:\n@@ -1805,6 +1808,9 @@ class APITest(jtu.JaxTestCase):\nf(1, 2)\ndef test_concrete_error_because_const(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test is omnistaging-specific\")\n+\n@jax.jit\ndef f():\nassert jnp.add(1, 1) > 0\n"
}
] | Python | Apache License 2.0 | google/jax | only enable new tests with omnistaging |
260,325 | 08.09.2020 13:51:19 | 25,200 | 7fd7009c231bf9a86e009f6e86ccd4b374cb29dc | Expose scale_and_translate as a public function, fix a bug in implementation when translation is not 0.
Change implementation to use native JAX everywhere allowing vmaping and gradients wrt scale and translation. | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.image.rst",
"new_path": "docs/jax.image.rst",
"diff": "@@ -13,4 +13,5 @@ Image manipulation functions\n:toctree: _autosummary\nresize\n+ scale_and_translate\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/image/__init__.py",
"new_path": "jax/image/__init__.py",
"diff": "# flake8: noqa: F401\nfrom .scale import (\nresize,\n- ResizeMethod\n+ ResizeMethod,\n+ scale_and_translate,\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/image_test.py",
"new_path": "tests/image_test.py",
"diff": "@@ -180,6 +180,108 @@ class ImageTest(jtu.JaxTestCase):\nantialias=antialias)\njtu.check_grads(jax_fn, args_maker(), order=2, rtol=1e-2, eps=1.)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\"_shape={}_target={}_method={}\".format(\n+ jtu.format_shape_dtype_string(image_shape, dtype),\n+ jtu.format_shape_dtype_string(target_shape, dtype), method),\n+ \"dtype\": dtype, \"image_shape\": image_shape,\n+ \"target_shape\": target_shape,\n+ \"scale\": scale, \"translation\": translation, \"method\": method}\n+ for dtype in inexact_dtypes\n+ for image_shape, target_shape, scale, translation in [\n+ ([3, 1, 2], [6, 1, 4], [2.0, 1.0, 2.0], [1.0, 0.0, -1.0]),\n+ ([1, 3, 2, 1], [1, 6, 4, 1], [1.0, 2.0, 2.0, 1.0], [0.0, 1.0, -1.0, 0.0])]\n+ for method in [\"linear\", \"lanczos3\", \"lanczos5\", \"cubic\"]))\n+ def testScaleAndTranslateUp(self, dtype, image_shape, target_shape, scale,\n+ translation, method):\n+ data = [64, 32, 32, 64, 50, 100]\n+ # Note zeros occur in the output because the sampling location is outside\n+ # the boundaries of the input image.\n+ expected_data = {}\n+ expected_data[\"linear\"] = [\n+ 0.0, 0.0, 0.0, 0.0, 56.0, 40.0, 32.0, 0.0, 52.0, 44.0, 40.0, 0.0, 44.0,\n+ 52.0, 56.0, 0.0, 45.625, 63.875, 73.0, 0.0, 56.875, 79.625, 91.0, 0.0\n+ ]\n+ expected_data[\"lanczos3\"] = [\n+ 0.0, 0.0, 0.0, 0.0, 59.6281, 38.4313, 22.23, 0.0, 52.0037, 40.6454,\n+ 31.964, 0.0, 41.0779, 47.9383, 53.1818, 0.0, 43.0769, 67.1244, 85.5045,\n+ 0.0, 56.4713, 83.5243, 104.2017, 0.0\n+ ]\n+ expected_data[\"lanczos5\"] = [\n+ 0.0, 0.0, 0.0, 0.0, 60.0223, 40.6694, 23.1219, 0.0, 51.2369, 39.5593,\n+ 28.9709, 0.0, 40.8875, 46.5604, 51.7041, 0.0, 43.5299, 67.7223, 89.658,\n+ 0.0, 56.784, 83.984, 108.6467, 0.0\n+ ]\n+ expected_data[\"cubic\"] = [\n+ 0.0, 0.0, 0.0, 0.0, 59.0252, 36.9748, 25.8547, 0.0, 53.3386, 41.4789,\n+ 35.4981, 0.0, 41.285, 51.0051, 55.9071, 0.0, 42.151, 65.8032, 77.731,\n+ 0.0, 55.823, 83.9288, 98.1026, 0.0\n+ ]\n+ x = np.array(data, dtype=dtype).reshape(image_shape)\n+ # Should we test different float types here?\n+ scale_a = jnp.array(scale, dtype=jnp.float32)\n+ translation_a = jnp.array(translation, dtype=jnp.float32)\n+ output = image.scale_and_translate(x, target_shape, scale_a, translation_a,\n+ method)\n+\n+ expected = np.array(\n+ expected_data[method], dtype=dtype).reshape(target_shape)\n+ self.assertAllClose(output, expected, atol=2e-03)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_dtype={}_method={}_antialias={}\".format(\n+ jtu.dtype_str(dtype), method, antialias),\n+ \"dtype\":dtype, \"method\":method, \"antialias\": antialias}\n+ for dtype in inexact_dtypes\n+ for method in [\"linear\", \"lanczos3\", \"lanczos5\", \"cubic\"]\n+ for antialias in [True, False]))\n+ def testScaleAndTranslateDown(self, dtype, method, antialias):\n+ image_shape = [1, 6, 7, 1]\n+ target_shape = [1, 3, 3, 1]\n+\n+ data = [\n+ 51, 38, 32, 89, 41, 21, 97, 51, 33, 87, 89, 34, 21, 97, 43, 25, 25, 92,\n+ 41, 11, 84, 11, 55, 111, 23, 99, 50, 83, 13, 92, 52, 43, 90, 43, 14, 89,\n+ 71, 32, 23, 23, 35, 93\n+ ]\n+ if antialias:\n+ expected_data = {}\n+ expected_data[\"linear\"] = [\n+ 43.5372, 59.3694, 53.6907, 49.3221, 56.8168, 55.4849, 0, 0, 0\n+ ]\n+ expected_data[\"lanczos3\"] = [\n+ 43.2884, 57.9091, 54.6439, 48.5856, 58.2427, 53.7551, 0, 0, 0\n+ ]\n+ expected_data[\"lanczos5\"] = [\n+ 43.9209, 57.6360, 54.9575, 48.9272, 58.1865, 53.1948, 0, 0, 0\n+ ]\n+ expected_data[\"cubic\"] = [\n+ 42.9935, 59.1687, 54.2138, 48.2640, 58.2678, 54.4088, 0, 0, 0\n+ ]\n+ else:\n+ expected_data = {}\n+ expected_data[\"linear\"] = [\n+ 43.6071, 89, 59, 37.1785, 27.2857, 58.3571, 0, 0, 0\n+ ]\n+ expected_data[\"lanczos3\"] = [\n+ 44.1390, 87.8786, 63.3111, 25.1161, 20.8795, 53.6165, 0, 0, 0\n+ ]\n+ expected_data[\"lanczos5\"] = [\n+ 44.8835, 85.5896, 66.7231, 16.9983, 19.8891, 47.1446, 0, 0, 0\n+ ]\n+ expected_data[\"cubic\"] = [\n+ 43.6426, 88.8854, 60.6638, 31.4685, 22.1204, 58.3457, 0, 0, 0\n+ ]\n+ x = np.array(data, dtype=dtype).reshape(image_shape)\n+\n+ scale_a = jnp.array([1.0, 0.35, 0.4, 1.0], dtype=jnp.float32)\n+ translation_a = jnp.array([0.0, 0.2, 0.1, 0.0], dtype=jnp.float32)\n+ output = image.scale_and_translate(\n+ x, target_shape, scale_a, translation_a, method, antialias=antialias)\n+ expected = np.array(\n+ expected_data[method], dtype=dtype).reshape(target_shape)\n+ self.assertAllClose(output, expected, atol=2e-03)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Expose scale_and_translate as a public function, fix a bug in implementation when translation is not 0.
Change implementation to use native JAX everywhere allowing vmaping and gradients wrt scale and translation. |
260,393 | 18.09.2020 14:58:03 | 25,200 | 2bc92f5593c04dfd9a7bbb65ed77b70092038031 | Fixed ppermute translation rule | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -547,7 +547,6 @@ ppermute_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nad.deflinear(ppermute_p, _ppermute_transpose_rule)\nxla.parallel_translations[ppermute_p] = _ppermute_translation_rule\npxla.multi_host_supported_collectives.add(ppermute_p)\n-batching.primitive_batchers[ppermute_p] = partial(_collective_batcher, pmin_p)\nbatching.collective_rules[ppermute_p] = _ppermute_batcher\n"
}
] | Python | Apache License 2.0 | google/jax | Fixed ppermute translation rule (#4349) |
260,335 | 18.09.2020 17:39:05 | 25,200 | f172fb74e17f250f769ca398d2eb563d88153ac2 | plumb donate_argnums into jax.xla_computation | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -437,7 +437,8 @@ def xla_computation(fun: Callable,\nbackend: Optional[str] = None,\ntuple_args: bool = False,\ninstantiate_const_outputs: Optional[bool] = None,\n- return_shape: bool = False) -> Callable:\n+ return_shape: bool = False,\n+ donate_argnums: Union[int, Iterable[int]] = ()) -> Callable:\n\"\"\"Creates a function that produces its XLA computation given example args.\nArgs:\n@@ -551,7 +552,8 @@ def xla_computation(fun: Callable,\nout_parts=out_parts,\nbackend=backend,\ntuple_args=tuple_args,\n- instantiate_const_outputs=instantiate_const_outputs)\n+ instantiate_const_outputs=instantiate_const_outputs,\n+ donate_argnums=donate_argnums)\ndef computation_maker(*args, **kwargs):\nxla_return = internal_computation_maker(*args, **kwargs)\n@@ -582,8 +584,7 @@ def _xla_computation(\nbackend: Optional[str] = None,\ntuple_args: Optional[bool] = None,\ninstantiate_const_outputs: Optional[bool] = True,\n- donate_argnums: Union[int, Iterable[int]] = ()\n-) -> Callable:\n+ donate_argnums: Union[int, Iterable[int]] = ()) -> Callable:\n\"\"\"An internal implementation for `xla_computation` and `_cpp_jit`.\nSee `xla_computation` for the full documentation.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/api_util.py",
"new_path": "jax/api_util.py",
"diff": "@@ -81,6 +81,15 @@ def argnums_partial(f, dyn_argnums, args):\ndyn_argnums = tuple(dyn_argnums)\nfixed_args = tuple([unit if i in dyn_argnums else wrap_hashably(arg)\nfor i, arg in enumerate(args)])\n+\n+@lu.transformation\n+def _argnums_partial(dyn_argnums, fixed_args, *dyn_args, **kwargs):\n+ args = [None if arg is unit else arg.val for arg in fixed_args]\n+ for i, arg in zip(dyn_argnums, dyn_args):\n+ args[i] = arg\n+ ans = yield args, kwargs\n+ yield ans\n+\ndyn_args = tuple(args[i] for i in dyn_argnums)\nreturn _argnums_partial(f, dyn_argnums, fixed_args), dyn_args\n@@ -135,14 +144,6 @@ def wrap_hashably(arg):\nelse:\nreturn Hashable(arg)\n-@lu.transformation\n-def _argnums_partial(dyn_argnums, fixed_args, *dyn_args, **kwargs):\n- args = [None if arg is unit else arg.val for arg in fixed_args]\n- for i, arg in zip(dyn_argnums, dyn_args):\n- args[i] = arg\n- ans = yield args, kwargs\n- yield ans\n-\ndef flatten_axes(name, treedef, axis_tree):\n# given an axis spec tree axis_tree (a pytree with integers and Nones at the\n# leaves, i.e. the Nones are to be considered leaves) that is a tree prefix of\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -656,6 +656,7 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\nfor a, d in zip(xla_args, donated_invars) if d]\nwarn(\"Some donated buffers were not usable: {}\".format(\", \".join(unused_donations)))\nbuilt = c.build(out_tuple)\n+ print(built.as_hlo_text())\noptions = xb.get_compile_options(\nnum_replicas=nreps,\n"
}
] | Python | Apache License 2.0 | google/jax | plumb donate_argnums into jax.xla_computation |
260,335 | 19.09.2020 19:41:17 | 25,200 | 50dd9c5016ce0bceaad7256208e790b0b02a3142 | don't initialize backend in xla_computation
This should allow us to use donate_argnums *and* build HLO computations
for backends not available at build time. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -676,12 +676,9 @@ def _xla_computation(\nout_tuple = build_out_tuple()\nif any(donated_invars):\n- # TODO(tomhennigan): At call time we should mark these buffers as deleted.\n- backend_ = xb.get_backend(backend)\n- if backend_.platform in (\"gpu\", \"tpu\"):\ndonated_invars = xla.set_up_aliases(c, xla_args, out_tuple, donated_invars,\ntuple_args)\n- if any(donated_invars):\n+ if backend in (\"gpu\", \"tpu\") and any(donated_invars):\nshapes = [str(c.GetShape(a)) for a, d in zip(xla_args, donated_invars) if d]\nwarn(\"Some donated buffers were not usable: {}\".format(\", \".join(shapes)))\nbuilt = c.build(out_tuple)\n"
}
] | Python | Apache License 2.0 | google/jax | don't initialize backend in xla_computation
This should allow us to use donate_argnums *and* build HLO computations
for backends not available at build time. |
260,335 | 19.09.2020 22:19:29 | 25,200 | 1092fa1d9b3de680aca5a883b781e6ba97c940be | fix logic, skip test | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -675,7 +675,7 @@ def _xla_computation(\nelse:\nout_tuple = build_out_tuple()\n- if any(donated_invars) and backend in (\"gpu\", \"tpu\"):\n+ if any(donated_invars):\ndonated_invars = xla.set_up_aliases(c, xla_args, out_tuple, donated_invars,\ntuple_args)\nif any(donated_invars):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -239,6 +239,7 @@ class CPPJitTest(jtu.JaxTestCase):\nself.assertDeleted(c)\nself.assertDeleted(d)\n+ @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\ndef test_jnp_array_copy(self):\n# https://github.com/google/jax/issues/3412\n"
}
] | Python | Apache License 2.0 | google/jax | fix logic, skip test |
260,287 | 21.09.2020 14:14:52 | 0 | c4f98eb8fa2947e0db4a65bb67daa3243e7d103d | Add back the batching rule for ppermute
Just make sure it's correct this time and add a test. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -547,6 +547,7 @@ ppermute_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nad.deflinear(ppermute_p, _ppermute_transpose_rule)\nxla.parallel_translations[ppermute_p] = _ppermute_translation_rule\npxla.multi_host_supported_collectives.add(ppermute_p)\n+batching.primitive_batchers[ppermute_p] = partial(_collective_batcher, ppermute_p)\nbatching.collective_rules[ppermute_p] = _ppermute_batcher\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -1540,6 +1540,23 @@ class VmapOfPmapTest(jtu.JaxTestCase):\nself.assertAllClose(f(jax.pmap, jax.vmap)(x, x), y)\nself.assertAllClose(f(jax.vmap, jax.pmap)(x, x), y)\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testPPermuteWithVmap(self):\n+ perm = [(0, 1), (1, 0)]\n+\n+ def f(map2):\n+ @partial(jax.pmap, axis_name='i')\n+ @partial(map2)\n+ def f(x, y):\n+ return x + jax.lax.ppermute(x.dot(y), 'i', perm)\n+ return f\n+\n+ if xla_bridge.device_count() < 4:\n+ raise SkipTest(\"test requires at least four devices\")\n+ x = jnp.ones((2, 2, 64, 64))\n+ self.assertAllClose(f(jax.pmap)(x, x), f(jax.vmap)(x, x))\n+\nclass PmapWithDevicesTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Add back the batching rule for ppermute
Just make sure it's correct this time and add a test. |
260,287 | 21.09.2020 16:25:50 | 0 | 2081e5acee2039930c250ccb91483ed6d6cfe580 | Test pmap/vmap interactions of all reduction collectives | [
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -1522,14 +1522,18 @@ class VmapOfPmapTest(jtu.JaxTestCase):\nexpected = np.stack([fun(*args_slice(i)) for i in range(vmapped_size)])\nself.assertAllClose(ans, expected)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_collective={}\".format(collective.__name__).replace(\" \", \"\"),\n+ \"collective\": collective}\n+ for collective in [lax.psum, lax.pmean, lax.pmax, lax.pmin])\n@skipIf(not jax.config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\n- def testCollectivesWithVmap(self):\n+ def testCollectivesWithVmap(self, collective):\ndef f(map1, map2):\n@partial(map1, axis_name='i')\n@partial(map2, axis_name='j')\ndef f(x, y):\n- return x + jax.lax.psum(x.dot(y), ('i', 'j'))\n+ return x + collective(x.dot(y), ('i', 'j'))\nreturn f\nif xla_bridge.device_count() < 4:\n"
}
] | Python | Apache License 2.0 | google/jax | Test pmap/vmap interactions of all reduction collectives |
260,631 | 21.09.2020 14:18:31 | 25,200 | 55c6bdfe9c5d0631200cb76e4f56481b3656b03f | Clean-up todos related to the upgrade of jaxlib. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -49,6 +49,7 @@ from .tree_util import (tree_map, tree_flatten, tree_unflatten, tree_structure,\ntreedef_is_leaf, Partial)\nfrom .util import (unzip2, curry, partial, safe_map, safe_zip, prod, split_list,\nextend_name_stack, wrap_name, cache)\n+from .lib import jax_jit\nfrom .lib import xla_bridge as xb\nfrom .lib import xla_client as xc\n# Unused imports to be exported\n@@ -308,9 +309,7 @@ def _cpp_jit(\nxla_result.shaped_arrays,\nxla_result.lazy_expressions)\n- # TODO(jblespiau): Remove when C++ jit has landed (jaxlib.version >= 0.1.54)\n# Delay the import, because it requires a new version of jaxlib.\n- from .lib import jax_jit # pylint: disable=g-import-not-at-top\ncpp_jitted_f = jax_jit.jit(fun, cache_miss,\npython_jitted_f, FLAGS.jax_enable_x64,\nconfig.read(\"jax_disable_jit\"), static_argnums)\n@@ -414,15 +413,11 @@ def disable_jit():\nprev_val = _thread_local_state.jit_is_disabled\n_thread_local_state.jit_is_disabled = True\n- # TODO(jblespiau): Remove when C++ jit has landed (jaxlib.version >= 0.1.54)\n- if hasattr(lib, \"jax_jit\") and hasattr(lib.jax_jit, \"set_disable_jit\"):\nprev_cpp_val = lib.jax_jit.get_disable_jit()\nlib.jax_jit.set_disable_jit(True)\n-\nyield\nfinally:\n_thread_local_state.jit_is_disabled = prev_val\n- if hasattr(lib, \"jax_jit\") and hasattr(lib.jax_jit, \"set_disable_jit\"):\nlib.jax_jit.set_disable_jit(prev_cpp_val)\n"
}
] | Python | Apache License 2.0 | google/jax | Clean-up todos related to the upgrade of jaxlib.
PiperOrigin-RevId: 332932271 |
260,325 | 21.09.2020 16:20:17 | 25,200 | be50847ceeafc3d08de31bae21e9404b6283f05f | Make scale_and_translate take spatial dimensions | [
{
"change_type": "MODIFY",
"old_path": "jax/image/scale.py",
"new_path": "jax/image/scale.py",
"diff": "@@ -52,7 +52,7 @@ def compute_weight_mat(input_size: int, output_size: int, scale,\n# When downsampling the kernel should be scaled since we want to low pass\n# filter and interpolate, but when upsampling it should not be since we only\n# want to interpolate.\n- kernel_scale = max(inv_scale, 1.) if antialias else 1.\n+ kernel_scale = jnp.maximum(inv_scale, 1.) if antialias else 1.\nsample_f = ((np.arange(output_size) + 0.5) * inv_scale -\ntranslation * inv_scale - 0.5)\n@@ -75,18 +75,12 @@ def compute_weight_mat(input_size: int, output_size: int, scale,\nsample_f <= input_size - 0.5)[jnp.newaxis, :], weights, 0)\n-def _scale_and_translate(x, output_shape, scale, translation, kernel,\n- antialias, precision):\n+def _scale_and_translate(x, output_shape, spatial_dims, scale, translation,\n+ kernel, antialias, precision):\ninput_shape = x.shape\nassert len(input_shape) == len(output_shape)\n- assert len(input_shape) == len(scale)\n- assert len(input_shape) == len(translation)\n- # Skip dimensions that have scale=1 and translation=0, this is only possible\n- # since all of the current resize methods (kernels) are interpolating, so the\n- # output = input under an identity warp.\n- spatial_dims, = np.nonzero(np.not_equal(input_shape, output_shape) |\n- np.not_equal(scale, 1) |\n- np.not_equal(translation, 0))\n+ assert len(spatial_dims) == len(scale)\n+ assert len(spatial_dims) == len(translation)\nif len(spatial_dims) == 0:\nreturn x\ncontractions = []\n@@ -95,7 +89,7 @@ def _scale_and_translate(x, output_shape, scale, translation, kernel,\nfor i, d in enumerate(spatial_dims):\nm = input_shape[d]\nn = output_shape[d]\n- w = compute_weight_mat(m, n, scale[d], translation[d],\n+ w = compute_weight_mat(m, n, scale[i], translation[i],\nkernel, antialias).astype(x.dtype)\ncontractions.append(w)\ncontractions.append([d, len(output_shape) + i])\n@@ -110,10 +104,10 @@ class ResizeMethod(enum.Enum):\nLANCZOS3 = 2\nLANCZOS5 = 3\nCUBIC = 4\n- # Caution: The current implementation assumes that the resize kernels are\n- # interpolating, i.e. for the identity warp the output equals the input. This\n- # is not true for, e.g. a Gaussian kernel, so if such kernels are added the\n- # implementation will need to be changed.\n+ # Caution: The current resize implementation assumes that the resize kernels\n+ # are interpolating, i.e. for the identity warp the output equals the input.\n+ # This is not true for, e.g. a Gaussian kernel, so if such kernels are added\n+ # the implementation will need to be changed.\n@staticmethod\ndef from_string(s: str):\n@@ -141,6 +135,7 @@ _kernels = {\n# scale and translation here are scalar elements of an np.array, what is the\n# correct type annotation?\ndef scale_and_translate(image, shape: Sequence[int],\n+ spatial_dims: Sequence[int],\nscale, translation,\nmethod: Union[str, ResizeMethod],\nantialias: bool = True,\n@@ -163,9 +158,9 @@ def scale_and_translate(image, shape: Sequence[int],\nThe ``method`` argument expects one of the following resize methods:\n- ``ResizeMethod.LINEAR``, ``\"linear\"``, ``\"bilinear\"``, ``\"trilinear\"``, ``\"triangle\"``\n- `Linear interpolation`_. If ``antialias`` is ``True``, uses a triangular\n- filter when downsampling.\n+ ``ResizeMethod.LINEAR``, ``\"linear\"``, ``\"bilinear\"``, ``\"trilinear\"``,\n+ ``\"triangle\"`` `Linear interpolation`_. If ``antialias`` is ``True``, uses a\n+ triangular filter when downsampling.\n``ResizeMethod.CUBIC``, ``\"cubic\"``, ``\"bicubic\"``, ``\"tricubic\"``\n`Cubic interpolation`_, using the Keys cubic kernel.\n@@ -184,6 +179,8 @@ def scale_and_translate(image, shape: Sequence[int],\nimage: a JAX array.\nshape: the output shape, as a sequence of integers with length equal to the\nnumber of dimensions of `image`.\n+ spatial_dims: A length K tuple specifying the spatial dimensions that the\n+ passed scale and translation should be applied to.\nscale: A [K] array with the same number of dimensions as image, containing\nthe scale to apply in each dimension.\ntranslation: A [K] array with the same number of dimensions as image,\n@@ -217,8 +214,8 @@ def scale_and_translate(image, shape: Sequence[int],\nif not jnp.issubdtype(translation.dtype, jnp.inexact):\ntranslation = lax.convert_element_type(\ntranslation, jnp.result_type(translation, jnp.float32))\n- return _scale_and_translate(image, shape, scale, translation, kernel,\n- antialias, precision)\n+ return _scale_and_translate(image, shape, spatial_dims, scale, translation,\n+ kernel, antialias, precision)\ndef _resize_nearest(x, output_shape):\n@@ -249,10 +246,15 @@ def _resize(image, shape: Sequence[int], method: Union[str, ResizeMethod],\nassert isinstance(method, ResizeMethod)\nkernel = _kernels[method]\n- scale = [float(o) / i for o, i in zip(shape, image.shape)]\nif not jnp.issubdtype(image.dtype, jnp.inexact):\nimage = lax.convert_element_type(image, jnp.result_type(image, jnp.float32))\n- return _scale_and_translate(image, shape, scale, [0.] * image.ndim, kernel,\n+ # Skip dimensions that have scale=1 and translation=0, this is only possible\n+ # since all of the current resize methods (kernels) are interpolating, so the\n+ # output = input under an identity warp.\n+ spatial_dims = tuple(np.nonzero(np.not_equal(image.shape, shape))[0])\n+ scale = [float(shape[d]) / image.shape[d] for d in spatial_dims]\n+ return _scale_and_translate(image, shape, spatial_dims,\n+ scale, [0.] * len(spatial_dims), kernel,\nantialias, precision)\n"
}
] | Python | Apache License 2.0 | google/jax | Make scale_and_translate take spatial dimensions |
260,325 | 21.09.2020 16:21:48 | 25,200 | ae910cdd311800fd1f2057b62d44028575820f60 | Updating image_test | [
{
"change_type": "MODIFY",
"old_path": "tests/image_test.py",
"new_path": "tests/image_test.py",
"diff": "@@ -21,6 +21,7 @@ import numpy as np\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n+import jax\nfrom jax import image\nfrom jax import numpy as jnp\nfrom jax import test_util as jtu\n@@ -221,7 +222,8 @@ class ImageTest(jtu.JaxTestCase):\n# Should we test different float types here?\nscale_a = jnp.array(scale, dtype=jnp.float32)\ntranslation_a = jnp.array(translation, dtype=jnp.float32)\n- output = image.scale_and_translate(x, target_shape, scale_a, translation_a,\n+ output = image.scale_and_translate(x, target_shape, range(len(image_shape)),\n+ scale_a, translation_a,\nmethod)\nexpected = np.array(\n@@ -274,12 +276,55 @@ class ImageTest(jtu.JaxTestCase):\n]\nx = np.array(data, dtype=dtype).reshape(image_shape)\n+ expected = np.array(\n+ expected_data[method], dtype=dtype).reshape(target_shape)\nscale_a = jnp.array([1.0, 0.35, 0.4, 1.0], dtype=jnp.float32)\ntranslation_a = jnp.array([0.0, 0.2, 0.1, 0.0], dtype=jnp.float32)\n+\noutput = image.scale_and_translate(\n- x, target_shape, scale_a, translation_a, method, antialias=antialias)\n- expected = np.array(\n- expected_data[method], dtype=dtype).reshape(target_shape)\n+ x, target_shape, (0,1,2,3),\n+ scale_a, translation_a, method, antialias=antialias)\n+ self.assertAllClose(output, expected, atol=2e-03)\n+\n+ # Tests that running with just a subset of dimensions that have non-trivial\n+ # scale and translation.\n+ output = image.scale_and_translate(\n+ x, target_shape, (1,2),\n+ scale_a[1:3], translation_a[1:3], method, antialias=antialias)\n+ self.assertAllClose(output, expected, atol=2e-03)\n+\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"antialias={}\".format(antialias),\n+ \"antialias\": antialias}\n+ for antialias in [True, False]))\n+ def testScaleAndTranslateJITs(self, antialias):\n+ image_shape = [1, 6, 7, 1]\n+ target_shape = [1, 3, 3, 1]\n+\n+ data = [\n+ 51, 38, 32, 89, 41, 21, 97, 51, 33, 87, 89, 34, 21, 97, 43, 25, 25, 92,\n+ 41, 11, 84, 11, 55, 111, 23, 99, 50, 83, 13, 92, 52, 43, 90, 43, 14, 89,\n+ 71, 32, 23, 23, 35, 93\n+ ]\n+ if antialias:\n+ expected_data = [\n+ 43.5372, 59.3694, 53.6907, 49.3221, 56.8168, 55.4849, 0, 0, 0\n+ ]\n+ else:\n+ expected_data = [43.6071, 89, 59, 37.1785, 27.2857, 58.3571, 0, 0, 0]\n+ x = jnp.array(data, dtype=jnp.float32).reshape(image_shape)\n+\n+ expected = jnp.array(expected_data, dtype=jnp.float32).reshape(target_shape)\n+ scale_a = jnp.array([1.0, 0.35, 0.4, 1.0], dtype=jnp.float32)\n+ translation_a = jnp.array([0.0, 0.2, 0.1, 0.0], dtype=jnp.float32)\n+\n+ def jit_fn(in_array, s, t):\n+ return jax.image.scale_and_translate(\n+ in_array, target_shape, (0, 1, 2, 3), s, t,\n+ \"linear\", antialias, precision=jax.lax.Precision.HIGHEST)\n+\n+ output = jax.jit(jit_fn)(x, scale_a, translation_a)\nself.assertAllClose(output, expected, atol=2e-03)\n"
}
] | Python | Apache License 2.0 | google/jax | Updating image_test |
260,335 | 21.09.2020 17:30:56 | 25,200 | 2abb37c286c92d70b8fb0104aacea60cda7675ce | move a _device_put_raw under broadcast impl
Before this change, we had to interact with the device to construct
an array of zeros, even if we were staging everything out (e.g. with
jax.xla_computation and omnistaging). | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -657,7 +657,8 @@ def broadcast_in_dim(operand: Array, shape: Shape,\n\"\"\"\nshape = _broadcast_in_dim_shape_rule(\noperand, shape=shape, broadcast_dimensions=broadcast_dimensions)\n- if np.ndim(operand) == len(shape) and not len(broadcast_dimensions):\n+ if (np.ndim(operand) == len(shape) and not len(broadcast_dimensions)\n+ and isinstance(operand, (xla.DeviceArray, core.Tracer))):\nreturn operand\nreturn broadcast_in_dim_p.bind(\noperand, shape=tuple(shape),\n@@ -1392,10 +1393,7 @@ def full(shape: Shape, fill_value: Array, dtype: Optional[DType] = None) -> Arra\nraise TypeError(msg.format(np.shape(fill_value)))\ndtype = dtypes.canonicalize_dtype(dtype or _dtype(fill_value))\nfill_value = convert_element_type(fill_value, dtype)\n- if config.omnistaging_enabled:\n- if not isinstance(fill_value, (xla.DeviceArray, core.Tracer)):\n- fill_value = _device_put_raw(fill_value)\n- else:\n+ if not config.omnistaging_enabled:\nfill_value = xla.device_put_p.bind(fill_value)\nreturn broadcast(fill_value, shape)\n@@ -3031,6 +3029,8 @@ ad.deflinear(broadcast_p, lambda t, sizes: [_reduce_sum(t, range(len(sizes)))])\nbatching.primitive_batchers[broadcast_p] = _broadcast_batch_rule\ndef _broadcast_in_dim_impl(operand, *, shape, broadcast_dimensions):\n+ if type(operand) is np.ndarray:\n+ operand = _device_put_raw(operand)\nif type(operand) is xla.DeviceArray and np.all(\nnp.equal(operand.shape, np.take(shape, broadcast_dimensions))):\nshape = _broadcast_in_dim_shape_rule(\n"
}
] | Python | Apache License 2.0 | google/jax | move a _device_put_raw under broadcast impl
Before this change, we had to interact with the device to construct
an array of zeros, even if we were staging everything out (e.g. with
jax.xla_computation and omnistaging). |
260,335 | 21.09.2020 19:33:14 | 25,200 | 34e04609610bd94498a0eb0eb0b902e4cb2fe287 | only test if omnistaging is enabled | [
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1798,6 +1798,9 @@ class APITest(jtu.JaxTestCase):\nf() # doesn't crash\ndef test_xla_computation_zeros_doesnt_device_put(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test is omnistaging-specific\")\n+\ncount = 0\ndef device_put_and_count(*args, **kwargs):\nnonlocal count\n"
}
] | Python | Apache License 2.0 | google/jax | only test if omnistaging is enabled |
260,548 | 21.09.2020 20:59:08 | -3,600 | 6aa35a2a7351e3c2bbf2fa1f58628801e95c8791 | Adding an option to return the output tree in make_jaxpr | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1938,7 +1938,8 @@ def linear_transpose(fun: Callable, *primals) -> Callable:\ndef make_jaxpr(fun: Callable,\n- static_argnums: Union[int, Iterable[int]] = ()\n+ static_argnums: Union[int, Iterable[int]] = (),\n+ return_shape: bool = False,\n) -> Callable[..., core.ClosedJaxpr]:\n\"\"\"Creates a function that produces its jaxpr given example args.\n@@ -1947,6 +1948,12 @@ def make_jaxpr(fun: Callable,\narguments and return value should be arrays, scalars, or standard Python\ncontainers (tuple/list/dict) thereof.\nstatic_argnums: See the :py:func:`jax.jit` docstring.\n+ return_shape: Optional boolean, defaults to ``False``. If ``True``, the\n+ wrapped function returns a pair where the first element is the ``jaxpr``\n+ and the second element is a pytree with the same structure as\n+ the output of ``fun`` and where the leaves are objects with ``shape`` and\n+ ``dtype`` attributes representing the corresponding types of the output\n+ leaves.\nReturns:\nA wrapped version of ``fun`` that when applied to example arguments returns\n@@ -2004,7 +2011,10 @@ def make_jaxpr(fun: Callable,\njaxpr, out_pvals, consts = pe.trace_to_jaxpr(\njaxtree_fun, in_pvals, instantiate=True, stage_out=True) # type: ignore\nout_avals = map(raise_to_shaped, unzip2(out_pvals)[0])\n- return core.ClosedJaxpr(jaxpr, consts)\n+ closed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\n+ if return_shape:\n+ return closed_jaxpr, tree_unflatten(out_tree(), out_avals)\n+ return closed_jaxpr\njaxpr_maker.__name__ = \"make_jaxpr({})\".format(jaxpr_maker.__name__)\nreturn jaxpr_maker\n"
}
] | Python | Apache License 2.0 | google/jax | Adding an option to return the output tree in make_jaxpr |
260,287 | 22.09.2020 13:08:38 | 0 | e0d1b375fa593c5ef777e7e650a3a3e75996cedc | Delete dead axis_index code
The primitive was moved to `lax_parallel.py` some time ago, so the one
in `core` should no longer be used. This is probably a result of a
botched rebase. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1191,48 +1191,6 @@ def axis_frame(axis_name):\nraise NameError(\"unbound axis name: {}\".format(axis_name))\n-def axis_index(axis_name):\n- \"\"\"Return the index along the mapped axis ``axis_name``.\n-\n- Args:\n- axis_name: hashable Python object used to name the mapped axis.\n-\n- Returns:\n- An integer representing the index.\n-\n- For example, with 8 XLA devices available:\n-\n- >>> from functools import partial\n- >>> @partial(jax.pmap, axis_name='i')\n- ... def f(_):\n- ... return lax.axis_index('i')\n- ...\n- >>> f(np.zeros(4))\n- ShardedDeviceArray([0, 1, 2, 3], dtype=int32)\n- >>> f(np.zeros(8))\n- ShardedDeviceArray([0, 1, 2, 3, 4, 5, 6, 7], dtype=int32)\n- >>> @partial(jax.pmap, axis_name='i')\n- ... @partial(jax.pmap, axis_name='j')\n- ... def f(_):\n- ... return lax.axis_index('i'), lax.axis_index('j')\n- ...\n- >>> x, y = f(np.zeros((4, 2)))\n- >>> print(x)\n- [[0 0]\n- [1 1]\n- [2 2]\n- [3 3]]\n- >>> print(y)\n- [[0 1]\n- [0 1]\n- [0 1]\n- [0 1]]\n- \"\"\"\n- return axis_index_p.bind(axis_name=axis_name)\n-\n-axis_index_p = Primitive('axis_index')\n-axis_index_p.def_abstract_eval(lambda *, axis_name: ShapedArray((), np.int32))\n-\n# ------------------- Jaxpr checking -------------------\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1277,15 +1277,6 @@ def _call_translation_rule(c, axis_env, in_nodes, name_stack,\ncall_translations[core.call_p] = _call_translation_rule\n-def _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\n- div = xb.constant(c, np.array(axis_env.nreps // prod(axis_env.sizes),\n- dtype=np.uint32))\n- mod = xb.constant(c, np.array(axis_env.sizes[-1], dtype=np.uint32))\n- unsigned_index = xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)\n- return xops.ConvertElementType(unsigned_index, xb.dtype_to_etype(np.int32))\n-parallel_translations[core.axis_index_p] = _axis_index_translation_rule # type: ignore\n-\n-\n@config.register_omnistaging_disabler\ndef omnistaging_disabler() -> None:\nglobal _pval_to_result_handler\n"
}
] | Python | Apache License 2.0 | google/jax | Delete dead axis_index code
The primitive was moved to `lax_parallel.py` some time ago, so the one
in `core` should no longer be used. This is probably a result of a
botched rebase. |
260,287 | 22.09.2020 16:05:24 | 0 | 8ac19c722211ffe4c7fb0bdbeeb236818d000291 | Fix a faulty soft_pmap rule for axis_index
The rule didn't specify the precision for the `np.arange` constant,
which caused an accidental dtype promotion in X64 mode. Previously the
error has luckicly been hidden behind a coerction that followed
`axis_index` in that test, but the new implementation has surfaced it. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -678,7 +678,7 @@ def _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\ndef _axis_index_soft_pmap_rule(vals, mapped, chunk_size, *, axis_name):\nassert not vals and not mapped\nidx = axis_index(axis_name) # type: ignore\n- return idx * chunk_size + np.arange(chunk_size), True\n+ return idx * chunk_size + np.arange(chunk_size, dtype=np.int32), True\naxis_index_p = core.Primitive('axis_index')\nxla.parallel_translations[axis_index_p] = _axis_index_translation_rule\n"
}
] | Python | Apache License 2.0 | google/jax | Fix a faulty soft_pmap rule for axis_index
The rule didn't specify the precision for the `np.arange` constant,
which caused an accidental dtype promotion in X64 mode. Previously the
error has luckicly been hidden behind a coerction that followed
`axis_index` in that test, but the new implementation has surfaced it. |
260,411 | 23.09.2020 13:14:36 | -10,800 | 625be69333ad46c7e0b4cb765060054faf5f2927 | [host_callback] Update the documentation
The module-level documentation was out of date. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "This module introduces the host callback functions :func:`id_tap` and\n:func:`id_print`, which behave like the identity function but have the\n-side-effect of sending the arguments from the accelerator to the host and\n+side-effect of sending the arguments from the device to the host and\ninvoking a user-specified Python function (for :func:`id_tap`) or printing the\n-arguments on the host (for :func:`id_print`). A few examples::\n+arguments on the host (for :func:`id_print`). The Python function passed\n+to :func:`id_tap` takes two positional arguments (the value tapped from the\n+device computation along with ``transforms`` sequence, described below).\n+A few examples::\n- # call func(2x) on host and return 2x\n+ # calls func(2x, []) on host and returns 2x\ny = id_tap(func, 2 * x)\n- # call func((2x, 3x)) and return (2x, 3x)\n+ # calls func((2x, 3x), []) and returns (2x, 3x)\ny, z = id_tap(func, (2 * x, 3 * x)) # The argument can be a pytree\n- # call func(2x) and return y\n- y = id_tap(func, 2 * x, result=y)\n- # call func(2x, what='activation') and return 2x\n- y = id_tap(func, 2 * x, what='activation')\n- # call func(dict(x=x, y=y), what='data') and return dict(x=x, y=y)\n- x, y = id_tap(func, dict(x=x, y=y), what='data')\n+ # calls func(2x, []) and returns y\n+ y = id_tap(func, 2 * x, result=y) # override the result of id_tap\n+ # calls func(2x, [], what='activation') and returns 2x\n+ y = id_tap(functools.partial(func, what='activation'), 2 * x)\n+ # calls func(dict(x=x, y=y), what='data') and returns dict(x=x, y=y)\n+ x, y = id_tap(lambda tap, transforms: func(tap, what='data'), dict(x=x, y=y))\n+\n+The above examples can all be adapted to use :func:`id_print` instead, with\n+the difference that :func:`id_print` takes one positional argument (to print\n+on the host), the optional kwarg ``result``, and possibly additional kwargs\n+that are also printed along with the automatic kwarg ``transforms``.\nThe order of execution of the tap functions is constrained by data dependency:\nthe arguments are sent after all the arguments are computed and before the\n@@ -78,15 +86,15 @@ following function definition::\ndef power3(x):\ny = x * x\n- _, y = id_print(x, y, what=\"x,x^2\")\n+ _, y = id_print((x, y), what=\"x,x^2\") # Must pack multiple arguments\nreturn y * x\n+ power3(3.)\n+ # what: x,x^2 : [3., 9.]\n+\nDuring JAX transformations the special parameter ``transforms`` is added to\n-contain a list of transformation descriptors. Each descriptor is a dictionary\n-containing the key ``name`` holding the name of the transformation and\n-additional keys holding transformation parameters, if applicable. This\n-parameter is passed to the tap function (or printed), in addition to\n-user-defined parameters.\n+contain a list of transformation descriptors in the form\n+``(transform_name, transform_params)``.\nFor :func:`jax.vmap` the arguments are batched, and ``transforms`` is extended\nwith transformation name ``batch`` and ``batch_dims`` set to the the tuple of\n@@ -94,15 +102,15 @@ batched dimensions (one entry per argument, ``None`` denotes an argument that\nwas broadcast)::\njax.vmap(power3)(np.arange(3.))\n- # what=x,x^2 transforms=({name=batch, batch_dims=(0, 0)}): ([0, 1, 2], [0, 1,\n- 4])\n+ # transforms: [('batch', {'batch_dims': (0, 0)})] what: x,x^2 : [[0, 1, 2], [0, 1,\n+ 4]]\nFor :func:`jax.jvp` there will be two callbacks, one with the values of\nthe primals and one with the tangents::\njax.jvp(power3, (3.,), (0.1,))\n- # what=x,x^2: (3., 9.)\n- # what=x,x^2 transforms={name=jvp}: (0.1, 0.6)\n+ # what: x,x^2: [3., 9.]\n+ # transforms: ['jvp'] what: x,x^2 : [0.1, 0.6]\nFor :func:`jax.vjp` or :func:`jax.grad` there will be one callback with the\nvalues of the adjoints for the arguments. You may also see a callback with\n@@ -110,13 +118,11 @@ the values of the primals from the forward pass, if those values are needed for\nthe backward pass::\njax.grad(power3)(3.)\n- # what=x,x^2: (3., 9.) # from forward pass, since y is needed in backward\n- pass\n- # what=x,x^2 transforms=({name=jvp}, {name=transpose}): (0., 3.) # from\n- backward pass, adjoints of _, y\n+ # what=x,x^2: [3., 9.] # from forward pass, since y is used in backward pass\n+ # transforms: ['jvp', 'transpose'] what: x,x^2 : [0., 3.] # from backward pass, adjoints of _, y\nSee documentation for :func:`id_tap` and :func:`id_print`.\n-For usage example, see tests/host_callback_test.py.\n+For more usage example, see tests/host_callback_test.py.\nStill to do:\n* Performance tests.\n@@ -187,20 +193,18 @@ def id_tap(tap_func, arg, *, result=None, **kwargs):\n``id_tap`` behaves semantically like the identity function but has the\nside-effect that a user-defined Python function is called with the runtime\n- values of the argument.\n+ value of the argument.\nArgs:\ntap_func: tap function to call like ``tap_func(arg, transforms)``, with\n- ``arg`` as described below and where ``transforms`` is sequence of applied\n- JAX transformations in the form ``(name, params)``.\n+ ``arg`` as described below and where ``transforms`` is the sequence of\n+ applied JAX transformations in the form ``(name, params)``.\narg: the argument passed to the tap function, can be a pytree of JAX\ntypes.\nresult: if given, specifies the return value of ``id_tap``. This value is\nnot passed to the tap function, and in fact is not sent from the device to\nthe host. If the ``result`` parameter is not specified then the return\nvalue of ``id_tap`` is ``arg``.\n- **kwargs: Deprecated option for passing additional keyword arguments to\n- ``tap_func``.\nReturns:\n``arg``, or ``result`` if given.\n"
}
] | Python | Apache License 2.0 | google/jax | [host_callback] Update the documentation
The module-level documentation was out of date. |
260,287 | 23.09.2020 12:59:01 | 0 | 2b7580c2d206e692a83fbc37eaeeb846e0a4462f | Consider lists as groups of axis names too | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -692,7 +692,7 @@ pxla.multi_host_supported_collectives.add(axis_index_p)\n# wants to bind an axis name has to additionally implement `process_axis_index`\n# and put its main trace on the axis env stack.\ndef _axis_index_bind(*, axis_name):\n- if not isinstance(axis_name, tuple):\n+ if not isinstance(axis_name, (tuple, list)):\naxis_name = (axis_name,)\ninner_size = 1\nindex = 0\n"
}
] | Python | Apache License 2.0 | google/jax | Consider lists as groups of axis names too |
260,287 | 23.09.2020 10:45:23 | 0 | 0d5f15f5c0f862d3d5cbf8f6853409cdc1091de1 | Fix the abstract eval and translation rule for all_to_all
The previous rules assumed that `split_axis == concat_axis` (i.e. that
the used collective is equivalent to `pswapaxes`). Since we expose this
as part of our API, we should probably make sure that we handle other
cases too.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -557,13 +557,25 @@ def _all_to_all_translation_rule(c, x, *, split_axis, concat_axis, axis_name,\nreplica_groups = _replica_groups(axis_env, axis_name, None)\nif len(replica_groups[0]) == 1:\nreturn x\n- else:\n+ elif platform == 'tpu':\nsplit_count = len(replica_groups[0])\nif not all(split_count == len(g) for g in replica_groups):\nraise ValueError('Replica groups must be equally sized')\nreplica_groups_protos = xc.make_replica_groups(replica_groups)\n+ if concat_axis == split_axis:\nreturn xops.AllToAll(x, split_axis, concat_axis, split_count,\nreplica_groups_protos)\n+ else:\n+ if concat_axis < split_axis:\n+ split_axis += 1\n+ elif split_axis < concat_axis:\n+ concat_axis += 1\n+ x = xla.lower_fun(partial(lax.expand_dims, dimensions=(concat_axis,)), multiple_results=False)(c, x)\n+ x = xops.AllToAll(x, split_axis, concat_axis, split_count, replica_groups_protos)\n+ x = xla.lower_fun(partial(lax.squeeze, dimensions=(split_axis,)), multiple_results=False)(c, x)\n+ return x\n+ else:\n+ raise NotImplementedError(\"all_to_all and pswapaxes only supported on TPU\")\ndef _all_to_all_split_axis_rule(vals, which_mapped, split_axis, concat_axis,\naxis_name):\n@@ -585,8 +597,15 @@ def _moveaxis(src, dst, x):\nperm.insert(dst, src)\nreturn lax.transpose(x, perm)\n+def _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis):\n+ input_aval = raise_to_shaped(x)\n+ shape = list(input_aval.shape)\n+ size = shape.pop(split_axis)\n+ shape.insert(concat_axis, size)\n+ return ShapedArray(tuple(shape), input_aval.dtype, weak_type=False)\n+\nall_to_all_p = core.Primitive('all_to_all')\n-all_to_all_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\n+all_to_all_p.def_abstract_eval(_all_to_all_abstract_eval)\nxla.parallel_translations[all_to_all_p] = _all_to_all_translation_rule\nad.deflinear(all_to_all_p, _all_to_all_transpose_rule)\npxla.multi_host_supported_collectives.add(all_to_all_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -197,6 +197,55 @@ class PmapTest(jtu.JaxTestCase):\nans = f(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_split={split_axis}_concat={concat_axis}\",\n+ \"split_axis\": split_axis, \"concat_axis\": concat_axis}\n+ for split_axis, concat_axis in it.product(range(2), range(2)))\n+ def testAllToAll(self, split_axis, concat_axis):\n+ if jtu.device_under_test() != \"tpu\":\n+ raise SkipTest(\"all_to_all not implemented on non-TPU platforms\")\n+ pmap_in_axis = 0\n+ shape = (xla_bridge.device_count(),) * 3\n+ x = np.arange(np.prod(shape)).reshape(shape)\n+\n+ @partial(pmap, axis_name='i')\n+ def f(x):\n+ return lax.all_to_all(x, 'i', split_axis, concat_axis)\n+ y = f(x)\n+ if pmap_in_axis <= split_axis:\n+ split_axis += 1\n+ ref = jnp.moveaxis(x, (pmap_in_axis, split_axis),\n+ (concat_axis + 1, 0))\n+ self.assertAllClose(y, ref)\n+\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_split={split_axis}_concat={concat_axis}\",\n+ \"split_axis\": split_axis, \"concat_axis\": concat_axis}\n+ for split_axis, concat_axis in it.product(range(2), range(2)))\n+ def testAllToAllSplitAxis(self, split_axis, concat_axis):\n+ if jtu.device_under_test() != \"tpu\":\n+ raise SkipTest(\"all_to_all not implemented on non-TPU platforms\")\n+ if xla_bridge.device_count() < 4:\n+ raise SkipTest(\"test requires at least four devices\")\n+ pmap_in_axis = 0\n+ shape = (4, 4, 4)\n+ x = np.arange(np.prod(shape)).reshape(shape)\n+\n+ @partial(pmap, axis_name='i')\n+ @partial(pmap, axis_name='j')\n+ def f(x):\n+ return lax.all_to_all(x, ('i', 'j'), split_axis, concat_axis)\n+\n+ unroll_shape = (2, 2, *shape[1:])\n+ x_unroll = x.reshape(unroll_shape)\n+ y_unroll = f(x_unroll)\n+ y = y_unroll.reshape(shape)\n+\n+ if pmap_in_axis <= split_axis:\n+ split_axis += 1\n+ ref = jnp.moveaxis(x, (pmap_in_axis, split_axis),\n+ (concat_axis + 1, 0))\n+ self.assertAllClose(y, ref)\ndef testNestedBasic(self):\nf = lambda x: lax.psum(lax.psum(x, 'i'), 'j')\n"
}
] | Python | Apache License 2.0 | google/jax | Fix the abstract eval and translation rule for all_to_all
The previous rules assumed that `split_axis == concat_axis` (i.e. that
the used collective is equivalent to `pswapaxes`). Since we expose this
as part of our API, we should probably make sure that we handle other
cases too.
Fixes #1332. |
260,335 | 23.09.2020 19:37:34 | 25,200 | c42d736e347d059290ab20c013635d62a1ee6c45 | remove limit on size of random arrays | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -308,12 +308,17 @@ def _random_bits(key, bit_width, shape):\nraise TypeError(\"requires 8-, 16-, 32- or 64-bit field width.\")\nsize = prod(shape)\nmax_count = int(np.ceil(bit_width * size / 32))\n- if max_count >= jnp.iinfo(np.uint32).max:\n- # TODO(mattjj): just split the key here\n- raise TypeError(\"requesting more random bits than a single call provides.\")\n- counts = lax.iota(np.uint32, max_count)\n- bits = threefry_2x32(key, counts)\n+ nblocks, rem = divmod(max_count, jnp.iinfo(np.uint32).max)\n+ if not nblocks:\n+ bits = threefry_2x32(key, lax.iota(np.uint32, rem))\n+ else:\n+ *subkeys, last_key = split(key, nblocks + 1)\n+ blocks = [threefry_2x32(k, lax.iota(np.uint32, jnp.iinfo(np.uint32).max))\n+ for k in subkeys]\n+ last = threefry_2x32(last_key, lax.iota(np.uint32, rem))\n+ bits = lax.concatenate(blocks + [last], 0)\n+\ndtype = _UINT_DTYPES[bit_width]\nif bit_width == 64:\nbits = [lax.convert_element_type(x, dtype) for x in jnp.split(bits, 2)]\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -857,6 +857,11 @@ class LaxRandomTest(jtu.JaxTestCase):\nwith self.assertRaises(TypeError):\nrandom.choice(key, 5, 2, replace=True)\n+ def test_eval_shape_big_random_array(self):\n+ def f():\n+ return random.normal(random.PRNGKey(0), (int(1e10),))\n+ api.eval_shape(f) # doesn't error\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | remove limit on size of random arrays |
260,335 | 23.09.2020 19:39:22 | 25,200 | 96f5a3c4026c929664e75e07262bba7a4c8d2044 | fix test for non-omnistaging | [
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -858,9 +858,9 @@ class LaxRandomTest(jtu.JaxTestCase):\nrandom.choice(key, 5, 2, replace=True)\ndef test_eval_shape_big_random_array(self):\n- def f():\n- return random.normal(random.PRNGKey(0), (int(1e10),))\n- api.eval_shape(f) # doesn't error\n+ def f(x):\n+ return random.normal(random.PRNGKey(x), (int(1e10),))\n+ api.eval_shape(f, 0) # doesn't error\nif __name__ == \"__main__\":\n"
}
] | Python | Apache License 2.0 | google/jax | fix test for non-omnistaging |
260,335 | 23.09.2020 20:15:32 | 25,200 | 71f5f9972cd305d4060637115a7ff316087d229e | skip checks in big randomness test | [
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -859,7 +859,8 @@ class LaxRandomTest(jtu.JaxTestCase):\ndef test_eval_shape_big_random_array(self):\ndef f(x):\n- return random.normal(random.PRNGKey(x), (int(1e10),))\n+ return random.normal(random.PRNGKey(x), (int(1e12),))\n+ with core.skipping_checks(): # check_jaxpr will materialize array\napi.eval_shape(f, 0) # doesn't error\n"
}
] | Python | Apache License 2.0 | google/jax | skip checks in big randomness test |
260,335 | 23.09.2020 20:41:57 | 25,200 | d607164d35e05077d60969a8e6b145f10aca95e0 | make_jaxpr return_shape use ShapeDtypeStruct, test | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1957,7 +1957,11 @@ def make_jaxpr(fun: Callable,\nReturns:\nA wrapped version of ``fun`` that when applied to example arguments returns\n- a ``ClosedJaxpr`` representation of ``fun`` on those arguments.\n+ a ``ClosedJaxpr`` representation of ``fun`` on those arguments. If the\n+ argument ``return_shape`` is ``True``, then the returned function instead\n+ returns a pair where the first element is the ``ClosedJaxpr``\n+ representation of ``fun`` and the second element is a pytree representing\n+ the structure, shape, and dtypes of the output of ``fun``.\nA ``jaxpr`` is JAX's intermediate representation for program traces. The\n``jaxpr`` language is based on the simply-typed first-order lambda calculus\n@@ -2013,7 +2017,8 @@ def make_jaxpr(fun: Callable,\nout_avals = map(raise_to_shaped, unzip2(out_pvals)[0])\nclosed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\nif return_shape:\n- return closed_jaxpr, tree_unflatten(out_tree(), out_avals)\n+ out_shapes_flat = [ShapeDtypeStruct(a.shape, a.dtype) for a in out_avals]\n+ return closed_jaxpr, tree_unflatten(out_tree(), out_shapes_flat)\nreturn closed_jaxpr\njaxpr_maker.__name__ = \"make_jaxpr({})\".format(jaxpr_maker.__name__)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2259,6 +2259,13 @@ class JaxprTest(jtu.JaxTestCase):\njaxpr = api.make_jaxpr(f, static_argnums=(1,))(2, 3)\nself.assertIn('3', str(jaxpr))\n+ def test_make_jaxpr_return_shape(self):\n+ _, shape_tree = api.make_jaxpr(lambda x: (x + 1, jnp.zeros(2, jnp.float32)),\n+ return_shape=True)(np.int32(1))\n+ expected = (api.ShapeDtypeStruct(shape=(), dtype=jnp.int32),\n+ api.ShapeDtypeStruct(shape=(2,), dtype=jnp.float32))\n+ self.assertEqual(shape_tree, expected)\n+\nclass LazyTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | make_jaxpr return_shape use ShapeDtypeStruct, test |
260,335 | 23.09.2020 21:09:44 | 25,200 | ebf7c1b6127d6df3a64a4d969297ca70e126a341 | add jax logo file | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/jax_logo.svg",
"diff": "+<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 451 260.81\"><defs><style>.cls-1{fill:#5e97f6;}.cls-1,.cls-2,.cls-3,.cls-4,.cls-5,.cls-6,.cls-7,.cls-8,.cls-9{stroke:#dce0df;stroke-linejoin:round;}.cls-2{fill:#2a56c6;}.cls-3{fill:#00796b;}.cls-4{fill:#3367d6;}.cls-5{fill:#26a69a;}.cls-6{fill:#9c27b0;}.cls-7{fill:#6a1b9a;}.cls-8{fill:#00695c;}.cls-9{fill:#ea80fc;}</style></defs><title>JAX Light Stroke</title><g id=\"Layer_2\" data-name=\"Layer 2\"><g id=\"Layer_1-2\" data-name=\"Layer 1\"><polygon class=\"cls-1\" points=\"50.5 130.4 25.5 173.71 75.5 173.71 100.5 130.4 50.5 130.4\"/><polygon class=\"cls-1\" points=\"0.5 217.01 25.5 173.71 75.5 173.71 50.5 217.01 0.5 217.01\"/><polygon class=\"cls-1\" points=\"125.5 173.71 75.5 173.71 50.5 217.01 100.5 217.01 125.5 173.71\"/><polygon class=\"cls-1\" points=\"175.5 173.71 125.5 173.71 100.5 217.01 150.5 217.01 175.5 173.71\"/><polygon class=\"cls-1\" points=\"150.5 130.4 125.5 173.71 175.5 173.71 200.5 130.4 150.5 130.4\"/><polygon class=\"cls-1\" points=\"175.5 87.1 150.5 130.4 200.5 130.4 225.5 87.1 175.5 87.1\"/><polygon class=\"cls-1\" points=\"200.5 43.8 175.5 87.1 225.5 87.1 250.5 43.8 200.5 43.8\"/><polygon class=\"cls-1\" points=\"225.5 0.5 200.5 43.8 250.5 43.8 275.5 0.5 225.5 0.5\"/><polygon class=\"cls-2\" points=\"0.5 217.01 25.5 260.31 75.5 260.31 50.5 217.01 0.5 217.01\"/><polygon class=\"cls-2\" points=\"125.5 260.31 75.5 260.31 50.5 217.01 100.5 217.01 125.5 260.31\"/><polygon class=\"cls-2\" points=\"175.5 260.31 125.5 260.31 100.5 217.01 150.5 217.01 175.5 260.31\"/><polygon class=\"cls-3\" points=\"200.5 217.01 175.5 173.71 150.5 217.01 175.5 260.31 200.5 217.01\"/><polygon class=\"cls-3\" points=\"250.5 130.4 225.5 87.1 200.5 130.4 250.5 130.4\"/><polygon class=\"cls-3\" points=\"250.5 43.8 225.5 87.1 250.5 130.4 275.5 87.1 250.5 43.8\"/><polygon class=\"cls-4\" points=\"125.5 173.71 100.5 130.4 75.5 173.71 125.5 173.71\"/><polygon class=\"cls-5\" points=\"250.5 130.4 200.5 130.4 175.5 173.71 225.5 173.71 250.5 130.4\"/><polygon class=\"cls-5\" points=\"300.5 130.4 250.5 130.4 225.5 173.71 275.5 173.71 300.5 130.4\"/><polygon class=\"cls-6\" points=\"350.5 43.8 325.5 0.5 300.5 43.8 325.5 87.1 350.5 43.8\"/><polygon class=\"cls-6\" points=\"375.5 87.1 350.5 43.8 325.5 87.1 350.5 130.4 375.5 87.1\"/><polygon class=\"cls-6\" points=\"400.5 130.4 375.5 87.1 350.5 130.4 375.5 173.71 400.5 130.4\"/><polygon class=\"cls-6\" points=\"425.5 173.71 400.5 130.4 375.5 173.71 400.5 217.01 425.5 173.71\"/><polygon class=\"cls-6\" points=\"450.5 217.01 425.5 173.71 400.5 217.01 425.5 260.31 450.5 217.01\"/><polygon class=\"cls-6\" points=\"425.5 0.5 400.5 43.8 425.5 87.1 450.5 43.8 425.5 0.5\"/><polygon class=\"cls-6\" points=\"375.5 87.1 400.5 43.8 425.5 87.1 400.5 130.4 375.5 87.1\"/><polygon class=\"cls-6\" points=\"350.5 130.4 325.5 173.71 350.5 217.01 375.5 173.71 350.5 130.4\"/><polygon class=\"cls-6\" points=\"325.5 260.31 300.5 217.01 325.5 173.71 350.5 217.01 325.5 260.31\"/><polygon class=\"cls-7\" points=\"275.5 260.31 250.5 217.01 300.5 217.01 325.5 260.31 275.5 260.31\"/><polygon class=\"cls-8\" points=\"225.5 173.71 175.5 173.71 200.5 217.01 250.5 217.01 225.5 173.71\"/><polygon class=\"cls-8\" points=\"275.5 173.71 225.5 173.71 250.5 217.01 275.5 173.71\"/><polygon class=\"cls-8\" points=\"275.5 87.1 300.5 130.4 350.5 130.4 325.5 87.1 275.5 87.1\"/><polygon class=\"cls-8\" points=\"300.5 43.8 250.5 43.8 275.5 87.1 325.5 87.1 300.5 43.8\"/><polygon class=\"cls-8\" points=\"425.5 260.31 400.5 217.01 350.5 217.01 375.5 260.31 425.5 260.31\"/><polygon class=\"cls-8\" points=\"375.5 173.71 350.5 217.01 400.5 217.01 375.5 173.71\"/><polygon class=\"cls-9\" points=\"325.5 0.5 275.5 0.5 250.5 43.8 300.5 43.8 325.5 0.5\"/><polygon class=\"cls-9\" points=\"325.5 173.71 275.5 173.71 250.5 217.01 300.5 217.01 325.5 173.71\"/><polygon class=\"cls-9\" points=\"350.5 130.4 300.5 130.4 275.5 173.71 325.5 173.71 350.5 130.4\"/><polygon class=\"cls-9\" points=\"425.5 0.5 375.5 0.5 350.5 43.8 400.5 43.8 425.5 0.5\"/><polygon class=\"cls-9\" points=\"375.5 87.1 350.5 43.8 400.5 43.8 375.5 87.1\"/></g></g></svg>\n\\ No newline at end of file\n"
}
] | Python | Apache License 2.0 | google/jax | add jax logo file |
260,411 | 24.09.2020 15:08:07 | -10,800 | 03970e9787bcf7a04257ea9b0b6f537ceac68d4f | Tag tests that require omnistaging | [
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -294,6 +294,8 @@ class HostCallbackTest(jtu.JaxTestCase):\ndef test_jit_result_unused(self):\n\"\"\"We can id_print even if we don't use the result.\"\"\"\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"Test requires omnistaging\")\ndef func(x):\nhcb.id_print(x, where=\"1\", output_stream=testing_stream)\nhcb.id_print(x + 1, where=\"2\", output_stream=testing_stream)\n@@ -742,6 +744,8 @@ class HostCallbackTest(jtu.JaxTestCase):\ntesting_stream.reset()\ndef test_grad_primal_unused(self):\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"Test requires omnistaging\")\n# The output of id_print is not needed for backwards pass\ndef func(x):\nreturn 2. * hcb.id_print(x * 3., what=\"x * 3\",\n@@ -803,7 +807,8 @@ class HostCallbackTest(jtu.JaxTestCase):\ntesting_stream.reset()\ndef test_grad_double(self):\n-\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"Test requires omnistaging\")\ndef func(x):\ny = hcb.id_print(x * 2., what=\"x * 2\", output_stream=testing_stream)\nreturn x * (y * 3.)\n"
}
] | Python | Apache License 2.0 | google/jax | Tag tests that require omnistaging |
260,287 | 28.08.2020 15:21:50 | 0 | acd4cc573722b2f5069e69d64f15b71e4502da55 | Allow vmapping all_to_all and implement a (slow) CPU and GPU translation
This allows pmapping vmapped computations that use `all_to_all` or
`pswapaxes` inside. It also includes a very slow CPU and GPU translation
rule that might be useful for debugging programs locally, since XLA only
implements the `AllToAll` collective on TPUs.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -857,7 +857,7 @@ def _tuple_output(*args, **kwargs):\nans = yield args, kwargs\nyield (ans,)\n-def lower_fun(fun, multiple_results):\n+def lower_fun(fun, multiple_results, parallel=False):\n# This function can only be used to lower functions that take JAX array types\n# as arguments (and e.g. don't accept unit values), because it assumes it can\n# map from XLA types to JAX types. In general that mapping is not possible (as\n@@ -868,10 +868,14 @@ def lower_fun(fun, multiple_results):\ndef f(c, *xla_args, **params):\n# TODO(mattjj): revise this 'calling convention'\navals = [_array_aval_from_xla_shape(c.get_shape(x)) for x in xla_args]\n+ if parallel:\n+ axis_env = params.pop('axis_env')\n+ del params['platform']\n+ else:\n+ axis_env = AxisEnv(1, (), (), None)\nwrapped_fun = lu.wrap_init(fun, params)\nif not multiple_results:\nwrapped_fun = _tuple_output(wrapped_fun)\n- axis_env = AxisEnv(1, (), (), None)\nif config.omnistaging_enabled:\njaxpr, _, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, avals)\nouts = jaxpr_subcomp(c, jaxpr, None, axis_env, _xla_consts(c, consts), '',\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -16,6 +16,7 @@ Parallelization primitives.\n\"\"\"\nimport collections\n+import warnings\nimport numpy as np\n@@ -243,9 +244,7 @@ def pswapaxes(x, axis_name, axis):\n``axis_name``.\nReturns:\n- Array(s) with shape ``np.insert(np.delete(x.shape, axis), axis, axis_size)``\n- where ``axis_size`` is the size of the mapped axis named ``axis_name`` in\n- the input ``x``.\n+ Array(s) with the same shape as ``x``.\n\"\"\"\nreturn all_to_all(x, axis_name, axis, axis)\n@@ -551,13 +550,32 @@ batching.primitive_batchers[ppermute_p] = partial(_collective_batcher, ppermute_\nbatching.collective_rules[ppermute_p] = _ppermute_batcher\n+def _moveaxis(src, dst, x):\n+ perm = [i for i in range(x.ndim) if i != src]\n+ perm.insert(dst, src)\n+ return lax.transpose(x, perm)\n+\n+def _all_to_all_via_all_gather(x, *, axis_name, split_axis, concat_axis):\n+ global_full = all_gather(x, axis_name)\n+ idx = axis_index(axis_name)\n+ local_slice = lax.dynamic_index_in_dim(global_full, idx, split_axis + 1, keepdims=False)\n+ return _moveaxis(0, concat_axis, local_slice)\n+\ndef _all_to_all_translation_rule(c, x, *, split_axis, concat_axis, axis_name,\naxis_env, platform):\n# Workaround for AllToAll not being implemented on CPU.\nreplica_groups = _replica_groups(axis_env, axis_name, None)\nif len(replica_groups[0]) == 1:\nreturn x\n- elif platform == 'tpu':\n+ elif platform != 'tpu':\n+ warnings.warn(\"all_to_all (and pswapaxes) are only implemented properly for TPUs. All other \"\n+ \"backends emulate it using a very slow and memory intensive algorithm, so expect \"\n+ \"significant slowdowns.\")\n+ lowering = xla.lower_fun(_all_to_all_via_all_gather, multiple_results=False, parallel=True)\n+ return lowering(c, x,\n+ split_axis=split_axis, concat_axis=concat_axis, axis_name=axis_name,\n+ axis_env=axis_env, platform=platform)\n+ else:\nsplit_count = len(replica_groups[0])\nif not all(split_count == len(g) for g in replica_groups):\nraise ValueError('Replica groups must be equally sized')\n@@ -574,28 +592,25 @@ def _all_to_all_translation_rule(c, x, *, split_axis, concat_axis, axis_name,\nx = xops.AllToAll(x, split_axis, concat_axis, split_count, replica_groups_protos)\nx = xla.lower_fun(partial(lax.squeeze, dimensions=(split_axis,)), multiple_results=False)(c, x)\nreturn x\n- else:\n- raise NotImplementedError(\"all_to_all and pswapaxes only supported on TPU\")\n-\n-def _all_to_all_split_axis_rule(vals, which_mapped, split_axis, concat_axis,\n- axis_name):\n- assert tuple(which_mapped) == (True,)\n- x, = vals\n- # perform the communication to swap the hardware-mapped axes\n- stacked = all_to_all_p.bind(x, split_axis=split_axis + 1, concat_axis=0,\n- axis_name=axis_name)\n- # transpose the newly mapped axis to the front, newly unmapped to concat_axis\n- out = _moveaxis(split_axis + 1, 0, stacked)\n- out = _moveaxis(1, concat_axis + 1, out)\n- return out, True\ndef _all_to_all_transpose_rule(cts, axis_name, split_axis, concat_axis):\nreturn (all_to_all(cts, axis_name=axis_name, split_axis=concat_axis, concat_axis=split_axis),)\n-def _moveaxis(src, dst, x):\n- perm = [i for i in range(x.ndim) if i != src]\n- perm.insert(dst, src)\n- return lax.transpose(x, perm)\n+def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_axis, concat_axis):\n+ x, = vals_in\n+ d, = dims_in\n+ if d <= split_axis:\n+ split_axis += 1\n+ if d <= concat_axis:\n+ concat_axis += 1\n+ # Note: At this point split_axis and concat_axis are adjusted to the extra\n+ # dimension and we have d != split_axis and d != concat_axis.\n+ if split_axis < d < concat_axis:\n+ d -= 1\n+ elif concat_axis < d < split_axis:\n+ d += 1\n+ result = all_to_all_p.bind(x, axis_name=axis_name, split_axis=split_axis, concat_axis=concat_axis)\n+ return result, d\ndef _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis):\ninput_aval = raise_to_shaped(x)\n@@ -609,6 +624,7 @@ all_to_all_p.def_abstract_eval(_all_to_all_abstract_eval)\nxla.parallel_translations[all_to_all_p] = _all_to_all_translation_rule\nad.deflinear(all_to_all_p, _all_to_all_transpose_rule)\npxla.multi_host_supported_collectives.add(all_to_all_p)\n+batching.primitive_batchers[all_to_all_p] = _all_to_all_batcher\ndef _expand(dim, size, index, x):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -97,6 +97,8 @@ ignore_soft_pmap_warning = partial(\nignore_jit_of_pmap_warning = partial(\njtu.ignore_warning, message=\".*jit-of-pmap.*\")\n+ignore_slow_all_to_all_warning = partial(\n+ jtu.ignore_warning, message=\"all_to_all.*expect significant slowdowns.*\")\nclass PmapTest(jtu.JaxTestCase):\ndef _getMeshShape(self, device_mesh_shape):\n@@ -143,6 +145,7 @@ class PmapTest(jtu.JaxTestCase):\nans = f(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @ignore_slow_all_to_all_warning()\ndef testTrees(self):\nptranspose = lambda x, axis_name: lax.all_to_all(x, axis_name, 0, 0)\ndef protate(x, axis_name):\n@@ -166,9 +169,9 @@ class PmapTest(jtu.JaxTestCase):\nassert_allclose(jax_f(lax.pmin)(x), np_f(np.min)(x))\nassert_allclose(jax_f(lax.psum)(x), np_f(np.sum)(x))\nassert_allclose(jax_f(lax.pmean)(x), np_f(np.mean)(x))\n- if jtu.device_under_test() not in (\"cpu\", \"gpu\"):\n- # NOTE: all-to-all and ppermute only supported on TPU.\nassert_allclose(jax_f(ptranspose)(x), np_transpose(x))\n+ # NOTE: ppermute only supported on TPU.\n+ if jtu.device_under_test() not in (\"cpu\", \"gpu\"):\nassert_allclose(jax_f(protate)(x), np_rotate(x))\ndef testCollectivesWithTreesOfDifferentDtypes(self):\n@@ -1630,6 +1633,77 @@ class VmapOfPmapTest(jtu.JaxTestCase):\nx = jnp.ones((2, 2, 64, 64))\nself.assertAllClose(f(jax.pmap)(x, x), f(jax.vmap)(x, x))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_split={split_axis}_concat={concat_axis}_vmap={vmap_axis}\",\n+ \"split_axis\": split_axis, \"concat_axis\": concat_axis, \"vmap_axis\": vmap_axis}\n+ for split_axis, concat_axis, vmap_axis in it.product(range(3), range(3), range(4)))\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ @ignore_slow_all_to_all_warning()\n+ def testAllToAllInVmap(self, split_axis, concat_axis, vmap_axis):\n+ def f(x):\n+ return lax.all_to_all(x, 'i', split_axis=split_axis, concat_axis=concat_axis)\n+\n+ def adj(axis, hidden_axes):\n+ for hax in sorted(hidden_axes):\n+ if hax <= axis:\n+ axis += 1\n+ return axis\n+\n+ def reference(x, split_axis, concat_axis, vmap_axis):\n+ pmap_axis = 0\n+ vmap_axis = adj(vmap_axis, [pmap_axis])\n+ ref = x\n+\n+ # Step 1.\n+ # Adjust the split axis to the real tensor layout and move it to\n+ # position 1. Since pmap_axis is always 0 we don't have to adjust it,\n+ # but we do have to adjust vmap_axis.\n+ split_axis = adj(split_axis, [pmap_axis, vmap_axis])\n+ ref = jnp.moveaxis(ref, split_axis, pmap_axis + 1)\n+ vmap_axis = vmap_axis + (0 if split_axis < vmap_axis else 1)\n+ split_axis = pmap_axis + 1 # split_axes == 1\n+\n+ # Step 2.\n+ # Now, we move pmap_axis to the position indicated by concat_axis.\n+ concat_axis = adj(concat_axis, [pmap_axis, split_axis, vmap_axis]) - 1\n+ ref = jnp.moveaxis(ref, pmap_axis, concat_axis)\n+ pmap_axis = 0\n+ vmap_axis = vmap_axis - (1 if concat_axis >= vmap_axis else 0)\n+ del split_axis, concat_axis\n+\n+ # Step 3. vmap_axis always ends in position 1, since out_axes=0.\n+ ref = jnp.moveaxis(ref, vmap_axis, 1)\n+ return ref\n+\n+ def verify_ref():\n+ # Both the reference and the real implementation of all_to_all batching involve\n+ # some pretty complicated axis arithmetic, so it would be good to verify that it's\n+ # not the case that the test passes because they're both incorrect. Fortunately, it\n+ # is quite easy to write out the shape function for this code, and we know\n+ # that it should be equivalent to a bunch of transposes, so the code below verifies\n+ # that the reference puts the right dimensions in the right places. Note that we\n+ # can't do the same comparison on f, since all_to_all wouldn't allow us to swap axes of\n+ # different sizes.\n+ start_shape = [2, 3, 4, 5, 6]\n+ instance_shape = start_shape.copy()\n+ pmap_dim_id = instance_shape.pop(0)\n+ vmap_dim_id = instance_shape.pop(vmap_axis)\n+ split_axis_id = instance_shape.pop(split_axis)\n+ instance_shape.insert(concat_axis, pmap_dim_id)\n+ expected_shape = (split_axis_id, vmap_dim_id, *instance_shape)\n+\n+ x = np.empty(start_shape)\n+ self.assertEqual(reference(x, split_axis, concat_axis, vmap_axis).shape,\n+ expected_shape)\n+\n+ verify_ref()\n+\n+ shape = (jax.device_count(),) * 5\n+ x = jnp.arange(np.prod(shape)).reshape(shape)\n+ self.assertAllClose(pmap(vmap(f, in_axes=vmap_axis), axis_name='i')(x),\n+ reference(x, split_axis, concat_axis, vmap_axis))\n+\nclass PmapWithDevicesTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Allow vmapping all_to_all and implement a (slow) CPU and GPU translation
This allows pmapping vmapped computations that use `all_to_all` or
`pswapaxes` inside. It also includes a very slow CPU and GPU translation
rule that might be useful for debugging programs locally, since XLA only
implements the `AllToAll` collective on TPUs.
Fixes #4141. |
260,411 | 25.09.2020 15:28:23 | -10,800 | f46a42206c0917d4da5f040f273aa0fefef050bd | [host_callback] improved logging, and add instructions for debugging | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -56,7 +56,8 @@ which eventually pauses the computation on devices. The runtime has one\nadditional thread that invokes the Python user functions with the received data.\nIf the processing of the callbacks is slow, it may actually lead to the runtime\nbuffer filling up, and eventually pausing the computation on the devices\n-when they need to send something. For more details on the runtime mechanism see\n+when they need to send something. For more details on the outfeed receiver\n+runtime mechanism see\n`runtime code\n<https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/python/outfeed_receiver.cc>`_.\n@@ -136,6 +137,34 @@ Still to do:\n* Explore an extended API that allows the host function to return\nvalues to the accelerator computation.\n+\n+Low-level details and debugging\n+-------------------------------\n+\n+The C++ `receiver\n+<https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/python/outfeed_receiver.cc>`_\n+is started automatically on the first call to :func:`id_tap`. In order to stop\n+it properly, upon start an ``atexit`` handler is registered to call\n+:func:`barrier_wait` with the logging name \"at_exit\".\n+\n+\n+There are a few environment variables that you can use to turn on logging\n+for the C++ outfeed `receiver backend\n+<https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/python/outfeed_receiver.cc>`_.\n+\n+ * ``TF_CPP_MIN_LOG_LEVEL=0``: will turn on INFO logging, needed for all below.\n+ * ``TF_CPP_MIN_VLOG_LEVEL=3``: will turn make all VLOG logging up to level 3\n+ behave like INFO logs. This may be too much, but you will see which\n+ modules are logging relevant info, and then you can select which modules\n+ to log from:\n+ * `TF_CPP_VMODULE=<module_name>=3``\n+\n+You should also use the ``--verbosity=2`` flag so that you see the logs from Python.\n+\n+For example:\n+```\n+TF_CPP_MIN_LOG_LEVEL=0 TF_CPP_VMODULE=outfeed_receiver=3,host_callback=3,outfeed_receiver_py=3,outfeed_thunk=3,cpu_transfer_manager=3,xfeed_manager=3,pjrt_client=3 python tests/host_callback_test.py --verbosity=2 HostCallbackTest.test_jit_simple\n+```\n\"\"\"\nfrom absl import logging\nimport atexit\n@@ -833,7 +862,7 @@ def outfeed_receiver():\nyield\nfinally:\n# We put a barrier, which will also raise the TapFunctionException\n- barrier_wait()\n+ barrier_wait(\"outfeed_receiver_stop\")\n# For now we keep a single outfeed receiver\n@@ -933,13 +962,12 @@ def _initialize_outfeed_receiver(\ndef exit_handler():\n# Prevent logging usage during compilation, gives errors under pytest\nxla._on_exit = True\n- logging.vlog(2, \"Barrier wait atexit\")\n- barrier_wait()\n+ barrier_wait(\"at_exit\")\natexit.register(exit_handler) # We wait as long as we have callbacks\n-def barrier_wait():\n+def barrier_wait(logging_name: Optional[str] = None):\n\"\"\"Blocks the calling thread until all current outfeed is processed.\nWaits until all outfeed from computations already running on all devices\n@@ -952,10 +980,15 @@ def barrier_wait():\nNote: If any of the devices are busy and cannot accept new computations,\nthis will deadlock.\n+\n+ Args:\n+ logging_name: an optional string that will be used in the logging statements\n+ for this invocation. See `Debugging` in the module documentation.\n\"\"\"\n- logging.vlog(2, \"barrier_wait: start\")\n+ logging_name = logging_name or \"\"\n+ logging.vlog(2, f\"barrier_wait[{logging_name}]: start\")\nif not _outfeed_receiver.receiver:\n- logging.vlog(2, \"barrier_wait: receiver not started\")\n+ logging.vlog(2, f\"barrier_wait[{logging_name}]: receiver not started\")\nreturn\nlock = threading.Lock()\n@@ -965,20 +998,21 @@ def barrier_wait():\ndef barrier_tap(dev_idx, _):\nnonlocal num_at_large\nlogging.vlog(\n- 2, f\"barrier_wait: thread {threading.current_thread()} for \"\n- f\"device {_outfeed_receiver.devices[dev_idx]} at barrier_tap\")\n+ 2, f\"barrier_wait[{logging_name}]: at barrier_tap for device {_outfeed_receiver.devices[dev_idx]} \"\n+ f\". Thread {threading.current_thread()}\")\nwith lock:\nnum_at_large -= 1\n+ logging.vlog(2, f\"barrier_wait[{logging_name}]: still waiting for {num_at_large} barrier_tap\")\ncv.notify()\nfor d_idx, d in enumerate(_outfeed_receiver.devices):\n- logging.vlog(2, f\"barrier_wait: enqueueing barrier on device {d}\")\n+ logging.vlog(2, f\"barrier_wait[{logging_name}]: enqueueing barrier on device {d}\")\nx_on_dev = api.device_put(d_idx, device=d)\napi.jit(lambda x: id_tap(barrier_tap, x), device=d)(x_on_dev)\n- logging.vlog(2, \"barrier_wait: waiting for calblacks\")\n+ logging.vlog(2, f\"barrier_wait[{logging_name}]: waiting for callbacks\")\nwith lock:\ncv.wait_for(lambda: num_at_large == 0)\n- logging.vlog(2, \"Done barrier_wait\")\n+ logging.vlog(2, f\"barrier_wait[{logging_name}]: done\")\nif _outfeed_receiver.num_tap_exceptions > 0:\n_outfeed_receiver.num_tap_exceptions = 0\nraise TapFunctionException(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -114,7 +114,7 @@ class HostCallbackTest(jtu.JaxTestCase):\nif os.getenv(\"XLA_FLAGS\") != self.old_flags:\nos.environ[\"XLA_FLAGS\"] = self.old_flags\nxla_bridge.get_backend.cache_clear()\n- hcb.barrier_wait()\n+ hcb.barrier_wait(\"HostCallbackTest.tearDown\")\ndef helper_set_devices(self, nr_devices):\nflags_str = os.getenv(\"XLA_FLAGS\", \"\")\n"
}
] | Python | Apache License 2.0 | google/jax | [host_callback] improved logging, and add instructions for debugging |
260,335 | 25.09.2020 11:50:32 | 25,200 | 90b272aa88baa90ecbd89734eb5309f8d58eac2d | add author line, fix typo | [
{
"change_type": "MODIFY",
"old_path": "design_notes/omnistaging.md",
"new_path": "design_notes/omnistaging.md",
"diff": "# Omnistaging\n+_mattjj@_\n+_Sept 25 2020_\nThis is more of an upgrade guide than a design doc.\n@@ -6,7 +8,7 @@ This is more of an upgrade guide than a design doc.\n* [tl;dr](#tldr)\n* [What is \"omnistaging\" and why is it useful?](what-is-omnistaging-and-why-is-it-useful)\n-* [What issues can arise when omnistaging is siwtched on?](what-issues-can-arise-when-omnistaging-is-siwtched-on)\n+* [What issues can arise when omnistaging is switched on?](what-issues-can-arise-when-omnistaging-is-switched-on)\n## tl;dr\n"
}
] | Python | Apache License 2.0 | google/jax | add author line, fix typo |
260,335 | 25.09.2020 12:10:03 | 25,200 | be6e85a176ed4cb180c96082a2a779f85bf25e65 | fix links in omnistaging doc (hopefully...) | [
{
"change_type": "MODIFY",
"old_path": "design_notes/omnistaging.md",
"new_path": "design_notes/omnistaging.md",
"diff": "@@ -7,8 +7,13 @@ This is more of an upgrade guide than a design doc.\n### Contents\n* [tl;dr](#tldr)\n-* [What is \"omnistaging\" and why is it useful?](what-is-omnistaging-and-why-is-it-useful)\n-* [What issues can arise when omnistaging is switched on?](what-issues-can-arise-when-omnistaging-is-switched-on)\n+* [What is \"omnistaging\" and why is it useful?](#what-is-omnistaging-and-why-is-it-useful)\n+* [What issues can arise when omnistaging is switched on?](#what-issues-can-arise-when-omnistaging-is-switched-on)\n+ * [Using `jax.numpy` for shape computations](#using-jaxnumpy-for-shape-computations)\n+ * [Side-effects](#side-effects)\n+ * [Small numerical differences based on XLA optimizations](#small-numerical-differences-based-on-xla-optimizations)\n+ * [Dependence on JAX internal APIs that changed](#dependence-on-jax-internal-apis-that-changed)\n+ * [Triggering XLA compile time bugs](#triggering-xla-compile-time-bugs)\n## tl;dr\n"
}
] | Python | Apache License 2.0 | google/jax | fix links in omnistaging doc (hopefully...) |
260,335 | 25.09.2020 15:35:44 | 25,200 | 61fcea93e52976d94899461d217070b1db59efde | tweak error to mention *flattened* positions | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -805,7 +805,7 @@ class DynamicJaxprTracer(core.Tracer):\norigin = (f\"While tracing the function {self._trace.main.source_info}, \"\n\"this concrete value was not available in Python because it \"\n\"depends on the value of the arguments to \"\n- f\"{self._trace.main.source_info} at positions {invar_pos}, \"\n+ f\"{self._trace.main.source_info} at flattened positions {invar_pos}, \"\n\"and the computation of these values is being staged out \"\n\"(that is, delayed rather than executed eagerly).\\n\\n\"\n\"You can use transformation parameters such as `static_argnums` \"\n"
}
] | Python | Apache License 2.0 | google/jax | tweak error to mention *flattened* positions |
260,287 | 22.09.2020 11:19:06 | 0 | fa38f250e314346d6d47586c99dd4fffb1b1daba | Add support for all_to_all over vmapped axes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -612,6 +612,17 @@ def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_axis, concat_axis)\nresult = all_to_all_p.bind(x, axis_name=axis_name, split_axis=split_axis, concat_axis=concat_axis)\nreturn result, d\n+def _all_to_all_batched_collective(vals_in, dims_in, axis_size, axis_name, split_axis, concat_axis):\n+ x, = vals_in\n+ d, = dims_in\n+ split_axis_adj = split_axis + (1 if d <= split_axis else 0)\n+ concat_axis_adj = concat_axis + (1 if split_axis_adj <= concat_axis else 0)\n+ if d < split_axis_adj < concat_axis_adj:\n+ split_axis_adj -= 1\n+ elif concat_axis_adj < split_axis_adj < d:\n+ split_axis_adj += 1\n+ return [_moveaxis(d, concat_axis_adj, x)], [split_axis_adj]\n+\ndef _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis):\ninput_aval = raise_to_shaped(x)\nshape = list(input_aval.shape)\n@@ -625,6 +636,7 @@ xla.parallel_translations[all_to_all_p] = _all_to_all_translation_rule\nad.deflinear(all_to_all_p, _all_to_all_transpose_rule)\npxla.multi_host_supported_collectives.add(all_to_all_p)\nbatching.primitive_batchers[all_to_all_p] = _all_to_all_batcher\n+batching.collective_rules[all_to_all_p] = _all_to_all_batched_collective\ndef _expand(dim, size, index, x):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "# limitations under the License.\n+import itertools as it\nimport numpy as np\nfrom unittest import skipIf\nfrom absl.testing import absltest\n@@ -20,6 +21,7 @@ from absl.testing import parameterized\nimport jax\nimport jax.numpy as jnp\n+from jax.interpreters import batching\nfrom jax import test_util as jtu\nfrom jax import lax\nfrom jax import lax_linalg\n@@ -1018,6 +1020,30 @@ class BatchingTest(jtu.JaxTestCase):\nvmap(lambda x: x - lax.ppermute(x, 'i', perm_pairs), axis_name='i')(x),\nx - x[perm])\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_split={split_axis}_concat={concat_axis}_vmap={vmap_axis}\",\n+ \"split_axis\": split_axis, \"concat_axis\": concat_axis, \"vmap_axis\": vmap_axis}\n+ for split_axis, concat_axis, vmap_axis in it.product(range(3), range(3), range(4)))\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testAllToAll(self, vmap_axis, split_axis, concat_axis):\n+ d = vmap_axis\n+\n+ def shape_fun(x, out_d):\n+ shape = list(x.shape)\n+ vmap_dim_id = shape.pop(d)\n+ split_dim_id = shape.pop(split_axis)\n+ shape.insert(concat_axis, vmap_dim_id)\n+ shape.insert(out_d, split_dim_id)\n+ return tuple(shape)\n+\n+ shape = (2, 3, 4, 5)\n+ x = np.arange(np.prod(shape)).reshape(shape)\n+ rule = batching.collective_rules[lax.all_to_all_p]\n+ (y,), (out_d,) = rule((x,), (d,), None, None, split_axis, concat_axis)\n+ exp_shape = shape_fun(x, out_d)\n+ self.assertEqual(y.shape, exp_shape)\n+\ndef testNegativeAxes(self):\nx = np.arange(3*4*5).reshape(3, 4, 5)\nself.assertAllClose(jax.vmap(jnp.sum, in_axes=-3)(x),\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -1704,6 +1704,22 @@ class VmapOfPmapTest(jtu.JaxTestCase):\nself.assertAllClose(pmap(vmap(f, in_axes=vmap_axis), axis_name='i')(x),\nreference(x, split_axis, concat_axis, vmap_axis))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_split={split_axis}_concat={concat_axis}\",\n+ \"split_axis\": split_axis, \"concat_axis\": concat_axis}\n+ for split_axis, concat_axis in it.product(range(3), range(3)))\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ @ignore_slow_all_to_all_warning()\n+ def testAllToAllVsVmap(self, split_axis, concat_axis):\n+ def f(x):\n+ return lax.all_to_all(x, 'i', split_axis=split_axis, concat_axis=concat_axis)\n+\n+ shape = (jax.device_count(),) * 4\n+ x = jnp.arange(np.prod(shape)).reshape(shape)\n+ self.assertAllClose(pmap(f, axis_name='i')(x),\n+ vmap(f, axis_name='i')(x))\n+\nclass PmapWithDevicesTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Add support for all_to_all over vmapped axes |
260,287 | 22.09.2020 13:05:08 | 0 | e61ca913606bbb8a92c57ef49852bd736c064558 | Implement split_axis for all_to_all
This allows us to use `all_to_all` over a mix of vmapped and pmapped
dimensions, which will be useful for `gmap`. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -964,6 +964,7 @@ def _pmap_translation_rule(c, axis_env,\n_xla_shard(c, aval, new_env, in_node) if in_node_mapped else in_node\nfor aval, in_node, in_node_mapped in zip(in_avals, in_nodes, mapped_invars))\n+ with maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\nsharded_outs = xla.jaxpr_subcomp(\nc, call_jaxpr, backend, new_env, (),\nextend_name_stack(name_stack, wrap_name(name, 'pmap')), *in_nodes_sharded)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -623,6 +623,39 @@ def _all_to_all_batched_collective(vals_in, dims_in, axis_size, axis_name, split\nsplit_axis_adj += 1\nreturn [_moveaxis(d, concat_axis_adj, x)], [split_axis_adj]\n+def _all_to_all_split_axis_rule(split_name, vals, params):\n+ concat_axis = params['concat_axis']\n+ split_axis = params['split_axis']\n+ axis_names = params['axis_name']\n+ assert isinstance(axis_names, tuple)\n+ x, = vals\n+\n+ split_pos = list(axis_names).index(split_name)\n+ before_axes = axis_names[:split_pos]\n+ after_axes = axis_names[split_pos+1:]\n+\n+ # Flatten the split_dim\n+ split_name_size = psum(1, split_name)\n+ before_size = psum(1, before_axes)\n+ after_size = psum(1, after_axes)\n+ unroll_shape = list(x.shape)\n+ unroll_shape[split_axis:split_axis+1] = [before_size, split_name_size, after_size]\n+ unroll_x = lax.reshape(x, unroll_shape)\n+\n+ if before_axes:\n+ out_before = all_to_all(unroll_x, before_axes, split_axis, concat_axis=0)\n+ else:\n+ out_before = _moveaxis(split_axis, 0, unroll_x)\n+ out_split = all_to_all(out_before, split_name, split_axis + 1, concat_axis=1)\n+ if after_axes:\n+ out_after = all_to_all(out_split, after_axes, split_axis + 2, concat_axis=2)\n+ else:\n+ out_after = _moveaxis(split_axis + 2, 2, out_split)\n+\n+ # Flatten the concat axes and move them to the right position\n+ y = out_after.reshape((np.prod(out_after.shape[:3]), *out_after.shape[3:]))\n+ return _moveaxis(0, concat_axis, y)\n+\ndef _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis):\ninput_aval = raise_to_shaped(x)\nshape = list(input_aval.shape)\n@@ -637,6 +670,7 @@ ad.deflinear(all_to_all_p, _all_to_all_transpose_rule)\npxla.multi_host_supported_collectives.add(all_to_all_p)\nbatching.primitive_batchers[all_to_all_p] = _all_to_all_batcher\nbatching.collective_rules[all_to_all_p] = _all_to_all_batched_collective\n+batching.split_axis_rules[all_to_all_p] = _all_to_all_split_axis_rule\ndef _expand(dim, size, index, x):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -1044,6 +1044,34 @@ class BatchingTest(jtu.JaxTestCase):\nexp_shape = shape_fun(x, out_d)\nself.assertEqual(y.shape, exp_shape)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_split={split_axis}_concat={concat_axis}_vmap={vmap_axis}\",\n+ \"split_axis\": split_axis, \"concat_axis\": concat_axis, \"vmap_axis\": vmap_axis}\n+ for split_axis, concat_axis, vmap_axis in it.product(range(2), range(2), range(3)))\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testAllToAllSplitAxis(self, vmap_axis, split_axis, concat_axis):\n+ shape = (4, 4, 4)\n+ x = np.arange(np.prod(shape)).reshape(shape)\n+\n+ @partial(vmap, in_axes=vmap_axis, axis_name='i')\n+ @partial(vmap, in_axes=vmap_axis, axis_name='j')\n+ def f(x):\n+ return lax.all_to_all(x, ('i', 'j'), split_axis, concat_axis)\n+\n+ unroll_shape = (2, 2, *shape[1:])\n+ unroll_shape = list(shape)\n+ unroll_shape[vmap_axis:vmap_axis+1] = (2, 2)\n+ x_unroll = x.reshape(unroll_shape)\n+ y_unrolled = f(x_unroll)\n+ y = y_unrolled.reshape(shape)\n+\n+ if vmap_axis <= split_axis:\n+ split_axis += 1\n+ ref = jnp.moveaxis(x, (vmap_axis, split_axis),\n+ (concat_axis + 1, 0))\n+ self.assertAllClose(y, ref)\n+\ndef testNegativeAxes(self):\nx = np.arange(3*4*5).reshape(3, 4, 5)\nself.assertAllClose(jax.vmap(jnp.sum, in_axes=-3)(x),\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -1720,6 +1720,26 @@ class VmapOfPmapTest(jtu.JaxTestCase):\nself.assertAllClose(pmap(f, axis_name='i')(x),\nvmap(f, axis_name='i')(x))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_split={split_axis}_concat={concat_axis}_axes={''.join(axes)}\",\n+ \"axes\": axes, \"split_axis\": split_axis, \"concat_axis\": concat_axis}\n+ for axes, split_axis, concat_axis\n+ in it.product([('i', 'j'), ('j', 'i')], range(3), range(3)))\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ @ignore_slow_all_to_all_warning()\n+ def testAllToAllMultipleAxesVsVmap(self, axes, split_axis, concat_axis):\n+ if xla_bridge.device_count() < 4:\n+ raise SkipTest(\"test requires at least four devices\")\n+\n+ def f(x):\n+ return lax.all_to_all(x, axes, split_axis=split_axis, concat_axis=concat_axis)\n+\n+ shape = (2, 2, 4, 4, 4)\n+ x = jnp.arange(np.prod(shape)).reshape(shape)\n+ self.assertAllClose(pmap(pmap(f, axis_name='j'), axis_name='i')(x),\n+ vmap(vmap(f, axis_name='j'), axis_name='i')(x))\n+\nclass PmapWithDevicesTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Implement split_axis for all_to_all
This allows us to use `all_to_all` over a mix of vmapped and pmapped
dimensions, which will be useful for `gmap`. |
260,424 | 01.10.2020 13:07:33 | -3,600 | cc0114a0a9dc330f5cf6e2f9318e593482eff43f | Fix dtype behavior with float0s in CustomVJP. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1594,5 +1594,7 @@ def omnistaging_disabler() -> None:\ntrace_state.initial_style = prev\n# Casting float0 array to a float-valued zero array.\n-def zeros_like_float0(array):\n- return np.zeros(array.shape, np.float)\n+def zeros_like_float0(array, dtype=None):\n+ if not dtype:\n+ dtype = np.float\n+ return np.zeros(array.shape, dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -303,8 +303,9 @@ class JVPTrace(Trace):\ntangents_in = map(instantiate_zeros, tangents_in)\n# Cast float0 to regular float zeros because custom jvp rules don't\n# currently handle float0s\n- tangents_in = [core.zeros_like_float0(tangent) if dtype(tangent) is float0\n- else tangent for tangent in tangents_in]\n+ tangents_in = [core.zeros_like_float0(tangent, dtype(primal))\n+ if dtype(tangent) is float0 else tangent\n+ for primal, tangent in zip(primals_in, tangents_in)]\nouts = f_jvp.call_wrapped(*it.chain(primals_in, tangents_in))\nprimals_out, tangents_out = split_list(outs, [len(outs) // 2])\nreturn map(partial(JVPTracer, self), primals_out, tangents_out)\n@@ -314,8 +315,9 @@ class JVPTrace(Trace):\ntangents_in = map(instantiate_zeros, tangents_in)\n# Cast float0 to regular float zeros because custom vjp rules don't\n# currently handle float0s\n- tangents_in = [core.zeros_like_float0(tangent) if dtype(tangent) is float0\n- else tangent for tangent in tangents_in]\n+ tangents_in = [core.zeros_like_float0(tangent, dtype(primal))\n+ if dtype(tangent) is float0 else tangent\n+ for primal, tangent in zip(primals_in, tangents_in)]\nres_and_primals_out = fwd.call_wrapped(*map(core.full_lower, primals_in))\nout_tree, res_tree = out_trees()\nres, primals_out = split_list(res_and_primals_out, [res_tree.num_leaves])\n"
}
] | Python | Apache License 2.0 | google/jax | Fix dtype behavior with float0s in CustomVJP. |
260,639 | 21.09.2020 16:59:46 | 14,400 | 0893b08a6fa71108992aea564beb6cbabfd5fce7 | histogramdd implemenation | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -176,6 +176,7 @@ Not every function in NumPy is implemented; contributions are welcome!\nheaviside\nhistogram\nhistogram_bin_edges\n+ histogramdd\nhsplit\nhstack\nhypot\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -36,7 +36,7 @@ from .lax_numpy import (\nfabs, finfo, fix, flatnonzero, flexible, flip, fliplr, flipud, float16, float32,\nfloat64, float_, float_power, floating, floor, floor_divide, fmax, fmin,\nfmod, frexp, full, full_like, function, gcd, geomspace, gradient, greater,\n- greater_equal, hamming, hanning, heaviside, histogram, histogram_bin_edges,\n+ greater_equal, hamming, hanning, heaviside, histogram, histogram_bin_edges, histogramdd,\nhsplit, hstack, hypot, i0, identity, iinfo, imag,\nindices, inexact, in1d, inf, inner, int16, int32, int64, int8, int_, integer,\ninterp, intersect1d, invert,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -897,6 +897,44 @@ def histogram(a, bins=10, range=None, weights=None, density=None):\ncounts = counts / bin_widths / counts.sum()\nreturn counts, bin_edges\n+@_wraps(np.histogramdd)\n+def histogramdd(sample, bins=10, range=None, weights=None, density=None):\n+ _check_arraylike(\"histogramdd\", sample)\n+ N, D = shape(sample)\n+\n+ if weights is not None and weights.shape != (N,):\n+ raise ValueError(\"should have one weight for each sample.\")\n+\n+ bin_idx_by_dim = D*[None]\n+ nbins = np.empty(D, int)\n+ bin_edges_by_dim = D*[None]\n+ dedges = D*[None]\n+\n+ for i in builtins.range(D):\n+ bin_edges = histogram_bin_edges(sample[:, i], bins[i], range, weights)\n+ bin_idx = searchsorted(bin_edges, sample[:, i], side='right')\n+ bin_idx = where(sample[:, i] == bin_edges[-1], bin_idx - 1, bin_idx)\n+ bin_idx_by_dim[i] = bin_idx\n+ nbins[i] = len(bin_edges) + 1\n+ bin_edges_by_dim[i] = bin_edges\n+ dedges[i] = diff(bin_edges_by_dim[i])\n+\n+ xy = ravel_multi_index(bin_idx_by_dim, nbins, mode='clip')\n+ hist = bincount(xy, weights, length=nbins.prod())\n+ hist = reshape(hist, nbins)\n+ core = D*(slice(1, -1),)\n+ hist = hist[core]\n+\n+ if density:\n+ s = sum(hist)\n+ for i in builtins.range(D):\n+ _shape = np.ones(D, int)\n+ _shape[i] = nbins[i] - 2\n+ hist = hist / reshape(dedges[i], _shape)\n+\n+ hist /= s\n+\n+ return hist, bin_edges_by_dim\n@_wraps(np.heaviside)\ndef heaviside(x1, x2):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -2277,7 +2277,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n}\nfor shape in [(5,), (5, 5)]\nfor dtype in default_dtypes\n- # We only test explicit integer-valued bin edges beause in other cases\n+ # We only test explicit integer-valued bin edges because in other cases\n# rounding errors lead to flaky tests.\nfor bins in [np.arange(-5, 6), [-5, 0, 3]]\nfor density in [True, False]\n@@ -2299,6 +2299,37 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ntol=tol)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_bins={}_weights={}_density={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), bins, weights, density),\n+ \"shape\": shape,\n+ \"dtype\": dtype,\n+ \"bins\": bins,\n+ \"weights\": weights,\n+ \"density\": density\n+ }\n+ for shape in [(5, 3), (10, 3)]\n+ for dtype in int_dtypes\n+ # We only test explicit integer-valued bin edges because in other cases\n+ # rounding errors lead to flaky tests.\n+ for bins in [(2, 2, 2), [[-5, 0, 4], [-4, -1, 2], [-6, -1, 4]]]\n+ for weights in [False, True]\n+ for density in [False, True]\n+ ))\n+ def testHistogramdd(self, shape, dtype, bins, weights, density):\n+ rng = jtu.rand_default(self.rng())\n+ _weights = lambda w: abs(w) if weights else None\n+ np_fun = lambda a, w: np.histogramdd(a, bins=bins, weights=_weights(w), density=density)\n+ jnp_fun = lambda a, w: jnp.histogramdd(a, bins=bins, weights=_weights(w), density=density)\n+ args_maker = lambda: [rng(shape, dtype), rng((shape[0],), dtype)]\n+ tol = {jnp.bfloat16: 2E-2, np.float16: 1E-1}\n+ # np.searchsorted errors on bfloat16 with\n+ # \"TypeError: invalid type promotion with custom data type\"\n+ if dtype != jnp.bfloat16:\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False,\n+ tol=tol)\n+ self._CompileAndCheck(jnp_fun, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_axis={}_{}sections\".format(\njtu.format_shape_dtype_string(shape, dtype), axis, num_sections),\n@@ -4331,6 +4362,7 @@ class NumpySignaturesTest(jtu.JaxTestCase):\n'full_like': ['shape', 'subok', 'order'],\n'gradient': ['varargs', 'axis', 'edge_order'],\n'histogram': ['normed'],\n+ 'histogramdd': ['normed'],\n'isneginf': ['out'],\n'isposinf': ['out'],\n'max': ['initial', 'where'],\n"
}
] | Python | Apache License 2.0 | google/jax | histogramdd implemenation |
260,325 | 05.10.2020 10:19:18 | 25,200 | b357005e60440657321737b1465f3b900a2c9b8c | Update Common_Gotchas_in_JAX.ipynb
Clarify that the index is clamped to the bounds of the array when accessing out of bounds. | [
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb",
"new_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb",
"diff": "\"id\": \"eoXrGARWypdR\"\n},\n\"source\": [\n- \"However, raising an error on other accelerators can be more difficult. Therefore, JAX does not raise an error and instead returns the last value in the array. \"\n+ \"However, raising an error on other accelerators can be more difficult. Therefore, JAX does not raise an error, instead the index is clamped to the bounds of the array, meaning that for this example the last value of the array will be returned. \"\n]\n},\n{\n"
}
] | Python | Apache License 2.0 | google/jax | Update Common_Gotchas_in_JAX.ipynb
Clarify that the index is clamped to the bounds of the array when accessing out of bounds. |
260,411 | 07.10.2020 11:14:35 | -10,800 | ae7e5b99d6e12d7410564c429fb423126f810dbd | Another attempt to save the notebook | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/JAX2TF_getting_started.ipynb",
"new_path": "jax/experimental/jax2tf/JAX2TF_getting_started.ipynb",
"diff": "\"output_type\": \"stream\",\n\"text\": [\n\"Execute with TF eager: hello_tf(x) = -0.44657254219055176\\n\",\n+ \"WARNING:tensorflow:@custom_gradient grad_fn has 'variables' in signature, but no ResourceVariables were used on the forward pass.\\n\"\n],\n\"name\": \"stdout\"\n},\n{\n\"output_type\": \"stream\",\n\"text\": [\n+ \"WARNING:tensorflow:@custom_gradient grad_fn has 'variables' in signature, but no ResourceVariables were used on the forward pass.\\n\"\n],\n\"name\": \"stderr\"\n},\n\"output_type\": \"stream\",\n\"text\": [\n\"Execute with TF graph: hello_tf_graph(x) = -0.44657254219055176\\n\",\n+ \"WARNING:tensorflow:@custom_gradient grad_fn has 'variables' in signature, but no ResourceVariables were used on the forward pass.\\n\"\n],\n\"name\": \"stdout\"\n},\n{\n\"output_type\": \"stream\",\n\"text\": [\n+ \"WARNING:tensorflow:@custom_gradient grad_fn has 'variables' in signature, but no ResourceVariables were used on the forward pass.\\n\"\n],\n\"name\": \"stderr\"\n},\n{\n\"output_type\": \"stream\",\n\"text\": [\n+ \"WARNING:tensorflow:@custom_gradient grad_fn has 'variables' in signature, but no ResourceVariables were used on the forward pass.\\n\"\n],\n\"name\": \"stdout\"\n},\n{\n\"output_type\": \"stream\",\n\"text\": [\n+ \"WARNING:tensorflow:@custom_gradient grad_fn has 'variables' in signature, but no ResourceVariables were used on the forward pass.\\n\"\n],\n\"name\": \"stderr\"\n},\n"
}
] | Python | Apache License 2.0 | google/jax | Another attempt to save the notebook |
260,411 | 08.10.2020 12:28:42 | -10,800 | dc9168ba93764a6f282dd33c376e8dd84da7d8db | [jax2tf] Ensure that in tests TF does not constant-fold in eager mode before compiling | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"new_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"diff": "@@ -33,15 +33,15 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\ndef f_jax(pred, x):\nreturn lax.cond(pred, lambda t: t + 1., lambda f: f, x)\n- self.ConvertAndCompare(f_jax, True, jnp.float_(1.))\n- self.ConvertAndCompare(f_jax, False, jnp.float_(1.))\n+ self.ConvertAndCompare(f_jax, jnp.bool_(True), jnp.float_(1.))\n+ self.ConvertAndCompare(f_jax, jnp.bool_(False), jnp.float_(1.))\ndef test_cond_multiple_results(self):\ndef f_jax(pred, x):\nreturn lax.cond(pred, lambda t: (t + 1., 1.), lambda f: (f + 2., 2.), x)\n- self.ConvertAndCompare(f_jax, True, jnp.float_(1.))\n- self.ConvertAndCompare(f_jax, False, jnp.float_(1.))\n+ self.ConvertAndCompare(f_jax, jnp.bool_(True), jnp.float_(1.))\n+ self.ConvertAndCompare(f_jax, jnp.bool_(False), jnp.float_(1.))\ndef test_cond_partial_eval(self):\ndef f(x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"new_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"diff": "@@ -16,7 +16,7 @@ import atexit\nimport contextlib\nimport logging\nimport numpy as np\n-from typing import Any, Callable, Optional, Tuple\n+from typing import Any, Callable, List, Optional, Tuple\nimport tensorflow as tf # type: ignore[import]\nimport jax\n@@ -126,16 +126,28 @@ class JaxToTfTestCase(jtu.JaxTestCase):\njax2tf.jax2tf.to_tf_dtype(v.dtype))\nreturn v\n- tf_args = tuple(map(convert_if_bfloat16, args))\n+ tf_args = tf.nest.map_structure(convert_if_bfloat16, args)\n+\n+ def make_input_signature(*tf_args) -> List[tf.TensorSpec]:\n+ # tf_args can be PyTrees\n+ def make_one_arg_signature(tf_arg):\n+ return tf.TensorSpec(np.shape(tf_arg), tf_arg.dtype)\n+ return tf.nest.map_structure(make_one_arg_signature, list(tf_args))\ndef run_tf(mode):\nif mode == \"eager\":\nreturn func_tf(*tf_args)\nelif mode == \"graph\":\n- return tf.function(func_tf, autograph=False)(*tf_args)\n+ return tf.function(\n+ func_tf, autograph=False,\n+ input_signature=make_input_signature(*tf_args))(*tf_args)\nelif mode == \"compiled\":\n- return tf.function(func_tf, autograph=False,\n- experimental_compile=True)(*tf_args)\n+ # Adding an explicit input_signature prevents TF from constant-folding\n+ # the computation eagerly before compilation\n+ return tf.function(\n+ func_tf, autograph=False,\n+ experimental_compile=True,\n+ input_signature=make_input_signature(*tf_args))(*tf_args)\nelse:\nassert False\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Ensure that in tests TF does not constant-fold in eager mode before compiling |
260,424 | 08.10.2020 15:36:05 | -3,600 | e3d622cc67edb9c0ea18c336798d3f29cbfeae90 | Recast int/bool tangents to float0 in custom_jvp/vjps
(also in the initial_style path). | [
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -306,8 +306,14 @@ custom_jvp_call_jaxpr_p.def_abstract_eval(_custom_jvp_call_jaxpr_abstract_eval)\ndef _custom_jvp_call_jaxpr_jvp(primals, tangents, *, fun_jaxpr, jvp_jaxpr_thunk):\njvp_jaxpr = jvp_jaxpr_thunk()\ntangents = map(ad.instantiate_zeros, tangents)\n+ # Cast float0 to zeros with the primal dtype because custom jvp rules don't\n+ # currently handle float0s\n+ tangents = ad.replace_float0s(primals, tangents)\nouts = core.jaxpr_as_fun(jvp_jaxpr)(*primals, *tangents)\n- return split_list(outs, [len(outs) // 2])\n+ primals_out, tangents_out = split_list(outs, [len(outs) // 2])\n+ tangents_out = ad.recast_to_float0(primals_out, tangents_out)\n+ return primals_out, tangents_out\n+\nad.primitive_jvps[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_jvp\ndef _custom_jvp_call_jaxpr_vmap(args, in_dims, *, fun_jaxpr, jvp_jaxpr_thunk):\n@@ -545,6 +551,9 @@ custom_vjp_call_jaxpr_p.def_abstract_eval(_custom_vjp_call_jaxpr_abstract_eval)\ndef _custom_vjp_call_jaxpr_jvp(primals, tangents, *, fun_jaxpr, fwd_jaxpr_thunk,\nbwd, out_trees):\ntangents = map(ad.instantiate_zeros, tangents)\n+ # Cast float0 to zeros with the primal dtype because custom vjp rules don't\n+ # currently handle float0s\n+ tangents = ad.replace_float0s(primals, tangents)\nfwd_jaxpr = fwd_jaxpr_thunk()\nout_tree, res_tree = out_trees()\nres_and_primals_out = core.jaxpr_as_fun(fwd_jaxpr)(*primals)\n@@ -552,7 +561,9 @@ def _custom_vjp_call_jaxpr_jvp(primals, tangents, *, fun_jaxpr, fwd_jaxpr_thunk,\navals_out = [raise_to_shaped(core.get_aval(x)) for x in primals_out]\ntangents_out = ad.custom_lin_p.bind(\n*res, *tangents, num_res=res_tree.num_leaves, bwd=bwd, avals_out=avals_out)\n+ tangents_out = ad.recast_to_float0(primals_out, tangents_out)\nreturn primals_out, tangents_out\n+\nad.primitive_jvps[custom_vjp_call_jaxpr_p] = _custom_vjp_call_jaxpr_jvp\ndef _custom_vjp_call_jaxpr_vmap(args, in_dims, *, fun_jaxpr, fwd_jaxpr_thunk,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -146,6 +146,17 @@ def unpair_pval(pval):\naval_1, aval_2 = aval\nreturn (aval_1, const_1), (aval_2, const_2)\n+def replace_float0s(primals, tangents):\n+ return [core.zeros_like_float0(tangent, dtype(primal))\n+ if dtype(tangent) is float0 else tangent\n+ for primal, tangent in zip(primals, tangents)]\n+\n+def recast_to_float0(primals, tangents):\n+ return [Zero(get_aval(primal).at_least_vspace())\n+ if core.primal_dtype_to_tangent_dtype(dtype(primal)) == float0\n+ else tangent\n+ for primal, tangent in zip(primals, tangents)]\n+\n# NOTE: The FIXMEs below are caused by primal/tangent mixups (type errors if you will)\ndef backward_pass(jaxpr: core.Jaxpr, consts, primals_in, cotangents_in):\nif all(type(ct) is Zero for ct in cotangents_in):\n@@ -301,23 +312,20 @@ class JVPTrace(Trace):\nprimals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers)\nprimals_in = map(core.full_lower, primals_in)\ntangents_in = map(instantiate_zeros, tangents_in)\n- # Cast float0 to regular float zeros because custom jvp rules don't\n+ # Cast float0 to zeros with the primal dtype because custom jvp rules don't\n# currently handle float0s\n- tangents_in = [core.zeros_like_float0(tangent, dtype(primal))\n- if dtype(tangent) is float0 else tangent\n- for primal, tangent in zip(primals_in, tangents_in)]\n+ tangents_in = replace_float0s(primals_in, tangents_in)\nouts = f_jvp.call_wrapped(*it.chain(primals_in, tangents_in))\nprimals_out, tangents_out = split_list(outs, [len(outs) // 2])\n+ tangents_out = recast_to_float0(primals_out, tangents_out)\nreturn map(partial(JVPTracer, self), primals_out, tangents_out)\ndef process_custom_vjp_call(self, _, __, fwd, bwd, tracers, *, out_trees):\nprimals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers)\ntangents_in = map(instantiate_zeros, tangents_in)\n- # Cast float0 to regular float zeros because custom vjp rules don't\n+ # Cast float0 to zeros with the primal dtype because custom vjp rules don't\n# currently handle float0s\n- tangents_in = [core.zeros_like_float0(tangent, dtype(primal))\n- if dtype(tangent) is float0 else tangent\n- for primal, tangent in zip(primals_in, tangents_in)]\n+ tangents_in = replace_float0s(primals_in, tangents_in)\nres_and_primals_out = fwd.call_wrapped(*map(core.full_lower, primals_in))\nout_tree, res_tree = out_trees()\nres, primals_out = split_list(res_and_primals_out, [res_tree.num_leaves])\n@@ -325,6 +333,7 @@ class JVPTrace(Trace):\ntangents_out = custom_lin_p.bind(\n*res, *tangents_in, num_res=res_tree.num_leaves, bwd=bwd,\navals_out=avals_out)\n+ tangents_out = recast_to_float0(primals_out, tangents_out)\nreturn map(partial(JVPTracer, self), primals_out, tangents_out)\ndef join(self, xt, yt):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1185,22 +1185,6 @@ class APITest(jtu.JaxTestCase):\ntangent, = fn_vjp(out)\nself.assertArraysEqual(tangent, np.zeros(shape=(4, 1), dtype=float0))\n- def test_custom_vjp_int(self):\n- @api.custom_vjp\n- def f(x):\n- return jnp.sin(x)\n- def f_fwd(x):\n- return f(x), jnp.cos(x)\n- def f_rev(cos_x, g):\n- return (2 * cos_x * g,)\n- f.defvjp(f_fwd, f_rev)\n-\n- x = 3\n- self.assertEqual(api.grad(f, allow_int=True)(x),\n- np.zeros(shape=(), dtype=float0))\n- self.assertEqual(api.value_and_grad(f, allow_int=True)(x),\n- (jnp.sin(x), np.zeros(shape=(), dtype=float0)))\n-\ndef test_jit_vjp_of_int(self):\nprimal, fn_vjp = api.vjp(lambda x, y: x+y, 2, 1)\ntangent_x, tangent_i = jax.jit(fn_vjp)(1)\n@@ -3112,6 +3096,40 @@ class CustomJVPTest(jtu.JaxTestCase):\nfor ans in results:\nself.assertAllClose(ans, expected)\n+ def test_float0(self):\n+ @api.custom_jvp\n+ def f(x, y):\n+ return x, y\n+ def f_jvp(primals, _):\n+ # we need a defined (non-float0) tangent to trigger the rule\n+ return primals, (2., 1)\n+ f.defjvp(f_jvp)\n+\n+ primals = (2., 3)\n+ tangents = (np.ones(()), np.zeros((), float0),)\n+ expected_tangents = (2., np.zeros((), float0))\n+ self.assertArraysEqual(api.jvp(f, primals, tangents),\n+ (primals, expected_tangents))\n+\n+ def test_float0_initial_style(self):\n+ @api.custom_jvp\n+ def f(x, y):\n+ return x, y\n+ def f_jvp(primals, _):\n+ x, y = primals\n+ return (x, y), (2., 1)\n+ f.defjvp(f_jvp)\n+\n+ def foo(x, y):\n+ out, _ = lax.scan(lambda c, _: (f(*c), None), (x, y), None, length=1)\n+ return out\n+\n+ primals = (2., 3)\n+ tangents = (np.ones(()), np.zeros((), float0),)\n+ expected_tangents = (2., np.zeros((), float0))\n+ self.assertArraysEqual(api.jvp(foo, primals, tangents),\n+ (primals, expected_tangents))\n+\nclass CustomVJPTest(jtu.JaxTestCase):\n@@ -3491,6 +3509,42 @@ class CustomVJPTest(jtu.JaxTestCase):\ny, = z(1.0)(3.0)\nself.assertAllClose(y, jnp.array(6.0))\n+ def test_float0(self):\n+ @api.custom_vjp\n+ def f(x, _):\n+ return x\n+ def f_fwd(x, _):\n+ # we need a defined (non-float0) tangent to trigger the rule\n+ return x, (2., 1)\n+ def f_rev(*_):\n+ return (2., 1)\n+ f.defvjp(f_fwd, f_rev)\n+\n+ x = 2.\n+ y = 3\n+ self.assertEqual(api.grad(f, allow_int=True, argnums=(0, 1))(x, y),\n+ (2., np.zeros(shape=(), dtype=float0)))\n+\n+ def test_float0_initial_style(self):\n+ @api.custom_vjp\n+ def f(x):\n+ return x\n+ def f_fwd(x):\n+ return x, (2., x)\n+ def f_rev(*_):\n+ return ((2., 1),)\n+ f.defvjp(f_fwd, f_rev)\n+\n+ def foo(x, y):\n+ out, _ = lax.scan(lambda c, _: (f(c), None), (x, y), None, length=1)\n+ return out[0]\n+\n+ x = 2.\n+ y = 3\n+ self.assertEqual(api.grad(foo, allow_int=True, argnums=(0, 1))(x, y),\n+ (2., np.zeros(shape=(), dtype=float0)))\n+\n+\nclass InvertibleADTest(jtu.JaxTestCase):\ndef test_invertible_basic(self):\n"
}
] | Python | Apache License 2.0 | google/jax | Recast int/bool tangents to float0 in custom_jvp/vjps
(also in the initial_style path). |
260,265 | 08.10.2020 12:12:15 | 25,200 | a2a9409a8ac5bd3e60dbb2f1e854304e0ce0e64b | Mark pmin and pmax as multi-host supported. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -491,6 +491,7 @@ pmax_p = core.Primitive('pmax')\npmax_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nxla.parallel_translations[pmax_p] = \\\npartial(_allreduce_translation_rule, lax.max_p)\n+pxla.multi_host_supported_collectives.add(pmax_p)\nbatching.split_axis_rules[pmax_p] = partial(_split_axis_comm_assoc, pmax_p)\nbatching.primitive_batchers[pmax_p] = partial(_collective_batcher, pmax_p)\nbatching.collective_rules[pmax_p] = \\\n@@ -504,6 +505,7 @@ pmin_p = core.Primitive('pmin')\npmin_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\nxla.parallel_translations[pmin_p] = \\\npartial(_allreduce_translation_rule, lax.min_p)\n+pxla.multi_host_supported_collectives.add(pmin_p)\nbatching.split_axis_rules[pmin_p] = partial(_split_axis_comm_assoc, pmin_p)\nbatching.primitive_batchers[pmin_p] = partial(_collective_batcher, pmin_p)\nbatching.collective_rules[pmin_p] = \\\n"
}
] | Python | Apache License 2.0 | google/jax | Mark pmin and pmax as multi-host supported. |
260,335 | 08.10.2020 13:00:32 | 25,200 | 09f2be15d29b6fc9c9df5808afca1ef399593e20 | wait for result in debug_nans_test | [
{
"change_type": "MODIFY",
"old_path": "tests/debug_nans_test.py",
"new_path": "tests/debug_nans_test.py",
"diff": "@@ -34,20 +34,24 @@ class DebugNaNsTest(jtu.JaxTestCase):\ndef testSingleResultPrimitiveNoNaN(self):\nA = jnp.array([[1., 2.], [2., 3.]])\n- _ = jnp.tanh(A)\n+ ans = jnp.tanh(A)\n+ ans.block_until_ready()\ndef testMultipleResultPrimitiveNoNaN(self):\nA = jnp.array([[1., 2.], [2., 3.]])\n- _, _ = jnp.linalg.eigh(A)\n+ ans, _ = jnp.linalg.eigh(A)\n+ ans.block_until_ready()\ndef testJitComputationNoNaN(self):\nA = jnp.array([[1., 2.], [2., 3.]])\n- _ = jax.jit(jnp.tanh)(A)\n+ ans = jax.jit(jnp.tanh)(A)\n+ ans.block_until_ready()\ndef testSingleResultPrimitiveNaN(self):\nA = jnp.array(0.)\nwith self.assertRaises(FloatingPointError):\n- _ = 0. / A\n+ ans = 0. / A\n+ ans.block_until_ready()\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | wait for result in debug_nans_test |
260,335 | 08.10.2020 13:34:56 | 25,200 | 24de811a392040bfe85a3fcc24a1ca3be715d4b0 | move a debug_nans test into debug_nans test file | [
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -399,20 +399,6 @@ class PythonJitTest(CPPJitTest):\njit_fun(a) # doesn't crash\n- def test_debug_nans(self):\n- @self.jit\n- def f(x):\n- return jnp.add(x, np.nan)\n- f(1)\n-\n- msg = r\"invalid value \\(nan\\) encountered in add\" # 'add' not 'xla_call'\n- FLAGS.jax_debug_nans = True\n- try:\n- with self.assertRaisesRegex(FloatingPointError, msg):\n- f(1)\n- finally:\n- FLAGS.jax_debug_nans = False\n-\nclass APITest(jtu.JaxTestCase):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/debug_nans_test.py",
"new_path": "tests/debug_nans_test.py",
"diff": "@@ -53,6 +53,15 @@ class DebugNaNsTest(jtu.JaxTestCase):\nans = 0. / A\nans.block_until_ready()\n+ def testCallDeoptimized(self):\n+ @jax.jit\n+ def f(x):\n+ return jnp.add(x, jnp.nan)\n+\n+ msg = r\"invalid value \\(nan\\) encountered in add\" # 'add' not 'xla_call'\n+ with self.assertRaisesRegex(FloatingPointError, msg):\n+ f(1)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | move a debug_nans test into debug_nans test file |
260,335 | 08.10.2020 15:36:42 | 25,200 | 55be9dd91bc4a1ce04d250d2d7500c6819bd2076 | remove mysterious code that is no longer needed | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -1566,10 +1566,6 @@ def _scan_partial_eval(trace, *tracers, reverse, length, num_consts, num_carry,\nlu.wrap_init(core.jaxpr_as_fun(jaxpr_1)), in_pvals_1,\ninstantiate=[True] * (num_carry + num_ys) + [False] * num_res)\n- # TODO(cjfj): Explain the need for the code below.\n- for var in jaxpr_1_opt.invars[:num_consts]:\n- var.aval = core.abstract_unit\n-\njaxpr_1_opt = pe.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr_1_opt), ())\nnum_consts_1 = num_consts + len(consts_1)\n# any now-known residuals are intensive, so we want to revise jaxpr_2 to take\n"
}
] | Python | Apache License 2.0 | google/jax | remove mysterious code that is no longer needed |
260,335 | 08.10.2020 20:31:39 | 25,200 | 52fe026c099cd3572c12b6819bb19c55c58f3313 | optimize scan partial_eval to fix
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -232,9 +232,6 @@ class Literal:\ndef __hash__(self):\nassert False\n- def __eq__(self, other):\n- assert False\n-\ndef __repr__(self):\nif hasattr(self, 'hash'):\nreturn '{}'.format(self.val)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -1566,7 +1566,6 @@ def _scan_partial_eval(trace, *tracers, reverse, length, num_consts, num_carry,\njaxpr_1_opt, out_pvals_1, consts_1 = pe.trace_to_jaxpr(\nlu.wrap_init(core.jaxpr_as_fun(jaxpr_1)), in_pvals_1,\ninstantiate=[True] * (num_carry + num_ys) + [False] * num_res)\n-\njaxpr_1_opt = pe.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr_1_opt), ())\nnum_consts_1 = num_consts + len(consts_1)\n# any now-known residuals are intensive, so we want to revise jaxpr_2 to take\n@@ -1577,6 +1576,18 @@ def _scan_partial_eval(trace, *tracers, reverse, length, num_consts, num_carry,\njaxpr_2_opt = pe.move_binders_to_front(jaxpr_2, move)\nnum_consts_2 = num_consts + len(intensive_residuals)\n+ # As another optimization, for any extensive inputs that are just forwarded to\n+ # extensive outputs, to avoid a copy (looping over dynamic-update-slice) we'd\n+ # rather just forward the input tracer. That means pruning some extensive\n+ # outputs from the jaxpr here, and updating out_flat below.\n+ extensive_invars = jaxpr_1_opt.jaxpr.invars[num_consts_1 + num_carry:]\n+ extensive_outvars = jaxpr_1_opt.jaxpr.outvars[num_carry:]\n+ fwd_extensive = [num_consts + num_carry + extensive_invars.index(v)\n+ if v in extensive_invars else None for v in extensive_outvars]\n+ jaxpr_1_opt.jaxpr.outvars = (\n+ jaxpr_1_opt.jaxpr.outvars[:num_carry] +\n+ [v for i, v in zip(fwd_extensive, extensive_outvars) if i is None])\n+\nin_consts = (list(consts_1) + [core.unit] * num_consts +\n[core.unit if uk else t.pval[1]\nfor uk, t in zip(unknowns[num_consts:], tracers[num_consts:])])\n@@ -1587,6 +1598,15 @@ def _scan_partial_eval(trace, *tracers, reverse, length, num_consts, num_carry,\n*in_consts, reverse=reverse, length=length, jaxpr=jaxpr_1_opt,\nnum_consts=num_consts_1, num_carry=num_carry, linear=tuple(linear_1),\nunroll=unroll)\n+\n+ # Propagate the forwarded extensive outputs using fwd_extensive.\n+ out_carry, out_extensive = split_list(out_flat, [num_carry])\n+ out_extensive = iter(out_extensive)\n+ out_extensive = [next(out_extensive) if i is None else\n+ tracers[i].pval[1] if tracers[i].is_known() else tracers[i]\n+ for i in fwd_extensive]\n+ out_flat = out_carry + out_extensive\n+\nout_carry, ys, res_and_units = split_list(out_flat, [num_carry, num_ys])\nextensive_residuals = [r for r, (pv, _) in zip(res_and_units, res_pvals) if pv is not None]\n@@ -1802,19 +1822,19 @@ def _scan_typecheck(bind_time, *avals, reverse, length, num_consts, num_carry,\ncore.typecheck_assert(\nall(_map(core.typematch, init_avals_jaxpr, carry_avals_jaxpr)),\nf'scan input carry input and output types mismatch: '\n- f'{_avals_short(init_avals_jaxpr)} vs {_avals_short(carry_avals_jaxpr)}')\n+ f'\\n{_avals_short(init_avals_jaxpr)}\\nvs\\n{_avals_short(carry_avals_jaxpr)}')\ncore.typecheck_assert(\nall(_map(core.typecompat, const_avals_jaxpr, const_avals)),\n- f'scan jaxpr takes input const types {_avals_short(const_avals_jaxpr)}, '\n- f'called with consts of type {_avals_short(const_avals)}')\n+ f'scan jaxpr takes input const types\\n{_avals_short(const_avals_jaxpr)},\\n'\n+ f'called with consts of type\\n{_avals_short(const_avals)}')\ncore.typecheck_assert(\nall(_map(core.typecompat, init_avals_jaxpr, init_avals)),\n- f'scan jaxpr takes input carry types {_avals_short(init_avals_jaxpr)}, '\n- f'called with initial carry of type {_avals_short(init_avals)}')\n+ f'scan jaxpr takes input carry types\\n{_avals_short(init_avals_jaxpr)},\\n'\n+ f'called with initial carry of type\\n{_avals_short(init_avals)}')\ncore.typecheck_assert(\nall(_map(core.typecompat, x_avals_jaxpr, x_avals_mapped)),\n- f'scan jaxpr takes input sequence types {_avals_short(x_avals_jaxpr)}, '\n- f'called with sequence of type {_avals_short(x_avals)}')\n+ f'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)}')\ndef scan_bind(*args, **params):\nif not core.skip_checks:\n"
}
] | Python | Apache License 2.0 | google/jax | optimize scan partial_eval to fix #4510
fixes #4510 |
260,335 | 09.10.2020 10:26:28 | 25,200 | 5355776e574f5fb0dd38486926a05532384fd03f | make scan fwd raw extensive inputs as DeviceArray
follow-up on | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -1582,6 +1582,8 @@ def _scan_partial_eval(trace, *tracers, reverse, length, num_consts, num_carry,\n# outputs from the jaxpr here, and updating out_flat below.\nextensive_invars = jaxpr_1_opt.jaxpr.invars[num_consts_1 + num_carry:]\nextensive_outvars = jaxpr_1_opt.jaxpr.outvars[num_carry:]\n+ extensive_avals = [core.unmapped_aval(length, core.raise_to_shaped(v.aval))\n+ for v in extensive_outvars]\nfwd_extensive = [num_consts + num_carry + extensive_invars.index(v)\nif v in extensive_invars else None for v in extensive_outvars]\njaxpr_1_opt.jaxpr.outvars = (\n@@ -1599,12 +1601,15 @@ def _scan_partial_eval(trace, *tracers, reverse, length, num_consts, num_carry,\nnum_consts=num_consts_1, num_carry=num_carry, linear=tuple(linear_1),\nunroll=unroll)\n- # Propagate the forwarded extensive outputs using fwd_extensive.\n+ # Propagate the forwarded extensive outputs using fwd_extensive. Any\n+ # numpy.ndarray inputs should be converted to JAX DeviceArrays.\nout_carry, out_extensive = split_list(out_flat, [num_carry])\nout_extensive_iter = iter(out_extensive)\n- out_extensive = [next(out_extensive_iter) if i is None else\n- tracers[i].pval[1] if tracers[i].is_known() else tracers[i]\n- for i in fwd_extensive]\n+ out_extensive = [next(out_extensive_iter) if i is None\n+ else _maybe_device_put(tracers[i].pval[1]) if tracers[i].is_known()\n+ else tracers[i] for i in fwd_extensive]\n+ assert all(a == core.raise_to_shaped(core.get_aval(out))\n+ for a, out in zip(extensive_avals, out_extensive))\nout_flat = out_carry + out_extensive\nout_carry, ys, res_and_units = split_list(out_flat, [num_carry, num_ys])\n@@ -1635,6 +1640,12 @@ def _scan_partial_eval(trace, *tracers, reverse, length, num_consts, num_carry,\nfor t in out_tracers: t.recipe = eqn\nreturn out_tracers\n+def _maybe_device_put(x):\n+ if isinstance(x, np.ndarray):\n+ return lax._device_put_raw(x)\n+ else:\n+ return x\n+\ndef _promote_aval_rank(sz, aval):\nif aval is core.abstract_unit:\nreturn core.abstract_unit\n"
}
] | Python | Apache License 2.0 | google/jax | make scan fwd raw extensive inputs as DeviceArray
follow-up on #4517 |
260,335 | 09.10.2020 10:35:47 | 25,200 | 0aeeb63f85c52a6f35a9408d4581d3a56b83f34a | add test for scan input forwarding | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -34,6 +34,7 @@ from jax import random\nfrom jax import test_util as jtu\nfrom jax.util import unzip2\nfrom jax.lib import xla_bridge\n+from jax.interpreters import xla\nimport jax.numpy as jnp # scan tests use numpy\nimport jax.scipy as jsp\n@@ -2490,6 +2491,27 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nresult = lax.while_loop(cond_fun, body_fun, init_weak)\nself.assertArraysEqual(result, jnp.full_like(increment, 2))\n+ def test_scan_vjp_forwards_extensive_residuals(self):\n+ # https://github.com/google/jax/issues/4510\n+ def cumprod(x):\n+ s = jnp.ones((2, 32), jnp.float32)\n+ return lax.scan(lambda s, x: (x*s, s), s, x)\n+\n+ rng = np.random.RandomState(1234)\n+ x = jnp.asarray(rng.randn(32, 2, 32))\n+ _, vjp_fun = api.vjp(cumprod, x)\n+\n+ # Need to spelunk into vjp_fun. This is fragile, and if it causes problems\n+ # just skip this test.\n+ *_, ext_res = vjp_fun.args[0].args[0]\n+ self.assertIs(ext_res, x)\n+\n+ x = rng.randn(32, 2, 32) # numpy.ndarray, not DeviceArray\n+ _, vjp_fun = api.vjp(cumprod, x)\n+ *_, ext_res = vjp_fun.args[0].args[0]\n+ self.assertIsInstance(ext_res, xla.DeviceArray)\n+\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | add test for scan input forwarding |
260,411 | 10.10.2020 10:30:23 | -10,800 | 9d9762b714c8fd83a4e566784edf4750074cef95 | [jax2tf] Ensure jax2tf still works without omnistaging
This refines changes from PR 4470 to ensure that jax2tf works even without omnistaging.
Some tests would fail though, e.g., converting a function with no arguments | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -20,6 +20,7 @@ import jax\nfrom jax import abstract_arrays\nfrom jax import ad_util\nfrom jax import api\n+from jax import config\nfrom jax import core\nfrom jax import custom_derivatives\nfrom jax import dtypes\n@@ -154,7 +155,7 @@ def convert(fun, with_gradient=True):\ndef converted_fun(*args: TfVal) -> TfVal:\n# TODO: is there a better way to check if we are inside a transformation?\n- if not core.trace_state_clean():\n+ if config.omnistaging_enabled and not core.trace_state_clean():\nraise ValueError(\"convert must be used outside all JAX transformations.\"\n+ f\"Trace state: {core.thread_local_state.trace_state}\")\n@@ -216,7 +217,8 @@ def convert(fun, with_gradient=True):\ndef _interpret_fun(fun: lu.WrappedFun,\nin_vals: Sequence[TfValOrUnit]) -> Sequence[TfValOrUnit]:\n- with core.new_base_main(TensorFlowTrace) as main:\n+ new_main = core.new_base_main if config.omnistaging_enabled else core.new_main\n+ with new_main(TensorFlowTrace) as main:\nfun = _interpret_subtrace(fun, main)\nout_vals: Sequence[TfValOrUnit] = fun.call_wrapped(*in_vals)\ndel main\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Ensure jax2tf still works without omnistaging
This refines changes from PR 4470 to ensure that jax2tf works even without omnistaging.
Some tests would fail though, e.g., converting a function with no arguments |
260,639 | 04.10.2020 17:46:13 | 14,400 | 0485fd87366bfa80477de4ac4c268887459d0231 | adding histogram2d implementation | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -178,6 +178,7 @@ Not every function in NumPy is implemented; contributions are welcome!\nheaviside\nhistogram\nhistogram_bin_edges\n+ histogram2d\nhistogramdd\nhsplit\nhstack\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -36,7 +36,7 @@ from .lax_numpy import (\nfabs, finfo, fix, flatnonzero, flexible, flip, fliplr, flipud, float16, float32,\nfloat64, float_, float_power, floating, floor, floor_divide, fmax, fmin,\nfmod, frexp, full, full_like, function, gcd, geomspace, gradient, greater,\n- greater_equal, hamming, hanning, heaviside, histogram, histogram_bin_edges, histogramdd,\n+ greater_equal, hamming, hanning, heaviside, histogram, histogram_bin_edges, histogram2d, histogramdd,\nhsplit, hstack, hypot, i0, identity, iinfo, imag,\nindices, inexact, in1d, inf, inner, int16, int32, int64, int8, int_, integer,\ninterp, intersect1d, invert,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -921,6 +921,22 @@ def histogram(a, bins=10, range=None, weights=None, density=None):\ncounts = counts / bin_widths / counts.sum()\nreturn counts, bin_edges\n+@_wraps(np.histogram2d)\n+def histogram2d(x, y, bins=10, range=None, weights=None, density=None):\n+\n+ try:\n+ N = len(bins)\n+ except TypeError:\n+ N = 1\n+\n+ if N != 1 and N != 2:\n+ x_edges = y_edges = asarray(bins)\n+ bins = [x_edges, y_edges]\n+\n+ sample = transpose(asarray([x, y]))\n+ hist, edges = histogramdd(sample, bins, range, weights, density)\n+ return hist, edges[0], edges[1]\n+\n@_wraps(np.histogramdd)\ndef histogramdd(sample, bins=10, range=None, weights=None, density=None):\n_check_arraylike(\"histogramdd\", sample)\n@@ -929,6 +945,14 @@ def histogramdd(sample, bins=10, range=None, weights=None, density=None):\nif weights is not None and weights.shape != (N,):\nraise ValueError(\"should have one weight for each sample.\")\n+ try:\n+ num_bins = len(bins)\n+ if num_bins != D:\n+ raise ValueError(\"should be a bin for each dimension.\")\n+ except TypeError:\n+ # when bin_size is integer, the same bin is used for each dimension\n+ bins = D * [bins]\n+\nbin_idx_by_dim = D*[None]\nnbins = np.empty(D, int)\nbin_edges_by_dim = D*[None]\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -2325,6 +2325,36 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ntol=tol)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_bins={}_weights={}_density={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), bins, weights, density),\n+ \"shape\": shape,\n+ \"dtype\": dtype,\n+ \"bins\": bins,\n+ \"weights\": weights,\n+ \"density\": density\n+ }\n+ for shape in [(5,), (12,)]\n+ for dtype in int_dtypes\n+ for bins in [2, [2, 2], [[0, 1, 3, 5], [0, 2, 3, 4, 6]]]\n+ for weights in [False, True]\n+ for density in [False, True]\n+ ))\n+ def testHistogram2d(self, shape, dtype, bins, weights, density):\n+ rng = jtu.rand_default(self.rng())\n+ _weights = lambda w: abs(w) if weights else None\n+ np_fun = lambda a, b, w: np.histogram2d(a, b, bins=bins, weights=_weights(w), density=density)\n+ jnp_fun = lambda a, b, w: jnp.histogram2d(a, b, bins=bins, weights=_weights(w), density=density)\n+ args_maker = lambda: [rng(shape, dtype), rng(shape, dtype), rng(shape, dtype)]\n+ tol = {jnp.bfloat16: 2E-2, np.float16: 1E-1}\n+ # np.searchsorted errors on bfloat16 with\n+ # \"TypeError: invalid type promotion with custom data type\"\n+ with np.errstate(divide='ignore', invalid='ignore'):\n+ if dtype != jnp.bfloat16:\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False,\n+ tol=tol)\n+ self._CompileAndCheck(jnp_fun, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_bins={}_weights={}_density={}\".format(\njtu.format_shape_dtype_string(shape, dtype), bins, weights, density),\n@@ -2336,8 +2366,6 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n}\nfor shape in [(5, 3), (10, 3)]\nfor dtype in int_dtypes\n- # We only test explicit integer-valued bin edges because in other cases\n- # rounding errors lead to flaky tests.\nfor bins in [(2, 2, 2), [[-5, 0, 4], [-4, -1, 2], [-6, -1, 4]]]\nfor weights in [False, True]\nfor density in [False, True]\n@@ -4434,6 +4462,7 @@ class NumpySignaturesTest(jtu.JaxTestCase):\n'full_like': ['shape', 'subok', 'order'],\n'gradient': ['varargs', 'axis', 'edge_order'],\n'histogram': ['normed'],\n+ 'histogram2d': ['normed'],\n'histogramdd': ['normed'],\n'isneginf': ['out'],\n'isposinf': ['out'],\n"
}
] | Python | Apache License 2.0 | google/jax | adding histogram2d implementation |
260,335 | 10.10.2020 21:08:52 | 25,200 | 4e65a6f0a9d792ebcd22ea29efffa485f1d76f8c | don't generate lazy iota/eye/tri/delta omnistaging | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1409,6 +1409,11 @@ def iota(dtype: DType, size: int) -> Array:\n<https://www.tensorflow.org/xla/operation_semantics#iota>`_\noperator.\n\"\"\"\n+ if config.omnistaging_enabled:\n+ dtype = dtypes.canonicalize_dtype(dtype)\n+ size = core.concrete_or_error(int, size, \"size argument of lax.iota\")\n+ return iota_p.bind(dtype=dtype, shape=(size,), dimension=0)\n+ else:\nsize = size if type(size) is masking.Poly else int(size)\nshape = canonicalize_shape((size,))\ndtype = dtypes.canonicalize_dtype(dtype)\n@@ -1420,41 +1425,54 @@ def broadcasted_iota(dtype: DType, shape: Shape, dimension: int) -> Array:\n\"\"\"Convenience wrapper around ``iota``.\"\"\"\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = canonicalize_shape(shape)\n- dimension = int(dimension)\n- return broadcast_in_dim(iota(dtype, shape[dimension]), shape, [dimension])\n+ dimension = core.concrete_or_error(\n+ int, dimension, \"dimension argument of lax.broadcasted_iota\")\n+ return iota_p.bind(dtype=dtype, shape=shape, dimension=dimension)\ndef _eye(dtype: DType, shape: Shape, offset: int) -> Array:\n- \"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\n-\n- This function exists for creating lazy identity matrices; that is,\n- materialization of the array is delayed and it may be fused into consumers to\n- avoid materialization at all.\"\"\"\n+ \"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\"\"\"\nN, M = tuple(map(int, shape))\noffset = int(offset)\ndtype = dtypes.canonicalize_dtype(dtype)\n+ if config.omnistaging_enabled:\n+ bool_eye = eq(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n+ broadcasted_iota(np.int32, (N, M), 1))\n+ return convert_element_type_p.bind(bool_eye, new_dtype=dtype,\n+ old_dtype=np.bool_)\n+ else:\nlazy_expr = lazy.eye(dtype, (N, M), offset)\naval = ShapedArray((N, M), dtype)\nreturn xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\ndef _delta(dtype: DType, shape: Shape, axes: Sequence[int]) -> Array:\n- \"\"\"This function exists for creating lazy Kronecker delta arrays, particularly\n- for use in jax.numpy.einsum to express traces. It differs from ``eye`` in that\n- it can create arrays of any rank, but doesn't allow offsets.\"\"\"\n+ \"\"\"This utility function exists for creating Kronecker delta arrays.\"\"\"\nshape = tuple(map(int, shape))\naxes = tuple(map(int, axes))\ndtype = dtypes.canonicalize_dtype(dtype)\nbase_shape = tuple(np.take(shape, axes))\n+ if config.omnistaging_enabled:\n+ iotas = [broadcasted_iota(np.uint32, base_shape, i)\n+ for i in range(len(base_shape))]\n+ eyes = [eq(i1, i2) for i1, i2 in zip(iotas[:-1], iotas[1:])]\n+ result = convert_element_type_p.bind(_reduce(operator.and_, eyes),\n+ new_dtype=dtype, old_dtype=np.bool_)\n+ return broadcast_in_dim(result, shape, axes)\n+ else:\nlazy_expr = lazy.broadcast(lazy.delta(dtype, base_shape), shape, axes)\naval = ShapedArray(shape, dtype)\nreturn xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\ndef _tri(dtype: DType, shape: Shape, offset: int) -> Array:\n- \"\"\"Like numpy.tri, create a 2D array with ones below a diagonal.\n- This function exists for creating lazy triangular matrices, particularly for\n- use in jax.numpy.tri.\"\"\"\n+ \"\"\"Like numpy.tri, create a 2D array with ones below a diagonal.\"\"\"\nN, M = tuple(map(int, shape))\noffset = int(offset)\ndtype = dtypes.canonicalize_dtype(dtype)\n+ if config.omnistaging_enabled:\n+ bool_tri = ge(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n+ broadcasted_iota(np.int32, (N, M), 1))\n+ return convert_element_type_p.bind(bool_tri, old_dtype=np.int32,\n+ new_dtype=dtype)\n+ else:\nlazy_expr = lazy.tri(dtype, (N, M), offset)\naval = ShapedArray((N, M), dtype)\nreturn xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\n@@ -5797,6 +5815,7 @@ outfeed_p.def_impl(partial(xla.apply_primitive, outfeed_p))\noutfeed_p.def_abstract_eval(_outfeed_abstract_eval)\nxla.translations[outfeed_p] = _outfeed_translation_rule\n+\ndef rng_uniform(a, b, shape):\n\"\"\"Stateful PRNG generator. Experimental and its use is discouraged.\n@@ -5829,6 +5848,30 @@ rng_uniform_p.def_impl(partial(xla.apply_primitive, rng_uniform_p))\nrng_uniform_p.def_abstract_eval(_rng_uniform_abstract_eval)\nxla.translations[rng_uniform_p] = _rng_uniform_translation_rule\n+\n+def _iota_abstract_eval(*, dtype, shape, dimension):\n+ _check_shapelike(\"iota\", \"shape\", shape)\n+ if not any(dtypes.issubdtype(dtype, t) for t in _num):\n+ msg = 'iota does not accept dtype {}. Accepted dtypes are subtypes of {}.'\n+ typename = str(np.dtype(dtype).name)\n+ accepted_typenames = (t.__name__ for t in _num)\n+ raise TypeError(msg.format(typename, ', '.join(accepted_typenames)))\n+ if not 0 <= dimension < len(shape):\n+ raise ValueError(\"iota dimension must be between 0 and len(shape), got \"\n+ f\"dimension={dimension} for shape {shape}\")\n+ return ShapedArray(shape, dtype)\n+\n+def _iota_translation_rule(c, dtype, shape, dimension):\n+ etype = xla_client.dtype_to_etype(dtype)\n+ xla_shape = xc.Shape.array_shape(etype, shape)\n+ return xops.Iota(c, xla_shape, dimension)\n+\n+iota_p = Primitive('iota')\n+iota_p.def_impl(partial(xla.apply_primitive, iota_p))\n+iota_p.def_abstract_eval(_iota_abstract_eval)\n+xla.translations[iota_p] = _iota_translation_rule\n+\n+\n### util\n_ndim = np.ndim\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -300,6 +300,7 @@ def _fold_in(key, data):\nreturn threefry_2x32(key, PRNGKey(data))\n+@partial(jit, static_argnums=(1, 2))\ndef _random_bits(key, bit_width, shape):\n\"\"\"Sample uniform random bits of given width and shape using PRNG key.\"\"\"\nif not _is_prng_key(key):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -33,7 +33,7 @@ import concurrent.futures\nimport jax\nimport jax.numpy as jnp\nfrom jax import float0, jit, grad, device_put, jacfwd, jacrev, hessian\n-from jax import api, core, lax, lax_reference\n+from jax import api, core, lax, lax_reference, lazy\nfrom jax.core import Primitive\nfrom jax.interpreters import ad\nfrom jax.interpreters import xla\n@@ -1450,7 +1450,7 @@ class APITest(jtu.JaxTestCase):\ndef test_dtype_warning(self):\n# cf. issue #1230\nif FLAGS.jax_enable_x64:\n- return # test only applies when x64 is disabled\n+ raise unittest.SkipTest(\"test only applies when x64 is disabled\")\ndef check_warning(warn, nowarn):\nwith warnings.catch_warnings(record=True) as w:\n@@ -2443,14 +2443,14 @@ class LazyTest(jtu.JaxTestCase):\nassert python_should_be_executing\nreturn jnp.sum(x)\n- x = jnp.arange(10, dtype=jnp.int32)\n- assert xla.is_device_constant(x) # lazy iota\n+ x = jnp.zeros(10, dtype=jnp.int32)\n+ assert not lazy.is_trivial(x._lazy_expr)\npython_should_be_executing = True\n_ = f(x)\npython_should_be_executing = False # should not recompile\n- x = np.arange(10, dtype=np.int32)\n+ x = np.zeros(10, dtype=np.int32)\n_ = f(x)\n@parameterized.parameters(jtu.cases_from_list(range(10000)))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -3623,6 +3623,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ntype(lax.iota(np.int32, 77)))\n# test laziness for int dtypes\n+ if not config.omnistaging_enabled:\nself.assertTrue(xla.is_device_constant(jnp.arange(77)))\nself.assertTrue(xla.is_device_constant(jnp.arange(77, dtype=jnp.int32)))\n"
}
] | Python | Apache License 2.0 | google/jax | don't generate lazy iota/eye/tri/delta omnistaging |
260,268 | 11.10.2020 11:30:45 | 14,400 | 00e70492e4e8aa0caf9377124fd6d7af35a310c3 | Export expit and logsumexp in jax.nn.functions | [
{
"change_type": "MODIFY",
"old_path": "jax/nn/__init__.py",
"new_path": "jax/nn/__init__.py",
"diff": "@@ -19,6 +19,7 @@ from . import initializers\nfrom .functions import (\ncelu,\nelu,\n+ expit,\ngelu,\nglu,\nhard_sigmoid,\n@@ -28,6 +29,7 @@ from .functions import (\nleaky_relu,\nlog_sigmoid,\nlog_softmax,\n+ logsumexp,\nnormalize,\none_hot,\nrelu,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/nn/functions.py",
"new_path": "jax/nn/functions.py",
"diff": "@@ -21,7 +21,7 @@ from jax import custom_jvp\nfrom jax import dtypes\nfrom jax import lax\nfrom jax import core\n-from jax.scipy.special import expit\n+from jax.scipy.special import expit, logsumexp\nimport jax.numpy as jnp\n# activations\n"
}
] | Python | Apache License 2.0 | google/jax | Export expit and logsumexp in jax.nn.functions |
260,335 | 11.10.2020 10:15:48 | 25,200 | e1708f5c91684bea7f51fe48dd65456c5e5992cb | fix typo "differentiaion" | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -60,7 +60,7 @@ restored_model = tf.saved_model.load('/some/directory')\nMore involved examples of using SavedModel are described in the\n[getting started Colab](JAX2TF_getting_started.ipynb).\n-## Differentiaion\n+## Differentiation\nThe converted code supports differentiation from TF.\nThe main challenge with TF-differentiation of the converted code is that some\n"
}
] | Python | Apache License 2.0 | google/jax | fix typo "differentiaion" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.