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,335
29.04.2022 16:36:57
25,200
65bff3c856ecb7b21c48ab254444dacf4f90e669
[remove-units] avoid unit-generating function in jax.linear_transpose
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -2515,7 +2515,7 @@ def linear_transpose(fun: Callable, *primals, reduce_axes=()) -> Callable:\nin_dtypes = map(dtypes.dtype, in_avals)\nin_pvals = map(pe.PartialVal.unknown, in_avals)\n- jaxpr, out_pvals, consts = pe.trace_to_jaxpr(flat_fun, in_pvals,\n+ jaxpr, out_pvals, const = pe.trace_to_jaxpr_nounits(flat_fun, in_pvals,\ninstantiate=True)\nout_avals, _ = unzip2(out_pvals)\nout_dtypes = map(dtypes.dtype, out_avals)\n@@ -2527,22 +2527,21 @@ def linear_transpose(fun: Callable, *primals, reduce_axes=()) -> Callable:\nf\"but got {in_dtypes} -> {out_dtypes}.\")\n@api_boundary\n- def transposed_fun(consts, out_cotangent):\n- out_cotangents, out_tree2 = tree_flatten(out_cotangent)\n+ def transposed_fun(const, out_cotangent):\n+ out_cts, out_tree2 = tree_flatten(out_cotangent)\nif out_tree() != out_tree2:\nraise TypeError(\"cotangent tree does not match function output, \"\nf\"expected {out_tree()} but got {out_tree2}\")\n- if not all(map(core.typecheck, out_avals, out_cotangents)):\n+ if not all(map(core.typecheck, out_avals, out_cts)):\nraise TypeError(\"cotangent type does not match function output, \"\n- f\"expected {out_avals} but got {out_cotangents}\")\n+ f\"expected {out_avals} but got {out_cts}\")\ndummies = [ad.UndefinedPrimal(a) for a in in_avals]\n- in_cotangents = map(\n- ad.instantiate_zeros,\n- ad.backward_pass(jaxpr, reduce_axes, True, consts, dummies, out_cotangents))\n- return tree_unflatten(in_tree, in_cotangents)\n+ in_cts = ad.backward_pass(jaxpr, reduce_axes, True, const, dummies, out_cts)\n+ in_cts = map(ad.instantiate_zeros, in_cts)\n+ return tree_unflatten(in_tree, in_cts)\n# Ensure that transposed_fun is a PyTree\n- return Partial(transposed_fun, consts)\n+ return Partial(transposed_fun, const)\ndef make_jaxpr(fun: Callable,\n" } ]
Python
Apache License 2.0
google/jax
[remove-units] avoid unit-generating function in jax.linear_transpose
260,447
29.04.2022 16:42:08
25,200
020849076c9e927b3ee091015bddecc7d01bf71d
[linalg] Add tpu svd lowering rule.
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -13,6 +13,10 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* [GitHub\ncommits](https://github.com/google/jax/compare/jax-v0.3.7...main).\n* Changes\n+ * {func}`jax.numpy.linalg.svd` on TPUs uses a qdwh-svd solver.\n+ * {func}`jax.numpy.linalg.cond` on TPUs now accepts complex input.\n+ * {func}`jax.numpy.linalg.pinv` on TPUs now accepts complex input.\n+ * {func}`jax.numpy.linalg.matrix_rank` on TPUs now accepts complex input.\n* {func}`jax.scipy.cluster.vq.vq` has been added.\n* `jax.experimental.maps.mesh` has been deleted.\nPlease use `jax.experimental.maps.Mesh`. Please see https://jax.readthedocs.io/en/latest/_autosummary/jax.experimental.maps.Mesh.html#jax.experimental.maps.Mesh\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/linalg.py", "new_path": "jax/_src/lax/linalg.py", "diff": "@@ -34,6 +34,7 @@ from jax._src.lax.lax import (\nstandard_primitive, standard_unop, naryop_dtype_rule, _float, _complex,\n_input_dtype)\nfrom jax._src.lax import lax as lax_internal\n+from jax._src.lax import svd as lax_svd\nfrom jax._src.lib import lapack\nfrom jax._src.lib import cuda_linalg\n@@ -202,6 +203,7 @@ def qr(x, full_matrices: bool = True):\nq, r = qr_p.bind(x, full_matrices=full_matrices)\nreturn q, r\n+# TODO: Add `max_qdwh_iterations` to the function signature for TPU SVD.\ndef svd(x, full_matrices=True, compute_uv=True):\n\"\"\"Singular value decomposition.\n@@ -1295,32 +1297,6 @@ def _eye_like_xla(c, aval):\nxops.Iota(c, iota_shape, len(aval.shape) - 2))\nreturn xops.ConvertElementType(x, xla.dtype_to_primitive_type(aval.dtype))\n-def _svd_translation_rule(ctx, avals_in, avals_out, operand, *, full_matrices,\n- compute_uv):\n- operand_aval, = avals_in\n- shape = operand_aval.shape\n- m, n = shape[-2:]\n- if m == 0 or n == 0:\n- out = [_zeros_like_xla(ctx.builder, avals_out[0])]\n- if compute_uv:\n- out.append(_eye_like_xla(ctx.builder, avals_out[1]))\n- out.append(_eye_like_xla(ctx.builder, avals_out[2]))\n- return out\n-\n- u, s, v = xops.SVD(operand)\n- permutation = list(range(len(shape)))\n- permutation[-1], permutation[-2] = permutation[-2], permutation[-1]\n- vt = xops.Transpose(v, permutation)\n- if not full_matrices and m != n:\n- u = xops.SliceInDim(u, 0, min(m, n), stride=1, dimno=len(shape) - 1)\n- vt = xops.SliceInDim(vt, 0, min(m, n), stride=1, dimno=len(shape) - 2)\n-\n- if not compute_uv:\n- return [s]\n- else:\n- return [s, u, vt]\n-\n-\ndef svd_abstract_eval(operand, full_matrices, compute_uv):\nif isinstance(operand, ShapedArray):\nif operand.ndim < 2:\n@@ -1440,6 +1416,31 @@ def _svd_cpu_gpu_lowering(gesvd_impl, ctx, operand, *, full_matrices,\nreturn result\n+def _svd_tpu(a, *, full_matrices, compute_uv):\n+ batch_dims = a.shape[:-2]\n+\n+ fn = partial(lax_svd.svd, full_matrices=full_matrices, compute_uv=compute_uv)\n+ for _ in range(len(batch_dims)):\n+ fn = api.vmap(fn)\n+\n+ if compute_uv:\n+ u, s, vh = fn(a)\n+ return [s, u, vh]\n+ else:\n+ s = fn(a)\n+ return [s]\n+\n+def _svd_tpu_lowering_rule(ctx, operand, *, full_matrices, compute_uv):\n+ operand_aval, = ctx.avals_in\n+ m, n = operand_aval.shape[-2:]\n+\n+ if m == 0 or n == 0:\n+ return mlir.lower_fun(_empty_svd, multiple_results=True)(\n+ ctx, operand, full_matrices=full_matrices, compute_uv=compute_uv)\n+\n+ return mlir.lower_fun(_svd_tpu, multiple_results=True)(\n+ ctx, operand, full_matrices=full_matrices, compute_uv=compute_uv)\n+\ndef svd_batching_rule(batched_args, batch_dims, full_matrices, compute_uv):\nx, = batched_args\nbd, = batch_dims\n@@ -1457,7 +1458,6 @@ svd_p.def_impl(svd_impl)\nsvd_p.def_abstract_eval(svd_abstract_eval)\nad.primitive_jvps[svd_p] = svd_jvp_rule\nbatching.primitive_batchers[svd_p] = svd_batching_rule\n-xla.register_translation(svd_p, _svd_translation_rule)\nmlir.register_lowering(\nsvd_p, partial(_svd_cpu_gpu_lowering, lapack.gesdd_mhlo),\n@@ -1468,6 +1468,7 @@ if solver_apis is not None:\nsvd_p, partial(_svd_cpu_gpu_lowering, solver_apis.gesvd_mhlo),\nplatform='gpu')\n+mlir.register_lowering(svd_p, _svd_tpu_lowering_rule)\ndef _tridiagonal_solve_gpu_lowering(ctx, dl, d, du, b, *, m, n, ldb, t):\nreturn [sparse_apis.gtsv2_mhlo(dl, d, du, b, m=m, n=n, ldb=ldb, t=t)]\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/svd.py", "new_path": "jax/_src/lax/svd.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License\n-\"\"\"A JIT-compatible library for QDWH-based SVD decomposition.\n+\"\"\"A JIT-compatible library for QDWH-based singular value decomposition.\nQDWH is short for QR-based dynamically weighted Halley iteration. The Halley\niteration implemented through QR decmopositions is numerically stable and does\n@@ -35,8 +35,7 @@ https://epubs.siam.org/doi/abs/10.1137/090774999\nimport functools\n-from typing import Sequence, Union\n-\n+from typing import Any, Sequence, Union\nimport jax\nfrom jax import core\nfrom jax import lax\n@@ -44,10 +43,10 @@ import jax.numpy as jnp\n@functools.partial(jax.jit, static_argnums=(1, 2, 3))\n-def _svd(a: jnp.ndarray,\n+def _svd(a: Any,\nhermitian: bool,\ncompute_uv: bool,\n- max_iterations: int) -> Union[jnp.ndarray, Sequence[jnp.ndarray]]:\n+ max_iterations: int) -> Union[Any, Sequence[Any]]:\n\"\"\"Singular value decomposition for m x n matrix and m >= n.\nArgs:\n@@ -99,11 +98,11 @@ def _svd(a: jnp.ndarray,\n@functools.partial(jax.jit, static_argnums=(1, 2, 3, 4))\n-def svd(a: jnp.ndarray,\n+def svd(a: Any,\nfull_matrices: bool,\ncompute_uv: bool = True,\nhermitian: bool = False,\n- max_iterations: int = 10) -> Union[jnp.ndarray, Sequence[jnp.ndarray]]:\n+ max_iterations: int = 10) -> Union[Any, Sequence[Any]]:\n\"\"\"Singular value decomposition.\nArgs:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -1071,9 +1071,9 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n# than O(\\sqrt(eps)), which is likely a property of the SVD algorithms\n# in question; revisit with better understanding of the SVD algorithms.\nif x.dtype in [np.float32, np.complex64]:\n- slack_factor = 1E4\n+ slack_factor = 2E4\nelif x.dtype in [np.float64, np.complex128]:\n- slack_factor = 1E9\n+ slack_factor = 2E9\nnp.testing.assert_array_less(angular_diff,\nslack_factor * error_bound)\n@@ -1131,17 +1131,18 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndtypes=[np.complex64, np.complex128],\ndevices=(\"cpu\", \"gpu\"),\nmodes=(\"compiled\",)),\n+ Jax2TfLimitation(\n+ \"Large numerical discrepancy\",\n+ dtypes=[np.float16],\n+ devices=(\"tpu\"),\n+ modes=(\"eager\", \"graph\", \"compiled\"),\n+ skip_comparison=True),\nmissing_tf_kernel(dtypes=[dtypes.bfloat16], devices=\"tpu\"),\ncustom_numeric(\ntol=1e-4,\ndtypes=[np.float32, np.complex64],\ndevices=(\"cpu\", \"gpu\"),\nmodes=(\"eager\", \"graph\", \"compiled\")),\n- custom_numeric(\n- tol=1e-2,\n- dtypes=[np.float16],\n- devices=(\"tpu\"),\n- modes=(\"eager\", \"graph\", \"compiled\")),\n# TODO: this is very low tolerance for f64\ncustom_numeric(\ntol=1e-4,\n@@ -1149,11 +1150,20 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndevices=(\"cpu\", \"gpu\"),\nmodes=(\"eager\", \"graph\", \"compiled\")),\ncustom_numeric(\n+ tol=1e-4,\ndescription=\"custom numeric comparison when compute_uv on CPU/GPU\",\ncustom_assert=custom_assert,\ndevices=(\"cpu\", \"gpu\"),\nmodes=(\"eager\", \"graph\", \"compiled\"),\nenabled=(compute_uv == True)),\n+ custom_numeric(\n+ tol=1e-2,\n+ description=\"custom numeric comparison when compute_uv on TPU\",\n+ dtypes=[np.float32, np.float64, np.complex64, np.complex128],\n+ custom_assert=custom_assert,\n+ devices=(\"tpu\"),\n+ modes=(\"eager\", \"graph\", \"compiled\"),\n+ enabled=(compute_uv == True)),\n]\n@classmethod\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -544,10 +544,6 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nfor hermitian in ([False, True] if m == n else [False])))\n@jtu.skip_on_devices(\"rocm\") # will be fixed in ROCm-5.1\ndef testSVD(self, b, m, n, dtype, full_matrices, compute_uv, hermitian):\n- # TODO: enable after linking lax.svd to lax.linalg.svd\n- if (jnp.issubdtype(dtype, np.complexfloating) and\n- jtu.device_under_test() == \"tpu\"):\n- raise unittest.SkipTest(\"No complex SVD implementation\")\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: [rng(b + (m, n), dtype)]\n@@ -744,11 +740,6 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nfor dtype in float_types + complex_types))\n@jtu.skip_on_devices(\"gpu\") # TODO(#2203): numerical errors\ndef testCond(self, shape, pnorm, dtype):\n- # TODO: enable after linking lax.svd to lax.linalg.svd\n- if (jnp.issubdtype(dtype, np.complexfloating) and\n- jtu.device_under_test() == \"tpu\"):\n- raise unittest.SkipTest(\"No complex SVD implementation\")\n-\ndef gen_mat():\n# arr_gen = jtu.rand_some_nan(self.rng())\narr_gen = jtu.rand_default(self.rng())\n@@ -855,10 +846,6 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nfor dtype in float_types + complex_types))\n@jtu.skip_on_devices(\"rocm\") # will be fixed in ROCm-5.1\ndef testPinv(self, shape, dtype):\n- # TODO: enable after linking lax.svd to lax.linalg.svd\n- if (jnp.issubdtype(dtype, np.complexfloating) and\n- jtu.device_under_test() == \"tpu\"):\n- raise unittest.SkipTest(\"No complex SVD implementation\")\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\n@@ -910,10 +897,6 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nfor dtype in float_types + complex_types))\n@jtu.skip_on_devices(\"rocm\") # will be fixed in ROCm-5.1\ndef testMatrixRank(self, shape, dtype):\n- # TODO: enable after linking lax.svd to lax.linalg.svd\n- if (jnp.issubdtype(dtype, np.complexfloating) and\n- jtu.device_under_test() == \"tpu\"):\n- raise unittest.SkipTest(\"No complex SVD implementation\")\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\na, = args_maker()\n" }, { "change_type": "MODIFY", "old_path": "tests/svd_test.py", "new_path": "tests/svd_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License\n-\"\"\"Tests for the library of QDWH-based SVD decomposition.\"\"\"\n+\"\"\"Tests for the library of QDWH-based singular value decomposition.\"\"\"\nimport functools\nimport jax\n" } ]
Python
Apache License 2.0
google/jax
[linalg] Add tpu svd lowering rule. PiperOrigin-RevId: 445533767
260,335
29.04.2022 19:58:16
25,200
290c90d37a0e112022c75f190cb518aa54b13110
Trivial change for backward compatibility stub.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -2135,3 +2135,5 @@ def trace_to_subjaxpr(main: core.MainTrace, instantiate: Union[bool, Sequence[bo\nout_pvals = [t.pval for t in out_tracers]\ndel trace, in_tracers, out_tracers\nyield jaxpr, (out_pvals, consts, env)\n+\n+partial_eval_jaxpr: Callable\n" } ]
Python
Apache License 2.0
google/jax
Trivial change for backward compatibility stub. PiperOrigin-RevId: 445564091
260,335
02.05.2022 10:02:02
25,200
11ad045dfd561882660861d0a3e2bae69fc8e7e4
[remove-units] remove units from partial_eval.py After last week's changes, units are no longer traced or introduced into jaxprs in any way, so we don't need to use them in partial evaluation. (Also there are some unrelated removals of dead code in maps.py.)
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -1512,7 +1512,7 @@ def _mapped_axis_size(tree, vals, dims, name, *, kws=False):\ntree, leaf = treedef_children(tree)\nassert treedef_is_leaf(leaf)\n# TODO(mattjj,phawkins): add a way to inspect pytree kind more directly\n- if tree == tree_flatten((core.unit,) * tree.num_leaves)[1]:\n+ if tree == tree_flatten((0,) * tree.num_leaves)[1]:\nlines1 = [f\"arg {i} has shape {np.shape(x)} and axis {d} is to be mapped\"\nfor i, (x, d) in enumerate(zip(vals, dims))]\nsizes = collections.defaultdict(list)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1106,25 +1106,6 @@ def out_local_named_shapes(local_axes, *args, **kwargs):\nans_axes = [frozenset(a.aval.named_shape) & local_axes for a in ans]\nyield ans, ans_axes\n-@lu.transformation_with_aux\n-def hide_units(unit_args, *args, **kwargs):\n- ans = yield restore_units(unit_args, args), kwargs\n- yield filter_units(ans)\n-\n-def filter_units(vals):\n- vals_no_units = [v for v in vals if v is not core.unit]\n- vals_is_unit = [v is core.unit for v in vals]\n- return vals_no_units, vals_is_unit\n-\n-def restore_units(is_unit, vals):\n- vals_it = iter(vals)\n- vals_with_units = [core.unit if u else next(vals_it) for u in is_unit]\n- try:\n- next(vals_it)\n- raise RuntimeError(\"Expected the iterator to be exhausted\")\n- except StopIteration:\n- return vals_with_units\n-\ndef _jaxpr_trace_process_xmap(self, primitive, f: lu.WrappedFun, tracers, params):\nassert primitive is xmap_p\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -62,9 +62,9 @@ class PartialVal(tuple):\n\"\"\"Partial value: either a known value or an unknown (abstract) value.\nRepresented as a pair `(aval_opt, const)` of one of two kinds:\n- * `(None, <Constant>)` indicates a known value, either a Python regular\n- value, or a Tracer.\n- * `(<AbstractValue>, *)` indicates an unknown value characterized by an\n+ * `(None, <Constant>)` indicates a known value, where the constant is either a\n+ Tracer or satisfies `core.valid_jaxtype(const)`;\n+ * `(<AbstractValue>, None)` indicates an unknown value characterized by an\nabstract value.\n\"\"\"\ndef __new__(cls, xs: Tuple[Optional[AbstractValue], core.Value]):\n@@ -72,10 +72,10 @@ class PartialVal(tuple):\nif config.jax_enable_checks:\n# type checks\nassert isinstance(pv, (AbstractValue, type(None))), xs\n- assert isinstance(const, core.Tracer) or type(const) is Zero or core.valid_jaxtype(const), xs\n+ assert (const is None or isinstance(const, core.Tracer) or\n+ core.valid_jaxtype(const)), const\n# invariant checks\n- if isinstance(pv, AbstractValue):\n- assert get_aval(const) == core.abstract_unit, xs\n+ assert (pv is None) ^ (const is None)\nreturn tuple.__new__(cls, xs)\n@classmethod\n@@ -84,7 +84,7 @@ class PartialVal(tuple):\n@classmethod\ndef unknown(cls, aval: AbstractValue) -> PartialVal:\n- return PartialVal((aval, core.unit))\n+ return PartialVal((aval, None))\ndef is_known(self) -> bool:\nreturn self[0] is None\n@@ -120,7 +120,7 @@ class JaxprTrace(Trace):\ndef new_const(self, val) -> JaxprTracer:\nif isinstance(val, Tracer) and val._trace.level == self.level:\nraise Exception\n- return JaxprTracer(self, PartialVal.known(val), core.unit)\n+ return JaxprTracer(self, PartialVal.known(val), None)\ndef new_instantiated_literal(self, val) -> JaxprTracer:\naval = get_aval(val)\n@@ -742,8 +742,8 @@ def tracers_to_jaxpr(\nconsts[v] = recipe.val\nelif isinstance(recipe, Literal):\nt_to_var[id(t)] = recipe\n- elif recipe is core.unit:\n- t_to_var[id(t)] = core.unitvar\n+ elif recipe is None:\n+ assert False\nelse:\nraise TypeError(recipe)\n" } ]
Python
Apache License 2.0
google/jax
[remove-units] remove units from partial_eval.py After last week's changes, units are no longer traced or introduced into jaxprs in any way, so we don't need to use them in partial evaluation. (Also there are some unrelated removals of dead code in maps.py.)
260,475
26.04.2022 18:03:14
-3,600
372371cec68d1d18df7ccfb7e5b7b27ae59f7236
Add jax.scipy.linalg.funm
[ { "change_type": "MODIFY", "old_path": "docs/jax.scipy.rst", "new_path": "docs/jax.scipy.rst", "diff": "@@ -29,6 +29,7 @@ jax.scipy.linalg\neigh_tridiagonal\nexpm\nexpm_frechet\n+ funm\ninv\nlu\nlu_factor\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/third_party/scipy/linalg.py", "diff": "+import scipy.linalg\n+\n+from jax import jit, lax\n+from jax._src.numpy import lax_numpy as jnp\n+from jax._src.numpy.linalg import norm\n+from jax._src.numpy.util import _wraps\n+from jax._src.scipy.linalg import rsf2csf, schur\n+\n+@jit\n+def _algorithm_11_1_1(F, T):\n+ # Algorithm 11.1.1 from Golub and Van Loan \"Matrix Computations\"\n+ N = T.shape[0]\n+ minden = jnp.abs(T[0, 0])\n+\n+ def _outer_loop(p, F_minden):\n+ _, F, minden = lax.fori_loop(1, N-p+1, _inner_loop, (p, *F_minden))\n+ return F, minden\n+\n+ def _inner_loop(i, p_F_minden):\n+ p, F, minden = p_F_minden\n+ j = i+p\n+ s = T[i-1, j-1] * (F[j-1, j-1] - F[i-1, i-1])\n+ T_row, T_col = T[i-1], T[:, j-1]\n+ F_row, F_col = F[i-1], F[:, j-1]\n+ ind = (jnp.arange(N) >= i) & (jnp.arange(N) < j-1)\n+ val = (jnp.where(ind, T_row, 0) @ jnp.where(ind, F_col, 0) -\n+ jnp.where(ind, F_row, 0) @ jnp.where(ind, T_col, 0))\n+ s = s + val\n+ den = T[j-1, j-1] - T[i-1, i-1]\n+ s = jnp.where(den != 0, s / den, s)\n+ F = F.at[i-1, j-1].set(s)\n+ minden = jnp.minimum(minden, jnp.abs(den))\n+ return p, F, minden\n+\n+ return lax.fori_loop(1, N, _outer_loop, (F, minden))\n+\n+_FUNM_LAX_DESCRIPTION = \"\"\"\\\n+The array returned by :py:func:`jax.scipy.linalg.funm` may differ in dtype\n+from the array returned by py:func:`scipy.linalg.funm`. Specifically, in cases\n+where all imaginary parts of the array values are close to zero, the SciPy\n+function may return a real-valued array, whereas the JAX implementation will\n+return a complex-valued array.\n+\n+Additionally, unlike the SciPy implementation, when ``disp=True`` no warning\n+will be printed if the error in the array output is estimated to be large.\n+\"\"\"\n+\n+@_wraps(scipy.linalg.funm, lax_description=_FUNM_LAX_DESCRIPTION)\n+def funm(A, func, disp=True):\n+ A = jnp.asarray(A)\n+ if A.ndim != 2 or A.shape[0] != A.shape[1]:\n+ raise ValueError('expected square array_like input')\n+\n+ T, Z = schur(A)\n+ T, Z = rsf2csf(T, Z)\n+\n+ F = jnp.diag(func(jnp.diag(T)))\n+ F = F.astype(T.dtype.char)\n+\n+ F, minden = _algorithm_11_1_1(F, T)\n+ F = Z @ F @ Z.conj().T\n+\n+ if disp:\n+ return F\n+\n+ if F.dtype.char.lower() == 'e':\n+ tol = jnp.finfo(jnp.float16).eps\n+ if F.dtype.char.lower() == 'f':\n+ tol = jnp.finfo(jnp.float32).eps\n+ else:\n+ tol = jnp.finfo(jnp.float64).eps\n+\n+ minden = jnp.where(minden == 0.0, tol, minden)\n+ err = jnp.where(jnp.any(jnp.isinf(F)), jnp.inf, jnp.minimum(1, jnp.maximum(\n+ tol, (tol / minden) * norm(jnp.triu(T, 1), 1))))\n+\n+ return F, err\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/linalg.py", "new_path": "jax/scipy/linalg.py", "diff": "@@ -41,3 +41,7 @@ from jax._src.scipy.linalg import (\nfrom jax._src.lax.polar import (\npolar_unitary as polar_unitary,\n)\n+\n+from jax._src.third_party.scipy.linalg import (\n+ funm as funm,\n+)\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -1465,6 +1465,28 @@ class ScipyLinalgTest(jtu.JaxTestCase):\nargs_maker, tol=tol)\nself._CompileAndCheck(jsp.linalg.rsf2csf, args_maker)\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_shape={}_disp={}\".format(jtu.format_shape_dtype_string(shape, dtype), disp),\n+ \"shape\": shape, \"dtype\": dtype, \"disp\": disp\n+ } for shape in [(1, 1), (5, 5), (20, 20), (50, 50)]\n+ for dtype in float_types + complex_types\n+ for disp in [True, False]))\n+ # funm uses jax.scipy.linalg.schur which is implemented for a CPU\n+ # backend only, so tests on GPU and TPU backends are skipped here\n+ @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ def testFunm(self, shape, dtype, disp):\n+ def func(x):\n+ return x**-2.718\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+ jnp_fun = lambda arr: jsp.linalg.funm(arr, func, disp=disp)\n+ scp_fun = lambda arr: osp.linalg.funm(arr, func, disp=disp)\n+ self._CheckAgainstNumpy(jnp_fun, scp_fun, args_maker, check_dtypes=False,\n+ tol={np.complex64: 1e-5, np.complex128: 1e-6})\n+ self._CompileAndCheck(jnp_fun, args_maker)\n+\n@parameterized.named_parameters(\njtu.cases_from_list({\n\"testcase_name\":\n" } ]
Python
Apache License 2.0
google/jax
Add jax.scipy.linalg.funm
260,631
02.05.2022 23:24:19
25,200
c72154474f88e64d44086ab8fc152ff83d6dc5a7
better error message in mesh_utils.py
[ { "change_type": "MODIFY", "old_path": "jax/experimental/mesh_utils.py", "new_path": "jax/experimental/mesh_utils.py", "diff": "@@ -251,7 +251,8 @@ def create_device_mesh(\nif devices is None:\ndevices = jax.devices()\nif np.prod(mesh_shape) != len(devices):\n- raise ValueError('Number of devices must equal the product of mesh_shape')\n+ raise ValueError(f'Number of devices {len(devices)} must equal the product '\n+ f'of mesh_shape {mesh_shape}')\ndevice_kind = devices[-1].device_kind\nif device_kind in (_TPU_V2, _TPU_V3):\nif len(devices) == 8:\n" } ]
Python
Apache License 2.0
google/jax
better error message in mesh_utils.py PiperOrigin-RevId: 446119369
260,447
02.05.2022 23:52:31
25,200
f7296a48e57f6006de679c0b2a3ac3d8350a90f1
[linalg] Update LU decomposition.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/linalg.py", "new_path": "jax/_src/lax/linalg.py", "diff": "@@ -950,17 +950,12 @@ def _lu_blocked(a, block_size=128):\ndef _lu_python(x):\n\"\"\"Default LU decomposition in Python, where no better version exists.\"\"\"\n- m, n = x.shape[-2:]\nbatch_dims = x.shape[:-2]\n- if len(batch_dims) > 0:\n- batch_size = np.prod(batch_dims, dtype=np.int64)\n- lu, pivot, perm = api.vmap(_lu_blocked)(lax.reshape(x, (batch_size, m, n)))\n- lu = lax.reshape(lu, batch_dims + (m, n))\n- pivot = lax.reshape(pivot, batch_dims + (min(m, n),))\n- perm = lax.reshape(perm, batch_dims + (m,))\n- else:\n- lu, pivot, perm = _lu_blocked(x)\n- return lu, pivot, perm\n+ fn = _lu_blocked\n+ for _ in range(len(batch_dims)):\n+ fn = api.vmap(fn)\n+\n+ return fn(x)\ndef _lu_impl(operand):\nlu, pivot, perm = xla.apply_primitive(lu_p, operand)\n" } ]
Python
Apache License 2.0
google/jax
[linalg] Update LU decomposition. PiperOrigin-RevId: 446122667
260,510
14.04.2022 14:18:31
25,200
8031eee7ee9eede434e540dbb2d0076da88b2c25
Add in runtime tokens for effectful jaxprs
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -476,18 +476,21 @@ def _cpp_jit(\n# outputs that could be tracers (if f is capturing `Tracer` by closure).\nexecute: Optional[functools.partial] = (\ndispatch._xla_callable.most_recent_entry())\n+ # TODO(sharadmv): Enable fast path for effectful jaxprs\nuse_fastpath = (\n# This is if we have already executed this code-path (most-recent entry\n# has been reset to None). Thus, we do not support the fast-path.\nexecute is not None and\nexecute.func is dispatch._execute_compiled and # not trivial, not pmap\n+ # No effects in computation\n+ not execute.args[5] and\n# Not supported: ShardedDeviceArray\nall(device_array.type_is_device_array(x) for x in out_flat) and\n# Not supported: dynamic shapes\nnot jax.config.jax_dynamic_shapes)\n### If we can use the fastpath, we return required info to the caller.\nif use_fastpath:\n- _, xla_executable, _, _, result_handlers, kept_var_idx = execute.args\n+ _, xla_executable, _, _, result_handlers, _, kept_var_idx = execute.args\nsticky_device = None\navals = []\nlazy_exprs = [None] * len(result_handlers)\n@@ -811,9 +814,11 @@ def xla_computation(fun: Callable,\nelse:\nout_parts_flat = tuple(flatten_axes(\n\"xla_computation out_parts\", out_tree(), out_parts))\n+ effects = list(jaxpr.effects)\nm = mlir.lower_jaxpr_to_module(\nf\"xla_computation_{fun_name}\",\ncore.ClosedJaxpr(jaxpr, consts),\n+ effects=effects,\nplatform=backend,\naxis_context=mlir.ReplicaAxisContext(axis_env_),\nname_stack=new_name_stack(wrap_name(fun_name, \"xla_computation\")),\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "# Primitive dispatch and jit dispatch.\nfrom __future__ import annotations\n+import atexit\nimport contextlib\nfrom functools import partial\nimport itertools\n@@ -24,6 +25,7 @@ from typing import (\nfrom typing_extensions import Protocol\nimport os\nimport re\n+import threading\nimport warnings\nfrom absl import logging\n@@ -100,6 +102,37 @@ def apply_primitive(prim, *args, **params):\n# TODO(phawkins): update code referring to xla.apply_primitive to point here.\nxla.apply_primitive = apply_primitive\n+RuntimeToken = Any\n+\n+class RuntimeTokenSet(threading.local):\n+ tokens: Dict[core.Effect, Tuple[RuntimeToken, Device]]\n+\n+ def __init__(self):\n+ self.tokens = {}\n+\n+ def get_token(self, eff: core.Effect, device: Device) -> RuntimeToken:\n+ if eff not in self.tokens:\n+ self.tokens[eff] = device_put(np.zeros(0, np.bool_), device), device\n+ elif self.tokens[eff][1] != device:\n+ (old_token,), _ = self.tokens[eff]\n+ old_token.aval = core.ShapedArray((0,), np.bool_)\n+ self.tokens[eff] = device_put(old_token, device), device\n+ return self.tokens[eff][0]\n+\n+ def update_token(self, eff: core.Effect, token: RuntimeToken):\n+ self.tokens[eff] = token, self.tokens[eff][1]\n+\n+ def clear(self):\n+ self.tokens = {}\n+\n+ def block_until_ready(self):\n+ [t[0].block_until_ready() for t, _ in self.tokens.values()]\n+\n+runtime_tokens: RuntimeTokenSet = RuntimeTokenSet()\n+\n+@atexit.register\n+def wait_for_tokens():\n+ runtime_tokens.block_until_ready()\n@util.cache()\ndef xla_primitive_callable(prim, *arg_specs: ArgSpec, **params):\n@@ -256,7 +289,8 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nif not jaxpr.eqns and not always_lower:\nreturn XlaComputation(\nname, None, True, None, None, jaxpr=jaxpr, consts=consts, device=device,\n- in_avals=abstract_args, out_avals=out_avals, kept_var_idx=kept_var_idx)\n+ in_avals=abstract_args, out_avals=out_avals, effects=jaxpr.effects,\n+ kept_var_idx=kept_var_idx)\nif not _on_exit:\nlog_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG\n@@ -291,13 +325,15 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nname_stack = util.new_name_stack(util.wrap_name(name, 'jit'))\nclosed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\nmodule_name = f\"jit_{fun.__name__}\"\n+ effects = [eff for eff in closed_jaxpr.effects if eff in core.ordered_effects]\nmodule = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, backend.platform,\n+ module_name, closed_jaxpr, effects, backend.platform,\nmlir.ReplicaAxisContext(axis_env), name_stack, donated_invars)\nreturn XlaComputation(\nname, module, False, donated_invars, which_explicit, nreps=nreps,\ndevice=device, backend=backend, tuple_args=tuple_args,\n- in_avals=abstract_args, out_avals=out_avals, kept_var_idx=kept_var_idx)\n+ in_avals=abstract_args, out_avals=out_avals, effects=effects,\n+ kept_var_idx=kept_var_idx)\ndef _backend_supports_unbounded_dynamic_shapes(backend: Backend) -> bool:\n@@ -544,27 +580,48 @@ def _check_special(name, xla_shape, buf):\nif config.jax_debug_infs and np.any(np.isinf(buf.to_py())):\nraise FloatingPointError(f\"invalid value (inf) encountered in {name}\")\n+def _add_tokens(effects: List[core.Effect], device, input_bufs):\n+ tokens = [runtime_tokens.get_token(eff, device) for eff in effects]\n+ tokens_flat = flatten(tokens)\n+ input_bufs = [*tokens_flat, *input_bufs]\n+ def _remove_tokens(output_bufs):\n+ token_bufs, output_bufs = util.split_list(output_bufs, [len(effects)])\n+ for eff, token_buf in zip(effects, token_bufs):\n+ runtime_tokens.update_token(eff, token_buf)\n+ return output_bufs\n+ return input_bufs, _remove_tokens\n+\ndef _execute_compiled(name: str, compiled: XlaExecutable,\ninput_handler: Optional[Callable],\noutput_buffer_counts: Optional[Sequence[int]],\n- result_handlers, kept_var_idx, *args):\n+ result_handlers,\n+ effects: List[core.Effect],\n+ kept_var_idx, *args):\ndevice, = compiled.local_devices()\nargs = input_handler(args) if input_handler else args\ninput_bufs_flat = flatten(device_put(x, device) for i, x in enumerate(args)\nif i in kept_var_idx)\n+ if effects:\n+ input_bufs_flat, token_handler = _add_tokens(effects, device, input_bufs_flat)\nout_bufs_flat = compiled.execute(input_bufs_flat)\ncheck_special(name, out_bufs_flat)\nif output_buffer_counts is None:\nreturn (result_handlers[0](*out_bufs_flat),)\nout_bufs = unflatten(out_bufs_flat, output_buffer_counts)\n+ if effects:\n+ out_bufs = token_handler(out_bufs)\nreturn tuple(h(*bs) for h, bs in unsafe_zip(result_handlers, out_bufs))\ndef _execute_replicated(name: str, compiled: XlaExecutable,\ninput_handler: Optional[Callable],\noutput_buffer_counts: Optional[Sequence[int]],\n- result_handlers, kept_var_idx, *args):\n+ result_handlers,\n+ effects: List[core.Effect],\n+ kept_var_idx, *args):\n+ if effects:\n+ raise NotImplementedError('Cannot execute replicated computation with effects.')\nif input_handler: raise NotImplementedError # TODO(mattjj, dougalm)\ninput_bufs = [flatten(device_put(x, device) for i, x in enumerate(args)\nif i in kept_var_idx)\n@@ -580,7 +637,7 @@ def _execute_replicated(name: str, compiled: XlaExecutable,\ndef _execute_trivial(jaxpr, device: Optional[Device], consts, avals, handlers,\n- kept_var_idx, *args):\n+ _: List[core.Effect], kept_var_idx, *args):\nenv = {core.unitvar: core.unit}\npruned_args = (x for i, x in enumerate(args) if i in kept_var_idx)\nmap(env.setdefault, jaxpr.invars, pruned_args)\n@@ -721,6 +778,7 @@ class XlaCompiledComputation(stages.Executable):\ntuple_args: bool,\nin_avals: Sequence[core.AbstractValue],\nout_avals: Sequence[core.AbstractValue],\n+ effects: List[core.Effect],\nkept_var_idx: Set[int]) -> XlaCompiledComputation:\nsticky_device = device\ninput_handler = _input_handler(backend, explicit_args, in_avals)\n@@ -735,9 +793,13 @@ class XlaCompiledComputation(stages.Executable):\ncompiled = compile_or_get_cached(backend, xla_computation, options)\nbuffer_counts = (None if len(out_avals) == 1 and not config.jax_dynamic_shapes\nelse [aval_to_num_buffers(aval) for aval in out_avals])\n+ if effects:\n+ if buffer_counts is None:\n+ buffer_counts = [1]\n+ buffer_counts = ([1] * len(effects)) + buffer_counts\nexecute = _execute_compiled if nreps == 1 else _execute_replicated\nunsafe_call = partial(execute, name, compiled, input_handler, buffer_counts,\n- result_handlers, kept_var_idx)\n+ result_handlers, effects, kept_var_idx)\nreturn XlaCompiledComputation(compiled, in_avals, kept_var_idx, unsafe_call)\ndef is_trivial(self):\n@@ -751,11 +813,11 @@ class XlaCompiledComputation(stages.Executable):\nreturn self._xla_executable\n@staticmethod\n- def from_trivial_jaxpr(jaxpr, consts, device, in_avals, out_avals,\n+ def from_trivial_jaxpr(jaxpr, consts, device, in_avals, out_avals, effects,\nkept_var_idx) -> XlaCompiledComputation:\nresult_handlers = map(partial(aval_to_result_handler, device), out_avals)\nunsafe_call = partial(_execute_trivial, jaxpr, device, consts,\n- out_avals, result_handlers, kept_var_idx)\n+ out_avals, result_handlers, effects, kept_var_idx)\nreturn XlaCompiledComputation(None, in_avals, kept_var_idx, unsafe_call)\n# -- stages.Executable protocol\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -473,8 +473,11 @@ def sharded_aval(aval: core.ShapedArray,\nsharded_shape.append((aval.shape[i] + partitions - 1) // partitions)\nreturn aval.update(tuple(sharded_shape))\n+\ndef lower_jaxpr_to_module(\n- module_name: str, jaxpr: core.ClosedJaxpr, platform: str,\n+ module_name: str, jaxpr: core.ClosedJaxpr,\n+ effects: List[core.Effect],\n+ platform: str,\naxis_context: AxisContext,\nname_stack: NameStack, donated_args: Sequence[bool],\nreplicated_args: Optional[Sequence[bool]] = None,\n@@ -504,6 +507,8 @@ def lower_jaxpr_to_module(\nif platform in platforms_with_donation:\ninput_output_aliases, donated_args = _set_up_aliases(\nin_avals, out_avals, donated_args)\n+ if any(eff not in lowerable_effects for eff in jaxpr.effects):\n+ raise ValueError(f'Cannot lower jaxpr with effects: {jaxpr.effects}')\nif any(donated_args):\n# TODO(tomhennigan): At call time we should mark these buffers as deleted.\nunused_donations = [str(a) for a, d in zip(in_avals, donated_args)\n@@ -528,7 +533,6 @@ def lower_jaxpr_to_module(\nif unlowerable_effects:\nraise ValueError(\nf'Cannot lower jaxpr with unlowerable effects: {unlowerable_effects}')\n- effects = [eff for eff in jaxpr.effects if eff in core.ordered_effects]\nlower_jaxpr_to_fun(\nctx, \"main\", jaxpr, effects, public=True, create_tokens=True,\nreplace_units_with_dummy=True,\n@@ -623,6 +627,12 @@ class TokenSet:\nnew_tokens.append(self._tokens[eff])\nreturn TokenSet(zip(self.effects(), new_tokens))\n+def dummy_token_type() -> Sequence[ir.Type]:\n+ return aval_to_ir_types(core.ShapedArray((0,), np.bool_))\n+\n+def dummy_token() -> Sequence[ir.Value]:\n+ return ir_constants(np.zeros(0, np.bool_))\n+\ndef lower_jaxpr_to_fun(\nctx: ModuleContext,\nname: str,\n@@ -650,6 +660,7 @@ def lower_jaxpr_to_fun(\njaxpr: the jaxpr to lower.\neffects: a sequence of `core.Effect`s corresponding to an ordering of tokens\nthat will be created in or used by the lowered function.\n+ create_tokens: if true, the MHLO will create tokens and ignore dummy input tokens.\npublic: if true, the function's visibility is set to \"public\".\nreplace_units_with_dummy: if true, unit arguments/return values are\nreplaced with bool arrays of size [0].\n@@ -676,10 +687,10 @@ def lower_jaxpr_to_fun(\ninput_types = map(aval_to_types, jaxpr.in_avals)\noutput_types = map(aval_to_types, jaxpr.out_avals)\n+ num_tokens = len(effects)\nif create_tokens:\n# If we create the tokens they won't be inputs to the MLIR function.\n- num_tokens = 0\n- token_types = []\n+ token_types = [dummy_token_type() for _ in effects]\nelse:\n# If we aren't creating tokens they will be the initial inputs to the\n# MLIR function.\n@@ -789,9 +800,8 @@ def lower_jaxpr_to_fun(\n*args)\nouts = []\nif create_tokens:\n- # If we created the tokens in this function, we are done with them and can\n- # ignore `tokens_out`.\n- pass\n+ for _ in effects:\n+ outs.append(dummy_token())\nelse:\nfor token in tokens_out.tokens():\nouts.append(token)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1053,8 +1053,9 @@ def lower_parallel_callable(\ntuple_args = should_tuple_args(shards)\nmodule_name = f\"pmap_{fun.__name__}\"\nwith maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\n+ effects = list(closed_jaxpr.effects)\nmodule = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, backend.platform, mlir.ReplicaAxisContext(axis_env),\n+ module_name, closed_jaxpr, effects, backend.platform, mlir.ReplicaAxisContext(axis_env),\nname_stack, donated_invars, replicated_args=replicated_args,\narg_shardings=_shardings_to_mlir_shardings(parts.arg_parts),\nresult_shardings=_shardings_to_mlir_shardings(parts.out_parts))\n@@ -2236,8 +2237,9 @@ def lower_mesh_computation(\nmodule: Union[str, xc.XlaComputation]\nmodule_name = f\"{api_name}_{fun_name}\"\nwith core.extend_axis_env_nd(mesh.shape.items()):\n+ effects = list(closed_jaxpr.effects)\nmodule = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, backend.platform, axis_ctx, name_stack,\n+ module_name, closed_jaxpr, effects, backend.platform, axis_ctx, name_stack,\ndonated_invars, replicated_args=replicated_args,\narg_shardings=in_partitions, result_shardings=out_partitions)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/sharded_jit.py", "new_path": "jax/interpreters/sharded_jit.py", "diff": "@@ -140,9 +140,11 @@ def _sharded_callable(\nfun.__name__, nparts, global_abstract_args)\naxis_env = xla.AxisEnv(nrep, (), ())\n+ effects = list(jaxpr.effects)\nmodule = mlir.lower_jaxpr_to_module(\n\"spjit_{}\".format(fun.__name__),\ncore.ClosedJaxpr(jaxpr, consts),\n+ effects,\nplatform=platform,\naxis_context=mlir.ReplicaAxisContext(axis_env),\nname_stack=new_name_stack(wrap_name(name, \"sharded_jit\")),\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n+import functools\n+import threading\n+import unittest\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -20,10 +23,12 @@ from jax import ad_checkpoint\nfrom jax import core\nfrom jax import lax\nfrom jax import linear_util as lu\n+from jax.config import config\nfrom jax.experimental import maps\nfrom jax.experimental import pjit\n-from jax.config import config\nfrom jax.interpreters import mlir\n+from jax._src import lib as jaxlib\n+from jax._src import dispatch\nfrom jax._src import test_util as jtu\nfrom jax._src import util\nimport numpy as np\n@@ -47,6 +52,7 @@ core.ordered_effects.add('foo2')\ndef trivial_effect_lowering(ctx, *, effect):\nctx.set_tokens_out(ctx.tokens_in)\nreturn []\n+mlir.register_lowering(effect_p, trivial_effect_lowering)\ndef function_effect_lowering(ctx, *, effect):\ndef _f(ctx):\n@@ -65,6 +71,58 @@ def function_effect_lowering(ctx, *, effect):\nctx.set_tokens_out(mlir.TokenSet(zip(ctx.tokens_in.effects(), tokens)))\nreturn out\n+callback_p = core.Primitive('callback')\n+callback_p.multiple_results = True\n+\n+mlir.lowerable_effects.add('log')\n+core.ordered_effects.add('log')\n+\n+@callback_p.def_impl\n+def _(*args, callback, out_avals, effect):\n+ del out_avals, effect\n+ callback(*args)\n+ return []\n+\n+@callback_p.def_effectful_abstract_eval\n+def _(*avals, callback, out_avals, effect):\n+ del avals, callback\n+ return out_avals, {effect}\n+\n+\n+# TODO(sharadmv): Attach keep alive to executable\n+leak = [].append\n+def callback_effect_lowering(ctx: mlir.LoweringRuleContext, *args, callback, out_avals, effect):\n+ del out_avals\n+ def _token_callback(token, *args):\n+ out = callback(*args)\n+ flat_out = jax.tree_util.tree_leaves(out)\n+ return (token, *flat_out)\n+ token_in = ctx.tokens_in.get(effect)[0]\n+ (token_out, *out_op), keep_alive = mlir.emit_python_callback(\n+ ctx.module_context.platform, _token_callback,\n+ [token_in, *args], [core.abstract_token, *ctx.avals_in],\n+ [core.abstract_token, *ctx.avals_out], True)\n+ leak(keep_alive)\n+ ctx.set_tokens_out(ctx.tokens_in.update_tokens(mlir.TokenSet({effect:\n+ token_out})))\n+ return out_op\n+\n+mlir.register_lowering(callback_p, callback_effect_lowering)\n+\n+\n+prev_xla_flags = None\n+\n+\n+def setUpModule():\n+ global prev_xla_flags\n+ # This will control the CPU devices. On TPU we always have 2 devices\n+ prev_xla_flags = jtu.set_host_platform_device_count(2)\n+\n+\n+# Reset to previous configuration in case other test modules will be run.\n+def tearDownModule():\n+ prev_xla_flags()\n+\nclass JaxprEffectsTest(jtu.JaxTestCase):\n@@ -210,6 +268,18 @@ class EffectfulJaxprLoweringTest(jtu.JaxTestCase):\nreturn []\nmlir.register_lowering(effect_p, _effect_lowering)\n+ def setUp(self):\n+ super().setUp()\n+ self.old_x64 = config.jax_enable_x64\n+ config.update('jax_enable_x64', False)\n+ dispatch.runtime_tokens.clear()\n+\n+ def tearDown(self):\n+ super().tearDown()\n+ dispatch.runtime_tokens.clear()\n+ config.update('jax_enable_x64', self.old_x64)\n+\n+ def test_cannot_lower_unlowerable_effect(self):\n@jax.jit\ndef f(x):\neffect_p.bind(effect='foo')\n@@ -350,6 +420,194 @@ class EffectfulJaxprLoweringTest(jtu.JaxTestCase):\nself.assertLen(list(func.type.inputs), 0)\nself.assertLen(list(func.type.results), 0)\n+ def test_lowered_jaxpr_without_ordered_effects_takes_no_dummy_inputs(self):\n+ @jax.jit\n+ def f(x):\n+ effect_p.bind(effect='bar')\n+ return x + 1.\n+ mhlo = f.lower(1.).compiler_ir(dialect='mhlo')\n+ input_types = mhlo.body.operations[0].type.inputs\n+ # First argument should be dummy token\n+ self.assertLen(list(input_types), 1)\n+ self.assertEqual(str(input_types[0]), 'tensor<f32>')\n+\n+ # First output should be dummy token\n+ result_types = mhlo.body.operations[0].type.results\n+ self.assertLen(list(result_types), 1)\n+ self.assertEqual(str(result_types[0]), 'tensor<f32>')\n+\n+ def test_lowered_jaxpr_with_ordered_effects_takes_in_dummy_inputs(self):\n+ @jax.jit\n+ def f(x):\n+ effect_p.bind(effect='foo')\n+ return x + 1.\n+ mhlo = f.lower(1.).compiler_ir(dialect='mhlo')\n+ input_types = mhlo.body.operations[0].type.inputs\n+ # First argument should be dummy token\n+ self.assertLen(list(input_types), 2)\n+ self.assertEqual(str(input_types[0]), 'tensor<0xi1>')\n+\n+ # First output should be dummy token\n+ result_types = mhlo.body.operations[0].type.results\n+ self.assertLen(list(result_types), 2)\n+ self.assertEqual(str(result_types[0]), 'tensor<0xi1>')\n+\n+ def test_lowered_jaxpr_with_multiple_ordered_effects_takes_in_dummy_inputs(self):\n+ @jax.jit\n+ def f(x):\n+ effect_p.bind(effect='foo')\n+ effect_p.bind(effect='foo2')\n+ return x + 1.\n+ mhlo = f.lower(1.).compiler_ir(dialect='mhlo')\n+ input_types = mhlo.body.operations[0].type.inputs\n+ # First two arguments should be dummy values\n+ self.assertLen(list(input_types), 3)\n+ self.assertEqual(str(input_types[0]), 'tensor<0xi1>')\n+ self.assertEqual(str(input_types[1]), 'tensor<0xi1>')\n+\n+ # First two outputs should be dummy values\n+ result_types = mhlo.body.operations[0].type.results\n+ self.assertLen(list(result_types), 3)\n+ self.assertEqual(str(result_types[0]), 'tensor<0xi1>')\n+ self.assertEqual(str(result_types[1]), 'tensor<0xi1>')\n+\n+ def test_can_lower_and_run_jaxpr_with_ordered_effects(self):\n+ @jax.jit\n+ def f(x):\n+ effect_p.bind(effect='foo')\n+ return x + 1.\n+ self.assertEqual(f(2.), 3.)\n+\n+ def test_can_lower_and_run_jaxpr_with_unordered_effects(self):\n+ @jax.jit\n+ def f(x):\n+ effect_p.bind(effect='bar')\n+ return x + 1.\n+ self.assertEqual(f(2.), 3.)\n+\n+ def test_runtime_tokens_should_update_after_running_effectful_function(self):\n+ @jax.jit\n+ def f(x):\n+ effect_p.bind(effect='foo')\n+ return x + 1.\n+ self.assertNotIn('foo', dispatch.runtime_tokens.tokens)\n+ f(2.)\n+ prev_token = dispatch.runtime_tokens.tokens['foo']\n+ f(2.)\n+ curr_token = dispatch.runtime_tokens.tokens['foo']\n+ self.assertIsNot(prev_token, curr_token)\n+\n+ def test_can_lower_multiple_effects(self):\n+ @jax.jit\n+ def f(x):\n+ effect_p.bind(effect='foo')\n+ effect_p.bind(effect='foo2')\n+ return x + 1.\n+ @jax.jit\n+ def g(x):\n+ effect_p.bind(effect='foo')\n+ return x + 1.\n+ self.assertNotIn('foo', dispatch.runtime_tokens.tokens)\n+ self.assertNotIn('foo2', dispatch.runtime_tokens.tokens)\n+ f(2.)\n+ foo_token = dispatch.runtime_tokens.tokens['foo'][0]\n+ foo2_token = dispatch.runtime_tokens.tokens['foo'][0]\n+ f(2.)\n+ self.assertIsNot(foo_token, dispatch.runtime_tokens.tokens['foo'][0])\n+ self.assertIsNot(foo2_token, dispatch.runtime_tokens.tokens['foo2'][0])\n+ foo_token = dispatch.runtime_tokens.tokens['foo'][0]\n+ foo2_token = dispatch.runtime_tokens.tokens['foo2'][0]\n+ g(2.)\n+ self.assertIsNot(foo_token, dispatch.runtime_tokens.tokens['foo'][0])\n+ self.assertIs(foo2_token, dispatch.runtime_tokens.tokens['foo2'][0])\n+\n+class EffectOrderingTest(jtu.JaxTestCase):\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_execute_python_callback(self):\n+ # TODO(sharadmv): remove jaxlib check when minimum version is bumped\n+ # TODO(sharadmv): enable this test on GPU and TPU when backends are\n+ # supported\n+ if jaxlib.version < (0, 3, 8):\n+ raise unittest.SkipTest(\"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\n+ log = []\n+ def log_value(x):\n+ log.append(x)\n+ return ()\n+\n+ @jax.jit\n+ def f(x):\n+ return callback_p.bind(x, callback=log_value, effect='log', out_avals=[])\n+\n+ f(2.)\n+ self.assertListEqual(log, [2.])\n+ f(3.)\n+ self.assertListEqual(log, [2., 3.])\n+ dispatch.runtime_tokens.block_until_ready()\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_ordered_effect_remains_ordered_across_multiple_devices(self):\n+ # TODO(sharadmv): remove jaxlib check when minimum version is bumped\n+ # TODO(sharadmv): enable this test on GPU and TPU when backends are\n+ # supported\n+ if jaxlib.version < (0, 3, 8):\n+ raise unittest.SkipTest(\"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices.\")\n+ log = []\n+ def log_value(x):\n+ log.append(x)\n+ return ()\n+\n+ @functools.partial(jax.jit, device=jax.devices()[0])\n+ def f(x):\n+ # Expensive computation\n+ x = x.dot(x)\n+ x = jnp.log(x.sum())\n+ return callback_p.bind(x, callback=log_value, effect='log', out_avals=[])\n+\n+ @functools.partial(jax.jit, device=jax.devices()[1])\n+ def g(x):\n+ return callback_p.bind(x, callback=log_value, effect='log', out_avals=[])\n+\n+ f(jnp.ones((500, 500)))\n+ g(3.)\n+ f(jnp.ones((500, 500)))\n+ g(3.)\n+ f(jnp.ones((500, 500)))\n+ g(3.)\n+ dispatch.runtime_tokens.block_until_ready()\n+ x_, y_ = float(jnp.log(1.25e8)), 3.\n+ expected_log = [x_, y_, x_, y_, x_, y_]\n+ self.assertListEqual(log, expected_log)\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_different_threads_get_different_tokens(self):\n+ # TODO(sharadmv): remove jaxlib check when minimum version is bumped\n+ # TODO(sharadmv): enable this test on GPU and TPU when backends are\n+ # supported\n+ if jaxlib.version < (0, 3, 8):\n+ raise unittest.SkipTest(\"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices.\")\n+ tokens = []\n+ def _noop(_):\n+ tokens.append(dispatch.runtime_tokens.tokens['log'][0])\n+ return ()\n+\n+ @functools.partial(jax.jit, device=jax.devices()[0])\n+ def f(x):\n+ return callback_p.bind(x, callback=_noop, effect='log', out_avals=[])\n+\n+ t1 = threading.Thread(target=lambda: f(2.))\n+ t2 = threading.Thread(target=lambda: f(3.))\n+ t1.start()\n+ t2.start()\n+ t1.join()\n+ t2.join()\n+ token1, token2 = tokens\n+ self.assertIsNot(token1, token2)\n+\nclass ControlFlowEffectsTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Add in runtime tokens for effectful jaxprs
260,510
14.04.2022 14:18:31
25,200
ef982cfa8c2b94273208828954f6afd50133ea7e
Attach keepalive to executable
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -815,7 +815,7 @@ def xla_computation(fun: Callable,\nout_parts_flat = tuple(flatten_axes(\n\"xla_computation out_parts\", out_tree(), out_parts))\neffects = list(jaxpr.effects)\n- m = mlir.lower_jaxpr_to_module(\n+ m, _ = mlir.lower_jaxpr_to_module(\nf\"xla_computation_{fun_name}\",\ncore.ClosedJaxpr(jaxpr, consts),\neffects=effects,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -290,7 +290,7 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nreturn XlaComputation(\nname, None, True, None, None, jaxpr=jaxpr, consts=consts, device=device,\nin_avals=abstract_args, out_avals=out_avals, effects=jaxpr.effects,\n- kept_var_idx=kept_var_idx)\n+ kept_var_idx=kept_var_idx, keepalive=None)\nif not _on_exit:\nlog_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG\n@@ -326,14 +326,14 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nclosed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\nmodule_name = f\"jit_{fun.__name__}\"\neffects = [eff for eff in closed_jaxpr.effects if eff in core.ordered_effects]\n- module = mlir.lower_jaxpr_to_module(\n+ module, keepalive = mlir.lower_jaxpr_to_module(\nmodule_name, closed_jaxpr, effects, backend.platform,\nmlir.ReplicaAxisContext(axis_env), name_stack, donated_invars)\nreturn XlaComputation(\nname, module, False, donated_invars, which_explicit, nreps=nreps,\ndevice=device, backend=backend, tuple_args=tuple_args,\nin_avals=abstract_args, out_avals=out_avals, effects=effects,\n- kept_var_idx=kept_var_idx)\n+ kept_var_idx=kept_var_idx, keepalive=keepalive)\ndef _backend_supports_unbounded_dynamic_shapes(backend: Backend) -> bool:\n@@ -761,11 +761,15 @@ def compile_or_get_cached(backend, computation, compile_options):\nclass XlaCompiledComputation(stages.Executable):\n- def __init__(self, xla_executable, in_avals, kept_var_idx, unsafe_call):\n+ def __init__(self, xla_executable, in_avals, kept_var_idx, unsafe_call,\n+ keepalive: Any):\nself._xla_executable = xla_executable\nself.in_avals = in_avals\nself._kept_var_idx = kept_var_idx\nself.unsafe_call = unsafe_call\n+ # Only the `unsafe_call` function is cached, so to avoid the `keepalive`\n+ # being garbage collected we attach it to `unsafe_call`.\n+ self.unsafe_call.keepalive = keepalive\n@staticmethod\ndef from_xla_computation(\n@@ -779,7 +783,8 @@ class XlaCompiledComputation(stages.Executable):\nin_avals: Sequence[core.AbstractValue],\nout_avals: Sequence[core.AbstractValue],\neffects: List[core.Effect],\n- kept_var_idx: Set[int]) -> XlaCompiledComputation:\n+ kept_var_idx: Set[int],\n+ keepalive: Optional[Any]) -> XlaCompiledComputation:\nsticky_device = device\ninput_handler = _input_handler(backend, explicit_args, in_avals)\nresult_handlers = map(partial(aval_to_result_handler, sticky_device),\n@@ -800,7 +805,8 @@ class XlaCompiledComputation(stages.Executable):\nexecute = _execute_compiled if nreps == 1 else _execute_replicated\nunsafe_call = partial(execute, name, compiled, input_handler, buffer_counts,\nresult_handlers, effects, kept_var_idx)\n- return XlaCompiledComputation(compiled, in_avals, kept_var_idx, unsafe_call)\n+ return XlaCompiledComputation(compiled, in_avals, kept_var_idx, unsafe_call,\n+ keepalive)\ndef is_trivial(self):\nreturn self._xla_executable == None\n@@ -814,11 +820,13 @@ class XlaCompiledComputation(stages.Executable):\n@staticmethod\ndef from_trivial_jaxpr(jaxpr, consts, device, in_avals, out_avals, effects,\n- kept_var_idx) -> XlaCompiledComputation:\n+ kept_var_idx, keepalive: Optional[Any]) -> XlaCompiledComputation:\n+ assert keepalive is None\nresult_handlers = map(partial(aval_to_result_handler, device), out_avals)\nunsafe_call = partial(_execute_trivial, jaxpr, device, consts,\nout_avals, result_handlers, effects, kept_var_idx)\n- return XlaCompiledComputation(None, in_avals, kept_var_idx, unsafe_call)\n+ return XlaCompiledComputation(None, in_avals, kept_var_idx, unsafe_call,\n+ keepalive)\n# -- stages.Executable protocol\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -365,6 +365,7 @@ class ModuleContext:\nplatform: str\naxis_context: AxisContext\nname_stack: NameStack\n+ keepalives: List[Any]\n# Cached primitive lowerings.\ncached_primitive_lowerings: Dict[Any, func_dialect.FuncOp]\n@@ -378,6 +379,7 @@ class ModuleContext:\nplatform: str,\naxis_context: AxisContext,\nname_stack: NameStack,\n+ keepalives: List[Any],\ncontext: Optional[ir.Context] = None,\nmodule: Optional[ir.Module] = None,\nip: Optional[ir.InsertionPoint] = None,\n@@ -393,6 +395,10 @@ class ModuleContext:\nself.name_stack = name_stack\nself.cached_primitive_lowerings = ({} if cached_primitive_lowerings is None\nelse cached_primitive_lowerings)\n+ self.keepalives = keepalives\n+\n+ def add_keepalive(self, keepalive: Any) -> None:\n+ self.keepalives.append(keepalive)\ndef replace(self, **kw): return dataclasses.replace(self, **kw)\n@@ -483,7 +489,7 @@ def lower_jaxpr_to_module(\nreplicated_args: Optional[Sequence[bool]] = None,\narg_shardings: Optional[Sequence[Optional[xc.OpSharding]]] = None,\nresult_shardings: Optional[Sequence[Optional[xc.OpSharding]]] = None\n- ) -> ir.Module:\n+ ) -> Tuple[ir.Module, Optional[Any]]:\n\"\"\"Lowers a top-level jaxpr to an MHLO module.\nHandles the quirks of the argument/return value passing conventions of the\n@@ -518,7 +524,9 @@ def lower_jaxpr_to_module(\nmsg = f\"Donation is not implemented for {platform}.\\n{msg}\"\nwarnings.warn(f\"Some donated buffers were not usable: {', '.join(unused_donations)}.\\n{msg}\")\n- ctx = ModuleContext(platform, axis_context, name_stack)\n+ # Create a keepalives list that will be mutated during the lowering.\n+ keepalives: List[Any] = []\n+ ctx = ModuleContext(platform, axis_context, name_stack, keepalives)\nwith ctx.context, ir.Location.unknown(ctx.context):\n# Remove module name characters that XLA would alter. This ensures that\n# XLA computation preserves the module name.\n@@ -541,7 +549,7 @@ def lower_jaxpr_to_module(\ninput_output_aliases=input_output_aliases)\nctx.module.operation.verify()\n- return ctx.module\n+ return ctx.module, ctx.keepalives\ndef module_to_string(module: ir.Module) -> str:\noutput = io.StringIO()\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1054,11 +1054,13 @@ def lower_parallel_callable(\nmodule_name = f\"pmap_{fun.__name__}\"\nwith maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\neffects = list(closed_jaxpr.effects)\n- module = mlir.lower_jaxpr_to_module(\n+ # TODO(sharadmv): attach keepalive to computation\n+ module, keepalive = mlir.lower_jaxpr_to_module(\nmodule_name, closed_jaxpr, effects, backend.platform, mlir.ReplicaAxisContext(axis_env),\nname_stack, donated_invars, replicated_args=replicated_args,\narg_shardings=_shardings_to_mlir_shardings(parts.arg_parts),\nresult_shardings=_shardings_to_mlir_shardings(parts.out_parts))\n+ del keepalive\nreturn PmapComputation(module, pci=pci, replicas=replicas, parts=parts,\nshards=shards, tuple_args=tuple_args)\n@@ -2238,10 +2240,12 @@ def lower_mesh_computation(\nmodule_name = f\"{api_name}_{fun_name}\"\nwith core.extend_axis_env_nd(mesh.shape.items()):\neffects = list(closed_jaxpr.effects)\n- module = mlir.lower_jaxpr_to_module(\n+ # TODO(sharadmv): attach keepalive to computation\n+ module, keepalive = mlir.lower_jaxpr_to_module(\nmodule_name, closed_jaxpr, effects, backend.platform, axis_ctx, name_stack,\ndonated_invars, replicated_args=replicated_args,\narg_shardings=in_partitions, result_shardings=out_partitions)\n+ del keepalive\nreturn MeshComputation(\nstr(name_stack), module, donated_invars, mesh=mesh, global_in_avals=global_in_avals,\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/sharded_jit.py", "new_path": "jax/interpreters/sharded_jit.py", "diff": "@@ -141,7 +141,7 @@ def _sharded_callable(\naxis_env = xla.AxisEnv(nrep, (), ())\neffects = list(jaxpr.effects)\n- module = mlir.lower_jaxpr_to_module(\n+ module, _ = mlir.lower_jaxpr_to_module(\n\"spjit_{}\".format(fun.__name__),\ncore.ClosedJaxpr(jaxpr, consts),\neffects,\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -88,9 +88,6 @@ def _(*avals, callback, out_avals, effect):\ndel avals, callback\nreturn out_avals, {effect}\n-\n-# TODO(sharadmv): Attach keep alive to executable\n-leak = [].append\ndef callback_effect_lowering(ctx: mlir.LoweringRuleContext, *args, callback, out_avals, effect):\ndel out_avals\ndef _token_callback(token, *args):\n@@ -102,7 +99,7 @@ def callback_effect_lowering(ctx: mlir.LoweringRuleContext, *args, callback, out\nctx.module_context.platform, _token_callback,\n[token_in, *args], [core.abstract_token, *ctx.avals_in],\n[core.abstract_token, *ctx.avals_out], True)\n- leak(keep_alive)\n+ ctx.module_context.add_keepalive(keep_alive)\nctx.set_tokens_out(ctx.tokens_in.update_tokens(mlir.TokenSet({effect:\ntoken_out})))\nreturn out_op\n" } ]
Python
Apache License 2.0
google/jax
Attach keepalive to executable
260,510
03.05.2022 16:50:11
25,200
7a641de7a7d96b5bc6da9875a47300c392294029
Add initial debug print implementation
[ { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/debugging.py", "diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Module for JAX debugging primitives and related functionality.\"\"\"\n+import enum\n+import functools\n+import sys\n+\n+from typing import Callable, Any\n+\n+from jax import core\n+from jax import tree_util\n+from jax.interpreters import ad\n+from jax.interpreters import batching\n+from jax.interpreters import mlir\n+\n+DebugEffect = enum.Enum('DebugEffect', ['PRINT', 'ORDERED_PRINT'])\n+\n+core.ordered_effects.add(DebugEffect.ORDERED_PRINT)\n+mlir.lowerable_effects.add(DebugEffect.PRINT)\n+mlir.lowerable_effects.add(DebugEffect.ORDERED_PRINT)\n+\n+# `debug_callback_p` is the main primitive for staging out Python callbacks.\n+debug_callback_p = core.Primitive('debug_callback')\n+debug_callback_p.multiple_results = True\n+\n+@debug_callback_p.def_impl\n+def debug_callback_impl(*flat_args, callback: Callable[..., Any],\n+ effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n+ del effect\n+ args, kwargs = tree_util.tree_unflatten(in_tree, flat_args)\n+ out = callback(*args, **kwargs)\n+ return tree_util.tree_leaves(out)\n+\n+@debug_callback_p.def_effectful_abstract_eval\n+def debug_callback_abstract_eval(*flat_avals, callback: Callable[..., Any],\n+ effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n+ del flat_avals, callback, in_tree\n+ return [], {effect}\n+\n+def debug_callback_batching_rule(*flat_args, callback: Callable[..., Any],\n+ effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n+ del flat_args, callback, effect, in_tree\n+ # TODO(sharadmv): implement batching rule\n+ raise NotImplementedError('Batching not supported for `debug_callback`.')\n+batching.primitive_batchers[debug_callback_p] = debug_callback_batching_rule\n+\n+def debug_callback_jvp_rule(*flat_args, callback: Callable[..., Any],\n+ effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n+ del flat_args, callback, effect, in_tree\n+ # TODO(sharadmv): implement jvp rule\n+ raise NotImplementedError('JVP not supported for `debug_callback`.')\n+ad.primitive_jvps[debug_callback_p] = debug_callback_jvp_rule\n+\n+def debug_callback_transpose_rule(*flat_args, callback: Callable[..., Any],\n+ effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n+ del flat_args, callback, effect, in_tree\n+ # TODO(sharadmv): implement transpose rule\n+ raise NotImplementedError('Transpose not supported for `debug_callback`.')\n+ad.primitive_transposes[debug_callback_p] = debug_callback_transpose_rule\n+\n+# TODO(sharadmv): remove this global keepalive list in favor of attaching\n+# keepalives to the module context.\n+_keepalives = []\n+\n+def _ordered_effect_lowering(ctx, token, *args, **params):\n+ avals_in = [core.abstract_token, *ctx.avals_in]\n+ avals_out = [core.abstract_token, *ctx.avals_out]\n+ args = (token, *args)\n+ def _callback(token, *flat_args):\n+ out = debug_callback_p.impl(*flat_args, **params)\n+ return (token, *out)\n+ (token, *result), keepalive = mlir.emit_python_callback(\n+ ctx.module_context.platform, _callback, list(args), avals_in, avals_out,\n+ True)\n+ return result, keepalive, token\n+\n+def debug_callback_lowering(ctx, *args, effect, callback, **params):\n+ if effect in core.ordered_effects:\n+ token = ctx.tokens_in.get(effect)[0]\n+ result, keepalive, token = _ordered_effect_lowering(ctx, token,\n+ *args, effect=effect, callback=callback, **params)\n+ ctx.set_tokens_out(mlir.TokenSet({effect: (token,)}))\n+ else:\n+ def _callback(*flat_args):\n+ return tuple(debug_callback_p.impl(\n+ *flat_args, effect=effect, callback=callback, **params))\n+ result, keepalive = mlir.emit_python_callback(ctx.module_context.platform,\n+ _callback, list(args), ctx.avals_in, ctx.avals_out, True)\n+ _keepalives.append(keepalive)\n+ return result\n+mlir.register_lowering(debug_callback_p, debug_callback_lowering,\n+ platform=\"cpu\")\n+\n+def debug_callback(callback: Callable[..., Any], effect: DebugEffect, *args,\n+ **kwargs):\n+ \"\"\"Calls a stageable Python callback.\n+\n+ `debug_callback` enables you to pass in a Python function that can be called\n+ inside of a staged JAX program. A `debug_callback` follows existing JAX\n+ transformation *pure* operational semantics, which are therefore unaware of\n+ side-effects. This means the effect could be dropped, duplicated, or\n+ potentially reordered in the presence of higher-order primitives and\n+ transformations.\n+\n+ We want this behavior because we'd like `debug_callback` to be \"innocuous\",\n+ i.e. we want these primitives to change the JAX computation as little as\n+ possible while revealing as much about them as possible, such as which parts\n+ of the computation are duplicated or dropped.\n+\n+ Args:\n+ callback: A Python callable.\n+ effect: A `DebugEffect`.\n+ *args: The positional arguments to the callback.\n+ **kwargs: The positional arguments to the callback.\n+ Returns:\n+ The value of `callback(*args, **kwargs)`.\n+ \"\"\"\n+ if not isinstance(effect, DebugEffect):\n+ raise ValueError(\"Can only use `DebugEffect` effects in `debug_callback`\")\n+ flat_args, in_tree = tree_util.tree_flatten((args, kwargs))\n+ return debug_callback_p.bind(*flat_args, callback=callback, effect=effect,\n+ in_tree=in_tree)\n+\n+def _format_print_callback(fmt: str, *args, **kwargs):\n+ sys.stdout.write(fmt.format(*args, **kwargs) + \"\\n\")\n+\n+def debug_print(fmt: str, *args, ordered=False, **kwargs) -> None:\n+ \"\"\"Prints values and works in staged out JAX functions.\n+\n+ Args:\n+ fmt: A format string, e.g. `\"hello {x}\"`, that will be used to format\n+ input arguments.\n+ *args: A list of positional arguments to be formatted.\n+ ordered: A keyword only argument used to indicate whether or not the\n+ staged out computation will enforce ordering of this `debug_print` w.r.t.\n+ other ordered `debug_print`s.\n+ **kwargs: Additional keyword arguments to be formatted.\n+ \"\"\"\n+ effect = DebugEffect.ORDERED_PRINT if ordered else DebugEffect.PRINT\n+ debug_callback(functools.partial(_format_print_callback, fmt), effect, *args,\n+ **kwargs)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/debugging_primitives_test.py", "diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+import contextlib\n+import io\n+import unittest\n+from unittest import mock\n+\n+from typing import Callable, Generator\n+\n+from absl.testing import absltest\n+import jax\n+from jax.config import config\n+from jax._src import debugging\n+from jax._src import lib as jaxlib\n+from jax._src import test_util as jtu\n+\n+config.parse_flags_with_absl()\n+\n+debug_print = debugging.debug_print\n+\n+@contextlib.contextmanager\n+def capture_stdout() -> Generator[Callable[[], str], None, None]:\n+ with mock.patch('sys.stdout', new_callable=io.StringIO) as fp:\n+ def _read() -> str:\n+ return fp.getvalue()\n+ yield _read\n+\n+class DebugPrintTest(jtu.JaxTestCase):\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_simple_debug_print_works_in_eager_mode(self):\n+ def f(x):\n+ debug_print('x: {}', x)\n+ with capture_stdout() as output:\n+ f(2)\n+ self.assertEqual(output(), \"x: 2\\n\")\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_debug_print_works_with_named_format_strings(self):\n+ def f(x):\n+ debug_print('x: {x}', x=x)\n+ with capture_stdout() as output:\n+ f(2)\n+ self.assertEqual(output(), \"x: 2\\n\")\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_multiple_debug_prints_should_print_multiple_values(self):\n+ def f(x):\n+ debug_print('x: {x}', x=x)\n+ debug_print('y: {y}', y=x + 1)\n+ with capture_stdout() as output:\n+ f(2)\n+ self.assertEqual(output(), \"x: 2\\ny: 3\\n\")\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_stage_out_debug_print(self):\n+ if jaxlib.version < (0, 3, 8):\n+ raise unittest.SkipTest(\n+ \"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\n+ @jax.jit\n+ def f(x):\n+ debug_print('x: {x}', x=x)\n+ with capture_stdout() as output:\n+ f(2)\n+ self.assertEqual(output(), \"x: 2\\n\")\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_stage_out_ordered_print(self):\n+ if jaxlib.version < (0, 3, 8):\n+ raise unittest.SkipTest(\n+ \"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\n+ @jax.jit\n+ def f(x):\n+ debug_print('x: {x}', x=x, ordered=True)\n+ with capture_stdout() as output:\n+ f(2)\n+ self.assertEqual(output(), \"x: 2\\n\")\n+\n+\n+if jaxlib.version < (0, 3, 8):\n+ # No lowering for `emit_python_callback` in older jaxlibs.\n+ del DebugPrintTest\n+\n+if __name__ == '__main__':\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add initial debug print implementation Co-authored-by: Matthew Johnson <mattjj@google.com>
260,510
03.05.2022 20:53:30
25,200
78a4e30651c676037bcf043435a07ab19845a577
Don't leak the keepalive in debug_callback lowering
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugging.py", "new_path": "jax/_src/debugging.py", "diff": "@@ -69,10 +69,6 @@ def debug_callback_transpose_rule(*flat_args, callback: Callable[..., Any],\nraise NotImplementedError('Transpose not supported for `debug_callback`.')\nad.primitive_transposes[debug_callback_p] = debug_callback_transpose_rule\n-# TODO(sharadmv): remove this global keepalive list in favor of attaching\n-# keepalives to the module context.\n-_keepalives = []\n-\ndef _ordered_effect_lowering(ctx, token, *args, **params):\navals_in = [core.abstract_token, *ctx.avals_in]\navals_out = [core.abstract_token, *ctx.avals_out]\n@@ -97,7 +93,7 @@ def debug_callback_lowering(ctx, *args, effect, callback, **params):\n*flat_args, effect=effect, callback=callback, **params))\nresult, keepalive = mlir.emit_python_callback(ctx.module_context.platform,\n_callback, list(args), ctx.avals_in, ctx.avals_out, True)\n- _keepalives.append(keepalive)\n+ ctx.module_context.add_keepalive(keepalive)\nreturn result\nmlir.register_lowering(debug_callback_p, debug_callback_lowering,\nplatform=\"cpu\")\n" } ]
Python
Apache License 2.0
google/jax
Don't leak the keepalive in debug_callback lowering
260,335
04.05.2022 09:42:20
25,200
0c5864a2203c3f7249bff171355a9e70dc0f7ec2
add xla_client._version checks for mhlo.ConstOp signature fix break from
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -208,6 +208,7 @@ def _numpy_array_constant(x: np.ndarray, canonicalize_types\nif canonicalize_types:\nx = np.asarray(x, dtypes.canonicalize_dtype(x.dtype))\nelement_type = dtype_to_ir_type(x.dtype)\n+ ir_type = ir.RankedTensorType.get(x.shape, element_type)\nshape = x.shape\nif x.dtype == np.bool_:\nnelems = x.size\n@@ -220,7 +221,11 @@ def _numpy_array_constant(x: np.ndarray, canonicalize_types\nx = x.view(np.uint16)\nx = np.ascontiguousarray(x)\nattr = ir.DenseElementsAttr.get(x, type=element_type, shape=shape)\n+ if jax._src.lib.xla_extension_version >= 64:\nreturn (mhlo.ConstOp(attr).result,)\n+ else:\n+ return (mhlo.ConstOp(ir_type, attr).result,)\n+\ndef _ndarray_constant_handler(val: np.ndarray, canonicalize_types\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/lapack.py", "new_path": "jaxlib/lapack.py", "diff": "@@ -26,6 +26,7 @@ for _name, _value in _lapack.registrations().items():\nxla_client.register_custom_call_target(_name, _value, platform=\"cpu\")\n+if xla_client._version >= 64:\ndef _mhlo_u8(x):\nreturn mhlo.ConstOp(\nir.DenseElementsAttr.get(np.array(x, dtype=np.uint8),\n@@ -35,6 +36,18 @@ def _mhlo_s32(x):\nreturn mhlo.ConstOp(\nir.DenseElementsAttr.get(np.array(x, dtype=np.int32),\ntype=ir.IntegerType.get_signless(32))).result\n+else:\n+ def _mhlo_u8(x):\n+ typ = ir.RankedTensorType.get([], ir.IntegerType.get_unsigned(8))\n+ return mhlo.ConstOp(\n+ typ,\n+ ir.DenseElementsAttr.get(np.array(x, dtype=np.uint8),\n+ type=typ.element_type)).result\n+\n+ def _mhlo_s32(x):\n+ typ = ir.RankedTensorType.get([], ir.IntegerType.get_signless(32))\n+ return mhlo.ConstOp(\n+ typ, ir.DenseElementsAttr.get(np.array(x, dtype=np.int32))).result\n# TODO(phawkins): it would be nice to avoid duplicating code for each type.\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/pocketfft.py", "new_path": "jaxlib/pocketfft.py", "diff": "@@ -160,8 +160,13 @@ def pocketfft_mhlo(a, dtype, *, fft_type: FftType, fft_lengths: List[int]):\nraise ValueError(f\"Unknown output type {out_dtype}\")\nif 0 in a_type.shape or 0 in out_shape:\n+ if xla_client._version >= 64:\nzero = mhlo.ConstOp(\nir.DenseElementsAttr.get(np.array(0, dtype=out_dtype), type=out_type))\n+ else:\n+ zero = mhlo.ConstOp(ir.RankedTensorType.get([], out_type),\n+ ir.DenseElementsAttr.get(np.array(0, dtype=out_dtype),\n+ type=out_type))\nif jax._src.lib.mlir_api_version < 9:\nreturn mhlo.BroadcastOp(\nir.RankedTensorType.get(out_shape, out_type),\n@@ -173,7 +178,13 @@ def pocketfft_mhlo(a, dtype, *, fft_type: FftType, fft_lengths: List[int]):\nir.DenseElementsAttr.get(np.asarray(out_shape, np.int64))).result\nu8_type = ir.IntegerType.get_unsigned(8)\n+ if xla_client._version >= 64:\n+ descriptor = mhlo.ConstOp(\n+ ir.DenseElementsAttr.get(np.frombuffer(descriptor_bytes, dtype=np.uint8),\n+ type=u8_type))\n+ else:\ndescriptor = mhlo.ConstOp(\n+ ir.RankedTensorType.get([len(descriptor_bytes)], u8_type),\nir.DenseElementsAttr.get(np.frombuffer(descriptor_bytes, dtype=np.uint8),\ntype=u8_type))\nlayout = ir.DenseIntElementsAttr.get(np.arange(n - 1, -1, -1),\n" } ]
Python
Apache License 2.0
google/jax
add xla_client._version checks for mhlo.ConstOp signature fix break from 0cf08d0c6841332240cae873e4b4cf9a9b313373
260,510
04.05.2022 11:11:02
25,200
dc42d7bb8e60be2b44396a89dbc4f07174b6c721
Enable print in while loops/scan
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugging.py", "new_path": "jax/_src/debugging.py", "diff": "@@ -23,12 +23,15 @@ from jax import tree_util\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\n+from jax._src.lax import control_flow as lcf\nDebugEffect = enum.Enum('DebugEffect', ['PRINT', 'ORDERED_PRINT'])\ncore.ordered_effects.add(DebugEffect.ORDERED_PRINT)\nmlir.lowerable_effects.add(DebugEffect.PRINT)\nmlir.lowerable_effects.add(DebugEffect.ORDERED_PRINT)\n+lcf.allowed_effects.add(DebugEffect.PRINT)\n+lcf.allowed_effects.add(DebugEffect.ORDERED_PRINT)\n# `debug_callback_p` is the main primitive for staging out Python callbacks.\ndebug_callback_p = core.Primitive('debug_callback')\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -24,7 +24,7 @@ import inspect\nimport itertools\nimport operator\nimport os\n-from typing import Any, Callable, Optional, Sequence, Tuple, TypeVar, List\n+from typing import Any, Callable, Optional, Sequence, Set, Tuple, TypeVar, List\nimport numpy as np\n@@ -66,6 +66,8 @@ T = TypeVar('T')\nArray = Any\nBooleanNumeric = Any # A bool, or a Boolean array.\n+allowed_effects: Set[core.Effect] = set()\n+\n@cache()\ndef _initial_style_open_jaxpr(fun: Callable, in_tree, in_avals,\nprimitive_name: Optional[str] = None):\n@@ -321,8 +323,11 @@ def while_loop(cond_fun: Callable[[T], BooleanNumeric],\n_check_tree_and_avals(\"body_fun output and input\",\nbody_tree, body_jaxpr.out_avals,\nin_tree_children[0], init_avals)\n- if cond_jaxpr.effects or body_jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `while`.')\n+ effects = core.join_effects(cond_jaxpr.effects, body_jaxpr.effects)\n+ disallowed_effects = effects - allowed_effects\n+ if disallowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `while`: {disallowed_effects}')\nouts = while_p.bind(*cond_consts, *body_consts, *init_vals,\ncond_nconsts=len(cond_consts), cond_jaxpr=cond_jaxpr,\nbody_nconsts=len(body_consts), body_jaxpr=body_jaxpr)\n@@ -330,9 +335,11 @@ def while_loop(cond_fun: Callable[[T], BooleanNumeric],\ndef _while_loop_abstract_eval(*args, cond_jaxpr, body_jaxpr, **kwargs):\ndel args, kwargs\n- if cond_jaxpr.effects or body_jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `while_loop`.')\njoined_effects = core.join_effects(cond_jaxpr.effects, body_jaxpr.effects)\n+ disallowed_effects = joined_effects - allowed_effects\n+ if disallowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `while`: {disallowed_effects}')\nreturn _map(raise_to_shaped, body_jaxpr.out_avals), joined_effects\n@@ -572,9 +579,20 @@ def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\nbody_nconsts):\npred_aval = cond_jaxpr.out_avals[0]\nbatched = bool(pred_aval.shape)\n+ if cond_jaxpr.effects:\n+ # TODO(sharadmv): enable effects in cond\n+ raise NotImplementedError(\n+ '`while_loop` with effects in `cond` not supported.')\nloop_carry_types = _map(mlir.aval_to_ir_types, ctx.avals_in)\n+ body_effects = [eff for eff in body_jaxpr.effects\n+ if eff in core.ordered_effects]\n+ num_tokens = len(body_effects)\n+ tokens = [ctx.tokens_in.get(eff) for eff in body_effects]\n+ token_types = [mlir.token_type() for _ in tokens]\n+ loop_carry_types = [*token_types, *loop_carry_types]\nflat_loop_carry_types = util.flatten(loop_carry_types)\n+ args = [*tokens, *args]\nflat_args = mlir.flatten_lowering_ir_args(args)\nwhile_op = mhlo.WhileOp(flat_loop_carry_types, flat_args)\n@@ -582,13 +600,13 @@ def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\n# Loop condition\ncond_block = while_op.regions[0].blocks.append(*flat_loop_carry_types)\nname_stack = extend_name_stack(ctx.module_context.name_stack, 'while')\n- if cond_jaxpr.effects:\n- raise NotImplementedError('`while_loop` with effects in `cond` not supported.')\nwith ir.InsertionPoint(cond_block):\nflat_cond_args = [\ncond_block.arguments[i] for i in range(len(flat_loop_carry_types))\n]\ncond_args = util.unflatten(flat_cond_args, _map(len, loop_carry_types))\n+ # Remove tokens from cond args\n+ cond_args = cond_args[num_tokens:]\nx, _, z = util.split_list(cond_args, [cond_nconsts, body_nconsts])\ncond_ctx = ctx.module_context.replace(\nname_stack=xla.extend_name_stack(name_stack, 'cond'))\n@@ -618,14 +636,15 @@ def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\nbody_block.arguments[i] for i in range(len(flat_loop_carry_types))\n]\nbody_args = util.unflatten(flat_body_args, _map(len, loop_carry_types))\n+ # Tokens are at the front of the args list to the while loop\n+ token_args, body_args = util.split_list(body_args, [num_tokens])\n+ tokens_in = mlir.TokenSet(zip(body_effects, token_args))\nx, y, z = util.split_list(body_args, [cond_nconsts, body_nconsts])\nbody_ctx = ctx.module_context.replace(\nname_stack=xla.extend_name_stack(name_stack, 'body'))\n- if body_jaxpr.effects:\n- raise NotImplementedError('`while_loop` with effects in `body` not supported.')\n- new_z, _ = mlir.jaxpr_subcomp(body_ctx, body_jaxpr.jaxpr, mlir.TokenSet(),\n- _map(mlir.ir_constants, body_jaxpr.consts),\n- *(y + z))\n+ new_z, tokens_out = mlir.jaxpr_subcomp(body_ctx, body_jaxpr.jaxpr,\n+ tokens_in, _map(mlir.ir_constants, body_jaxpr.consts), *(y + z))\n+ out_tokens = [tokens_out.get(eff) for eff in body_effects]\nif batched:\nbody_pred_ctx = ctx.module_context.replace(\nname_stack=xla.extend_name_stack(name_stack,\n@@ -637,10 +656,13 @@ def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\npartial(_pred_bcast_select_mhlo, pred_aval, body_pred), new_z, z,\nbody_jaxpr.out_avals)\n- mhlo.ReturnOp([*util.flatten(x), *util.flatten(y), *util.flatten(new_z)])\n+ mhlo.ReturnOp([*util.flatten(out_tokens), *util.flatten(x),\n+ *util.flatten(y), *util.flatten(new_z)])\noutputs = util.unflatten(while_op.results, _map(len, loop_carry_types))\n- _, _, z = util.split_list(outputs, [cond_nconsts, body_nconsts])\n+ tokens, _, _, z = util.split_list(outputs, [num_tokens, cond_nconsts, body_nconsts])\n+ if tokens:\n+ ctx.set_tokens_out(mlir.TokenSet(zip(body_effects, tokens)))\nreturn z\nmlir.register_lowering(while_p, _while_lowering)\n@@ -1419,8 +1441,10 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\n# Extract the subtree and avals for the first element of the return tuple\nout_tree_children[0], carry_avals_out,\ninit_tree, carry_avals)\n- if jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `scan`.')\n+ disallowed_effects = jaxpr.effects - allowed_effects\n+ if disallowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `scan`: {disallowed_effects}')\nout = scan_p.bind(*consts, *in_flat,\nreverse=reverse, length=length, jaxpr=jaxpr,\n@@ -1613,11 +1637,9 @@ def _prepend_dim_to_aval(sz, aval):\ndef _scan_abstract_eval(*args, reverse, length, num_consts, num_carry, jaxpr,\nlinear, unroll):\n- if jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `scan`.')\ncarry_avals, y_avals = split_list(jaxpr.out_avals, [num_carry])\nys_avals = _map(partial(_prepend_dim_to_aval, length), y_avals)\n- return carry_avals + ys_avals, core.no_effects\n+ return carry_avals + ys_avals, jaxpr.effects\ndef _scan_jvp(primals, tangents, reverse, length, jaxpr, num_consts, num_carry,\nlinear, unroll):\n@@ -2053,7 +2075,7 @@ def _scan_typecheck(bind_time, *avals, reverse, length, num_consts, num_carry,\nraise core.JaxprTypeError(\nf'scan jaxpr takes input sequence types\\n{_avals_short(x_avals_jaxpr)},\\n'\nf'called with sequence of type\\n{_avals_short(x_avals)}')\n- return None, core.no_effects\n+ return None, jaxpr.effects\ndef scan_bind(*args, **params):\nif config.jax_enable_checks:\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -2285,10 +2285,13 @@ def _check_jaxpr(\nelse:\nout_avals, effects = check_eqn(prim, in_avals, eqn.params)\nif eqn.effects != effects:\n- raise JaxprTypeError(\"Inferred effects do not match equation effects.\")\n+ raise JaxprTypeError(\"Inferred effects do not match equation effects. \"\n+ f\"Equation effects: {eqn.effects}. \"\n+ f\"Jaxpr effects: {effects}\")\nif not eqn.effects.issubset(jaxpr.effects):\nraise JaxprTypeError(\"Equation effects are not subset of Jaxpr effects. \"\n- f\"Equation effects: {eqn.effects}. Jaxpr effects: {jaxpr.effects}\")\n+ f\"Equation effects: {eqn.effects}. \"\n+ f\"Jaxpr effects: {jaxpr.effects}\")\nmap(write, eqn.outvars, out_avals)\nexcept JaxprTypeError as e:\nctx, settings = ctx_factory()\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "# limitations under the License.\nimport contextlib\nimport io\n-import unittest\n+import textwrap\nfrom unittest import mock\nfrom typing import Callable, Generator\nfrom absl.testing import absltest\n+from absl.testing import parameterized\nimport jax\n+from jax import lax\nfrom jax.config import config\nfrom jax._src import debugging\nfrom jax._src import lib as jaxlib\nfrom jax._src import test_util as jtu\n+import jax.numpy as jnp\nconfig.parse_flags_with_absl()\n@@ -36,6 +39,9 @@ def capture_stdout() -> Generator[Callable[[], str], None, None]:\nreturn fp.getvalue()\nyield _read\n+def _format_multiline(text):\n+ return textwrap.dedent(text).lstrip()\n+\nclass DebugPrintTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n@@ -65,9 +71,6 @@ class DebugPrintTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_can_stage_out_debug_print(self):\n- if jaxlib.version < (0, 3, 8):\n- raise unittest.SkipTest(\n- \"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\n@jax.jit\ndef f(x):\ndebug_print('x: {x}', x=x)\n@@ -77,9 +80,6 @@ class DebugPrintTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_can_stage_out_ordered_print(self):\n- if jaxlib.version < (0, 3, 8):\n- raise unittest.SkipTest(\n- \"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\n@jax.jit\ndef f(x):\ndebug_print('x: {x}', x=x, ordered=True)\n@@ -88,9 +88,74 @@ class DebugPrintTest(jtu.JaxTestCase):\nself.assertEqual(output(), \"x: 2\\n\")\n+class DebugPrintControlFlowTest(jtu.JaxTestCase):\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\n+ for ordered in [False, True]))\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_print_inside_scan(self, ordered):\n+ def f(xs):\n+ def _body(carry, x):\n+ debug_print(\"carry: {carry}\", carry=carry, ordered=ordered)\n+ debug_print(\"x: {x}\", x=x, ordered=ordered)\n+ return carry + 1, x + 1\n+ return lax.scan(_body, 2, xs)\n+ with capture_stdout() as output:\n+ f(jnp.arange(2))\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ carry: 2\n+ x: 0\n+ carry: 3\n+ x: 1\n+ \"\"\"))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\n+ for ordered in [False, True]))\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_print_inside_for_loop(self, ordered):\n+ def f(x):\n+ def _body(i, x):\n+ debug_print(\"x: {x}\", x=x, ordered=ordered)\n+ return x + 1\n+ return lax.fori_loop(0, 5, _body, x)\n+ with capture_stdout() as output:\n+ f(2)\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ x: 2\n+ x: 3\n+ x: 4\n+ x: 5\n+ x: 6\n+ \"\"\"))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\n+ for ordered in [False, True]))\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_print_inside_while_loop(self, ordered):\n+ def f(x):\n+ def _cond(x):\n+ return x < 10\n+ def _body(x):\n+ debug_print(\"x: {x}\", x=x, ordered=ordered)\n+ return x + 1\n+ return lax.while_loop(_cond, _body, x)\n+ with capture_stdout() as output:\n+ f(5)\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ x: 5\n+ x: 6\n+ x: 7\n+ x: 8\n+ x: 9\n+ \"\"\"))\n+\nif jaxlib.version < (0, 3, 8):\n# No lowering for `emit_python_callback` in older jaxlibs.\ndel DebugPrintTest\n+ del DebugPrintControlFlowTest\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -31,6 +31,7 @@ from jax._src import lib as jaxlib\nfrom jax._src import dispatch\nfrom jax._src import test_util as jtu\nfrom jax._src import util\n+from jax._src.lax import control_flow as lcf\nimport numpy as np\nconfig.parse_flags_with_absl()\n@@ -45,8 +46,17 @@ def _(*, effect):\nmlir.lowerable_effects.add('foo')\nmlir.lowerable_effects.add('foo2')\nmlir.lowerable_effects.add('bar')\n+mlir.lowerable_effects.add('while')\n+mlir.lowerable_effects.add('while1')\n+mlir.lowerable_effects.add('while2')\ncore.ordered_effects.add('foo')\ncore.ordered_effects.add('foo2')\n+core.ordered_effects.add('while1')\n+core.ordered_effects.add('while2')\n+\n+lcf.allowed_effects.add('while')\n+lcf.allowed_effects.add('while1')\n+lcf.allowed_effects.add('while2')\ndef trivial_effect_lowering(ctx, *, effect):\n@@ -257,24 +267,27 @@ class HigherOrderPrimitiveTest(jtu.JaxTestCase):\nclass EffectfulJaxprLoweringTest(jtu.JaxTestCase):\n- def test_should_pass_tokens_into_ordered_effect(self):\n-\n- def _effect_lowering(ctx, *, effect):\n- self.assertListEqual(list(ctx.tokens_in.effects()), ['foo'])\n- ctx.set_tokens_out(ctx.tokens_in)\n- return []\n- mlir.register_lowering(effect_p, _effect_lowering)\n-\ndef setUp(self):\nsuper().setUp()\nself.old_x64 = config.jax_enable_x64\nconfig.update('jax_enable_x64', False)\n+ self._old_lowering = mlir._lowerings[effect_p]\n+ def _effect_lowering(ctx, *, effect):\n+ if effect in core.ordered_effects:\n+ expected_effects = [effect]\n+ else:\n+ expected_effects = []\n+ self.assertListEqual(list(ctx.tokens_in.effects()), expected_effects)\n+ ctx.set_tokens_out(ctx.tokens_in)\n+ return []\n+ mlir.register_lowering(effect_p, _effect_lowering)\ndispatch.runtime_tokens.clear()\ndef tearDown(self):\nsuper().tearDown()\ndispatch.runtime_tokens.clear()\nconfig.update('jax_enable_x64', self.old_x64)\n+ mlir.register_lowering(effect_p, self._old_lowering)\ndef test_cannot_lower_unlowerable_effect(self):\n@jax.jit\n@@ -631,6 +644,37 @@ class ControlFlowEffectsTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(NotImplementedError, 'Effects not supported'):\njax.make_jaxpr(f2)(2.)\n+ def test_allowed_effect_in_while_body(self):\n+ def f(x):\n+ def cond_fun(x):\n+ return False\n+ def body_fun(x):\n+ effect_p.bind(effect='while')\n+ return x\n+ return lax.while_loop(cond_fun, body_fun, x)\n+ f(2)\n+\n+ def test_allowed_ordered_effect_in_while_body(self):\n+ def f(x):\n+ def cond_fun(x):\n+ return False\n+ def body_fun(x):\n+ effect_p.bind(effect='while1')\n+ return x\n+ return lax.while_loop(cond_fun, body_fun, x)\n+ f(2)\n+\n+ def test_multiple_allowed_ordered_effect_in_while_body(self):\n+ def f(x):\n+ def cond_fun(x):\n+ return False\n+ def body_fun(x):\n+ effect_p.bind(effect='while1')\n+ effect_p.bind(effect='while2')\n+ return x\n+ return lax.while_loop(cond_fun, body_fun, x)\n+ f(2)\n+\ndef test_effects_disallowed_in_while(self):\ndef f1(x):\ndef cond_fun(x):\n@@ -654,6 +698,31 @@ class ControlFlowEffectsTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(NotImplementedError, 'Effects not supported'):\njax.make_jaxpr(f2)(2.)\n+ def test_allowed_effect_in_scan(self):\n+ def f(x):\n+ def body_fun(carry, x):\n+ effect_p.bind(effect='while')\n+ return carry, x\n+ return lax.scan(body_fun, x, jnp.arange(5))\n+ f(2)\n+\n+ def test_allowed_ordered_effect_in_scan(self):\n+ def f(x):\n+ def body_fun(carry, x):\n+ effect_p.bind(effect='while1')\n+ return carry, x\n+ return lax.scan(body_fun, x, jnp.arange(5))\n+ f(2)\n+\n+ def test_multiple_allowed_ordered_effect_in_scan(self):\n+ def f(x):\n+ def body_fun(carry, x):\n+ effect_p.bind(effect='while1')\n+ effect_p.bind(effect='while2')\n+ return carry, x\n+ return lax.scan(body_fun, x, jnp.arange(5))\n+ f(2)\n+\ndef test_effects_disallowed_in_scan(self):\ndef f(x):\n" } ]
Python
Apache License 2.0
google/jax
Enable print in while loops/scan
260,510
04.05.2022 15:46:05
25,200
4703766f61cfb310fafe3e22ce95d2ab4cd872b6
Enable effects for cond in while loop
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -577,10 +577,52 @@ def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\nbody_nconsts):\npred_aval = cond_jaxpr.out_avals[0]\nbatched = bool(pred_aval.shape)\n- if cond_jaxpr.effects:\n- # TODO(sharadmv): enable effects in cond\n- raise NotImplementedError(\n- '`while_loop` with effects in `cond` not supported.')\n+ cond_ordered_effects = [eff for eff in cond_jaxpr.effects if eff in\n+ core.ordered_effects]\n+ if cond_ordered_effects:\n+ # For a while loop with ordered effects in the cond, we need a special\n+ # lowering. Fundamentally, we'd like to rewrite a while loop that looks like\n+ # this:\n+ # ```\n+ # while cond(x):\n+ # x = body(x)\n+ # ```\n+ # into something that looks like this:\n+ # ```\n+ # while True:\n+ # token, pred = cond(token, x)\n+ # if not pred:\n+ # break\n+ # token, x = body(token, x)\n+ # ```\n+ # Unfortunately, with an MHLO while we can't (1) return multiple values\n+ # from a `cond` and (2) can't break a while loop. We thus adopt the\n+ # following rewrite strategy:\n+ # ```\n+ # def new_cond(pred, token, x):\n+ # return pred\n+ # token, pred = cond(token, x)\n+ # while new_cond(pred, token, x):\n+ # token, x = body(token, x)\n+ # token, pred = cond(token, x)\n+ # ```\n+ def cond(args):\n+ return core.eval_jaxpr(cond_jaxpr.jaxpr, cond_jaxpr.consts, *args)[0]\n+ def body(args):\n+ return tuple(core.eval_jaxpr(body_jaxpr.jaxpr, body_jaxpr.consts, *args))\n+ def new_cond(pred_args):\n+ pred, _ = pred_args\n+ return pred\n+ def new_body(pred_args):\n+ _, args = pred_args\n+ args = body(args)\n+ pred = cond(args)\n+ return pred, args\n+ def fun(*args):\n+ pred = cond(args)\n+ _, out = while_loop(new_cond, new_body, (pred, args))\n+ return out\n+ return mlir.lower_fun(fun)(ctx, *args)\nloop_carry_types = _map(mlir.aval_to_ir_types, ctx.avals_in)\nbody_effects = [eff for eff in body_jaxpr.effects\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -134,7 +134,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\nfor ordered in [False, True]))\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n- def test_can_print_inside_while_loop(self, ordered):\n+ def test_can_print_inside_while_loop_body(self, ordered):\ndef f(x):\ndef _cond(x):\nreturn x < 10\n@@ -152,6 +152,36 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nx: 9\n\"\"\"))\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\n+ for ordered in [False, True]))\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_print_inside_while_loop_cond(self, ordered):\n+ def f(x):\n+ def _cond(x):\n+ debug_print(\"x: {x}\", x=x, ordered=ordered)\n+ return x < 10\n+ def _body(x):\n+ return x + 1\n+ return lax.while_loop(_cond, _body, x)\n+ with capture_stdout() as output:\n+ f(5)\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ x: 5\n+ x: 6\n+ x: 7\n+ x: 8\n+ x: 9\n+ x: 10\n+ \"\"\"))\n+\n+ with capture_stdout() as output:\n+ f(10)\n+ # Should run the cond once\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ x: 10\n+ \"\"\"))\n+\nif jaxlib.version < (0, 3, 8):\n# No lowering for `emit_python_callback` in older jaxlibs.\ndel DebugPrintTest\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -654,6 +654,16 @@ class ControlFlowEffectsTest(jtu.JaxTestCase):\nreturn lax.while_loop(cond_fun, body_fun, x)\nf(2)\n+ def test_allowed_effect_in_cond_body(self):\n+ def f(x):\n+ def cond_fun(x):\n+ effect_p.bind(effect='while')\n+ return False\n+ def body_fun(x):\n+ return x\n+ return lax.while_loop(cond_fun, body_fun, x)\n+ f(2)\n+\ndef test_allowed_ordered_effect_in_while_body(self):\ndef f(x):\ndef cond_fun(x):\n" } ]
Python
Apache License 2.0
google/jax
Enable effects for cond in while loop
260,510
04.05.2022 17:42:50
25,200
c1a8d7fb573fd57fb37c7b075839c00c06107544
Enable batching rule for debug_print
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugging.py", "new_path": "jax/_src/debugging.py", "diff": "@@ -20,10 +20,13 @@ from typing import Callable, Any\nfrom jax import core\nfrom jax import tree_util\n+from jax import lax\n+from jax._src import util\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax._src.lax import control_flow as lcf\n+import jax.numpy as jnp\nDebugEffect = enum.Enum('DebugEffect', ['PRINT', 'ORDERED_PRINT'])\n@@ -37,6 +40,8 @@ lcf.allowed_effects.add(DebugEffect.ORDERED_PRINT)\ndebug_callback_p = core.Primitive('debug_callback')\ndebug_callback_p.multiple_results = True\n+map, unsafe_map = util.safe_map, map\n+\n@debug_callback_p.def_impl\ndef debug_callback_impl(*flat_args, callback: Callable[..., Any],\neffect: DebugEffect, in_tree: tree_util.PyTreeDef):\n@@ -51,11 +56,23 @@ def debug_callback_abstract_eval(*flat_avals, callback: Callable[..., Any],\ndel flat_avals, callback, in_tree\nreturn [], {effect}\n-def debug_callback_batching_rule(*flat_args, callback: Callable[..., Any],\n- effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n- del flat_args, callback, effect, in_tree\n- # TODO(sharadmv): implement batching rule\n- raise NotImplementedError('Batching not supported for `debug_callback`.')\n+def debug_callback_batching_rule(args, dims, **params):\n+ \"\"\"Unrolls the debug callback across the mapped axis.\"\"\"\n+ axis_size = next(x.shape[i] for x, i in zip(args, dims)\n+ if i is not None)\n+ # TODO(sharadmv): implement in terms of rolled loop unstead of\n+ # unrolled.\n+ def get_arg_at_dim(i, dim, arg):\n+ if dim is batching.not_mapped:\n+ # Broadcast unmapped argument\n+ return arg\n+ return lax.index_in_dim(arg, i, axis=dim, keepdims=False)\n+ outs = []\n+ for i in range(axis_size):\n+ args_idx = map(functools.partial(get_arg_at_dim, i), dims, args)\n+ outs.append(debug_callback_p.bind(*args_idx, **params))\n+ outs = [jnp.stack(xs) for xs in zip(*outs)]\n+ return outs, (0,) * len(outs)\nbatching.primitive_batchers[debug_callback_p] = debug_callback_batching_rule\ndef debug_callback_jvp_rule(*flat_args, callback: Callable[..., Any],\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\nimport contextlib\n+import functools\nimport io\nimport textwrap\nfrom unittest import mock\n@@ -27,6 +28,7 @@ from jax._src import debugging\nfrom jax._src import lib as jaxlib\nfrom jax._src import test_util as jtu\nimport jax.numpy as jnp\n+import numpy as np\nconfig.parse_flags_with_absl()\n@@ -87,6 +89,53 @@ class DebugPrintTest(jtu.JaxTestCase):\nf(2)\nself.assertEqual(output(), \"x: 2\\n\")\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_stage_out_ordered_print_with_pytree(self):\n+ @jax.jit\n+ def f(x):\n+ struct = dict(foo=x)\n+ debug_print('x: {}', struct, ordered=True)\n+ with capture_stdout() as output:\n+ f(np.array(2, np.int32))\n+ self.assertEqual(output(), f\"x: {str(dict(foo=np.array(2, np.int32)))}\\n\")\n+\n+class DebugPrintTransformationTest(jtu.JaxTestCase):\n+\n+ def test_debug_print_batching(self):\n+ @jax.vmap\n+ def f(x):\n+ debug_print('hello: {}', x)\n+ with capture_stdout() as output:\n+ f(jnp.arange(2))\n+ self.assertEqual(output(), \"hello: 0\\nhello: 1\\n\")\n+\n+ def test_debug_print_batching_with_diff_axes(self):\n+ @functools.partial(jax.vmap, in_axes=(0, 1))\n+ def f(x, y):\n+ debug_print('hello: {} {}', x, y)\n+ with capture_stdout() as output:\n+ f(jnp.arange(2), jnp.arange(2)[None])\n+ self.assertEqual(output(), \"hello: 0 [0]\\nhello: 1 [1]\\n\")\n+\n+ def tested_debug_print_with_nested_vmap(self):\n+ def f(x):\n+ debug_print('hello: {}', x)\n+ # Call with\n+ # [[0, 1],\n+ # [2, 3],\n+ # [4, 5]]\n+ with capture_stdout() as output:\n+ # Should print over 0-axis then 1-axis\n+ jax.vmap(jax.vmap(f))(jnp.arange(6).reshape((3, 2)))\n+ self.assertEqual(\n+ output(),\n+ \"hello: 0\\nhello: 2\\nhello: 4\\nhello: 1\\nhello: 3\\nhello: 5\\n\")\n+ with capture_stdout() as output:\n+ # Should print over 1-axis then 0-axis\n+ jax.vmap(jax.vmap(f, in_axes=0), in_axes=1)(jnp.arange(6).reshape((3, 2)))\n+ self.assertEqual(\n+ output(),\n+ \"hello: 0\\nhello: 1\\nhello: 2\\nhello: 3\\nhello: 4\\nhello: 5\\n\")\nclass DebugPrintControlFlowTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Enable batching rule for debug_print Co-authored-by: Matthew Johnson <mattjj@google.com>
260,631
05.05.2022 07:11:42
25,200
ef18220158d50f85c8e22ff8e7a216f20db0eadd
Updated documentation for approx_*_k to specify when the top k is guaranteed to be ordered.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/ann.py", "new_path": "jax/_src/lax/ann.py", "diff": "@@ -101,10 +101,10 @@ def approx_max_k(operand: Array,\nrecall. This option is useful when the given ``operand`` is only a subset\nof the overall computation in SPMD or distributed pipelines, where the\ntrue input size cannot be deferred by the operand shape.\n- aggregate_to_topk : When true, aggregates approximate results to top-k. When\n- false, returns the approximate results. The number of the approximate\n- results is implementation defined and is greater equals to the specified\n- ``k``.\n+ aggregate_to_topk : When true, aggregates approximate results to the top-k\n+ in sorted order. When false, returns the approximate results unsorted. In\n+ this case, the number of the approximate results is implementation defined\n+ and is greater or equal to the specified ``k``.\nReturns:\nTuple of two arrays. The arrays are the max ``k`` values and the\n@@ -160,10 +160,10 @@ def approx_min_k(operand: Array,\nrecall. This option is useful when the given operand is only a subset of\nthe overall computation in SPMD or distributed pipelines, where the true\ninput size cannot be deferred by the ``operand`` shape.\n- aggregate_to_topk: When true, aggregates approximate results to top-k. When\n- false, returns the approximate results. The number of the approximate\n- results is implementation defined and is greater equals to the specified\n- ``k``.\n+ aggregate_to_topk : When true, aggregates approximate results to the top-k\n+ in sorted order. When false, returns the approximate results unsorted. In\n+ this case, the number of the approximate results is implementation defined\n+ and is greater or equal to the specified ``k``.\nReturns:\nTuple of two arrays. The arrays are the least ``k`` values and the\n" } ]
Python
Apache License 2.0
google/jax
Updated documentation for approx_*_k to specify when the top k is guaranteed to be ordered. PiperOrigin-RevId: 446708610
260,510
04.05.2022 17:58:09
25,200
4296cb1c2bc1a109b2f4f815de46ac5d831c972f
Enable AD rules for `debug_print`
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugging.py", "new_path": "jax/_src/debugging.py", "diff": "@@ -78,15 +78,16 @@ batching.primitive_batchers[debug_callback_p] = debug_callback_batching_rule\ndef debug_callback_jvp_rule(*flat_args, callback: Callable[..., Any],\neffect: DebugEffect, in_tree: tree_util.PyTreeDef):\ndel flat_args, callback, effect, in_tree\n- # TODO(sharadmv): implement jvp rule\n- raise NotImplementedError('JVP not supported for `debug_callback`.')\n+ # TODO(sharadmv): link to relevant documentation when it exists\n+ raise ValueError(\n+ \"JVP doesn't support debugging callbacks. \"\n+ \"Instead, you can use them with `jax.custom_jvp` or `jax.custom_vjp`.\")\nad.primitive_jvps[debug_callback_p] = debug_callback_jvp_rule\ndef debug_callback_transpose_rule(*flat_args, callback: Callable[..., Any],\neffect: DebugEffect, in_tree: tree_util.PyTreeDef):\ndel flat_args, callback, effect, in_tree\n- # TODO(sharadmv): implement transpose rule\n- raise NotImplementedError('Transpose not supported for `debug_callback`.')\n+ raise ValueError(\"Transpose doesn't support debugging callbacks.\")\nad.primitive_transposes[debug_callback_p] = debug_callback_transpose_rule\ndef _ordered_effect_lowering(ctx, token, *args, **params):\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -137,6 +137,30 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\noutput(),\n\"hello: 0\\nhello: 1\\nhello: 2\\nhello: 3\\nhello: 4\\nhello: 5\\n\")\n+ def test_debug_print_jvp_rule(self):\n+ def f(x):\n+ debug_print('should never be called: {}', x)\n+ with self.assertRaisesRegex(\n+ ValueError, \"JVP doesn't support debugging callbacks\"):\n+ jax.jvp(f, (1.,), (1.,))\n+\n+ def test_debug_print_vjp_rule(self):\n+ def f(x):\n+ debug_print('should never be called: {}', x)\n+ with self.assertRaisesRegex(\n+ ValueError, \"JVP doesn't support debugging callbacks\"):\n+ jax.vjp(f, 1.)\n+\n+ def test_debug_print_transpose_rule(self):\n+ def f(x):\n+ debug_print('should never be called: {}', x)\n+ return x\n+ with capture_stdout() as output:\n+ jax.linear_transpose(f, 1.)(1.)\n+ # `debug_print` should be dropped by `partial_eval` because of no\n+ # output data-dependence.\n+ self.assertEqual(output(), \"\")\n+\nclass DebugPrintControlFlowTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n" } ]
Python
Apache License 2.0
google/jax
Enable AD rules for `debug_print`
260,335
05.05.2022 13:16:44
25,200
b92c6b1e4d3ec577761a886fd4daec863ce9f9d6
fix ad_checkpoint.checkpoint vmap rule
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_checkpoint.py", "new_path": "jax/_src/ad_checkpoint.py", "diff": "@@ -305,6 +305,7 @@ def remat_partial_eval(trace, *tracers, jaxpr, **params):\npolicy = params['policy'] or (lambda *_, **__: False)\n# unzip into jaxpr_known and jaxpr_unknown\nin_unknowns = [not t.is_known() for t in tracers]\n+ # TODO(mattjj): use cached version of pe.partial_eval_jaxpr_custom\njaxpr_known, jaxpr_unknown, out_unknowns, out_inst, _ = \\\npe._partial_eval_jaxpr_custom(jaxpr, in_unknowns, policy)\njaxpr_known, in_used_known = pe.dce_jaxpr(jaxpr_known, [True] * len(jaxpr_known.outvars))\n@@ -374,11 +375,10 @@ ad.reducing_transposes[remat_p] = remat_transpose\ndef remat_vmap(axis_size, axis_name, main_type, args, dims, *, jaxpr, **params):\nassert not jaxpr.constvars\n- in_batched = [d is not batching.not_mapped for d in dims]\njaxpr_ = core.ClosedJaxpr(jaxpr, ())\n- jaxpr_batched_, out_batched = batching.batch_jaxpr(\n- jaxpr_, axis_size, in_batched, instantiate=False, axis_name=axis_name,\n- main_type=main_type)\n+ jaxpr_batched_, out_batched = batching.batch_jaxpr_axes(\n+ jaxpr_, axis_size, dims, [batching.zero_if_mapped] * len(jaxpr.outvars),\n+ axis_name=axis_name, main_type=main_type)\njaxpr_batched, consts = jaxpr_batched_.jaxpr, jaxpr_batched_.consts\nout_dims = [0 if b else None for b in out_batched]\nreturn remat_p.bind(*consts, *args, jaxpr=jaxpr_batched, **params), out_dims\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -29,7 +29,8 @@ from jax._src.ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval,\nfrom jax import linear_util as lu\nfrom jax._src.util import (unzip2, unzip3, safe_map, safe_zip, wrap_name,\nsplit_list, canonicalize_axis, moveaxis,\n- as_hashable_function, curry, memoize, cache)\n+ as_hashable_function, curry, memoize,\n+ weakref_lru_cache)\nfrom jax.interpreters import partial_eval as pe\nmap = safe_map\n@@ -473,9 +474,9 @@ def batch_jaxpr_axes(closed_jaxpr, axis_size, in_axes, out_axes_dest, axis_name,\nreturn _batch_jaxpr_axes(closed_jaxpr, axis_size, tuple(in_axes),\ntuple(out_axes_dest), axis_name, main_type)\n-@cache()\n-def _batch_jaxpr_axes(closed_jaxpr, axis_size, in_axes, out_axes_dest, axis_name,\n- main_type):\n+@weakref_lru_cache\n+def _batch_jaxpr_axes(closed_jaxpr, axis_size, in_axes, out_axes_dest,\n+ axis_name, main_type):\nf = lu.wrap_init(core.jaxpr_as_fun(closed_jaxpr))\nf, out_batched = _batch_jaxpr_inner(f, axis_size, out_axes_dest)\nf = _batch_jaxpr_outer(f, axis_name, axis_size, in_axes, main_type)\n@@ -527,7 +528,8 @@ def _merge_bdims(x, y):\nelse:\nreturn x # arbitrary\n-zero_if_mapped = object()\n+class ZeroIfMapped: pass\n+zero_if_mapped = ZeroIfMapped()\n### functions for handling custom_vjp\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3631,6 +3631,24 @@ class RematTest(jtu.JaxTestCase):\nexpected = np.diag(np.cos(np.sin(x)) * np.cos(x))\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', api.remat),\n+ ('_policy', partial(api.remat, policy=lambda *_, **__: False)),\n+ ('_new', partial(new_checkpoint, policy=lambda *_, **__: False)),\n+ ])\n+ def test_remat_vmap_not_leading_dim(self, remat):\n+ @remat\n+ def g(x):\n+ return lax.sin(lax.sin(x))\n+\n+ x = np.arange(3 * 5.).reshape(3, 5)\n+\n+ ans = api.vmap(g, 1, 0)(x)\n+ expected = np.sin(np.sin(x)).T\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n@parameterized.named_parameters(\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n" } ]
Python
Apache License 2.0
google/jax
fix ad_checkpoint.checkpoint vmap rule
260,510
04.05.2022 14:37:40
25,200
3941e76f6c3c872034b3c337fe48c43f1881ea8a
Enable effects for cond
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -789,8 +789,11 @@ def switch(index, branches: Sequence[Callable], *operands,\n_check_tree_and_avals(f\"branch 0 and {i + 1} outputs\",\nout_trees[0], jaxprs[0].out_avals,\nout_tree, jaxpr.out_avals)\n- if any(b.effects for b in jaxprs):\n- raise NotImplementedError('Effects not supported in `switch`.')\n+ joined_effects = core.join_effects(*(jaxpr.effects for jaxpr in jaxprs))\n+ disallowed_effects = joined_effects - allowed_effects\n+ if disallowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `switch`: {disallowed_effects}')\nlinear = (False,) * (len(consts) + len(ops))\nout = cond_p.bind(\n@@ -877,8 +880,11 @@ def _cond(pred, true_fun: Callable, false_fun: Callable, *operands,\n_check_tree_and_avals(\"true_fun and false_fun output\",\nout_tree, true_jaxpr.out_avals,\nfalse_out_tree, false_jaxpr.out_avals)\n- if any(b.effects for b in jaxprs):\n- raise NotImplementedError('Effects not supported in `cond`.')\n+ joined_effects = core.join_effects(true_jaxpr.effects, false_jaxpr.effects)\n+ disallowed_effects = joined_effects - allowed_effects\n+ if disallowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `cond`: {disallowed_effects}')\nindex = lax.convert_element_type(pred, np.int32)\n@@ -927,8 +933,11 @@ def _cond_with_per_branch_args(pred,\n(true_operand, false_operand))\ndef _cond_abstract_eval(*args, branches, **kwargs):\n- if any(b.effects for b in branches):\n- raise NotImplementedError('Effects not supported in `cond`.')\n+ joined_effects = core.join_effects(*(b.effects for b in branches))\n+ disallowed_effects = joined_effects - allowed_effects\n+ if disallowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `cond`: {disallowed_effects}')\njoined_effects = core.join_effects(*(b.effects for b in branches))\nreturn _map(raise_to_shaped, branches[0].out_avals), joined_effects\n@@ -1222,8 +1231,11 @@ def _cond_typecheck(*avals, branches, linear):\njaxpr0 = branches[0]\njaxpr0_in_avals_str = _avals_short(jaxpr0.in_avals)\njaxpr0_out_avals_str = _avals_short(jaxpr0.out_avals)\n- if any(b.effects for b in branches):\n- raise NotImplementedError('Effects not supported in `cond`.')\n+ joined_effects = core.join_effects(*(b.effects for b in branches))\n+ disallowed_effects = joined_effects - allowed_effects\n+ if disallowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `cond`: {disallowed_effects}')\nfor i, jaxpr in enumerate(branches[1:]):\nif len(jaxpr0.in_avals) != len(jaxpr.in_avals):\n@@ -1287,7 +1299,14 @@ pe.partial_eval_jaxpr_custom_rules[cond_p] = \\\ndef _cond_lowering(ctx, index, *args, branches, linear):\ndel linear # Unused.\n- output_types = _map(mlir.aval_to_ir_types, ctx.avals_out)\n+ joined_effects = core.join_effects(*(branch.effects for branch in branches))\n+ ordered_effects = [eff for eff in joined_effects\n+ if eff in core.ordered_effects]\n+ num_tokens = len(ordered_effects)\n+ tokens_in = ctx.tokens_in.subset(ordered_effects)\n+ output_token_types = [mlir.token_type() for _ in ordered_effects]\n+ output_types = [\n+ *output_token_types, *_map(mlir.aval_to_ir_types, ctx.avals_out)]\nflat_output_types = util.flatten(output_types)\n# mhlo.CaseOp takes a single argument 'index' and the corresponding blocks\n@@ -1301,17 +1320,20 @@ def _cond_lowering(ctx, index, *args, branches, linear):\nfor i, jaxpr in enumerate(branches):\nbranch = case_op.regions[i].blocks.append()\nwith ir.InsertionPoint(branch):\n- if jaxpr.effects:\n- raise NotImplementedError('Cannot lower effectful `cond`.')\nsub_ctx = ctx.module_context.replace(\nname_stack=xla.extend_name_stack(name_stack, f'branch_{i}_fun'))\n- out_vals, _ = mlir.jaxpr_subcomp(\n- sub_ctx, jaxpr.jaxpr, mlir.TokenSet(),\n+ out_vals, tokens_out = mlir.jaxpr_subcomp(\n+ sub_ctx, jaxpr.jaxpr, tokens_in,\n_map(mlir.ir_constants, jaxpr.consts),\n*_map(mlir.wrap_singleton_ir_values, args))\n+ out_tokens = [tokens_out.get(eff) for eff in ordered_effects]\n+ out_vals = [*out_tokens, *out_vals]\nmhlo.ReturnOp(util.flatten(out_vals))\n- return util.unflatten(case_op.results, _map(len, output_types))\n+ tokens_and_outputs = util.unflatten(case_op.results, _map(len, output_types))\n+ tokens, outputs = util.split_list(tokens_and_outputs, [num_tokens])\n+ ctx.set_tokens_out(mlir.TokenSet(zip(ordered_effects, tokens)))\n+ return outputs\nmlir.register_lowering(cond_p, _cond_lowering)\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -255,6 +255,62 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nx: 10\n\"\"\"))\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\n+ for ordered in [False, True]))\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_print_inside_cond(self, ordered):\n+ def f(x):\n+ def true_fun(x):\n+ debug_print(\"true: {}\", x, ordered=ordered)\n+ return x\n+ def false_fun(x):\n+ debug_print(\"false: {}\", x, ordered=ordered)\n+ return x\n+ return lax.cond(x < 5, true_fun, false_fun, x)\n+ with capture_stdout() as output:\n+ f(5)\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ false: 5\n+ \"\"\"))\n+ with capture_stdout() as output:\n+ f(4)\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ true: 4\n+ \"\"\"))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\n+ for ordered in [False, True]))\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_print_inside_switch(self, ordered):\n+ def f(x):\n+ def b1(x):\n+ debug_print(\"b1: {}\", x, ordered=ordered)\n+ return x\n+ def b2(x):\n+ debug_print(\"b2: {}\", x, ordered=ordered)\n+ return x\n+ def b3(x):\n+ debug_print(\"b3: {}\", x, ordered=ordered)\n+ return x\n+ return lax.switch(x, (b1, b2, b3), x)\n+ with capture_stdout() as output:\n+ f(0)\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ b1: 0\n+ \"\"\"))\n+ with capture_stdout() as output:\n+ f(1)\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ b2: 1\n+ \"\"\"))\n+ with capture_stdout() as output:\n+ f(2)\n+ self.assertEqual(output(), _format_multiline(\"\"\"\n+ b3: 2\n+ \"\"\"))\n+\nif jaxlib.version < (0, 3, 8):\n# No lowering for `emit_python_callback` in older jaxlibs.\ndel DebugPrintTest\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -633,6 +633,41 @@ class ControlFlowEffectsTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(NotImplementedError, 'Effects not supported'):\njax.make_jaxpr(f1)(2.)\n+ def test_allowed_effect_in_cond(self):\n+ def f(x):\n+ def true_fun(x):\n+ effect_p.bind(effect='while')\n+ return x\n+ def false_fun(x):\n+ effect_p.bind(effect='while')\n+ return x\n+ return lax.cond(x, true_fun, false_fun, x)\n+ f(2)\n+\n+ def test_allowed_ordered_effect_in_cond(self):\n+ def f(x):\n+ def true_fun(x):\n+ effect_p.bind(effect='while1')\n+ return x\n+ def false_fun(x):\n+ effect_p.bind(effect='while1')\n+ return x\n+ return lax.cond(x, true_fun, false_fun, x)\n+ f(2)\n+\n+ def test_multiple_allowed_ordered_effect_in_cond(self):\n+ def f(x):\n+ def true_fun(x):\n+ effect_p.bind(effect='while1')\n+ effect_p.bind(effect='while2')\n+ return x\n+ def false_fun(x):\n+ effect_p.bind(effect='while1')\n+ effect_p.bind(effect='while2')\n+ return x\n+ return lax.cond(x, true_fun, false_fun, x)\n+ f(2)\n+\ndef f2(x):\ndef true_fun(x):\nreturn x\n" } ]
Python
Apache License 2.0
google/jax
Enable effects for cond Co-authored-by: Matthew Johnson <mattjj@google.com>
260,447
05.05.2022 20:12:01
25,200
d57e36416f9ddba10f434e70123df22a3d38ac77
[linalg] Update qdwh to prevent underflow in norm estimation.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/qdwh.py", "new_path": "jax/_src/lax/qdwh.py", "diff": "@@ -73,7 +73,8 @@ def _qdwh(x, is_symmetric, max_iterations):\n# norm(x, 2) such that `alpha >= norm(x, 2)` and `beta` is a lower bound for\n# the smallest singular value of x.\neps = jnp.finfo(x.dtype).eps\n- alpha = jnp.sqrt(jnp.linalg.norm(x, ord=1) * jnp.linalg.norm(x, ord=jnp.inf))\n+ alpha = (jnp.sqrt(jnp.linalg.norm(x, ord=1)) *\n+ jnp.sqrt(jnp.linalg.norm(x, ord=jnp.inf)))\nl = eps\nu = x / alpha\n" }, { "change_type": "MODIFY", "old_path": "tests/qdwh_test.py", "new_path": "tests/qdwh_test.py", "diff": "\"\"\"Tests for the library of QDWH-based polar decomposition.\"\"\"\nimport functools\n+import jax\nfrom jax.config import config\nimport jax.numpy as jnp\nimport numpy as np\n@@ -27,10 +28,10 @@ from absl.testing import parameterized\nconfig.parse_flags_with_absl()\n-_JAX_ENABLE_X64 = config.x64_enabled\n+_JAX_ENABLE_X64_QDWH = config.x64_enabled\n# Input matrix data type for QdwhTest.\n-_QDWH_TEST_DTYPE = np.float64 if _JAX_ENABLE_X64 else np.float32\n+_QDWH_TEST_DTYPE = np.float64 if _JAX_ENABLE_X64_QDWH else np.float32\n# Machine epsilon used by QdwhTest.\n_QDWH_TEST_EPS = jnp.finfo(_QDWH_TEST_DTYPE).eps\n@@ -171,7 +172,7 @@ class QdwhTest(jtu.JaxTestCase):\n'testcase_name': '_m={}_by_n={}_log_cond={}'.format(\nm, n, log_cond),\n'm': m, 'n': n, 'log_cond': log_cond}\n- for m, n in zip([10, 12], [10, 12])\n+ for m, n in zip([10, 8], [10, 8])\nfor log_cond in np.linspace(1, 4, 4)))\n# TODO(tianjianlu): Fails on A100 GPU.\n@jtu.skip_on_devices(\"gpu\")\n@@ -187,12 +188,12 @@ class QdwhTest(jtu.JaxTestCase):\na = (u * s) @ v\nis_symmetric = _check_symmetry(a)\n- max_iterations = 10\n+ max_iterations = 15\nactual_u, actual_h, _, _ = qdwh.qdwh(a, is_symmetric, max_iterations)\n_, expected_h = osp_linalg.polar(a)\n# Sets the test tolerance.\n- rtol = 1E6 * _QDWH_TEST_EPS\n+ rtol = 1E4 * _QDWH_TEST_EPS\n# For rank-deficient matrix, `u` is not unique.\nwith self.subTest('Test h.'):\n@@ -205,10 +206,44 @@ class QdwhTest(jtu.JaxTestCase):\nnp.testing.assert_almost_equal(relative_diff_a, 1E-6, decimal=5)\nwith self.subTest('Test orthogonality.'):\n- actual_results = _dot(actual_u.T, actual_u)\n+ actual_results = _dot(actual_u.T.conj(), actual_u)\nexpected_results = np.eye(n)\nself.assertAllClose(\n- actual_results, expected_results, rtol=rtol, atol=1E-3)\n+ actual_results, expected_results, rtol=rtol, atol=1E-6)\n+\n+ @parameterized.named_parameters([\n+ {'testcase_name': f'_m={m}_by_n={n}_r={r}_c={c}_dtype={dtype}',\n+ 'm': m, 'n': n, 'r': r, 'c': c, 'dtype': dtype}\n+ for m, n, r, c in zip([4, 5], [3, 2], [1, 0], [1, 0])\n+ for dtype in jtu.dtypes.floating\n+ ])\n+ def testQdwhWithTinyElement(self, m, n, r, c, dtype):\n+ \"\"\"Tests qdwh on matrix with zeros and close-to-zero entries.\"\"\"\n+ a = jnp.zeros((m, n), dtype=dtype)\n+ tiny_elem = jnp.finfo(a).tiny\n+ a = a.at[r, c].set(tiny_elem)\n+\n+ is_symmetric = _check_symmetry(a)\n+ max_iterations = 10\n+\n+ @jax.jit\n+ def lsp_linalg_fn(a):\n+ u, h, _, _ = qdwh.qdwh(\n+ a, is_symmetric=is_symmetric, max_iterations=max_iterations)\n+ return u, h\n+\n+ actual_u, actual_h = lsp_linalg_fn(a)\n+\n+ expected_u = jnp.zeros((m, n), dtype=dtype)\n+ expected_u = expected_u.at[r, c].set(1.0)\n+ with self.subTest('Test u.'):\n+ np.testing.assert_array_equal(expected_u, actual_u)\n+\n+ expected_h = jnp.zeros((n, n), dtype=dtype)\n+ expected_h = expected_h.at[r, c].set(tiny_elem)\n+ with self.subTest('Test h.'):\n+ np.testing.assert_array_equal(expected_h, actual_h)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[linalg] Update qdwh to prevent underflow in norm estimation. PiperOrigin-RevId: 446887070
260,335
30.04.2022 21:50:18
25,200
d0863a1258d2fba11ce5885453b32f30f23bedbe
add scan dce rule tests, fix bugs
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -2037,30 +2037,36 @@ def _scan_padding_rule(in_avals, out_avals, *args, jaxpr, **params):\ndef _scan_dce_rule(used_outputs: List[bool], eqn: core.JaxprEqn\n) -> Tuple[List[bool], core.JaxprEqn]:\n+ jaxpr = eqn.params['jaxpr']\nnum_consts, num_carry = eqn.params['num_consts'], eqn.params['num_carry']\n+ num_xs = len(jaxpr.in_avals) - num_consts - num_carry\nused_carry_out, used_extensive_out = split_list(used_outputs, [num_carry])\nfor i in range(1 + num_carry):\nused_outputs = used_carry_out + used_extensive_out\n- jaxpr, used_inputs = pe.dce_jaxpr(eqn.params['jaxpr'].jaxpr, used_outputs)\n+ jaxpr_dce, used_inputs = pe.dce_jaxpr(\n+ jaxpr.jaxpr, used_outputs,\n+ instantiate=[False] * num_consts + used_carry_out + [False] * num_xs)\nused_consts, used_carry_in, used_extensive_in = \\\nsplit_list(used_inputs, [num_consts, num_carry])\n- if used_carry_in == used_carry_out:\n+ if list(used_carry_in) == list(used_carry_out):\nbreak\nelse:\nused_carry_out = _map(operator.or_, used_carry_out, used_carry_in)\nelse:\nassert False, \"Fixpoint not reached\"\n+ core.check_jaxpr(jaxpr.jaxpr)\nnew_linear = [l for l, u in zip(eqn.params['linear'], used_inputs) if u]\nnew_params = dict(eqn.params, num_consts=sum(used_consts),\nnum_carry=sum(used_carry_in), linear=tuple(new_linear),\n- jaxpr=core.ClosedJaxpr(jaxpr, eqn.params['jaxpr'].consts))\n+ jaxpr=core.ClosedJaxpr(jaxpr_dce, jaxpr.consts))\nnew_eqn = pe.new_jaxpr_eqn([v for v, used in zip(eqn.invars, used_inputs)\nif used],\n[v for v, used in zip(eqn.outvars, used_outputs)\nif used],\neqn.primitive, new_params, eqn.effects,\neqn.source_info)\n+ assert len(new_eqn.invars ) == len(new_params['jaxpr'].in_avals )\nassert len(new_eqn.outvars) == len(new_params['jaxpr'].out_avals)\nreturn used_inputs, new_eqn\n@@ -2133,8 +2139,7 @@ core.custom_typechecks[scan_p] = partial(_scan_typecheck, False)\npe.partial_eval_jaxpr_custom_rules[scan_p] = \\\npartial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'scan')\npe.padding_rules[scan_p] = _scan_padding_rule\n-# TODO(mattjj): re-enable\n-# pe.dce_rules[scan_p] = _scan_dce_rule\n+pe.dce_rules[scan_p] = _scan_dce_rule\n@api_boundary\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1161,12 +1161,16 @@ def _jaxpr_forwarding(jaxpr: Jaxpr) -> List[Optional[int]]:\nfor v in jaxpr.outvars]\n-def dce_jaxpr(jaxpr: Jaxpr, used_outputs: Sequence[bool]\n+def dce_jaxpr(jaxpr: Jaxpr, used_outputs: Sequence[bool],\n+ instantiate: Union[bool, Sequence[bool]] = False,\n) -> Tuple[Jaxpr, List[bool]]:\n- return _dce_jaxpr(jaxpr, tuple(used_outputs))\n+ if type(instantiate) is bool:\n+ instantiate = (instantiate,) * len(jaxpr.invars)\n+ return _dce_jaxpr(jaxpr, tuple(used_outputs), tuple(instantiate))\n@weakref_lru_cache\n-def _dce_jaxpr(jaxpr: Jaxpr, used_outputs: Tuple[bool, ...]\n+def _dce_jaxpr(jaxpr: Jaxpr, used_outputs: Tuple[bool, ...],\n+ instantiate: Tuple[bool, ...]\n) -> Tuple[Jaxpr, List[bool]]:\nenv: Dict[Var, bool] = {}\n@@ -1177,26 +1181,23 @@ def _dce_jaxpr(jaxpr: Jaxpr, used_outputs: Tuple[bool, ...]\nif type(x) is Var:\nenv[x] = read(x) or b\n+ def has_effects(e: JaxprEqn) -> bool:\n+ return bool(e.effects) or core.primitive_uses_outfeed(e.primitive, e.params)\n+\nnew_eqns = []\nmap(write, jaxpr.outvars, used_outputs)\nfor eqn in jaxpr.eqns[::-1]:\nused_outs = map(read, eqn.outvars)\n- # If any outputs are used, then we need to keep a version of the eqn and\n- # potentially mark some inputs as used. Otherwise mark all inputs as unused.\n- if any(used_outs) or core.primitive_uses_outfeed(eqn.primitive, eqn.params):\n- # If there's a rule for modifying the eqn and computing used inputs, apply\n- # it. Otherwise, keep the eqn unmodified and mark all inputs as used.\n- rule = dce_rules.get(eqn.primitive)\n- if rule:\n- used_ins, new_eqn = rule(used_outs, eqn)\n+ if not any(used_outs) and not has_effects(eqn):\n+ used_ins = [False] * len(eqn.invars)\nelse:\n- used_ins = [True] * len(eqn.invars)\n- new_eqn = eqn\n+ rule = dce_rules.get(eqn.primitive, _default_dce_rule)\n+ used_ins, new_eqn = rule(used_outs, eqn)\n+ if new_eqn is not None:\nnew_eqns.append(new_eqn)\n- else:\n- used_ins = [False] * len(eqn.invars)\nmap(write, eqn.invars, used_ins)\nused_inputs = map(read, jaxpr.invars)\n+ used_inputs = map(op.or_, instantiate, used_inputs)\nnew_jaxpr = Jaxpr(jaxpr.constvars,\n[v for v, b in zip(jaxpr.invars, used_inputs) if b],\n@@ -1206,7 +1207,13 @@ def _dce_jaxpr(jaxpr: Jaxpr, used_outputs: Tuple[bool, ...]\nreturn new_jaxpr, used_inputs\n-DCERule = Callable[[List[bool], JaxprEqn], Tuple[List[bool], JaxprEqn]]\n+DCERule = Callable[[List[bool], JaxprEqn], Tuple[List[bool], Optional[JaxprEqn]]]\n+\n+def _default_dce_rule(\n+ used_outs: List[bool], eqn: JaxprEqn\n+ ) -> Tuple[List[bool], JaxprEqn]:\n+ return [True] * len(eqn.invars), eqn\n+\ndce_rules: Dict[Primitive, DCERule] = {}\n@@ -1217,7 +1224,8 @@ def dce_jaxpr_call_rule(used_outputs: List[bool], eqn: JaxprEqn\nupdate_params = call_param_updaters.get(eqn.primitive)\nif update_params:\nnew_params = update_params(new_params, used_inputs, 0)\n- new_eqn = new_jaxpr_eqn([v for v, used in zip(eqn.invars, used_inputs) if used],\n+ new_eqn = new_jaxpr_eqn(\n+ [v for v, used in zip(eqn.invars, used_inputs) if used],\n[v for v, used in zip(eqn.outvars, used_outputs) if used],\neqn.primitive, new_params, new_jaxpr.effects, eqn.source_info)\nreturn used_inputs, new_eqn\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -24,7 +24,7 @@ import re\nimport subprocess\nimport sys\nimport types\n-from typing import Callable\n+from typing import Callable, List, Optional\nimport unittest\nimport warnings\nimport weakref\n@@ -4518,56 +4518,202 @@ class JaxprTest(jtu.JaxTestCase):\njaxpr = api.make_jaxpr(lambda: cet(3.))()\nself.assertLen(jaxpr.eqns, 0)\n- def test_dce_jaxpr_scan(self):\n- raise unittest.SkipTest() # TODO(mattjj)\n- @api.remat\n- def scanned_f(c, x):\n- out = jnp.tanh(c * x)\n- return out, out\n- def f(xs):\n- return lax.scan(scanned_f, 1., xs)\n-\n- jaxpr = api.make_jaxpr(lambda xs: api.linearize(f, xs)[1])(jnp.arange(10.)).jaxpr\n- jaxpr, _ = pe.dce_jaxpr(jaxpr, [True] * len(jaxpr.outvars))\n-\n- self.assertLen(jaxpr.eqns, 1)\n- self.assertLen(jaxpr.eqns[-1].params['jaxpr'].jaxpr.eqns, 2)\n-\n- def test_dce_jaxpr_scan_nontrivial_fixedpoint(self):\n- raise unittest.SkipTest() # TODO(mattjj)\n+class DCETest(jtu.JaxTestCase):\n+\n+ def assert_dce_result(self, jaxpr: core.Jaxpr, used_outputs: List[bool],\n+ expected_used_inputs: List[bool],\n+ expected_num_eqns: Optional[int] = None,\n+ check_diff: bool = True):\n+ jaxpr_dce, used_inputs = pe.dce_jaxpr(jaxpr, used_outputs)\n+ core.check_jaxpr(jaxpr_dce)\n+ self.assertEqual(used_inputs, expected_used_inputs)\n+ if expected_num_eqns is not None:\n+ all_jaxprs = it.chain([jaxpr_dce], core.subjaxprs(jaxpr_dce))\n+ num_eqns = sum(len(subjaxpr.eqns) for subjaxpr in all_jaxprs)\n+ self.assertEqual(num_eqns, expected_num_eqns, msg=str(jaxpr_dce))\n+\n+ rand_ = jtu.rand_small(np.random.RandomState(0))\n+ rand = lambda v: rand_(v.aval.shape, v.aval.dtype)\n+ consts = [rand(v) for v in jaxpr.constvars]\n+ inputs = [rand(v) for v in jaxpr.invars ]\n+ inputs_dce = [x for x, used in zip(inputs, used_inputs) if used]\n+ full_outs = core.eval_jaxpr(jaxpr , consts, *inputs)\n+ expected_outs_dce = [y for y, used in zip(full_outs, used_outputs) if used]\n+ outs = core.eval_jaxpr(jaxpr_dce, consts, *inputs_dce)\n+ self.assertAllClose(outs, expected_outs_dce)\n+\n+ if check_diff and expected_num_eqns != 0:\n+ f = lambda *args: core.eval_jaxpr(jaxpr_dce, consts, *args)\n+ jtu.check_grads(f, inputs_dce, order=2, modes=['rev'])\n+\n+ def test_dce_jaxpr_scan_nontrivial_fixedpoint_carry(self):\n+ # The idea is that each element of the output carry tuple depends on the\n+ # corresponding carried input as well as the one to the left. The extensive\n+ # inputs and outputs aren't used here; just the carry depending on itself.\ndef f(lst):\ndef body(c, _):\nreturn [c[0]] + [c1 + c2 for c1, c2 in zip(c[:-1], c[1:])], None\nout, _ = jax.lax.scan(body, lst, None, length=len(lst))\nreturn out\n- jaxpr = api.make_jaxpr(f)([1, 2, 3, 4]).jaxpr\n+ jaxpr = api.make_jaxpr(f)([1., 2., 3., 4.]).jaxpr\nself.assertLen(jaxpr.eqns, 1)\nself.assertLen(jaxpr.eqns[0].params['jaxpr'].jaxpr.eqns, 3)\n- # If we use all but the last element, only one eqn is pruned.\n- jaxpr_pruned, used_inputs = pe.dce_jaxpr(jaxpr, [True, True, True, False])\n- self.assertLen(jaxpr_pruned.eqns, 1)\n- self.assertLen(jaxpr_pruned.eqns[0].params['jaxpr'].jaxpr.eqns, 2)\n- # And all but the first input is used.\n- self.assertEqual(used_inputs, [True, True, True, False])\n-\n- # If we use all but the last two elements, two eqns can be pruned.\n- jaxpr_pruned, used_inputs = pe.dce_jaxpr(jaxpr, [True, True, False, False])\n- self.assertLen(jaxpr_pruned.eqns, 1)\n- self.assertLen(jaxpr_pruned.eqns[0].params['jaxpr'].jaxpr.eqns, 1)\n- # And the last two inputs are not used.\n- self.assertEqual(used_inputs, [True, True, False, False])\n+ # If we use all but the last element, all but the first input is used, and\n+ # only one eqn is pruned.\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[True, True, True, False],\n+ expected_used_inputs=[True, True, True, False],\n+ expected_num_eqns=1 + 2) # one outer scan eqn, two adds in the body\n+\n+ # Same as above if we just pull on the third element.\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[False, False, True, False],\n+ expected_used_inputs=[True, True, True, False],\n+ expected_num_eqns=1 + 2) # one outer scan eqn, two adds in the body\n+\n+ # If we use all but the last two elements, the last two inputs are not used,\n+ # and two eqns can be pruned.\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[True, True, False, False],\n+ expected_used_inputs=[True, True, False, False],\n+ expected_num_eqns=1 + 1) # one outer scan eqn, one add in body\n# If we only use the last element, no eqns can be pruned.\n- jaxpr_pruned, used_inputs = pe.dce_jaxpr(jaxpr, [False, False, False, True])\n- self.assertLen(jaxpr_pruned.eqns, 1)\n- self.assertLen(jaxpr_pruned.eqns[0].params['jaxpr'].jaxpr.eqns, 3)\n- # And all inputs are used.\n- self.assertEqual(used_inputs, [True, True, True, True])\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[False, False, False, True],\n+ expected_used_inputs=[True, True, True, True],\n+ expected_num_eqns=1 + 3) # one outer scan eqn, three adds in body\n+\n+ def test_dce_jaxpr_scan_nontrivial_fixedpoint_carry_2(self):\n+ # This is much like the above test, except with a more interesting\n+ # dependence structure among the carry elements. Also add a const and\n+ # extensive input.\n+ hidden_sequence = [1, 2, 3, 5, 8]\n+ def f(lst):\n+ def body(c, _):\n+ _ = jnp.sin(np.array([3., 1., 4.]))\n+ sub_c = [c[i] for i in hidden_sequence]\n+ sub_c = [sub_c[0]] + [c1 * c2 for c1, c2 in zip(sub_c[:-1], sub_c[1:])]\n+ new_c = list(c)\n+ for i, elt in zip(hidden_sequence, sub_c):\n+ new_c[i] = elt\n+ return new_c, None\n+ out, _ = jax.lax.scan(body, lst, np.arange(len(lst), dtype='float32'))\n+ return out\n+ jaxpr = api.make_jaxpr(f)([1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]).jaxpr\n+ self.assertLen(jaxpr.eqns, 1)\n+ self.assertLen(jaxpr.eqns[0].params['jaxpr'].jaxpr.eqns, 5)\n+\n+ # If we use the value at index 8 only, all the hidden sequence must be kept\n+ # and no eqns can be pruned.\n+ used_outputs = [False] * 10\n+ used_outputs[8] = True\n+ expected_used_inputs = [False] * 10\n+ for i in hidden_sequence:\n+ expected_used_inputs[i] = True\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=used_outputs,\n+ expected_used_inputs=expected_used_inputs,\n+ expected_num_eqns=1 + 4)\n+\n+ # If we use the value at any indices not in the hidden sequence, none of the\n+ # hidden sequence must be kept and we can prune all body eqns.\n+ used_outputs = [False] * 10\n+ expected_used_inputs = [False] * 10\n+ used_outputs[9] = expected_used_inputs[9] = True\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=used_outputs,\n+ expected_used_inputs=expected_used_inputs,\n+ expected_num_eqns=1) # 1 b/c scan doesn't have fwding rule\n+ used_outputs[7] = expected_used_inputs[7] = True\n+ used_outputs[6] = expected_used_inputs[6] = True\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=used_outputs,\n+ expected_used_inputs=expected_used_inputs,\n+ expected_num_eqns=1)\n+\n+ # If we use the value at index 3 only, some of the hidden sequence must be\n+ # kept but the rest pruned.\n+ used_outputs = [False] * 10\n+ used_outputs[3] = True\n+ expected_used_inputs = [False] * 10\n+ expected_used_inputs[1] = expected_used_inputs[2] = \\\n+ expected_used_inputs[3] = True\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=used_outputs,\n+ expected_used_inputs=expected_used_inputs,\n+ expected_num_eqns=1 + 2)\n+\n+ def test_dce_jaxpr_scan_nontrivial_fixedpoint_extensive_output(self):\n+ # Here we test how using the extensive output affects the carry.\n+ def f(lst):\n+ def body(c, _):\n+ return [c[-1], *c[:-1]], c[-1]\n+ _, ys = jax.lax.scan(body, lst, None, length=len(lst))\n+ return ys\n+ jaxpr = api.make_jaxpr(f)([1., 2., 3., 4.]).jaxpr\n+ self.assertLen(jaxpr.eqns, 1)\n+\n+ # If we only use the extensive output, all carry elements are needed, and we\n+ # need to keep the scan itself.\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[True],\n+ expected_used_inputs=[True, True, True, True],\n+ expected_num_eqns=1)\n+\n+ # If we don't use the extensive output, no carry elements are needed, and we\n+ # don't need to keep the scan.\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[False],\n+ expected_used_inputs=[False, False, False, False],\n+ expected_num_eqns=0)\n+\n+ def test_dce_jaxpr_scan_extensive_input(self):\n+ # Here we test an extensive input affecting the carry.\n+ def cumprod(xs):\n+ def body(c, x):\n+ return c * x, c\n+ c, ys = jax.lax.scan(body, jnp.float32(1.), xs)\n+ return c, ys\n+ jaxpr = api.make_jaxpr(cumprod)(jnp.arange(1., 5., dtype='float32')).jaxpr\n+\n+ # If we only use the carry output or extensive output, we need the input.\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[True, False],\n+ expected_used_inputs=[True],\n+ expected_num_eqns=2)\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[False, True],\n+ expected_used_inputs=[True],\n+ expected_num_eqns=2)\n+\n+ # If we don't use either output, the scan is eliminated.\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[False, False],\n+ expected_used_inputs=[False],\n+ expected_num_eqns=0)\n+\n+ def test_dce_jaxpr_scan_overpruning(self):\n+ # This is a regression test for a specific issue.\n+ @api.remat\n+ def scanned_f(c, x):\n+ out = jnp.tanh(c * x)\n+ return out, out\n+\n+ def f(xs):\n+ return lax.scan(scanned_f, 1., xs)\n+\n+ xs = jnp.arange(10.)\n+ jaxpr = api.make_jaxpr(lambda xs: api.linearize(f, xs)[1])(xs).jaxpr\n+\n+ jaxpr, used_inputs = pe.dce_jaxpr(jaxpr, [True] * len(jaxpr.outvars))\n+ self.assertLen(jaxpr.eqns, 1)\n+ self.assertLen(jaxpr.eqns[-1].params['jaxpr'].jaxpr.eqns, 2)\ndef test_dce_jaxpr_scan_const_in_jvp(self):\n- raise unittest.SkipTest() # TODO(mattjj)\n+ # The main point of this test is to check for a crash.\n@api.custom_jvp\ndef f(x):\nreturn x * np.arange(3.)\n@@ -4582,14 +4728,38 @@ class JaxprTest(jtu.JaxTestCase):\ny, _ = jax.lax.scan(body, x, None, length=1)\nreturn y\n- jvp_jaxpr = api.make_jaxpr(lambda x, xdot: api.jvp(g, (x,), (xdot,)))(\n- np.arange(3.), np.arange(3.)).jaxpr\n-\n- jaxpr_pruned, used_inputs = pe.dce_jaxpr(jvp_jaxpr, [True, True])\n- self.assertTrue(all(used_inputs))\n-\n- jaxpr_pruned, used_inputs = pe.dce_jaxpr(jvp_jaxpr, [True, False])\n- self.assertEqual(used_inputs, [True, False])\n+ jaxpr = api.make_jaxpr(lambda x, xdot: api.jvp(g, (x,), (xdot,))\n+ )(np.arange(3.), np.arange(3.)).jaxpr\n+\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[True, True],\n+ expected_used_inputs=[True, True])\n+\n+ self.assert_dce_result(\n+ jaxpr, used_outputs=[True, False],\n+ expected_used_inputs=[True, False])\n+\n+ def test_dce_jaxpr_scan_results(self):\n+ # This doesn't test whether DCE is doing nontrivial work; instead it tests\n+ # whether the result after applying DCE computes different values. If\n+ # dce_jaxpr were an identity function, it'd pass this test!\n+ def f(cs, xs):\n+ def body(c, x):\n+ return (c[0], c[0] + c[1], jnp.arange(3.)), x\n+ cs, xs = jax.lax.scan(body, cs, xs)\n+ return cs[::2], xs[::2]\n+\n+ cs = 1., 2., jnp.arange(3.)\n+ xs = jnp.arange(3.), jnp.arange(3.) + 5\n+ jaxpr_ = jax.make_jaxpr(f)(cs, xs)\n+ jaxpr, consts = jaxpr_.jaxpr, jaxpr_.consts\n+ jaxpr_pruned, used_inputs = pe.dce_jaxpr(jaxpr, [True] * len(jaxpr.outvars))\n+\n+ args = (*cs, *xs)\n+ result1 = core.eval_jaxpr(jaxpr , consts, *cs, *xs)\n+ pruned_args = [x for x, used in zip(args, used_inputs) if used]\n+ result2 = core.eval_jaxpr(jaxpr_pruned, consts, *pruned_args)\n+ self.assertAllClose(result1, result2)\nclass CustomJVPTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add scan dce rule tests, fix bugs
260,335
05.05.2022 22:09:40
25,200
04e4ffdda737e42c691bc4f9d46186ff3be1ed65
gate scan dce rule on after_neurips flag
[ { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -734,6 +734,12 @@ config.define_bool_state(\ndefault=(lib.version >= (0, 3, 6)),\nhelp=('Enables using optimization-barrier op for lowering remat.'))\n+# TODO(mattjj): remove after May 19 2022, NeurIPS submission deadline\n+config.define_bool_state(\n+ name='after_neurips',\n+ default=False,\n+ help='Gate changes until after NeurIPS 2022 deadline.')\n+\n@contextlib.contextmanager\ndef explicit_device_put_scope() -> Iterator[None]:\n\"\"\"Indicates that the current context is an explicit device_put*() call.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -2037,6 +2037,8 @@ def _scan_padding_rule(in_avals, out_avals, *args, jaxpr, **params):\ndef _scan_dce_rule(used_outputs: List[bool], eqn: core.JaxprEqn\n) -> Tuple[List[bool], core.JaxprEqn]:\n+ if not config.after_neurips:\n+ return [True] * len(eqn.params['jaxpr'].in_avals), eqn\njaxpr = eqn.params['jaxpr']\nnum_consts, num_carry = eqn.params['num_consts'], eqn.params['num_carry']\nnum_xs = len(jaxpr.in_avals) - num_consts - num_carry\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4519,6 +4519,7 @@ class JaxprTest(jtu.JaxTestCase):\nself.assertLen(jaxpr.eqns, 0)\n+@unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\nclass DCETest(jtu.JaxTestCase):\ndef assert_dce_result(self, jaxpr: core.Jaxpr, used_outputs: List[bool],\n" } ]
Python
Apache License 2.0
google/jax
gate scan dce rule on after_neurips flag
260,447
06.05.2022 16:33:13
25,200
109355985664a23054b6a88b583c2465a8e101f6
[linalg] Add matmul precision scope for svd.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/svd.py", "new_path": "jax/_src/lax/svd.py", "diff": "@@ -153,10 +153,11 @@ def svd(a: Any,\nreduce_to_square = True\nif not compute_uv:\n+ with jax.default_matmul_precision('float32'):\nreturn _svd(a, hermitian, compute_uv, max_iterations)\n+ with jax.default_matmul_precision('float32'):\nu_out, s_out, v_out = _svd(a, hermitian, compute_uv, max_iterations)\n-\nif reduce_to_square:\nu_out = q @ u_out\n" } ]
Python
Apache License 2.0
google/jax
[linalg] Add matmul precision scope for svd. PiperOrigin-RevId: 447095391
260,301
07.05.2022 13:38:55
-3,600
a11f15e3eccfb59d02ba42b714f5c36e9117c9ef
feat: officially support Python 3.10
[ { "change_type": "MODIFY", "old_path": ".github/workflows/ci-build.yaml", "new_path": ".github/workflows/ci-build.yaml", "diff": "name: CI\n+# We test all supported Python versions as follows:\n+# - 3.7 : Documentation build\n+# - 3.8 : Part of Matrix\n+# - 3.9 : Part of Matrix with NumPy dispatch\n+# - 3.10 : Part of Matrix\n+\non:\n# Trigger the workflow on push or pull request,\n# but only for the main branch\n@@ -35,20 +41,27 @@ jobs:\nmatrix:\ninclude:\n- name-prefix: \"with 3.8\"\n- python-version: 3.8\n+ python-version: \"3.8\"\nos: ubuntu-latest\nenable-x64: 0\npackage-overrides: \"none\"\nnum_generated_cases: 1\nuse-latest-jaxlib: false\n- name-prefix: \"with numpy-dispatch\"\n- python-version: 3.9\n+ python-version: \"3.9\"\nos: ubuntu-latest\nenable-x64: 1\n# Test experimental NumPy dispatch\npackage-overrides: \"git+https://github.com/seberg/numpy-dispatch.git\"\nnum_generated_cases: 1\nuse-latest-jaxlib: false\n+ - name-prefix: \"with 3.10\"\n+ python-version: \"3.10\"\n+ os: ubuntu-latest\n+ enable-x64: 0\n+ package-overrides: \"none\"\n+ num_generated_cases: 1\n+ use-latest-jaxlib: false\nsteps:\n- name: Cancel previous\nuses: styfle/cancel-workflow-action@0.9.1\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/setup.py", "new_path": "jaxlib/setup.py", "diff": "@@ -36,6 +36,12 @@ setup(\ninstall_requires=['scipy', 'numpy>=1.19', 'absl-py', 'flatbuffers >= 1.12, < 3.0'],\nurl='https://github.com/google/jax',\nlicense='Apache-2.0',\n+ classifiers=[\n+ \"Programming Language :: Python :: 3.7\",\n+ \"Programming Language :: Python :: 3.8\",\n+ \"Programming Language :: Python :: 3.9\",\n+ \"Programming Language :: Python :: 3.10\",\n+ ],\npackage_data={\n'jaxlib': [\n'*.so',\n" }, { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "@@ -80,6 +80,7 @@ setup(\n\"Programming Language :: Python :: 3.7\",\n\"Programming Language :: Python :: 3.8\",\n\"Programming Language :: Python :: 3.9\",\n+ \"Programming Language :: Python :: 3.10\",\n],\nzip_safe=False,\n)\n" } ]
Python
Apache License 2.0
google/jax
feat: officially support Python 3.10
260,411
09.05.2022 15:45:36
-10,800
137fdb4c88db1e8944da1f0bec99c0fa70df917a
[jax2tf] Update JAX limitations. JAX has made progress in coverage of primitives on TPU. This PR updates those limitations.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "new_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "diff": "# Primitives with limited JAX support\n-*Last generated on: 2021-07-31* (YYYY-MM-DD)\n+*Last generated on: 2022-05-09* (YYYY-MM-DD)\n## Supported data types for primitives\n-We use a set of 2809 test harnesses to test\n-the implementation of 126 numeric JAX primitives.\n+We use a set of 3075 test harnesses to test\n+the implementation of 127 numeric JAX primitives.\nWe consider a JAX primitive supported for a particular data\ntype if it is supported on at least one device type.\nThe following table shows the dtypes at which primitives\n@@ -64,14 +64,14 @@ be updated.\n| complex | 4 | float32, float64 | bfloat16, bool, complex, float16, integer |\n| concatenate | 17 | all | |\n| conj | 5 | complex, float32, float64 | bfloat16, bool, float16, integer |\n-| conv_general_dilated | 73 | inexact, int16, int32, int8 | bool, int64, unsigned |\n+| conv_general_dilated | 96 | inexact, int16, int32, int8 | bool, int64, unsigned |\n| convert_element_type | 201 | all | |\n| cos | 6 | inexact | bool, integer |\n| cosh | 6 | inexact | bool, integer |\n-| cummax | 17 | inexact, integer | bool |\n-| cummin | 17 | inexact, integer | bool |\n-| cumprod | 17 | inexact, integer | bool |\n-| cumsum | 17 | inexact, integer | bool |\n+| cummax | 34 | inexact, integer | bool |\n+| cummin | 34 | inexact, integer | bool |\n+| cumprod | 34 | inexact, integer | bool |\n+| cumsum | 34 | inexact, integer | bool |\n| custom_linear_solve | 4 | float32, float64 | bfloat16, bool, complex, float16, integer |\n| device_put | 16 | all | |\n| digamma | 4 | floating | bool, complex, integer |\n@@ -89,7 +89,7 @@ be updated.\n| expm1 | 6 | inexact | bool, integer |\n| fft | 20 | complex, float32, float64 | bfloat16, bool, float16, integer |\n| floor | 4 | floating | bool, complex, integer |\n-| gather | 80 | all | |\n+| gather | 136 | all | |\n| ge | 17 | all | |\n| gt | 17 | all | |\n| igamma | 6 | floating | bool, complex, integer |\n@@ -111,7 +111,7 @@ be updated.\n| neg | 14 | inexact, integer | bool |\n| nextafter | 6 | floating | bool, complex, integer |\n| or | 11 | bool, integer | inexact |\n-| pad | 120 | all | |\n+| pad | 180 | all | |\n| population_count | 8 | integer | bool, inexact |\n| pow | 10 | inexact | bool, integer |\n| qr | 60 | inexact | bool, integer |\n@@ -129,22 +129,23 @@ be updated.\n| reduce_prod | 14 | inexact, integer | bool |\n| reduce_sum | 14 | inexact, integer | bool |\n| reduce_window_add | 33 | inexact, integer | bool |\n-| reduce_window_max | 37 | all | |\n+| reduce_window_max | 39 | all | |\n| reduce_window_min | 15 | all | |\n| reduce_window_mul | 42 | inexact, integer | bool |\n| regularized_incomplete_beta | 4 | floating | bool, complex, integer |\n| rem | 18 | floating, integer | bool, complex |\n| reshape | 19 | all | |\n| rev | 19 | all | |\n+| rng_bit_generator | 36 | uint32, uint64 | bool, inexact, signed, uint16, uint8 |\n| round | 6 | floating | bool, complex, integer |\n| rsqrt | 6 | inexact | bool, integer |\n| scatter_add | 15 | all | |\n| scatter_max | 15 | all | |\n-| scatter_min | 19 | all | |\n+| scatter_min | 24 | all | |\n| scatter_mul | 15 | all | |\n-| select | 16 | all | |\n| select_and_gather_add | 15 | floating | bool, complex, integer |\n| select_and_scatter_add | 27 | bool, floating, integer | complex |\n+| select_n | 32 | all | |\n| shift_left | 10 | integer | bool, inexact |\n| shift_right_arithmetic | 10 | integer | bool, inexact |\n| shift_right_logical | 10 | integer | bool, inexact |\n@@ -191,11 +192,6 @@ and search for \"limitation\".\n|cholesky|unimplemented|float16|cpu, gpu|\n|clamp|unimplemented|bool, complex|cpu, gpu, tpu|\n|conv_general_dilated|preferred_element_type not implemented for integers|int16, int32, int8|gpu|\n-|conv_general_dilated|preferred_element_type=c128 not implemented|complex64|tpu|\n-|conv_general_dilated|preferred_element_type=f64 not implemented|bfloat16, float16, float32|tpu|\n-|conv_general_dilated|preferred_element_type=i64 not implemented|int16, int32, int8|tpu|\n-|dot_general|preferred_element_type=c128 not implemented|complex64|tpu|\n-|dot_general|preferred_element_type=i64 not implemented|int16, int32, int8|tpu|\n|eig|only supported on CPU in JAX|all|tpu, gpu|\n|eig|unimplemented|bfloat16, float16|cpu|\n|eigh|unimplemented|bfloat16, float16|cpu, gpu|\n@@ -204,7 +200,6 @@ and search for \"limitation\".\n|scatter_add|unimplemented|bool|cpu, gpu, tpu|\n|scatter_mul|unimplemented|bool|cpu, gpu, tpu|\n|select_and_scatter_add|works only for 2 or more inactive dimensions|all|tpu|\n-|svd|complex not implemented. Works in JAX for CPU and GPU with custom kernels|complex|tpu|\n|svd|unimplemented|bfloat16, float16|cpu, gpu|\n|triangular_solve|unimplemented|float16|gpu|\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "new_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "diff": "# Primitives with limited support for jax2tf\n-*Last generated on (YYYY-MM-DD): 2021-12-06*\n+*Last generated on (YYYY-MM-DD): 2022-05-09*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -66,14 +66,9 @@ More detailed information can be found in the\n| cholesky | TF test skipped: Not implemented in JAX: unimplemented | float16 | cpu, gpu | compiled, eager, graph |\n| clamp | TF test skipped: Not implemented in JAX: unimplemented | bool, complex | cpu, gpu, tpu | compiled, eager, graph |\n| conv_general_dilated | TF test skipped: Not implemented in JAX: preferred_element_type not implemented for integers | int16, int32, int8 | gpu | compiled, eager, graph |\n-| conv_general_dilated | TF test skipped: Not implemented in JAX: preferred_element_type=c128 not implemented | complex64 | tpu | compiled, eager, graph |\n-| conv_general_dilated | TF test skipped: Not implemented in JAX: preferred_element_type=f64 not implemented | bfloat16, float16, float32 | tpu | compiled, eager, graph |\n-| conv_general_dilated | TF test skipped: Not implemented in JAX: preferred_element_type=i64 not implemented | int16, int32, int8 | tpu | compiled, eager, graph |\n| digamma | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| div | TF error: TF integer division fails if divisor contains 0; JAX returns NaN | integer | cpu, gpu, tpu | compiled, eager, graph |\n| dot_general | TF error: Numeric comparison disabled: Non-deterministic NaN for dot_general with preferred_element_type on GPU (b/189287598) | bfloat16, complex64, float16, float32 | gpu | compiled, eager, graph |\n-| dot_general | TF test skipped: Not implemented in JAX: preferred_element_type=c128 not implemented | complex64 | tpu | compiled, eager, graph |\n-| dot_general | TF test skipped: Not implemented in JAX: preferred_element_type=i64 not implemented | int16, int32, int8 | tpu | compiled, eager, graph |\n| dot_general | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n| eig | TF test skipped: Not implemented in JAX: only supported on CPU in JAX | all | gpu, tpu | compiled, eager, graph |\n| eig | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu | compiled, eager, graph |\n@@ -102,10 +97,11 @@ More detailed information can be found in the\n| scatter_mul | TF test skipped: Not implemented in JAX: unimplemented | bool | cpu, gpu, tpu | compiled, eager, graph |\n| select_and_gather_add | TF error: jax2tf unimplemented for 64-bit inputs because the current implementation relies on packing two values into a single value. This can be fixed by using a variadic XlaReduceWindow, when available | float64 | cpu, gpu | compiled, eager, graph |\n| select_and_scatter_add | TF test skipped: Not implemented in JAX: works only for 2 or more inactive dimensions | all | tpu | compiled, eager, graph |\n-| svd | TF test skipped: Not implemented in JAX: complex not implemented. Works in JAX for CPU and GPU with custom kernels | complex | tpu | compiled, eager, graph |\n+| svd | TF error: Numeric comparison disabled: Large numerical discrepancy | float16 | tpu | compiled, eager, graph |\n| svd | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu | compiled, eager, graph |\n| svd | TF error: function not compilable. Implemented using `tf.linalg.svd` and `tf.linalg.adjoint` | complex | cpu, gpu | compiled |\n| svd | TF error: op not defined for dtype | bfloat16 | tpu | compiled, eager, graph |\n+| svd | TF error: op not defined for dtype | complex | tpu | compiled, graph |\n| triangular_solve | TF test skipped: Not implemented in JAX: unimplemented | float16 | gpu | compiled, eager, graph |\n| triangular_solve | TF error: op not defined for dtype | bfloat16 | cpu, gpu, tpu | compiled, eager, graph |\n| triangular_solve | TF error: op not defined for dtype | float16 | cpu, gpu | eager, graph |\n@@ -142,7 +138,8 @@ with jax2tf. The following table lists that cases when this does not quite hold:\n| min | May return different values when one of the values is NaN. JAX always returns NaN, while TF returns the value NaN is compared with. | all | cpu, gpu, tpu | compiled, eager, graph |\n| pow | custom numeric comparison | complex | cpu, gpu, tpu | eager, graph |\n| sort | Numeric comparison disabled: TODO: TF non-stable multiple-array sort | all | gpu | compiled, eager, graph |\n-| svd | custom numeric comparison when compute_uv | all | cpu, gpu | compiled, eager, graph |\n+| svd | custom numeric comparison when compute_uv on CPU/GPU | all | cpu, gpu | compiled, eager, graph |\n+| svd | custom numeric comparison when compute_uv on TPU | complex, float32, float64 | tpu | compiled, eager, graph |\n| top_k | Produces different results when the array contains `inf` and `NaN` (they are sorted differently in TF vs. XLA). | floating | cpu, gpu, tpu | eager, graph |\n## Updating the documentation\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -1138,6 +1138,9 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nmodes=(\"eager\", \"graph\", \"compiled\"),\nskip_comparison=True),\nmissing_tf_kernel(dtypes=[dtypes.bfloat16], devices=\"tpu\"),\n+ missing_tf_kernel(dtypes=[np.complex64, np.complex128],\n+ modes=(\"compiled\", \"graph\"),\n+ devices=\"tpu\"),\ncustom_numeric(\ntol=1e-4,\ndtypes=[np.float32, np.complex64],\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax_primitives_coverage_test.py", "new_path": "jax/experimental/jax2tf/tests/jax_primitives_coverage_test.py", "diff": "@@ -78,11 +78,11 @@ class JaxPrimitiveTest(jtu.JaxTestCase):\nlogging.warning(\"Found no JAX error but expected JAX limitations: %s in \"\n\"harness: %s\",\n[u.description for u in jax_unimpl], harness.fullname)\n- # We assert that we don't have too strict limitations. This assert can\n- # fail if somebody fixes a JAX or XLA limitation. In that case, you should\n- # find and remove the Limitation in primitive_harness. Alternatively,\n- # uncomment this assert and ping an OWNER of primitive_harness.\n- # self.assertEmpty(msg)\n+ # We do not fail the test if we have too many limitations. If you want\n+ # to find extraneous limitations, uncomment this assert and run the test\n+ # on all platforms.\n+ # self.assertEmpty((\"Found no JAX error but expected JAX limitations: \"\n+ # f\"{[u.description for u in jax_unimpl]} in harness: {harness.fullname}\"))\ndef test_generate_primitives_coverage_doc(self):\nharnesses = primitive_harness.all_harnesses\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -1688,10 +1688,6 @@ for dtype in jtu.dtypes.all_floating + jtu.dtypes.complex:\n\"unimplemented\",\ndevices=(\"cpu\", \"gpu\"),\ndtypes=[np.float16, dtypes.bfloat16]),\n- Limitation(\n- \"complex not implemented. Works in JAX for CPU and GPU with custom kernels\",\n- devices=\"tpu\",\n- dtypes=[np.complex64, np.complex128])\n],\nshape=shape,\ndtype=dtype,\n@@ -2621,18 +2617,6 @@ def _make_dot_general_harness(name,\ndimension_numbers=dimension_numbers,\nprecision=precision,\npreferred_element_type=preferred_element_type,\n- jax_unimplemented=[\n- Limitation(\n- \"preferred_element_type=c128 not implemented\",\n- devices=\"tpu\",\n- dtypes=np.complex64,\n- enabled=(preferred_element_type in [np.complex128])),\n- Limitation(\n- \"preferred_element_type=i64 not implemented\",\n- devices=\"tpu\",\n- dtypes=(np.int8, np.int16, np.int32),\n- enabled=(preferred_element_type in [np.int64])),\n- ],\n)\n@@ -2794,11 +2778,6 @@ def _make_conv_harness(name,\npreferred_element_type=preferred_element_type,\nenable_xla=enable_xla,\njax_unimplemented=[\n- Limitation(\n- \"preferred_element_type=i64 not implemented\",\n- devices=\"tpu\",\n- dtypes=(np.int8, np.int16, np.int32),\n- enabled=(preferred_element_type in [np.int64])),\n# b/183565702 - no integer convolutions for GPU\nLimitation(\n\"preferred_element_type not implemented for integers\",\n@@ -2806,16 +2785,6 @@ def _make_conv_harness(name,\ndtypes=(np.int8, np.int16, np.int32),\nenabled=(preferred_element_type in [np.int16, np.int32,\nnp.int64])),\n- Limitation(\n- \"preferred_element_type=f64 not implemented\",\n- devices=\"tpu\",\n- dtypes=(np.float16, jnp.bfloat16, np.float32),\n- enabled=(preferred_element_type in [np.float64])),\n- Limitation(\n- \"preferred_element_type=c128 not implemented\",\n- devices=\"tpu\",\n- dtypes=np.complex64,\n- enabled=(preferred_element_type in [np.complex128])),\n],\n)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Update JAX limitations. JAX has made progress in coverage of primitives on TPU. This PR updates those limitations.
260,411
09.05.2022 18:40:41
-10,800
91583f9c25a16d67574b28717895dc2546133948
[jax2tf] Update jax2tf limitations. It seems that TF has made progress and more JAX primitives can now be converted correctly to TF. This PR updates the limitations.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "new_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "diff": "@@ -76,13 +76,11 @@ More detailed information can be found in the\n| eig | TF error: function not compilable | all | cpu | compiled |\n| eigh | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu | compiled, eager, graph |\n| eigh | TF error: op not defined for dtype | bfloat16 | tpu | compiled, eager, graph |\n-| erf | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| erf_inv | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n-| erfc | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n-| fft | TF error: TF function not compileable | complex128, float64 | cpu, gpu | compiled |\n+| fft | TF error: TF function not compileable | float64 | cpu, gpu | compiled |\n+| fft | TF error: TF function not compileable for IFFT and IRFFT | complex128 | cpu, gpu | compiled |\n| igamma | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| igammac | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n-| integer_pow | TF error: op not defined for dtype | int16, int8, unsigned | cpu, gpu | graph |\n| lgamma | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| lu | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n| nextafter | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n@@ -103,7 +101,7 @@ More detailed information can be found in the\n| svd | TF error: op not defined for dtype | bfloat16 | tpu | compiled, eager, graph |\n| svd | TF error: op not defined for dtype | complex | tpu | compiled, graph |\n| triangular_solve | TF test skipped: Not implemented in JAX: unimplemented | float16 | gpu | compiled, eager, graph |\n-| triangular_solve | TF error: op not defined for dtype | bfloat16 | cpu, gpu, tpu | compiled, eager, graph |\n+| triangular_solve | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| triangular_solve | TF error: op not defined for dtype | float16 | cpu, gpu | eager, graph |\n## Generated summary of primitives with known numerical discrepancies in Tensorflow\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -558,21 +558,11 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef erf(cls, harness: primitive_harness.Harness):\n- return [\n- missing_tf_kernel(\n- dtypes=[dtypes.bfloat16],\n- devices=(\"cpu\", \"gpu\"),\n- modes=(\"eager\", \"graph\"))\n- ]\n+ return []\n@classmethod\ndef erfc(cls, harness: primitive_harness.Harness):\n- return [\n- missing_tf_kernel(\n- dtypes=[dtypes.bfloat16],\n- devices=(\"cpu\", \"gpu\"),\n- modes=(\"eager\", \"graph\"))\n- ]\n+ return []\n@classmethod\ndef erf_inv(cls, harness: primitive_harness.Harness):\n@@ -615,8 +605,15 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nJax2TfLimitation(\n\"TF function not compileable\",\ndevices=(\"cpu\", \"gpu\"),\n- dtypes=[np.float64, np.complex128],\n+ dtypes=[np.float64],\nmodes=\"compiled\"),\n+ Jax2TfLimitation(\n+ \"TF function not compileable for IFFT and IRFFT\",\n+ devices=(\"cpu\", \"gpu\"),\n+ dtypes=[np.complex128],\n+ modes=\"compiled\",\n+ enabled=(str(harness.params[\"fft_type\"]) in [\"FftType.IFFT\",\n+ \"FftType.IRFFT\"])),\n# TODO: very high tolerance\ncustom_numeric(tol=1e-3, modes=(\"eager\", \"graph\", \"compiled\")),\n]\n@@ -732,13 +729,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndef integer_pow(cls, harness: primitive_harness.Harness):\ny = harness.params[\"y\"]\nreturn [\n- missing_tf_kernel(\n- dtypes=[\n- np.int8, np.int16, np.uint8, np.uint16, np.uint32, np.uint64\n- ],\n- modes=\"graph\",\n- enabled=(y not in [0, 1]), # These are special-cased\n- devices=(\"cpu\", \"gpu\")),\n# TODO: on TPU, for f16, we get different results with eager mode\n# than with compiled mode.\nJax2TfLimitation(\n@@ -1211,7 +1201,10 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef triangular_solve(cls, harness: primitive_harness.Harness):\nreturn [\n- missing_tf_kernel(dtypes=[dtypes.bfloat16]),\n+ missing_tf_kernel(\n+ dtypes=[dtypes.bfloat16],\n+ devices=(\"gpu\", \"cpu\"),\n+ modes=(\"eager\", \"graph\")),\nmissing_tf_kernel(\ndtypes=[np.float16],\ndevices=(\"gpu\", \"cpu\"),\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Update jax2tf limitations. It seems that TF has made progress and more JAX primitives can now be converted correctly to TF. This PR updates the limitations.
260,631
09.05.2022 10:45:40
25,200
96173913f0b5a5024ca006d335be1ab6c191afa3
Add retry logic to `cloud_tpu_init.py` when API response fails
[ { "change_type": "MODIFY", "old_path": "jax/_src/cloud_tpu_init.py", "new_path": "jax/_src/cloud_tpu_init.py", "diff": "@@ -60,6 +60,7 @@ def cloud_tpu_init():\n# pylint: disable=import-outside-toplevel\n# pytype: disable=import-error\nimport requests\n+ import time\n# pytype: enable=import-error\n# pylint: enable=import-outside-toplevel\n@@ -68,11 +69,22 @@ def cloud_tpu_init():\n'GCE_METADATA_IP', 'metadata.google.internal')\ndef get_metadata(key):\n- return requests.get(\n+ retry_count = 0\n+ retrySeconds = 0.500\n+ api_resp = None\n+\n+ while retry_count < 6:\n+ api_resp = requests.get(\nf'{gce_metadata_endpoint}/computeMetadata/v1/instance/attributes/{key}',\n- headers={\n- 'Metadata-Flavor': 'Google'\n- }).text\n+ headers={'Metadata-Flavor': 'Google'})\n+ if api_resp.status == 200:\n+ break\n+ retry_count += 1\n+ time.sleep(retrySeconds)\n+\n+ if api_resp is None:\n+ raise RuntimeError(f\"Getting metadata['{key}'] failed for 6 tries\")\n+ return api_resp.text\nworker_id = get_metadata('agent-worker-number')\naccelerator_type = get_metadata('accelerator-type')\n" } ]
Python
Apache License 2.0
google/jax
Add retry logic to `cloud_tpu_init.py` when API response fails PiperOrigin-RevId: 447509510
260,447
09.05.2022 11:28:53
25,200
4bc1c1c00455ff2d07acb87dc03dcfd43b9c7014
[linalg] Add svd on zero matrix.
[ { "change_type": "MODIFY", "old_path": "tests/svd_test.py", "new_path": "tests/svd_test.py", "diff": "@@ -184,6 +184,25 @@ class SvdTest(jtu.JaxTestCase):\nactual_diff = jnp.diff(actual_s, append=0)\nnp.testing.assert_array_less(actual_diff, np.zeros_like(actual_diff))\n+ @parameterized.named_parameters([\n+ {'testcase_name': f'_m={m}_by_n={n}_full_matrices={full_matrices}_' # pylint:disable=g-complex-comprehension\n+ f'compute_uv={compute_uv}_dtype={dtype}',\n+ 'm': m, 'n': n, 'full_matrices': full_matrices, # pylint:disable=undefined-variable\n+ 'compute_uv': compute_uv, 'dtype': dtype} # pylint:disable=undefined-variable\n+ for m, n in zip([2, 4, 8], [4, 4, 6])\n+ for full_matrices in [True, False]\n+ for compute_uv in [True, False]\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.complex\n+ ])\n+ def testSvdOnZero(self, m, n, full_matrices, compute_uv, dtype):\n+ \"\"\"Tests SVD on matrix of all zeros.\"\"\"\n+ osp_fun = functools.partial(osp_linalg.svd, full_matrices=full_matrices,\n+ compute_uv=compute_uv)\n+ lax_fun = functools.partial(svd.svd, full_matrices=full_matrices,\n+ compute_uv=compute_uv)\n+ args_maker_svd = lambda: [jnp.zeros((m, n), dtype=dtype)]\n+ self._CheckAgainstNumpy(osp_fun, lax_fun, args_maker_svd)\n+ self._CompileAndCheck(lax_fun, args_maker_svd)\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[linalg] Add svd on zero matrix. PiperOrigin-RevId: 447521398
260,403
10.05.2022 09:43:36
25,200
882a2d5dd3abc301226657e20819a7550f8d8d9f
Rollback of PR "Improve performance of array integer indexing" This PR has broken some user models so needs to be investigated further before merging.
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -3416,12 +3416,6 @@ def _take(a, indices, axis: Optional[int] = None, out=None, mode=None):\ndef _normalize_index(index, axis_size):\n\"\"\"Normalizes an index value in the range [-N, N) to the range [0, N).\"\"\"\n- try:\n- idx, ndim = operator.index(index), operator.index(axis_size)\n- except TypeError:\n- pass\n- else:\n- return idx + ndim if idx < 0 else idx\nif issubdtype(_dtype(index), np.unsignedinteger):\nreturn index\nif core.is_constant_dim(axis_size):\n@@ -3536,6 +3530,7 @@ def _rewriting_take(arr, idx, indices_are_sorted=False, unique_indices=False,\n# Computes arr[idx].\n# All supported cases of indexing can be implemented as an XLA gather,\n# followed by an optional reverse and broadcast_in_dim.\n+ arr = asarray(arr)\n# TODO(mattjj,dougalm): expand dynamic shape indexing support\nif (jax.config.jax_dynamic_shapes and type(idx) is slice and idx.step is None\n@@ -3555,7 +3550,7 @@ def _rewriting_take(arr, idx, indices_are_sorted=False, unique_indices=False,\ndef _gather(arr, treedef, static_idx, dynamic_idx, indices_are_sorted,\nunique_indices, mode, fill_value):\nidx = _merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx)\n- indexer = _index_to_gather(arr.shape, idx) # shared with _scatter_update\n+ indexer = _index_to_gather(shape(arr), idx) # shared with _scatter_update\ny = arr\nif fill_value is not None:\n@@ -3584,10 +3579,7 @@ def _gather(arr, treedef, static_idx, dynamic_idx, indices_are_sorted,\ny = lax.rev(y, indexer.reversed_y_dims)\n# This adds np.newaxis/None dimensions.\n- if indexer.newaxis_dims:\n- y = lax.expand_dims(y, indexer.newaxis_dims)\n-\n- return y\n+ return expand_dims(y, indexer.newaxis_dims)\n_Indexer = collections.namedtuple(\"_Indexer\", [\n# The expected shape of the slice output.\n@@ -3654,17 +3646,8 @@ def _merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx):\nidx.append(s)\nreturn treedef.unflatten(idx)\n-def _is_basic_int_index(x):\n- if isinstance(x, core.Tracer):\n- aval = x.aval\n- return (isinstance(aval, ShapedArray) and not aval.shape\n- and issubdtype(aval.dtype, integer))\n- try:\n- operator.index(x)\n- except TypeError:\n- return False\n- else:\n- return not isinstance(x, (bool, np.bool_))\n+def _int(aval):\n+ return not aval.shape and issubdtype(aval.dtype, integer)\ndef _index_to_gather(x_shape, idx, normalize_indices=True):\n# Remove ellipses and add trailing slice(None)s.\n@@ -3706,7 +3689,7 @@ def _index_to_gather(x_shape, idx, normalize_indices=True):\ncollapsed_slice_dims = []\nstart_index_map = []\n- use_64bit_index = _any(not core.is_constant_dim(d) or d >= (1 << 31) for d in x_shape)\n+ use_64bit_index = _any([not core.is_constant_dim(d) or d >= (1 << 31) for d in x_shape])\nindex_dtype = int64 if use_64bit_index else int32\n# Gather indices.\n@@ -3742,7 +3725,8 @@ def _index_to_gather(x_shape, idx, normalize_indices=True):\nndim = len(shape)\nstart_dim = len(gather_indices_shape)\n- gather_indices += ((a, start_dim) for a in advanced_indexes)\n+ gather_indices += ((lax.convert_element_type(a, index_dtype), start_dim)\n+ for a in advanced_indexes)\ngather_indices_shape += shape\nstart_index_map.extend(x_advanced_axes)\n@@ -3757,12 +3741,17 @@ def _index_to_gather(x_shape, idx, normalize_indices=True):\ngather_slice_shape.append(1)\ncontinue\n+ try:\n+ abstract_i = core.get_aval(i)\n+ except TypeError:\n+ abstract_i = None\n# Handle basic int indexes.\n- if _is_basic_int_index(i):\n+ if isinstance(abstract_i, (ConcreteArray, ShapedArray)) and _int(abstract_i):\nif core.symbolic_equal_dim(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\")\ni = _normalize_index(i, x_shape[x_axis]) if normalize_indices else i\n+ i = lax.convert_element_type(i, index_dtype)\ngather_indices.append((i, len(gather_indices_shape)))\ncollapsed_slice_dims.append(x_axis)\ngather_slice_shape.append(1)\n@@ -3819,7 +3808,8 @@ def _index_to_gather(x_shape, idx, normalize_indices=True):\nif needs_rev:\nreversed_y_dims.append(collapsed_y_axis)\nif stride == 1:\n- gather_indices.append((start, len(gather_indices_shape)))\n+ i = lax.convert_element_type(start, index_dtype)\n+ gather_indices.append((i, len(gather_indices_shape)))\nslice_shape.append(limit - start)\ngather_slice_shape.append(limit - start)\noffset_dims.append(collapsed_y_axis)\n@@ -3839,10 +3829,6 @@ def _index_to_gather(x_shape, idx, normalize_indices=True):\ny_axis += 1\nx_axis += 1\nelse:\n- try:\n- abstract_i = core.get_aval(i)\n- except TypeError:\n- abstract_i = None\nif (abstract_i is not None and\nnot (issubdtype(abstract_i.dtype, integer) or issubdtype(abstract_i.dtype, bool_))):\nmsg = (\"Indexer must have integer or boolean type, got indexer \"\n@@ -3856,16 +3842,12 @@ def _index_to_gather(x_shape, idx, normalize_indices=True):\ngather_indices_array = np.zeros((0,), dtype=index_dtype)\nelif len(gather_indices) == 1:\ng, _ = gather_indices[0]\n- try:\n- gather_indices_array = np.array([operator.index(g)], dtype=index_dtype)\n- except TypeError:\n- gather_indices_array = lax.expand_dims(lax.convert_element_type(g, index_dtype), (g.ndim,))\n+ gather_indices_array = lax.expand_dims(g, (g.ndim,))\nelse:\nlast_dim = len(gather_indices_shape)\ngather_indices_shape.append(1)\ngather_indices_array = lax.concatenate([\n- lax.broadcast_in_dim(\n- lax.convert_element_type(g, index_dtype), gather_indices_shape, tuple(range(i, i + _ndim(g))))\n+ lax.broadcast_in_dim(g, gather_indices_shape, tuple(range(i, i + g.ndim)))\nfor g, i in gather_indices],\nlast_dim)\n@@ -3895,8 +3877,6 @@ def _eliminate_deprecated_list_indexing(idx):\n# non-tuple sequence containing slice objects, [Ellipses, or newaxis\n# objects]\". Detects this and raises a TypeError.\nif not isinstance(idx, tuple):\n- if isinstance(idx, (int, slice)):\n- return (idx,)\nif isinstance(idx, Sequence) and not isinstance(idx, (ndarray, np.ndarray)):\n# As of numpy 1.16, some non-tuple sequences of indices result in a warning, while\n# others are converted to arrays, based on a set of somewhat convoluted heuristics\n@@ -3916,11 +3896,13 @@ def _eliminate_deprecated_list_indexing(idx):\nreturn idx\ndef _is_boolean_index(i):\n- if isinstance(i, core.Tracer):\n- i = i.aval\n- return (isinstance(i, bool) or getattr(i, \"dtype\", None) == np.bool_ or\n- isinstance(i, list) and i and _all(_is_scalar(e)\n- and _dtype(e) == np.bool_ for e in i))\n+ try:\n+ abstract_i = core.get_aval(i)\n+ except TypeError:\n+ abstract_i = None\n+ return (isinstance(abstract_i, ShapedArray) and issubdtype(abstract_i.dtype, bool_)\n+ or isinstance(i, list) and i and _all(_is_scalar(e)\n+ and issubdtype(_dtype(e), np.bool_) for e in i))\ndef _expand_bool_indices(idx, shape):\n\"\"\"Converts concrete bool indexes into advanced integer indexes.\"\"\"\n@@ -3934,11 +3916,11 @@ def _expand_bool_indices(idx, shape):\nif e is not None and e is not Ellipsis)\nellipsis_offset = 0\nfor dim_number, i in enumerate(idx):\n- if _is_boolean_index(i):\ntry:\nabstract_i = core.get_aval(i)\nexcept TypeError:\nabstract_i = None\n+ if _is_boolean_index(i):\nif isinstance(i, list):\ni = array(i)\nabstract_i = core.get_aval(i)\n@@ -3977,7 +3959,7 @@ def _is_advanced_int_indexer(idx):\n# https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing\nassert isinstance(idx, tuple)\nif _all(e is None or e is Ellipsis or isinstance(e, slice)\n- or _is_basic_int_index(e) for e in idx):\n+ or _is_scalar(e) and issubdtype(_dtype(e), np.integer) for e in idx):\nreturn False\nreturn _all(e is None or e is Ellipsis or isinstance(e, slice)\nor _is_int_arraylike(e) for e in idx)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_indexing_test.py", "new_path": "tests/lax_numpy_indexing_test.py", "diff": "@@ -871,19 +871,6 @@ class IndexingTest(jtu.JaxTestCase):\njaxpr = jax.make_jaxpr(lambda x: x[:4])(np.arange(4))\nself.assertEqual(len(jaxpr.jaxpr.eqns), 0)\n- @parameterized.named_parameters(\n- {\"testcase_name\": f\"_{idx_type_name}_{idx}\", \"idx\": idx, \"idx_type\": idx_type}\n- for idx in (-3, 5)\n- for idx_type_name, idx_type in (\n- (\"int\", int), (\"np.array\", np.array), (\"jnp.array\", jnp.array),\n- (\"slice_up_to\", slice), (\"slice_from\", lambda s: slice(s, None))))\n- def testConstantIndexing(self, idx, idx_type):\n- x = jnp.arange(10)\n- idx = idx_type(idx)\n- jaxpr = jax.make_jaxpr(lambda: x[idx])()\n- self.assertEqual(len(jaxpr.jaxpr.eqns), 1)\n- self.assertEqual(jaxpr.jaxpr.eqns[0].primitive, lax.gather_p)\n-\ndef testIndexingEmptyDimension(self):\n# Issue 2671: XLA error when indexing into dimension of size 0\nx = jnp.ones((2, 0))\n" } ]
Python
Apache License 2.0
google/jax
Rollback of PR #10393 "Improve performance of array integer indexing" This PR has broken some user models so needs to be investigated further before merging. PiperOrigin-RevId: 447756000
260,447
10.05.2022 13:02:18
25,200
48f47c36c4f671e9cdd068a7ab67f0dc19d0a6f9
[linalg] Fix a bug in computing derivatives of scipy.special.lpmn.
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/special.py", "new_path": "jax/_src/scipy/special.py", "diff": "@@ -769,7 +769,7 @@ def _gen_derivatives(p: jnp.ndarray,\nif num_l > 2:\nl_vec = jnp.arange(2, num_l - 1)\np_p2 = p[2, 2:num_l - 1, :]\n- coeff = 1.0 / ((l_vec + 2) * (l_vec + 1) * l_vec)\n+ coeff = 1.0 / ((l_vec + 2) * (l_vec + 1) * l_vec * (l_vec - 1))\nupdate_p_p2 = jnp.einsum('i,ij->ij', coeff, p_p2)\np_mm2_lm1 = p_mm2_lm1.at[0, 3:num_l, :].set(update_p_p2)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -322,7 +322,7 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\n{\"testcase_name\": \"_{}_lmax={}\".format(\njtu.format_shape_dtype_string(shape, dtype), l_max),\n\"l_max\": l_max, \"shape\": shape, \"dtype\": dtype}\n- for l_max in [1, 2, 3]\n+ for l_max in [1, 2, 3, 6]\nfor shape in [(5,), (10,)]\nfor dtype in float_dtypes))\ndef testLpmn(self, l_max, shape, dtype):\n@@ -336,8 +336,9 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nvals, derivs = zip(*(osp_special.lpmn(m, n, zi) for zi in z))\nreturn np.dstack(vals), np.dstack(derivs)\n- self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, rtol=1e-6, atol=1e-6)\n- self._CompileAndCheck(lax_fun, args_maker, rtol=1E-6, atol=1E-6)\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, rtol=1e-5,\n+ atol=3e-3)\n+ self._CompileAndCheck(lax_fun, args_maker, rtol=1E-5, atol=3e-3)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_lmax={}\".format(\n" } ]
Python
Apache License 2.0
google/jax
[linalg] Fix a bug in computing derivatives of scipy.special.lpmn. PiperOrigin-RevId: 447807140
260,510
10.05.2022 13:13:55
25,200
7d27343506d58b35f1f103651b72e83d0c6893df
Attach keepalive to pmap executable
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1048,16 +1048,17 @@ def lower_parallel_callable(\ntuple_args = should_tuple_args(shards)\nmodule_name = f\"pmap_{fun.__name__}\"\nwith maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\n- effects = list(closed_jaxpr.effects)\n- # TODO(sharadmv): attach keepalive to computation\n+ if any(eff in core.ordered_effects for eff in closed_jaxpr.effects):\n+ raise ValueError(\"Ordered effects not supported in `pmap`.\")\nmodule, keepalive = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, effects, backend.platform, mlir.ReplicaAxisContext(axis_env),\n- name_stack, donated_invars, replicated_args=replicated_args,\n+ module_name, closed_jaxpr, [], backend.platform,\n+ mlir.ReplicaAxisContext(axis_env), name_stack, donated_invars,\n+ replicated_args=replicated_args,\narg_shardings=_shardings_to_mlir_shardings(parts.arg_parts),\nresult_shardings=_shardings_to_mlir_shardings(parts.out_parts))\n- del keepalive\nreturn PmapComputation(module, pci=pci, replicas=replicas, parts=parts,\n- shards=shards, tuple_args=tuple_args)\n+ shards=shards, tuple_args=tuple_args,\n+ keepalive=keepalive)\nclass PmapComputation(stages.Computation):\n@@ -1107,7 +1108,8 @@ class PmapExecutable(stages.Executable):\nreplicas: ReplicaInfo,\nparts: 'PartitionInfo',\nshards: ShardInfo,\n- tuple_args: bool):\n+ tuple_args: bool,\n+ keepalive: Any):\ndevices = pci.devices\nif devices is None:\nif shards.num_global_shards > xb.device_count(pci.backend):\n@@ -1215,7 +1217,8 @@ class PmapExecutable(stages.Executable):\npci.backend, xla_computation, compile_options)\nhandle_args = InputsHandler(\ncompiled.local_devices(), input_sharding_specs, input_indices)\n- execute_fun = ExecuteReplicated(compiled, pci.backend, handle_args, handle_outs)\n+ execute_fun = ExecuteReplicated(compiled, pci.backend, handle_args,\n+ handle_outs, keepalive)\nfingerprint = getattr(compiled, \"fingerprint\", None)\nreturn PmapExecutable(compiled, execute_fun, fingerprint, pci.avals)\n@@ -1552,14 +1555,16 @@ def partitioned_sharding_spec(num_partitions: int,\nclass ExecuteReplicated:\n\"\"\"The logic to shard inputs, execute a replicated model, returning outputs.\"\"\"\n- __slots__ = ['xla_executable', 'backend', 'in_handler', 'out_handler']\n+ __slots__ = ['xla_executable', 'backend', 'in_handler', 'out_handler',\n+ 'keepalive']\ndef __init__(self, xla_executable, backend, in_handler: InputsHandler,\n- out_handler: ResultsHandler):\n+ out_handler: ResultsHandler, keepalive: Any):\nself.xla_executable = xla_executable\nself.backend = backend\nself.in_handler = in_handler\nself.out_handler = out_handler\n+ self.keepalive = keepalive\n@profiler.annotate_function\ndef __call__(self, *args):\n@@ -2219,19 +2224,19 @@ def lower_mesh_computation(\nmodule: Union[str, xc.XlaComputation]\nmodule_name = f\"{api_name}_{fun_name}\"\nwith core.extend_axis_env_nd(mesh.shape.items()):\n- effects = list(closed_jaxpr.effects)\n- # TODO(sharadmv): attach keepalive to computation\n+ if any(eff in core.ordered_effects for eff in closed_jaxpr.effects):\n+ raise ValueError(\"Ordered effects not supported in mesh computations.\")\nmodule, keepalive = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, effects, backend.platform, axis_ctx, name_stack,\n+ module_name, closed_jaxpr, [], backend.platform, axis_ctx, name_stack,\ndonated_invars, replicated_args=replicated_args,\narg_shardings=in_partitions, result_shardings=out_partitions)\n- del keepalive\nreturn MeshComputation(\nstr(name_stack), module, donated_invars, mesh=mesh, global_in_avals=global_in_avals,\nglobal_out_avals=global_out_avals, in_axes=in_axes, out_axes=out_axes,\nspmd_lowering=spmd_lowering, tuple_args=tuple_args, in_is_global=in_is_global,\n- auto_spmd_lowering=auto_spmd_lowering)\n+ auto_spmd_lowering=auto_spmd_lowering,\n+ keepalive=keepalive)\nclass MeshComputation(stages.Computation):\n@@ -2337,7 +2342,8 @@ class MeshExecutable(stages.Executable):\nin_is_global: Sequence[bool],\nauto_spmd_lowering: bool,\n_allow_propagation_to_outputs: bool,\n- _allow_compile_replicated: bool) -> 'MeshExecutable':\n+ _allow_compile_replicated: bool,\n+ keepalive: Any) -> 'MeshExecutable':\nassert not mesh.empty\nbackend = xb.get_device_backend(mesh.devices.flat[0])\n@@ -2383,7 +2389,8 @@ class MeshExecutable(stages.Executable):\nglobal_in_avals, mesh, in_axes, in_is_global)\nhandle_outs = global_avals_to_results_handler(global_out_avals, out_axes, mesh) # type: ignore # arg-type\nhandle_args = InputsHandler(xla_executable.local_devices(), input_specs, input_indices)\n- unsafe_call = ExecuteReplicated(xla_executable, backend, handle_args, handle_outs)\n+ unsafe_call = ExecuteReplicated(xla_executable, backend, handle_args,\n+ handle_outs, keepalive)\nreturn MeshExecutable(xla_executable, unsafe_call, input_avals,\nin_axes, out_axes, auto_spmd_lowering)\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -44,6 +44,17 @@ def capture_stdout() -> Generator[Callable[[], str], None, None]:\ndef _format_multiline(text):\nreturn textwrap.dedent(text).lstrip()\n+prev_xla_flags = None\n+\n+def setUpModule():\n+ global prev_xla_flags\n+ # This will control the CPU devices. On TPU we always have 2 devices\n+ prev_xla_flags = jtu.set_host_platform_device_count(2)\n+\n+# Reset to previous configuration in case other test modules will be run.\n+def tearDownModule():\n+ prev_xla_flags()\n+\nclass DebugPrintTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n@@ -311,10 +322,34 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nb3: 2\n\"\"\"))\n+class DebugPrintParallelTest(jtu.JaxTestCase):\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\", \"cpu\")\n+ def test_ordered_print_not_supported_in_pmap(self):\n+\n+ @jax.pmap\n+ def f(x):\n+ debug_print(\"{}\", x, ordered=True)\n+ with self.assertRaisesRegex(\n+ ValueError, \"Ordered effects not supported in `pmap`.\"):\n+ f(jnp.arange(jax.local_device_count()))\n+\n+ # TODO(sharadmv): Enable test on CPU when we have output tokens to block on\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\", \"cpu\")\n+ def test_unordered_print_works_in_pmap(self):\n+\n+ @jax.pmap\n+ def f(x):\n+ debug_print(\"{}\", x, ordered=False)\n+ with capture_stdout() as output:\n+ f(jnp.arange(jax.local_device_count()))\n+ self.assertSetEqual(set(\"0\\n1\\n\".split(\"\\n\")), set(output().split(\"\\n\")))\n+\nif jaxlib.version < (0, 3, 8):\n# No lowering for `emit_python_callback` in older jaxlibs.\ndel DebugPrintTest\ndel DebugPrintControlFlowTest\n+ del DebugPrintParallelTest\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -85,6 +85,7 @@ callback_p = core.Primitive('callback')\ncallback_p.multiple_results = True\nmlir.lowerable_effects.add('log')\n+mlir.lowerable_effects.add('unordered_log')\ncore.ordered_effects.add('log')\n@callback_p.def_impl\n@@ -100,6 +101,7 @@ def _(*avals, callback, out_avals, effect):\ndef callback_effect_lowering(ctx: mlir.LoweringRuleContext, *args, callback, out_avals, effect):\ndel out_avals\n+ if effect in core.ordered_effects:\ndef _token_callback(token, *args):\nout = callback(*args)\nflat_out = jax.tree_util.tree_leaves(out)\n@@ -109,9 +111,14 @@ def callback_effect_lowering(ctx: mlir.LoweringRuleContext, *args, callback, out\nctx.module_context.platform, _token_callback,\n[token_in, *args], [core.abstract_token, *ctx.avals_in],\n[core.abstract_token, *ctx.avals_out], True)\n- ctx.module_context.add_keepalive(keep_alive)\nctx.set_tokens_out(ctx.tokens_in.update_tokens(mlir.TokenSet({effect:\ntoken_out})))\n+ else:\n+ out_op, keep_alive = mlir.emit_python_callback(\n+ ctx.module_context.platform, callback,\n+ list(args), list(ctx.avals_in),\n+ list(ctx.avals_out), True)\n+ ctx.module_context.add_keepalive(keep_alive)\nreturn out_op\nmlir.register_lowering(callback_p, callback_effect_lowering)\n@@ -618,6 +625,57 @@ class EffectOrderingTest(jtu.JaxTestCase):\ntoken1, token2 = tokens\nself.assertIsNot(token1, token2)\n+class ParallelEffectsTest(jtu.JaxTestCase):\n+\n+ def test_cannot_pmap_unlowerable_effect(self):\n+\n+ def f(x):\n+ # abc is not lowerable\n+ effect_p.bind(effect='abc')\n+ return x\n+ with self.assertRaisesRegex(\n+ ValueError, \"Cannot lower jaxpr with effects: {'abc'}\"):\n+ jax.pmap(f)(jnp.arange(jax.local_device_count()))\n+\n+ def test_cannot_pmap_ordered_effect(self):\n+\n+ def f(x):\n+ # foo is lowerable and ordered\n+ effect_p.bind(effect='foo')\n+ return x\n+ with self.assertRaisesRegex(\n+ ValueError, \"Ordered effects not supported in `pmap`.\"):\n+ jax.pmap(f)(jnp.arange(jax.local_device_count()))\n+\n+ def test_can_pmap_unordered_effect(self):\n+\n+ def f(x):\n+ # bar is lowerable and unordered\n+ effect_p.bind(effect='bar')\n+ return x\n+ jax.pmap(f)(jnp.arange(jax.local_device_count()))\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_can_pmap_unordered_callback(self):\n+ # TODO(sharadmv): remove jaxlib check when minimum version is bumped\n+ # TODO(sharadmv): enable this test on GPU and TPU when backends are\n+ # supported\n+ if jaxlib.version < (0, 3, 8):\n+ raise unittest.SkipTest(\"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices.\")\n+ log = set()\n+ def log_value(x):\n+ log.add(int(x))\n+ return ()\n+\n+ @jax.pmap\n+ def f(x):\n+ callback_p.bind(\n+ x, callback=log_value, effect='unordered_log', out_avals=[])\n+ return x + 1\n+ f(jnp.arange(2)).block_until_ready()\n+ self.assertSetEqual(set([0, 1]), log)\nclass ControlFlowEffectsTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Attach keepalive to pmap executable PiperOrigin-RevId: 447810195
260,447
11.05.2022 09:59:17
25,200
52ad3e6682ef85c1f6724ce2e194da5f2423613b
[linalg] Extend svd test coverage to input of zero and near-zero elements.
[ { "change_type": "MODIFY", "old_path": "tests/svd_test.py", "new_path": "tests/svd_test.py", "diff": "@@ -201,5 +201,32 @@ class SvdTest(jtu.JaxTestCase):\nself._CheckAgainstNumpy(osp_fun, lax_fun, args_maker_svd)\nself._CompileAndCheck(lax_fun, args_maker_svd)\n+\n+ @parameterized.named_parameters([\n+ {'testcase_name': f'_m={m}_by_n={n}_r={r}_c={c}_dtype={dtype}',\n+ 'm': m, 'n': n, 'r': r, 'c': c, 'dtype': dtype}\n+ for m, n, r, c in zip([2, 4, 8], [4, 4, 6], [1, 0, 1], [1, 0, 1])\n+ for dtype in jtu.dtypes.floating\n+ ])\n+ def testSvdOnTinyElement(self, m, n, r, c, dtype):\n+ \"\"\"Tests SVD on matrix of zeros and close-to-zero entries.\"\"\"\n+ a = jnp.zeros((m, n), dtype=dtype)\n+ tiny_element = jnp.finfo(a).tiny\n+ a = a.at[r, c].set(tiny_element)\n+\n+ @jax.jit\n+ def lax_fun(a):\n+ return svd.svd(a, full_matrices=False, compute_uv=False, hermitian=False)\n+\n+ actual_s = lax_fun(a)\n+\n+ k = min(m, n)\n+ expected_s = np.zeros((k,), dtype=dtype)\n+ expected_s[0] = tiny_element\n+\n+ self.assertAllClose(expected_s, jnp.real(actual_s), rtol=_SVD_RTOL,\n+ atol=1E-6)\n+\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[linalg] Extend svd test coverage to input of zero and near-zero elements. PiperOrigin-RevId: 448019846
260,510
11.05.2022 11:07:00
25,200
aca9dc6c6f40eb99886568dbf1b70cc4d56a4e0f
Update custom interpreter tutorial
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "new_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "diff": "\"source\": [\n\"To get a first look at Jaxprs, consider the `make_jaxpr` transformation. `make_jaxpr` is essentially a \\\"pretty-printing\\\" transformation:\\n\",\n\"it transforms a function into one that, given example arguments, produces a Jaxpr representation of its computation.\\n\",\n- \"Although we can't generally use the Jaxprs that it returns, it is useful for debugging and introspection.\\n\",\n- \"Let's use it to look at how some example Jaxprs\\n\",\n- \"are structured.\"\n+ \"`make_jaxpr` is useful for debugging and introspection.\\n\",\n+ \"Let's use it to look at how some example Jaxprs are structured.\"\n]\n},\n{\n\"\\n\",\n\"### 1. Tracing a function\\n\",\n\"\\n\",\n- \"We can't use `make_jaxpr` for this, because we need to pull out constants created during the trace to pass into the Jaxpr. However, we can write a function that does something very similar to `make_jaxpr`.\"\n+ \"Let's use `make_jaxpr` to trace a function into a Jaxpr.\"\n]\n},\n{\n\"id\": \"CpTml2PTrzZ4\"\n},\n\"source\": [\n- \"This function first flattens its arguments into a list, which are the abstracted and wrapped as partial values. The `jax.make_jaxpr` function is used to then trace a function into a Jaxpr\\n\",\n- \"from a list of partial value inputs.\"\n+ \"`jax.make_jaxpr` returns a *closed* Jaxpr, which is a Jaxpr that has been bundled with\\n\",\n+ \"the constants (`literals`) from the trace.\"\n]\n},\n{\n\" return jnp.exp(jnp.tanh(x))\\n\",\n\"\\n\",\n\"closed_jaxpr = jax.make_jaxpr(f)(jnp.ones(5))\\n\",\n- \"print(closed_jaxpr)\\n\",\n+ \"print(closed_jaxpr.jaxpr)\\n\",\n\"print(closed_jaxpr.literals)\"\n]\n},\n\"source\": [\n\"Notice that `eval_jaxpr` will always return a flat list even if the original function does not.\\n\",\n\"\\n\",\n- \"Furthermore, this interpreter does not handle `subjaxprs`, which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/main/jax/core.py)) to see the edge cases that this interpreter does not cover.\"\n+ \"Furthermore, this interpreter does not handle higher-order primitives (like `jit` and `pmap`), which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/main/jax/core.py)) to see the edge cases that this interpreter does not cover.\"\n]\n},\n{\n\"def inverse(fun):\\n\",\n\" @wraps(fun)\\n\",\n\" def wrapped(*args, **kwargs):\\n\",\n- \" # Since we assume unary functions, we won't\\n\",\n- \" # worry about flattening and\\n\",\n- \" # unflattening arguments\\n\",\n+ \" # Since we assume unary functions, we won't worry about flattening and\\n\",\n+ \" # unflattening arguments.\\n\",\n\" closed_jaxpr = jax.make_jaxpr(fun)(*args, **kwargs)\\n\",\n\" out = inverse_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.literals, *args)\\n\",\n\" return out[0]\\n\",\n\" # outvars are now invars \\n\",\n\" invals = safe_map(read, eqn.outvars)\\n\",\n\" if eqn.primitive not in inverse_registry:\\n\",\n- \" raise NotImplementedError(\\\"{} does not have registered inverse.\\\".format(\\n\",\n- \" eqn.primitive\\n\",\n- \" ))\\n\",\n+ \" raise NotImplementedError(\\n\",\n+ \" f\\\"{eqn.primitive} does not have registered inverse.\\\")\\n\",\n\" # Assuming a unary function \\n\",\n\" outval = inverse_registry[eqn.primitive](*invals)\\n\",\n\" safe_map(write, eqn.invars, [outval])\\n\",\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.md", "new_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.md", "diff": "@@ -70,9 +70,8 @@ for function transformation.\nTo get a first look at Jaxprs, consider the `make_jaxpr` transformation. `make_jaxpr` is essentially a \"pretty-printing\" transformation:\nit transforms a function into one that, given example arguments, produces a Jaxpr representation of its computation.\n-Although we can't generally use the Jaxprs that it returns, it is useful for debugging and introspection.\n-Let's use it to look at how some example Jaxprs\n-are structured.\n+`make_jaxpr` is useful for debugging and introspection.\n+Let's use it to look at how some example Jaxprs are structured.\n```{code-cell} ipython3\n:id: RSxEiWi-EeYW\n@@ -139,7 +138,7 @@ The way we'll implement this is by (1) tracing `f` into a Jaxpr, then (2) interp\n### 1. Tracing a function\n-We can't use `make_jaxpr` for this, because we need to pull out constants created during the trace to pass into the Jaxpr. However, we can write a function that does something very similar to `make_jaxpr`.\n+Let's use `make_jaxpr` to trace a function into a Jaxpr.\n```{code-cell} ipython3\n:id: BHkg_3P1pXJj\n@@ -155,8 +154,8 @@ from jax._src.util import safe_map\n+++ {\"id\": \"CpTml2PTrzZ4\"}\n-This function first flattens its arguments into a list, which are the abstracted and wrapped as partial values. The `jax.make_jaxpr` function is used to then trace a function into a Jaxpr\n-from a list of partial value inputs.\n+`jax.make_jaxpr` returns a *closed* Jaxpr, which is a Jaxpr that has been bundled with\n+the constants (`literals`) from the trace.\n```{code-cell} ipython3\n:id: Tc1REN5aq_fH\n@@ -165,7 +164,7 @@ def f(x):\nreturn jnp.exp(jnp.tanh(x))\nclosed_jaxpr = jax.make_jaxpr(f)(jnp.ones(5))\n-print(closed_jaxpr)\n+print(closed_jaxpr.jaxpr)\nprint(closed_jaxpr.literals)\n```\n@@ -224,7 +223,7 @@ eval_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.literals, jnp.ones(5))\nNotice that `eval_jaxpr` will always return a flat list even if the original function does not.\n-Furthermore, this interpreter does not handle `subjaxprs`, which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/main/jax/core.py)) to see the edge cases that this interpreter does not cover.\n+Furthermore, this interpreter does not handle higher-order primitives (like `jit` and `pmap`), which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/main/jax/core.py)) to see the edge cases that this interpreter does not cover.\n+++ {\"id\": \"0vb2ZoGrCMM4\"}\n@@ -261,9 +260,8 @@ inverse_registry[lax.tanh_p] = jnp.arctanh\ndef inverse(fun):\n@wraps(fun)\ndef wrapped(*args, **kwargs):\n- # Since we assume unary functions, we won't\n- # worry about flattening and\n- # unflattening arguments\n+ # Since we assume unary functions, we won't worry about flattening and\n+ # unflattening arguments.\nclosed_jaxpr = jax.make_jaxpr(fun)(*args, **kwargs)\nout = inverse_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.literals, *args)\nreturn out[0]\n@@ -296,9 +294,8 @@ def inverse_jaxpr(jaxpr, consts, *args):\n# outvars are now invars\ninvals = safe_map(read, eqn.outvars)\nif eqn.primitive not in inverse_registry:\n- raise NotImplementedError(\"{} does not have registered inverse.\".format(\n- eqn.primitive\n- ))\n+ raise NotImplementedError(\n+ f\"{eqn.primitive} does not have registered inverse.\")\n# Assuming a unary function\noutval = inverse_registry[eqn.primitive](*invals)\nsafe_map(write, eqn.invars, [outval])\n" } ]
Python
Apache License 2.0
google/jax
Update custom interpreter tutorial
260,335
11.05.2022 11:18:25
25,200
28672970bb07686c79e9b4e18cf420df420211f2
fix grad(..., argnums=-1), regressed in
[ { "change_type": "MODIFY", "old_path": "jax/_src/api_util.py", "new_path": "jax/_src/api_util.py", "diff": "import operator\nfrom functools import partial\n-from typing import Any, Dict, Iterable, Tuple, Union, Optional\n+from typing import Any, Dict, Iterable, Tuple, Sequence, Union, Optional\nimport numpy as np\n@@ -135,6 +135,7 @@ class _HashableWithStrictTypeEquality:\ndef argnums_partial(f, dyn_argnums, args, require_static_args_hashable=True):\ndyn_argnums = _ensure_index_tuple(dyn_argnums)\n+ dyn_argnums = _ensure_inbounds(False, len(args), dyn_argnums)\nif require_static_args_hashable:\nfixed_args = []\nfor i, arg in enumerate(args):\n@@ -151,11 +152,25 @@ def argnums_partial(f, dyn_argnums, args, require_static_args_hashable=True):\ndyn_args = tuple(args[i] for i in dyn_argnums)\nreturn _argnums_partial(f, dyn_argnums, tuple(fixed_args)), dyn_args\n+def _ensure_inbounds(allow_invalid: bool, num_args: int, argnums: Sequence[int]\n+ ) -> Tuple[int, ...]:\n+ result = []\n+ for i in argnums:\n+ if i >= num_args and allow_invalid: continue\n+ if not -num_args <= i < num_args:\n+ raise ValueError(\n+ \"Positional argument indices, e.g. for `static_argnums`, must have \"\n+ \"value greater than or equal to -len(args) and less than len(args), \"\n+ f\"but got value {i} for len(args) == {num_args}.\")\n+ result.append(i % num_args)\n+ return tuple(result)\n+\ndef argnums_partial_except(f: lu.WrappedFun, static_argnums: Tuple[int, ...],\nargs: Tuple[Any], *, allow_invalid: bool):\n\"\"\"Version of ``argnums_partial`` that checks hashability of static_argnums.\"\"\"\nif not static_argnums:\nreturn f, args\n+ static_argnums = _ensure_inbounds(allow_invalid, len(args), static_argnums)\ndyn_argnums = tuple(i for i in range(len(args)) if i not in static_argnums)\ndyn_args = tuple(args[i] for i in dyn_argnums)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3486,6 +3486,19 @@ class APITest(jtu.JaxTestCase):\nfinally:\nFLAGS.jax_numpy_rank_promotion = allow_promotion\n+ def test_grad_negative_argnums(self):\n+ def f(x, y):\n+ return x.sum() * y.sum()\n+\n+ x = jax.random.normal(jax.random.PRNGKey(0), (16, 16))\n+ y = jax.random.normal(jax.random.PRNGKey(1), (16, 16))\n+ g = jax.grad(f, argnums=-1)\n+ g(x, y) # doesn't crash\n+\n+ def test_jit_negative_static_argnums(self):\n+ g = jax.jit(lambda x, y: x * y, static_argnums=-1)\n+ g(1, 2) # doesn't crash\n+\nclass RematTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
fix grad(..., argnums=-1), regressed in #10453
260,510
10.05.2022 10:43:03
25,200
2bce098f1526ebc27115aceed9c2865f33e7d6e0
Add sequencing effects design note
[ { "change_type": "MODIFY", "old_path": "docs/design_notes/index.rst", "new_path": "docs/design_notes/index.rst", "diff": "@@ -9,3 +9,4 @@ Design Notes\nomnistaging\nprng\ntype_promotion\n+ sequencing_effects\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/design_notes/sequencing_effects.md", "diff": "+# Sequencing side-effects in JAX\n+_sharadmv@_\n+_May 9 2022_\n+\n+## Overview\n+\n+When we write JAX code, we can usually pretend we're writing single-threaded, eagerly-executed Python\n+even though underneath the hood, JAX and its runtime may execute it asynchronously in the background.\n+As long as we write pure (side-effect-free) code, these performance optimizations are usually invisible to us and don't interfere with our single-threaded mental model.\n+Asynchronous execution is great -- we get performant, parallel code without\n+having to think about it at all!\n+\n+However, in the presence of side-effects, the illusion begins to break down and\n+the cracks in our mental model start to show. Specifically, these differences\n+show up when we think about the *order* in which side-effects happen.\n+\n+In this design note, we explore the interaction between JAX's execution model,\n+and the ordering of side-effects. We also provide a way of enforcing a\n+\"single-threaded\" ordering of effects.\n+\n+## Background\n+\n+When we write the following Python code\n+```python\n+def f():\n+ print(\"hello\")\n+ return 2\n+def g():\n+ print(\"world\")\n+ return 3\n+f()\n+g()\n+```\n+we expect `\"hello\"` to be printed before `\"world\"`. This might seem obvious\n+but consider the following JAX code:\n+```python\n+@partial(jax.jit, device=<device 0>)\n+def f():\n+ return 2\n+\n+@partial(jax.jit, device=<device 1>)\n+def g():\n+ return 3\n+f()\n+g()\n+```\n+In many cases, JAX will execute `f` and `g` *in parallel*, dispatching\n+the computations onto different threads -- `g` might actually be executed\n+before `f`. Parallel execution is a nice performance optimization, especially if copying\n+to and from a device is expensive (see the [asynchronous dispatch note](https://jax.readthedocs.io/en/latest/async_dispatch.html) for more details).\n+In practice, however, we often don't need to\n+think about asynchronous dispatch because we're writing pure functions and only\n+care about the inputs and outputs of functions -- we'll naturally block on future\n+values.\n+\n+However, now imagine that we have a `jax.print` function that works inside of\n+JIT-ted JAX functions (`host_callback.id_print` is an example of this). Let's\n+return to the previous example except with prints in the mix.\n+```python\n+@partial(jax.jit, device=<device 0>)\n+def f():\n+ jax.print(\"hello\")\n+ return 2\n+\n+@partial(jax.jit, device=<device 1>)\n+def g():\n+ jax.print(\"world\")\n+ return 3\n+f()\n+g()\n+```\n+Thanks to asynchronous dispatch, we could actually see `\"world\"` being printed\n+before `\"hello\"`. The reordering of the print side-effects breaks the illusion\n+of a single-threaded execution model.\n+\n+Another example of where side-effects can \"reveal\" out-of-order execution is\n+when we we compile JAX programs. Consider the following JAX code:\n+```python\n+@jax.jit\n+def f(x):\n+ jax.print(\"hello\")\n+ jax.print(\"world\")\n+ return x\n+```\n+Even though in Python, we've written the the `\"hello\"` print before the `\"world\"` print,\n+a compiler like XLA is free to reorder them because there's no explicit data-dependence between the prints.\n+\n+## Motivation\n+\n+We'd like to support \"ordered\" effects. When we say ordered, we mean that the effects\n+occur in the same order as we would if we were executing a single-threaded Python program.\n+This is our main desideratum. In the presence of explicit parallelism like `pmap` or\n+user threads, we don't need to maintain this behavior but at least if the user is not\n+explicitly requesting parallelism, we'd like to preserve a single-threaded ordering.\n+\n+Before we dive in more, let's first step back and ask ourselves if it is okay\n+if we reorder effects in the name of performance, and conversely, do we need to\n+enforce an ordering on effects at all? In some cases, we don't need ordering.\n+Maybe some side-effects shouldn't adversely affect the\n+performance of a JAX program. However, for other side-effects, we may\n+want to enforce a single-threaded program order so users don't get counterintuitive\n+behavior. Consider a logging effect.\n+```python\n+@jax.jit\n+def f(x, y):\n+ log_value(x)\n+ log_value(y)\n+f(1, 2)\n+```\n+If `log` is mutating a global list, we might expect that we add `x` before adding `y`.\n+For a more strict effect, we may want the option to order the effects.\n+\n+## Enforcing ordered effects\n+\n+The main tool we have to enforce the ordering of computations is *data-dependence*.\n+Simply put, if a function `g` has an input that is the output of a function `f`,\n+`f` must be executed before `g`.\n+\n+However, we may have side effects like prints that have no inputs at all\n+so naively we couldn't sequence them. We thus use *tokens* as a means of injecting\n+artificial data-dependence into a computation.\n+\n+What is a token? A token is just a dummy value that can be threaded in and out of a computation.\n+By threading the same token in and out and several computations, we enforce that they have to happen\n+in a certain order. Let's take the previous print example and see what it would look like with tokens\n+in the mix:\n+```python\n+@jax.jit\n+def f(token, x):\n+ token = jax.print(token, \"hello\")\n+ token = jax.print(token, \"world\")\n+ return token, x\n+```\n+If we rewrite `jax.print` to take in and return a token, we have now sequenced\n+the two prints since the input to the second print depends is the output of the first print.\n+The actual value of `token` can be anything really, but we'll see in practice\n+that the tokens are invisible to users.\n+\n+## Runtime tokens vs. compiler tokens\n+\n+Here we will actually start talking about implementation details. In practice, we'll need\n+two separate types of tokens to sequence effects: one for each of the aforementioned sources\n+of reordering. We'll need *runtime tokens* to sequence asynchronously dispatched\n+side-effecting computations and we'll need *compiler tokens* to sequence effects within computations.\n+\n+In practice, our computation will be rewritten to look like this:\n+```python\n+@jax.jit\n+def f(runtime_token, x):\n+ compiler_token = new_compiler_token()\n+ compiler_token = jax.print(compiler_token, \"hello\")\n+ compiler_token = jax.print(compiler_token, \"world\")\n+ return runtime_token, x\n+```\n+Notice how the runtime tokens are only used at the JIT boundary and the compiler tokens\n+are only within the compiled code. Compiler tokens are created during\n+\"lowering\" (we convert Python code to a lower level representation like HLO or MHLO)\n+but runtime tokens need to be managed in Python since they're being threaded in and out\n+of JIT-ted functions.\n+\n+Furthermore, notice that the runtime tokens are \"disconnected\"\n+from the compiler tokens meaning there's no data dependency between them. This could\n+potentially be dangerous as if we will lose the data dependence between the bodies\n+of two dispatched function calls. However, if we assume \"strict execution\" -- i.e.\n+a dispatched function will only start execution when all of its inputs are ready\n+and all of it outputs will become ready at the same time -- we are safe to create a\n+fresh compiler token and return a non-output-dependent runtime token.\n+\n+\n+## Managing runtime tokens\n+\n+To manage runtime tokens on behalf of the user, we'll need to hook into JAX's dispatch machinery.\n+Whenever we call a JIT-ted function, we eventually bottom out in a function that looks like\n+this:\n+```python\n+def _execute(compiled_computation, *args):\n+ outputs = compiled_computation.execute(*args)\n+ return outputs\n+```\n+At this point we need to \"inject\" the runtime tokens into the computation\n+and \"extract\" them from the computation's outputs:\n+```python\n+def _execute(compiled_computation, *args):\n+ runtime_token = get_runtime_token() # Grab global token\n+ runtime_token, *outputs = compiled_computation.execute(runtime_token, *args)\n+ update_runtime_token(runtime_token) # Update global token\n+ return outputs\n+```\n+\n+What is `runtime_token` exactly? Well we need to be able to pass it into a `compiled_computation`,\n+which means it needs to be some sort of array (for now, since there's no shared token representation\n+inside and outside compiled JAX code). In practice we can use a `(0,)`-shaped array to minimize overheads.\n+\n+\n+We also need to think about the multiple device use case, e.g. the first example where\n+we first call a JIT-ted function on device 0 and then one on device 1.\n+In that case, we need to also *copy* the runtime token returned from the first computation (which lives on device 0)\n+to device 1 so we can pass it into the second computation. If two subsequent computations share the same device,\n+this copy is not necessary.\n+\n+## Adding compiler tokens\n+\n+When we lower Python code to HLO or MHLO we need to create a token at the start of the computation and\n+ensure they are available when we have side-effecting computations that need to be ordered. The side-effecting\n+computations will take the token as input and return it as an output.\n+\n+The implementation of this token threading involves upgrading the JAX lowering machinery to do\n+this bookkeeping automatically.\n+The main challenges involve dealing with higher-order primitives like call primitives\n+and control-flow primitives. We won't go into details in how to handle those in this design note.\n+\n+## Blocking on output tokens\n+\n+Adding support for runtime and compiler tokens for side-effecting computations is important for sequencing\n+but there's also another subtle use-case for tokens, which is blocking on side-effecting computations.\n+Even if we don't want a side-effecting computation to be *ordered* we may still want to wait on its\n+completion. Currently we have `jax.block_until_ready`, which waits until a future value has its\n+result ready. However, with side-effecting computations, we may have functions that don't have a return\n+value but are still executing a side-effect. Take the simple example here:\n+```python\n+@jax.jit\n+def f():\n+ jax.print(\"hello world\")\n+ return\n+f() # Executed asynchronously\n+```\n+This compiled computation takes no explicit inputs and has no explicit outputs. If it was an ordered print effect,\n+we could block on the returned runtime token, However,\n+when this is an unordered computation we don't do any token threading. How do we wait for `f()` to\n+finish executing when we have no output value to call `block_until_ready` on? Well, we could apply our same\n+token strategy except we only return runtime tokens and don't take them as inputs. This will give us\n+a value to block on that will only be ready once `f()` is done being executed. We'll call these tokens\n+*output tokens*. We end up with a function that looks like this:\n+```python\n+@jax.jit\n+def f():\n+ jax.print(\"hello world\")\n+ return new_runtime_token()\n+f() # Executed asynchronously\n+```\n+\n+Underneath the hood, we'll manage the output tokens in the same way we manage the runtime tokens but\n+provide a method for users to block on the current set of output tokens. Unlike runtime tokens,\n+output tokens need to be *device-specific*.\n+Consider a single device use-case:\n+\n+```python\n+@jax.jit\n+def f():\n+ jax.print(\"hello\")\n+\n+@jax.jit\n+def g():\n+ jax.print(\"world\")\n+\n+f()\n+g()\n+```\n+Since `f()` and `g()` are executed on the same device, blocking on `g()`'s output token\n+effectively blocks on `f()` since (as of now!), the JAX runtime does not interleave computations\n+executed on the same device. We'll have to revise this entire design if that changes, of course.\n+\n+However, consider the two device use-case:\n+```python\n+@partial(jax.jit, device=<device 0>)\n+def f():\n+ jax.print(\"hello\")\n+\n+@partial(jax.jit, device=<device 1>)\n+def g():\n+ jax.print(\"world\")\n+\n+f()\n+g()\n+```\n+Here we don't want to explicitly sequence `f()` and `g()` but want to wait for both of them to finish.\n+We'll need one output token for `f()` and one for `g()` and we'll block on both of those tokens:\n+```python\n+@partial(jax.jit, device=<device 0>)\n+def f():\n+ jax.print(\"hello\")\n+ return new_runtime_token()\n+\n+@partial(jax.jit, device=<device 1>)\n+def g():\n+ jax.print(\"world\")\n+ return new_runtime_token()\n+\n+t0 = f()\n+t1 = g()\n+block_until_ready((t0, t1))\n+```\n+We'll thus need a per-device output token so we can avoid sequencing computations on different\n+devices while offering the ability to block on side-effecting computations. We end up with the following\n+(approximate) change to the JAX dispatch machinery:\n+\n+```python\n+def _execute(compiled_computation, *args):\n+ output_token, *outputs = compiled_computation.execute(runtime_token, *args)\n+ update_output_token(output_token, compiled_computation.device)\n+ return outputs\n+```\n+We'll also need to expose a function to that blocks on the output token:\n+```python\n+def effects_barrier():\n+ output_token.block_until_ready()\n+```\n+\n+Note that blocking on output tokens may not be fairly common since most JAX computations will return\n+a value to block on. However, output tokens are helpful for testing and profiling, and are good to\n+support so that we have a consistent and cohesive effect system.\n+\n+## Some more details\n+\n+* All of the aforementioned token management infrastructure will be *thread-local*. This means\n+ that each user thread will have their own independent stream of runtime tokens. Sequencing\n+ is only promised at a user thread level.\n+* In practice, we have one runtime token per effect. Different instances of that effect will be\n+ sequenced. This is to avoid sequencing effectul computations that may not have any relation to each\n+ other. Technically this goes against our original goal though of enforcing a single-threaded Python\n+ program ordering, but this is a tradeoff that could be modulated by having both \"effect\"-specific tokens\n+ and \"global\" tokens.\n" } ]
Python
Apache License 2.0
google/jax
Add sequencing effects design note
260,532
11.05.2022 21:19:28
0
4a631886c67e36368f8e76dc28099d8777d3cbc8
Fixed a typo in `cloud_tpu_init.py`
[ { "change_type": "MODIFY", "old_path": "jax/_src/cloud_tpu_init.py", "new_path": "jax/_src/cloud_tpu_init.py", "diff": "@@ -77,7 +77,7 @@ def cloud_tpu_init():\napi_resp = requests.get(\nf'{gce_metadata_endpoint}/computeMetadata/v1/instance/attributes/{key}',\nheaders={'Metadata-Flavor': 'Google'})\n- if api_resp.status == 200:\n+ if api_resp.status_code == 200:\nbreak\nretry_count += 1\ntime.sleep(retrySeconds)\n" } ]
Python
Apache License 2.0
google/jax
Fixed a typo in `cloud_tpu_init.py`
260,335
05.05.2022 15:18:57
25,200
0b841cf35bf05b46504f575c727afac2ab368359
make core_test.py pass with core.call
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -593,7 +593,7 @@ def call_transpose(primitive, params, call_jaxpr, args, ct, _, reduce_axes):\nfun = lu.hashable_partial(lu.wrap_init(backward_pass), call_jaxpr,\nreduce_axes, False)\nfun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\n- if not config.jax_experimental_name_stack:\n+ if 'name' in params and not config.jax_experimental_name_stack:\nparams = dict(params, name=wrap_name(params['name'], 'transpose'))\nupdate_params = call_transpose_param_updaters.get(primitive)\nif update_params:\n" }, { "change_type": "MODIFY", "old_path": "tests/core_test.py", "new_path": "tests/core_test.py", "diff": "@@ -32,8 +32,10 @@ from jax import jvp, linearize, vjp, jit, make_jaxpr\nfrom jax.core import UnshapedArray, ShapedArray\nfrom jax.tree_util import (tree_flatten, tree_unflatten, tree_map, tree_reduce,\ntree_leaves)\n+from jax.api_util import flatten_fun_nokwargs\nfrom jax.interpreters import partial_eval as pe\n+from jax._src import util\nfrom jax._src import test_util as jtu\nfrom jax._src.abstract_arrays import make_shaped_array\nfrom jax._src.lax import lax as lax_internal\n@@ -47,6 +49,13 @@ __ = pe.PartialVal.unknown(ShapedArray((), np.float32))\ndef call(f, *args):\nreturn jit(f)(*args)\n+@util.curry\n+def core_call(f, *args):\n+ args, in_tree = tree_flatten(args)\n+ f, out_tree = flatten_fun_nokwargs(lu.wrap_init(f), in_tree)\n+ out = core.call_p.bind(f, *args)\n+ return tree_unflatten(out_tree(), out)\n+\ndef simple_fun(x, y):\nreturn jnp.sin(x * y)\n@@ -135,6 +144,9 @@ for ts in test_specs_base:\ntest_specs.append(CallSpec(partial(jvp, ts.fun), (ts.args, ts.args)))\ntest_specs.append(CallSpec(jit(ts.fun), ts.args))\ntest_specs.append(CallSpec(jit(jit(ts.fun)), ts.args))\n+ test_specs.append(CallSpec(core_call(ts.fun), ts.args))\n+ test_specs.append(CallSpec(core_call(jit(ts.fun)), ts.args))\n+ test_specs.append(CallSpec(core_call(core_call(ts.fun)), ts.args))\ntest_specs.append(CallSpec(partial(jvp_unlinearized, ts.fun),\n(ts.args, ts.args)))\n" } ]
Python
Apache License 2.0
google/jax
make core_test.py pass with core.call
260,301
12.05.2022 19:45:41
-3,600
e422441a65872eb698f51509eb9a3c726ea8c420
fix: mypy warning
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/shape_poly.py", "new_path": "jax/experimental/jax2tf/shape_poly.py", "diff": "@@ -823,7 +823,7 @@ def _solve_dim_equations(eqns: List[DimEquation]) -> ShapeEnv:\n# TODO(necula): check even in graph mode, by embedding the checks in\n# the graph.\nmsg = (f\"Dimension variable {var} must have integer value >= 1. \" # type: ignore\n- f\"Found value {int(_is_known_constant(dim_expr)) / factor_var} when solving \"\n+ f\"Found value {int(_is_known_constant(dim_expr)) / factor_var} when solving \" # type: ignore\nf\"{eqn.poly} == {eqn.dim_expr}.{_shapeenv_to_str()}\")\nraise ValueError(msg)\nvar_value_int = _is_known_constant(var_value)\n" } ]
Python
Apache License 2.0
google/jax
fix: mypy warning
260,335
12.05.2022 16:55:50
25,200
d719e5a55fb1bc1614da75036902f4d39bb05796
tweak mlir shape_tensor helper, fewer MHLO ops
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -79,11 +79,13 @@ def i64_attr(i): return ir.IntegerAttr.get(ir.IntegerType.get_signless(64), i)\ndef shape_tensor(sizes: Sequence[Union[int, ir.RankedTensorType]]\n) -> ir.RankedTensorType:\n- sizes = [ir_constant(np.array(d, np.dtype('int32'))) if type(d) is int else d\n- for d in sizes]\nint1d = aval_to_ir_type(core.ShapedArray((1,), np.dtype('int32')))\n- return mhlo.ConcatenateOp([mhlo.ReshapeOp(int1d, d) for d in sizes],\n- i64_attr(0)).results\n+ d, *ds = [ir_constant(np.array([d], np.dtype('int32'))) if type(d) is int\n+ else mhlo.ReshapeOp(int1d, d) for d in sizes]\n+ if not ds:\n+ return d\n+ else:\n+ return mhlo.ConcatenateOp([d, *ds], i64_attr(0)).result\n# IR Types\n" } ]
Python
Apache License 2.0
google/jax
tweak mlir shape_tensor helper, fewer MHLO ops
260,573
14.05.2022 16:13:38
-3,600
8579e28570e3db99a4dfa3dd7b85537a3123082f
tests: add lax.scatter to tests
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -949,6 +949,10 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndef scatter_mul(cls, harness):\nreturn []\n+ @classmethod\n+ def scatter(cls, harness):\n+ return []\n+\n@classmethod\ndef select_and_gather_add(cls, harness):\nreturn [\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -1272,7 +1272,7 @@ def _make_scatter_harness(name,\n# Validate dtypes\nfor dtype in jtu.dtypes.all:\nfor f_lax in [\n- lax.scatter_add, lax.scatter_mul, lax.scatter_max, lax.scatter_min\n+ lax.scatter, lax.scatter_add, lax.scatter_mul, lax.scatter_max, lax.scatter_min\n]:\n_make_scatter_harness(\"dtypes\", dtype=dtype, f_lax=f_lax)\n" } ]
Python
Apache License 2.0
google/jax
tests: add lax.scatter to tests
260,573
14.05.2022 16:21:05
-3,600
17f8638fd451e46fc387ef6f32a8db13b2a92e5a
feat: support subset of scatters with no XLA Supports: Scatters with unique indices e.g..at[:, ((3,4),(5,5)), 3].add Contiguous scatters with non-unique indices of single depth e.g..at[:, ((2,2,2),)].add
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/no_xla_limitations.md", "new_path": "jax/experimental/jax2tf/g3doc/no_xla_limitations.md", "diff": "@@ -33,7 +33,7 @@ For a detailed description of these XLA ops, please see the\n| XlaConv | `lax.conv_general_dilated` | [Partial](#xlaconv) |\n| XlaGather | `lax.gather` | [Partial](#xlagather) |\n| XlaReduceWindow | `lax.reduce_window_sum_p`, `lax.reduce_window_min_p`, `lax.reduce_window_max_p`, and `lax.reduce_window_p` | [Partial](#xlareducewindow) |\n-| XlaScatter | `lax.scatter_p`, `lax.scatter_min_p`, `lax.scatter_max_p`, `lax.scatter_mul_p`, `lax.scatter_add_p` | Unsupported |\n+| XlaScatter | `lax.scatter_p`, `lax.scatter_min_p`, `lax.scatter_max_p`, `lax.scatter_mul_p`, `lax.scatter_add_p` | [Partial](#xlascatter) |\n| XlaSelectAndScatter | `lax.select_and_scatter_add_p` | Unsupported |\n| XlaReduce | `lax.reduce`, `lax.argmin`, `lax.argmax` | Unsupported |\n| XlaVariadicSort | `lax.sort` | Unsupported |\n@@ -153,3 +153,15 @@ We support these ops with the following limitations:\n* `padding` should either be `VALID` or `SAME`.\n`lax.reduce_window_min_p` and `lax.reduce_window` are currently not supported.\n+\n+### XlaScatter\n+\n+This op is called by `lax.scatter`, `lax.scatter_min`, `lax.scatter_max`,\n+`lax.scatter_mul` and `lax.scatter_add`.\n+\n+We support all these ops for unique indices. For non-unique indices we\n+support (min,max,mul,add) for single depth scatters.\n+\n+There are a few more limitations:\n+* the GatherScatterMode must be PROMISE_IN_BOUNDS.\n+* dtypes `np.bool` and `jnp.complex*` are not supported.\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/impl_no_xla.py", "new_path": "jax/experimental/jax2tf/impl_no_xla.py", "diff": "@@ -792,10 +792,128 @@ def _dynamic_update_slice(operand, update, *start_indices,\ntf_impl_no_xla[lax.dynamic_update_slice_p] = _dynamic_update_slice\n-tf_impl_no_xla[lax.scatter_p] = _unimplemented(\"scatter\")\n-tf_impl_no_xla[lax.scatter_min_p] = _unimplemented(\"scatter min\")\n-tf_impl_no_xla[lax.scatter_max_p] = _unimplemented(\"scatter max\")\n-tf_impl_no_xla[lax.scatter_mul_p] = _unimplemented(\"scatter mul\")\n-tf_impl_no_xla[lax.scatter_add_p] = _unimplemented(\"scatter add\")\n+\n+def shift_axes_forward(operand, axes: tuple, inverse: bool=False,\n+ forward: bool=True):\n+ \"\"\"Shifts the tuple of axes to the front of an array\"\"\"\n+ other_axes = tuple([i for i in range(len(operand.shape)) if i not in axes])\n+ fwd_order = axes + other_axes if forward else other_axes + axes\n+ order = fwd_order if not inverse else tf.math.invert_permutation(fwd_order)\n+ return tf.transpose(operand, order)\n+\n+def convert_scatter_jax_to_tf(update_op, unsorted_segment_op=None):\n+ def error(msg):\n+ suffix = (\"See source code for the precise conditions under which \"\n+ \"scatter_(update/add/multiply/min/max) ops can be converted without XLA.\")\n+ return _xla_disabled_error(\"scatter_(update/add/multiply/min/max)\", f\"{msg} - {suffix}\")\n+\n+ def _sparse_scatter(\n+ operand,\n+ scatter_indices,\n+ updates,\n+ update_jaxpr,\n+ update_consts,\n+ dimension_numbers,\n+ indices_are_sorted: bool,\n+ unique_indices: bool,\n+ mode,\n+ _in_avals: Sequence[core.ShapedArray],\n+ _out_aval: core.ShapedArray):\n+ \"\"\"\n+ Implementation of scatter specialised to indexing from the\n+ front axes. This covers unique indices and non-unique indices\n+ of single depth.\n+\n+ Note on unique indices: `tf.tensor_scatter_nd_update` interprets\n+ indices thusly: every axis except the final one encodes a batch\n+ dimension, the final axis encoding the actual indices to scatter in to.\n+ It enforces, at least one, batch dimension so we add an empty\n+ dimension to indices and updates if lacking.\n+\n+ Note on non-unique indices: There is no tf op for non single depth\n+ indexing. But if indexing is single depth, this can be viewed as a\n+ segment op.\n+ \"\"\"\n+ # Infer unique indices from lack of batch dimension\n+ unique_indices = unique_indices or (len(scatter_indices.shape) == 1)\n+ if unique_indices:\n+ suboperand = tf.gather_nd(operand, scatter_indices)\n+ updated_suboperand = update_op(suboperand, updates)\n+ # add a batch dim if none exist\n+ if len(scatter_indices.shape) == 1:\n+ scatter_indices = scatter_indices[None]\n+ updated_suboperand = updated_suboperand[None]\n+ y = tf.tensor_scatter_nd_update(operand, scatter_indices, updated_suboperand)\n+ else:\n+ if (scatter_indices.shape[-1] == 1) and (unsorted_segment_op != None):\n+ # If only indexing into the first dimension, it's a segment op\n+ operand_update = unsorted_segment_op(updates, tf.squeeze(scatter_indices, -1), operand.shape[0])\n+ y = update_op(operand, operand_update)\n+ else:\n+ raise error(\"Scatter supports unique indices. Scatter also supports non-unique indices with indexing into only one dimension for (add, mul, min, max)\")\n+ return y\n+\n+ def sparse_scatter(\n+ operand,\n+ scatter_indices,\n+ updates,\n+ update_jaxpr,\n+ update_consts,\n+ dimension_numbers,\n+ indices_are_sorted: bool,\n+ unique_indices: bool,\n+ mode,\n+ _in_avals: Sequence[core.ShapedArray],\n+ _out_aval: core.ShapedArray):\n+ \"\"\"\n+ Wrapper around the scatter function.\n+ The underlying tf ops `tf.tensor_scatter_nd_update` and\n+ `tf.math.unsorted_segment_*` index from the front dimensions.\n+ `tf.math.unsorted_segment_*` indexs to a depth 1 from the front.\n+ `tf.tensor_scatter_nd_update` indexs from the front dimensions onwards\n+ , with no ability to skip a dimension. This function\n+ shifts the axes to be indexed to the front then calls a front-specific\n+ implementation, then inverse-shifts the output.\n+\n+ scatter_dims_to_operand_dims: dimensions which the scatter indexes in to.\n+ We shift these to the front to match tf syntax. All other dims are batch\n+ update_window_dims: dimensions which are not batch dimensions. We shift\n+ these to the back as the remaining dimensions are batch dimensions.\n+ \"\"\"\n+ ud = dimension_numbers.update_window_dims\n+ wd = dimension_numbers.inserted_window_dims\n+ sd = dimension_numbers.scatter_dims_to_operand_dims\n+ dtype = operand.dtype # assume updates has same dtype as operand\n+ if dtype in [tf.bool, tf.complex64]:\n+ raise error(f\"Scatter does not support operands of type {dtype}\")\n+ if not (wd == sd):\n+ raise error(\"Complex scatters are not supported\")\n+ if not (mode == lax.GatherScatterMode.PROMISE_IN_BOUNDS):\n+ raise error(\"Only scatter mode `PROMISE_IN_BOUNDS` is supported\")\n+ # Shift axes to the front to match tf syntax, inverse afterwards\n+ fwd = partial(shift_axes_forward, axes=sd)\n+ inv = partial(fwd, inverse=True)\n+ # shift update value axes to the back, so batch are at the front\n+ updates_shifted = shift_axes_forward(updates, axes=ud, forward=False)\n+ return inv(_sparse_scatter(\n+ fwd(operand),\n+ scatter_indices,\n+ updates_shifted,\n+ update_jaxpr,\n+ update_consts,\n+ dimension_numbers,\n+ indices_are_sorted,\n+ unique_indices,\n+ mode,\n+ _in_avals,\n+ _out_aval,\n+ ))\n+ return sparse_scatter\n+\n+tf_impl_no_xla[lax.scatter_p] = convert_scatter_jax_to_tf(lambda x,y: y) # just replace with the update\n+tf_impl_no_xla[lax.scatter_add_p] = convert_scatter_jax_to_tf(tf.add, tf.math.unsorted_segment_sum)\n+tf_impl_no_xla[lax.scatter_mul_p] = convert_scatter_jax_to_tf(tf.multiply, tf.math.unsorted_segment_prod)\n+tf_impl_no_xla[lax.scatter_min_p] = convert_scatter_jax_to_tf(tf.minimum, tf.math.unsorted_segment_min)\n+tf_impl_no_xla[lax.scatter_max_p] = convert_scatter_jax_to_tf(tf.maximum, tf.math.unsorted_segment_max)\ntf_impl_no_xla[lax.sort_p] = _unimplemented(\"sort\")\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -1236,11 +1236,12 @@ def _make_scatter_harness(name,\nupdate_shape=(2,),\nmode=lax.GatherScatterMode.FILL_OR_DROP,\ndtype=np.float32,\n- dimension_numbers=((), (0,), (0,))):\n+ dimension_numbers=((), (0,), (0,)),\n+ enable_xla=True):\ndimension_numbers = lax.ScatterDimensionNumbers(*dimension_numbers)\ndefine(\nf_lax.__name__,\n- f\"{name}_shape={jtu.format_shape_dtype_string(shape, dtype)}_scatterindices={scatter_indices.tolist()}_updateshape={update_shape}_updatewindowdims={dimension_numbers.update_window_dims}_insertedwindowdims={dimension_numbers.inserted_window_dims}_scatterdimstooperanddims={dimension_numbers.scatter_dims_to_operand_dims}_indicesaresorted={indices_are_sorted}_uniqueindices={unique_indices}_mode={mode}\"\n+ f\"{name}_shape={jtu.format_shape_dtype_string(shape, dtype)}_scatterindices={scatter_indices.tolist()}_updateshape={update_shape}_updatewindowdims={dimension_numbers.update_window_dims}_insertedwindowdims={dimension_numbers.inserted_window_dims}_scatterdimstooperanddims={dimension_numbers.scatter_dims_to_operand_dims}_indicesaresorted={indices_are_sorted}_uniqueindices={unique_indices}_mode={mode}_enablexla={enable_xla}\"\n.replace(\" \", \"\"),\npartial(\nf_lax,\n@@ -1266,7 +1267,8 @@ def _make_scatter_harness(name,\ndimension_numbers=dimension_numbers,\nindices_are_sorted=indices_are_sorted,\nunique_indices=unique_indices,\n- mode=mode)\n+ mode=mode,\n+ enable_xla=enable_xla)\n# Validate dtypes\n@@ -1315,6 +1317,60 @@ for mode in (lax.GatherScatterMode.PROMISE_IN_BOUNDS,\nscatter_indices=np.array([[4], [77]]),\nupdate_shape=(2,))\n+# Validate no XLA scatters\n+for dtype in set(jtu.dtypes.all) - set(jtu.dtypes.complex) - set(jtu.dtypes.boolean):\n+ for f_lax in [\n+ lax.scatter_add, lax.scatter_mul, lax.scatter_max, lax.scatter_min, lax.scatter\n+ ]:\n+ for shape, scatter_indices, update_shape, dimension_numbers in [\n+ ((1,), (0,), (), ((), (0,), (0,))), # zero case\n+ ((1, 1), (0,), (1,), ((0,), (0,), (0,))),\n+ ((1, 1, 1), (0,), (1, 1), ((0, 1), (0,), (0,))),\n+ ((1, 50, 3), (32,), (1, 3), ((0, 1), (1,), (1,))),\n+ ((1, 2, 3), [1], (1, 3), ((0, 1), (1,), (1,))), # slice 2nd dim\n+ ((1, 2, 3), [0], (2, 3), ((0, 1), (0,), (0,))), # slice 1st dim\n+ ((1, 2, 3), [1, 2], (1,), ((0,), (1, 2), (1, 2))), # 2nd and 3rd\n+ ((4, 2, 3), [3, 2], (2,), ((0,), (0, 2), (0, 2))), # 1st and 3rd\n+ ((4, 2, 3, 5), [0, 4], (4, 3), ((0, 1), (1, 3), (1, 3))), # 2nd and 4th\n+ ((5, 6, 7), [[0, 1],[2, 3]], (2, 7), ((1,), (0, 1), (0, 1))), # .at[((3,4),(5,5))] shapes\n+ ((5, 6, 7), [[[0],[1]],[[2],[3]]], (5, 2, 2, 7), ((0, 3), (1,), (1,))), # .at[:, ((3,4),(5,5))] shapes\n+ ((5, 6, 7), [[[0, 1],[2, 3]],[[4, 0],[1, 2]]], (5,2,2), ((0,), (1, 2), (1, 2))), # .at[:, ((3,4),(5,5)), 3] shapes\n+ ]:\n+ _make_scatter_harness(\"no_xla_unique_indices\",\n+ shape=shape,\n+ f_lax=f_lax,\n+ unique_indices=True,\n+ scatter_indices=np.array(scatter_indices),\n+ update_shape=update_shape,\n+ mode=lax.GatherScatterMode.PROMISE_IN_BOUNDS,\n+ dtype=dtype,\n+ dimension_numbers=dimension_numbers,\n+ enable_xla=False,\n+ )\n+\n+# Validate no XLA scatters with non-unique indices with an indexing depth of 1\n+for dtype in set(jtu.dtypes.all) - set(jtu.dtypes.complex) - set(jtu.dtypes.boolean):\n+ for f_lax in [\n+ lax.scatter_add, lax.scatter_mul, lax.scatter_max, lax.scatter_min\n+ ]:\n+ for shape, scatter_indices, update_shape, dimension_numbers in [\n+ ((1,), [[0],[0]], (2,), ((), (0,), (0,))), # .at[((0,0),)]\n+ ((3,), [[1],[0],[1]], (3,), ((), (0,), (0,))), # .at[((1,0,1),)]\n+ ((2, 3), [[[2],[2],[2]]], (2, 1, 3), ((0,), (1,), (1,))), # 2nd dim, .at[:, ((2,2,2),)]\n+ ((3, 5, 40), [[1],[1]], (3, 5, 2), ((0, 1), (2,), (2,))),\n+ ((3, 5, 4), [[1],[1]], (3, 2, 4), ((0, 2), (1,), (1,))),\n+ ]:\n+ _make_scatter_harness(\"no_xla_non_unique_indices\",\n+ shape=shape,\n+ f_lax=f_lax,\n+ unique_indices=False,\n+ scatter_indices=np.array(scatter_indices),\n+ update_shape=update_shape,\n+ mode=lax.GatherScatterMode.PROMISE_IN_BOUNDS,\n+ dtype=dtype,\n+ dimension_numbers=dimension_numbers,\n+ enable_xla=False,\n+ )\nfor dtype in jtu.dtypes.all:\narg_shape = (2, 3)\n" } ]
Python
Apache License 2.0
google/jax
feat: support subset of scatters with no XLA Supports: - Scatters with unique indices e.g..at[:, ((3,4),(5,5)), 3].add - Contiguous scatters with non-unique indices of single depth e.g..at[:, ((2,2,2),)].add
260,335
04.05.2022 22:59:06
25,200
c0d6a04b7666ff58fc92d5fee78772bf11012a8a
remove jnp.array case for handling buffers w/ aval=None This functionality was added in but was superceded by later changes which ensured that we never produce DeviceArrays with their 'aval' property set to None (even when indexing ShardedDeviceArrays with integers, which used to be a problem case).
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1806,15 +1806,16 @@ def array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nlax_internal._check_user_dtype_supported(dtype, \"array\")\n# Here we make a judgment call: we only return a weakly-typed array when the\n- # input object itself is weakly typed. That ensures asarray(x) is a no-op whenever\n- # x is weak, but avoids introducing weak types with something like array([1, 2, 3])\n+ # input object itself is weakly typed. That ensures asarray(x) is a no-op\n+ # whenever x is weak, but avoids introducing weak types with something like\n+ # array([1, 2, 3])\nweak_type = dtype is None and dtypes.is_weakly_typed(object)\n- # For Python scalar literals, call coerce_to_array to catch any overflow errors.\n- # We don't use dtypes.is_python_scalar because we don't want this triggering for\n- # traced values. We do this here because it matters whether or not dtype is None.\n- # We don't assign the result because we want the raw object to be used for type\n- # inference below.\n+ # For Python scalar literals, call coerce_to_array to catch any overflow\n+ # errors. We don't use dtypes.is_python_scalar because we don't want this\n+ # triggering for traced values. We do this here because it matters whether or\n+ # not dtype is None. We don't assign the result because we want the raw object\n+ # to be used for type inference below.\nif isinstance(object, (bool, int, float, complex)):\n_ = dtypes.coerce_to_array(object, dtype)\n@@ -1838,17 +1839,13 @@ def array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nndarray_types = (device_array.DeviceArray, core.Tracer)\nif not _any(isinstance(leaf, ndarray_types) for leaf in leaves):\n- # TODO(jakevdp): falling back to numpy here fails to overflow for lists containing\n- # large integers; see discussion in https://github.com/google/jax/pull/6047.\n- # More correct would be to call coerce_to_array on each leaf, but this may have\n- # performance implications.\n+ # TODO(jakevdp): falling back to numpy here fails to overflow for lists\n+ # containing large integers; see discussion in\n+ # https://github.com/google/jax/pull/6047. More correct would be to call\n+ # coerce_to_array on each leaf, but this may have performance implications.\nout = np.array(object, dtype=dtype, ndmin=ndmin, copy=False)\nelif isinstance(object, ndarray_types):\n- if object.aval is None:\n- # object is a raw buffer; convert to device array on its current device.\n- aval = ShapedArray(object.xla_shape().dimensions(), object.dtype,\n- weak_type=bool(getattr(object, \"weak_type\", False)))\n- object = device_array.make_device_array(aval, object.device(), object)\n+ assert object.aval is not None\nout = _array_copy(object) if copy else object\nelif isinstance(object, (list, tuple)):\nif object:\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -117,7 +117,12 @@ class PythonPmapTest(jtu.JaxTestCase):\ndef testDeviceBufferToArray(self):\nsda = self.pmap(lambda x: x)(jnp.ones((jax.device_count(), 2)))\n- buf = sda.device_buffers[-1]\n+\n+ # Changed in https://github.com/google/jax/pull/10584 not to access\n+ # sda.device_buffers, which isn't supported, and instead ensure fast slices\n+ # of the arrays returned by pmap are set up correctly.\n+ # buf = sda.device_buffers[-1]\n+ buf = sda[-1]\nview = jnp.array(buf, copy=False)\nself.assertArraysEqual(sda[-1], view)\n" } ]
Python
Apache License 2.0
google/jax
remove jnp.array case for handling buffers w/ aval=None This functionality was added in #8134, but was superceded by later changes which ensured that we never produce DeviceArrays with their 'aval' property set to None (even when indexing ShardedDeviceArrays with integers, which used to be a problem case).
260,335
14.05.2022 11:03:50
25,200
05dda560195fa2f6bf26ab75472c2c6a3c99a79a
add core.closed_call_p
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -17,7 +17,7 @@ import collections\nfrom collections import namedtuple\nfrom contextlib import contextmanager\nimport functools\n-from functools import partialmethod, total_ordering\n+from functools import partial, partialmethod, total_ordering\nimport gc\nimport itertools as it\nimport operator\n@@ -207,8 +207,6 @@ class JaxprEqn(NamedTuple):\nreturn self._replace(*args, **kwargs)\ndef new_jaxpr_eqn(invars, outvars, primitive, params, effects, source_info=None):\n- if primitive.call_primitive:\n- assert len(outvars) == len(params[\"call_jaxpr\"].outvars)\nsource_info = source_info or source_info_util.new_source_info()\nreturn JaxprEqn(invars, outvars, primitive, params, effects, source_info)\n@@ -1822,6 +1820,17 @@ named_call_p: CallPrimitive = CallPrimitive('named_call')\nnamed_call_p.def_impl(call_impl)\n+class ClosedCallPrimitive(CallPrimitive):\n+ def get_bind_params(self, params):\n+ new_params = dict(params)\n+ jaxpr = new_params.pop('call_jaxpr')\n+ subfun = lu.wrap_init(partial(eval_jaxpr, jaxpr.jaxpr, jaxpr.consts))\n+ return [subfun], new_params\n+\n+closed_call_p: ClosedCallPrimitive = ClosedCallPrimitive('closed_call')\n+closed_call_p.def_impl(call_impl)\n+\n+\noutfeed_primitives: Set[Primitive] = set()\ndef jaxpr_uses_outfeed(jaxpr: Jaxpr) -> bool:\n\"\"\"Finds if there are outfeed primitives anywhere inside a Jaxpr.\"\"\"\n@@ -2169,6 +2178,12 @@ class JaxprTypeError(TypeError): pass\ncustom_typechecks: Dict[Primitive, Callable] = {}\n+def _check_closed_call(*in_avals, call_jaxpr):\n+ if list(in_avals) != list(call_jaxpr.in_avals):\n+ raise JaxprTypeError(\"Closed call in_avals mismatch\")\n+ return call_jaxpr.out_avals, call_jaxpr.effects\n+custom_typechecks[closed_call_p] = _check_closed_call\n+\ndef check_jaxpr(jaxpr: Jaxpr):\n\"\"\"Checks well-formedness of a jaxpr.\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -983,6 +983,7 @@ tf_not_yet_impl = [\n\"reduce_precision\",\n\"schur\",\n\"name\",\n+ \"closed_call\",\n\"unreachable\",\n\"bint\",\n\"getslice\",\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -605,6 +605,16 @@ def call_transpose(primitive, params, call_jaxpr, args, ct, _, reduce_axes):\nout_flat = primitive.bind(fun, *all_args, **params)\nreturn tree_unflatten(out_tree(), out_flat)\nprimitive_transposes[core.call_p] = partial(call_transpose, call_p)\n+primitive_transposes[core.named_call_p] = \\\n+ partial(call_transpose, core.named_call_p)\n+\n+\n+def _closed_call_transpose(params, jaxpr, args, ct, cts_in_avals, reduce_axes):\n+ jaxpr_, consts = jaxpr.jaxpr, jaxpr.consts\n+ jaxpr_ = pe.convert_constvars_jaxpr(jaxpr_)\n+ return call_transpose(core.closed_call_p, params, jaxpr_, (*consts, *args),\n+ ct, cts_in_avals, reduce_axes)\n+primitive_transposes[core.closed_call_p] = _closed_call_transpose\ndef remat_transpose(params, call_jaxpr, primals_in, cotangents_in,\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -986,13 +986,13 @@ def lower_fun(fun: Callable, multiple_results: bool = True) -> Callable:\ndef _call_lowering(fn_name, stack_name, call_jaxpr, backend, ctx, avals_in,\navals_out, tokens_in, *args):\n+ if isinstance(call_jaxpr, core.Jaxpr):\n+ call_jaxpr = core.ClosedJaxpr(call_jaxpr, ())\nxla.check_backend_matches(backend, ctx.platform)\noutput_types = map(aval_to_ir_types, avals_out)\nflat_output_types = util.flatten(output_types)\neffects = tokens_in.effects()\n- symbol_name = lower_jaxpr_to_fun(ctx, fn_name,\n- core.ClosedJaxpr(call_jaxpr, ()),\n- effects).name.value\n+ symbol_name = lower_jaxpr_to_fun(ctx, fn_name, call_jaxpr, effects).name.value\nargs = [*tokens_in.tokens(), *args]\ncall = func_dialect.CallOp(flat_output_types,\nir.FlatSymbolRefAttr.get(symbol_name),\n@@ -1024,6 +1024,8 @@ def _named_call_lowering(ctx, *args, name, backend=None,\nregister_lowering(core.named_call_p, _named_call_lowering)\nregister_lowering(core.call_p, partial(_named_call_lowering, name=\"core_call\"))\n+register_lowering(core.closed_call_p,\n+ partial(_named_call_lowering, name=\"core_closed_call\"))\ndef full_like_aval(value, aval: core.ShapedArray) -> ir.Value:\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -222,15 +222,17 @@ class JaxprTrace(Trace):\nunknown_arg_tracers = [t for t in tracers if not t.is_known()]\n# Adjust parameters (e.g. donated_invars) for the staged-out call's args.\nnum_new_args = len(const_tracers) + len(env_tracers)\n- staged_params = update_params(params, map(op.not_, in_knowns), num_new_args)\n- staged_params = dict(staged_params, call_jaxpr=convert_constvars_jaxpr(jaxpr))\n+ staged_params = dict(params, call_jaxpr=convert_constvars_jaxpr(jaxpr))\n+ staged_params = update_params(staged_params, map(op.not_, in_knowns),\n+ num_new_args)\n# The outputs of the staged-out call are Tracers with the new eqn as recipe.\nout_tracers = [JaxprTracer(self, PartialVal.unknown(a), None)\nfor a in out_avals]\nname_stack = self._current_truncated_name_stack()\nsource = source_info_util.current().replace(name_stack=name_stack)\neqn = new_eqn_recipe((*const_tracers, *env_tracers, *unknown_arg_tracers),\n- out_tracers, primitive, staged_params, jaxpr.effects, source)\n+ out_tracers, primitive, staged_params, jaxpr.effects,\n+ source)\nfor t in out_tracers: t.recipe = eqn\nreturn merge_lists(out_knowns, out_tracers, out_consts)\n@@ -511,6 +513,12 @@ custom_partial_eval_rules: Dict[Primitive, Callable] = {}\ncall_partial_eval_rules: Dict[Primitive, Callable] = {}\ncall_param_updaters: Dict[Primitive, Callable] = {}\n+def _closed_call_param_updater(params, _, __):\n+ jaxpr = params.get('call_jaxpr')\n+ if jaxpr is None: return params\n+ assert type(jaxpr) is core.Jaxpr\n+ return dict(params, call_jaxpr=core.ClosedJaxpr(jaxpr, ()))\n+call_param_updaters[core.closed_call_p] = _closed_call_param_updater\ndef abstract_eval_fun(fun, *avals, debug_info=None, **params):\n_, avals_out, _ = trace_to_jaxpr_dynamic(\n@@ -666,8 +674,6 @@ def new_eqn_recipe(in_tracers: Sequence[JaxprTracer],\n# TODO(necula): move these checks to core.check_jaxpr, and call in more places\nif primitive.call_primitive or primitive.map_primitive:\nassert \"call_jaxpr\" in params\n- # assert len(invars) == len(params[\"call_jaxpr\"].invars) # TODO constvars?\n- assert len(out_tracers) == len(params[\"call_jaxpr\"].outvars)\nassert (\"donated_invars\" not in params or\nlen(params[\"donated_invars\"]) == len(params[\"call_jaxpr\"].invars))\nif primitive.map_primitive:\n@@ -1254,6 +1260,20 @@ dce_rules[core.named_call_p] = dce_jaxpr_call_rule\ndce_rules[remat_call_p] = dce_jaxpr_call_rule\n+def dce_jaxpr_closed_call_rule(used_outputs: List[bool], eqn: JaxprEqn\n+ ) -> Tuple[List[bool], JaxprEqn]:\n+ # TODO(mattjj): de-duplicate with above rule?\n+ jaxpr_ = eqn.params['call_jaxpr']\n+ jaxpr, consts = jaxpr_.jaxpr, jaxpr_.consts\n+ new_jaxpr, used_inputs = dce_jaxpr(jaxpr, used_outputs)\n+ new_params = dict(eqn.params, call_jaxpr=core.ClosedJaxpr(new_jaxpr, consts))\n+ new_eqn = new_jaxpr_eqn(\n+ [v for v, used in zip(eqn.invars, used_inputs) if used],\n+ [v for v, used in zip(eqn.outvars, used_outputs) if used],\n+ eqn.primitive, new_params, new_jaxpr.effects, eqn.source_info)\n+ return used_inputs, new_eqn\n+dce_rules[core.closed_call_p] = dce_jaxpr_closed_call_rule\n+\ndef move_binders_to_front(closed_jaxpr: ClosedJaxpr, to_move: Sequence[bool]\n) -> ClosedJaxpr:\n\"\"\"Reorder `invars` by moving those indicated in `to_move` to the front.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -560,7 +560,3 @@ def lower_fun(fun: Callable, *, multiple_results: bool, backend=None,\n\"Add an MLIR (MHLO) lowering via jax.interpreters.mlir \"\n\"instead.\")\nreturn f\n-\n-\n-ad.primitive_transposes[core.named_call_p] = partial(ad.call_transpose,\n- core.named_call_p)\n" }, { "change_type": "MODIFY", "old_path": "tests/core_test.py", "new_path": "tests/core_test.py", "diff": "@@ -56,6 +56,13 @@ def core_call(f, *args):\nout = core.call_p.bind(f, *args)\nreturn tree_unflatten(out_tree(), out)\n+@util.curry\n+def core_closed_call(f, *args):\n+ args, in_tree = tree_flatten(args)\n+ f, out_tree = flatten_fun_nokwargs(lu.wrap_init(f), in_tree)\n+ out = core.closed_call_p.bind(f, *args)\n+ return tree_unflatten(out_tree(), out)\n+\ndef simple_fun(x, y):\nreturn jnp.sin(x * y)\n@@ -147,6 +154,9 @@ for ts in test_specs_base:\ntest_specs.append(CallSpec(core_call(ts.fun), ts.args))\ntest_specs.append(CallSpec(core_call(jit(ts.fun)), ts.args))\ntest_specs.append(CallSpec(core_call(core_call(ts.fun)), ts.args))\n+ test_specs.append(CallSpec(core_closed_call(ts.fun), ts.args))\n+ test_specs.append(CallSpec(core_closed_call(jit(ts.fun)), ts.args))\n+ test_specs.append(CallSpec(core_closed_call(core_closed_call(ts.fun)), ts.args))\ntest_specs.append(CallSpec(partial(jvp_unlinearized, ts.fun),\n(ts.args, ts.args)))\n" } ]
Python
Apache License 2.0
google/jax
add core.closed_call_p
260,510
12.05.2022 22:22:52
25,200
b8a523f977a9b4e63b568a7af83621fdb1c755be
Enable colors when we are using a terminal or IPython
[ { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -476,7 +476,7 @@ flags.DEFINE_integer(\nflags.DEFINE_bool(\n'jax_pprint_use_color',\n- bool_env('JAX_PPRINT_USE_COLOR', False),\n+ bool_env('JAX_PPRINT_USE_COLOR', True),\nhelp='Enable jaxpr pretty-printing with colorful syntax highlighting.'\n)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/pretty_printer.py", "new_path": "jax/_src/pretty_printer.py", "diff": "import abc\nimport enum\n+import sys\nfrom functools import partial\nfrom typing import List, NamedTuple, Optional, Sequence, Tuple, Union\nfrom jax.config import config\n@@ -36,13 +37,31 @@ try:\nexcept ImportError:\ncolorama = None\n+def _can_use_color() -> bool:\n+ try:\n+ # Check if we're in IPython or Colab\n+ ipython = get_ipython() # type: ignore[name-defined]\n+ shell = ipython.__class__.__name__\n+ if shell == \"ZMQInteractiveShell\":\n+ # Jupyter Notebook\n+ return True\n+ elif \"colab\" in str(ipython.__class__):\n+ # Google Colab (external or internal)\n+ return True\n+ except NameError:\n+ pass\n+ # Otherwise check if we're in a terminal\n+ return sys.stdout.isatty()\n+\n+CAN_USE_COLOR = _can_use_color()\nclass Doc(abc.ABC):\n__slots__ = ()\n- def format(self, width: int = 80, use_color: bool = False,\n+ def format(self, width: int = 80, use_color: Optional[bool] = None,\nannotation_prefix=\" # \") -> str:\n- use_color = use_color or config.FLAGS.jax_pprint_use_color\n+ if use_color is None:\n+ use_color = CAN_USE_COLOR and config.FLAGS.jax_pprint_use_color\nreturn _format(self, width, use_color=use_color,\nannotation_prefix=annotation_prefix)\n" } ]
Python
Apache License 2.0
google/jax
Enable colors when we are using a terminal or IPython
260,411
09.05.2022 15:41:38
-10,800
e65dd91b670148d62abc8ba0410ac375602bc85f
[jax2tf] Document the handling of custom JAX pytrees Add a test also.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -708,6 +708,82 @@ g_jaxx2tf_0 = tape.gradient(res, xs,\n# In this case we get the same result as for TF native.\n```\n+### Functions whose arguments and results are Python nested data structures\n+\n+jax2tf can convert functions with arguments and results that are nested\n+collections (tuples, lists, dictionaries) of numeric values or JAX arrays\n+([pytrees](https://jax.readthedocs.io/en/latest/pytrees.html)). The\n+resulting TensorFlow function will take the same kind of arguments except the\n+leaves can be numeric values or TensorFlow tensors (`tf.Tensor`, `tf.TensorSpec`, `tf.Variable`).\n+\n+As long as the arguments use only standard Python containers (tuple, list, dictionaries),\n+both JAX and TensorFlow can flatten and unflatten them and you can use the converted\n+function in TensorFlow without limitations.\n+\n+However, if your JAX function takes a custom container, you can register it with\n+the JAX `tree_util` module so that JAX will know how to operate with it, and you\n+can still convert the function to use it in TensorFlow\n+eager and with `tf.function`, but you won't be able to save it to a SavedModel, nor\n+will you be able to compute gradients with TensorFlow\n+(code from `jax2tf_test.test_custom_pytree_readme`):\n+\n+```\n+class CustomPair:\n+ def __init__(self, a, b):\n+ self.a = a\n+ self.b = b\n+\n+# Register it with the JAX tree_util module\n+jax.tree_util.register_pytree_node(CustomPair,\n+ lambda x: ((x.a, x.b), None),\n+ lambda _, ab: CustomPair(*ab))\n+def f_jax(pair: CustomPair):\n+ return 2. * pair.a + 3. * pair.b\n+\n+x = CustomPair(4., 5.)\n+res_jax = f_jax(x)\n+# TF execution works as long as JAX can flatten the arguments\n+res_tf = jax2tf.convert(f_jax)(x)\n+self.assertAllClose(res_jax, res_tf.numpy())\n+res_tf_2 = tf.function(jax2tf.convert(f_jax), autograph=False, jit_compile=True)(x)\n+```\n+\n+If you want to save the function in a SavedModel or compute gradients,\n+you should construct a wrapper:\n+\n+```\n+ # wrapped TF function to use only standard containers\n+def f_tf_wrapped(a, b):\n+ return f_tf(CustomPair(a, b))\n+\n+# Try to put into SavedModel\n+my_model = tf.Module()\n+# Save a function that can take scalar inputs.\n+my_model.f = tf.function(f_tf_wrapped, autograph=False,\n+ input_signature=[tf.TensorSpec([], tf.float32),\n+ tf.TensorSpec([], tf.float32)])\n+model_dir = os.path.join(absltest.get_default_test_tmpdir(), str(id(my_model)))\n+tf.saved_model.save(my_model, model_dir,\n+ options=tf.saved_model.SaveOptions(experimental_custom_gradients=True))\n+\n+# Restoring (note: the restored model does *not* require JAX to run, just XLA).\n+restored_model = tf.saved_model.load(model_dir)\n+def restored_f(pair: CustomPair):\n+ return restored_model.f(pair.a, pair.b)\n+\n+res_tf_3 = restored_f(x)\n+self.assertAllClose(res_jax, res_tf_3)\n+grad_jax = jax.grad(f_jax)(x)\n+\n+x_v = [tf.Variable(x.a), tf.Variable(x.b)]\n+with tf.GradientTape() as tape:\n+ res = f_tf_wrapped(*x_v)\n+\n+ grad_tf = tape.gradient(res, x_v)\n+self.assertAllClose(grad_jax.a, grad_tf[0])\n+self.assertAllClose(grad_jax.b, grad_tf[1])\n+```\n+\n### Different 64-bit precision in JAX and TensorFlow\nJAX behaves somewhat differently than TensorFlow in the handling\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -22,6 +22,7 @@ from absl.testing import absltest\nfrom absl.testing import parameterized\nfrom collections import OrderedDict\n+import os\nimport jax\nfrom jax import ad_checkpoint\n@@ -291,6 +292,60 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(5., tape.gradient(uv[\"two\"], x))\nself.assertAllClose(4., tape.gradient(uv[\"two\"], y))\n+ def test_custom_pytree_readme(self):\n+ # Code examples from README.md\n+ class CustomPair:\n+ def __init__(self, a, b):\n+ self.a = a\n+ self.b = b\n+\n+ jax.tree_util.register_pytree_node(CustomPair,\n+ lambda x: ((x.a, x.b), None),\n+ lambda _, ab: CustomPair(*ab))\n+ def f_jax(pair: CustomPair):\n+ return np.float32(2.) * pair.a + np.float32(3.) * pair.b\n+ f_tf = jax2tf.convert(f_jax)\n+\n+ x = CustomPair(np.float32(4.), np.float32(5.))\n+ res_jax = f_jax(x)\n+ # TF execution works as long as JAX can flatten the arguments and results\n+ res_tf = f_tf(x)\n+ self.assertAllClose(res_jax, res_tf.numpy())\n+ res_tf_2 = tf.function(f_tf, autograph=False, jit_compile=True)(x)\n+ self.assertAllClose(res_jax, res_tf_2)\n+\n+ # wrapped TF function to use only standard containers\n+ def f_tf_wrapped(a, b):\n+ return f_tf(CustomPair(a, b))\n+\n+ # Try to put into SavedModel\n+ my_model = tf.Module()\n+ # Save a function that can take scalar inputs.\n+ my_model.f = tf.function(f_tf_wrapped, autograph=False,\n+ input_signature=[tf.TensorSpec([], tf.float32),\n+ tf.TensorSpec([], tf.float32)])\n+ model_dir = os.path.join(absltest.get_default_test_tmpdir(), str(id(my_model)))\n+ tf.saved_model.save(my_model, model_dir,\n+ options=tf.saved_model.SaveOptions(experimental_custom_gradients=True))\n+\n+ # Restoring (note: the restored model does *not* require JAX to run, just XLA).\n+ restored_model = tf.saved_model.load(model_dir)\n+ def restored_f(pair: CustomPair):\n+ return restored_model.f(pair.a, pair.b)\n+\n+ res_tf_3 = restored_f(x)\n+ self.assertAllClose(res_jax, res_tf_3)\n+ grad_jax = jax.grad(f_jax)(x)\n+\n+ x_v = [tf.Variable(x.a), tf.Variable(x.b)]\n+ with tf.GradientTape() as tape:\n+ res = f_tf_wrapped(*x_v)\n+\n+ grad_tf = tape.gradient(res, x_v)\n+ self.assertAllClose(grad_jax.a, grad_tf[0])\n+ self.assertAllClose(grad_jax.b, grad_tf[1])\n+\n+\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"function={with_function}\",\nwith_function=with_function)\n@@ -306,7 +361,6 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nif with_function:\nf_tf = tf.function(f_tf, autograph=False)\ndefault_float_type = jax2tf.dtype_of_val(4.)\n- inputs = OrderedDict()\nx = tf.Variable([4.], dtype=default_float_type)\ny = tf.Variable([4., 5.], dtype=default_float_type)\ninputs = OrderedDict()\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Document the handling of custom JAX pytrees Add a test also.
260,510
16.05.2022 18:55:52
25,200
268b4be21b7f3b9a92c45e4b77adda749f6e18cc
Add output token for unordered effects Currently we can't block on *unordered* effectful computations because there are no runtime tokens for them. This change adds a per-device token that is returned by effectful computations. This enables us to block on them if we want. See the design note added in
[ { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -57,6 +57,7 @@ from jax._src.config import (\nfrom .core import eval_context as ensure_compile_time_eval\nfrom jax._src.api import (\nad, # TODO(phawkins): update users to avoid this.\n+ effects_barrier,\nblock_until_ready,\ncheckpoint as checkpoint,\ncheckpoint_policies as checkpoint_policies,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -485,6 +485,7 @@ def _cpp_jit(\nexecute: Optional[functools.partial] = (\ndispatch._xla_callable.most_recent_entry())\n# TODO(sharadmv): Enable fast path for effectful jaxprs\n+ # TODO(sharadmv): Clean up usage of `execute.args`\nuse_fastpath = (\n# This is if we have already executed this code-path (most-recent entry\n# has been reset to None). Thus, we do not support the fast-path.\n@@ -492,13 +493,15 @@ def _cpp_jit(\nexecute.func is dispatch._execute_compiled and # not trivial, not pmap\n# No effects in computation\nnot execute.args[5] and\n+ not execute.args[6] and\n# Not supported: ShardedDeviceArray\nall(device_array.type_is_device_array(x) for x in out_flat) and\n# Not supported: dynamic shapes\nnot jax.config.jax_dynamic_shapes)\n### If we can use the fastpath, we return required info to the caller.\nif use_fastpath:\n- _, xla_executable, _, _, result_handlers, _, kept_var_idx = execute.args\n+ (_, xla_executable,\n+ _, _, result_handlers, _, _, kept_var_idx) = execute.args\nsticky_device = None\navals = []\nlazy_exprs = [None] * len(result_handlers)\n@@ -823,11 +826,15 @@ def xla_computation(fun: Callable,\nelse:\nout_parts_flat = tuple(flatten_axes(\n\"xla_computation out_parts\", out_tree(), out_parts))\n- effects = list(jaxpr.effects)\n+ unordered_effects = [eff for eff in jaxpr.effects\n+ if eff not in core.ordered_effects]\n+ ordered_effects = [eff for eff in jaxpr.effects\n+ if eff in core.ordered_effects]\nm, _ = mlir.lower_jaxpr_to_module(\nf\"xla_computation_{fun_name}\",\ncore.ClosedJaxpr(jaxpr, consts),\n- effects=effects,\n+ unordered_effects=unordered_effects,\n+ ordered_effects=ordered_effects,\nplatform=backend,\naxis_context=mlir.ReplicaAxisContext(axis_env_),\nname_stack=new_name_stack(wrap_name(fun_name, \"xla_computation\")),\n@@ -2034,6 +2041,8 @@ def _cpp_pmap(\nexecute is not None and\n# We don't support JAX extension backends.\nisinstance(execute[0], pxla.ExecuteReplicated) and\n+ # TODO(sharadmv): Enable effects in replicated computation\n+ not execute[0].has_unordered_effects and\n# No tracers in the outputs. Checking for ShardedDeviceArray should be\n# sufficient, but we use the more general `DeviceArray`.\nall(isinstance(x, device_array.DeviceArray) for x in out_flat))\n@@ -3137,6 +3146,9 @@ def named_call(\nreturn named_call_f\n+def effects_barrier():\n+ \"\"\"Waits until existing functions have completed any side-effects.\"\"\"\n+ dispatch.runtime_tokens.block_until_ready()\ndef block_until_ready(x):\n\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -106,9 +106,11 @@ RuntimeToken = Any\nclass RuntimeTokenSet(threading.local):\ntokens: Dict[core.Effect, Tuple[RuntimeToken, Device]]\n+ output_tokens: Dict[Device, RuntimeToken]\ndef __init__(self):\nself.tokens = {}\n+ self.output_tokens = {}\ndef get_token(self, eff: core.Effect, device: Device) -> RuntimeToken:\nif eff not in self.tokens:\n@@ -122,11 +124,22 @@ class RuntimeTokenSet(threading.local):\ndef update_token(self, eff: core.Effect, token: RuntimeToken):\nself.tokens[eff] = token, self.tokens[eff][1]\n+ def set_output_token(self, device: Device, token: RuntimeToken):\n+ # We're free to clobber the previous output token because on each\n+ # device we have a total ordering of computations. Only the token\n+ # from the latest computation matters. If this weren't the case\n+ # we'd need to store a set of output tokens.\n+ self.output_tokens[device] = token\n+\ndef clear(self):\nself.tokens = {}\n+ self.output_tokens = {}\ndef block_until_ready(self):\n- [t[0].block_until_ready() for t, _ in self.tokens.values()]\n+ for t, _ in self.tokens.values():\n+ t[0].block_until_ready()\n+ for t in self.output_tokens.values():\n+ t[0].block_until_ready()\nruntime_tokens: RuntimeTokenSet = RuntimeTokenSet()\n@@ -300,7 +313,8 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nif not jaxpr.eqns and not always_lower:\nreturn XlaComputation(\nname, None, True, None, None, jaxpr=jaxpr, consts=consts, device=device,\n- in_avals=abstract_args, out_avals=out_avals, effects=jaxpr.effects,\n+ in_avals=abstract_args, out_avals=out_avals,\n+ has_unordered_effects=False, ordered_effects=[],\nkept_var_idx=kept_var_idx, keepalive=None)\nif not _on_exit:\n@@ -336,15 +350,20 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nname_stack = util.new_name_stack(util.wrap_name(name, 'jit'))\nclosed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\nmodule_name = f\"jit_{fun.__name__}\"\n- effects = [eff for eff in closed_jaxpr.effects if eff in core.ordered_effects]\n+ unordered_effects = [eff for eff in closed_jaxpr.effects\n+ if eff not in core.ordered_effects]\n+ ordered_effects = [eff for eff in closed_jaxpr.effects\n+ if eff in core.ordered_effects]\nmodule, keepalive = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, effects, backend.platform,\n+ module_name, closed_jaxpr, unordered_effects, ordered_effects, backend.platform,\nmlir.ReplicaAxisContext(axis_env), name_stack, donated_invars)\nreturn XlaComputation(\nname, module, False, donated_invars, which_explicit, nreps=nreps,\ndevice=device, backend=backend, tuple_args=tuple_args,\n- in_avals=abstract_args, out_avals=out_avals, effects=effects,\n- kept_var_idx=kept_var_idx, keepalive=keepalive)\n+ in_avals=abstract_args, out_avals=out_avals,\n+ has_unordered_effects=bool(unordered_effects),\n+ ordered_effects=ordered_effects, kept_var_idx=kept_var_idx,\n+ keepalive=keepalive)\ndef _backend_supports_unbounded_dynamic_shapes(backend: Backend) -> bool:\n@@ -588,13 +607,18 @@ def _check_special(name, xla_shape, buf):\nif config.jax_debug_infs and np.any(np.isinf(buf.to_py())):\nraise FloatingPointError(f\"invalid value (inf) encountered in {name}\")\n-def _add_tokens(effects: List[core.Effect], device, input_bufs):\n- tokens = [runtime_tokens.get_token(eff, device) for eff in effects]\n+def _add_tokens(has_unordered_effects: bool, ordered_effects: List[core.Effect],\n+ device: Device, input_bufs):\n+ tokens = [runtime_tokens.get_token(eff, device) for eff in ordered_effects]\ntokens_flat = flatten(tokens)\ninput_bufs = [*tokens_flat, *input_bufs]\ndef _remove_tokens(output_bufs):\n- token_bufs, output_bufs = util.split_list(output_bufs, [len(effects)])\n- for eff, token_buf in zip(effects, token_bufs):\n+ token_bufs, output_bufs = util.split_list(\n+ output_bufs, [has_unordered_effects + len(ordered_effects)])\n+ if has_unordered_effects:\n+ output_token_buf, *token_bufs = token_bufs\n+ runtime_tokens.set_output_token(device, output_token_buf)\n+ for eff, token_buf in zip(ordered_effects, token_bufs):\nruntime_tokens.update_token(eff, token_buf)\nreturn output_bufs\nreturn input_bufs, _remove_tokens\n@@ -604,20 +628,22 @@ def _execute_compiled(name: str, compiled: XlaExecutable,\ninput_handler: Optional[Callable],\noutput_buffer_counts: Optional[Sequence[int]],\nresult_handlers,\n- effects: List[core.Effect],\n+ has_unordered_effects: bool,\n+ ordered_effects: List[core.Effect],\nkept_var_idx, *args):\ndevice, = compiled.local_devices()\nargs = input_handler(args) if input_handler else args\ninput_bufs_flat = flatten(device_put(x, device) for i, x in enumerate(args)\nif i in kept_var_idx)\n- if effects:\n- input_bufs_flat, token_handler = _add_tokens(effects, device, input_bufs_flat)\n+ if has_unordered_effects or ordered_effects:\n+ input_bufs_flat, token_handler = _add_tokens(\n+ has_unordered_effects, ordered_effects, device, input_bufs_flat)\nout_bufs_flat = compiled.execute(input_bufs_flat)\ncheck_special(name, out_bufs_flat)\nif output_buffer_counts is None:\nreturn (result_handlers[0](*out_bufs_flat),)\nout_bufs = unflatten(out_bufs_flat, output_buffer_counts)\n- if effects:\n+ if ordered_effects or has_unordered_effects:\nout_bufs = token_handler(out_bufs)\nreturn tuple(h(*bs) for h, bs in unsafe_zip(result_handlers, out_bufs))\n@@ -626,10 +652,13 @@ def _execute_replicated(name: str, compiled: XlaExecutable,\ninput_handler: Optional[Callable],\noutput_buffer_counts: Optional[Sequence[int]],\nresult_handlers,\n- effects: List[core.Effect],\n+ has_unordered_effects: bool,\n+ ordered_effects: List[core.Effect],\nkept_var_idx, *args):\n- if effects:\n- raise NotImplementedError('Cannot execute replicated computation with effects.')\n+ if has_unordered_effects or ordered_effects:\n+ # TODO(sharadmv): support jit-of-pmap with effects\n+ raise NotImplementedError(\n+ \"Cannot execute replicated computation with effects.\")\nif input_handler: raise NotImplementedError # TODO(mattjj, dougalm)\ninput_bufs = [flatten(device_put(x, device) for i, x in enumerate(args)\nif i in kept_var_idx)\n@@ -645,7 +674,8 @@ def _execute_replicated(name: str, compiled: XlaExecutable,\ndef _execute_trivial(jaxpr, device: Optional[Device], consts, avals, handlers,\n- _: List[core.Effect], kept_var_idx, *args):\n+ has_unordered_effects: bool,\n+ ordered_effects: List[core.Effect], kept_var_idx, *args):\nenv: Dict[core.Var, Any] = {}\npruned_args = (x for i, x in enumerate(args) if i in kept_var_idx)\nmap(env.setdefault, jaxpr.invars, pruned_args)\n@@ -790,7 +820,8 @@ class XlaCompiledComputation(stages.Executable):\ntuple_args: bool,\nin_avals: Sequence[core.AbstractValue],\nout_avals: Sequence[core.AbstractValue],\n- effects: List[core.Effect],\n+ has_unordered_effects: bool,\n+ ordered_effects: List[core.Effect],\nkept_var_idx: Set[int],\nkeepalive: Optional[Any]) -> XlaCompiledComputation:\nsticky_device = device\n@@ -806,13 +837,15 @@ class XlaCompiledComputation(stages.Executable):\ncompiled = compile_or_get_cached(backend, xla_computation, options)\nbuffer_counts = (None if len(out_avals) == 1 and not config.jax_dynamic_shapes\nelse [aval_to_num_buffers(aval) for aval in out_avals])\n- if effects:\n+ if ordered_effects or has_unordered_effects:\n+ num_output_tokens = len(ordered_effects) + has_unordered_effects\nif buffer_counts is None:\nbuffer_counts = [1]\n- buffer_counts = ([1] * len(effects)) + buffer_counts\n+ buffer_counts = ([1] * num_output_tokens) + buffer_counts\nexecute = _execute_compiled if nreps == 1 else _execute_replicated\n- unsafe_call = partial(execute, name, compiled, input_handler, buffer_counts,\n- result_handlers, effects, kept_var_idx)\n+ unsafe_call = partial(execute, name, compiled, input_handler, buffer_counts, # type: ignore # noqa: F811\n+ result_handlers, has_unordered_effects,\n+ ordered_effects, kept_var_idx)\nreturn XlaCompiledComputation(compiled, in_avals, kept_var_idx, unsafe_call,\nkeepalive)\n@@ -827,12 +860,14 @@ class XlaCompiledComputation(stages.Executable):\nreturn self._xla_executable\n@staticmethod\n- def from_trivial_jaxpr(jaxpr, consts, device, in_avals, out_avals, effects,\n- kept_var_idx, keepalive: Optional[Any]) -> XlaCompiledComputation:\n+ def from_trivial_jaxpr(jaxpr, consts, device, in_avals, out_avals,\n+ has_unordered_effects, ordered_effects, kept_var_idx,\n+ keepalive: Optional[Any]) -> XlaCompiledComputation:\nassert keepalive is None\nresult_handlers = map(partial(aval_to_result_handler, device), out_avals)\nunsafe_call = partial(_execute_trivial, jaxpr, device, consts,\n- out_avals, result_handlers, effects, kept_var_idx)\n+ out_avals, result_handlers, has_unordered_effects,\n+ ordered_effects, kept_var_idx)\nreturn XlaCompiledComputation(None, in_avals, kept_var_idx, unsafe_call,\nkeepalive)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -2318,8 +2318,10 @@ def check_map(ctx_factory, prim, in_avals, params):\nif \"call_jaxpr\" not in params:\nraise JaxprTypeError(f\"Map primitive {prim} missing 'call_jaxpr' parameter\")\ncall_jaxpr = params[\"call_jaxpr\"]\n- if call_jaxpr.effects:\n- raise JaxprTypeError(f\"Map primitive {prim} mapping an effectful function\")\n+ ordered_effects_ = call_jaxpr.effects & ordered_effects\n+ if ordered_effects_:\n+ raise JaxprTypeError(\n+ f\"Map primitive {prim} mapping ordered effects: {ordered_effects_}\")\nif \"axis_size\" not in params:\nraise JaxprTypeError(f\"Map primitive {prim} missing 'axis_size' parameter\")\naxis_size = params[\"axis_size\"]\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -493,7 +493,8 @@ def sharded_aval(aval: core.ShapedArray,\ndef lower_jaxpr_to_module(\nmodule_name: str, jaxpr: core.ClosedJaxpr,\n- effects: List[core.Effect],\n+ unordered_effects: List[core.Effect],\n+ ordered_effects: List[core.Effect],\nplatform: str,\naxis_context: AxisContext,\nname_stack: NameStack, donated_args: Sequence[bool],\n@@ -554,8 +555,10 @@ def lower_jaxpr_to_module(\nraise ValueError(\nf'Cannot lower jaxpr with unlowerable effects: {unlowerable_effects}')\nlower_jaxpr_to_fun(\n- ctx, \"main\", jaxpr, effects, public=True, create_tokens=True,\n- replace_tokens_with_dummy=True, replicated_args=replicated_args,\n+ ctx, \"main\", jaxpr, ordered_effects, public=True, create_tokens=True,\n+ replace_tokens_with_dummy=True,\n+ num_output_tokens=1 if unordered_effects else 0,\n+ replicated_args=replicated_args,\narg_shardings=arg_shardings, result_shardings=result_shardings,\ninput_output_aliases=input_output_aliases)\n@@ -665,7 +668,8 @@ def lower_jaxpr_to_fun(\narg_shardings: Optional[Sequence[Optional[xc.OpSharding]]] = None,\nresult_shardings: Optional[Sequence[Optional[xc.OpSharding]]] = None,\nuse_sharding_annotations: bool = True,\n- input_output_aliases: Optional[Sequence[Optional[int]]] = None\n+ input_output_aliases: Optional[Sequence[Optional[int]]] = None,\n+ num_output_tokens: int = 0,\n) -> func_dialect.FuncOp:\n\"\"\"Lowers jaxpr and its callees to an IR function.\n@@ -705,13 +709,15 @@ def lower_jaxpr_to_fun(\nif create_tokens:\n# If we create the tokens they won't be inputs to the MLIR function.\ntoken_types = [dummy_token_type() for _ in effects]\n+ output_token_types = [dummy_token_type() for _ in range(num_output_tokens)]\nelse:\n# If we aren't creating tokens they will be the initial inputs to the\n# MLIR function.\n+ output_token_types = []\nnum_tokens = len(effects)\ntoken_types = [token_type() for _ in effects]\ninput_types = [*token_types, *input_types]\n- output_types = [*token_types, *output_types]\n+ output_types = [*output_token_types, *token_types, *output_types]\nif input_output_aliases:\ntoken_input_output_aliases = [None] * num_tokens\ninput_output_aliases = [*token_input_output_aliases, *input_output_aliases]\n@@ -719,7 +725,7 @@ def lower_jaxpr_to_fun(\ntoken_shardings = [None] * num_tokens\narg_shardings = [*token_shardings, *arg_shardings]\nif result_shardings:\n- token_shardings = [None] * num_tokens\n+ token_shardings = [None] * (num_tokens + num_output_tokens)\nresult_shardings = [*token_shardings, *result_shardings]\nif replicated_args:\ntoken_replicated_args = [False] * num_tokens\n@@ -812,6 +818,8 @@ def lower_jaxpr_to_fun(\n*args)\nouts = []\nif create_tokens:\n+ for _ in range(num_output_tokens):\n+ outs.append(dummy_token())\nfor _ in effects:\nouts.append(dummy_token())\nelse:\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1619,8 +1619,10 @@ class DynamicJaxprTrace(core.Trace):\nwith core.new_sublevel():\njaxpr, reduced_out_avals, consts = trace_to_subjaxpr_dynamic(\nf, self.main, reduced_in_avals)\n- if jaxpr.effects:\n- raise NotImplementedError('Effects not supported for map primitives.')\n+ ordered_effects = jaxpr.effects & core.ordered_effects\n+ if ordered_effects:\n+ raise ValueError(\"Ordered effects not supported for \"\n+ f\"map primitives: {ordered_effects}\")\nout_axes = params['out_axes_thunk']()\nout_avals = [core.unmapped_aval(axis_size, axis_name, out_axis, a)\nif out_axis is not None else a\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1048,14 +1048,17 @@ def lower_parallel_callable(\nwith maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\nif any(eff in core.ordered_effects for eff in closed_jaxpr.effects):\nraise ValueError(\"Ordered effects not supported in `pmap`.\")\n+ unordered_effects = [eff for eff in closed_jaxpr.effects\n+ if eff not in core.ordered_effects]\nmodule, keepalive = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, [], backend.platform,\n- mlir.ReplicaAxisContext(axis_env), name_stack, donated_invars,\n- replicated_args=replicated_args,\n+ module_name, closed_jaxpr, unordered_effects, [],\n+ backend.platform, mlir.ReplicaAxisContext(axis_env),\n+ name_stack, donated_invars, replicated_args=replicated_args,\narg_shardings=_shardings_to_mlir_shardings(parts.arg_parts),\nresult_shardings=_shardings_to_mlir_shardings(parts.out_parts))\nreturn PmapComputation(module, pci=pci, replicas=replicas, parts=parts,\nshards=shards, tuple_args=tuple_args,\n+ unordered_effects=unordered_effects,\nkeepalive=keepalive)\n@@ -1107,6 +1110,7 @@ class PmapExecutable(stages.Executable):\nparts: 'PartitionInfo',\nshards: ShardInfo,\ntuple_args: bool,\n+ unordered_effects: List[core.Effect],\nkeepalive: Any):\ndevices = pci.devices\nif devices is None:\n@@ -1216,7 +1220,7 @@ class PmapExecutable(stages.Executable):\nhandle_args = InputsHandler(\ncompiled.local_devices(), input_sharding_specs, input_indices)\nexecute_fun = ExecuteReplicated(compiled, pci.backend, handle_args,\n- handle_outs, keepalive)\n+ handle_outs, unordered_effects, keepalive)\nfingerprint = getattr(compiled, \"fingerprint\", None)\nreturn PmapExecutable(compiled, execute_fun, fingerprint, pci.avals)\n@@ -1554,20 +1558,27 @@ def partitioned_sharding_spec(num_partitions: int,\nclass ExecuteReplicated:\n\"\"\"The logic to shard inputs, execute a replicated model, returning outputs.\"\"\"\n__slots__ = ['xla_executable', 'backend', 'in_handler', 'out_handler',\n- 'keepalive']\n+ 'has_unordered_effects', 'keepalive']\ndef __init__(self, xla_executable, backend, in_handler: InputsHandler,\n- out_handler: ResultsHandler, keepalive: Any):\n+ out_handler: ResultsHandler,\n+ unordered_effects: List[core.Effect], keepalive: Any):\nself.xla_executable = xla_executable\nself.backend = backend\nself.in_handler = in_handler\nself.out_handler = out_handler\n+ self.has_unordered_effects = bool(unordered_effects)\nself.keepalive = keepalive\n@profiler.annotate_function\ndef __call__(self, *args):\ninput_bufs = self.in_handler(args)\nout_bufs = self.xla_executable.execute_sharded_on_local_devices(input_bufs)\n+ if self.has_unordered_effects:\n+ token_bufs, *out_bufs = out_bufs\n+ for i, device in enumerate(self.xla_executable.local_devices()):\n+ token = (token_bufs[i],)\n+ dispatch.runtime_tokens.set_output_token(device, token)\nif dispatch.needs_check_special():\nfor bufs in out_bufs:\ndispatch.check_special(\"parallel computation\", bufs)\n@@ -2224,9 +2235,11 @@ def lower_mesh_computation(\nwith core.extend_axis_env_nd(mesh.shape.items()):\nif any(eff in core.ordered_effects for eff in closed_jaxpr.effects):\nraise ValueError(\"Ordered effects not supported in mesh computations.\")\n+ unordered_effects = [eff for eff in closed_jaxpr.effects\n+ if eff not in core.ordered_effects]\nmodule, keepalive = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, [], backend.platform, axis_ctx, name_stack,\n- donated_invars, replicated_args=replicated_args,\n+ module_name, closed_jaxpr, unordered_effects, [], backend.platform,\n+ axis_ctx, name_stack, donated_invars, replicated_args=replicated_args,\narg_shardings=in_partitions, result_shardings=out_partitions)\nreturn MeshComputation(\n@@ -2234,6 +2247,7 @@ def lower_mesh_computation(\nglobal_out_avals=global_out_avals, in_axes=in_axes, out_axes=out_axes,\nspmd_lowering=spmd_lowering, tuple_args=tuple_args, in_is_global=in_is_global,\nauto_spmd_lowering=auto_spmd_lowering,\n+ unordered_effects=unordered_effects,\nkeepalive=keepalive)\n@@ -2341,6 +2355,7 @@ class MeshExecutable(stages.Executable):\nauto_spmd_lowering: bool,\n_allow_propagation_to_outputs: bool,\n_allow_compile_replicated: bool,\n+ unordered_effects: List[core.Effect],\nkeepalive: Any) -> 'MeshExecutable':\nassert not mesh.empty\nbackend = xb.get_device_backend(mesh.devices.flat[0])\n@@ -2388,7 +2403,7 @@ class MeshExecutable(stages.Executable):\nhandle_outs = global_avals_to_results_handler(global_out_avals, out_axes, mesh) # type: ignore # arg-type\nhandle_args = InputsHandler(xla_executable.local_devices(), input_specs, input_indices)\nunsafe_call = ExecuteReplicated(xla_executable, backend, handle_args,\n- handle_outs, keepalive)\n+ handle_outs, unordered_effects, keepalive)\nreturn MeshExecutable(xla_executable, unsafe_call, input_avals,\nin_axes, out_axes, auto_spmd_lowering)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/sharded_jit.py", "new_path": "jax/interpreters/sharded_jit.py", "diff": "@@ -137,11 +137,14 @@ def _sharded_callable(\nfun.__name__, nparts, global_abstract_args)\naxis_env = xla.AxisEnv(nrep, (), ())\n- effects = list(jaxpr.effects)\n+ unordered_effects = [eff for eff in jaxpr.effects\n+ if eff not in core.ordered_effects]\n+ ordered_effects = [eff for eff in jaxpr.effects\n+ if eff in core.ordered_effects]\nmodule, _ = mlir.lower_jaxpr_to_module(\n\"spjit_{}\".format(fun.__name__),\ncore.ClosedJaxpr(jaxpr, consts),\n- effects,\n+ unordered_effects, ordered_effects,\nplatform=platform,\naxis_context=mlir.ReplicaAxisContext(axis_env),\nname_stack=new_name_stack(wrap_name(name, \"sharded_jit\")),\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -15,6 +15,7 @@ import contextlib\nimport functools\nimport io\nimport textwrap\n+import unittest\nfrom unittest import mock\nfrom typing import Callable, Generator\n@@ -63,6 +64,7 @@ class DebugPrintTest(jtu.JaxTestCase):\ndebug_print('x: {}', x)\nwith capture_stdout() as output:\nf(2)\n+ jax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n@@ -71,6 +73,7 @@ class DebugPrintTest(jtu.JaxTestCase):\ndebug_print('x: {x}', x=x)\nwith capture_stdout() as output:\nf(2)\n+ jax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n@@ -80,6 +83,7 @@ class DebugPrintTest(jtu.JaxTestCase):\ndebug_print('y: {y}', y=x + 1)\nwith capture_stdout() as output:\nf(2)\n+ jax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\ny: 3\\n\")\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n@@ -89,6 +93,7 @@ class DebugPrintTest(jtu.JaxTestCase):\ndebug_print('x: {x}', x=x)\nwith capture_stdout() as output:\nf(2)\n+ jax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n@@ -98,6 +103,7 @@ class DebugPrintTest(jtu.JaxTestCase):\ndebug_print('x: {x}', x=x, ordered=True)\nwith capture_stdout() as output:\nf(2)\n+ jax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n@@ -108,6 +114,7 @@ class DebugPrintTest(jtu.JaxTestCase):\ndebug_print('x: {}', struct, ordered=True)\nwith capture_stdout() as output:\nf(np.array(2, np.int32))\n+ jax.effects_barrier()\nself.assertEqual(output(), f\"x: {str(dict(foo=np.array(2, np.int32)))}\\n\")\nclass DebugPrintTransformationTest(jtu.JaxTestCase):\n@@ -118,6 +125,7 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\ndebug_print('hello: {}', x)\nwith capture_stdout() as output:\nf(jnp.arange(2))\n+ jax.effects_barrier()\nself.assertEqual(output(), \"hello: 0\\nhello: 1\\n\")\ndef test_debug_print_batching_with_diff_axes(self):\n@@ -126,6 +134,7 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\ndebug_print('hello: {} {}', x, y)\nwith capture_stdout() as output:\nf(jnp.arange(2), jnp.arange(2)[None])\n+ jax.effects_barrier()\nself.assertEqual(output(), \"hello: 0 [0]\\nhello: 1 [1]\\n\")\ndef tested_debug_print_with_nested_vmap(self):\n@@ -138,12 +147,14 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\nwith capture_stdout() as output:\n# Should print over 0-axis then 1-axis\njax.vmap(jax.vmap(f))(jnp.arange(6).reshape((3, 2)))\n+ jax.effects_barrier()\nself.assertEqual(\noutput(),\n\"hello: 0\\nhello: 2\\nhello: 4\\nhello: 1\\nhello: 3\\nhello: 5\\n\")\nwith capture_stdout() as output:\n# Should print over 1-axis then 0-axis\njax.vmap(jax.vmap(f, in_axes=0), in_axes=1)(jnp.arange(6).reshape((3, 2)))\n+ jax.effects_barrier()\nself.assertEqual(\noutput(),\n\"hello: 0\\nhello: 1\\nhello: 2\\nhello: 3\\nhello: 4\\nhello: 5\\n\")\n@@ -168,6 +179,7 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\nreturn x\nwith capture_stdout() as output:\njax.linear_transpose(f, 1.)(1.)\n+ jax.effects_barrier()\n# `debug_print` should be dropped by `partial_eval` because of no\n# output data-dependence.\nself.assertEqual(output(), \"\")\n@@ -187,6 +199,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nreturn lax.scan(_body, 2, xs)\nwith capture_stdout() as output:\nf(jnp.arange(2))\n+ jax.effects_barrier()\nself.assertEqual(output(), _format_multiline(\"\"\"\ncarry: 2\nx: 0\n@@ -206,6 +219,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nreturn lax.fori_loop(0, 5, _body, x)\nwith capture_stdout() as output:\nf(2)\n+ jax.effects_barrier()\nself.assertEqual(output(), _format_multiline(\"\"\"\nx: 2\nx: 3\n@@ -228,6 +242,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nreturn lax.while_loop(_cond, _body, x)\nwith capture_stdout() as output:\nf(5)\n+ jax.effects_barrier()\nself.assertEqual(output(), _format_multiline(\"\"\"\nx: 5\nx: 6\n@@ -250,6 +265,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nreturn lax.while_loop(_cond, _body, x)\nwith capture_stdout() as output:\nf(5)\n+ jax.effects_barrier()\nself.assertEqual(output(), _format_multiline(\"\"\"\nx: 5\nx: 6\n@@ -261,6 +277,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nwith capture_stdout() as output:\nf(10)\n+ jax.effects_barrier()\n# Should run the cond once\nself.assertEqual(output(), _format_multiline(\"\"\"\nx: 10\n@@ -281,11 +298,13 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nreturn lax.cond(x < 5, true_fun, false_fun, x)\nwith capture_stdout() as output:\nf(5)\n+ jax.effects_barrier()\nself.assertEqual(output(), _format_multiline(\"\"\"\nfalse: 5\n\"\"\"))\nwith capture_stdout() as output:\nf(4)\n+ jax.effects_barrier()\nself.assertEqual(output(), _format_multiline(\"\"\"\ntrue: 4\n\"\"\"))\n@@ -313,18 +332,23 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\n\"\"\"))\nwith capture_stdout() as output:\nf(1)\n+ jax.effects_barrier()\nself.assertEqual(output(), _format_multiline(\"\"\"\nb2: 1\n\"\"\"))\nwith capture_stdout() as output:\nf(2)\n+ jax.effects_barrier()\nself.assertEqual(output(), _format_multiline(\"\"\"\nb3: 2\n\"\"\"))\nclass DebugPrintParallelTest(jtu.JaxTestCase):\n- @jtu.skip_on_devices(\"tpu\", \"gpu\", \"cpu\")\n+ def _assertLinesEqual(self, text1, text2):\n+ self.assertSetEqual(set(text1.split(\"\\n\")), set(text2.split(\"\\n\")))\n+\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_ordered_print_not_supported_in_pmap(self):\n@jax.pmap\n@@ -334,16 +358,27 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\nValueError, \"Ordered effects not supported in `pmap`.\"):\nf(jnp.arange(jax.local_device_count()))\n- # TODO(sharadmv): Enable test on CPU when we have output tokens to block on\n- @jtu.skip_on_devices(\"tpu\", \"gpu\", \"cpu\")\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\ndef test_unordered_print_works_in_pmap(self):\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices.\")\n@jax.pmap\ndef f(x):\n- debug_print(\"{}\", x, ordered=False)\n+ debug_print(\"hello: {}\", x, ordered=False)\nwith capture_stdout() as output:\nf(jnp.arange(jax.local_device_count()))\n- self.assertSetEqual(set(\"0\\n1\\n\".split(\"\\n\")), set(output().split(\"\\n\")))\n+ jax.effects_barrier()\n+ self._assertLinesEqual(output(), \"hello: 0\\nhello: 1\\n\")\n+\n+ @jax.pmap\n+ def f2(x):\n+ debug_print('hello: {}', x)\n+ debug_print('hello: {}', x + 2)\n+ with capture_stdout() as output:\n+ f2(jnp.arange(2))\n+ jax.effects_barrier()\n+ self._assertLinesEqual(output(), \"hello: 0\\nhello: 1\\nhello: 2\\nhello: 3\\n\")\nif jaxlib.version < (0, 3, 8):\n# No lowering for `emit_python_callback` in older jaxlibs.\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "import functools\nimport threading\nimport unittest\n+import warnings\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -247,7 +248,9 @@ class HigherOrderPrimitiveTest(jtu.JaxTestCase):\neffect_p.bind(effect='foo')\neffect_p.bind(effect='bar')\nreturn x\n- with self.assertRaisesRegex(NotImplementedError, 'Effects not supported'):\n+ with self.assertRaisesRegex(\n+ ValueError,\n+ \"Ordered effects not supported for map primitives: {'foo'}\"):\njax.make_jaxpr(f)(jnp.arange(jax.local_device_count()))\ndef test_xmap_inherits_effects(self):\n@@ -444,14 +447,15 @@ class EffectfulJaxprLoweringTest(jtu.JaxTestCase):\nreturn x + 1.\nmhlo = f.lower(1.).compiler_ir(dialect='mhlo')\ninput_types = mhlo.body.operations[0].type.inputs\n- # First argument should be dummy token\nself.assertLen(list(input_types), 1)\nself.assertEqual(str(input_types[0]), 'tensor<f32>')\n- # First output should be dummy token\n+ # First output should be output token\nresult_types = mhlo.body.operations[0].type.results\n- self.assertLen(list(result_types), 1)\n- self.assertEqual(str(result_types[0]), 'tensor<f32>')\n+ self.assertLen(list(result_types), 2)\n+ self.assertEqual(str(result_types[0]), 'tensor<0xi1>')\n+ self.assertLen(list(result_types), 2)\n+ self.assertEqual(str(result_types[1]), 'tensor<f32>')\ndef test_lowered_jaxpr_with_ordered_effects_takes_in_dummy_inputs(self):\n@jax.jit\n@@ -502,6 +506,32 @@ class EffectfulJaxprLoweringTest(jtu.JaxTestCase):\nreturn x + 1.\nself.assertEqual(f(2.), 3.)\n+ def test_cant_jit_and_pmap_function_with_unordered_effects(self):\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices.\")\n+ @jax.jit\n+ @jax.pmap\n+ def f(x):\n+ effect_p.bind(effect='bar')\n+ return x + 1\n+ with self.assertRaisesRegex(\n+ NotImplementedError,\n+ \"Cannot execute replicated computation with effects.\"):\n+ with warnings.catch_warnings():\n+ warnings.simplefilter(\"ignore\")\n+ f(jnp.arange(jax.device_count()))\n+\n+ def test_cant_jit_and_pmap_function_with_ordered_effects(self):\n+ @jax.jit\n+ @jax.pmap\n+ def f(x):\n+ effect_p.bind(effect='foo')\n+ return x + 1.\n+ with self.assertRaisesRegex(\n+ ValueError,\n+ \"Ordered effects not supported for map primitives: {'foo'}\"):\n+ f(jnp.arange(jax.device_count()))\n+\ndef test_runtime_tokens_should_update_after_running_effectful_function(self):\n@jax.jit\ndef f(x):\n" } ]
Python
Apache License 2.0
google/jax
Add output token for unordered effects Currently we can't block on *unordered* effectful computations because there are no runtime tokens for them. This change adds a per-device token that is returned by effectful computations. This enables us to block on them if we want. See the design note added in https://github.com/google/jax/pull/10657. PiperOrigin-RevId: 449106281
260,301
06.05.2022 16:28:24
-3,600
838a05329df5c039eff95a484eb059e0b46a0da5
feat: validate jit args
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -32,6 +32,7 @@ import types\nfrom typing import (Any, Callable, Iterable, NamedTuple, Mapping, Optional,\nSequence, Tuple, TypeVar, Union, overload, Dict, Hashable,\nList)\n+from typing_extensions import Literal\nfrom warnings import warn\nimport numpy as np\n@@ -56,7 +57,7 @@ from jax._src.api_util import (\nflatten_fun, apply_flat_fun, flatten_fun_nokwargs, flatten_fun_nokwargs2,\nargnums_partial, argnums_partial_except, flatten_axes, donation_vector,\nrebase_donate_argnums, _ensure_index, _ensure_index_tuple,\n- shaped_abstractify, _ensure_str_tuple, argnames_partial_except)\n+ shaped_abstractify, _ensure_str_tuple, argnames_partial_except, validate_argnames, validate_argnums)\nfrom jax._src.lax import lax as lax_internal\nfrom jax._src.lib import jax_jit\nfrom jax._src.lib import xla_bridge as xb\n@@ -178,6 +179,7 @@ def _check_callable(fun):\nraise TypeError(f\"Expected a function, got a generator function: {fun}\")\ndef _isgeneratorfunction(fun):\n+ # TODO 3.9+: remove\n# re-implemented here because of https://bugs.python.org/issue33261\nwhile inspect.ismethod(fun):\nfun = fun.__func__\n@@ -188,26 +190,21 @@ def _isgeneratorfunction(fun):\n_POSITIONAL_OR_KEYWORD = inspect.Parameter.POSITIONAL_OR_KEYWORD\ndef _infer_argnums_and_argnames(\n- fun: Callable,\n+ sig: inspect.Signature,\nargnums: Union[int, Iterable[int], None],\nargnames: Union[str, Iterable[str], None],\n) -> Tuple[Tuple[int, ...], Tuple[str, ...]]:\n\"\"\"Infer missing argnums and argnames for a function with inspect.\"\"\"\nif argnums is None and argnames is None:\n- argnums = ()\n- argnames = ()\n- elif argnums is not None and argnames is not None:\n+ return (), ()\n+\n+ if argnums is not None and argnames is not None:\nargnums = _ensure_index_tuple(argnums)\nargnames = _ensure_str_tuple(argnames)\n- else:\n- try:\n- signature = inspect.signature(fun)\n- except ValueError:\n- # In rare cases, inspect can fail, e.g., on some builtin Python functions.\n- # In these cases, don't infer any parameters.\n- parameters: Mapping[str, inspect.Parameter] = {}\n- else:\n- parameters = signature.parameters\n+\n+ return argnums, argnames\n+\n+ parameters = sig.parameters\nif argnums is None:\nassert argnames is not None\nargnames = _ensure_str_tuple(argnames)\n@@ -216,12 +213,12 @@ def _infer_argnums_and_argnames(\nif param.kind == _POSITIONAL_OR_KEYWORD and k in argnames\n)\nelse:\n- assert argnames is None\nargnums = _ensure_index_tuple(argnums)\nargnames = tuple(\nk for i, (k, param) in enumerate(parameters.items())\nif param.kind == _POSITIONAL_OR_KEYWORD and i in argnums\n)\n+\nreturn argnums, argnames\n@@ -332,15 +329,63 @@ def jit(\nDeviceArray([ 0, 1, 256, 6561], dtype=int32)\n\"\"\"\nif FLAGS.experimental_cpp_jit and not config.jax_dynamic_shapes:\n- return _cpp_jit(fun, static_argnums, static_argnames, device, backend,\n+ return _jit(True, fun, static_argnums, static_argnames, device, backend,\ndonate_argnums, inline, keep_unused)\n- else:\n- return _python_jit(fun, static_argnums, static_argnames, device, backend,\n+ return _jit(False, fun, static_argnums, static_argnames, device, backend,\ndonate_argnums, inline, keep_unused, abstracted_axes)\n+def _jit(\n+ use_cpp_jit: bool,\n+ fun: Callable,\n+ static_argnums: Union[int, Iterable[int], None] = None,\n+ static_argnames: Union[str, Iterable[str], None] = None,\n+ device: Optional[xc.Device] = None,\n+ backend: Optional[str] = None,\n+ donate_argnums: Union[int, Iterable[int]] = (),\n+ inline: bool = False,\n+ keep_unused: bool = False,\n+ abstracted_axes: Optional[Any] = None,\n+ ) -> stages.Wrapped:\n+ # Implemements common logic between CPP and Python backends\n+ _check_callable(fun)\n+\n+ # Coerce input\n+ donate_argnums = _ensure_index_tuple(donate_argnums)\n+\n+ try:\n+ sig = inspect.signature(fun)\n+ except ValueError:\n+ # Some built-in functions don't support signature.\n+ # See: https://github.com/python/cpython/issues/73485\n+ # In this case no validation is done\n+ static_argnums = () if static_argnums is None else _ensure_index_tuple(static_argnums)\n+ static_argnames = () if static_argnames is None else _ensure_str_tuple(static_argnames)\n+ else:\n+ # Infer argnums and argnames according to docstring\n+ static_argnums, static_argnames = _infer_argnums_and_argnames(\n+ sig, static_argnums, static_argnames)\n+\n+ # Validation\n+ validate_argnums(sig, static_argnums, \"static_argnums\")\n+ validate_argnums(sig, donate_argnums, \"donate_argnums\")\n+\n+ validate_argnames(sig, static_argnames, \"static_argnames\")\n+\n+ # Compensate for static argnums absorbing args\n+ donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)\n+\n+ if use_cpp_jit:\n+ return _cpp_jit(fun, static_argnums=static_argnums, static_argnames=static_argnames,\n+ device=device, backend=backend,\n+ donate_argnums=donate_argnums, inline=inline, keep_unused=keep_unused)\n+\n+ return _python_jit(fun, static_argnums=static_argnums, static_argnames=static_argnames,\n+ device=device, backend=backend, donate_argnums=donate_argnums,\n+ inline=inline, keep_unused=keep_unused, abstracted_axes=abstracted_axes)\ndef _prepare_jit(fun, static_argnums, static_argnames, donate_argnums,\nargs, kwargs):\n+ # Validate donate_argnums\nif max(donate_argnums, default=-1) >= len(args):\nraise ValueError(\nf\"jitted function has donate_argnums={donate_argnums} but \"\n@@ -362,22 +407,16 @@ PytreeOfAbstractedAxesSpec = Any\ndef _python_jit(\nfun: Callable,\n- static_argnums: Union[int, Iterable[int], None] = None,\n- static_argnames: Union[str, Iterable[str], None] = None,\n- device: Optional[xc.Device] = None,\n- backend: Optional[str] = None,\n- donate_argnums: Union[int, Iterable[int]] = (),\n- inline: bool = False,\n- keep_unused: bool = False,\n- abstracted_axes: Optional[PytreeOfAbstractedAxesSpec] = None,\n+ *,\n+ static_argnums: Tuple[int, ...],\n+ static_argnames: Tuple[str, ...],\n+ device: Optional[xc.Device],\n+ backend: Optional[str],\n+ donate_argnums: Tuple[int, ...],\n+ inline: bool,\n+ keep_unused: bool,\n+ abstracted_axes: Optional[PytreeOfAbstractedAxesSpec],\n) -> stages.Wrapped:\n- _check_callable(fun)\n- static_argnums, static_argnames = _infer_argnums_and_argnames(\n- fun, static_argnums, static_argnames)\n- static_argnums = _ensure_index_tuple(static_argnums)\n- donate_argnums = _ensure_index_tuple(donate_argnums)\n- donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)\n-\n@wraps(fun)\n@api_boundary\ndef f_jitted(*args, **kwargs):\n@@ -429,13 +468,14 @@ _cpp_jit_cache = jax_jit.CompiledFunctionCache()\ndef _cpp_jit(\nfun: Callable,\n- static_argnums: Union[int, Iterable[int], None] = None,\n- static_argnames: Union[str, Iterable[str], None] = None,\n- device: Optional[xc.Device] = None,\n- backend: Optional[str] = None,\n- donate_argnums: Union[int, Iterable[int]] = (),\n- inline: bool = False,\n- keep_unused: bool = False,\n+ *,\n+ static_argnums: Tuple[int, ...],\n+ static_argnames: Tuple[str, ...],\n+ device: Optional[xc.Device],\n+ backend: Optional[str],\n+ donate_argnums: Tuple[int, ...],\n+ inline: bool,\n+ keep_unused: bool,\n) -> stages.Wrapped:\n# An implementation of `jit` that tries to do as much as possible in C++.\n# The goal of this function is to speed up the time it takes to process the\n@@ -444,13 +484,6 @@ def _cpp_jit(\n# As long as it does not support all features of the Python implementation\n# the C++ code will fallback to `_python_jit` when it faces some unsupported\n# feature.\n- _check_callable(fun)\n- static_argnums, static_argnames = _infer_argnums_and_argnames(\n- fun, static_argnums, static_argnames)\n- static_argnums = _ensure_index_tuple(static_argnums)\n- donate_argnums = _ensure_index_tuple(donate_argnums)\n- donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)\n-\nif device is not None and backend is not None:\nraise ValueError(\"can't specify both a device and a backend for jit, \"\nf\"got device={device} and backend={backend}.\")\n@@ -2372,11 +2405,7 @@ def _vjp_pullback_wrapper(cotangent_dtypes, cotangent_shapes,\nans = fun(*args)\nreturn tree_unflatten(out_tree, ans)\n-\n-if sys.version_info >= (3, 8):\n- from typing import Literal\n-\n- @overload # type: ignore\n+@overload\ndef vjp(fun: Callable[..., T],\n*primals: Any,\nhas_aux: Literal[False] = False,\n@@ -2388,21 +2417,6 @@ if sys.version_info >= (3, 8):\nhas_aux: Literal[True],\nreduce_axes: Sequence[AxisName] = ()) -> Tuple[T, Callable, U]:\n...\n-else:\n-\n- @overload # type: ignore\n- def vjp(fun: Callable[..., T], *primals: Any) -> Tuple[T, Callable]:\n- ...\n-\n- @overload\n- def vjp(\n- fun: Callable[..., Any], *primals: Any,\n- has_aux: bool,\n- reduce_axes: Sequence[AxisName] = ()\n- ) -> Union[Tuple[Any, Callable], Tuple[Any, Callable, Any]]:\n- ...\n-\n-\ndef vjp( # type: ignore\nfun: Callable, *primals, has_aux: bool = False, reduce_axes=()\n) -> Union[Tuple[Any, Callable], Tuple[Any, Callable, Any]]:\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api_util.py", "new_path": "jax/_src/api_util.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import inspect\nimport operator\nfrom functools import partial\n-from typing import Any, Dict, Iterable, Tuple, Sequence, Union, Optional\n+from typing import Any, Dict, Iterable, Sequence, Set, Tuple, Union, Optional\n+import warnings\nimport numpy as np\n@@ -132,6 +134,94 @@ class _HashableWithStrictTypeEquality:\ndef __eq__(self, other):\nreturn type(self.val) is type(other.val) and self.val == other.val\n+_POSITIONAL_ARGUMENTS = (\n+ inspect.Parameter.POSITIONAL_ONLY,\n+ inspect.Parameter.POSITIONAL_OR_KEYWORD\n+)\n+\n+def validate_argnums(sig: inspect.Signature, argnums: Tuple[int, ...], argnums_name: str) -> None:\n+ \"\"\"\n+ Validate that the argnums are sensible for a given function.\n+\n+ For functions that accept a variable number of positions arguments\n+ (`f(..., *args)`) all positive argnums are considered valid.\n+ \"\"\"\n+ n_pos_args = 0\n+ for param in sig.parameters.values():\n+ if param.kind in _POSITIONAL_ARGUMENTS:\n+ n_pos_args += 1\n+\n+ elif param.kind is inspect.Parameter.VAR_POSITIONAL:\n+ # We can have any number of positional arguments\n+ return\n+\n+ if argnums and (-min(argnums) > n_pos_args or max(argnums) >= n_pos_args):\n+ # raise ValueError(f\"Jitted function has {argnums_name}={argnums}, \"\n+ # f\"but only accepts {n_pos_args} positional arguments.\")\n+ # TODO: 2022-08-20 or later: replace with error\n+ warnings.warn(f\"Jitted function has {argnums_name}={argnums}, \"\n+ f\"but only accepts {n_pos_args} positional arguments. \"\n+ \"This warning will be replaced by an error after 2022-08-20 \"\n+ \"at the earliest.\", SyntaxWarning)\n+\n+_INVALID_KEYWORD_ARGUMENTS = (\n+ inspect.Parameter.POSITIONAL_ONLY,\n+ inspect.Parameter.VAR_POSITIONAL\n+)\n+\n+_KEYWORD_ARGUMENTS = (\n+ inspect.Parameter.POSITIONAL_OR_KEYWORD,\n+ inspect.Parameter.KEYWORD_ONLY,\n+)\n+def validate_argnames(sig: inspect.Signature, argnames: Tuple[str, ...], argnames_name: str) -> None:\n+ \"\"\"\n+ Validate that the argnames are sensible for a given function.\n+\n+ For functions that accept a variable keyword arguments\n+ (`f(..., **kwargs)`) all argnames are considered valid except those\n+ marked as position-only (`f(pos_only, /, ...)`).\n+ \"\"\"\n+ var_kwargs = False\n+ valid_kwargs: Set[str] = set()\n+ invalid_kwargs: Set[str] = set()\n+ for param_name, param in sig.parameters.items():\n+ if param.kind in _KEYWORD_ARGUMENTS:\n+ valid_kwargs.add(param_name)\n+\n+ elif param.kind is inspect.Parameter.VAR_KEYWORD:\n+ var_kwargs = True\n+\n+ elif param.kind in _INVALID_KEYWORD_ARGUMENTS:\n+ invalid_kwargs.add(param_name)\n+\n+\n+ # Check whether any kwargs are invalid due to position only\n+ invalid_argnames = invalid_kwargs & set(argnames)\n+ if invalid_argnames:\n+ # raise ValueError(f\"Jitted function has invalid argnames {invalid_argnames} \"\n+ # f\"in {argnames_name}. These are positional-only\")\n+ # TODO: 2022-08-20 or later: replace with error\n+ warnings.warn(f\"Jitted function has invalid argnames {invalid_argnames} \"\n+ f\"in {argnames_name}. These are positional-only. \"\n+ \"This warning will be replaced by an error after 2022-08-20 \"\n+ \"at the earliest.\", SyntaxWarning)\n+\n+ # Takes any kwargs\n+ if var_kwargs:\n+ return\n+\n+ # Check that all argnames exist on function\n+ invalid_argnames = set(argnames) - valid_kwargs\n+ if invalid_argnames:\n+ # TODO: 2022-08-20 or later: replace with error\n+ # raise ValueError(f\"Jitted function has invalid argnames {invalid_argnames} \"\n+ # f\"in {argnames_name}. Function does not take these args.\")\n+ warnings.warn(f\"Jitted function has invalid argnames {invalid_argnames} \"\n+ f\"in {argnames_name}. Function does not take these args.\"\n+ \"This warning will be replaced by an error after 2022-08-20 \"\n+ \"at the earliest.\", SyntaxWarning)\n+\n+\ndef argnums_partial(f, dyn_argnums, args, require_static_args_hashable=True):\ndyn_argnums = _ensure_index_tuple(dyn_argnums)\n@@ -154,6 +244,11 @@ def argnums_partial(f, dyn_argnums, args, require_static_args_hashable=True):\ndef _ensure_inbounds(allow_invalid: bool, num_args: int, argnums: Sequence[int]\n) -> Tuple[int, ...]:\n+ \"\"\"\n+ Ensure argnum is within bounds.\n+\n+ Also resolves negative argnums\n+ \"\"\"\nresult = []\nfor i in argnums:\nif i >= num_args and allow_invalid: continue\n@@ -162,9 +257,10 @@ def _ensure_inbounds(allow_invalid: bool, num_args: int, argnums: Sequence[int]\n\"Positional argument indices, e.g. for `static_argnums`, must have \"\n\"value greater than or equal to -len(args) and less than len(args), \"\nf\"but got value {i} for len(args) == {num_args}.\")\n- result.append(i % num_args)\n+ result.append(i % num_args) # Resolve negative\nreturn tuple(result)\n+\ndef argnums_partial_except(f: lu.WrappedFun, static_argnums: Tuple[int, ...],\nargs: Tuple[Any], *, allow_invalid: bool):\n\"\"\"Version of ``argnums_partial`` that checks hashability of static_argnums.\"\"\"\n@@ -180,9 +276,7 @@ def argnums_partial_except(f: lu.WrappedFun, static_argnums: Tuple[int, ...],\nif allow_invalid and i >= len(args):\ncontinue\nstatic_arg = args[i]\n- try:\n- hash(static_arg)\n- except TypeError:\n+ if not is_hashable(static_arg):\nraise ValueError(\n\"Non-hashable static arguments are not supported, as this can lead \"\nf\"to unexpected cache-misses. Static argument (index {i}) of type \"\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/linalg.py", "new_path": "jax/_src/scipy/linalg.py", "diff": "@@ -148,7 +148,7 @@ def lu_factor(a, overwrite_a=False, check_finite=True):\n@_wraps(scipy.linalg.lu_solve,\nlax_description=_no_overwrite_and_chkfinite_doc, skip_params=('overwrite_b', 'check_finite'))\n-@partial(jit, static_argnames=('trans', 'overwrite_a', 'check_finite'))\n+@partial(jit, static_argnames=('trans', 'overwrite_b', 'check_finite'))\ndef lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):\ndel overwrite_b, check_finite\nlu, pivots = lu_and_piv\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/test_util.py", "new_path": "jax/_src/test_util.py", "diff": "@@ -844,6 +844,18 @@ class JaxTestCase(parameterized.TestCase):\natol=atol or tol, rtol=rtol or tol,\ncanonicalize_dtypes=canonicalize_dtypes)\n+_CPP_JIT_IMPLEMENTATION = functools.partial(api._jit, True)\n+_CPP_JIT_IMPLEMENTATION._name = \"cpp\"\n+_PYTHON_JIT_IMPLEMENTATION = functools.partial(api._jit, False)\n+_PYTHON_JIT_IMPLEMENTATION._name = \"python\"\n+_NOOP_JIT_IMPLEMENTATION = lambda x, *args, **kwargs: x\n+_NOOP_JIT_IMPLEMENTATION._name = \"noop\"\n+\n+JIT_IMPLEMENTATION = (\n+ _CPP_JIT_IMPLEMENTATION,\n+ _PYTHON_JIT_IMPLEMENTATION,\n+ _NOOP_JIT_IMPLEMENTATION,\n+)\nclass BufferDonationTestCase(JaxTestCase):\nassertDeleted = lambda self, x: self._assertDeleted(x, True)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -19,6 +19,7 @@ from contextlib import contextmanager\nimport copy\nimport enum\nfrom functools import partial\n+import inspect\nimport operator\nimport re\nimport subprocess\n@@ -78,9 +79,13 @@ class CPPJitTest(jtu.BufferDonationTestCase):\nPython tests that extend the C++ tests (and not the other way around).\n\"\"\"\n+ @property\n+ def use_cpp_jit(self) -> bool:\n+ return True\n+\n@property\ndef jit(self):\n- return api._cpp_jit\n+ return functools.partial(api._jit, self.use_cpp_jit)\ndef test_jit_repr(self):\ndef my_function():\n@@ -182,7 +187,7 @@ class CPPJitTest(jtu.BufferDonationTestCase):\nself.assertLen(side, 1)\nself.assertEqual(f1(1, A()), 100)\nself.assertLen(side, 1)\n- if self.jit == api._cpp_jit:\n+ if self.use_cpp_jit:\nf1_cpp = getattr(f1, \"_cpp_jitted_f\", f1)\nself.assertEqual(f1_cpp._cache_size(), 1)\n@@ -231,6 +236,90 @@ class CPPJitTest(jtu.BufferDonationTestCase):\ndef test_complex_support(self):\nself.assertEqual(self.jit(lambda x: x + 1)(1 + 1j), 2 + 1j)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": f\"_{argnum_type}\",\n+ \"argnum_type\": argnum_type}\n+ for argnum_type in (\"static_argnums\", \"donate_argnums\")))\n+ def test_jit_argnums_overflow_error(self, argnum_type: str):\n+ def f(a, b, c):\n+ ...\n+\n+ def g(a, /, b, *, c):\n+ ...\n+\n+ def h(a, *args):\n+ ...\n+\n+ def i():\n+ ...\n+\n+ # Simplest cases\n+ self.jit(f, **{argnum_type: (0, 1)})\n+ self.jit(g, **{argnum_type: (0, 1)})\n+ self.jit(f, **{argnum_type: (0, 1, -3)})\n+\n+ # Out of bounds without *args\n+ # with self.assertRaises(ValueError):\n+ with self.assertWarns(SyntaxWarning):\n+ self.jit(f, **{argnum_type: (0, 1, 3)})\n+\n+ # with self.assertRaises(ValueError):\n+ with self.assertWarns(SyntaxWarning):\n+ self.jit(f, **{argnum_type: (0, 1, -4)})\n+\n+ # with self.assertRaises(ValueError):\n+ with self.assertWarns(SyntaxWarning):\n+ self.jit(g, **{argnum_type: (0, 1, 3)})\n+\n+ # with self.assertRaises(ValueError):\n+ with self.assertWarns(SyntaxWarning):\n+ self.jit(g, **{argnum_type: (0, 1, -3)})\n+\n+ # Out of bounds with *args\n+ self.jit(h, **{argnum_type: (0, 999)})\n+ self.jit(h, **{argnum_type: (0, -999)})\n+\n+\n+ # No positional arguments\n+ self.jit(i, static_argnums=())\n+ self.jit(i)\n+\n+ def test_jit_argnames_validation(self):\n+ def f(a, b, c):\n+ ...\n+\n+ def g(a, b, **kwargs):\n+ ...\n+\n+ def h(a, /, b, c, *args, **kwargs):\n+ ...\n+\n+ # Simplest case\n+ self.jit(f, static_argnames=(\"b\", \"c\"))\n+\n+ # Undefined arg without **kwargs\n+ # with self.assertRaises(ValueError):\n+ with self.assertWarns(SyntaxWarning):\n+ self.jit(f, static_argnames=(\"b\", \"c\", \"not_defined\"))\n+\n+ # Undefined arg with **kwargs\n+ self.jit(g, static_argnames=(\"a\", \"b\", \"not_defined\"))\n+\n+ self.jit(h, static_argnames=(\"b\", \"c\"))\n+ self.jit(h, static_argnames=(\"b\", \"c\", \"not_defined\"))\n+\n+ # Positional only\n+ # with self.assertRaises(ValueError):\n+ with self.assertWarns(SyntaxWarning):\n+ self.jit(h, static_argnames=(\"a\", \"c\"))\n+\n+ # Var positional\n+ # with self.assertRaises(ValueError):\n+ with self.assertWarns(SyntaxWarning):\n+ self.jit(h, static_argnames=(\"args\", \"c\"))\n+\n+\ndef test_jit_with_many_args_works(self):\n@self.jit\n@@ -486,11 +575,11 @@ class CPPJitTest(jtu.BufferDonationTestCase):\njitted_f(1, np.asarray(1))\ndef test_cpp_jit_raises_on_non_hashable_static_argnum(self):\n- if self.jit != api._cpp_jit:\n+ if not self.use_cpp_jit:\nraise unittest.SkipTest(\"this test only applies to _cpp_jit\")\nf = lambda x, y: x + 3\n- jitted_f = api._cpp_jit(f, static_argnums=[1])\n+ jitted_f = self.jit(f, static_argnums=[1])\njitted_f(1, 1)\n@@ -534,7 +623,7 @@ class CPPJitTest(jtu.BufferDonationTestCase):\nf(a)\ndef test_cpp_jitted_function_returns_PyBuffer(self):\n- if self.jit != api._cpp_jit:\n+ if not self.use_cpp_jit:\nraise unittest.SkipTest(\"this test only applies to _cpp_jit\")\njitted_f = self.jit(lambda a: a + 1)\n@@ -630,39 +719,45 @@ class CPPJitTest(jtu.BufferDonationTestCase):\ndef f(x, y=1):\npass\n+ sig = inspect.signature(f)\n+\nargnums, argnames = api._infer_argnums_and_argnames(\n- f, argnums=None, argnames=None)\n+ sig, argnums=None, argnames=None)\nassert argnums == ()\nassert argnames == ()\nargnums, argnames = api._infer_argnums_and_argnames(\n- f, argnums=0, argnames=None)\n+ sig, argnums=0, argnames=None)\nassert argnums == (0,)\nassert argnames == ('x',)\nargnums, argnames = api._infer_argnums_and_argnames(\n- f, argnums=None, argnames='y')\n+ sig, argnums=None, argnames='y')\nassert argnums == (1,)\nassert argnames == ('y',)\nargnums, argnames = api._infer_argnums_and_argnames(\n- f, argnums=0, argnames='y') # no validation\n+ sig, argnums=0, argnames='y') # no validation\nassert argnums == (0,)\nassert argnames == ('y',)\ndef g(x, y, *args):\npass\n+ sig = inspect.signature(g)\n+\nargnums, argnames = api._infer_argnums_and_argnames(\n- g, argnums=(1, 2), argnames=None)\n+ sig, argnums=(1, 2), argnames=None)\nassert argnums == (1, 2)\nassert argnames == ('y',)\ndef h(x, y, **kwargs):\npass\n+ sig = inspect.signature(h)\n+\nargnums, argnames = api._infer_argnums_and_argnames(\n- h, argnums=None, argnames=('foo', 'bar'))\n+ sig, argnums=None, argnames=('foo', 'bar'))\nassert argnums == ()\nassert argnames == ('foo', 'bar')\n@@ -921,9 +1016,8 @@ class CPPJitTest(jtu.BufferDonationTestCase):\nclass PythonJitTest(CPPJitTest):\n@property\n- def jit(self):\n- return api._python_jit\n-\n+ def use_cpp_jit(self) -> bool:\n+ return False\nclass APITest(jtu.JaxTestCase):\n@@ -7856,23 +7950,19 @@ class NamedCallTest(jtu.JaxTestCase):\nself.assertEqual(out, 5)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": f\"_jit_type={jit_type}_func={func}\",\n- \"jit_type\": jit_type, \"func\": func}\n+ {\"testcase_name\": f\"_jit={jit._name}_func={func}\",\n+ \"jit\": jit, \"func\": func}\nfor func in ['identity', 'asarray', 'device_put']\n- for jit_type in [None, \"python\", \"cpp\"]\n- if not (jit_type is None and func == 'identity')))\n- def test_integer_overflow(self, jit_type, func):\n+ for jit in jtu.JIT_IMPLEMENTATION\n+ if not (jit._name == \"noop\" and func == 'identity')))\n+ def test_integer_overflow(self, jit, func):\nfuncdict = {\n'identity': lambda x: x,\n'asarray': jnp.asarray,\n'device_put': api.device_put,\n}\n- jit = {\n- 'python': api._python_jit,\n- 'cpp': api._cpp_jit,\n- None: lambda x: x,\n- }\n- f = jit[jit_type](funcdict[func])\n+\n+ f = jit(funcdict[func])\nint_dtype = dtypes.canonicalize_dtype(jnp.int_)\nint_max = np.iinfo(int_dtype).max\n" }, { "change_type": "MODIFY", "old_path": "tests/debug_nans_test.py", "new_path": "tests/debug_nans_test.py", "diff": "\"\"\"Tests for --debug_nans.\"\"\"\n-from absl.testing import absltest\n+from absl.testing import absltest, parameterized\nimport jax\nimport numpy as np\n@@ -29,6 +29,7 @@ import jax._src.lib\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n+\nclass DebugNaNsTest(jtu.JaxTestCase):\ndef setUp(self):\n@@ -80,9 +81,10 @@ class DebugNaNsTest(jtu.JaxTestCase):\nans = 0. / A\nans.block_until_ready()\n- def testCallDeoptimized(self):\n- for jit in [api._python_jit, api._cpp_jit]:\n-\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": f\"_jit={jit._name}\", \"jit\": jit}\n+ for jit in jtu.JIT_IMPLEMENTATION))\n+ def testCallDeoptimized(self, jit):\n@jit\ndef f(x):\nreturn jax.lax.cond(\n@@ -190,9 +192,10 @@ class DebugInfsTest(jtu.JaxTestCase):\nans = 1. / A\nans.block_until_ready()\n- def testCallDeoptimized(self):\n- for jit in [api._python_jit, api._cpp_jit]:\n-\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": f\"_jit={jit._name}\", \"jit\": jit}\n+ for jit in jtu.JIT_IMPLEMENTATION))\n+ def testCallDeoptimized(self, jit):\n@jit\ndef f(x):\nreturn jax.lax.cond(\n" }, { "change_type": "MODIFY", "old_path": "tests/jax_jit_test.py", "new_path": "tests/jax_jit_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+from functools import partial\nimport inspect\nfrom absl.testing import absltest\n@@ -199,10 +200,11 @@ class JaxJitTest(jtu.JaxTestCase):\nself.assertTrue(signature.weak_type)\ndef test_signature_support(self):\n+ jit = partial(api._jit, True)\ndef f(a, b, c):\nreturn a + b + c\n- jitted_f = api._cpp_jit(f)\n+ jitted_f = jit(f)\nself.assertEqual(inspect.signature(f), inspect.signature(jitted_f))\n" }, { "change_type": "MODIFY", "old_path": "tests/x64_context_test.py", "new_path": "tests/x64_context_test.py", "diff": "@@ -23,7 +23,6 @@ from absl.testing import parameterized\nimport numpy as np\nimport jax\n-from jax._src import api\nfrom jax import lax\nfrom jax import random\nfrom jax.config import config\n@@ -34,23 +33,12 @@ import jax._src.test_util as jtu\nconfig.parse_flags_with_absl()\n-def _maybe_jit(jit_type, func, *args, **kwargs):\n- if jit_type == \"python\":\n- return api._python_jit(func, *args, **kwargs)\n- elif jit_type == \"cpp\":\n- return api._cpp_jit(func, *args, **kwargs)\n- elif jit_type is None:\n- return func\n- else:\n- raise ValueError(f\"Unrecognized jit_type={jit_type!r}\")\n-\n-\nclass X64ContextTests(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": f\"_jit={jit}\", \"jit\": jit}\n- for jit in [\"python\", \"cpp\", None]))\n+ {\"testcase_name\": f\"_jit={jit._name}\", \"jit\": jit}\n+ for jit in jtu.JIT_IMPLEMENTATION))\ndef test_make_array(self, jit):\n- func = _maybe_jit(jit, lambda: jnp.array(np.float64(0)))\n+ func = jit(lambda: jnp.array(np.float64(0)))\ndtype_start = func().dtype\nwith enable_x64():\nself.assertEqual(func().dtype, \"float64\")\n@@ -60,15 +48,15 @@ class X64ContextTests(jtu.JaxTestCase):\n@parameterized.named_parameters(\njtu.cases_from_list({\n- \"testcase_name\": f\"_jit={jit}_f_{f.__name__}\",\n+ \"testcase_name\": f\"_jit={jit._name}_f_{f.__name__}\",\n\"jit\": jit,\n\"enable_or_disable\": f\n- } for jit in [\"python\", \"cpp\", None] for f in [enable_x64, disable_x64]))\n+ } for jit in jtu.JIT_IMPLEMENTATION for f in [enable_x64, disable_x64]))\ndef test_correctly_capture_default(self, jit, enable_or_disable):\n# The fact we defined a jitted function with a block with a different value\n# of `config.enable_x64` has no impact on the output.\nwith enable_or_disable():\n- func = _maybe_jit(jit, lambda: jnp.array(np.float64(0)))\n+ func = jit(lambda: jnp.array(np.float64(0)))\nfunc()\nexpected_dtype = \"float64\" if config._read(\"jax_enable_x64\") else \"float32\"\n@@ -81,12 +69,12 @@ class X64ContextTests(jtu.JaxTestCase):\n@unittest.skipIf(jtu.device_under_test() != \"cpu\", \"Test presumes CPU precision\")\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": f\"_jit={jit}\", \"jit\": jit}\n- for jit in [\"python\", \"cpp\", None]))\n+ {\"testcase_name\": f\"_jit={jit._name}\", \"jit\": jit}\n+ for jit in jtu.JIT_IMPLEMENTATION))\ndef test_near_singular_inverse(self, jit):\nrng = jtu.rand_default(self.rng())\n- @partial(_maybe_jit, jit, static_argnums=1)\n+ @partial(jit, static_argnums=1)\ndef near_singular_inverse(N=5, eps=1E-40):\nX = rng((N, N), dtype='float64')\nX = jnp.asarray(X)\n@@ -102,10 +90,10 @@ class X64ContextTests(jtu.JaxTestCase):\nself.assertTrue(jnp.all(~jnp.isfinite(result_32)))\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": f\"_jit={jit}\", \"jit\": jit}\n- for jit in [\"python\", \"cpp\", None]))\n+ {\"testcase_name\": f\"_jit={jit._name}\", \"jit\": jit}\n+ for jit in jtu.JIT_IMPLEMENTATION))\ndef test_while_loop(self, jit):\n- @partial(_maybe_jit, jit)\n+ @jit\ndef count_to(N):\nreturn lax.while_loop(lambda x: x < N, lambda x: x + 1.0, 0.0)\n" } ]
Python
Apache License 2.0
google/jax
feat: validate jit args
260,335
18.05.2022 14:11:10
25,200
052a9183f065de0d62596b41f47701b9e377e6a9
quick fix for add checks and todo
[ { "change_type": "MODIFY", "old_path": "jax/_src/custom_derivatives.py", "new_path": "jax/_src/custom_derivatives.py", "diff": "@@ -360,6 +360,8 @@ def _custom_jvp_call_jaxpr_jvp(\nouts = core.eval_jaxpr(jvp_jaxpr, jvp_consts, *args, *args_dot)\nprimals_out, tangents_out = split_list(outs, [len(outs) // 2])\ntangents_out = map(ad.recast_to_float0, primals_out, tangents_out)\n+ if config.jax_enable_checks:\n+ assert all(map(core.typecheck, fun_jaxpr.out_avals, primals_out))\nreturn primals_out, tangents_out\nad.primitive_jvps[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_jvp\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/ufuncs.py", "new_path": "jax/_src/numpy/ufuncs.py", "diff": "@@ -700,10 +700,11 @@ def sinc(x):\ndef _sinc_maclaurin(k, x):\n# compute the kth derivative of x -> sin(x)/x evaluated at zero (since we\n# compute the monomial term in the jvp rule)\n+ # TODO(mattjj): see https://github.com/google/jax/issues/10750\nif k % 2:\n- return lax.full_like(x, 0)\n+ return x * 0\nelse:\n- return lax.full_like(x, (-1) ** (k // 2) / (k + 1))\n+ return x * 0 + _lax_const(x, (-1) ** (k // 2) / (k + 1))\n@_sinc_maclaurin.defjvp\ndef _sinc_maclaurin_jvp(k, primals, tangents):\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -371,13 +371,12 @@ def traverse_jaxpr_params(f, params):\ndef eval_jaxpr(jaxpr: Jaxpr, consts, *args):\n- def read(v):\n- if type(v) is Literal:\n- return v.val\n- else:\n- return env[v]\n+ def read(v: Atom) -> Any:\n+ return v.val if isinstance(v, Literal) else env[v]\n- def write(v, val):\n+ def write(v: Var, val: Any) -> None:\n+ if config.jax_enable_checks and not config.jax_dynamic_shapes:\n+ assert typecheck(v.aval, val), (v.aval, val)\nenv[v] = val\nenv: Dict[Var, Any] = {}\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -5817,6 +5817,24 @@ class CustomJVPTest(jtu.JaxTestCase):\nself.assertEmpty(aux_args)\nf()\n+ def test_sinc_constant_function_batching(self):\n+ # https://github.com/google/jax/pull/10756\n+ batch_data = jnp.arange(15.).reshape(5, 3)\n+\n+ @jax.vmap\n+ def f(x):\n+ return jax.lax.map(jnp.sinc, x)\n+ g = lambda param: f(param * batch_data).sum()\n+\n+ @jax.vmap\n+ def f_ref(x):\n+ return jnp.stack([jnp.sinc(x_) for x_ in x])\n+ g_ref = lambda param: f_ref(param * batch_data).sum()\n+\n+ grad = jax.grad(g )(0.1) # doesn't crash\n+ grad_ref = jax.grad(g_ref)(0.1)\n+ self.assertAllClose(grad, grad_ref, check_dtypes=False)\n+\nclass CustomVJPTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
quick fix for #10750, add checks and todo
260,510
18.05.2022 16:53:52
25,200
1bf51797e452da26445aef78d5a4c1740381221d
add TODO for removing output tokens
[ { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -138,6 +138,8 @@ class RuntimeTokenSet(threading.local):\ndef block_until_ready(self):\nfor t, _ in self.tokens.values():\nt[0].block_until_ready()\n+ # TODO(sharadmv): use a runtime mechanism to block on computations instead\n+ # of using output tokens.\nfor t in self.output_tokens.values():\nt[0].block_until_ready()\n" } ]
Python
Apache License 2.0
google/jax
add TODO for removing output tokens
260,335
18.05.2022 17:26:10
25,200
bea66b1b1a3cae03bf70d346332a3b875fabfdbd
add support for lambda-bound dynamic shape output (iree only)
[ { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -209,7 +209,8 @@ def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name,\n# is intentional here, to avoid \"Store occupied\" errors we clone the\n# WrappedFun with empty stores.\nstores = [lu.Store() for _ in fun.stores]\n- clone = lu.WrappedFun(fun.f, fun.transforms, stores, fun.params, fun.in_type)\n+ clone = lu.WrappedFun(fun.f, fun.transforms, stores, fun.params,\n+ fun.in_type)\nwith core.new_sublevel():\n_ = clone.call_wrapped(*args) # may raise, not return\n@@ -286,18 +287,30 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nfun, abstract_args, pe.debug_info_final(fun, \"jit\"), which_explicit)\nif any(isinstance(c, core.Tracer) for c in consts):\nraise UnexpectedTracerError(\"Encountered an unexpected tracer.\")\n- # TODO(mattjj): handle argument pruning w/ dynamic shapes\n- if fun.in_type is None and not keep_unused:\n+\n+ if config.jax_dynamic_shapes and fun.in_type is not None:\n+ # TODO(mattjj): maybe move this into trace_to_subjaxpr_dynamic\n+ # TODO(mattjj,dougalm): out_type and out_avals are redundant, simplify!\n+ out_type = tuple([aval.update(shape=tuple(pe.InDBIdx(jaxpr.invars.index(d))\n+ if type(d) is core.Var\n+ else d for d in aval.shape))\n+ for aval in out_avals])\n+ keep_unused = True\n+ else:\n+ out_type = None\n+ # TODO(mattjj): handle host_callback w/ dyn shapes, or wait for replacement\n+ jaxpr = apply_outfeed_rewriter(jaxpr)\n+\n+ if not keep_unused:\njaxpr, kept_const_idx, kept_var_idx = _prune_unused_inputs(jaxpr)\nconsts = [c for i, c in enumerate(consts) if i in kept_const_idx]\nabstract_args, arg_devices = util.unzip2(\n[a for i, a in enumerate(arg_specs) if i in kept_var_idx])\n- donated_invars = [x for i, x in enumerate(donated_invars) if i in kept_var_idx]\n+ donated_invars = [x for i, x in enumerate(donated_invars)\n+ if i in kept_var_idx]\ndel kept_const_idx\nelse:\nkept_var_idx = set(range(len(abstract_args)))\n- map(prefetch, itertools.chain(consts, jaxpr_literals(jaxpr)))\n- jaxpr = apply_outfeed_rewriter(jaxpr)\nnreps = jaxpr_replicas(jaxpr)\ndevice = _xla_callable_device(nreps, backend, device, arg_devices)\n@@ -307,13 +320,15 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nnot _backend_supports_unbounded_dynamic_shapes(backend)):\njaxpr, consts = pe.pad_jaxpr(jaxpr, consts)\n+ map(prefetch, itertools.chain(consts, jaxpr_literals(jaxpr)))\n+\n# Computations that only produce constants and/or only rearrange their inputs,\n# which are often produced from partial evaluation, don't need compilation,\n# and don't need to evaluate their arguments.\nif not jaxpr.eqns and not always_lower:\nreturn XlaComputation(\n- name, None, True, None, None, jaxpr=jaxpr, consts=consts, device=device,\n- in_avals=abstract_args, out_avals=out_avals,\n+ name, None, True, None, None, None, jaxpr=jaxpr, consts=consts,\n+ device=device, in_avals=abstract_args, out_avals=out_avals,\nhas_unordered_effects=False, ordered_effects=[],\nkept_var_idx=kept_var_idx, keepalive=None)\n@@ -355,10 +370,11 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nordered_effects = [eff for eff in closed_jaxpr.effects\nif eff in core.ordered_effects]\nmodule, keepalive = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, unordered_effects, ordered_effects, backend.platform,\n- mlir.ReplicaAxisContext(axis_env), name_stack, donated_invars)\n+ module_name, closed_jaxpr, unordered_effects, ordered_effects,\n+ backend.platform, mlir.ReplicaAxisContext(axis_env), name_stack,\n+ donated_invars)\nreturn XlaComputation(\n- name, module, False, donated_invars, which_explicit, nreps=nreps,\n+ name, module, False, donated_invars, fun.in_type, out_type, nreps=nreps,\ndevice=device, backend=backend, tuple_args=tuple_args,\nin_avals=abstract_args, out_avals=out_avals,\nhas_unordered_effects=bool(unordered_effects),\n@@ -492,21 +508,24 @@ def aval_to_num_buffers(aval: core.AbstractValue) -> int:\nnum_buffers_handlers[core.AbstractToken] = lambda _: 1\nnum_buffers_handlers[core.ShapedArray] = lambda _: 1\n+num_buffers_handlers[core.DShapedArray] = lambda _: 1\nnum_buffers_handlers[core.ConcreteArray] = lambda _: 1\ndef _input_handler(backend: Backend,\n- which_explicit: Optional[Sequence[bool]],\n- in_avals: Sequence[core.AbstractValue]\n+ in_type: Optional[pe.InputType],\n+ out_type: Optional[pe.OutputType],\n) -> Optional[Callable]:\n- # Extract implicit inputs, and pad bounded-size inputs to their max size.\n+ if in_type is None:\n+ assert out_type is None\n+ return None\n+ in_avals, which_explicit = util.unzip2(in_type)\n+ # Check whether we actually need an input_handler.\nneeds_implicit = which_explicit and not all(which_explicit)\n- needs_padding = any(backend.platform != 'iree' and\n- type(in_avals[d.val]) is core.AbstractBInt # type: ignore\n- for a in in_avals if type(a) is core.DShapedArray\n- for d in a.shape if type(d) is pe.DBIdx)\n+ needs_out_handling = any(type(d) is pe.InDBIdx for a in out_type or []\n+ if type(a) is core.DShapedArray for d in a.shape)\n- if not needs_implicit and not needs_padding:\n+ if not needs_implicit and not needs_out_handling:\nreturn None\nassert config.jax_dynamic_shapes\n@@ -521,43 +540,43 @@ def _input_handler(backend: Backend,\nimplicit_args_from_axes.append((d.val, arg_idx, axis_idx))\nassert {i for i, _, _ in implicit_args_from_axes} == implicit_idxs\n- # Precompute how to pad bounded-size inputs to their max size.\n- def needs_pad(a: core.AbstractValue) -> bool:\n- return (type(a) is core.DShapedArray and\n- any(type(d) is pe.DBIdx for d in aval.shape))\n+ # Precompute which input values are needed for output types.\n+ inputs_needed_for_out_types = out_type and [\n+ d.val for aval in out_type if type(aval) is core.DShapedArray # type: ignore\n+ for d in aval.shape if type(d) is pe.InDBIdx]\n- def padshape(a: core.DShapedArray) -> List[int]:\n- return [in_avals[d.val].bound if type(d) is pe.DBIdx and # type: ignore\n- type(in_avals[d.val]) is core.AbstractBInt else d for d in a.shape] # type: ignore\n-\n- padders = [partial(jax.jit(_pad_arg, static_argnums=0), tuple(padshape(aval))) # type: ignore\n- if needs_pad(aval) else None for aval in in_avals]\n-\n- def elaborate_and_pad(explicit_args):\n+ def elaborate(explicit_args: Sequence[Any]) -> Tuple[Tuple, Optional[Tuple]]:\n+ if needs_implicit:\n+ # Build full argument list, leaving Nones for implicit arguments.\nexplicit_args_ = iter(explicit_args)\nargs = [next(explicit_args_) if ex else None for ex in which_explicit]\nassert next(explicit_args_, None) is None\n- assert needs_implicit\n+ # Populate implicit arguments.\nfor i, j, k in implicit_args_from_axes:\nif args[i] is None:\nargs[i] = args[j].shape[k] # type: ignore\nelse:\nif args[i] != args[j].shape[k]:\nraise Exception(\"inconsistent argument axis sizes for type\")\n- if needs_padding:\n- args = tuple(pad(x) if pad else x for x, pad in zip(args, padders))\n- return args\n- return elaborate_and_pad\n+ else:\n+ args = list(explicit_args)\n+\n+ if needs_out_handling:\n+ # Make a list of inputs needed by output types, leaving unneeded as None.\n+ out_type_env = [None] * len(args)\n+ for i in inputs_needed_for_out_types or []:\n+ out_type_env[i] = args[i]\n+ else:\n+ out_type_env = None # type: ignore\n-def _pad_arg(shape, x):\n- zeros = jax.lax.full(shape, 0, x.dtype)\n- return jax.lax.dynamic_update_slice(zeros, x, (0,) * len(shape))\n+ return tuple(args), out_type_env and tuple(out_type_env) # type: ignore\n+ return elaborate\nif MYPY:\nResultHandler = Any\nelse:\nclass ResultHandler(Protocol):\n- def __call__(self, *args: xla.Buffer) -> Any:\n+ def __call__(self, env: Optional[Sequence[Any]], *args: xla.Buffer) -> Any:\n\"\"\"Boxes raw buffers into their user-facing representation.\"\"\"\ndef aval_to_result_handler(sticky_device: Optional[Device],\n@@ -570,22 +589,33 @@ def aval_to_result_handler(sticky_device: Optional[Device],\ndef array_result_handler(sticky_device: Optional[Device],\naval: core.ShapedArray):\nif aval.dtype is dtypes.float0:\n- return lambda _: np.zeros(aval.shape, dtypes.float0)\n- return partial(device_array.make_device_array, core.raise_to_shaped(aval),\n- sticky_device)\n+ return lambda _, __: np.zeros(aval.shape, dtypes.float0)\n+ aval = core.raise_to_shaped(aval)\n+ handler = lambda _, b: device_array.make_device_array(aval, sticky_device, b)\n+ handler.args = aval, sticky_device # for C++ dispatch path in api.py\n+ return handler\ndef dynamic_array_result_handler(sticky_device: Optional[Device],\naval: core.DShapedArray):\nif aval.dtype is dtypes.float0:\nreturn lambda _: np.zeros(aval.shape, dtypes.float0) # type: ignore\nelse:\n- raise NotImplementedError\n+ return partial(_dynamic_array_result_handler, sticky_device, aval)\n+\n+def _dynamic_array_result_handler(sticky_device, aval, env, buf):\n+ if all(type(d) is int for d in aval.shape):\n+ return device_array.make_device_array(aval, sticky_device, buf)\n+ else:\n+ # TODO(mattjj,dougalm): handle OutDBIdx\n+ shape = [env[d.val] if type(d) is pe.InDBIdx else d for d in aval.shape]\n+ aval = core.ShapedArray(shape, aval.dtype)\n+ return device_array.make_device_array(aval, sticky_device, buf)\nresult_handlers: Dict[\nType[core.AbstractValue],\nCallable[[Optional[Device], Any], ResultHandler]] = {}\n-result_handlers[core.AbstractToken] = lambda _, __: lambda _: core.token\n+result_handlers[core.AbstractToken] = lambda _, __: lambda _, __: core.token\nresult_handlers[core.ShapedArray] = array_result_handler\nresult_handlers[core.DShapedArray] = dynamic_array_result_handler\nresult_handlers[core.ConcreteArray] = array_result_handler\n@@ -632,7 +662,7 @@ def _execute_compiled(name: str, compiled: XlaExecutable,\nordered_effects: List[core.Effect],\nkept_var_idx, *args):\ndevice, = compiled.local_devices()\n- args = input_handler(args) if input_handler else args\n+ args, env = input_handler(args) if input_handler else (args, None)\ninput_bufs_flat = flatten(device_put(x, device) for i, x in enumerate(args)\nif i in kept_var_idx)\nif has_unordered_effects or ordered_effects:\n@@ -640,12 +670,13 @@ def _execute_compiled(name: str, compiled: XlaExecutable,\nhas_unordered_effects, ordered_effects, device, input_bufs_flat)\nout_bufs_flat = compiled.execute(input_bufs_flat)\ncheck_special(name, out_bufs_flat)\n- if output_buffer_counts is None:\n- return (result_handlers[0](*out_bufs_flat),)\n+ if output_buffer_counts is None and not config.jax_dynamic_shapes:\n+ return (result_handlers[0](None, *out_bufs_flat),)\n+ output_buffer_counts = output_buffer_counts or [1] * len(out_bufs_flat)\nout_bufs = unflatten(out_bufs_flat, output_buffer_counts)\nif ordered_effects or has_unordered_effects:\nout_bufs = token_handler(out_bufs)\n- return tuple(h(*bs) for h, bs in unsafe_zip(result_handlers, out_bufs))\n+ return tuple(h(env, *bs) for h, bs in unsafe_zip(result_handlers, out_bufs))\ndef _execute_replicated(name: str, compiled: XlaExecutable,\n@@ -668,9 +699,9 @@ def _execute_replicated(name: str, compiled: XlaExecutable,\nout_bufs_flat = [bufs[0] for bufs in out_bufs_flat_rep]\ncheck_special(name, out_bufs_flat)\nif output_buffer_counts is None:\n- return (result_handlers[0](*out_bufs_flat),)\n+ return (result_handlers[0](None, *out_bufs_flat),)\nout_bufs = unflatten(out_bufs_flat, output_buffer_counts)\n- return tuple(h(*bs) for h, bs in unsafe_zip(result_handlers, out_bufs))\n+ return tuple(h(None, *bs) for h, bs in unsafe_zip(result_handlers, out_bufs))\ndef _execute_trivial(jaxpr, device: Optional[Device], consts, avals, handlers,\n@@ -683,7 +714,7 @@ def _execute_trivial(jaxpr, device: Optional[Device], consts, avals, handlers,\nouts = [xla.canonicalize_dtype(v.val) if type(v) is core.Literal else env[v]\nfor v in jaxpr.outvars]\nreturn [_copy_device_array_to_device(x, device) if device_array.type_is_device_array(x)\n- else h(*device_put(x, device)) for h, x in zip(handlers, outs)]\n+ else h(None, *device_put(x, device)) for h, x in zip(handlers, outs)]\nclass XlaComputation(stages.Computation):\n@@ -694,13 +725,15 @@ class XlaComputation(stages.Computation):\ndef __init__(self, name: str, hlo, is_trivial: bool,\ndonated_invars: Optional[Sequence[bool]],\n- explicit_args: Optional[Sequence[bool]],\n+ in_type: Optional[pe.InputType],\n+ out_type: Optional[pe.OutputType],\n**compile_args):\nself.name = name\nself._hlo = hlo\nself._is_trivial = is_trivial\nself._donated_invars = donated_invars\n- self._explicit_args = explicit_args\n+ self._in_type = in_type\n+ self._out_type = out_type\nself._executable = None\nself.compile_args = compile_args\n@@ -732,7 +765,8 @@ class XlaComputation(stages.Computation):\n**self.compile_args)\nelse:\nself._executable = XlaCompiledComputation.from_xla_computation(\n- self.name, self._hlo, self._explicit_args, **self.compile_args)\n+ self.name, self._hlo, self._in_type, self._out_type,\n+ **self.compile_args)\nreturn self._executable\n@@ -813,7 +847,8 @@ class XlaCompiledComputation(stages.Executable):\ndef from_xla_computation(\nname: str,\nxla_computation: Optional[ir.Module],\n- explicit_args: Optional[Sequence[bool]],\n+ in_type: Optional[pe.InputType],\n+ out_type: Optional[pe.OutputType],\nnreps: int,\ndevice: Optional[Device],\nbackend: Backend,\n@@ -825,9 +860,9 @@ class XlaCompiledComputation(stages.Executable):\nkept_var_idx: Set[int],\nkeepalive: Optional[Any]) -> XlaCompiledComputation:\nsticky_device = device\n- input_handler = _input_handler(backend, explicit_args, in_avals)\n+ input_handler = _input_handler(backend, in_type, out_type)\nresult_handlers = map(partial(aval_to_result_handler, sticky_device),\n- out_avals)\n+ out_type or out_avals)\noptions = xb.get_compile_options(\nnum_replicas=nreps, num_partitions=1,\ndevice_assignment=(sticky_device,) if sticky_device else None)\n@@ -860,9 +895,10 @@ class XlaCompiledComputation(stages.Executable):\nreturn self._xla_executable\n@staticmethod\n- def from_trivial_jaxpr(jaxpr, consts, device, in_avals, out_avals,\n- has_unordered_effects, ordered_effects, kept_var_idx,\n- keepalive: Optional[Any]) -> XlaCompiledComputation:\n+ def from_trivial_jaxpr(\n+ jaxpr, consts, device, in_avals, out_avals, has_unordered_effects,\n+ ordered_effects, kept_var_idx, keepalive: Optional[Any]\n+ ) -> XlaCompiledComputation:\nassert keepalive is None\nresult_handlers = map(partial(aval_to_result_handler, device), out_avals)\nunsafe_call = partial(_execute_trivial, jaxpr, device, consts,\n@@ -969,7 +1005,7 @@ def _device_put_impl(x, device: Optional[Device] = None):\nexcept TypeError as err:\nraise TypeError(\nf\"Argument '{x}' of type {type(x)} is not a valid JAX type\") from err\n- return aval_to_result_handler(device, a)(*device_put(x, device))\n+ return aval_to_result_handler(device, a)(None, *device_put(x, device))\ndevice_put_p = core.Primitive('device_put')\ndevice_put_p.def_impl(_device_put_impl)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -56,7 +56,7 @@ def _update_annotation(\nin_knowns: List[bool]) -> lu.WrappedFun:\nif orig_type is None:\nreturn f\n- return lu.annotate(f, tuple(ty for k, ty in zip(in_knowns, orig_type) if k))\n+ return lu.annotate(f, tuple([ty for k, ty in zip(in_knowns, orig_type) if k]))\nclass PartialVal(tuple):\n\"\"\"Partial value: either a known value or an unknown (abstract) value.\n@@ -1835,28 +1835,6 @@ def trace_to_jaxpr_dynamic(fun: lu.WrappedFun,\ndef trace_to_subjaxpr_dynamic(fun: lu.WrappedFun, main: core.MainTrace,\nin_avals: Sequence[AbstractValue], *,\nkeep_inputs: Optional[Sequence[bool]] = None):\n- # In general, the Tracers passed to ther Python callable underlying `fun` may\n- # correspond to a subset of `in_avals` (i.e. a subset of the input binders in\n- # the jaxpr). For example:\n- #\n- # n = core.DShapedArray((), jnp.dtype('int32'), weak_type=False)\n- # a = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n- # b = core.DShapedArray((n,), jnp.dtype('float32'), weak_type=False)\n- #\n- # @lu.wrap_init\n- # def f(x, y):\n- # return x, y\n- #\n- # jaxpr, _, _ = pe.trace_to_jaxpr_dynamic(f, [n, a, b],\n- # keep_inputs=[False, True, True])\n- # print(jaxpr)\n- # # { lambda ; a:i32[] b:f32[a] c:f32[a]. let in (b, c) }\n- #\n- # The abstract values passed to trace_to_jaxpr_dynamic are in direct\n- # correspondence to the input binders (invars) of the jaxpr it returns. But in\n- # general the Tracers passed to the function f correspond only to a subset of\n- # those abstract values. That's because axis size variables may not be\n- # explicit arguments to f, while we make everything explicit in the jaxpr.\nkeep_inputs = [True] * len(in_avals) if keep_inputs is None else keep_inputs\nframe = JaxprStackFrame()\n@@ -1869,8 +1847,7 @@ def trace_to_subjaxpr_dynamic(fun: lu.WrappedFun, main: core.MainTrace,\njaxpr, consts = frame.to_jaxpr(out_tracers)\ndel fun, main, trace, frame, in_tracers, out_tracers, ans\nif not config.jax_dynamic_shapes:\n- # TODO(frostig,mattjj): check_jaxpr is incomplete under dynamic\n- # shapes; remove this guard when it is\n+ # TODO(frostig,mattjj): update check_jaxpr to handle dynamic shapes\nconfig.jax_enable_checks and core.check_jaxpr(jaxpr)\nreturn jaxpr, [v.aval for v in jaxpr.outvars], consts\n@@ -1899,17 +1876,23 @@ def trace_to_jaxpr_final(fun: lu.WrappedFun,\nAbstractedAxisName = Hashable\n-AbstractedAxesSpec = Union[Dict[int, AbstractedAxisName], Tuple[AbstractedAxisName, ...]]\n+AbstractedAxesSpec = Union[Dict[int, AbstractedAxisName],\n+ Tuple[AbstractedAxisName, ...]]\nclass DBIdx(NamedTuple):\nval: int\n@dataclass(frozen=True)\n-class Bound:\n- name: AbstractedAxisName\n- bound: int\n+class InDBIdx:\n+ val: int\n+\n+@dataclass(frozen=True)\n+class OutDBIdx:\n+ val: int\n+\n+InputType = Tuple[Tuple[AbstractValue, bool], ...] # DBIdx in shapes\n+OutputType = Tuple[AbstractValue, ...] # InDBIdx / OutDBIdx in shapes\n-InputType = Tuple[Tuple[AbstractValue, bool], ...]\ndef infer_lambda_input_type(\naxes_specs: Optional[Sequence[AbstractedAxesSpec]],\n@@ -1981,9 +1964,6 @@ def _collect_implicit(\nreturn idxs, implicit_names\ndef _implicit_arg_type(name: AbstractedAxisName) -> AbstractValue:\n- if type(name) is Bound:\n- return AbstractBInt(name.bound)\n- else:\nreturn ShapedArray((), dtypes.dtype('int32'))\ndef _arg_type(\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -8483,13 +8483,9 @@ class DynamicShapeTest(jtu.JaxTestCase):\n@unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\ndef test_jit_basic_iree(self):\n- if not jtu.device_under_test() == 'iree':\n- raise unittest.SkipTest(\"test only works on IREE\")\n-\n@jax.jit\ndef f(i):\nreturn jnp.sum(jnp.ones(i, dtype='float32'))\n-\nself.assertAllClose(f(3), jnp.array(3., dtype='float32'), check_dtypes=True)\n@unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n@@ -8508,10 +8504,21 @@ class DynamicShapeTest(jtu.JaxTestCase):\nself.assertAllClose(y, 6., check_dtypes=False)\nself.assertEqual(count, 1)\n- # TODO(mattjj,dougalm,phawkins): debug iree failure, \"'arith.subi' op requires\n- # the same type for all operands and results\"\n- # https://github.com/google/iree/issues/8881\n- @jtu.skip_on_devices('iree')\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_jit_polymorphic_output_iree(self):\n+ # like test_jit_basic_iree, but without the jnp.sum!\n+ count = 0\n+\n+ @jax.jit\n+ def f(i):\n+ nonlocal count\n+ count += 1\n+ return jnp.ones(i, dtype='float32')\n+\n+ self.assertAllClose(f(3), jnp.ones(3, dtype='float32'), check_dtypes=True)\n+ self.assertAllClose(f(4), jnp.ones(4, dtype='float32'), check_dtypes=True)\n+ self.assertEqual(count, 1)\n+\ndef test_slicing_basic(self):\nf = jax.jit(lambda x, n: jnp.sum(x[:n]))\nans = f(jnp.arange(10), 3)\n" }, { "change_type": "MODIFY", "old_path": "tests/custom_object_test.py", "new_path": "tests/custom_object_test.py", "diff": "@@ -108,7 +108,7 @@ class ConcreteSparseArray(AbstractSparseArray):\npass\ndef sparse_array_result_handler(device, aval):\n- def build_sparse_array(data_buf, indices_buf):\n+ def build_sparse_array(_, data_buf, indices_buf):\ndata = device_array.make_device_array(aval.data_aval, device, data_buf)\nindices = device_array.make_device_array(aval.indices_aval, device, indices_buf)\nreturn SparseArray(aval, data, indices)\n" } ]
Python
Apache License 2.0
google/jax
add support for lambda-bound dynamic shape output (iree only) Co-authored-by: Dougal Maclaurin <dougalm@google.com>
260,510
19.05.2022 10:15:15
25,200
94e719935bd96e6417817c32c004e15d7e58a37d
Make `Effect` a hashable type
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -54,7 +54,7 @@ map, unsafe_map = safe_map, map\n# -------------------- jaxprs --------------------\n-Effect = Any\n+Effect = Hashable\nEffects = Set[Effect]\nno_effects: Effects = set()\n@@ -114,7 +114,7 @@ class Jaxpr:\nreturn Jaxpr(constvars=constvars, invars=invars, outvars=outvars, eqns=eqns,\neffects=effects)\n-def join_effects(*effects: Effect) -> Effects:\n+def join_effects(*effects: Effects) -> Effects:\nreturn set.union(*effects) if effects else no_effects\ndef jaxprs_in_params(params) -> Iterator[Jaxpr]:\n" } ]
Python
Apache License 2.0
google/jax
Make `Effect` a hashable type
260,625
19.05.2022 16:35:07
14,400
c128876b34b45683bbbecb88fd3f2d9c38e7e521
incorrect link in dpsgd example
[ { "change_type": "MODIFY", "old_path": "examples/differentially_private_sgd.py", "new_path": "examples/differentially_private_sgd.py", "diff": "@@ -30,7 +30,7 @@ This code depends on tensorflow_privacy (https://github.com/tensorflow/privacy)\n$ pip install .\nThe results match those in the reference TensorFlow baseline implementation:\n- https://github.com/tensorflow/privacy/tree/main/tutorials\n+ https://github.com/tensorflow/privacy/tree/master/tutorials\nExample invocations:\n# this non-private baseline should get ~99% acc\n" } ]
Python
Apache License 2.0
google/jax
incorrect link in dpsgd example
260,447
19.05.2022 14:28:29
25,200
1656b33ca93d73eb90cde3f9f0ad217f941821be
[sparse] Track `indices_sorted` in sparsify transform.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcoo.py", "new_path": "jax/experimental/sparse/bcoo.py", "diff": "@@ -100,7 +100,7 @@ def _bcoo_set_nse(mat, nse):\nindices = jnp.zeros_like(mat.indices, shape=(*mat.indices.shape[:-2], nse, mat.indices.shape[-1]))\nindices = indices.at[..., :mat.nse, :].set(mat.indices)\nindices = indices.at[..., mat.nse:, :].set(jnp.array(mat.shape[mat.n_batch:mat.n_batch + mat.n_sparse]))\n- return BCOO((data, indices), shape=mat.shape, indices_sorted=mat._indices_sorted)\n+ return BCOO((data, indices), shape=mat.shape, indices_sorted=mat.indices_sorted)\n# TODO(jakevdp) this can be problematic when used with autodiff; see\n# https://github.com/google/jax/issues/10163. Should this be a primitive?\n@@ -1385,7 +1385,7 @@ def _bcoo_sum_duplicates_unbatched(indices, *, shape):\nfill_value = jnp.expand_dims(jnp.array(shape[:props.n_sparse], dtype=indices.dtype), (0,))\nout_of_bounds = (indices >= fill_value).any(-1, keepdims=True)\nindices = jnp.where(out_of_bounds, fill_value, indices)\n- # TODO: check if `_indices_sorted` is True.\n+ # TODO: check if `indices_sorted` is True.\nindices_unique, inv_idx, nse = _unique(\nindices, axis=0, return_inverse=True, return_true_size=True,\nsize=props.nse, fill_value=fill_value)\n@@ -2042,15 +2042,15 @@ class BCOO(JAXSparse):\nn_batch = property(lambda self: self.indices.ndim - 2)\nn_sparse = property(lambda self: self.indices.shape[-1])\nn_dense = property(lambda self: self.data.ndim - 1 - self.n_batch)\n- _info = property(lambda self: BCOOInfo(self.shape, self._indices_sorted))\n+ indices_sorted: bool\n+ _info = property(lambda self: BCOOInfo(self.shape, self.indices_sorted))\n_bufs = property(lambda self: (self.data, self.indices))\n- _indices_sorted: bool\ndef __init__(self, args, *, shape, indices_sorted=False):\n# JAX transforms will sometimes instantiate pytrees with null values, so we\n# must catch that in the initialization of inputs.\nself.data, self.indices = _safe_asarray(args)\n- self._indices_sorted = indices_sorted\n+ self.indices_sorted = indices_sorted\nsuper().__init__(args, shape=shape)\ndef __repr__(self):\n@@ -2175,7 +2175,7 @@ class BCOO(JAXSparse):\nsparse_perm = [p - self.n_batch\nfor p in axes[self.n_batch: self.n_batch + self.n_sparse]]\nif tuple(sparse_perm) == tuple(range(self.n_sparse)):\n- is_sorted = self._indices_sorted\n+ is_sorted = self.indices_sorted\nelse:\n# TODO: address the corner cases that the transposed indices are sorted.\n# possibly use permutation?\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/transform.py", "new_path": "jax/experimental/sparse/transform.py", "diff": "@@ -62,6 +62,7 @@ from jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\nfrom jax.tree_util import tree_flatten, tree_map, tree_unflatten\nfrom jax.util import safe_map, safe_zip, split_list\n+from jax._src.config import config\nfrom jax._src.lax.control_flow import _check_tree_and_avals\nfrom jax._src.numpy import lax_numpy\nfrom jax._src.util import canonicalize_axis\n@@ -153,7 +154,7 @@ class SparsifyEnv:\nreturn SparsifyValue(np.shape(data), self._push(data), None)\ndef sparse(self, shape, data=None, indices=None,\n- *, data_ref=None, indices_ref=None):\n+ *, data_ref=None, indices_ref=None, indices_sorted=False):\n\"\"\"Add a new sparse array to the sparsify environment.\"\"\"\nif data is not None:\nassert data_ref is None\n@@ -167,13 +168,14 @@ class SparsifyEnv:\nelse:\nassert indices_ref is not None and indices_ref < len(self._buffers)\n- return SparsifyValue(shape, data_ref, indices_ref)\n+ return SparsifyValue(shape, data_ref, indices_ref, indices_sorted)\nclass SparsifyValue(NamedTuple):\nshape: Tuple[int, ...]\ndata_ref: Optional[int]\nindices_ref: Optional[int]\n+ indices_sorted: Optional[bool] = False\n@property\ndef ndim(self):\n@@ -194,7 +196,8 @@ def arrays_to_spvalues(\n\"\"\"Convert a pytree of (sparse) arrays to an equivalent pytree of spvalues.\"\"\"\ndef array_to_spvalue(arg):\nif isinstance(arg, BCOO):\n- return spenv.sparse(arg.shape, arg.data, arg.indices)\n+ return spenv.sparse(arg.shape, arg.data, arg.indices,\n+ indices_sorted=arg.indices_sorted)\nelse:\nreturn spenv.dense(arg)\nreturn tree_map(array_to_spvalue, args, is_leaf=_is_bcoo)\n@@ -208,7 +211,8 @@ def spvalues_to_arrays(\ndef spvalue_to_array(spvalue):\nif spvalue.is_sparse():\nassert spvalue.indices_ref is not None\n- return BCOO((spenv.data(spvalue), spenv.indices(spvalue)), shape=spvalue.shape)\n+ return BCOO((spenv.data(spvalue), spenv.indices(spvalue)),\n+ shape=spvalue.shape, indices_sorted=spvalue.indices_sorted)\nelse:\nreturn spenv.data(spvalue)\nreturn tree_map(spvalue_to_array, spvalues, is_leaf=_is_spvalue)\n@@ -471,7 +475,8 @@ def _transpose_sparse(spenv, *spvalues, permutation):\npermutation = tuple(permutation)\nargs = spvalues_to_arrays(spenv, spvalues)\nshape = args[0].shape\n- mat = sparse.BCOO((args[0].data, args[0].indices), shape=shape)\n+ mat = sparse.BCOO((args[0].data, args[0].indices), shape=shape,\n+ indices_sorted=args[0].indices_sorted)\nmat_transposed = sparse.bcoo_transpose(mat, permutation=permutation)\nout_shape = tuple(shape[i] for i in permutation)\n@@ -494,6 +499,7 @@ def _transpose_sparse(spenv, *spvalues, permutation):\nelse:\nkwds['indices'] = mat_transposed.indices\n+ kwds['indices_sorted'] = mat_transposed.indices_sorted\nspvalue = spenv.sparse(out_shape, **kwds)\nreturn (spvalue,)\n@@ -506,7 +512,10 @@ def _add_sparse(spenv, *spvalues):\nraise NotImplementedError(\"Addition between sparse matrices of different shapes.\")\nif X.indices_ref == Y.indices_ref:\nout_data = lax.add(spenv.data(X), spenv.data(Y))\n- out_spvalue = spenv.sparse(X.shape, out_data, indices_ref=X.indices_ref)\n+ if config.jax_enable_checks:\n+ assert X.indices_sorted == Y.indices_sorted\n+ out_spvalue = spenv.sparse(X.shape, out_data, indices_ref=X.indices_ref,\n+ indices_sorted=X.indices_sorted)\nelif spenv.indices(X).ndim != spenv.indices(Y).ndim or spenv.data(X).ndim != spenv.data(Y).ndim:\nraise NotImplementedError(\"Addition between sparse matrices with different batch/dense dimensions.\")\nelse:\n@@ -535,7 +544,10 @@ def _mul_sparse(spenv, *spvalues):\nif X.indices_ref == Y.indices_ref:\n# TODO(jakevdp): this is inaccurate if there are duplicate indices\nout_data = lax.mul(spenv.data(X), spenv.data(Y))\n- out_spvalue = spenv.sparse(X.shape, out_data, indices_ref=X.indices_ref)\n+ if config.jax_enable_checks:\n+ assert X.indices_sorted == Y.indices_sorted\n+ out_spvalue = spenv.sparse(X.shape, out_data, indices_ref=X.indices_ref,\n+ indices_sorted=X.indices_sorted)\nelse:\nX_promoted, Y_promoted = spvalues_to_arrays(spenv, spvalues)\nmat = bcoo_multiply_sparse(X_promoted, Y_promoted)\n@@ -545,7 +557,8 @@ def _mul_sparse(spenv, *spvalues):\nX, Y = Y, X\nX_promoted = spvalues_to_arrays(spenv, X)\nout_data = bcoo_multiply_dense(X_promoted, spenv.data(Y))\n- out_spvalue = spenv.sparse(X.shape, out_data, indices_ref=X.indices_ref)\n+ out_spvalue = spenv.sparse(X.shape, out_data, indices_ref=X.indices_ref,\n+ indices_sorted=X.indices_sorted)\nreturn (out_spvalue,)\n@@ -716,7 +729,9 @@ sparse_rules[lax.cond_p] = _cond_sparse\ndef _todense_sparse_rule(spenv, spvalue, *, tree):\ndel tree # TODO(jakvdp): we should assert that tree is PytreeDef(*)\n- out = sparse.BCOO((spenv.data(spvalue), spenv.indices(spvalue)), shape=spvalue.shape).todense()\n+ out = sparse.BCOO((spenv.data(spvalue), spenv.indices(spvalue)),\n+ shape=spvalue.shape,\n+ indices_sorted=spvalue.indices_sorted).todense()\nreturn (spenv.dense(out),)\nsparse_rules[sparse.todense_p] = _todense_sparse_rule\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -954,11 +954,11 @@ class BCOOTest(jtu.JaxTestCase):\npermutations = (1, 0, 2, 3, 4, 6, 5)\nmat_T_indices_sorted = mat.transpose(axes=permutations)\n- self.assertTrue(mat_T_indices_sorted._indices_sorted)\n+ self.assertTrue(mat_T_indices_sorted.indices_sorted)\npermutations = (0, 1, 3, 2, 4, 5, 6)\nmat_T_indices_unsorted = mat.transpose(axes=permutations)\n- self.assertFalse(mat_T_indices_unsorted._indices_sorted)\n+ self.assertFalse(mat_T_indices_unsorted.indices_sorted)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_nbatch={}_ndense={}\".format(\n" }, { "change_type": "MODIFY", "old_path": "tests/sparsify_test.py", "new_path": "tests/sparsify_test.py", "diff": "@@ -26,7 +26,6 @@ import jax._src.test_util as jtu\nfrom jax.experimental.sparse import BCOO, sparsify, todense, SparseTracer\nfrom jax.experimental.sparse.transform import (\narrays_to_spvalues, spvalues_to_arrays, sparsify_raw, SparsifyValue, SparsifyEnv)\n-from jax.experimental.sparse.util import CuSparseEfficiencyWarning\nconfig.parse_flags_with_absl()\n@@ -73,7 +72,9 @@ class SparsifyTest(jtu.JaxTestCase):\nself.assertEqual(len(spvalues), len(args))\nself.assertLen(spenv._buffers, 5)\nself.assertEqual(spvalues,\n- (SparsifyValue(X.shape, 0, None), SparsifyValue(X.shape, 1, 2), SparsifyValue(X.shape, 3, 4)))\n+ (SparsifyValue(X.shape, 0, None, False),\n+ SparsifyValue(X.shape, 1, 2, True),\n+ SparsifyValue(X.shape, 3, 4, True)))\nargs_out = spvalues_to_arrays(spenv, spvalues)\nself.assertEqual(len(args_out), len(args))\n@@ -120,9 +121,6 @@ class SparsifyTest(jtu.JaxTestCase):\ndef func(x, v):\nreturn -jnp.sin(jnp.pi * x).T @ (v + 1)\n- with jtu.ignore_warning(\n- category=CuSparseEfficiencyWarning,\n- message=\"bcoo_dot_general GPU lowering requires matrices with sorted indices*\"):\nresult_sparse = func(M_sparse, v)\nresult_dense = func(M_dense, v)\nself.assertAllClose(result_sparse, result_dense)\n@@ -149,17 +147,11 @@ class SparsifyTest(jtu.JaxTestCase):\nfunc = self.sparsify(operator.matmul)\n# dot_general\n- with jtu.ignore_warning(\n- category=CuSparseEfficiencyWarning,\n- message=\"bcoo_dot_general GPU lowering requires matrices with sorted indices*\"):\nresult_sparse = func(Xsp, Y)\nresult_dense = operator.matmul(X, Y)\nself.assertAllClose(result_sparse, result_dense)\n# rdot_general\n- with jtu.ignore_warning(\n- category=CuSparseEfficiencyWarning,\n- message=\"bcoo_dot_general GPU lowering requires matrices with sorted indices*\"):\nresult_sparse = func(Y, Xsp)\nresult_dense = operator.matmul(Y, X)\nself.assertAllClose(result_sparse, result_dense)\n@@ -439,9 +431,6 @@ class SparsifyTest(jtu.JaxTestCase):\nM_bcoo = BCOO.fromdense(M)\nresult_dense = func(M, x)\n- with jtu.ignore_warning(\n- category=CuSparseEfficiencyWarning,\n- message=\"bcoo_dot_general GPU lowering requires matrices with sorted indices*\"):\nresult_sparse = self.sparsify(func)(M_bcoo, x)\nself.assertArraysAllClose(result_dense, result_sparse)\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Track `indices_sorted` in sparsify transform. PiperOrigin-RevId: 449833669
260,335
24.05.2022 15:01:00
25,200
762f359772994af5aaa0bf50d190e79d062b32b5
remove old pjit comment
[ { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -818,8 +818,6 @@ def _pjit_partial_eval(trace, *in_tracers,\njaxpr, in_axis_resources, out_axis_resources,\nresource_env, donated_invars, name, in_positional_semantics,\nout_positional_semantics):\n- # XXX: At the moment all residuals get fully replicated, which is extremely\n- # wasteful and might quickly lead to OOM errors.\nmesh = resource_env.physical_mesh\nin_pvals = [t.pval for t in in_tracers]\n" } ]
Python
Apache License 2.0
google/jax
remove old pjit comment
260,424
25.05.2022 15:01:35
-3,600
f8f5a5dca34a817ca25938b578c7ff01997c959b
Add notes in buffer donation FAQ about key-word args limitation.
[ { "change_type": "MODIFY", "old_path": "docs/faq.rst", "new_path": "docs/faq.rst", "diff": "@@ -578,12 +578,22 @@ Buffer donation\n(This feature is implemented only for TPU and GPU.)\n-When JAX executes a computation it reserves buffers on the device for all inputs and outputs.\n+When JAX executes a computation it uses buffers on the device for all inputs and outputs.\nIf you know than one of the inputs is not needed after the computation, and if it\nmatches the shape and element type of one of the outputs, you can specify that you\nwant the corresponding input buffer to be donated to hold an output. This will reduce\nthe memory required for the execution by the size of the donated buffer.\n+If you have something like the following pattern, you can use buffer donation::\n+\n+ params, state = jax.pmap(update_fn, donate_argnums=(0, 1))(params, state)\n+\n+You can think of this as a way to do a memory-efficient functional update\n+on your immutable JAX arrays. Within the boundaries of a computation XLA can\n+make this optimization for you, but at the jit/pmap boundary you need to\n+guarantee to XLA that you will not use the donated input buffer after calling\n+the donating function.\n+\nYou achieve this by using the `donate_argnums` parameter to the functions :func:`jax.jit`,\n:func:`jax.pjit`, and :func:`jax.pmap`. This parameter is a sequence of indices (0 based) into\nthe positional argument list::\n@@ -597,6 +607,11 @@ the positional argument list::\n# the same shape and type as `y`, so it will share its buffer.\nz = jax.jit(add, donate_argnums=(1,))(x, y)\n+Note that this currently does not work when calling your function with key-word arguments!\n+The following code will not donate any buffers::\n+\n+ params, state = jax.pmap(update_fn, donate_argnums=(0, 1))(params=params, state=state)\n+\nIf an argument whose buffer is donated is a pytree, then all the buffers\nfor its components are donated::\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -221,7 +221,6 @@ def _infer_argnums_and_argnames(\nreturn argnums, argnames\n-\ndef jit(\nfun: Callable,\n*,\n@@ -277,15 +276,19 @@ def jit(\nbackend: This is an experimental feature and the API is likely to change.\nOptional, a string representing the XLA backend: ``'cpu'``, ``'gpu'``, or\n``'tpu'``.\n- donate_argnums: Specify which argument buffers are \"donated\" to the computation.\n- It is safe to donate argument buffers if you no longer need them once the\n- computation has finished. In some cases XLA can make use of donated\n- buffers to reduce the amount of memory needed to perform a computation,\n- for example recycling one of your input buffers to store a result. You\n- should not reuse buffers that you donate to a computation, JAX will raise\n- an error if you try to. By default, no argument buffers are donated.\n-\n- For more details on buffer donation see the [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\n+ donate_argnums: Specify which positional argument buffers are \"donated\" to\n+ the computation. It is safe to donate argument buffers if you no longer\n+ need them once the computation has finished. In some cases XLA can make\n+ use of donated buffers to reduce the amount of memory needed to perform a\n+ computation, for example recycling one of your input buffers to store a\n+ result. You should not reuse buffers that you donate to a computation, JAX\n+ will raise an error if you try to. By default, no argument buffers are\n+ donated.\n+ Note that donate_argnums only work for positional arguments, and keyword\n+ arguments will not be donated.\n+\n+ For more details on buffer donation see the\n+ [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\ninline: Specify whether this function should be inlined into enclosing\njaxprs (rather than being represented as an application of the xla_call\n@@ -1674,15 +1677,18 @@ def pmap(\nbackend: This is an experimental feature and the API is likely to change.\nOptional, a string representing the XLA backend. 'cpu', 'gpu', or 'tpu'.\naxis_size: Optional; the size of the mapped axis.\n- donate_argnums: Specify which argument buffers are \"donated\" to the computation.\n- It is safe to donate argument buffers if you no longer need them once the\n- computation has finished. In some cases XLA can make use of donated\n- buffers to reduce the amount of memory needed to perform a computation,\n- for example recycling one of your input buffers to store a result. You\n- should not reuse buffers that you donate to a computation, JAX will raise\n- an error if you try to.\n-\n- For more details on buffer donation see the [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\n+ donate_argnums: Specify which positional argument buffers are \"donated\" to\n+ the computation. It is safe to donate argument buffers if you no longer need\n+ them once the computation has finished. In some cases XLA can make use of\n+ donated buffers to reduce the amount of memory needed to perform a\n+ computation, for example recycling one of your input buffers to store a\n+ result. You should not reuse buffers that you donate to a computation, JAX\n+ will raise an error if you try to.\n+ Note that donate_argnums only work for positional arguments, and keyword\n+ arguments will not be donated.\n+\n+ For more details on buffer donation see the\n+ [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\nglobal_arg_shapes: Optional, must be set when using pmap(sharded_jit) and\nthe partitioned values span multiple processes. The global cross-process\n" } ]
Python
Apache License 2.0
google/jax
Add notes in buffer donation FAQ about key-word args limitation.
260,447
25.05.2022 21:06:52
25,200
b6d4c59e64976216b427ee53dd72bff5052445ac
[sparse] Trace BCOO `indices_sorted` in sparsifying zero_preserving_unary_ops.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/transform.py", "new_path": "jax/experimental/sparse/transform.py", "diff": "@@ -453,7 +453,12 @@ def _zero_preserving_unary_op(prim):\nassert len(spvalues) == 1\nbuf = spenv.data(spvalues[0])\nbuf_out = prim.bind(buf, **kwargs)\n- out_spvalue = spenv.sparse(spvalues[0].shape, buf_out, indices_ref=spvalues[0].indices_ref)\n+ if spvalues[0].is_sparse():\n+ out_spvalue = spenv.sparse(spvalues[0].shape, buf_out,\n+ indices_ref=spvalues[0].indices_ref,\n+ indices_sorted=spvalues[0].indices_sorted)\n+ else:\n+ out_spvalue = spenv.dense(buf)\nreturn (out_spvalue,)\nreturn func\n" }, { "change_type": "MODIFY", "old_path": "tests/sparsify_test.py", "new_path": "tests/sparsify_test.py", "diff": "@@ -26,6 +26,7 @@ import jax._src.test_util as jtu\nfrom jax.experimental.sparse import BCOO, sparsify, todense, SparseTracer\nfrom jax.experimental.sparse.transform import (\narrays_to_spvalues, spvalues_to_arrays, sparsify_raw, SparsifyValue, SparsifyEnv)\n+from jax.experimental.sparse.util import CuSparseEfficiencyWarning\nconfig.parse_flags_with_absl()\n@@ -121,6 +122,9 @@ class SparsifyTest(jtu.JaxTestCase):\ndef func(x, v):\nreturn -jnp.sin(jnp.pi * x).T @ (v + 1)\n+ with jtu.ignore_warning(\n+ category=CuSparseEfficiencyWarning,\n+ message=\"bcoo_dot_general GPU lowering requires matrices with sorted indices*\"):\nresult_sparse = func(M_sparse, v)\nresult_dense = func(M_dense, v)\nself.assertAllClose(result_sparse, result_dense)\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Trace BCOO `indices_sorted` in sparsifying zero_preserving_unary_ops. PiperOrigin-RevId: 451081409
260,335
19.05.2022 16:23:06
25,200
9b724647d169a73ffae08610741676cb9b182d26
[djax] add support for dynamic-shape outputs
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -529,7 +529,9 @@ def _cpp_jit(\n# Not supported: ShardedDeviceArray\nall(device_array.type_is_device_array(x) for x in out_flat) and\n# Not supported: dynamic shapes\n- not jax.config.jax_dynamic_shapes)\n+ not jax.config.jax_dynamic_shapes and\n+ execute.args[4] is dispatch.SimpleResultHandler\n+ )\n### If we can use the fastpath, we return required info to the caller.\nif use_fastpath:\n(_, xla_executable,\n@@ -2663,14 +2665,16 @@ def make_jaxpr(fun: Callable,\ndyn_argnums = [i for i in range(len(args)) if i not in static_argnums]\nf, args = argnums_partial(f, dyn_argnums, args)\nin_avals, in_tree, keep_inputs = abstractify(args, kwargs)\n+ in_type = tuple(zip(in_avals, keep_inputs))\nf, out_tree = flatten_fun(f, in_tree)\n+ f = lu.annotate(f, in_type)\nwith ExitStack() as stack:\nfor axis_name, size in axis_env or []:\nstack.enter_context(core.extend_axis_env(axis_name, size, None))\n- jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(\n- f, in_avals, keep_inputs=keep_inputs)\n+ jaxpr, out_type, consts = pe.trace_to_jaxpr_dynamic2(f)\nclosed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\nif return_shape:\n+ out_avals, _ = unzip2(out_type)\nout_shapes_flat = [\nShapeDtypeStruct(a.shape, a.dtype, a.named_shape) for a in out_avals]\nreturn closed_jaxpr, tree_unflatten(out_tree(), out_shapes_flat)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -192,8 +192,6 @@ def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name,\ndonated_invars, inline, keep_unused: bool):\ndel inline # Only used at tracing time\narg_specs = unsafe_map(arg_spec, args)\n- if fun.in_type is not None:\n- arg_specs = [(None, *xs) for _, *xs in arg_specs]\ncompiled_fun = _xla_callable(fun, device, backend, name, donated_invars,\nkeep_unused, *arg_specs)\ntry:\n@@ -279,28 +277,24 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nraise ValueError(\"can't specify both a device and a backend for jit, \"\n\"got device={} and backend={}\".format(device, backend))\nabstract_args, arg_devices = util.unzip2(arg_specs)\n- if fun.in_type is not None:\n- abstract_args, which_explicit = util.unzip2(fun.in_type)\n+ if fun.in_type is None:\n+ # Add an annotation inferred from the arguments; no dynamic axes here.\n+ in_type = tuple(unsafe_zip(abstract_args, itertools.repeat(True)))\n+ fun = lu.annotate(fun, in_type)\nelse:\n- which_explicit = None\n+ assert all(map(core.typematch, abstract_args,\n+ [a for a, k in fun.in_type if k]))\nwith log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n\"for jit in {elapsed_time} sec\"):\n- jaxpr, out_avals, consts = pe.trace_to_jaxpr_final(\n- fun, abstract_args, pe.debug_info_final(fun, \"jit\"), which_explicit)\n+ jaxpr, out_type, consts = pe.trace_to_jaxpr_final2(\n+ fun, pe.debug_info_final(fun, \"jit\"))\n+ out_avals, kept_outputs = util.unzip2(out_type)\nif any(isinstance(c, core.Tracer) for c in consts):\nraise UnexpectedTracerError(\"Encountered an unexpected tracer.\")\n- if config.jax_dynamic_shapes and fun.in_type is not None:\n- # TODO(mattjj): maybe move this into trace_to_subjaxpr_dynamic\n- # TODO(mattjj,dougalm): out_type and out_avals are redundant, simplify!\n- out_type = tuple([aval.update(shape=tuple(pe.InDBIdx(jaxpr.invars.index(d))\n- if type(d) is core.Var\n- else d for d in aval.shape))\n- for aval in out_avals])\n+ if config.jax_dynamic_shapes:\nkeep_unused = True\nelse:\n- out_type = None\n- # TODO(mattjj): handle host_callback w/ dyn shapes, or wait for replacement\njaxpr = apply_outfeed_rewriter(jaxpr)\nif not keep_unused:\n@@ -327,7 +321,7 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\n# Computations that only produce constants and/or only rearrange their inputs,\n# which are often produced from partial evaluation, don't need compilation,\n# and don't need to evaluate their arguments.\n- if not jaxpr.eqns and not always_lower:\n+ if not jaxpr.eqns and not always_lower and all(kept_outputs):\nreturn XlaComputation(\nname, None, True, None, None, None, jaxpr=jaxpr, consts=consts,\ndevice=device, in_avals=abstract_args, out_avals=out_avals,\n@@ -574,6 +568,31 @@ def _input_handler(backend: Backend,\nreturn tuple(args), out_type_env and tuple(out_type_env) # type: ignore\nreturn elaborate\n+def _result_handler(backend: Backend,\n+ sticky_device: Optional[Device],\n+ out_type: Optional[pe.OutputType]\n+ ) -> Callable:\n+ out_avals, kept_outputs = util.unzip2(out_type)\n+ handlers = map(partial(aval_to_result_handler, sticky_device), out_avals)\n+ if out_type is None:\n+ return SimpleResultHandler(handlers)\n+\n+ def result_handler(input_env, lists_of_bufs):\n+ results = []\n+ for handler, bufs in unsafe_zip(handlers, lists_of_bufs):\n+ results.append(handler((input_env, results), *bufs))\n+ return [r for r, keep in unsafe_zip(results, kept_outputs) if keep]\n+ return result_handler\n+\n+class SimpleResultHandler:\n+ handlers: Sequence[ResultHandler]\n+ def __init__(self, handlers): self.handlers = handlers\n+ def __iter__(self): return iter(self.handlers)\n+ def __len__(self): return len(self.handlers)\n+ def __call__(self, env, lists_of_bufs):\n+ return tuple(h(env, *bs) for h, bs in zip(self.handlers, lists_of_bufs))\n+\n+\nif MYPY:\nResultHandler = Any\nelse:\n@@ -606,11 +625,14 @@ def dynamic_array_result_handler(sticky_device: Optional[Device],\ndef _dynamic_array_result_handler(sticky_device, aval, env, buf):\nif all(type(d) is int for d in aval.shape):\n+ del env\nreturn device_array.make_device_array(aval, sticky_device, buf)\nelse:\n- # TODO(mattjj,dougalm): handle OutDBIdx\n- shape = [env[d.val] if type(d) is pe.InDBIdx else d for d in aval.shape]\n- aval = core.ShapedArray(shape, aval.dtype)\n+ assert env is not None\n+ in_env, out_env = env\n+ shape = [in_env[d.val] if type(d) is pe.InDBIdx else\n+ out_env[d.val] if type(d) is pe.OutDBIdx else d for d in aval.shape]\n+ aval = core.ShapedArray(tuple(shape), aval.dtype)\nreturn device_array.make_device_array(aval, sticky_device, buf)\n@@ -658,33 +680,30 @@ def _add_tokens(has_unordered_effects: bool, ordered_effects: List[core.Effect],\ndef _execute_compiled(name: str, compiled: XlaExecutable,\ninput_handler: Optional[Callable],\n- output_buffer_counts: Optional[Sequence[int]],\n- result_handlers,\n+ output_buffer_counts: Sequence[int],\n+ result_handler: Callable,\nhas_unordered_effects: bool,\nordered_effects: List[core.Effect],\nkept_var_idx, *args):\ndevice, = compiled.local_devices()\nargs, env = input_handler(args) if input_handler else (args, None)\n- input_bufs_flat = flatten(device_put(x, device) for i, x in enumerate(args)\n+ in_flat = flatten(device_put(x, device) for i, x in enumerate(args)\nif i in kept_var_idx)\nif has_unordered_effects or ordered_effects:\n- input_bufs_flat, token_handler = _add_tokens(\n- has_unordered_effects, ordered_effects, device, input_bufs_flat)\n- out_bufs_flat = compiled.execute(input_bufs_flat)\n- check_special(name, out_bufs_flat)\n- if output_buffer_counts is None and not config.jax_dynamic_shapes:\n- return (result_handlers[0](None, *out_bufs_flat),)\n- output_buffer_counts = output_buffer_counts or [1] * len(out_bufs_flat)\n- out_bufs = unflatten(out_bufs_flat, output_buffer_counts)\n+ in_flat, token_handler = _add_tokens(has_unordered_effects, ordered_effects,\n+ device, in_flat)\n+ out_flat = compiled.execute(in_flat)\n+ check_special(name, out_flat)\n+ out_bufs = unflatten(out_flat, output_buffer_counts)\nif ordered_effects or has_unordered_effects:\nout_bufs = token_handler(out_bufs)\n- return tuple(h(env, *bs) for h, bs in unsafe_zip(result_handlers, out_bufs))\n+ return result_handler(env, out_bufs)\ndef _execute_replicated(name: str, compiled: XlaExecutable,\ninput_handler: Optional[Callable],\n- output_buffer_counts: Optional[Sequence[int]],\n- result_handlers,\n+ output_buffer_counts: Sequence[int],\n+ result_handler: Callable,\nhas_unordered_effects: bool,\nordered_effects: List[core.Effect],\nkept_var_idx, *args):\n@@ -698,12 +717,10 @@ def _execute_replicated(name: str, compiled: XlaExecutable,\nfor device in compiled.local_devices()]\ninput_bufs_flip = list(unsafe_zip(*input_bufs))\nout_bufs_flat_rep = compiled.execute_sharded_on_local_devices(input_bufs_flip)\n- out_bufs_flat = [bufs[0] for bufs in out_bufs_flat_rep]\n- check_special(name, out_bufs_flat)\n- if output_buffer_counts is None:\n- return (result_handlers[0](None, *out_bufs_flat),)\n- out_bufs = unflatten(out_bufs_flat, output_buffer_counts)\n- return tuple(h(None, *bs) for h, bs in unsafe_zip(result_handlers, out_bufs))\n+ out_flat = [bufs[0] for bufs in out_bufs_flat_rep]\n+ check_special(name, out_flat)\n+ out_bufs = unflatten(out_flat, output_buffer_counts)\n+ return result_handler(None, out_bufs)\ndef _execute_trivial(jaxpr, device: Optional[Device], consts, avals, handlers,\n@@ -863,8 +880,7 @@ class XlaCompiledComputation(stages.Executable):\nkeepalive: Optional[Any]) -> XlaCompiledComputation:\nsticky_device = device\ninput_handler = _input_handler(backend, in_type, out_type)\n- result_handlers = map(partial(aval_to_result_handler, sticky_device),\n- out_type or out_avals)\n+ result_handler = _result_handler(backend, sticky_device, out_type)\noptions = xb.get_compile_options(\nnum_replicas=nreps, num_partitions=1,\ndevice_assignment=(sticky_device,) if sticky_device else None)\n@@ -872,16 +888,13 @@ class XlaCompiledComputation(stages.Executable):\nwith log_elapsed_time(f\"Finished XLA compilation of {name} \"\n\"in {elapsed_time} sec\"):\ncompiled = compile_or_get_cached(backend, xla_computation, options)\n- buffer_counts = (None if len(out_avals) == 1 and not config.jax_dynamic_shapes\n- else [aval_to_num_buffers(aval) for aval in out_avals])\n+ buffer_counts = [aval_to_num_buffers(aval) for aval in out_avals]\nif ordered_effects or has_unordered_effects:\nnum_output_tokens = len(ordered_effects) + has_unordered_effects\n- if buffer_counts is None:\n- buffer_counts = [1]\nbuffer_counts = ([1] * num_output_tokens) + buffer_counts\nexecute = _execute_compiled if nreps == 1 else _execute_replicated\nunsafe_call = partial(execute, name, compiled, input_handler, buffer_counts, # type: ignore # noqa: F811\n- result_handlers, has_unordered_effects,\n+ result_handler, has_unordered_effects,\nordered_effects, kept_var_idx)\nreturn XlaCompiledComputation(compiled, in_avals, kept_var_idx, unsafe_call,\nkeepalive)\n@@ -976,7 +989,10 @@ def _device_put_device_array(x: Union[device_array.DeviceArrayProtocol, device_a\nfor t in device_array.device_array_types:\ndevice_put_handlers[t] = _device_put_device_array\n-def _copy_device_array_to_device(x: Union[device_array.DeviceArrayProtocol, device_array._DeviceArray], device: Optional[xc.Device]) -> Union[device_array.DeviceArrayProtocol, device_array._DeviceArray]:\n+def _copy_device_array_to_device(\n+ x: Union[device_array.DeviceArrayProtocol, device_array._DeviceArray],\n+ device: Optional[xc.Device]\n+ ) -> Union[device_array.DeviceArrayProtocol, device_array._DeviceArray]:\nif device is None:\n# no copying to be done because there's no target specified\nreturn x\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/iree.py", "new_path": "jax/_src/iree.py", "diff": "@@ -80,6 +80,10 @@ class IreeBuffer(xla_client.DeviceArrayBase):\ndef block_until_ready(self) -> IreeBuffer:\nreturn self # no async\n+ # overrides repr on base class which expects _value and aval attributes\n+ def __repr__(self):\n+ return f'IreeBuffer({self._npy_value})'\n+\nclass IreeExecutable:\ndef __init__(self, client, devices, module_object, function_name):\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -56,11 +56,10 @@ map, unsafe_map = safe_map, map\nEffect = Hashable\nEffects = Set[Effect]\n-\nno_effects: Effects = set()\n-\nordered_effects: Set[Effect] = set()\n+\nclass Jaxpr:\nconstvars: List[Var]\ninvars: List[Var]\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -22,7 +22,7 @@ import inspect\nimport itertools as it\nimport operator as op\nfrom typing import (Any, Callable, Dict, NamedTuple, Optional, Sequence, Tuple,\n- List, Union, Hashable, cast)\n+ List, Union, Hashable, Set, cast)\nfrom weakref import ref\nimport numpy as np\n@@ -1387,6 +1387,17 @@ class JaxprStackFrame:\njaxpr, constvals = _inline_literals(jaxpr, constvals)\nreturn jaxpr, constvals\n+ def to_jaxpr2(self, out_tracers):\n+ # It's not necessary, but we keep the tracer-to-var mapping injective:\n+ assert len(self.tracer_to_var) == len(set(self.tracer_to_var.values()))\n+ constvars, constvals = unzip2(self.constvar_to_val.items())\n+ expl_outvars = [self.tracer_to_var[id(t)] for t in out_tracers]\n+ jaxpr = Jaxpr(constvars, self.invars, expl_outvars, self.eqns, self.effects)\n+ jaxpr, constvals = _const_folding_and_forwarding(jaxpr, constvals)\n+ jaxpr, constvals = _inline_literals(jaxpr, constvals)\n+ jaxpr, out_type = _add_implicit_outputs(jaxpr)\n+ return jaxpr, out_type, constvals\n+\ndef newvar(self, aval):\nif isinstance(aval, DShapedArray):\n# this aval may have tracers in it, so we replace those with variables\n@@ -1573,38 +1584,37 @@ class DynamicJaxprTrace(core.Trace):\ndef process_call(self, call_primitive, f, explicit_tracers, params):\nif f.in_type is None:\n- in_avals = [core.raise_to_shaped(get_aval(x)) for x in explicit_tracers]\n- keep_inputs = [True] * len(explicit_tracers)\n- im_tracers = []\n- else:\n- im_tracers = _extract_implicit_args(self, f.in_type, explicit_tracers)\n- in_avals, keep_inputs = unzip2(f.in_type)\n+ f = lu.annotate(f, tuple((t.aval, True) for t in explicit_tracers))\nwith core.new_sublevel():\n- jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(\n- f, self.main, in_avals, keep_inputs=keep_inputs)\n+ jaxpr, out_type, consts = trace_to_subjaxpr_dynamic2(f, self.main)\nif jaxpr.effects:\nraise NotImplementedError('Effects not supported for call primitives.')\n- tracers = [*im_tracers, *explicit_tracers]\n+ implicit_tracers = _extract_implicit_args(self, f.in_type, explicit_tracers)\n+ in_tracers = [*implicit_tracers, *explicit_tracers]\nif params.get('inline', False):\n- return core.eval_jaxpr(jaxpr, consts, *tracers)\n- env = {v: t for v, t in zip(jaxpr.constvars, consts) if isinstance(t, Tracer)}\n- env.update(zip(jaxpr.invars, tracers))\n- out_avals_ = [_substitute_tracers_in_type(env, a) for a in out_avals]\n+ return core.eval_jaxpr(jaxpr, consts, *in_tracers)\nsource_info = source_info_util.current()\n- out_tracers = [DynamicJaxprTracer(self, a, source_info) for a in out_avals_]\n- invars = map(self.getvar, tracers)\n+ out_tracers = []\n+ for aval, _ in out_type:\n+ if type(aval) is DShapedArray:\n+ shape = [[*consts, *in_tracers][d.val] if type(d) is InDBIdx else\n+ out_tracers[d.val] if type(d) is OutDBIdx else\n+ d for d in aval.shape]\n+ aval = aval.update(shape=tuple(shape))\n+ out_tracers.append(DynamicJaxprTracer(self, aval, source_info))\n+ invars = map(self.getvar, in_tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\noutvars = map(self.makevar, out_tracers)\nnew_params = dict(params, call_jaxpr=convert_constvars_jaxpr(jaxpr))\nupdate_params = call_param_updaters.get(call_primitive)\nif update_params:\nnew_params = update_params(new_params, [True] * len(explicit_tracers),\n- len(consts) + len(im_tracers))\n- eqn = new_jaxpr_eqn([*constvars, *invars], outvars,\n- call_primitive, new_params,\n- new_params['call_jaxpr'].effects, source_info)\n+ len(consts) + len(implicit_tracers))\n+ eqn = new_jaxpr_eqn([*constvars, *invars], outvars, call_primitive,\n+ new_params, new_params['call_jaxpr'].effects,\n+ source_info)\nself.frame.add_eqn(eqn)\n- return out_tracers\n+ return [t for t, (_, keep) in zip(out_tracers, out_type) if keep]\ndef post_process_call(self, call_primitive, out_tracers, params):\nassert False # unreachable\n@@ -1851,6 +1861,37 @@ def trace_to_subjaxpr_dynamic(fun: lu.WrappedFun, main: core.MainTrace,\nconfig.jax_enable_checks and core.check_jaxpr(jaxpr)\nreturn jaxpr, [v.aval for v in jaxpr.outvars], consts\n+\n+@profiler.annotate_function\n+def trace_to_jaxpr_dynamic2(\n+ fun: lu.WrappedFun, debug_info: Optional[DebugInfo] = None\n+ ) -> Tuple[Jaxpr, OutputType, List[Any]]:\n+ with core.new_main(DynamicJaxprTrace, dynamic=True) as main: # type: ignore\n+ main.debug_info = debug_info # type: ignore\n+ main.jaxpr_stack = () # type: ignore\n+ jaxpr, out_type, consts = trace_to_subjaxpr_dynamic2(fun, main)\n+ del main, fun\n+ return jaxpr, out_type, consts\n+\n+def trace_to_subjaxpr_dynamic2(\n+ fun: lu.WrappedFun, main: core.MainTrace\n+ ) -> Tuple[Jaxpr, OutputType, List[Any]]:\n+ in_avals, keep_inputs = unzip2(fun.in_type)\n+ frame = JaxprStackFrame()\n+ with extend_jaxpr_stack(main, frame), source_info_util.reset_name_stack():\n+ trace = DynamicJaxprTrace(main, core.cur_sublevel())\n+ in_tracers = _input_type_to_tracers(trace, in_avals)\n+ in_tracers_ = [t for t, keep in zip(in_tracers, keep_inputs) if keep]\n+ ans = fun.call_wrapped(*in_tracers_)\n+ out_tracers = map(trace.full_raise, ans)\n+ jaxpr, out_type, consts = frame.to_jaxpr2(out_tracers)\n+ del fun, main, trace, frame, in_tracers, out_tracers, ans\n+ if not config.jax_dynamic_shapes:\n+ # TODO(frostig,mattjj): update check_jaxpr to handle dynamic shapes\n+ config.jax_enable_checks and core.check_jaxpr(jaxpr)\n+ return jaxpr, out_type, consts\n+\n+\n@contextlib.contextmanager\ndef extend_jaxpr_stack(main, frame):\nmain.jaxpr_stack = main.jaxpr_stack + (frame,)\n@@ -1874,6 +1915,18 @@ def trace_to_jaxpr_final(fun: lu.WrappedFun,\ndel fun, main\nreturn jaxpr, out_avals, consts\n+@profiler.annotate_function\n+def trace_to_jaxpr_final2(\n+ fun: lu.WrappedFun, debug_info: Optional[DebugInfo] = None\n+ ) -> Tuple[Jaxpr, OutputType, List[Any]]:\n+ with core.new_base_main(DynamicJaxprTrace) as main: # type: ignore\n+ main.debug_info = debug_info # type: ignore\n+ main.jaxpr_stack = () # type: ignore\n+ with core.new_sublevel():\n+ jaxpr, out_type, consts = trace_to_subjaxpr_dynamic2(fun, main)\n+ del fun, main\n+ return jaxpr, out_type, consts\n+\nAbstractedAxisName = Hashable\nAbstractedAxesSpec = Union[Dict[int, AbstractedAxisName],\n@@ -1891,14 +1944,15 @@ class OutDBIdx:\nval: int\nInputType = Tuple[Tuple[AbstractValue, bool], ...] # DBIdx in shapes\n-OutputType = Tuple[AbstractValue, ...] # InDBIdx / OutDBIdx in shapes\n+OutputType = Tuple[Tuple[AbstractValue, bool], ...] # InDBIdx / OutDBIdx shapes\ndef infer_lambda_input_type(\naxes_specs: Optional[Sequence[AbstractedAxesSpec]],\nargs: Sequence[Any]\n) -> InputType:\n- partial_specs = _canonicalize_specs(map(np.ndim, args), axes_specs)\n+ ndims = [getattr(get_aval(x), 'ndim', 0) for x in args]\n+ partial_specs = _canonicalize_specs(ndims, axes_specs)\nspecs = _complete_specs(args, partial_specs)\nidxs, implicit_names = _collect_implicit(args, specs)\nimplicit_inputs = [(_implicit_arg_type(n), False) for n in implicit_names]\n@@ -1917,12 +1971,21 @@ def _canonicalize_specs(\ndef _complete_specs(\nargs: Sequence[Any], partial_specs: List[Dict[int, AbstractedAxisName]]\n) -> List[Dict[int, AbstractedAxisName]]:\n+ # The abstracted axes specification in `partial_specs` is partial in the sense\n+ # that there could be additional axis abstraction represented in `args` due to\n+ # Tracers existing in the shapes of elements of `args`. The purpose of this\n+ # function is to produce a full specification, for each argument mapping any\n+ # abstracted axis positions to a name, introducing new names as needed for\n+ # Tracers in axis sizes which don't already correspond to abstracted axis\n+ # names (with one new name per unique Tracer object id).\n+\n# Identify each user-supplied name in partial_specs with a size.\nsizes: Dict[AbstractedAxisName, Union[int, DynamicJaxprTracer]] = {}\nfor x, spec in zip(args, partial_specs):\nfor i, name in spec.items():\nd = sizes.setdefault(name, x.shape[i])\nif d is not x.shape[i] and d != x.shape[i]: raise TypeError\n+\n# Introduce new names as needed for Tracers in shapes.\nnamed_tracers: Dict[TracerId, AbstractedAxisName] = {\nid(d): name for name, d in sizes.items() if isinstance(d, Tracer)}\n@@ -1934,6 +1997,9 @@ def _complete_specs(\nif isinstance(d, Tracer):\nspec[i] = named_tracers.get(id(d), TracerAsName(d))\nspecs.append(spec)\n+\n+ # Assert that `specs` is now complete in the sense that there are no Tracers\n+ # which don't correspond to an AbstractedAxisName.\nassert all(not spec or not any(isinstance(d, Tracer) and i not in spec\nfor i, d in enumerate(x.shape))\nfor x, spec in zip(args, specs))\n@@ -1942,9 +2008,16 @@ def _complete_specs(\ndef _collect_implicit(\nargs: Sequence[Any], specs: List[Dict[int, AbstractedAxisName]]\n) -> Tuple[Dict[AbstractedAxisName, DBIdx], List[AbstractedAxisName]]:\n+ # Given an explicit argument list and a specification of abstracted axes, we\n+ # want to produce an InputType by identifying AbstractedAxisNames with DBIdxs\n+ # and figuring out which AbstractedAxisNames correspond to implicit arguments.\n+ # An AbstractedAxisName corresponds to an implicit argument only when its size\n+ # is a Tracer which already occurs in `args` to the left of where it's needed.\n+\nidxs: Dict[AbstractedAxisName, DBIdx] = {}\nexplicit_tracers: Dict[TracerId, int] = {}\ncounter = (DBIdx(i) for i in it.count())\n+\n# Add implicit arguments to idxs.\nfor explicit_idx, (x, spec) in enumerate(zip(args, specs)):\nfor i, name in spec.items():\n@@ -1964,12 +2037,14 @@ def _collect_implicit(\nreturn idxs, implicit_names\ndef _implicit_arg_type(name: AbstractedAxisName) -> AbstractValue:\n+ # For now, implicit args are always axis sizes, which always have type i32[].\nreturn ShapedArray((), dtypes.dtype('int32'))\ndef _arg_type(\nidxs: Dict[AbstractedAxisName, DBIdx], x: Any,\nspec: Dict[int, AbstractedAxisName]\n) -> AbstractValue:\n+ # Produce an AbstractValue by substituting DBIdxs for AbstractedAxisNames.\naval = get_aval(x) # aval.shape could contain Tracers\nif not spec: return core.raise_to_shaped(aval)\nshape: List[Union[int, DBIdx]] = [idxs[spec[i]] if i in spec else d\n@@ -1977,6 +2052,34 @@ def _arg_type(\nassert not any(isinstance(d, Tracer) for d in shape)\nreturn DShapedArray(tuple(shape), aval.dtype, False)\n+def _add_implicit_outputs(jaxpr: Jaxpr) -> Tuple[Jaxpr, OutputType]:\n+ invars = [*jaxpr.constvars, *jaxpr.invars]\n+ expl_outvars = jaxpr.outvars\n+\n+ # First do a pass to collect implicit outputs, meaning variables which occurr\n+ # in explicit_outvars types but not in invars or to the left in outvars.\n+ seen: Set[Var] = set(invars)\n+ impl_outvars = [seen.add(d) or d for x in expl_outvars if type(x) is Var and # type: ignore\n+ (seen.add(x) or type(x.aval) is DShapedArray) # type: ignore\n+ for d in x.aval.shape if type(d) is Var and d not in seen]\n+ outvars = [*impl_outvars, *expl_outvars]\n+\n+ # Now assemble an OutputType by mapping vars in shapes to InDBIdx/OutDBIdx.\n+ in_map : Dict[Var, InDBIdx] = {v: InDBIdx(i) for i, v in enumerate(invars )}\n+ out_map: Dict[Var, OutDBIdx] = {x: OutDBIdx(i) for i, x in enumerate(outvars)\n+ if type(x) is Var}\n+ out_avals_ = (x.aval for x in outvars)\n+ out_avals = [a.update(shape=tuple(in_map.get(d, out_map.get(d))\n+ if type(d) is Var else d for d in a.shape))\n+ if type(a) is DShapedArray else a for a in out_avals_]\n+ kept_outs = [False] * len(impl_outvars) + [True] * len(expl_outvars)\n+ out_type = tuple(zip(out_avals, kept_outs))\n+\n+ new_jaxpr = Jaxpr(jaxpr.constvars, jaxpr.invars, outvars, jaxpr.eqns,\n+ jaxpr.effects)\n+ return new_jaxpr, out_type\n+\n+\nclass TracerAsName:\ntracer: DynamicJaxprTracer\ndef __init__(self, tracer):\n@@ -2055,18 +2158,6 @@ def _substitute_vars_in_type(\nelse:\nreturn a\n-def _substitute_tracers_in_type(\n- env: Dict[Var, Tracer], a: AbstractValue\n- ) -> AbstractValue:\n- # Substitutes variables into a given AbstractValue using given environment.\n- # That is, the input is an AbstractValue possibly containing Vars, and the\n- # output is an aval possibly containing Tracers.\n- if isinstance(a, DShapedArray) and any(isinstance(d, Var) for d in a.shape):\n- shape = [env[d] if isinstance(d, Var) else d for d in a.shape]\n- return a.update(shape=tuple(shape))\n- else:\n- return a\n-\nConst = Any\nVal = Any\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -70,6 +70,7 @@ FLAGS = config.FLAGS\npython_version = (sys.version_info[0], sys.version_info[1])\nnumpy_version = tuple(map(int, np.__version__.split('.')[:3]))\n+jaxlib_version = jax._src.lib.version\nclass CPPJitTest(jtu.BufferDonationTestCase):\n@@ -8633,6 +8634,18 @@ class DynamicShapeTest(jtu.JaxTestCase):\nexpected = jnp.cumsum(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ @unittest.skipIf(jaxlib_version < (0, 3, 11), \"test requires jaxlib>=0.3.11\")\n+ def test_jit_of_broadcast(self):\n+ x = jax.jit(jnp.ones)(3)\n+ self.assertAllClose(x, jnp.ones(3))\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ @unittest.skipIf(jaxlib_version < (0, 3, 11), \"test requires jaxlib>=0.3.11\")\n+ def test_jit_of_broadcast2(self):\n+ x = jax.jit(lambda n: jnp.ones(2 * n))(3)\n+ self.assertAllClose(x, jnp.ones(2 * 3))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[djax] add support for dynamic-shape outputs
260,447
26.05.2022 22:22:20
25,200
ae9f9f77eea1e1aba2009f2270ce69770af5f25d
[sparse] Set `jax_bcoo_cusparse_lowering` default to true.
[ { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -725,11 +725,11 @@ traceback_filtering = config.define_enum_state(\n\" * \\\"remove_frames\\\": removes hidden frames from tracebacks, and adds \"\n\" the unfiltered traceback as a __cause__ of the exception.\\n\")\n-# This flag is temporary and for internal use.\n-# TODO(tianjianlu): Removes after providing the information in BCOO meta data.\n+# This flag is for internal use.\n+# TODO(tianjianlu): Removes once we always enable cusparse lowering.\nbcoo_cusparse_lowering = config.define_bool_state(\nname='jax_bcoo_cusparse_lowering',\n- default=False,\n+ default=True,\nhelp=('Enables lowering BCOO ops to cuSparse.'))\n# TODO(mattjj): remove this flag when we ensure we only succeed at trace-staging\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Set `jax_bcoo_cusparse_lowering` default to true. PiperOrigin-RevId: 451314487
260,520
27.05.2022 02:56:51
25,200
ae908b875306e774899a12a6f361b8cc2b5806fc
Remove local positional semantics assertion in `make_xmap_callable`.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -661,7 +661,6 @@ def make_xmap_callable(fun: lu.WrappedFun,\nglobal_axis_sizes, axis_resources, resource_env, backend,\nspmd_in_axes, spmd_out_axes_thunk, in_positional_semantics,\nout_positional_semantics, *in_avals):\n- assert out_positional_semantics == _PositionalSemantics.LOCAL\nplan = EvaluationPlan.from_axis_resources(\naxis_resources, resource_env, global_axis_sizes, in_positional_semantics)\n" } ]
Python
Apache License 2.0
google/jax
Remove local positional semantics assertion in `make_xmap_callable`. PiperOrigin-RevId: 451347782
260,268
27.05.2022 12:19:47
14,400
6c7542e4a3b549e1d311a19a0ad9b84f8ab7145f
adding notification workflows.
[ { "change_type": "ADD", "old_path": null, "new_path": ".github/workflows/broken-main-notify.yml", "diff": "+name: Google Chat Broken Main Notification\n+on:\n+ check_suite:\n+ types:\n+ - completed\n+ branches:\n+ - main\n+ conclusion:\n+ - failure\n+\n+jobs:\n+ build:\n+ runs-on: ubuntu-latest\n+\n+ steps:\n+ - name: Google Chat Notification\n+ run: |\n+ curl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n+ --header 'Content-Type: application/json' \\\n+ --data-raw '{\n+ \"text\": \"Main is broken @ {github.event.check_suite.created_at} see <{github.event.check_suite.url}|[github]>\"\n+ }'\n" }, { "change_type": "ADD", "old_path": null, "new_path": ".github/workflows/pull-request-notify.yml", "diff": "+# Testing out a google chat notification workflow.\n+name: Google Chat Pull Request Notifier\n+on:\n+ pull_request:\n+ types:\n+ - opened\n+\n+jobs:\n+ build:\n+ runs-on: ubuntu-latest\n+\n+ steps:\n+ - name: Google Chat Notification\n+ run: |\n+ curl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n+ --header 'Content-Type: application/json' \\\n+ --data-raw '{\n+ \"text\": \"Pull Requst {github.event.pull_request.title} by {github.event.pull_request.user.login}: {github.event.pull_request.body} <{github.event.pull_request.html_url}|[github]>\"\n+ }'\n" }, { "change_type": "ADD", "old_path": null, "new_path": ".github/workflows/release-notification.yml", "diff": "+name: Google Chat Release Notification\n+on:\n+ release:\n+ types: [published]\n+\n+jobs:\n+ build:\n+ runs-on: ubuntu-latest\n+\n+ steps:\n+ - name: Google Chat Notification\n+ run: |\n+ curl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n+ --header 'Content-Type: application/json' \\\n+ --data-raw '{\n+ \"text\": \"Release {github.event.release.name} at {github.event.release.published_at} by {github.event.release.author.login}. Changes: {github.event.release.body} <{github.event.release.url}|[github]>\"\n+ }'\n" } ]
Python
Apache License 2.0
google/jax
adding notification workflows.
260,570
27.05.2022 11:03:24
25,200
3e766c76fb9f78b6a468faa279a13e5fc2dfc09a
fix incorrect f-string format in xmap
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -254,7 +254,7 @@ def _parse_entry(arg_name, entry):\nraise TypeError(f\"\"\"\\\nValue mapping specification in xmap {arg_name} pytree can be either:\n- lists of axis names (possibly ending with the ellipsis object: ...)\n-- dictionaries that map positional axes (integers) to axis names (e.g. {2: 'name'})\n+- dictionaries that map positional axes (integers) to axis names (e.g. {{2: 'name'}})\nbut got: {entry}\"\"\")\nif len(result) != num_mapped_dims:\nraise ValueError(f\"Named axes should be unique within each {arg_name} argument \"\n" } ]
Python
Apache License 2.0
google/jax
fix incorrect f-string format in xmap
260,268
27.05.2022 14:07:21
14,400
8e34061739593bba72405b0dd44e156c1046a7af
Fixing the interpolation errors and yaml syntax errors.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/broken-main-notify.yml", "new_path": ".github/workflows/broken-main-notify.yml", "diff": "@@ -18,5 +18,5 @@ jobs:\ncurl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n- \"text\": \"Main is broken @ {github.event.check_suite.created_at} see <{github.event.check_suite.url}|[github]>\"\n+ \"text\": \"Main is broken @ ${{github.event.check_suite.created_at}} see <${{github.event.check_suite.url}}|[github]>\"\n}'\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/pull-request-notify.yml", "new_path": ".github/workflows/pull-request-notify.yml", "diff": "@@ -15,5 +15,5 @@ jobs:\ncurl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n- \"text\": \"Pull Requst {github.event.pull_request.title} by {github.event.pull_request.user.login}: {github.event.pull_request.body} <{github.event.pull_request.html_url}|[github]>\"\n+ \"text\": \"Pull Request ${{github.event.pull_request.title}} by ${{github.event.pull_request.user.login}}: ${{github.event.pull_request.body}} <${{github.event.pull_request.html_url}}|[github]>\"\n}'\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/release-notification.yml", "new_path": ".github/workflows/release-notification.yml", "diff": "@@ -13,5 +13,5 @@ jobs:\ncurl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n- \"text\": \"Release {github.event.release.name} at {github.event.release.published_at} by {github.event.release.author.login}. Changes: {github.event.release.body} <{github.event.release.url}|[github]>\"\n+ \"text\": \"Release ${{github.event.release.name}} at ${{github.event.release.published_at}} by ${{github.event.release.author.login}}. Changes: ${{github.event.release.body}} <${{github.event.release.url}}|[github]>\"\n}'\n" } ]
Python
Apache License 2.0
google/jax
Fixing the interpolation errors and yaml syntax errors.
260,268
27.05.2022 16:13:19
14,400
57da8d941b14c0093d98fbb1cf2bfb6055d79125
Attempting again to fix the yaml syntax issues in the pull request notifier and trying to fix the trigger for the broken main.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/broken-main-notify.yml", "new_path": ".github/workflows/broken-main-notify.yml", "diff": "@@ -5,8 +5,6 @@ on:\n- completed\nbranches:\n- main\n- conclusion:\n- - failure\njobs:\nbuild:\n@@ -14,9 +12,10 @@ jobs:\nsteps:\n- name: Google Chat Notification\n+ if: ${{ github.event.check_suite.conclusion == 'failure' }}\nrun: |\ncurl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n- \"text\": \"Main is broken @ ${{github.event.check_suite.created_at}} see <${{github.event.check_suite.url}}|[github]>\"\n+ \"text\": \"Main is broken! @ ${{github.event.check_suite.created_at}} see <${{github.event.check_suite.url}}|[github]>\"\n}'\n" } ]
Python
Apache License 2.0
google/jax
Attempting again to fix the yaml syntax issues in the pull request notifier and trying to fix the trigger for the broken main.
260,268
31.05.2022 09:38:43
25,200
e8a92f33b01038291cd8740d5a0f7f5e8f980ae1
Remove bodies from the notification messages as they tend to break bash syntax.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/pull-request-notify.yml", "new_path": ".github/workflows/pull-request-notify.yml", "diff": "@@ -15,5 +15,5 @@ jobs:\ncurl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n- \"text\": \"Pull Request ${{github.event.pull_request.title}} by ${{github.event.pull_request.user.login}}: ${{github.event.pull_request.body}} <${{github.event.pull_request.html_url}}|[github]>\"\n+ \"text\": \"Pull Request ${{github.event.pull_request.title}} by ${{github.event.pull_request.user.login}} <${{github.event.pull_request.html_url}}|[github]>\"\n}'\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/release-notification.yml", "new_path": ".github/workflows/release-notification.yml", "diff": "@@ -13,5 +13,5 @@ jobs:\ncurl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n- \"text\": \"Release ${{github.event.release.name}} at ${{github.event.release.published_at}} by ${{github.event.release.author.login}}. Changes: ${{github.event.release.body}} <${{github.event.release.url}}|[github]>\"\n+ \"text\": \"Release ${{github.event.release.name}} at ${{github.event.release.published_at}} by ${{github.event.release.author.login}}. <${{github.event.release.url}}|[github]>\"\n}'\n" } ]
Python
Apache License 2.0
google/jax
Remove bodies from the notification messages as they tend to break bash syntax. PiperOrigin-RevId: 452068897
260,268
01.06.2022 06:19:23
25,200
4ca92edaecfc7b7d52cee02e93d7f77b95f3c2b9
Remove pull request notification.
[ { "change_type": "DELETE", "old_path": ".github/workflows/pull-request-notify.yml", "new_path": null, "diff": "-# Testing out a google chat notification workflow.\n-name: Google Chat Pull Request Notifier\n-on:\n- pull_request:\n- types:\n- - opened\n-\n-jobs:\n- build:\n- runs-on: ubuntu-latest\n-\n- steps:\n- - name: Google Chat Notification\n- run: |\n- curl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n- --header 'Content-Type: application/json' \\\n- --data-raw '{\n- \"text\": \"Pull Request ${{github.event.pull_request.title}} by ${{github.event.pull_request.user.login}} <${{github.event.pull_request.html_url}}|[github]>\"\n- }'\n" } ]
Python
Apache License 2.0
google/jax
Remove pull request notification. PiperOrigin-RevId: 452280419
260,510
01.06.2022 12:14:36
25,200
b80d7195f695b728a91f63ab2d2b6b09692f2064
Enable python callback on GPU
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugging.py", "new_path": "jax/_src/debugging.py", "diff": "@@ -21,6 +21,7 @@ from typing import Callable, Any\nfrom jax import core\nfrom jax import tree_util\nfrom jax import lax\n+from jax._src import lib as jaxlib\nfrom jax._src import util\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\n@@ -118,6 +119,9 @@ def debug_callback_lowering(ctx, *args, effect, callback, **params):\nreturn result\nmlir.register_lowering(debug_callback_p, debug_callback_lowering,\nplatform=\"cpu\")\n+if jaxlib.version >= (0, 3, 11):\n+ mlir.register_lowering(\n+ debug_callback_p, debug_callback_lowering, platform=\"gpu\")\ndef debug_callback(callback: Callable[..., Any], effect: DebugEffect, *args,\n**kwargs):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -1257,8 +1257,12 @@ def emit_python_callback(platform, callback,\nresult_avals: List[core.AbstractValue],\nhas_side_effect: bool) -> Tuple[List[ir.Value], Any]:\n\"\"\"Creates an MHLO `CustomCallOp` that calls back to the provided function.\"\"\"\n- if platform != \"cpu\":\n- raise ValueError('`EmitPythonCallback` not supported in non-CPU backends.')\n+ if platform == \"cuda\" and jax._src.lib.version < (0, 3, 11):\n+ raise ValueError(\n+ \"`EmitPythonCallback` on CUDA only supported on jaxlib >= 0.3.11\")\n+ if platform not in {\"cpu\", \"cuda\"}:\n+ raise ValueError(\n+ \"`EmitPythonCallback` only supported on CPU and CUDA backends.\")\nbackend = xb.get_backend(platform)\nresult_shapes = util.flatten(\n[xla.aval_to_xla_shapes(result_aval) for result_aval in result_avals])\n@@ -1272,14 +1276,16 @@ def emit_python_callback(platform, callback,\nresult_types = util.flatten(\n[aval_to_ir_types(aval) for aval in result_avals])\nresult_type = ir.TupleType.get_tuple(result_types)\n+ call_target_name = (\"xla_python_gpu_callback\"\n+ if platform == \"cuda\" else \"xla_python_cpu_callback\")\nresult = mhlo.CustomCallOp(\n[result_type],\ncallback_operands,\n- call_target_name=ir.StringAttr.get(\"xla_python_cpu_callback\"),\n+ call_target_name=ir.StringAttr.get(call_target_name),\nhas_side_effect=ir.BoolAttr.get(has_side_effect),\napi_version=i32_attr(2),\ncalled_computations=ir.ArrayAttr.get([]),\n- backend_config=ir.StringAttr.get(\"\"),\n+ backend_config=ir.StringAttr.get(str(callback_descriptor)),\noperand_layouts=None,\nresult_layouts=None)\nresults = [\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -56,9 +56,15 @@ def setUpModule():\ndef tearDownModule():\nprev_xla_flags()\n+# TODO(sharadmv): remove jaxlib guards for GPU tests when jaxlib minimum\n+# version is >= 0.3.11\n+disabled_backends = [\"tpu\"]\n+if jaxlib.version < (0, 3, 11):\n+ disabled_backends.append(\"gpu\")\n+\nclass DebugPrintTest(jtu.JaxTestCase):\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_simple_debug_print_works_in_eager_mode(self):\ndef f(x):\ndebug_print('x: {}', x)\n@@ -67,7 +73,7 @@ class DebugPrintTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_debug_print_works_with_named_format_strings(self):\ndef f(x):\ndebug_print('x: {x}', x=x)\n@@ -76,7 +82,7 @@ class DebugPrintTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_multiple_debug_prints_should_print_multiple_values(self):\ndef f(x):\ndebug_print('x: {x}', x=x)\n@@ -86,7 +92,7 @@ class DebugPrintTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\ny: 3\\n\")\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_stage_out_debug_print(self):\n@jax.jit\ndef f(x):\n@@ -96,7 +102,7 @@ class DebugPrintTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_stage_out_ordered_print(self):\n@jax.jit\ndef f(x):\n@@ -106,7 +112,7 @@ class DebugPrintTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_stage_out_ordered_print_with_pytree(self):\n@jax.jit\ndef f(x):\n@@ -189,28 +195,27 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\nfor ordered in [False, True]))\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_print_inside_scan(self, ordered):\ndef f(xs):\ndef _body(carry, x):\n- debug_print(\"carry: {carry}\", carry=carry, ordered=ordered)\n- debug_print(\"x: {x}\", x=x, ordered=ordered)\n+ debug_print(\"carry: {carry}, x: {x}\", carry=carry, x=x, ordered=ordered)\nreturn carry + 1, x + 1\nreturn lax.scan(_body, 2, xs)\nwith capture_stdout() as output:\nf(jnp.arange(2))\njax.effects_barrier()\n- self.assertEqual(output(), _format_multiline(\"\"\"\n- carry: 2\n- x: 0\n- carry: 3\n- x: 1\n+ self.assertEqual(\n+ output(),\n+ _format_multiline(\"\"\"\n+ carry: 2, x: 0\n+ carry: 3, x: 1\n\"\"\"))\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\nfor ordered in [False, True]))\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_print_inside_for_loop(self, ordered):\ndef f(x):\ndef _body(i, x):\n@@ -231,7 +236,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\nfor ordered in [False, True]))\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_print_inside_while_loop_body(self, ordered):\ndef f(x):\ndef _cond(x):\n@@ -254,7 +259,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\nfor ordered in [False, True]))\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_print_inside_while_loop_cond(self, ordered):\ndef f(x):\ndef _cond(x):\n@@ -286,7 +291,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\nfor ordered in [False, True]))\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_print_inside_cond(self, ordered):\ndef f(x):\ndef true_fun(x):\n@@ -312,7 +317,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\nfor ordered in [False, True]))\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_print_inside_switch(self, ordered):\ndef f(x):\ndef b1(x):\n@@ -348,7 +353,7 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\ndef _assertLinesEqual(self, text1, text2):\nself.assertSetEqual(set(text1.split(\"\\n\")), set(text2.split(\"\\n\")))\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_ordered_print_not_supported_in_pmap(self):\n@jax.pmap\n@@ -358,7 +363,7 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\nValueError, \"Ordered effects not supported in `pmap`.\"):\nf(jnp.arange(jax.local_device_count()))\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_unordered_print_works_in_pmap(self):\nif jax.device_count() < 2:\nraise unittest.SkipTest(\"Test requires >= 2 devices.\")\n@@ -369,7 +374,8 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\nwith capture_stdout() as output:\nf(jnp.arange(jax.local_device_count()))\njax.effects_barrier()\n- self._assertLinesEqual(output(), \"hello: 0\\nhello: 1\\n\")\n+ lines = [f\"hello: {i}\\n\" for i in range(jax.local_device_count())]\n+ self._assertLinesEqual(output(), \"\".join(lines))\n@jax.pmap\ndef f2(x):\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -59,6 +59,12 @@ lcf.allowed_effects.add('while')\nlcf.allowed_effects.add('while1')\nlcf.allowed_effects.add('while2')\n+# TODO(sharadmv): remove jaxlib guards for GPU tests when jaxlib minimum\n+# version is >= 0.3.11\n+disabled_backends = ['tpu']\n+if jaxlib.version < (0, 3, 11):\n+ disabled_backends.append('gpu')\n+\ndef trivial_effect_lowering(ctx, *, effect):\nctx.set_tokens_out(ctx.tokens_in)\n@@ -570,7 +576,7 @@ class EffectfulJaxprLoweringTest(jtu.JaxTestCase):\nclass EffectOrderingTest(jtu.JaxTestCase):\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_execute_python_callback(self):\n# TODO(sharadmv): remove jaxlib check when minimum version is bumped\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n@@ -592,7 +598,7 @@ class EffectOrderingTest(jtu.JaxTestCase):\nself.assertListEqual(log, [2., 3.])\ndispatch.runtime_tokens.block_until_ready()\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_ordered_effect_remains_ordered_across_multiple_devices(self):\n# TODO(sharadmv): remove jaxlib check when minimum version is bumped\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n@@ -628,7 +634,7 @@ class EffectOrderingTest(jtu.JaxTestCase):\nexpected_log = [x_, y_, x_, y_, x_, y_]\nself.assertListEqual(log, expected_log)\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_different_threads_get_different_tokens(self):\n# TODO(sharadmv): remove jaxlib check when minimum version is bumped\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n@@ -685,7 +691,7 @@ class ParallelEffectsTest(jtu.JaxTestCase):\nreturn x\njax.pmap(f)(jnp.arange(jax.local_device_count()))\n- @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_pmap_unordered_callback(self):\n# TODO(sharadmv): remove jaxlib check when minimum version is bumped\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n" } ]
Python
Apache License 2.0
google/jax
Enable python callback on GPU PiperOrigin-RevId: 452354891
260,510
25.05.2022 16:01:16
25,200
76669835baf64b30bbf6a7b2c1853a80a7e34bae
Add an option to create a perfetto link in the JAX profiler
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -32,6 +32,9 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* {func}`jax.numpy.ldexp` no longer silently promotes all inputs to float64,\ninstead it promotes to float32 for integer inputs of size int32 or smaller\n({jax-issue}`#10921`).\n+ * Add a `create_perfetto_link` option to {func}`jax.profiler.start_trace` and\n+ {func}`jax.profiler.start_trace`. When used, the profiler will generate a\n+ link to the Perfetto UI to view the trace.\n## jaxlib 0.3.11 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jaxlib-v0.3.10...main).\n" }, { "change_type": "ADD", "old_path": "docs/_static/perfetto.png", "new_path": "docs/_static/perfetto.png", "diff": "Binary files /dev/null and b/docs/_static/perfetto.png differ\n" }, { "change_type": "MODIFY", "old_path": "docs/profiling.md", "new_path": "docs/profiling.md", "diff": "# Profiling JAX programs\n+## Viewing program traces with Perfetto\n+\n+We can use the JAX profiler to generate traces of a JAX program that can be\n+visualized using the [Perfetto visualizer](https://ui.perfetto.dev). Currently,\n+this method blocks the program until a link is clicked and the Perfetto UI loads\n+the trace. If you wish to get profiling information without any interaction,\n+check out the the Tensorboard profiler below.\n+\n+```python\n+with jax.profiler.trace(\"/tmp/jax-trace\", create_perfetto_link=True):\n+ # Run the operations to be profiled\n+ key = jax.random.PRNGKey(0)\n+ x = jax.random.normal(key, (5000, 5000))\n+ y = x @ x\n+ y.block_until_ready()\n+```\n+\n+After this computation is done, the program will prompt you to open a link to\n+`ui.perfetto.dev`. When you open the link, the Perfetto UI will load the trace\n+file and open a visualizer.\n+\n+![Perfetto trace viewer](_static/perfetto.png)\n+\n+Program execution will continue after loading the link. The link is no longer\n+valid after opening once, but it will redirect to a new URL that remains valid.\n+You can then click the \"Share\" button in the Perfetto UI to create a permalink\n+to the trace that can be shared with others.\n+\n+### Remote profiling\n+\n+When profiling code that is running remotely (for example on a hosted VM),\n+you need to establish an SSH tunnel on port 9001 for the link to work. You can\n+do that with this command:\n+```bash\n+$ ssh -L 9001:127.0.0.1:9001 <user>@<host>\n+```\n+or if you're using Google Cloud:\n+```bash\n+$ gcloud compute ssh <machine-name> -- -L 9001:127.0.0.1:9001\n+```\n+\n## TensorBoard profiling\n[TensorBoard's\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/profiler.py", "new_path": "jax/_src/profiler.py", "diff": "from contextlib import contextmanager\nfrom functools import wraps\n+import glob\n+import gzip\n+import http.server\n+import json\n+import os\n+import socketserver\nimport threading\n-from typing import Callable, Optional\nimport warnings\n+from typing import Callable, Optional\n+\n+from absl import logging\nfrom jax._src import traceback_util\ntraceback_util.register_exclusion(__file__)\n@@ -43,12 +51,13 @@ class _ProfileState:\ndef __init__(self):\nself.profile_session = None\nself.log_dir = None\n+ self.create_perfetto_link = False\nself.lock = threading.Lock()\n_profile_state = _ProfileState()\n-def start_trace(log_dir):\n+def start_trace(log_dir, create_perfetto_link: bool = False):\n\"\"\"Starts a profiler trace.\nThe trace will capture CPU, GPU, and/or TPU activity, including Python\n@@ -64,14 +73,79 @@ def start_trace(log_dir):\nArgs:\nlog_dir: The directory to save the profiler trace to (usually the\nTensorBoard log directory).\n+ create_perfetto_link: A boolean which, if true, creates and prints link to\n+ the Perfetto trace viewer UI (https://ui.perfetto.dev). The program will\n+ block until the link is opened and Perfetto loads the trace.\n\"\"\"\nwith _profile_state.lock:\nif _profile_state.profile_session is not None:\nraise RuntimeError(\"Profile has already been started. \"\n\"Only one profile may be run at a time.\")\n_profile_state.profile_session = xla_client.profiler.ProfilerSession()\n+ _profile_state.create_perfetto_link = create_perfetto_link\n_profile_state.log_dir = log_dir\n+def _write_perfetto_trace_file(log_dir):\n+ # Navigate to folder with the latest trace dump to find `trace.json.jz`\n+ curr_path = os.path.abspath(log_dir)\n+ root_trace_folder = os.path.join(curr_path, \"plugins\", \"profile\")\n+ trace_folders = [os.path.join(root_trace_folder, trace_folder) for\n+ trace_folder in os.listdir(root_trace_folder)]\n+ latest_folder = max(trace_folders, key=os.path.getmtime)\n+ trace_jsons = glob.glob(os.path.join(latest_folder, \"*.trace.json.gz\"))\n+ if len(trace_jsons) != 1:\n+ raise ValueError(f\"Invalid trace folder: {latest_folder}\")\n+ trace_json, = trace_jsons\n+\n+ logging.info(\"Loading trace.json.gz and removing its metadata...\")\n+ # Perfetto doesn't like the `metadata` field in `trace.json` so we remove\n+ # it.\n+ # TODO(sharadmv): speed this up by updating the generated `trace.json`\n+ # to not include metadata if possible.\n+ with gzip.open(trace_json, \"rb\") as fp:\n+ trace = json.load(fp)\n+ del trace[\"metadata\"]\n+ filename = \"perfetto_trace.json.gz\"\n+ perfetto_trace = os.path.join(latest_folder, filename)\n+ logging.info(\"Writing perfetto_trace.json.gz...\")\n+ with gzip.open(perfetto_trace, \"w\") as fp:\n+ fp.write(json.dumps(trace).encode(\"utf-8\"))\n+ return perfetto_trace\n+\n+class _PerfettoServer(http.server.SimpleHTTPRequestHandler):\n+ \"\"\"Handles requests from `ui.perfetto.dev` for the `trace.json`\"\"\"\n+\n+ def end_headers(self):\n+ self.send_header('Access-Control-Allow-Origin', '*')\n+ return super().end_headers()\n+\n+ def do_GET(self):\n+ self.server.last_request = self.path\n+ return super().do_GET()\n+\n+ def do_POST(self):\n+ self.send_error(404, \"File not found\")\n+\n+def _host_perfetto_trace_file(log_dir):\n+ # ui.perfetto.dev looks for files hosted on `127.0.0.1:9001`. We set up a\n+ # TCP server that is hosting the `perfetto_trace.json.gz` file.\n+ port = 9001\n+ abs_filename = _write_perfetto_trace_file(log_dir)\n+ orig_directory = os.path.abspath(os.getcwd())\n+ directory, filename = os.path.split(abs_filename)\n+ try:\n+ os.chdir(directory)\n+ socketserver.TCPServer.allow_reuse_address = True\n+ with socketserver.TCPServer(('127.0.0.1', port), _PerfettoServer) as httpd:\n+ url = f\"https://ui.perfetto.dev/#!/?url=http://127.0.0.1:{port}/{filename}'\"\n+ print(f\"Open URL in browser: {url}\")\n+\n+ # Once ui.perfetto.dev acquires trace.json from this server we can close\n+ # it down.\n+ while httpd.__dict__.get('last_request') != '/' + filename:\n+ httpd.handle_request()\n+ finally:\n+ os.chdir(orig_directory)\ndef stop_trace():\n\"\"\"Stops the currently-running profiler trace.\n@@ -83,12 +157,15 @@ def stop_trace():\nif _profile_state.profile_session is None:\nraise RuntimeError(\"No profile started\")\n_profile_state.profile_session.stop_and_export(_profile_state.log_dir)\n+ if _profile_state.create_perfetto_link:\n+ _host_perfetto_trace_file(_profile_state.log_dir)\n_profile_state.profile_session = None\n+ _profile_state.create_perfetto_link = False\n_profile_state.log_dir = None\n@contextmanager\n-def trace(log_dir):\n+def trace(log_dir, create_perfetto_link=False):\n\"\"\"Context manager to take a profiler trace.\nThe trace will capture CPU, GPU, and/or TPU activity, including Python\n@@ -103,8 +180,11 @@ def trace(log_dir):\nArgs:\nlog_dir: The directory to save the profiler trace to (usually the\nTensorBoard log directory).\n+ create_perfetto_link: A boolean which, if true, creates and prints link to\n+ the Perfetto trace viewer UI (https://ui.perfetto.dev). The program will\n+ block until the link is opened and Perfetto loads the trace.\n\"\"\"\n- start_trace(log_dir)\n+ start_trace(log_dir, create_perfetto_link)\ntry:\nyield\nfinally:\n" } ]
Python
Apache License 2.0
google/jax
Add an option to create a perfetto link in the JAX profiler
260,510
31.05.2022 15:42:46
25,200
449da304b3665b90fd10c6203deec7863fd99928
Store profiler server as a global variable and add a `stop_server` function
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -35,6 +35,9 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Add a `create_perfetto_link` option to {func}`jax.profiler.start_trace` and\n{func}`jax.profiler.start_trace`. When used, the profiler will generate a\nlink to the Perfetto UI to view the trace.\n+ * Changed the semantics of {func}`jax.profiler.start_server(...)` to store the\n+ keepalive globally, rather than requiring the user to keep a reference to\n+ it.\n## jaxlib 0.3.11 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jaxlib-v0.3.10...main).\n" }, { "change_type": "MODIFY", "old_path": "docs/profiling.md", "new_path": "docs/profiling.md", "diff": "@@ -154,13 +154,12 @@ from a running program.\n```python\nimport jax.profiler\n- server = jax.profiler.start_server(9999)\n+ jax.profiler.start_server(9999)\n```\nThis starts the profiler server that TensorBoard connects to. The profiler\n- server must be running before you move on to the next step. It will remain\n- alive and listening until the object returned by `start_server()` is\n- destroyed.\n+ server must be running before you move on to the next step. When you're done\n+ using the server, you can call `jax.profiler.stop_server()` to shut it down.\nIf you'd like to profile a snippet of a long-running program (e.g. a long\ntraining loop), you can put this at the beginning of the program and start\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/profiler.py", "new_path": "jax/_src/profiler.py", "diff": "@@ -32,19 +32,30 @@ traceback_util.register_exclusion(__file__)\nfrom jax._src.lib import xla_bridge\nfrom jax._src.lib import xla_client\n+_profiler_server: Optional[xla_client.profiler.ProfilerServer] = None\n+\ndef start_server(port: int):\n- \"\"\"Starts a profiler server on port `port`.\n+ \"\"\"Starts the profiler server on port `port`.\nUsing the \"TensorFlow profiler\" feature in `TensorBoard\n<https://www.tensorflow.org/tensorboard>`_ 2.2 or newer, you can\nconnect to the profiler server and sample execution traces that show CPU,\nGPU, and/or TPU device activity.\n-\n- Returns a profiler server object. The server remains alive and listening until\n- the server object is destroyed.\n\"\"\"\n- return xla_client.profiler.start_server(port)\n+ global _profiler_server\n+ if _profiler_server is not None:\n+ raise ValueError(\"Only one profiler server can be active at a time.\")\n+ _profiler_server = xla_client.profiler.start_server(port)\n+ return _profiler_server\n+\n+\n+def stop_server():\n+ \"\"\"Stops the running profiler server.\"\"\"\n+ global _profiler_server\n+ if _profiler_server is None:\n+ raise ValueError(\"No active profiler server.\")\n+ _profiler_server = None # Should destroy the profiler server\nclass _ProfileState:\n" }, { "change_type": "MODIFY", "old_path": "jax/profiler.py", "new_path": "jax/profiler.py", "diff": "@@ -20,6 +20,7 @@ from jax._src.profiler import (\ndevice_memory_profile as device_memory_profile,\nsave_device_memory_profile as save_device_memory_profile,\nstart_server as start_server,\n+ stop_server as stop_server,\nstart_trace as start_trace,\nstop_trace as stop_trace,\ntrace as trace,\n" }, { "change_type": "MODIFY", "old_path": "tests/profiler_test.py", "new_path": "tests/profiler_test.py", "diff": "@@ -52,10 +52,25 @@ class ProfilerTest(unittest.TestCase):\nself.profile_done = False\n@unittest.skipIf(not portpicker, \"Test requires portpicker\")\n- def testStartServer(self):\n+ def testStartStopServer(self):\nport = portpicker.pick_unused_port()\njax.profiler.start_server(port=port)\ndel port\n+ jax.profiler.stop_server()\n+\n+ @unittest.skipIf(not portpicker, \"Test requires portpicker\")\n+ def testCantStartMultipleServers(self):\n+ port = portpicker.pick_unused_port()\n+ jax.profiler.start_server(port=port)\n+ port = portpicker.pick_unused_port()\n+ with self.assertRaisesRegex(\n+ ValueError, \"Only one profiler server can be active at a time.\"):\n+ jax.profiler.start_server(port=port)\n+ jax.profiler.stop_server()\n+\n+ def testCantStopServerBeforeStartingServer(self):\n+ with self.assertRaisesRegex(ValueError, \"No active profiler server.\"):\n+ jax.profiler.stop_server()\ndef testProgrammaticProfiling(self):\nwith tempfile.TemporaryDirectory() as tmpdir:\n@@ -151,14 +166,14 @@ class ProfilerTest(unittest.TestCase):\n\"Test requires tensorflow.profiler and portpicker\")\ndef testSingleWorkerSamplingMode(self, delay_ms=None):\ndef on_worker(port, worker_start):\n- # Must keep return value `server` around.\n- server = jax.profiler.start_server(port) # noqa: F841\n+ jax.profiler.start_server(port)\nworker_start.set()\nx = jnp.ones((1000, 1000))\nwhile True:\nwith jax.profiler.TraceAnnotation(\"atraceannotation\"):\njnp.dot(x, x.T).block_until_ready()\nif self.profile_done:\n+ jax.profiler.stop_server()\nbreak\ndef on_profile(port, logdir, worker_start):\n" } ]
Python
Apache License 2.0
google/jax
Store profiler server as a global variable and add a `stop_server` function
260,411
02.06.2022 16:41:55
-7,200
064ba6e58f75fea40f07fb066fd44444b001d5d3
[jax2tf] Added a test for SavedModel with pytrees This was in response to an external user running into problems with converting and saving a SavedModel for a function where one of the arguments is a dict. This test demonstrates that this works, both for the conversion, and for the saving/restoring.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/savedmodel_test.py", "new_path": "jax/experimental/jax2tf/tests/savedmodel_test.py", "diff": "@@ -241,6 +241,41 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\nres_restored = restored_f(*args)\nself.assertAllClose(res, res_restored)\n+ def test_pytree(self):\n+ def f_jax(params, x):\n+ # params is a dict\n+ return x @ params[\"w\"] + params[\"b\"]\n+\n+ x = np.ones((2, 3), dtype=np.float32)\n+ params = dict(w=np.ones((3, 4), dtype=np.float32),\n+ b=np.ones((2, 4), dtype=np.float32))\n+ res_jax = f_jax(params, x)\n+ f_tf = jax2tf.convert(f_jax)\n+\n+ res_tf = f_tf(params, x)\n+ self.assertAllClose(res_jax, res_tf.numpy())\n+\n+ restored_f, restored_model = tf_test_util.SaveAndLoadFunction(f_tf, input_args=(params, x),\n+ save_gradients=True)\n+ self.assertAllClose(restored_f(params, x).numpy(), res_tf.numpy())\n+\n+ # Gradients for the converted function\n+ params_v = tf.nest.map_structure(tf.Variable, params)\n+ with tf.GradientTape() as tape:\n+ res = f_tf(params_v, x)\n+ loss = tf.reduce_sum(res)\n+ g_tf = tape.gradient(loss, params_v)\n+\n+ params_v = tf.nest.map_structure(tf.Variable, params)\n+ with tf.GradientTape() as tape:\n+ res = restored_f(params_v, x)\n+ loss = tf.reduce_sum(res)\n+ g_restored_f = tape.gradient(loss, params_v)\n+\n+ self.assertAllClose(g_tf[\"w\"].numpy(), g_restored_f[\"w\"].numpy())\n+ self.assertAllClose(g_tf[\"b\"].numpy(), g_restored_f[\"b\"].numpy())\n+\n+\ndef test_xla_context_preserved_slice(self):\narr = np.arange(10, dtype=np.float32)\ndef f_jax(arr):\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Added a test for SavedModel with pytrees This was in response to an external user running into problems with converting and saving a SavedModel for a function where one of the arguments is a dict. This test demonstrates that this works, both for the conversion, and for the saving/restoring.
260,510
02.06.2022 11:54:58
25,200
426c7356fb326262de6424fcfade546e30a50f72
Guard `has_explicit_device` with xla_client version
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -63,6 +63,7 @@ from jax._src.lib import jax_jit\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\nfrom jax._src.lib import pmap_lib\n+from jax._src.lib import xla_extension_version\nfrom jax._src.traceback_util import api_boundary\nfrom jax._src.tree_util import broadcast_prefix\nfrom jax._src.util import (unzip2, curry, safe_map, safe_zip, prod, split_list,\n@@ -567,6 +568,10 @@ def _cpp_jit(\nreturn _BackendAndDeviceInfo(default_device, committed_to_device)\n+ jitted_f_kwargs = {}\n+ if xla_extension_version >= 71:\n+ jitted_f_kwargs[\"has_explicit_device\"] = (\n+ device is not None or backend is not None)\ncpp_jitted_f = jax_jit.jit(\nfun,\ncache_miss,\n@@ -575,7 +580,7 @@ def _cpp_jit(\nstatic_argnames=static_argnames,\ndonate_argnums=donate_argnums,\ncache=_cpp_jit_cache,\n- has_explicit_device=device is not None or backend is not None)\n+ **jitted_f_kwargs) # type: ignore\nf_jitted = wraps(fun)(cpp_jitted_f)\nf_jitted.lower = _jit_lower(fun, static_argnums, static_argnames, device,\n" } ]
Python
Apache License 2.0
google/jax
Guard `has_explicit_device` with xla_client version
260,314
03.06.2022 17:11:09
-25,200
3ca0d3f149ac8802eccbf04fd500543c80f96da1
Rename mesh into Mesh in xmap tutorial and doc
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/xmap_tutorial.ipynb", "new_path": "docs/notebooks/xmap_tutorial.ipynb", "diff": "\"source\": [\n\"import jax\\n\",\n\"import numpy as np\\n\",\n- \"from jax.experimental.maps import mesh\\n\",\n+ \"from jax.experimental.maps import Mesh\\n\",\n\"\\n\",\n\"loss = xmap(named_loss, in_axes=in_axes, out_axes=[...],\\n\",\n\" axis_resources={'batch': 'x'})\\n\",\n\"\\n\",\n\"devices = np.array(jax.local_devices())\\n\",\n- \"with mesh(devices, ('x',)):\\n\",\n+ \"with Mesh(devices, ('x',)):\\n\",\n\" print(loss(w1, w2, images, labels))\"\n]\n},\n\" axis_resources={'hidden': 'x'})\\n\",\n\"\\n\",\n\"devices = np.array(jax.local_devices())\\n\",\n- \"with mesh(devices, ('x',)):\\n\",\n+ \"with Mesh(devices, ('x',)):\\n\",\n\" print(loss(w1, w2, images, labels))\"\n]\n},\n\" axis_resources={'batch': 'x', 'hidden': 'y'})\\n\",\n\"\\n\",\n\"devices = np.array(jax.local_devices()).reshape((4, 2))\\n\",\n- \"with mesh(devices, ('x', 'y')):\\n\",\n+ \"with Mesh(devices, ('x', 'y')):\\n\",\n\" print(loss(w1, w2, images, labels))\"\n]\n},\n\"id\": \"KHbRwYl0BOr1\"\n},\n\"source\": [\n- \"To introduce the resources in a scope, use the `with mesh` context manager:\"\n+ \"To introduce the resources in a scope, use the `with Mesh` context manager:\"\n]\n},\n{\n},\n\"outputs\": [],\n\"source\": [\n- \"from jax.experimental.maps import mesh\\n\",\n+ \"from jax.experimental.maps import Mesh\\n\",\n\"\\n\",\n\"local = local_matmul(x, x) # The local function doesn't require the mesh definition\\n\",\n- \"with mesh(*mesh_def): # Makes the mesh axis names available as resources\\n\",\n+ \"with Mesh(*mesh_def): # Makes the mesh axis names available as resources\\n\",\n\" distr = distr_matmul(x, x)\\n\",\n\"np.testing.assert_allclose(local, distr)\"\n]\n\"\\n\",\n\"q = jnp.ones((4,), dtype=np.float32)\\n\",\n\"u = jnp.ones((12,), dtype=np.float32)\\n\",\n- \"with mesh(np.array(jax.devices()[:4]), ('x',)):\\n\",\n+ \"with Mesh(np.array(jax.devices()[:4]), ('x',)):\\n\",\n\" v = xmap(sum_two_args,\\n\",\n\" in_axes=(['a', ...], ['b', ...]),\\n\",\n\" out_axes=[...],\\n\",\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/xmap_tutorial.md", "new_path": "docs/notebooks/xmap_tutorial.md", "diff": "@@ -120,13 +120,13 @@ But on a whim we can decide to parallelize over the batch axis:\nimport jax\nimport numpy as np\n-from jax.experimental.maps import mesh\n+from jax.experimental.maps import Mesh\nloss = xmap(named_loss, in_axes=in_axes, out_axes=[...],\naxis_resources={'batch': 'x'})\ndevices = np.array(jax.local_devices())\n-with mesh(devices, ('x',)):\n+with Mesh(devices, ('x',)):\nprint(loss(w1, w2, images, labels))\n```\n@@ -141,7 +141,7 @@ loss = xmap(named_loss, in_axes=in_axes, out_axes=[...],\naxis_resources={'hidden': 'x'})\ndevices = np.array(jax.local_devices())\n-with mesh(devices, ('x',)):\n+with Mesh(devices, ('x',)):\nprint(loss(w1, w2, images, labels))\n```\n@@ -156,7 +156,7 @@ loss = xmap(named_loss, in_axes=in_axes, out_axes=[...],\naxis_resources={'batch': 'x', 'hidden': 'y'})\ndevices = np.array(jax.local_devices()).reshape((4, 2))\n-with mesh(devices, ('x', 'y')):\n+with Mesh(devices, ('x', 'y')):\nprint(loss(w1, w2, images, labels))\n```\n@@ -531,15 +531,15 @@ except Exception as e:\n+++ {\"id\": \"KHbRwYl0BOr1\"}\n-To introduce the resources in a scope, use the `with mesh` context manager:\n+To introduce the resources in a scope, use the `with Mesh` context manager:\n```{code-cell} ipython3\n:id: kYdoeaSS9m9f\n-from jax.experimental.maps import mesh\n+from jax.experimental.maps import Mesh\nlocal = local_matmul(x, x) # The local function doesn't require the mesh definition\n-with mesh(*mesh_def): # Makes the mesh axis names available as resources\n+with Mesh(*mesh_def): # Makes the mesh axis names available as resources\ndistr = distr_matmul(x, x)\nnp.testing.assert_allclose(local, distr)\n```\n@@ -580,7 +580,7 @@ def sum_two_args(x: f32[(), {'a': 4}], y: f32[(), {'b': 12}]) -> f32[()]:\nq = jnp.ones((4,), dtype=np.float32)\nu = jnp.ones((12,), dtype=np.float32)\n-with mesh(np.array(jax.devices()[:4]), ('x',)):\n+with Mesh(np.array(jax.devices()[:4]), ('x',)):\nv = xmap(sum_two_args,\nin_axes=(['a', ...], ['b', ...]),\nout_axes=[...],\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -154,7 +154,7 @@ class SerialLoop:\ndef serial_loop(name: ResourceAxisName, length: int):\n\"\"\"Define a serial loop resource to be available in scope of this context manager.\n- This is similar to :py:func:`mesh` in that it extends the resource\n+ This is similar to :py:class:`Mesh` in that it extends the resource\nenvironment with a resource called ``name``. But, any use of this resource\naxis in ``axis_resources`` argument of :py:func:`xmap` will cause the\nbody of :py:func:`xmap` to get executed ``length`` times with each execution\n@@ -330,7 +330,7 @@ def xmap(fun: Callable,\n:py:func:`vmap`. However, this behavior can be further customized by the\n``axis_resources`` argument. When specified, each axis introduced by\n:py:func:`xmap` can be assigned to one or more *resource axes*. Those include\n- the axes of the hardware mesh, as defined by the :py:func:`mesh` context\n+ the axes of the hardware mesh, as defined by the :py:class:`Mesh` context\nmanager. Each value that has a named axis in its ``named_shape`` will be\npartitioned over all mesh axes that axis is assigned to. Hence,\n:py:func:`xmap` can be seen as an alternative to :py:func:`pmap` that also\n@@ -423,7 +423,7 @@ def xmap(fun: Callable,\nto implement a distributed matrix-multiplication in just a few lines of code::\ndevices = np.array(jax.devices())[:4].reshape((2, 2))\n- with mesh(devices, ('x', 'y')): # declare a 2D mesh with axes 'x' and 'y'\n+ with Mesh(devices, ('x', 'y')): # declare a 2D mesh with axes 'x' and 'y'\ndistributed_out = xmap(\njnp.vdot,\nin_axes=({0: 'left'}, {1: 'right'}),\n" } ]
Python
Apache License 2.0
google/jax
Rename mesh into Mesh in xmap tutorial and doc
260,447
03.06.2022 10:33:40
25,200
7ab70338af7d57a99a7591ac9ca1523351cd7e17
[sparse] Add `unique_indices` to BCOO.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcoo.py", "new_path": "jax/experimental/sparse/bcoo.py", "diff": "@@ -100,7 +100,9 @@ def _bcoo_set_nse(mat, nse):\nindices = jnp.zeros_like(mat.indices, shape=(*mat.indices.shape[:-2], nse, mat.indices.shape[-1]))\nindices = indices.at[..., :mat.nse, :].set(mat.indices)\nindices = indices.at[..., mat.nse:, :].set(jnp.array(mat.shape[mat.n_batch:mat.n_batch + mat.n_sparse]))\n- return BCOO((data, indices), shape=mat.shape, indices_sorted=mat.indices_sorted)\n+ return BCOO((data, indices), shape=mat.shape,\n+ indices_sorted=mat.indices_sorted,\n+ unique_indices=mat.unique_indices)\n# TODO(jakevdp) this can be problematic when used with autodiff; see\n# https://github.com/google/jax/issues/10163. Should this be a primitive?\n@@ -132,6 +134,7 @@ class BCOOProperties(NamedTuple):\nclass BCOOInfo(NamedTuple):\nshape: Shape\nindices_sorted: bool = False\n+ unique_indices: bool = False\ndef _validate_bcoo(data: jnp.ndarray, indices: jnp.ndarray, shape: Sequence[int]) -> BCOOProperties:\nprops = _validate_bcoo_indices(indices, shape)\n@@ -238,7 +241,9 @@ def _bcoo_todense_batching_rule(batched_args, batch_dims, *, spinfo):\nif batch_dims[1] is None:\nindices = indices[None, ...]\nnew_spinfo = BCOOInfo(\n- shape=(max(data.shape[0], indices.shape[0]), *spinfo.shape))\n+ shape=(max(data.shape[0], indices.shape[0]), *spinfo.shape),\n+ indices_sorted=spinfo.indices_sorted,\n+ unique_indices=spinfo.unique_indices)\nreturn _bcoo_todense(data, indices, spinfo=new_spinfo), 0\nad.defjvp(bcoo_todense_p, _bcoo_todense_jvp, None)\n@@ -278,7 +283,7 @@ def bcoo_fromdense(mat, *, nse=None, n_batch=0, n_dense=0, index_dtype=jnp.int32\nnse = core.concrete_or_error(operator.index, nse, _TRACED_NSE_ERROR)\nreturn BCOO(_bcoo_fromdense(mat, nse=nse, n_batch=n_batch, n_dense=n_dense,\nindex_dtype=index_dtype),\n- shape=mat.shape, indices_sorted=True)\n+ shape=mat.shape, indices_sorted=True, unique_indices=True)\ndef _bcoo_fromdense(mat, *, nse, n_batch=0, n_dense=0, index_dtype=jnp.int32):\n\"\"\"Create BCOO-format sparse matrix from a dense matrix.\n@@ -475,7 +480,7 @@ def bcoo_transpose(mat, *, permutation: Sequence[int]):\nA BCOO-format array.\n\"\"\"\nreturn BCOO(_bcoo_transpose(mat.data, mat.indices, permutation=permutation, spinfo=mat._info),\n- shape=mat._info.shape)\n+ shape=mat._info.shape, unique_indices=mat.unique_indices)\ndef _bcoo_transpose(data, indices, *, permutation: Sequence[int], spinfo: BCOOInfo):\npermutation = tuple(permutation)\n@@ -1223,7 +1228,7 @@ bcoo_sort_indices_p = core.Primitive(\"bcoo_sort_indices\")\nbcoo_sort_indices_p.multiple_results = True\ndef bcoo_sort_indices(mat):\n- \"\"\"Sort indices of a BCOO array, and optionally sum duplicates & eliminate zeros.\n+ \"\"\"Sort indices of a BCOO array.\nArgs:\nmat : BCOO array\n@@ -1232,7 +1237,8 @@ def bcoo_sort_indices(mat):\nmat_out : BCOO array with sorted indices.\n\"\"\"\ndata, indices = bcoo_sort_indices_p.bind(*mat._bufs, spinfo=mat._info)\n- return BCOO((data, indices), shape=mat.shape, indices_sorted=True)\n+ return BCOO((data, indices), shape=mat.shape, indices_sorted=True,\n+ unique_indices=mat.unique_indices)\n@bcoo_sort_indices_p.def_impl\ndef _bcoo_sort_indices_impl(data, indices, *, spinfo):\n@@ -1335,7 +1341,8 @@ def bcoo_sum_duplicates(mat, nse=None):\nmat_out : BCOO array with sorted indices and no duplicate indices.\n\"\"\"\ndata, indices = _bcoo_sum_duplicates(mat.data, mat.indices, spinfo=mat._info, nse=nse)\n- return BCOO((data, indices), shape=mat.shape, indices_sorted=True)\n+ return BCOO((data, indices), shape=mat.shape, indices_sorted=True,\n+ unique_indices=True)\ndef _bcoo_sum_duplicates(data, indices, *, spinfo, nse):\nif nse is not None:\n@@ -2043,14 +2050,18 @@ class BCOO(JAXSparse):\nn_sparse = property(lambda self: self.indices.shape[-1])\nn_dense = property(lambda self: self.data.ndim - 1 - self.n_batch)\nindices_sorted: bool\n- _info = property(lambda self: BCOOInfo(self.shape, self.indices_sorted))\n+ unique_indices: bool\n+ _info = property(lambda self: BCOOInfo(self.shape, self.indices_sorted,\n+ self.unique_indices))\n_bufs = property(lambda self: (self.data, self.indices))\n- def __init__(self, args, *, shape, indices_sorted=False):\n+ def __init__(self, args, *, shape, indices_sorted=False,\n+ unique_indices=False):\n# JAX transforms will sometimes instantiate pytrees with null values, so we\n# must catch that in the initialization of inputs.\nself.data, self.indices = _safe_asarray(args)\nself.indices_sorted = indices_sorted\n+ self.unique_indices = unique_indices\nsuper().__init__(args, shape=shape)\ndef __repr__(self):\n@@ -2088,8 +2099,9 @@ class BCOO(JAXSparse):\ndata = jnp.asarray(mat.data)\nindices = jnp.column_stack((mat.row, mat.col)).astype(\nindex_dtype or jnp.int32)\n- # TODO: determines sorted indices for scipy conversion.\n- return cls((data, indices), shape=mat.shape, indices_sorted=False)\n+ # TODO: determines sorted and unique indices for scipy conversion.\n+ return cls((data, indices), shape=mat.shape, indices_sorted=False,\n+ unique_indices=False)\n@classmethod\ndef _empty(cls, shape, *, dtype=None, index_dtype='int32', n_dense=0, n_batch=0, nse=0):\n@@ -2101,7 +2113,8 @@ class BCOO(JAXSparse):\nbatch_shape, sparse_shape, dense_shape = split_list(shape, [n_batch, n_sparse])\ndata = jnp.zeros((*batch_shape, nse, *dense_shape), dtype)\nindices = jnp.full((*batch_shape, nse, n_sparse), jnp.array(sparse_shape), index_dtype)\n- return cls((data, indices), shape=shape, indices_sorted=True)\n+ return cls((data, indices), shape=shape, indices_sorted=True,\n+ unique_indices=True)\n@classmethod\ndef _eye(cls, N, M, k, *, dtype=None, index_dtype='int32', n_batch=0, n_dense=0):\n@@ -2145,7 +2158,8 @@ class BCOO(JAXSparse):\nindices = indices.at[M - abs(k)].set(M)\ndata = data[:, None]\nindices = indices[:, None, None]\n- return cls((data, indices), shape=(N, M), indices_sorted=True)\n+ return cls((data, indices), shape=(N, M), indices_sorted=True,\n+ unique_indices=True)\ndef _dedupe(self):\nwarnings.warn(\"_dedupe() is deprecated. Use sum_duplicates() instead.\", FutureWarning)\n@@ -2225,7 +2239,7 @@ class BCOO(JAXSparse):\n# possibly use permutation?\nis_sorted = False\nreturn BCOO((mat_T.data, mat_T.indices), shape=shape_T,\n- indices_sorted=is_sorted)\n+ indices_sorted=is_sorted, unique_indices=self.unique_indices)\ndef tree_flatten(self):\nreturn (self.data, self.indices), self._info._asdict()\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -796,17 +796,24 @@ class BCOOTest(jtu.JaxTestCase):\nself.assertEqual(j1.shape, data.shape + M.shape)\nself.assertEqual(hess.shape, data.shape + 2 * M.shape)\n- def test_bcoo_fromdense_indices_sorted(self):\n+ def test_bcoo_fromdense_sorted_and_unique_indices(self):\nrng = self.rng()\nrng_sparse = rand_sparse(rng)\nmat = sparse.BCOO.fromdense(rng_sparse((5, 6), np.float32))\nperm = rng.permutation(mat.nse)\nmat_unsorted = sparse.BCOO((mat.data[perm], mat.indices[perm]),\n- shape=mat.shape)\n+ shape=mat.shape,\n+ unique_indices=mat.unique_indices)\nmat_resorted = mat_unsorted.sort_indices()\n+ with self.subTest('sorted indices'):\nself.assertArraysEqual(mat.indices, mat_resorted.indices)\nself.assertArraysEqual(mat.data, mat_resorted.data)\n+ with self.subTest('unique indices'):\n+ self.assertTrue(mat.unique_indices)\n+ self.assertTrue(mat_unsorted.unique_indices)\n+ self.assertTrue(mat_resorted.unique_indices)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_nbatch={}_ndense={}\".format(\njtu.format_shape_dtype_string(shape, dtype), n_batch, n_dense),\n@@ -1637,6 +1644,8 @@ class BCOOTest(jtu.JaxTestCase):\nself.assertAllClose(M.todense(), M_dedup.todense())\nself.assertEqual(M_dedup.nse, nse)\n+ self.assertTrue(M_dedup.unique_indices)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_nbatch={}_ndense={}_nse={}\".format(\njtu.format_shape_dtype_string(shape, dtype), n_batch, n_dense, nse),\n@@ -1687,6 +1696,7 @@ class BCOOTest(jtu.JaxTestCase):\nM_sorted = M.sort_indices()\nself.assertArraysEqual(M.todense(), M_sorted.todense())\n+ self.assertEqual(M.unique_indices, M_sorted.unique_indices)\nindices = M_sorted.indices\nif indices.size > 0:\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Add `unique_indices` to BCOO. PiperOrigin-RevId: 452794860
260,453
03.06.2022 15:11:29
14,400
ca83a80f9596263a5639ccfc6ce82e77e72de458
Added random.generalized_normal and random.ball.
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -38,6 +38,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Changed the semantics of {func}`jax.profiler.start_server(...)` to store the\nkeepalive globally, rather than requiring the user to keep a reference to\nit.\n+ * Added {func}`jax.random.generalized_normal`.\n+ * Added {func}`jax.random.ball`.\n## jaxlib 0.3.11 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jaxlib-v0.3.10...main).\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.random.rst", "new_path": "docs/jax.random.rst", "diff": "@@ -16,6 +16,7 @@ List of Available Functions\n:toctree: _autosummary\nPRNGKey\n+ ball\nbernoulli\nbeta\ncategorical\n@@ -26,6 +27,7 @@ List of Available Functions\nexponential\nfold_in\ngamma\n+ generalized_normal\ngumbel\nlaplace\nloggamma\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/random.py", "new_path": "jax/_src/random.py", "diff": "@@ -1623,3 +1623,56 @@ def orthogonal(\nq, r = jnp.linalg.qr(z)\nd = jnp.diagonal(r, 0, -2, -1)\nreturn lax.mul(q, lax.expand_dims(lax.div(d, abs(d).astype(d.dtype)), [-2]))\n+\n+def generalized_normal(\n+ key: KeyArray,\n+ p: float,\n+ shape: Sequence[int] = (),\n+ dtype: DTypeLikeFloat = dtypes.float_\n+) -> jnp.ndarray:\n+ \"\"\"Sample from the generalized normal distribution.\n+\n+ Args:\n+ key: a PRNG key used as the random key.\n+ p: a float representing the shape parameter.\n+ shape: optional, the batch dimensions of the result. Default ().\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ _check_shape(\"generalized_normal\", shape)\n+ keys = split(key)\n+ g = gamma(keys[0], 1/p, shape, dtype)\n+ r = rademacher(keys[1], shape, dtype)\n+ return r * g ** (1 / p)\n+\n+def ball(\n+ key: KeyArray,\n+ d: int,\n+ p: float = 2,\n+ shape: Sequence[int] = (),\n+ dtype: DTypeLikeFloat = dtypes.float_\n+):\n+ \"\"\"Sample uniformly from the unit Lp ball.\n+\n+ Reference: https://arxiv.org/abs/math/0503650.\n+\n+ Args:\n+ key: a PRNG key used as the random key.\n+ d: a nonnegative int representing the dimensionality of the ball.\n+ p: a float representing the p parameter of the Lp norm.\n+ shape: optional, the batch dimensions of the result. Default ().\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\n+\n+ Returns:\n+ A random array of shape `(*shape, d)` and specified dtype.\n+ \"\"\"\n+ _check_shape(\"ball\", shape)\n+ d = core.concrete_or_error(index, d, \"The error occurred in jax.random.ball()\")\n+ keys = split(key)\n+ g = generalized_normal(keys[0], p, (*shape, d), dtype)\n+ e = exponential(keys[1], shape, dtype)\n+ return g / (((jnp.abs(g) ** p).sum(-1) + e) ** (1 / p))[..., None]\n" }, { "change_type": "MODIFY", "old_path": "jax/random.py", "new_path": "jax/random.py", "diff": "@@ -125,6 +125,7 @@ KeyArray = PRNGKeyArray\nfrom jax._src.random import (\nPRNGKey as PRNGKey,\n+ ball as ball,\nbernoulli as bernoulli,\nbeta as beta,\ncategorical as categorical,\n@@ -136,6 +137,7 @@ from jax._src.random import (\nexponential as exponential,\nfold_in as fold_in,\ngamma as gamma,\n+ generalized_normal as generalized_normal,\ngumbel as gumbel,\nlaplace as laplace,\nlogistic as logistic,\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -1056,6 +1056,50 @@ class LaxRandomTest(jtu.JaxTestCase):\natol=tol, rtol=tol,\n)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_p={}_shape={}\"\\\n+ .format(p, jtu.format_shape_dtype_string(shape, dtype)),\n+ \"p\": p,\n+ \"shape\": shape,\n+ \"dtype\": dtype}\n+ for p in [.5, 1., 1.5, 2., 2.5]\n+ for shape in [(), (5,), (10, 5)]\n+ for dtype in jtu.dtypes.floating))\n+ def testGeneralizedNormal(self, p, shape, dtype):\n+ key = self.seed_prng(0)\n+ rand = lambda key, p: random.generalized_normal(key, p, shape, dtype)\n+ crand = jax.jit(rand)\n+ uncompiled_samples = rand(key, p)\n+ compiled_samples = crand(key, p)\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ self.assertEqual(samples.shape, shape)\n+ self.assertEqual(samples.dtype, dtype)\n+ self._CheckKolmogorovSmirnovCDF(samples.ravel(), scipy.stats.gennorm(p).cdf)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_d={}_p={}_shape={}\"\\\n+ .format(d, p, jtu.format_shape_dtype_string(shape, dtype)),\n+ \"d\": d,\n+ \"p\": p,\n+ \"shape\": shape,\n+ \"dtype\": dtype}\n+ for d in range(1, 5)\n+ for p in [.5, 1., 1.5, 2., 2.5]\n+ for shape in [(), (5,), (10, 5)]\n+ for dtype in jtu.dtypes.floating))\n+ def testBall(self, d, p, shape, dtype):\n+ key = self.seed_prng(0)\n+ rand = lambda key, p: random.ball(key, d, p, shape, dtype)\n+ crand = jax.jit(rand)\n+ uncompiled_samples = rand(key, p)\n+ compiled_samples = crand(key, p)\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ self.assertEqual(samples.shape, (*shape, d))\n+ self.assertEqual(samples.dtype, dtype)\n+ self.assertTrue(((jnp.abs(samples) ** p).sum(-1) <= 1).all())\n+ norms = (jnp.abs(samples) ** p).sum(-1) ** (d / p)\n+ self._CheckKolmogorovSmirnovCDF(norms.ravel(), scipy.stats.uniform().cdf)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": f\"_b={b}_dtype={np.dtype(dtype).name}\",\n\"b\": b, \"dtype\": dtype}\n" } ]
Python
Apache License 2.0
google/jax
Added random.generalized_normal and random.ball.
260,447
03.06.2022 14:50:44
25,200
cc4f2ade632d2985cd470ab30e1f2cfe3b01105f
[sparse] Track `unique_indices` in sparse transform.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/transform.py", "new_path": "jax/experimental/sparse/transform.py", "diff": "@@ -154,7 +154,8 @@ class SparsifyEnv:\nreturn SparsifyValue(np.shape(data), self._push(data), None)\ndef sparse(self, shape, data=None, indices=None,\n- *, data_ref=None, indices_ref=None, indices_sorted=False):\n+ *, data_ref=None, indices_ref=None, indices_sorted=False,\n+ unique_indices=False):\n\"\"\"Add a new sparse array to the sparsify environment.\"\"\"\nif data is not None:\nassert data_ref is None\n@@ -168,7 +169,8 @@ class SparsifyEnv:\nelse:\nassert indices_ref is not None and indices_ref < len(self._buffers)\n- return SparsifyValue(shape, data_ref, indices_ref, indices_sorted)\n+ return SparsifyValue(shape, data_ref, indices_ref, indices_sorted,\n+ unique_indices)\nclass SparsifyValue(NamedTuple):\n@@ -176,6 +178,7 @@ class SparsifyValue(NamedTuple):\ndata_ref: Optional[int]\nindices_ref: Optional[int]\nindices_sorted: Optional[bool] = False\n+ unique_indices: Optional[bool] = False\n@property\ndef ndim(self):\n@@ -197,7 +200,8 @@ def arrays_to_spvalues(\ndef array_to_spvalue(arg):\nif isinstance(arg, BCOO):\nreturn spenv.sparse(arg.shape, arg.data, arg.indices,\n- indices_sorted=arg.indices_sorted)\n+ indices_sorted=arg.indices_sorted,\n+ unique_indices=arg.unique_indices)\nelse:\nreturn spenv.dense(arg)\nreturn tree_map(array_to_spvalue, args, is_leaf=_is_bcoo)\n@@ -212,7 +216,8 @@ def spvalues_to_arrays(\nif spvalue.is_sparse():\nassert spvalue.indices_ref is not None\nreturn BCOO((spenv.data(spvalue), spenv.indices(spvalue)),\n- shape=spvalue.shape, indices_sorted=spvalue.indices_sorted)\n+ shape=spvalue.shape, indices_sorted=spvalue.indices_sorted,\n+ unique_indices=spvalue.unique_indices)\nelse:\nreturn spenv.data(spvalue)\nreturn tree_map(spvalue_to_array, spvalues, is_leaf=_is_spvalue)\n@@ -456,7 +461,8 @@ def _zero_preserving_unary_op(prim):\nif spvalues[0].is_sparse():\nout_spvalue = spenv.sparse(spvalues[0].shape, buf_out,\nindices_ref=spvalues[0].indices_ref,\n- indices_sorted=spvalues[0].indices_sorted)\n+ indices_sorted=spvalues[0].indices_sorted,\n+ unique_indices=spvalues[0].unique_indices)\nelse:\nout_spvalue = spenv.dense(buf)\nreturn (out_spvalue,)\n@@ -480,9 +486,7 @@ def _transpose_sparse(spenv, *spvalues, permutation):\npermutation = tuple(permutation)\nargs = spvalues_to_arrays(spenv, spvalues)\nshape = args[0].shape\n- mat = sparse.BCOO((args[0].data, args[0].indices), shape=shape,\n- indices_sorted=args[0].indices_sorted)\n- mat_transposed = sparse.bcoo_transpose(mat, permutation=permutation)\n+ mat_transposed = sparse.bcoo_transpose(args[0], permutation=permutation)\nout_shape = tuple(shape[i] for i in permutation)\nn_batch = args[0].indices.ndim - 2\n@@ -505,6 +509,7 @@ def _transpose_sparse(spenv, *spvalues, permutation):\nkwds['indices'] = mat_transposed.indices\nkwds['indices_sorted'] = mat_transposed.indices_sorted\n+ kwds['unique_indices'] = mat_transposed.unique_indices\nspvalue = spenv.sparse(out_shape, **kwds)\nreturn (spvalue,)\n@@ -519,8 +524,10 @@ def _add_sparse(spenv, *spvalues):\nout_data = lax.add(spenv.data(X), spenv.data(Y))\nif config.jax_enable_checks:\nassert X.indices_sorted == Y.indices_sorted\n+ assert X.unique_indices == Y.unique_indices\nout_spvalue = spenv.sparse(X.shape, out_data, indices_ref=X.indices_ref,\n- indices_sorted=X.indices_sorted)\n+ indices_sorted=X.indices_sorted,\n+ unique_indices=X.unique_indices)\nelif spenv.indices(X).ndim != spenv.indices(Y).ndim or spenv.data(X).ndim != spenv.data(Y).ndim:\nraise NotImplementedError(\"Addition between sparse matrices with different batch/dense dimensions.\")\nelse:\n@@ -546,13 +553,14 @@ sparse_rules[lax.sub_p] = _sub_sparse\ndef _mul_sparse(spenv, *spvalues):\nX, Y = spvalues\nif X.is_sparse() and Y.is_sparse():\n- if X.indices_ref == Y.indices_ref:\n- # TODO(jakevdp): this is inaccurate if there are duplicate indices\n- out_data = lax.mul(spenv.data(X), spenv.data(Y))\n+ if X.indices_ref == Y.indices_ref and X.unique_indices:\nif config.jax_enable_checks:\nassert X.indices_sorted == Y.indices_sorted\n+ assert X.unique_indices == Y.unique_indices\n+ out_data = lax.mul(spenv.data(X), spenv.data(Y))\nout_spvalue = spenv.sparse(X.shape, out_data, indices_ref=X.indices_ref,\n- indices_sorted=X.indices_sorted)\n+ indices_sorted=X.indices_sorted,\n+ unique_indices=True)\nelse:\nX_promoted, Y_promoted = spvalues_to_arrays(spenv, spvalues)\nmat = bcoo_multiply_sparse(X_promoted, Y_promoted)\n@@ -563,7 +571,8 @@ def _mul_sparse(spenv, *spvalues):\nX_promoted = spvalues_to_arrays(spenv, X)\nout_data = bcoo_multiply_dense(X_promoted, spenv.data(Y))\nout_spvalue = spenv.sparse(X.shape, out_data, indices_ref=X.indices_ref,\n- indices_sorted=X.indices_sorted)\n+ indices_sorted=X.indices_sorted,\n+ unique_indices=X.unique_indices)\nreturn (out_spvalue,)\n@@ -683,12 +692,10 @@ def _xla_call_sparse(spenv, *spvalues, call_jaxpr, donated_invars, **params):\nsparse_rules[xla.xla_call_p] = _xla_call_sparse\n-\ndef _duplicate_for_sparse_spvalues(spvalues, params):\nfor spvalue, param in safe_zip(spvalues, params):\nyield from [param, param] if spvalue.is_sparse() else [param]\n-\ndef _scan_sparse(spenv, *spvalues, jaxpr, num_consts, num_carry, **params):\nconst_spvalues, carry_spvalues, xs_spvalues = split_list(\nspvalues, [num_consts, num_carry])\n@@ -734,9 +741,7 @@ sparse_rules[lax.cond_p] = _cond_sparse\ndef _todense_sparse_rule(spenv, spvalue, *, tree):\ndel tree # TODO(jakvdp): we should assert that tree is PytreeDef(*)\n- out = sparse.BCOO((spenv.data(spvalue), spenv.indices(spvalue)),\n- shape=spvalue.shape,\n- indices_sorted=spvalue.indices_sorted).todense()\n+ out = spvalues_to_arrays(spenv, spvalue).todense()\nreturn (spenv.dense(out),)\nsparse_rules[sparse.todense_p] = _todense_sparse_rule\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Track `unique_indices` in sparse transform. PiperOrigin-RevId: 452848200
260,510
02.06.2022 22:15:53
25,200
143ed40a7814ca78d4b8f9e3370254d562cff1e8
Add collect_profile script
[ { "change_type": "MODIFY", "old_path": ".github/workflows/ci-build.yaml", "new_path": ".github/workflows/ci-build.yaml", "diff": "@@ -147,4 +147,4 @@ jobs:\nXLA_FLAGS: \"--xla_force_host_platform_device_count=8\"\nrun: |\npytest -n 1 --tb=short docs\n- pytest -n 1 --tb=short --doctest-modules jax --ignore=jax/experimental/jax2tf --ignore=jax/_src/lib/mlir --ignore=jax/interpreters/mlir.py --ignore=jax/_src/iree.py --ignore=jax/experimental/gda_serialization\n+ pytest -n 1 --tb=short --doctest-modules jax --ignore=jax/experimental/jax2tf --ignore=jax/_src/lib/mlir --ignore=jax/interpreters/mlir.py --ignore=jax/_src/iree.py --ignore=jax/experimental/gda_serialization --ignore=jax/collect_profile.py\n" }, { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -40,6 +40,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\nit.\n* Added {func}`jax.random.generalized_normal`.\n* Added {func}`jax.random.ball`.\n+ * Added a `python -m jax.collect_profile` script to manually capture program\n+ traces as an alternative to the Tensorboard UI.\n## jaxlib 0.3.11 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jaxlib-v0.3.10...main).\n" }, { "change_type": "MODIFY", "old_path": "docs/profiling.md", "new_path": "docs/profiling.md", "diff": "@@ -41,6 +41,29 @@ or if you're using Google Cloud:\n$ gcloud compute ssh <machine-name> -- -L 9001:127.0.0.1:9001\n```\n+### Manual capture\n+\n+Instead of capturing traces programmatically using `jax.profiler.trace`, you can\n+instead start a profiling server in the script of interest by calling\n+`jax.profiler.start_server(<port>)`. If you only need the profiler server to be\n+active for a portion of your script, you can shut it down by calling\n+`jax.profiler.stop_server()`.\n+\n+Once the script is running and after the profiler server has started, we can\n+manually capture an trace by running:\n+```bash\n+$ python -m jax.collect_profile <port> <duration_in_ms>\n+```\n+\n+By default, the resulting trace information is dumped into a temporary directory\n+but this can be overridden by passing in `--log_dir=<directory of choice>`.\n+Also, by default, the program will prompt you to open a link to\n+`ui.perfetto.dev`. When you open the link, the Perfetto UI will load the trace\n+file and open a visualizer. This feature is disabled by passing in\n+`--no_perfetto_link` into the command. Alternatively, you can also point\n+Tensorboard to the `log_dir` to analyze the trace (see the\n+\"Tensorboard Profiling\" section below).\n+\n## TensorBoard profiling\n[TensorBoard's\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/collect_profile.py", "diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+import argparse\n+import gzip\n+import os\n+import pathlib\n+import tempfile\n+\n+from typing import Optional\n+\n+# pytype: disable=import-error\n+import jax\n+try:\n+ from tensorflow.python.profiler import profiler_v2 as profiler\n+ from tensorflow.python.profiler import profiler_client\n+except ImportError:\n+ raise ImportError(\"This script requires `tensorflow` to be installed.\")\n+try:\n+ from tensorboard_plugin_profile.convert import raw_to_tool_data as convert\n+except ImportError:\n+ raise ImportError(\n+ \"This script requires `tensorboard_plugin_profile` to be installed.\")\n+# pytype: enable=import-error\n+\n+\n+_DESCRIPTION = \"\"\"\n+To profile running JAX programs, you first need to start the profiler server\n+in the program of interest. You can do this via\n+`jax.profiler.start_server(<port>)`. Once the program is running and the\n+profiler server has started, you can run `collect_profile` to trace the execution\n+for a provided duration. The trace file will be dumped into a directory\n+(determined by `--log_dir`) and by default, a Perfetto UI link will be generated\n+to view the resulting trace.\n+\"\"\"\n+parser = argparse.ArgumentParser(description=_DESCRIPTION)\n+parser.add_argument(\"--log_dir\", default=None,\n+ help=(\"Directory to store log files. \"\n+ \"Uses a temporary directory if none provided.\"),\n+ type=str)\n+parser.add_argument(\"port\", help=\"Port to collect trace\", type=int)\n+parser.add_argument(\"duration_in_ms\",\n+ help=\"Duration to collect trace in milliseconds\", type=int)\n+parser.add_argument(\"--no_perfetto_link\",\n+ help=\"Disable creating a perfetto link\",\n+ action=\"store_true\")\n+parser.add_argument(\"--host\", default=\"127.0.0.1\",\n+ help=\"Host to collect trace. Defaults to 127.0.0.1\",\n+ type=str)\n+parser.add_argument(\"--host_tracer_level\", default=2,\n+ help=\"Profiler host tracer level\", type=int)\n+parser.add_argument(\"--device_tracer_level\", default=1,\n+ help=\"Profiler device tracer level\", type=int)\n+parser.add_argument(\"--python_tracer_level\", default=1,\n+ help=\"Profiler Python tracer level\", type=int)\n+\n+def collect_profile(port: int, duration_in_ms: int, host: str,\n+ log_dir: Optional[str], host_tracer_level: int,\n+ device_tracer_level: int, python_tracer_level: int,\n+ no_perfetto_link: bool):\n+ options = profiler.ProfilerOptions(\n+ host_tracer_level=host_tracer_level,\n+ device_tracer_level=device_tracer_level,\n+ python_tracer_level=python_tracer_level,\n+ )\n+ log_dir_ = pathlib.Path(log_dir if log_dir is not None else tempfile.mkdtemp())\n+ profiler_client.trace(\n+ f\"{host}:{port}\",\n+ str(log_dir_),\n+ duration_in_ms,\n+ options=options)\n+ print(f\"Dumped profiling information in: {log_dir_}\")\n+ # The profiler dumps `xplane.pb` to the logging directory. To upload it to\n+ # the Perfetto trace viewer, we need to convert it to a `trace.json` file.\n+ # We do this by first finding the `xplane.pb` file, then passing it into\n+ # tensorflow_profile_plugin's `xplane` conversion function.\n+ curr_path = log_dir_.resolve()\n+ root_trace_folder = curr_path / \"plugins\" / \"profile\"\n+ trace_folders = [root_trace_folder / trace_folder for trace_folder\n+ in root_trace_folder.iterdir()]\n+ latest_folder = max(trace_folders, key=os.path.getmtime)\n+ xplane = next(latest_folder.glob(\"*.xplane.pb\"))\n+ result = convert.xspace_to_tool_data([xplane], \"trace_viewer^\", None)\n+\n+ with gzip.open(str(latest_folder / \"remote.trace.json.gz\"), \"wb\") as fp:\n+ fp.write(result.encode(\"utf-8\"))\n+\n+ if not no_perfetto_link:\n+ jax._src.profiler._host_perfetto_trace_file(str(log_dir_))\n+\n+def main(args):\n+ collect_profile(args.port, args.duration_in_ms, args.host, args.log_dir,\n+ args.host_tracer_level, args.device_tracer_level,\n+ args.python_tracer_level, args.no_perfetto_link)\n+\n+if __name__ == \"__main__\":\n+ main(parser.parse_args())\n" }, { "change_type": "MODIFY", "old_path": "tests/profiler_test.py", "new_path": "tests/profiler_test.py", "diff": "@@ -18,6 +18,7 @@ import os\nimport shutil\nimport tempfile\nimport threading\n+import time\nimport unittest\nfrom absl.testing import absltest\n@@ -39,6 +40,14 @@ except ImportError:\nprofiler_client = None\ntf_profiler = None\n+TBP_ENABLED = False\n+try:\n+ import tensorboard_plugin_profile\n+ del tensorboard_plugin_profile\n+ TBP_ENABLED = True\n+except ImportError:\n+ pass\n+\nconfig.parse_flags_with_absl()\n@@ -205,5 +214,32 @@ class ProfilerTest(unittest.TestCase):\nthread_worker.join(120)\nself._check_xspace_pb_exist(logdir)\n+ @unittest.skipIf(\n+ not (portpicker and profiler_client and tf_profiler and TBP_ENABLED),\n+ \"Test requires tensorflow.profiler, portpicker and \"\n+ \"tensorboard_profile_plugin\")\n+ def test_remote_profiler(self):\n+ port = portpicker.pick_unused_port()\n+\n+ logdir = absltest.get_default_test_tmpdir()\n+ # Remove any existing log files.\n+ shutil.rmtree(logdir, ignore_errors=True)\n+ def on_profile():\n+ os.system(\n+ f\"python -m jax.collect_profile {port} 500 --log_dir {logdir} \"\n+ \"--no_perfetto_link\")\n+\n+ thread_profiler = threading.Thread(\n+ target=on_profile, args=())\n+ thread_profiler.start()\n+ jax.profiler.start_server(port)\n+ start_time = time.time()\n+ y = jnp.zeros((5, 5))\n+ while time.time() - start_time < 3:\n+ y = jnp.dot(y, y)\n+ jax.profiler.stop_server()\n+ thread_profiler.join()\n+ self._check_xspace_pb_exist(logdir)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add collect_profile script
260,580
06.06.2022 15:24:41
-32,400
d71581d2cb42ab09885c5e86c7a71809e4dd479f
correct spelling on comment
[ { "change_type": "MODIFY", "old_path": "docs/design_notes/sequencing_effects.md", "new_path": "docs/design_notes/sequencing_effects.md", "diff": "@@ -82,7 +82,7 @@ def f(x):\njax.print(\"world\")\nreturn x\n```\n-Even though in Python, we've written the the `\"hello\"` print before the `\"world\"` print,\n+Even though in Python, we've written the `\"hello\"` print before the `\"world\"` print,\na compiler like XLA is free to reorder them because there's no explicit data-dependence between the prints.\n## Motivation\n" }, { "change_type": "MODIFY", "old_path": "docs/jax-101/02-jitting.ipynb", "new_path": "docs/jax-101/02-jitting.ipynb", "diff": "\"source\": [\n\"## When to use JIT\\n\",\n\"\\n\",\n- \"In many of the the examples above, jitting is not worth it:\"\n+ \"In many of the examples above, jitting is not worth it:\"\n]\n},\n{\n" }, { "change_type": "MODIFY", "old_path": "docs/jax-101/02-jitting.md", "new_path": "docs/jax-101/02-jitting.md", "diff": "@@ -263,7 +263,7 @@ print(g_jit_decorated(10, 20))\n## When to use JIT\n-In many of the the examples above, jitting is not worth it:\n+In many of the examples above, jitting is not worth it:\n```{code-cell} ipython3\n:id: uMOqsNnqYApD\n" }, { "change_type": "MODIFY", "old_path": "docs/profiling.md", "new_path": "docs/profiling.md", "diff": "@@ -6,7 +6,7 @@ We can use the JAX profiler to generate traces of a JAX program that can be\nvisualized using the [Perfetto visualizer](https://ui.perfetto.dev). Currently,\nthis method blocks the program until a link is clicked and the Perfetto UI loads\nthe trace. If you wish to get profiling information without any interaction,\n-check out the the Tensorboard profiler below.\n+check out the Tensorboard profiler below.\n```python\nwith jax.profiler.trace(\"/tmp/jax-trace\", create_perfetto_link=True):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -19,7 +19,7 @@ r\"\"\"Jet is an experimental module for higher-order automatic differentiation\nConsider a function :math:`f = g \\circ h`, some point :math:`x`\nand some offset :math:`v`.\nFirst-order automatic differentiation (such as :func:`jax.jvp`)\n- computes the pair :math:`(f(x), \\partial f(x)[v])` from the the pair\n+ computes the pair :math:`(f(x), \\partial f(x)[v])` from the pair\n:math:`(h(x), \\partial h(x)[v])`.\n:func:`jet` implements the higher-order analogue:\n" } ]
Python
Apache License 2.0
google/jax
correct spelling on comment
260,631
06.06.2022 10:08:02
25,200
24ad82685c8fc17df62207e04e4418bd6c078818
Fix reference to jax_coordination_service flag.
[ { "change_type": "MODIFY", "old_path": "jax/_src/distributed.py", "new_path": "jax/_src/distributed.py", "diff": "@@ -19,7 +19,7 @@ from typing import Optional\nfrom absl import logging\nfrom jax._src import cloud_tpu_init\n-from jax._src import config\n+from jax._src.config import config\nfrom jax._src.lib import xla_bridge\nfrom jax._src.lib import xla_client\nfrom jax._src.lib import xla_extension\n" } ]
Python
Apache License 2.0
google/jax
Fix reference to jax_coordination_service flag. PiperOrigin-RevId: 453224722
260,510
07.06.2022 14:02:28
25,200
c3aa9719483d6d8adcd159744856b7d02ee26e1b
Enable debug print in xmap
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1012,8 +1012,6 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nwith core.extend_axis_env_nd(global_axis_sizes.items()):\njaxpr, mapped_out_avals, consts = trace_to_subjaxpr_dynamic(\nf, self.main, mapped_in_avals)\n- if jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `xmap`.')\nout_axes = params['out_axes_thunk']()\nif params['spmd_out_axes_thunk'] is not None:\nspmd_out_axes = params['spmd_out_axes_thunk']()\n@@ -1051,7 +1049,7 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\ndel new_params['spmd_out_axes_thunk']\neqn = new_jaxpr_eqn([*constvars, *invars], outvars, primitive,\nnew_params, call_jaxpr.effects, source_info)\n- self.frame.eqns.append(eqn)\n+ self.frame.add_eqn(eqn)\nreturn out_tracers\npe.DynamicJaxprTrace.process_xmap = _dynamic_jaxpr_process_xmap # type: ignore\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -25,6 +25,7 @@ from absl.testing import parameterized\nimport jax\nfrom jax import lax\nfrom jax.config import config\n+from jax.experimental import maps\nfrom jax._src import debugging\nfrom jax._src import lib as jaxlib\nfrom jax._src import test_util as jtu\n@@ -386,6 +387,20 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\njax.effects_barrier()\nself._assertLinesEqual(output(), \"hello: 0\\nhello: 1\\nhello: 2\\nhello: 3\\n\")\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_unordered_print_with_xmap(self):\n+\n+ def f(x):\n+ debug_print(\"{}\", x, ordered=False)\n+ f = maps.xmap(f, in_axes=['a'], out_axes=None, backend='cpu',\n+ axis_resources={'a': 'dev'})\n+ with maps.Mesh(np.array(jax.devices(backend='cpu')), ['dev']):\n+ with capture_stdout() as output:\n+ f(jnp.arange(40))\n+ jax.effects_barrier()\n+ lines = [f\"{i}\\n\" for i in range(40)]\n+ self._assertLinesEqual(output(), \"\".join(lines))\n+\nif jaxlib.version < (0, 3, 8):\n# No lowering for `emit_python_callback` in older jaxlibs.\ndel DebugPrintTest\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -266,8 +266,8 @@ class HigherOrderPrimitiveTest(jtu.JaxTestCase):\neffect_p.bind(effect='bar')\nreturn x\nf = maps.xmap(f, in_axes=['a'], out_axes=['a'])\n- with self.assertRaisesRegex(NotImplementedError, 'Effects not supported'):\n- jax.make_jaxpr(f)(jnp.arange(jax.local_device_count()))\n+ jaxpr = jax.make_jaxpr(f)(jnp.arange(jax.local_device_count()))\n+ self.assertSetEqual(jaxpr.effects, {\"foo\", \"bar\"})\ndef test_pjit_inherits_effects(self):\ndef f(x):\n" } ]
Python
Apache License 2.0
google/jax
Enable debug print in xmap
260,350
08.06.2022 16:03:31
25,200
c083821a21752be409074f1e9e6cda0c7531e87c
fix pjit doc
[ { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -209,7 +209,7 @@ def pjit(fun: Callable,\nautomaticly partitioned by the mesh available at each call site.\nFor example, a convolution operator can be automatically partitioned over\n- an arbitrary set of devices by a single ```pjit`` application:\n+ an arbitrary set of devices by a single ``pjit`` application:\n>>> import jax\n>>> import jax.numpy as jnp\n" } ]
Python
Apache License 2.0
google/jax
fix pjit doc
260,510
25.05.2022 12:02:35
25,200
289610eb025e6d8fc11867997e74eed1f22f578c
Add a public facing `named_scope` function to allow adding to the name stack.
[ { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -96,6 +96,7 @@ from jax._src.api import (\nmake_jaxpr as make_jaxpr,\nmask as mask,\nnamed_call as named_call,\n+ named_scope as named_scope,\npmap as pmap,\nprocess_count as process_count,\nprocess_index as process_index,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -29,9 +29,9 @@ import sys\nimport threading\nimport weakref\nimport types\n-from typing import (Any, Callable, Iterable, NamedTuple, Mapping, Optional,\n- Sequence, Tuple, TypeVar, Union, overload, Dict, Hashable,\n- List)\n+from typing import (Any, Callable, Generator, Iterable, NamedTuple, Mapping,\n+ Optional, Sequence, Tuple, TypeVar, Union, overload, Dict,\n+ Hashable, List)\nfrom typing_extensions import Literal\nfrom warnings import warn\n@@ -3178,6 +3178,57 @@ def named_call(\nreturn named_call_f\n+@contextmanager\n+def named_scope(\n+ name: str,\n+ ) -> Generator[None, None, None]:\n+ \"\"\"A context manager that adds a user specified name to the JAX name stack.\n+\n+ When staging out computations for just-in-time compilation to XLA (or other\n+ backends such as TensorFlow) JAX does not, by default, preserve the names\n+ (or other source metadata) of Python functions it encounters.\n+ This can make debugging the staged out (and/or compiled) representation of\n+ your program complicated because there is limited context information for each\n+ operation being executed.\n+\n+ ``named_scope`` tells JAX to stage the given function with additional\n+ annotations on the underlying operations. JAX internally keeps track of these\n+ annotations in a name stack. When the staged out program is compiled with XLA\n+ these annotations are preserved and show up in debugging utilities like the\n+ TensorFlow Profiler in TensorBoard. Names are also preserved when staging out\n+ JAX programs to TensorFlow using :func:`experimental.jax2tf.convert`.\n+\n+\n+ Args:\n+ name: The prefix to use to name all operations created within the name\n+ scope.\n+ Yields:\n+ Yields ``None``, but enters a context in which `name` will be appended to\n+ the active name stack.\n+\n+ Examples:\n+ ``named_scope`` can be used as a context manager inside compiled functions:\n+\n+ >>> import jax\n+ >>>\n+ >>> @jax.jit\n+ ... def layer(w, x):\n+ ... with jax.named_scope(\"dot_product\"):\n+ ... logits = w.dot(x)\n+ ... with jax.named_scope(\"activation\"):\n+ ... return jax.nn.relu(logits)\n+\n+ It can also be used as a decorator:\n+\n+ >>> @jax.jit\n+ ... @jax.named_scope(\"layer\")\n+ ... def layer(w, x):\n+ ... logits = w.dot(x)\n+ ... return jax.nn.relu(logits)\n+ \"\"\"\n+ with source_info_util.extend_name_stack(name):\n+ yield\n+\ndef effects_barrier():\n\"\"\"Waits until existing functions have completed any side-effects.\"\"\"\ndispatch.runtime_tokens.block_until_ready()\n" }, { "change_type": "MODIFY", "old_path": "tests/name_stack_test.py", "new_path": "tests/name_stack_test.py", "diff": "@@ -21,11 +21,9 @@ from jax import lax\nfrom jax import linear_util as lu\nfrom jax.config import config\nfrom jax._src import test_util as jtu\n-from jax._src import source_info_util\nfrom jax._src.lib import xla_client\nconfig.parse_flags_with_absl()\n-extend_name_stack = source_info_util.extend_name_stack\ndef _get_hlo(f):\ndef wrapped(*args, **kwargs):\n@@ -66,7 +64,7 @@ class NameStackTest(_EnableNameStackTestCase):\ndef test_manual_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\nreturn x + 1\njaxpr = jax.make_jaxpr(f)(2).jaxpr\n@@ -75,9 +73,9 @@ class NameStackTest(_EnableNameStackTestCase):\ndef test_nested_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- with extend_name_stack('bar'):\n+ with jax.named_scope('bar'):\nreturn x + 1\njaxpr = jax.make_jaxpr(f)(2).jaxpr\nfor eqn in jaxpr.eqns:\n@@ -86,20 +84,20 @@ class NameStackTest(_EnableNameStackTestCase):\ndef test_multiple_name_stack(self):\ndef f(x):\n- with extend_name_stack('foo'):\n+ with jax.named_scope('foo'):\ny = x + 1\n- with extend_name_stack('bar'):\n- with extend_name_stack('baz'):\n+ with jax.named_scope('bar'):\n+ with jax.named_scope('baz'):\nreturn y + 1\njaxpr = jax.make_jaxpr(f)(2).jaxpr\nself.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'foo')\nself.assertEqual(str(jaxpr.eqns[1].source_info.name_stack), 'bar/baz')\ndef test_call_primitive_jaxpr_should_not_store_outer_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n@lu.wrap_init\n- @extend_name_stack('bar')\n+ @jax.named_scope('bar')\ndef _f(x):\nreturn [x + 1]\nreturn core.call(_f, x)[0]\n@@ -111,10 +109,10 @@ class NameStackTest(_EnableNameStackTestCase):\nself.assertIn('foo/jit(core_call)/bar', hlo_text)\ndef test_xla_call_primitive_jaxpr_should_not_store_outer_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n@jax.jit\n- @extend_name_stack('bar')\n+ @jax.named_scope('bar')\ndef _f(x):\nreturn x + 1\nreturn _f(x)\n@@ -127,10 +125,10 @@ class NameStackTest(_EnableNameStackTestCase):\nself.assertIn('foo/jit(_f)/bar', hlo_text)\ndef test_pmap_call_primitive_jaxpr_should_not_store_outer_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\n@jax.pmap\ndef f(x):\n- with extend_name_stack('bar'):\n+ with jax.named_scope('bar'):\nreturn x + 1\njaxpr = jax.make_jaxpr(f)(jnp.ones(1)).jaxpr\nself.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'foo')\n@@ -142,27 +140,27 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\ndef test_vmap_should_transform_name_stack(self):\n@jax.vmap\ndef f(x):\n- with extend_name_stack('foo'):\n+ with jax.named_scope('foo'):\nreturn x + 1\njaxpr = jax.make_jaxpr(f)(jnp.ones(2)).jaxpr\nself.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'vmap(foo)')\ndef test_vmap_should_transform_inner_name_stacks(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\n@jax.vmap\ndef f(x):\n- with extend_name_stack('bar'):\n- with extend_name_stack('baz'):\n+ with jax.named_scope('bar'):\n+ with jax.named_scope('baz'):\nreturn x + 1\njaxpr = jax.make_jaxpr(f)(jnp.ones(2)).jaxpr\nself.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'foo/vmap(bar)/vmap(baz)')\ndef test_vmap_should_apply_to_call_jaxpr(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\n@jax.vmap\ndef f(x):\n@jax.jit\n- @extend_name_stack('bar')\n+ @jax.named_scope('bar')\ndef _f(x):\nreturn x + 1\nreturn _f(x)\n@@ -176,10 +174,10 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\ndef test_jvp_should_transform_stacks(self):\ndef f(x):\n- with extend_name_stack('bar'):\n- with extend_name_stack('baz'):\n+ with jax.named_scope('bar'):\n+ with jax.named_scope('baz'):\nreturn jnp.square(x)\n- g = extend_name_stack('foo')(lambda x, t: jax.jvp(f, (x,), (t,)))\n+ g = jax.named_scope('foo')(lambda x, t: jax.jvp(f, (x,), (t,)))\njaxpr = jax.make_jaxpr(g)(1., 1.).jaxpr\nself.assertEqual(str(jaxpr.eqns[0].source_info.name_stack),\n'foo/jvp(bar)/jvp(baz)')\n@@ -187,10 +185,10 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\ndef test_jvp_should_apply_to_call_jaxpr(self):\n@jax.jit\ndef f(x):\n- with extend_name_stack('bar'):\n- with extend_name_stack('baz'):\n+ with jax.named_scope('bar'):\n+ with jax.named_scope('baz'):\nreturn jnp.square(x)\n- g = extend_name_stack('foo')(lambda x, t: jax.jvp(f, (x,), (t,)))\n+ g = jax.named_scope('foo')(lambda x, t: jax.jvp(f, (x,), (t,)))\njaxpr = jax.make_jaxpr(g)(1., 1.).jaxpr\nself.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'foo')\nself.assertEqual(\n@@ -203,7 +201,7 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\ndef test_grad_should_add_jvp_and_transpose_to_name_stack(self):\n@jax.value_and_grad\ndef f(x):\n- with extend_name_stack('foo'):\n+ with jax.named_scope('foo'):\nreturn 2 * jnp.sin(x)\njaxpr = jax.make_jaxpr(f)(1.).jaxpr\nself.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'jvp(foo)')\n@@ -219,10 +217,10 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\ndef test_grad_should_add_jvp_and_transpose_to_call_jaxpr(self):\n@jax.grad\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\n@jax.jit\ndef f(x):\n- with extend_name_stack('bar'):\n+ with jax.named_scope('bar'):\nreturn jnp.sin(x)\njaxpr = jax.make_jaxpr(f)(1.).jaxpr\nself.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'jvp(foo)')\n@@ -246,12 +244,12 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_while_loop_body_should_not_have_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- @extend_name_stack('bar')\n+ @jax.named_scope('bar')\ndef body(x):\nreturn x + 1\n- @extend_name_stack('bar_cond')\n+ @jax.named_scope('bar_cond')\ndef cond(x):\nreturn x < 5\nreturn lax.while_loop(cond, body, x)\n@@ -271,12 +269,12 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_vmap_of_while_loop_should_transform_name_stack(self):\n@jax.vmap\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- @extend_name_stack('bar')\n+ @jax.named_scope('bar')\ndef body(x):\nreturn x + 1\n- @extend_name_stack('bar_cond')\n+ @jax.named_scope('bar_cond')\ndef cond(x):\nreturn x < 5\nreturn lax.while_loop(cond, body, x)\n@@ -295,12 +293,12 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_jvp_of_while_loop_transforms_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- @extend_name_stack('bar')\n+ @jax.named_scope('bar')\ndef body(x):\nreturn x + 1.\n- @extend_name_stack('bar_cond')\n+ @jax.named_scope('bar_cond')\ndef cond(x):\nreturn x < 5.\nreturn lax.while_loop(cond, body, x)\n@@ -320,12 +318,12 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_vmap_of_jvp_of_while_loop_transforms_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- @extend_name_stack('bar')\n+ @jax.named_scope('bar')\ndef body(x):\nreturn x + 1.\n- @extend_name_stack('bar_cond')\n+ @jax.named_scope('bar_cond')\ndef cond(x):\nreturn x < 5.\nreturn lax.while_loop(cond, body, x)\n@@ -349,12 +347,12 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_cond_body_should_not_have_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x, y):\n- @extend_name_stack('true')\n+ @jax.named_scope('true')\ndef true_fn(x):\nreturn x + 1\n- @extend_name_stack('false')\n+ @jax.named_scope('false')\ndef false_fn(x):\nreturn x - 1\nreturn lax.cond(y, true_fn, false_fn, x)\n@@ -375,13 +373,13 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_vmap_of_cond_should_transform_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\n@functools.partial(jax.vmap, in_axes=(0, None))\ndef f(x, y):\n- @extend_name_stack('true')\n+ @jax.named_scope('true')\ndef true_fn(x):\nreturn x + 1\n- @extend_name_stack('false')\n+ @jax.named_scope('false')\ndef false_fn(x):\nreturn x - 1\nreturn lax.cond(y, true_fn, false_fn, x)\n@@ -402,12 +400,12 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_jvp_of_cond_transforms_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x, y):\n- @extend_name_stack('true')\n+ @jax.named_scope('true')\ndef true_fn(x):\nreturn x + 1\n- @extend_name_stack('false')\n+ @jax.named_scope('false')\ndef false_fn(x):\nreturn x - 1\nreturn lax.cond(y, true_fn, false_fn, x)\n@@ -429,12 +427,12 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_vmap_of_jvp_of_cond_transforms_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x, y):\n- @extend_name_stack('true')\n+ @jax.named_scope('true')\ndef true_fn(x):\nreturn x + 1\n- @extend_name_stack('false')\n+ @jax.named_scope('false')\ndef false_fn(x):\nreturn x - 1\nreturn lax.cond(y, true_fn, false_fn, x)\n@@ -460,12 +458,12 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_grad_of_cond_transforms_name_stack(self):\n@jax.grad\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x, y):\n- @extend_name_stack('true')\n+ @jax.named_scope('true')\ndef true_fn(x):\nreturn x * x * 2.\n- @extend_name_stack('false')\n+ @jax.named_scope('false')\ndef false_fn(x):\nreturn x / jnp.square(x)\nreturn lax.cond(y, true_fn, false_fn, x)\n@@ -492,12 +490,12 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n@functools.partial(jax.vmap, in_axes=(0, None))\n@jax.grad\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x, y):\n- @extend_name_stack('true')\n+ @jax.named_scope('true')\ndef true_fn(x):\nreturn x * x * 2.\n- @extend_name_stack('false')\n+ @jax.named_scope('false')\ndef false_fn(x):\nreturn x / x / 2.\nreturn lax.cond(y, true_fn, false_fn, x)\n@@ -522,9 +520,9 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_scan_body_should_not_have_name_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- @extend_name_stack('scan_body')\n+ @jax.named_scope('scan_body')\ndef body(carry, x):\nreturn carry + x, carry + x\nreturn lax.scan(body, x, jnp.arange(5.))\n@@ -540,9 +538,9 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_vmap_of_scan_should_transform_stack(self):\n@jax.vmap\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- @extend_name_stack('scan_body')\n+ @jax.named_scope('scan_body')\ndef body(carry, x):\nreturn carry + x, carry + x\nreturn lax.scan(body, x, jnp.arange(8.))\n@@ -557,9 +555,9 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_jvp_of_scan_should_transform_stack(self):\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- @extend_name_stack('scan_body')\n+ @jax.named_scope('scan_body')\ndef body(carry, x):\nreturn carry + x, carry + x\nreturn lax.scan(body, x, jnp.arange(8.))\n@@ -576,9 +574,9 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\ndef test_grad_of_scan_should_transform_stack(self):\n@jax.value_and_grad\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- @extend_name_stack('scan_body')\n+ @jax.named_scope('scan_body')\ndef body(carry, x):\nreturn 2 * carry * x, carry + x\nreturn lax.scan(body, x, jnp.arange(8.))[0]\n@@ -598,9 +596,9 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n@jax.vmap\n@jax.value_and_grad\n- @extend_name_stack('foo')\n+ @jax.named_scope('foo')\ndef f(x):\n- @extend_name_stack('scan_body')\n+ @jax.named_scope('scan_body')\ndef body(carry, x):\nreturn carry * x, carry + x\nreturn lax.scan(body, x, jnp.arange(8.))[0]\n" } ]
Python
Apache License 2.0
google/jax
Add a public facing `named_scope` function to allow adding to the name stack.
260,681
09.06.2022 17:56:03
0
4f8881539d6692a6e287aa34628a178fb1890bf6
Make the transfer guard documentation easier to find Move the main documentation of the transfer guard from "Notes" to "Reference documentation" section for better visibility. Add a link to the main documentation to the docstring of jax.transfer_guard(), which currently shows up as the top result when searching for "jax transfer_guard".
[ { "change_type": "MODIFY", "old_path": "docs/index.rst", "new_path": "docs/index.rst", "diff": "@@ -30,6 +30,7 @@ parallelize, Just-In-Time compile to GPU/TPU, and more.\npytrees\ntype_promotion\nerrors\n+ transfer_guard\nglossary\nchangelog\n@@ -59,7 +60,6 @@ parallelize, Just-In-Time compile to GPU/TPU, and more.\ndevice_memory_profiling\nrank_promotion_warning\ncustom_vjp_update\n- transfer_guard\n.. toctree::\n:maxdepth: 2\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -970,7 +970,17 @@ _transfer_guard = config.define_enum_state(\n@contextlib.contextmanager\ndef transfer_guard(new_val: str) -> Iterator[None]:\n- \"\"\"Set up thread-local state and return a contextmanager for managing it.\"\"\"\n+ \"\"\"A contextmanager to control the transfer guard level for all transfers.\n+\n+ For more information, see\n+ https://jax.readthedocs.io/en/latest/transfer_guard.html\n+\n+ Args:\n+ new_val: The new thread-local transfer guard level for all transfers.\n+\n+ Yields:\n+ None.\n+ \"\"\"\nwith contextlib.ExitStack() as stack:\nstack.enter_context(transfer_guard_host_to_device(new_val))\nstack.enter_context(transfer_guard_device_to_device(new_val))\n" } ]
Python
Apache License 2.0
google/jax
Make the transfer guard documentation easier to find Move the main documentation of the transfer guard from "Notes" to "Reference documentation" section for better visibility. Add a link to the main documentation to the docstring of jax.transfer_guard(), which currently shows up as the top result when searching for "jax transfer_guard".
260,510
09.06.2022 10:34:25
25,200
c0b47fdf2c9fff1d79efd8a65b0442ae6bb27ace
Update changelog for `named_scope` and adds it to the docs
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -43,6 +43,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Added {func}`jax.default_device`.\n* Added a `python -m jax.collect_profile` script to manually capture program\ntraces as an alternative to the Tensorboard UI.\n+ * Added a `jax.named_scope` context manager that adds profiler metadata to\n+ Python programs (similar to `jax.named_call`).\n## jaxlib 0.3.11 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jaxlib-v0.3.10...main).\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.rst", "new_path": "docs/jax.rst", "diff": "@@ -50,6 +50,7 @@ Just-in-time compilation (:code:`jit`)\ndevice_get\ndefault_backend\nnamed_call\n+ named_scope\nblock_until_ready\n.. _jax-grad:\n" } ]
Python
Apache License 2.0
google/jax
Update changelog for `named_scope` and adds it to the docs
260,336
09.06.2022 15:03:53
25,200
4723603967662c06d6e963c21e026e03e62968c0
Update lax.py Use the accurate mathematical description to avoid confusion. We may want to say the dimension of the array rather than the rank of the tensor array.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -635,8 +635,8 @@ def dot(lhs: Array, rhs: Array, precision: PrecisionLike = None,\nFor more general contraction, see the `dot_general` operator.\nArgs:\n- lhs: an array of rank 1 or 2.\n- rhs: an array of rank 1 or 2.\n+ lhs: an array of dimension 1 or 2.\n+ rhs: an array of dimension 1 or 2.\nprecision: Optional. Either ``None``, which means the default precision for\nthe backend, a :class:`~jax.lax.Precision` enum value (``Precision.DEFAULT``,\n``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two\n@@ -4403,7 +4403,7 @@ def _check_shapelike(fun_name, arg_name, obj, non_zero_shape=False):\nreturn # TODO(mattjj): handle more checks in the dynamic shape case\nobj_arr = np.array(obj)\nif obj_arr.ndim != 1:\n- msg = \"{} {} must be rank 1, got {}.\"\n+ msg = \"{} {} must be 1-dimensional, got {}.\"\nraise TypeError(msg.format(obj_arr.ndim))\ntry:\ncanonicalize_shape(obj_arr)\n" } ]
Python
Apache License 2.0
google/jax
Update lax.py Use the accurate mathematical description to avoid confusion. We may want to say the dimension of the array rather than the rank of the tensor array.
260,624
19.05.2022 21:06:25
0
498ee6007d345b05566aad9c854e4eb04fb60fbb
Using etils(gfile) to support gcs buckets and file system for persistent compilation caching
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -10,6 +10,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n## jax 0.3.14 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jax-v0.3.13...main).\n+* Breaking changes\n+ * {func}`jax.experimental.compilation_cache.initialize_cache` does not support `max_cache_size_ bytes` anymore and will not get that as an input.\n* Changes\n* {func}`jax.numpy.linalg.slogdet` now accepts an optional `method` argument\nthat allows selection between an LU-decomposition based implementation and\n@@ -45,6 +47,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\ntraces as an alternative to the Tensorboard UI.\n* Added a `jax.named_scope` context manager that adds profiler metadata to\nPython programs (similar to `jax.named_call`).\n+ * {func}`jax.experimental.compilation_cache.initialize_cache` now supports gcs\n+ bucket path as input.\n## jaxlib 0.3.11 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jaxlib-v0.3.10...main).\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/compilation_cache/compilation_cache.py", "new_path": "jax/experimental/compilation_cache/compilation_cache.py", "diff": "@@ -19,21 +19,19 @@ import sys\nfrom typing import List, Optional\nimport jax\n-from jax.experimental.compilation_cache.file_system_cache import FileSystemCache\n+from jax.experimental.compilation_cache.gfile_cache import GFileCache\nimport jax._src.lib\nfrom jax._src.lib import xla_client\nfrom absl import logging\n_cache = None\n-def initialize_cache(path, max_cache_size_bytes=32 * 2**30):\n+def initialize_cache(path):\n\"\"\"Creates a global cache object. Should only be called once per process.\n-\n- max_cache_sixe defaults to 32GiB.\n\"\"\"\nglobal _cache\nassert _cache == None, f\"The cache path has already been initialized to {_cache._path}\"\n- _cache = FileSystemCache(path, max_cache_size_bytes)\n+ _cache = GFileCache(path)\nlogging.warning(\"Initialized persistent compilation cache at %s\", path)\ndef get_executable(xla_computation, compile_options, backend) -> Optional[xla_client.Executable]:\n" }, { "change_type": "DELETE", "old_path": "jax/experimental/compilation_cache/file_system_cache.py", "new_path": null, "diff": "-# Copyright 2021 Google LLC\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-import os\n-from jax.experimental.compilation_cache.cache_interface import CacheInterface\n-import tempfile\n-from typing import Optional\n-import warnings\n-\n-class FileSystemCache(CacheInterface):\n-\n- def __init__(self, path: str, max_cache_size_bytes=32 * 2**30):\n- \"\"\"Sets up a cache at 'path'. Cached values may already be present.\"\"\"\n- os.makedirs(path, exist_ok=True)\n- self._path = path\n- self._max_cache_size_bytes = max_cache_size_bytes\n-\n- def get(self, key: str) -> Optional[bytes]:\n- \"\"\"Returns None if 'key' isn't present.\"\"\"\n- if not key:\n- raise ValueError(\"key cannot be empty\")\n- path_to_key = os.path.join(self._path, key)\n- if os.path.exists(path_to_key):\n- with open(path_to_key, \"rb\") as file:\n- return file.read()\n- else:\n- return None\n-\n- def put(self, key: str, value: bytes):\n- \"\"\"Adds new cache entry, possibly evicting older entries.\"\"\"\n- if not key:\n- raise ValueError(\"key cannot be empty\")\n- if self._evict_entries_if_necessary(key, value):\n- path_to_new_file = os.path.join(self._path, key)\n- # Create the path for the file in a temporary directory so we can use the\n- # atomic move function to ensure that the file is properly stored and read\n- # in the case of concurrent access across multiple threads or processes\n- with tempfile.TemporaryDirectory() as tmpdir:\n- temp_path_to_file = os.path.join(tmpdir, key)\n- with open(temp_path_to_file, \"wb\") as file:\n- file.write(value)\n- file.flush()\n- os.fsync(file.fileno())\n- os.rename(temp_path_to_file, path_to_new_file)\n- else:\n- warnings.warn(f\"Cache value of size {len(value)} is larger than\"\n- f\" the max cache size of {self._max_cache_size_bytes}\")\n-\n- def _evict_entries_if_necessary(self, key: str, value: bytes) -> bool:\n- \"\"\"Returns True if there's enough space to add 'value', False otherwise.\"\"\"\n- new_file_size = len(value)\n-\n- if new_file_size >= self._max_cache_size_bytes:\n- return False\n-\n- while new_file_size + self._get_cache_directory_size() > self._max_cache_size_bytes:\n- last_time = float('inf')\n- file_to_delete = None\n- for file_name in os.listdir(self._path):\n- file_to_inspect = os.path.join(self._path, file_name)\n- atime = os.stat(file_to_inspect).st_atime\n- if atime < last_time:\n- last_time = atime\n- file_to_delete = file_to_inspect\n- assert file_to_delete\n- os.remove(file_to_delete)\n- return True\n-\n- def _get_cache_directory_size(self):\n- \"\"\"Retrieves the current size of the directory, self.path\"\"\"\n- return sum(os.path.getsize(f) for f in os.scandir(self._path) if f.is_file())\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/compilation_cache/gfile_cache.py", "diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import os\n+import pathlib\n+\n+from jax.experimental.compilation_cache.cache_interface import CacheInterface\n+from etils import epath\n+from absl import logging\n+\n+class GFileCache(CacheInterface):\n+\n+ def __init__(self, path: str):\n+ \"\"\"Sets up a cache at 'path'. Cached values may already be present.\"\"\"\n+ self._path = epath.Path(path)\n+ self._path.mkdir(parents=True, exist_ok=True)\n+\n+ def get(self, key: str):\n+ \"\"\"Returns None if 'key' isn't present.\"\"\"\n+ if not key:\n+ raise ValueError(\"key cannot be empty\")\n+ path_to_key = self._path / key\n+ if path_to_key.exists():\n+ return path_to_key.read_bytes()\n+ else:\n+ return None\n+\n+ def put(self, key: str, value: bytes):\n+ \"\"\"Adds new cache entry.\"\"\"\n+ if not key:\n+ raise ValueError(\"key cannot be empty\")\n+ path_to_new_file = self._path / key\n+ if str(path_to_new_file).startswith('gs://'):\n+ # Writes to gcs are atomic.\n+ path_to_new_file.write_bytes(value)\n+ elif str(path_to_new_file).startswith('file://') or '://' not in str(path_to_new_file):\n+ tmp_path = self._path / f\"_temp_{key}\"\n+ with open(str(tmp_path), \"wb\") as f:\n+ f.write(value)\n+ f.flush()\n+ os.fsync(f.fileno())\n+ os.rename(tmp_path, path_to_new_file)\n+ else:\n+ tmp_path = self._path / f\"_temp_{key}\"\n+ tmp_path.write_bytes(value)\n+ tmp_path.rename(str(path_to_new_file))\n" }, { "change_type": "DELETE", "old_path": "tests/file_system_cache_test.py", "new_path": null, "diff": "-# Copyright 2021 Google LLC\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-from absl.testing import absltest\n-from jax.experimental.compilation_cache.file_system_cache import FileSystemCache\n-import jax._src.test_util as jtu\n-import tempfile\n-import threading\n-import time\n-\n-class FileSystemCacheTest(jtu.JaxTestCase):\n-\n- def test_get_nonexistent_key(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir)\n- self.assertEqual(cache.get(\"nonExistentKey\"), None)\n-\n- def test_put_and_get_key(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir)\n- cache.put(\"foo\", b\"bar\")\n- self.assertEqual(cache.get(\"foo\"), b\"bar\")\n-\n- def test_existing_cache_path(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache1 = FileSystemCache(tmpdir)\n- cache1.put(\"foo\", b\"bar\")\n- del cache1\n- cache2 = FileSystemCache(tmpdir)\n- self.assertEqual(cache2.get(\"foo\"), b\"bar\")\n-\n- def test_empty_value_put(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir)\n- cache.put(\"foo\", b\"\")\n- self.assertEqual(cache.get(\"foo\"), b\"\")\n-\n- def test_empty_key_put(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir)\n- with self.assertRaisesRegex(ValueError , r\"key cannot be empty\"):\n- cache.put(\"\", b\"bar\")\n-\n- def test_empty_key_get(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir)\n- with self.assertRaisesRegex(ValueError , r\"key cannot be empty\"):\n- cache.get(\"\")\n-\n- def test_size_of_directory(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir)\n- cache.put(\"foo\", b\"bar\")\n- self.assertEqual(cache._get_cache_directory_size(), 3)\n-\n- def test_size_of_empty_directory(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir)\n- self.assertEqual(cache._get_cache_directory_size(), 0)\n-\n- def test_size_of_existing_directory(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache1 = FileSystemCache(tmpdir)\n- cache1.put(\"foo\", b\"bar\")\n- del cache1\n- cache2 = FileSystemCache(tmpdir)\n- self.assertEqual(cache2._get_cache_directory_size(), 3)\n-\n- def test_cache_is_full(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir, max_cache_size_bytes=6)\n- cache.put(\"first\", b\"one\")\n- # Sleep because otherwise these operations execute too fast and\n- # the access time isn't captured properly.\n- time.sleep(1)\n- cache.put(\"second\", b\"two\")\n- cache.put(\"third\", b\"the\")\n- self.assertEqual(cache.get(\"first\"), None)\n- self.assertEqual(cache.get(\"second\"), b\"two\")\n- self.assertEqual(cache.get(\"third\"), b\"the\")\n-\n- def test_delete_multiple_files(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir, max_cache_size_bytes=6)\n- cache.put(\"first\", b\"one\")\n- # Sleep because otherwise these operations execute too fast and\n- # the access time isn't captured properly.\n- time.sleep(1)\n- cache.put(\"second\", b\"two\")\n- cache.put(\"third\", b\"three\")\n- self.assertEqual(cache.get(\"first\"), None)\n- self.assertEqual(cache.get(\"second\"), None)\n- self.assertEqual(cache.get(\"third\"), b\"three\")\n-\n- def test_least_recently_accessed_file(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir, max_cache_size_bytes=6)\n- cache.put(\"first\", b\"one\")\n- cache.put(\"second\", b\"two\")\n- # Sleep because otherwise these operations execute too fast and\n- # the access time isn't captured properly.\n- time.sleep(1)\n- cache.get(\"first\")\n- cache.put(\"third\", b\"the\")\n- self.assertEqual(cache.get(\"first\"), b\"one\")\n- self.assertEqual(cache.get(\"second\"), None)\n-\n- @jtu.ignore_warning(message=(\"Cache value of size 3 is larger than the max cache size of 2\"))\n- def test_file_bigger_than_cache(self):\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir, max_cache_size_bytes=2)\n- cache.put(\"foo\", b\"bar\")\n- self.assertEqual(cache.get(\"foo\"), None)\n-\n- def test_threads(self):\n- file_contents1 = \"1\" * (65536 + 1)\n- file_contents2 = \"2\" * (65536 + 1)\n-\n- def call_multiple_puts_and_gets(cache):\n- for i in range(50):\n- cache.put(\"foo\", file_contents1.encode('utf-8').strip())\n- cache.put(\"foo\", file_contents2.encode('utf-8').strip())\n- cache.get(\"foo\")\n- self.assertEqual(cache.get(\"foo\"), file_contents2.encode('utf-8').strip())\n-\n- with tempfile.TemporaryDirectory() as tmpdir:\n- cache = FileSystemCache(tmpdir)\n- threads = []\n- for i in range(50):\n- t = threading.Thread(target=call_multiple_puts_and_gets(cache))\n- t.start()\n- threads.append(t)\n- for t in threads:\n- t.join()\n-\n- self.assertEqual(cache.get(\"foo\"), file_contents2.encode('utf-8').strip())\n-\n-if __name__ == \"__main__\":\n- absltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/gfile_cache_test.py", "diff": "+# Copyright 2021 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from absl.testing import absltest\n+from jax.experimental.compilation_cache.gfile_cache import GFileCache\n+import jax._src.test_util as jtu\n+import tempfile\n+import threading\n+\n+class FileSystemCacheTest(jtu.JaxTestCase):\n+\n+ def test_get_nonexistent_key(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = GFileCache(tmpdir)\n+ self.assertEqual(cache.get(\"nonExistentKey\"), None)\n+\n+ def test_put_and_get_key(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = GFileCache(tmpdir)\n+ cache.put(\"foo\", b\"bar\")\n+ self.assertEqual(cache.get(\"foo\"), b\"bar\")\n+\n+ def test_existing_cache_path(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache1 = GFileCache(tmpdir)\n+ cache1.put(\"foo\", b\"bar\")\n+ del cache1\n+ cache2 = GFileCache(tmpdir)\n+ self.assertEqual(cache2.get(\"foo\"), b\"bar\")\n+\n+ def test_empty_value_put(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = GFileCache(tmpdir)\n+ cache.put(\"foo\", b\"\")\n+ self.assertEqual(cache.get(\"foo\"), b\"\")\n+\n+ def test_empty_key_put(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = GFileCache(tmpdir)\n+ with self.assertRaisesRegex(ValueError , r\"key cannot be empty\"):\n+ cache.put(\"\", b\"bar\")\n+\n+ def test_empty_key_get(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = GFileCache(tmpdir)\n+ with self.assertRaisesRegex(ValueError , r\"key cannot be empty\"):\n+ cache.get(\"\")\n+\n+\n+ def test_threads(self):\n+ file_contents1 = \"1\" * (65536 + 1)\n+ file_contents2 = \"2\" * (65536 + 1)\n+\n+ def call_multiple_puts_and_gets(cache):\n+ for i in range(50):\n+ cache.put(\"foo\", file_contents1.encode('utf-8').strip())\n+ cache.put(\"foo\", file_contents2.encode('utf-8').strip())\n+ cache.get(\"foo\")\n+ self.assertEqual(cache.get(\"foo\"), file_contents2.encode('utf-8').strip())\n+\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = GFileCache(tmpdir)\n+ threads = []\n+ for i in range(50):\n+ t = threading.Thread(target=call_multiple_puts_and_gets(cache))\n+ t.start()\n+ threads.append(t)\n+ for t in threads:\n+ t.join()\n+\n+ self.assertEqual(cache.get(\"foo\"), file_contents2.encode('utf-8').strip())\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Using etils(gfile) to support gcs buckets and file system for persistent compilation caching
260,424
10.06.2022 03:49:58
25,200
58f9ea07cd9f27b5a7c995ddda9815778f257c6a
Only wrap one level of the name-stack with transform names.
[ { "change_type": "MODIFY", "old_path": "jax/_src/source_info_util.py", "new_path": "jax/_src/source_info_util.py", "diff": "@@ -51,7 +51,10 @@ class Transform(NamedTuple):\nname: str\ndef wrap(self, stack: Tuple[str, ...]) -> Tuple[str, ...]:\n- return tuple(map(lambda x: f'{self.name}({x})', stack))\n+ if stack:\n+ return (f'{self.name}({stack[0]})', *stack[1:])\n+ else:\n+ return ()\n@dataclasses.dataclass(frozen=True)\nclass NameStack:\n" }, { "change_type": "MODIFY", "old_path": "tests/name_stack_test.py", "new_path": "tests/name_stack_test.py", "diff": "@@ -153,7 +153,7 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\nwith jax.named_scope('baz'):\nreturn x + 1\njaxpr = jax.make_jaxpr(f)(jnp.ones(2)).jaxpr\n- self.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'foo/vmap(bar)/vmap(baz)')\n+ self.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'foo/vmap(bar)/baz')\ndef test_vmap_should_apply_to_call_jaxpr(self):\n@jax.named_scope('foo')\n@@ -170,7 +170,7 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\nself.assertEqual(str(jaxpr.eqns[0].params['call_jaxpr'].eqns[0].source_info.name_stack), 'bar')\nhlo_text = _get_hlo(f)(jnp.ones(2))\n- self.assertIn('foo/vmap(jit(_f))/vmap(bar)', hlo_text)\n+ self.assertIn('foo/vmap(jit(_f))/bar', hlo_text)\ndef test_jvp_should_transform_stacks(self):\ndef f(x):\n@@ -180,7 +180,7 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\ng = jax.named_scope('foo')(lambda x, t: jax.jvp(f, (x,), (t,)))\njaxpr = jax.make_jaxpr(g)(1., 1.).jaxpr\nself.assertEqual(str(jaxpr.eqns[0].source_info.name_stack),\n- 'foo/jvp(bar)/jvp(baz)')\n+ 'foo/jvp(bar)/baz')\ndef test_jvp_should_apply_to_call_jaxpr(self):\n@jax.jit\n@@ -196,7 +196,7 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\n'bar/baz')\nhlo_text = _get_hlo(g)(1., 1.)\n- self.assertIn('foo/jvp(jit(f))/jvp(bar)', hlo_text)\n+ self.assertIn('foo/jvp(jit(f))/bar/baz/mul', hlo_text)\ndef test_grad_should_add_jvp_and_transpose_to_name_stack(self):\n@jax.value_and_grad\n@@ -233,11 +233,9 @@ class NameStackTransformationTest(_EnableNameStackTestCase):\njaxpr.eqns[1].params['call_jaxpr'].eqns[0].source_info.name_stack), 'bar')\nhlo_text = _get_hlo(f)(1.)\n- self.assertIn('jvp(foo)/jvp(jit(f))/jvp(bar)/sin', hlo_text)\n- self.assertIn('jvp(foo)/jvp(jit(f))/jvp(bar)/cos', hlo_text)\n- self.assertIn(\n- 'transpose(jvp(foo))/transpose(jvp(jit(f)))/transpose(jvp(bar))/mul',\n- hlo_text)\n+ self.assertIn('jvp(foo)/jit(f)/bar/sin', hlo_text)\n+ self.assertIn('jvp(foo)/jit(f)/bar/cos', hlo_text)\n+ self.assertIn('transpose(jvp(foo))/jit(f)/bar/mul', hlo_text)\nclass NameStackControlFlowTest(_EnableNameStackTestCase):\n@@ -288,8 +286,8 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n'bar_cond')\nhlo_text = _get_hlo(f)(jnp.arange(2.))\n- self.assertIn('vmap(foo)/vmap(while)/vmap(body)/vmap(bar)', hlo_text)\n- self.assertIn('vmap(foo)/vmap(while)/vmap(cond)/vmap(bar_cond)', hlo_text)\n+ self.assertIn('vmap(foo)/while/body/bar/add', hlo_text)\n+ self.assertIn('vmap(foo)/while/cond/bar_cond/lt', hlo_text)\ndef test_jvp_of_while_loop_transforms_name_stack(self):\n@@ -313,8 +311,8 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n'bar_cond')\nhlo_text = _get_hlo(g)(1., 1.)\n- self.assertIn('jvp(foo)/jvp(while)/jvp(body)/jvp(bar)', hlo_text)\n- self.assertIn('jvp(foo)/jvp(while)/jvp(cond)/jvp(bar_cond)', hlo_text)\n+ self.assertIn('jvp(foo)/while/body/bar/add', hlo_text)\n+ self.assertIn('jvp(foo)/while/cond/bar_cond/lt', hlo_text)\ndef test_vmap_of_jvp_of_while_loop_transforms_name_stack(self):\n@@ -338,12 +336,9 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n'bar_cond')\nhlo_text = _get_hlo(g)(jnp.arange(2.), jnp.ones(2))\n- self.assertIn(\n- 'vmap(jvp(foo))/vmap(jvp(while))/vmap(jvp(body))/vmap(jvp(bar))',\n- hlo_text)\n- self.assertIn(\n- 'vmap(jvp(foo))/vmap(jvp(while))/vmap(jvp(cond))/vmap(jvp(bar_cond))',\n- hlo_text)\n+ self.assertIn('vmap(jvp(foo))/while/body/bar/add', hlo_text)\n+ self.assertIn('vmap(jvp(foo))/while/body_pred/bar_cond', hlo_text)\n+\ndef test_cond_body_should_not_have_name_stack(self):\n@@ -395,8 +390,8 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n'true')\nhlo_text = _get_hlo(f)(jnp.arange(2.), True)\n- self.assertIn('foo/vmap(cond)/vmap(branch_0_fun)/vmap(false)/sub', hlo_text)\n- self.assertIn('foo/vmap(cond)/vmap(branch_1_fun)/vmap(true)/add', hlo_text)\n+ self.assertIn('foo/vmap(cond)/branch_0_fun/false/sub', hlo_text)\n+ self.assertIn('foo/vmap(cond)/branch_1_fun/true/add', hlo_text)\ndef test_jvp_of_cond_transforms_name_stack(self):\n@@ -422,8 +417,8 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n'true')\nhlo_text = _get_hlo(g)(jnp.arange(2.), jnp.ones(2))\n- self.assertIn('jvp(foo)/jvp(cond)/jvp(branch_0_fun)/jvp(false)/sub', hlo_text)\n- self.assertIn('jvp(foo)/jvp(cond)/jvp(branch_1_fun)/jvp(true)/add', hlo_text)\n+ self.assertIn('jvp(jit(f))/foo/cond/branch_0_fun/false/sub', hlo_text)\n+ self.assertIn('jvp(jit(f))/foo/cond/branch_1_fun/true/add', hlo_text)\ndef test_vmap_of_jvp_of_cond_transforms_name_stack(self):\n@@ -449,10 +444,10 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\nhlo_text = _get_hlo(g)(jnp.arange(2.), jnp.ones(2))\nself.assertIn(\n- 'vmap(jvp(foo))/vmap(jvp(cond))/vmap(jvp(branch_0_fun))/vmap(jvp(false))/sub',\n+ 'vmap(jvp(jit(f)))/foo/cond/branch_0_fun/false/sub\"',\nhlo_text)\nself.assertIn(\n- 'vmap(jvp(foo))/vmap(jvp(cond))/vmap(jvp(branch_1_fun))/vmap(jvp(true))/add',\n+ 'vmap(jvp(jit(f)))/foo/cond/branch_1_fun/true/add\"',\nhlo_text)\ndef test_grad_of_cond_transforms_name_stack(self):\n@@ -474,16 +469,16 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\nhlo_text = _get_hlo(f)(1., True)\nself.assertIn(\n- 'jvp(foo)/jvp(cond)/jvp(branch_0_fun)/jvp(false)/div',\n+ 'jvp(foo)/cond/branch_0_fun/false/div',\nhlo_text)\nself.assertIn(\n- 'jvp(foo)/jvp(cond)/jvp(branch_1_fun)/jvp(true)/mul',\n+ 'jvp(foo)/cond/branch_1_fun/true/mul',\nhlo_text)\nself.assertIn(\n- 'transpose(jvp(foo))/transpose(jvp(cond))/transpose(jvp(branch_0_fun))/transpose(jvp(false))/div',\n+ 'transpose(jvp(foo))/cond/branch_0_fun/false/div',\nhlo_text)\nself.assertIn(\n- 'transpose(jvp(foo))/transpose(jvp(cond))/transpose(jvp(branch_1_fun))/transpose(jvp(true))/mul',\n+ 'transpose(jvp(foo))/cond/branch_1_fun/true/mul',\nhlo_text)\ndef test_vmap_of_grad_of_cond_transforms_name_stack(self):\n@@ -506,16 +501,16 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\nhlo_text = _get_hlo(f)(jnp.arange(2.), True)\nself.assertIn(\n- 'vmap(jvp(foo))/vmap(jvp(cond))/vmap(jvp(branch_0_fun))/vmap(jvp(false))/div',\n+ 'vmap(jvp(foo))/cond/branch_0_fun/false/div',\nhlo_text)\nself.assertIn(\n- 'vmap(jvp(foo))/vmap(jvp(cond))/vmap(jvp(branch_1_fun))/vmap(jvp(true))/mul',\n+ 'vmap(jvp(foo))/cond/branch_1_fun/true/mul',\nhlo_text)\nself.assertIn(\n- 'vmap(transpose(jvp(foo)))/vmap(transpose(jvp(cond)))/vmap(transpose(jvp(branch_0_fun)))/vmap(transpose(jvp(false)))/div',\n+ 'vmap(transpose(jvp(foo)))/cond/branch_0_fun/false/div',\nhlo_text)\nself.assertIn(\n- 'vmap(transpose(jvp(foo)))/vmap(transpose(jvp(cond)))/vmap(transpose(jvp(branch_1_fun)))/vmap(transpose(jvp(true)))/mul',\n+ 'vmap(transpose(jvp(foo)))/cond/branch_1_fun/true/mul',\nhlo_text)\ndef test_scan_body_should_not_have_name_stack(self):\n@@ -551,7 +546,7 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n'scan_body')\nhlo_text = _get_hlo(f)(jnp.arange(2.))\n- self.assertIn('vmap(foo)/vmap(while)/vmap(body)/vmap(scan_body)/add', hlo_text)\n+ self.assertIn('vmap(foo)/while/body/scan_body/add', hlo_text)\ndef test_jvp_of_scan_should_transform_stack(self):\n@@ -569,7 +564,7 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n'scan_body')\nhlo_text = _get_hlo(g)(1., 1.)\n- self.assertIn('jvp(foo)/jvp(while)/jvp(body)/jvp(scan_body)/add', hlo_text)\n+ self.assertIn('jvp(foo)/while/body/scan_body/add', hlo_text)\ndef test_grad_of_scan_should_transform_stack(self):\n@@ -589,8 +584,8 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n'scan_body')\nhlo_text = _get_hlo(f)(1.)\n- self.assertIn('jvp(foo)/jvp(while)/jvp(body)/jvp(scan_body)/mul', hlo_text)\n- self.assertIn('transpose(jvp(foo))/transpose(jvp(while))/transpose(jvp(body))/transpose(jvp(scan_body))/mul', hlo_text)\n+ self.assertIn('jvp(foo)/while/body/scan_body/mul', hlo_text)\n+ self.assertIn('transpose(jvp(foo))/while/body/scan_body/mul', hlo_text)\ndef test_vmap_of_grad_of_scan_should_transform_stack(self):\n@@ -611,8 +606,8 @@ class NameStackControlFlowTest(_EnableNameStackTestCase):\n'scan_body')\nhlo_text = _get_hlo(f)(jnp.arange(2.))\n- self.assertIn('vmap(jvp(foo))/vmap(jvp(while))/vmap(jvp(body))/vmap(jvp(scan_body))/mul', hlo_text)\n- self.assertIn('vmap(transpose(jvp(foo)))/vmap(transpose(jvp(while)))/vmap(transpose(jvp(body)))/vmap(transpose(jvp(scan_body)))/mul', hlo_text)\n+ self.assertIn('vmap(jvp(foo))/while/body/scan_body/mul', hlo_text)\n+ self.assertIn('vmap(transpose(jvp(foo)))/while/body/scan_body/mul', hlo_text)\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Only wrap one level of the name-stack with transform names. PiperOrigin-RevId: 454125970
260,655
12.06.2022 00:51:10
0
e8903d4b4786a26ccb3fc4dc6c40f0a11363118e
Bump version of Tensorflow repository to fix build errors in the building of the MLIR compiler where cpp files have been renamed to cc files.
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -7,10 +7,10 @@ load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"4110a688a764c8d10734337d33aa3055c321bb621fb4f141668a3d2846ab0bbc\",\n- strip_prefix = \"tensorflow-b6ab86a3f12d1f7dda9c4be801f9920b4ef2ef7a\",\n+ sha256 = \"71c3e72584107eafa42ae1cdbbda70b7944c681b47b3c0f5c65a8f36fc6d26f4\",\n+ strip_prefix = \"tensorflow-325aa485592338bc4799ea5e28aa568299cb2b9b\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/b6ab86a3f12d1f7dda9c4be801f9920b4ef2ef7a.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/325aa485592338bc4799ea5e28aa568299cb2b9b.tar.gz\",\n],\n)\n" } ]
Python
Apache License 2.0
google/jax
Bump version of Tensorflow repository to fix build errors in the building of the MLIR compiler where cpp files have been renamed to cc files.
260,390
12.06.2022 16:51:25
25,200
0935b2986515e60efc7a33d7433e9a62dd980e39
added dtmax arg and test verifying correct behaviour - errors now with differentation
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ode.py", "new_path": "jax/experimental/ode.py", "diff": "@@ -142,7 +142,7 @@ def optimal_step_size(last_step, mean_error_ratio, safety=0.9, ifactor=10.0,\njnp.maximum(mean_error_ratio**(-1.0 / order) * safety, dfactor))\nreturn jnp.where(mean_error_ratio == 0, last_step * ifactor, last_step * factor)\n-def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf):\n+def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf, dtmax=jnp.inf):\n\"\"\"Adaptive stepsize (Dormand-Prince) Runge-Kutta odeint implementation.\nArgs:\n@@ -157,6 +157,7 @@ def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf):\nrtol: float, relative local error tolerance for solver (optional).\natol: float, absolute local error tolerance for solver (optional).\nmxstep: int, maximum number of steps to take for each timepoint (optional).\n+ dtmax: float, upper bound solver step size (optional).\nReturns:\nValues of the solution `y` (i.e. integrated system values) at each time\n@@ -171,17 +172,17 @@ def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf):\nraise TypeError(f\"t must be an array of floats, but got {t}.\")\nconverted, consts = custom_derivatives.closure_convert(func, y0, t[0], *args)\n- return _odeint_wrapper(converted, rtol, atol, mxstep, y0, t, *args, *consts)\n+ return _odeint_wrapper(converted, rtol, atol, mxstep, dtmax, y0, t, *args, *consts)\n@partial(jax.jit, static_argnums=(0, 1, 2, 3))\n-def _odeint_wrapper(func, rtol, atol, mxstep, y0, ts, *args):\n+def _odeint_wrapper(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\ny0, unravel = ravel_pytree(y0)\nfunc = ravel_first_arg(func, unravel)\n- out = _odeint(func, rtol, atol, mxstep, y0, ts, *args)\n+ out = _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args)\nreturn jax.vmap(unravel)(out)\n@partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2, 3))\n-def _odeint(func, rtol, atol, mxstep, y0, ts, *args):\n+def _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\nfunc_ = lambda y, t: func(y, t, *args)\ndef scan_fun(carry, target_t):\n@@ -196,7 +197,7 @@ def _odeint(func, rtol, atol, mxstep, y0, ts, *args):\nnext_t = t + dt\nerror_ratio = mean_error_ratio(next_y_error, rtol, atol, y, next_y)\nnew_interp_coeff = interp_fit_dopri(y, next_y, k, dt)\n- dt = optimal_step_size(dt, error_ratio)\n+ dt = jnp.clip(optimal_step_size(dt, error_ratio), a_min=0., a_max=dtmax)\nnew = [i + 1, next_y, next_f, next_t, dt, t, new_interp_coeff]\nold = [i + 1, y, f, t, dt, last_t, interp_coeff]\n@@ -209,7 +210,7 @@ def _odeint(func, rtol, atol, mxstep, y0, ts, *args):\nreturn carry, y_target\nf0 = func_(y0, ts[0])\n- dt = initial_step_size(func_, ts[0], y0, 4, rtol, atol, f0)\n+ dt = jnp.clip(initial_step_size(func_, ts[0], y0, 4, rtol, atol, f0), a_min=0., a_max=dtmax)\ninterp_coeff = jnp.array([y0] * 5)\ninit_carry = [y0, f0, ts[0], dt, ts[0], interp_coeff]\n_, ys = lax.scan(scan_fun, init_carry, ts[1:])\n" }, { "change_type": "MODIFY", "old_path": "tests/ode_test.py", "new_path": "tests/ode_test.py", "diff": "@@ -250,6 +250,20 @@ class ODETest(jtu.JaxTestCase):\njtu.check_grads(f, (y0, ts, alpha), modes=[\"rev\"], order=2, atol=tol, rtol=tol)\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\")\n+ def test_max_dt(self):\n+ \"\"\"Test max step size control.\"\"\"\n+\n+ def rhs(y, t):\n+ return jnp.piecewise(\n+ t,\n+ [t <= 2., (t >= 5.) & (t <= 7.)],\n+ [lambda s: jnp.array(1.), lambda s: jnp.array(-1.), lambda s: jnp.array(0.)]\n+ )\n+ ys = odeint(func=rhs, y0=jnp.array(0.), t=jnp.array([0., 5., 10.]), dtmax=1.)\n+\n+ self.assertTrue(jnp.abs(ys[-1]) < 1e-4)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
added dtmax arg and test verifying correct behaviour - errors now with differentation
260,390
12.06.2022 17:11:46
25,200
4d7a1d1382b424bfaf69895ff37d4c39e87562cf
fixing nondiff and static argnums for _odeint_wrapper and _odeint
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ode.py", "new_path": "jax/experimental/ode.py", "diff": "@@ -174,14 +174,14 @@ def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf, dtmax=j\nconverted, consts = custom_derivatives.closure_convert(func, y0, t[0], *args)\nreturn _odeint_wrapper(converted, rtol, atol, mxstep, dtmax, y0, t, *args, *consts)\n-@partial(jax.jit, static_argnums=(0, 1, 2, 3))\n+@partial(jax.jit, static_argnums=(0, 1, 2, 3, 4))\ndef _odeint_wrapper(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\ny0, unravel = ravel_pytree(y0)\nfunc = ravel_first_arg(func, unravel)\nout = _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args)\nreturn jax.vmap(unravel)(out)\n-@partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2, 3))\n+@partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2, 3, 4))\ndef _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\nfunc_ = lambda y, t: func(y, t, *args)\n@@ -216,11 +216,11 @@ def _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\n_, ys = lax.scan(scan_fun, init_carry, ts[1:])\nreturn jnp.concatenate((y0[None], ys))\n-def _odeint_fwd(func, rtol, atol, mxstep, y0, ts, *args):\n- ys = _odeint(func, rtol, atol, mxstep, y0, ts, *args)\n+def _odeint_fwd(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\n+ ys = _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args)\nreturn ys, (ys, ts, args)\n-def _odeint_rev(func, rtol, atol, mxstep, res, g):\n+def _odeint_rev(func, rtol, atol, mxstep, dtmax, res, g):\nys, ts, args = res\ndef aug_dynamics(augmented_state, t, *args):\n@@ -245,7 +245,7 @@ def _odeint_rev(func, rtol, atol, mxstep, res, g):\n_, y_bar, t0_bar, args_bar = odeint(\naug_dynamics, (ys[i], y_bar, t0_bar, args_bar),\njnp.array([-ts[i], -ts[i - 1]]),\n- *args, rtol=rtol, atol=atol, mxstep=mxstep)\n+ *args, rtol=rtol, atol=atol, mxstep=mxstep, dtmax=dtmax)\ny_bar, t0_bar, args_bar = tree_map(op.itemgetter(1), (y_bar, t0_bar, args_bar))\n# Add gradient from current output\ny_bar = y_bar + g[i - 1]\n" } ]
Python
Apache License 2.0
google/jax
fixing nondiff and static argnums for _odeint_wrapper and _odeint
260,390
12.06.2022 17:27:05
25,200
85dfca26fe2a19e9fe66480dcbc7335342171214
slight test changes
[ { "change_type": "MODIFY", "old_path": "tests/ode_test.py", "new_path": "tests/ode_test.py", "diff": "@@ -251,7 +251,7 @@ class ODETest(jtu.JaxTestCase):\njtu.check_grads(f, (y0, ts, alpha), modes=[\"rev\"], order=2, atol=tol, rtol=tol)\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n- def test_max_dt(self):\n+ def test_dtmax(self):\n\"\"\"Test max step size control.\"\"\"\ndef rhs(y, t):\n@@ -262,7 +262,8 @@ class ODETest(jtu.JaxTestCase):\n)\nys = odeint(func=rhs, y0=jnp.array(0.), t=jnp.array([0., 5., 10.]), dtmax=1.)\n- self.assertTrue(jnp.abs(ys[-1]) < 1e-4)\n+ self.assertTrue(jnp.abs(ys[1] - 2.) < 1e-4)\n+ self.assertTrue(jnp.abs(ys[2]) < 1e-4)\nif __name__ == '__main__':\n" } ]
Python
Apache License 2.0
google/jax
slight test changes
260,390
13.06.2022 06:38:34
25,200
f8357160853435efb7cc28e2747a94815eb7335c
changing dtmax to hmax
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ode.py", "new_path": "jax/experimental/ode.py", "diff": "@@ -142,7 +142,7 @@ def optimal_step_size(last_step, mean_error_ratio, safety=0.9, ifactor=10.0,\njnp.maximum(mean_error_ratio**(-1.0 / order) * safety, dfactor))\nreturn jnp.where(mean_error_ratio == 0, last_step * ifactor, last_step * factor)\n-def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf, dtmax=jnp.inf):\n+def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf, hmax=jnp.inf):\n\"\"\"Adaptive stepsize (Dormand-Prince) Runge-Kutta odeint implementation.\nArgs:\n@@ -157,7 +157,7 @@ def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf, dtmax=j\nrtol: float, relative local error tolerance for solver (optional).\natol: float, absolute local error tolerance for solver (optional).\nmxstep: int, maximum number of steps to take for each timepoint (optional).\n- dtmax: float, upper bound on solver step size (optional).\n+ hmax: float, maximum step size allowed (optional).\nReturns:\nValues of the solution `y` (i.e. integrated system values) at each time\n@@ -172,17 +172,17 @@ def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf, dtmax=j\nraise TypeError(f\"t must be an array of floats, but got {t}.\")\nconverted, consts = custom_derivatives.closure_convert(func, y0, t[0], *args)\n- return _odeint_wrapper(converted, rtol, atol, mxstep, dtmax, y0, t, *args, *consts)\n+ return _odeint_wrapper(converted, rtol, atol, mxstep, hmax, y0, t, *args, *consts)\n@partial(jax.jit, static_argnums=(0, 1, 2, 3, 4))\n-def _odeint_wrapper(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\n+def _odeint_wrapper(func, rtol, atol, mxstep, hmax, y0, ts, *args):\ny0, unravel = ravel_pytree(y0)\nfunc = ravel_first_arg(func, unravel)\n- out = _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args)\n+ out = _odeint(func, rtol, atol, mxstep, hmax, y0, ts, *args)\nreturn jax.vmap(unravel)(out)\n@partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2, 3, 4))\n-def _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\n+def _odeint(func, rtol, atol, mxstep, hmax, y0, ts, *args):\nfunc_ = lambda y, t: func(y, t, *args)\ndef scan_fun(carry, target_t):\n@@ -197,7 +197,7 @@ def _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\nnext_t = t + dt\nerror_ratio = mean_error_ratio(next_y_error, rtol, atol, y, next_y)\nnew_interp_coeff = interp_fit_dopri(y, next_y, k, dt)\n- dt = jnp.clip(optimal_step_size(dt, error_ratio), a_min=0., a_max=dtmax)\n+ dt = jnp.clip(optimal_step_size(dt, error_ratio), a_min=0., a_max=hmax)\nnew = [i + 1, next_y, next_f, next_t, dt, t, new_interp_coeff]\nold = [i + 1, y, f, t, dt, last_t, interp_coeff]\n@@ -210,17 +210,17 @@ def _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\nreturn carry, y_target\nf0 = func_(y0, ts[0])\n- dt = jnp.clip(initial_step_size(func_, ts[0], y0, 4, rtol, atol, f0), a_min=0., a_max=dtmax)\n+ dt = jnp.clip(initial_step_size(func_, ts[0], y0, 4, rtol, atol, f0), a_min=0., a_max=hmax)\ninterp_coeff = jnp.array([y0] * 5)\ninit_carry = [y0, f0, ts[0], dt, ts[0], interp_coeff]\n_, ys = lax.scan(scan_fun, init_carry, ts[1:])\nreturn jnp.concatenate((y0[None], ys))\n-def _odeint_fwd(func, rtol, atol, mxstep, dtmax, y0, ts, *args):\n- ys = _odeint(func, rtol, atol, mxstep, dtmax, y0, ts, *args)\n+def _odeint_fwd(func, rtol, atol, mxstep, hmax, y0, ts, *args):\n+ ys = _odeint(func, rtol, atol, mxstep, hmax, y0, ts, *args)\nreturn ys, (ys, ts, args)\n-def _odeint_rev(func, rtol, atol, mxstep, dtmax, res, g):\n+def _odeint_rev(func, rtol, atol, mxstep, hmax, res, g):\nys, ts, args = res\ndef aug_dynamics(augmented_state, t, *args):\n@@ -245,7 +245,7 @@ def _odeint_rev(func, rtol, atol, mxstep, dtmax, res, g):\n_, y_bar, t0_bar, args_bar = odeint(\naug_dynamics, (ys[i], y_bar, t0_bar, args_bar),\njnp.array([-ts[i], -ts[i - 1]]),\n- *args, rtol=rtol, atol=atol, mxstep=mxstep, dtmax=dtmax)\n+ *args, rtol=rtol, atol=atol, mxstep=mxstep, hmax=hmax)\ny_bar, t0_bar, args_bar = tree_map(op.itemgetter(1), (y_bar, t0_bar, args_bar))\n# Add gradient from current output\ny_bar = y_bar + g[i - 1]\n" }, { "change_type": "MODIFY", "old_path": "tests/ode_test.py", "new_path": "tests/ode_test.py", "diff": "@@ -251,7 +251,7 @@ class ODETest(jtu.JaxTestCase):\njtu.check_grads(f, (y0, ts, alpha), modes=[\"rev\"], order=2, atol=tol, rtol=tol)\n@jtu.skip_on_devices(\"tpu\", \"gpu\")\n- def test_dtmax(self):\n+ def test_hmax(self):\n\"\"\"Test max step size control.\"\"\"\ndef rhs(y, t):\n@@ -260,7 +260,7 @@ class ODETest(jtu.JaxTestCase):\n[t <= 2., (t >= 5.) & (t <= 7.)],\n[lambda s: jnp.array(1.), lambda s: jnp.array(-1.), lambda s: jnp.array(0.)]\n)\n- ys = odeint(func=rhs, y0=jnp.array(0.), t=jnp.array([0., 5., 10.]), dtmax=1.)\n+ ys = odeint(func=rhs, y0=jnp.array(0.), t=jnp.array([0., 5., 10.]), hmax=1.)\nself.assertTrue(jnp.abs(ys[1] - 2.) < 1e-4)\nself.assertTrue(jnp.abs(ys[2]) < 1e-4)\n" } ]
Python
Apache License 2.0
google/jax
changing dtmax to hmax
260,453
11.06.2022 14:24:19
14,400
57b89ba7cb735c11e7a3710c3f817e5dfcf02251
Added scipy.stats.gennorm.
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -55,6 +55,7 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\nsilently truncated to `1`.\n* {func}`jax.experimental.compilation_cache.initialize_cache` now supports gcs\nbucket path as input.\n+ * Added {func}`jax.scipy.stats.gennorm`.\n## jaxlib 0.3.11 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jaxlib-v0.3.10...main).\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.scipy.rst", "new_path": "docs/jax.scipy.rst", "diff": "@@ -220,6 +220,16 @@ jax.scipy.stats.gamma\nlogpdf\npdf\n+jax.scipy.stats.gennorm\n+~~~~~~~~~~~~~~~~~~~~~~~\n+.. automodule:: jax.scipy.stats.gennorm\n+.. autosummary::\n+ :toctree: _autosummary\n+\n+ cdf\n+ logpdf\n+ pdf\n+\njax.scipy.stats.geom\n~~~~~~~~~~~~~~~~~~~~\n.. automodule:: jax.scipy.stats.geom\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/scipy/stats/gennorm.py", "diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import scipy.stats as osp_stats\n+from jax import lax\n+from jax._src.numpy.util import _wraps\n+from jax._src.numpy.lax_numpy import _promote_args_inexact\n+\n+@_wraps(osp_stats.gennorm.logpdf, update_doc=False)\n+def logpdf(x, p):\n+ x, p = _promote_args_inexact(\"gennorm.logpdf\", x, p)\n+ return lax.log(.5 * p) - lax.lgamma(1/p) - lax.abs(x)**p\n+\n+@_wraps(osp_stats.gennorm.cdf, update_doc=False)\n+def cdf(x, p):\n+ x, p = _promote_args_inexact(\"gennorm.cdf\", x, p)\n+ return .5 * (1 + lax.sign(x) * lax.igamma(1/p, lax.abs(x)**p))\n+\n+@_wraps(osp_stats.gennorm.pdf, update_doc=False)\n+def pdf(x, p):\n+ return lax.exp(logpdf(x, p))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/__init__.py", "new_path": "jax/scipy/stats/__init__.py", "diff": "@@ -30,3 +30,4 @@ from jax.scipy.stats import t as t\nfrom jax.scipy.stats import uniform as uniform\nfrom jax.scipy.stats import chi2 as chi2\nfrom jax.scipy.stats import betabinom as betabinom\n+from jax.scipy.stats import gennorm as gennorm\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/scipy/stats/gennorm.py", "diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from jax._src.scipy.stats.gennorm import (\n+ cdf as cdf,\n+ logpdf as logpdf,\n+ pdf as pdf,\n+)\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_stats_test.py", "new_path": "tests/scipy_stats_test.py", "diff": "@@ -245,6 +245,34 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nself.assertAllClose(\nosp_stats.gamma.pdf(0.0, 1.0), lsp_stats.gamma.pdf(0.0, 1.0), atol=1E-6)\n+ @genNamedParametersNArgs(2)\n+ def testGenNormLogPdf(self, shapes, dtypes):\n+ rng = jtu.rand_default(self.rng())\n+ scipy_fun = osp_stats.gennorm.logpdf\n+ lax_fun = lsp_stats.gennorm.logpdf\n+\n+ def args_maker():\n+ x, p = map(rng, shapes, dtypes)\n+ return [x, p]\n+\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n+ tol=1e-4, rtol=1e-3)\n+ self._CompileAndCheck(lax_fun, args_maker)\n+\n+ @genNamedParametersNArgs(2)\n+ def testGenNormCdf(self, shapes, dtypes):\n+ rng = jtu.rand_default(self.rng())\n+ scipy_fun = osp_stats.gennorm.cdf\n+ lax_fun = lsp_stats.gennorm.cdf\n+\n+ def args_maker():\n+ x, p = map(rng, shapes, dtypes)\n+ return [x, p]\n+\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n+ tol=1e-4, rtol=1e-3)\n+ self._CompileAndCheck(lax_fun, args_maker)\n+\n@genNamedParametersNArgs(4)\ndef testNBinomLogPmf(self, shapes, dtypes):\nrng = jtu.rand_positive(self.rng())\n" } ]
Python
Apache License 2.0
google/jax
Added scipy.stats.gennorm.
260,624
14.06.2022 21:21:34
0
88f1b9fae70a4437ce45e769d0341bdabd691c59
adding os env to track JAX platform
[ { "change_type": "MODIFY", "old_path": "jax/_src/cloud_tpu_init.py", "new_path": "jax/_src/cloud_tpu_init.py", "diff": "@@ -48,6 +48,7 @@ def cloud_tpu_init():\nlibtpu.configure_library_path()\nos.environ.setdefault('GRPC_VERBOSITY', 'ERROR')\n+ os.environ['TPU_ML_PLATFORM'] = 'JAX'\n# If the user has set any topology-related env vars, don't set any\n# automatically.\n" } ]
Python
Apache License 2.0
google/jax
adding os env to track JAX platform
260,445
06.06.2022 21:27:43
0
ff637e12f1452b20cf7027f405be6ef78b1f9bbd
Allow doing reductions on empty arrays in some cases. Namely, when the reduction axis is not over the zero-sized dimension.
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/reductions.py", "new_path": "jax/_src/numpy/reductions.py", "diff": "@@ -73,16 +73,19 @@ def _reduction(a, name, np_fun, op, init_val, has_identity=True,\nlax_internal._check_user_dtype_supported(dtype, name)\naxis = core.concrete_or_error(None, axis, f\"axis argument to jnp.{name}().\")\n- if initial is None and not has_identity:\n- if not _all(core.greater_equal_dim(d, 1) for d in np.shape(a)):\n- raise ValueError(f\"zero-size array to reduction operation {name} which has no identity\")\n- if where_ is not None:\n+ if initial is None and not has_identity and where_ is not None:\nraise ValueError(f\"reduction operation {name} does not have an identity, so to use a \"\nf\"where mask one has to specify 'initial'\")\na = a if isinstance(a, ndarray) else _asarray(a)\na = preproc(a) if preproc else a\npos_dims, dims = _reduction_dims(a, axis)\n+\n+ if initial is None and not has_identity:\n+ shape = np.shape(a)\n+ if not _all(core.greater_equal_dim(shape[d], 1) for d in pos_dims):\n+ raise ValueError(f\"zero-size array to reduction operation {name} which has no identity\")\n+\nresult_dtype = dtypes.canonicalize_dtype(dtype or dtypes.dtype(np_fun(np.ones((), dtype=dtypes.dtype(a)))))\nif upcast_f16_for_computation and dtypes.issubdtype(result_dtype, np.inexact):\ncomputation_dtype = _upcast_f16(result_dtype)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -876,6 +876,42 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, rtol=tol)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(itertools.chain.from_iterable(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": \"{}_inshape={}_axis={}_keepdims={}\".format(\n+ rec.test_name.capitalize(),\n+ jtu.format_shape_dtype_string(shape, dtype), axis, keepdims),\n+ \"rng_factory\": rec.rng_factory, \"shape\": shape, \"dtype\": dtype,\n+ \"np_op\": getattr(np, rec.name), \"jnp_op\": getattr(jnp, rec.name),\n+ \"axis\": axis, \"keepdims\": keepdims, \"inexact\": rec.inexact}\n+ for shape in rec.shapes if np.prod(shape) == 0\n+ for dtype in rec.dtypes\n+ for keepdims in [False, True]\n+ for axis in range(-len(shape), len(shape)) if shape[axis] >= 1)\n+ for rec in JAX_REDUCER_INITIAL_RECORDS))\n+ def testReducerNoInitialZeroDims(self, np_op, jnp_op, rng_factory, shape, dtype, axis,\n+ keepdims, inexact):\n+ rng = rng_factory(self.rng())\n+ is_bf16_nan_test = dtype == jnp.bfloat16 and rng_factory.__name__ == 'rand_some_nan'\n+ @jtu.ignore_warning(category=RuntimeWarning,\n+ message=\"Degrees of freedom <= 0 for slice.*\")\n+ @jtu.ignore_warning(category=np.ComplexWarning)\n+ def np_fun(x):\n+ x = np.asarray(x)\n+ if inexact:\n+ x = x.astype(dtypes._to_inexact_dtype(x.dtype))\n+ x_cast = x if not is_bf16_nan_test else x.astype(np.float32)\n+ res = np_op(x_cast, axis, keepdims=keepdims)\n+ res = res if not is_bf16_nan_test else res.astype(jnp.bfloat16)\n+ return res\n+\n+ jnp_fun = lambda x: jnp_op(x, axis, keepdims=keepdims)\n+ jnp_fun = jtu.ignore_warning(category=jnp.ComplexWarning)(jnp_fun)\n+ args_maker = lambda: [rng(shape, dtype)]\n+ tol = {jnp.bfloat16: 3E-2}\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, rtol=tol)\n+ self._CompileAndCheck(jnp_fun, args_maker)\n+\n@parameterized.named_parameters(itertools.chain.from_iterable(\njtu.cases_from_list(\n{\"testcase_name\": \"{}_inshape={}_axis={}_keepdims={}_initial={}_whereshape={}\".format(\n" } ]
Python
Apache License 2.0
google/jax
Allow doing reductions on empty arrays in some cases. Namely, when the reduction axis is not over the zero-sized dimension.
260,563
09.06.2022 20:38:53
-7,200
311e6a92f9738f74c45c3aff75ebfbbc7b09afcd
Add bitwise XOR reducer to `lax.reduce` This commit adds handling for the `lax.bitwise_xor` operation to `lax.reduce`. It also includes a new standard reduce primitive, modeled after the existing `and`/ `or` reducer primitives.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -983,6 +983,8 @@ def _get_monoid_reducer(monoid_op: Callable,\nreturn np.equal(aval.val, _get_max_identity(dtype)) and _reduce_or\nelif monoid_op is bitwise_and and dtype == np.bool_:\nreturn np.equal(aval.val, _get_min_identity(dtype)) and _reduce_and\n+ elif monoid_op is bitwise_xor and dtype == np.bool_:\n+ return np.equal(aval.val, _get_max_identity(dtype)) and _reduce_xor\nelif monoid_op is max:\nreturn np.equal(aval.val, _get_max_identity(dtype)) and _reduce_max\nelif monoid_op is min:\n@@ -1023,6 +1025,8 @@ def _reduce_or(operand: Array, axes: Sequence[int]) -> Array:\ndef _reduce_and(operand: Array, axes: Sequence[int]) -> Array:\nreturn reduce_and_p.bind(operand, axes=tuple(axes))\n+def _reduce_xor(operand: Array, axes: Sequence[int]) -> Array:\n+ return reduce_xor_p.bind(operand, axes=tuple(axes))\ndef sort(operand: Union[Array, Sequence[Array]], dimension: int = -1,\nis_stable: bool = True, num_keys: int = 1) -> Union[Array, Tuple[Array, ...]]:\n@@ -3618,6 +3622,12 @@ reduce_and_p = standard_primitive(\nbatching.defreducer(reduce_and_p)\n+reduce_xor_p = standard_primitive(\n+ _reduce_logical_shape_rule, _fixed_dtype(np.bool_), 'reduce_xor',\n+ weak_type_rule=_strip_weak_type)\n+batching.defreducer(reduce_xor_p)\n+\n+\ndef _unary_reduce_lower(reducer, unit_factory, ctx, x, *, axes):\naval_out, = ctx.avals_out\ndtype = aval_out.dtype\n@@ -3639,6 +3649,8 @@ mlir.register_lowering(reduce_or_p, partial(_unary_reduce_lower, mhlo.OrOp,\nlambda dtype: np.array(False, dtype)))\nmlir.register_lowering(reduce_and_p, partial(_unary_reduce_lower, mhlo.AndOp,\nlambda dtype: np.array(True, dtype)))\n+mlir.register_lowering(reduce_xor_p, partial(_unary_reduce_lower, mhlo.XorOp,\n+ lambda dtype: np.array(False, dtype)))\nmlir.register_lowering(reduce_min_p, partial(_unary_reduce_lower, mlir.min_mhlo,\n_get_min_identity))\nmlir.register_lowering(reduce_max_p, partial(_unary_reduce_lower, mlir.max_mhlo,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -981,6 +981,7 @@ tf_not_yet_impl = [\n\"igamma_grad_a\",\n\"random_gamma_grad\",\n\"reduce_precision\",\n+ \"reduce_xor\",\n\"schur\",\n\"closed_call\",\n\"unreachable\",\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/__init__.py", "new_path": "jax/lax/__init__.py", "diff": "@@ -182,6 +182,7 @@ from jax._src.lax.lax import (\nreduce_precision_p as reduce_precision_p,\nreduce_prod_p as reduce_prod_p,\nreduce_sum_p as reduce_sum_p,\n+ reduce_xor_p as reduce_xor_p,\nregularized_incomplete_beta_p as regularized_incomplete_beta_p,\nrem as rem,\nrem_p as rem_p,\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -1748,6 +1748,44 @@ class LaxTest(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, dtype)]\nself._CompileAndCheck(fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_op={}_shape={}_reducedims={}_initval={}_prim={}\"\n+ .format(op.__name__, shape, dims, init_val, prim),\n+ \"op\": op, \"init_val\": init_val, \"shape\": shape, \"dims\": dims, \"prim\": prim}\n+ for init_val, op , prim in [\n+ (True, lax.bitwise_and, jax.lax.reduce_and_p),\n+ (False, lax.bitwise_or, jax.lax.reduce_or_p),\n+ (False, lax.bitwise_xor, jax.lax.reduce_xor_p),\n+ ]\n+ for shape, dims in [\n+ [(3, 4, 5), (0,)], [(3, 4, 5), (1, 2)],\n+ [(3, 4, 5), (0, 2)], [(3, 4, 5), (0, 1, 2)]\n+ ]))\n+ def testReduceBoolean(self, op, init_val, shape, dims, prim):\n+ def reference_fun(operand, init_value):\n+ np_op = getattr(np, op.__name__)\n+ return np_op.reduce(operand, axis=dims, initial=init_val)\n+\n+ dtype = np.bool_\n+ rng = jtu.rand_bool(self.rng())\n+ init_val = np.asarray(init_val, dtype=dtype)\n+ fun = lambda operand, init_val: lax.reduce(operand, init_val, op, dims)\n+ args_maker = lambda: [rng(shape, dtype), init_val]\n+ self._CompileAndCheck(fun, args_maker)\n+ self._CheckAgainstNumpy(reference_fun, fun, args_maker)\n+\n+ # recheck with a static init_val\n+ fun = lambda operand: lax.reduce(operand, init_val, op, dims)\n+ reference_fun = partial(reference_fun, init_value=init_val)\n+ args_maker = lambda: [rng(shape, dtype)]\n+ self._CompileAndCheck(fun, args_maker)\n+ self._CheckAgainstNumpy(reference_fun, fun, args_maker)\n+\n+ # check that the correct monoid reducer primitive is used inside the\n+ # jaxpr. This requires the init_val (monoid identity element) to be static\n+ jaxpr = jax.make_jaxpr(fun)(rng(shape, dtype))\n+ self.assertEqual(jaxpr.eqns[0].primitive, prim)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_op={}.{}_arr_weak_type={}_init_weak_type={}\"\n.format(op_namespace.__name__, op, arr_weak_type, init_weak_type),\n" } ]
Python
Apache License 2.0
google/jax
Add bitwise XOR reducer to `lax.reduce` This commit adds handling for the `lax.bitwise_xor` operation to `lax.reduce`. It also includes a new standard reduce primitive, modeled after the existing `and`/ `or` reducer primitives.
260,510
02.06.2022 11:50:03
25,200
5d3f48204d4d0a7f571452bda21a2d9a38380e28
Add stateful for loop primitives Adds a `get/swap/addupdate` primitive, along with impl, abstract_eval and jvp rules.
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_util.py", "new_path": "jax/_src/ad_util.py", "diff": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n+from __future__ import annotations\n-from typing import Any, Callable, Dict, Type\n+from typing import Any, Callable, Dict, Type, Union\nfrom jax import core\nfrom jax.core import (lattice_join, Primitive, valid_jaxtype, raise_to_shaped,\n@@ -45,6 +46,11 @@ def add_abstract(xs, ys):\njaxval_zeros_likers: Dict[type, Array] = {}\n+def instantiate(z: Union[Zero, Array]) -> Array:\n+ if type(z) is Zero:\n+ return zeros_like_aval(z.aval)\n+ return z\n+\ndef zeros_like_aval(aval):\nreturn aval_zeros_likers[type(aval)](aval)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Module for the `for_loop` primitive.\"\"\"\n+from functools import partial\n+\n+from typing import Any, List, Tuple\n+\n+from jax import core\n+from jax.interpreters import ad\n+from jax._src import ad_util\n+from jax._src import pretty_printer as pp\n+\n+\n+## Helpful type aliases\n+Ref = Any\n+Array = Any\n+\n+## State effect\n+\n+class StateEffect: pass\n+State = StateEffect\n+\n+## get/swap/addupdate implementations\n+\n+# `get` reads a value from a `Ref` type, a.k.a.:\n+# a = get_p.bind(x)\n+# or we can read using indices:\n+# a = get_p.bind(x, 0, 1)\n+# Staging out `a = get_p.bind(x)` where the aval of `x` is\n+# `ShapedArrayRef((3,), np.dtype('float32'))` leads to a jaxpr eqn printed like\n+# a:f32[3] <- x[]\n+get_p = core.Primitive(\"get\")\n+\n+def _get_impl(ref: Ref, *idx: int):\n+ del ref, idx\n+ raise ValueError(\"Can't evaluate `get` outside a stateful context.\")\n+get_p.def_impl(_get_impl)\n+\n+def ref_get(ref: Ref, idx: Tuple[int]) -> Array:\n+ \"\"\"Reads a value from a `Ref`, a.k.a. value <- ref[idx].\"\"\"\n+ return get_p.bind(ref, *idx)\n+\n+# `swap` mutates a `Ref`, setting its value and returns its previous value.\n+# b = swap_p.bind(x, a)\n+# It generalizes the setting operation for a `Ref` as we can ignore the return\n+# value:\n+# _ = swap_p.bind(x, a)\n+# `swap_p` also takes in index arguments following the value, i.e.:\n+# _ = swap_p.bind(x, a, 0, 1)\n+# Staging out `b = swap_p.bind(x, a)` where the aval of `x` is\n+# `ShapedArrayRef((3,), np.dtype('float32'))` and the aval of `a` is\n+# `ShapedArray((3,), np.dtype('float32'))` leads to a jaxpr eqn printed like\n+# b:f32[3], x:Ref{f32[3]} <- x, a\n+# Staging out `_ = swap_p.bind(x, a, i, j)` where the aval of `x` is\n+# `ShapedArrayRef((3,), np.dtype('float32'))` , the aval of `a` is\n+# `ShapedArray((3,), np.dtype('float32'))`, and the avals of both `i` and `j`\n+# are `ShapedArray((), np.dtype('int32'))` leads to a jaxpr eqn printed like\n+# x:Ref{f32[3]}[i, j] <- a\n+swap_p = core.Primitive(\"swap\")\n+\n+def _swap_impl(ref: Ref, value: Array, *idx: int):\n+ del ref, idx, value\n+ raise ValueError(\"Can't evaluate `swap` outside a stateful context.\")\n+swap_p.def_impl(_swap_impl)\n+\n+def ref_swap(ref: Ref, idx: Tuple[int], value: Array) -> Array:\n+ \"\"\"Sets a `Ref`'s value and returns the original value.\"\"\"\n+ return swap_p.bind(ref, value, *idx)\n+\n+def ref_set(ref: Ref, idx: Tuple[int], value: Array) -> None:\n+ \"\"\"Sets a `Ref`'s value, a.k.a. ref[idx] <- value.\"\"\"\n+ ref_swap(ref, idx, value)\n+\n+\n+# `addupdate_p` mutates a `Ref`, adding a value to its existing value.\n+# Semantically,\n+# ```\n+# addupdate ref a *idx\n+# ```\n+# is equivalent to\n+# ```\n+# b = get ref *idx\n+# c = add b x\n+# _ = swap ref c *idx\n+# ```\n+addupdate_p = core.Primitive('addupdate')\n+addupdate_p.multiple_results = True\n+\n+def _addupdate_impl(ref: Ref, value: Array, *idx: int):\n+ del ref, idx, value\n+ raise ValueError(\"Can't evaluate `addupdate` outside a stateful context.\")\n+addupdate_p.def_impl(_addupdate_impl)\n+\n+def ref_addupdate(ref: Ref, idx: Tuple[int], x: Array) -> None:\n+ \"\"\"Mutates a ref with an additive update i.e. `ref[idx] += x`.\"\"\"\n+ return addupdate_p.bind(ref, x, *idx)\n+\n+## get/set/addupdate abstract evaluation rules\n+\n+# We need an aval for `Ref`s so we can represent `get` and `swap` in Jaxprs.\n+# A `ShapedArrayRef` is a abstract value for mutable containers of array types\n+class ShapedArrayRef(core.AbstractValue):\n+ __slots__ = [\"shape\", \"dtype\"]\n+\n+ def __init__(self, shape, dtype):\n+ self.shape = shape\n+ self.dtype = dtype\n+\n+ def join(self, other):\n+ assert core.symbolic_equal_shape(self.shape, other.shape)\n+ assert self.dtype == other.dtype\n+ return self\n+\n+ def _getitem(self, tracer, idx) -> Array:\n+ if not isinstance(idx, tuple):\n+ idx = idx,\n+ return ref_get(tracer, idx)\n+\n+ def _setitem(self, tracer, idx, val) -> None:\n+ if not isinstance(idx, tuple):\n+ idx = idx,\n+ return ref_set(tracer, idx, val)\n+\n+ def __repr__(self) -> str:\n+ a = core.ShapedArray(self.shape, self.dtype)\n+ return f'Ref{{{a.str_short()}}}'\n+\n+ def at_least_vspace(self):\n+ return self\n+\n+core.raise_to_shaped_mappings[ShapedArrayRef] = lambda aval, _: aval\n+\n+def _get_abstract_eval(ref_aval: ShapedArrayRef, *idx: int):\n+ if not isinstance(ref_aval, ShapedArrayRef):\n+ raise ValueError(f\"`get` must be called on `Ref` types: {ref_aval}.\")\n+ return core.ShapedArray(ref_aval.shape[len(idx):], ref_aval.dtype), {State}\n+get_p.def_effectful_abstract_eval(_get_abstract_eval)\n+\n+\n+def _swap_abstract_eval(ref_aval: ShapedArrayRef, val_aval: core.AbstractValue,\n+ *idx: int):\n+ if not isinstance(ref_aval, ShapedArrayRef):\n+ raise ValueError(f\"`swap` must be called on `Ref` types: {ref_aval}.\")\n+ val_aval = core.raise_to_shaped(val_aval)\n+ assert isinstance(val_aval, core.ShapedArray)\n+ expected_output_shape = ref_aval.shape[len(idx):]\n+ if expected_output_shape != val_aval.shape:\n+ raise ValueError(\"Invalid shape for `swap`. \"\n+ f\"Ref shape: {ref_aval.shape}. \"\n+ f\"Value shape: {val_aval.shape}. \"\n+ f\"Indices: {idx}. \")\n+ return core.ShapedArray(ref_aval.shape[len(idx):], ref_aval.dtype), {State}\n+swap_p.def_effectful_abstract_eval(_swap_abstract_eval)\n+\n+\n+def _addupdate_abstract_eval(ref_aval: ShapedArrayRef,\n+ val_aval: core.AbstractValue,\n+ *idx: int):\n+ if not isinstance(ref_aval, ShapedArrayRef):\n+ raise ValueError(f\"`addupdate` must be called on `Ref` types: {ref_aval}.\")\n+ val_aval = core.raise_to_shaped(val_aval)\n+ assert isinstance(val_aval, core.ShapedArray)\n+ expected_output_shape = ref_aval.shape[len(idx):]\n+ if expected_output_shape != val_aval.shape:\n+ raise ValueError(\"Invalid shape for `swap`. \"\n+ f\"Ref shape: {ref_aval.shape}. \"\n+ f\"Value shape: {val_aval.shape}. \"\n+ f\"Indices: {idx}. \")\n+ return [], {State}\n+addupdate_p.def_effectful_abstract_eval(_addupdate_abstract_eval)\n+\n+## Pretty printing for `get` and `swap` in jaxprs\n+\n+pp_ref = partial(pp.color, intensity=pp.Intensity.NORMAL,\n+ foreground=pp.Color.GREEN)\n+\n+def _get_pp_rule(eqn, context, settings):\n+ # Pretty prints `a = get x i` as `x[i] <- a`\n+ y, = eqn.outvars\n+ x, *idx = eqn.invars\n+ idx = ','.join(core.pp_var(i, context) for i in idx)\n+ lhs = core.pp_vars([y], context, print_shapes=settings.print_shapes)\n+ return [lhs, pp.text(' <- '), pp_ref(pp.concat([\n+ pp.text(core.pp_var(x, context)), pp.text('['), pp.text(idx), pp.text(']')\n+ ]))]\n+core.pp_eqn_rules[get_p] = _get_pp_rule\n+\n+def _swap_pp_rule(eqn, context, settings):\n+ y, = eqn.outvars\n+ x, v, *idx = eqn.invars\n+ idx = ','.join(core.pp_var(i, context) for i in idx)\n+ if type(y) is core.DropVar:\n+ # In the case of a set (ignored return value),\n+ # pretty print `_ = swap x v i` as `x[i] <- v`\n+ del y\n+ return pp.concat([\n+ pp_ref(pp.concat([\n+ pp.text(core.pp_var(x, context)),\n+ pp.text('['), pp.text(idx), pp.text(']')\n+ ])), pp.text(' <- '), pp.text(core.pp_var(v, context))])\n+ else:\n+ # pretty-print `y:T = swap x v i` as `y:T, x[i] <- x[i], v`\n+ x_i = pp.concat([pp.text(core.pp_var(x, context)),\n+ pp.text('['), pp.text(idx), pp.text(']')])\n+ y = core.pp_vars([y], context, print_shapes=settings.print_shapes)\n+ return [y, pp.text(', '), x_i, pp.text(' <- '),\n+ x_i, pp.text(', '), pp.text(core.pp_var(v, context))]\n+core.pp_eqn_rules[swap_p] = _swap_pp_rule\n+\n+def _addupdate_pp_rule(eqn, context, settings):\n+ # pretty-print ` = addupdate x i v` as `x[i] += v`\n+ () = eqn.outvars\n+ x, v, *idx = eqn.invars\n+ idx = ','.join(core.pp_var(i, context) for i in idx)\n+ return [\n+ pp_ref(pp.concat([\n+ pp.text(core.pp_var(x, context)),\n+ pp.text('['), pp.text(idx), pp.text(']')\n+ ])), pp.text(' += '), pp.text(core.pp_var(v, context))]\n+core.pp_eqn_rules[addupdate_p] = _addupdate_pp_rule\n+\n+## get/swap/addupdate JVP rules\n+\n+def _get_jvp(primals: List[Any], tangents: List[Any]):\n+ ref_primal, *idx = primals\n+ assert isinstance(ref_primal.aval, ShapedArrayRef)\n+ ref_tangent, *_ = tangents\n+ assert isinstance(ref_tangent.aval, ShapedArrayRef)\n+ return ref_get(ref_primal, idx), ref_get(ref_tangent, idx) # type: ignore[arg-type]\n+ad.primitive_jvps[get_p] = _get_jvp\n+\n+def _swap_jvp(primals: List[Any], tangents: List[Any]):\n+ ref_primal, x_primal, *idx = primals\n+ assert isinstance(ref_primal.aval, ShapedArrayRef)\n+ ref_tangent, x_tangent, *_ = tangents\n+ assert isinstance(ref_tangent.aval, ShapedArrayRef)\n+ x_tangent = ad_util.instantiate(x_tangent)\n+ return (ref_swap(ref_tangent, idx, x_primal), # type: ignore[arg-type]\n+ ref_swap(ref_tangent, idx, x_tangent)) # type: ignore[arg-type]\n+ad.primitive_jvps[swap_p] = _swap_jvp\n+\n+def addupdate_jvp_rule(primals: List[Any], tangents: List[Any]):\n+ ref_primal, x_primal, *idx = primals\n+ ref_tangent, x_tangent, *_ = tangents\n+ x_tangent = ad_util.instantiate(x_tangent)\n+ addupdate_p.bind(ref_primal, x_primal, *idx)\n+ addupdate_p.bind(ref_tangent, x_tangent, *idx)\n+ return [], []\n+ad.primitive_jvps[addupdate_p] = addupdate_jvp_rule\n+\n+## get/swap/addupdate transpose rules\n+\n+def _get_transpose(g, ref, *idx):\n+ # get transpose is addupdate\n+ if type(g) is not ad_util.Zero:\n+ ref_addupdate(ref, idx, g)\n+ return [None] + [None] * len(idx)\n+ad.primitive_transposes[get_p] = _get_transpose\n+\n+def _swap_transpose(g, ref, x, *idx):\n+ # swap transpose is swap\n+ x_bar = ref_swap(ref, idx, ad_util.instantiate(g))\n+ return [None, x_bar] + [None] * len(idx)\n+ad.primitive_transposes[swap_p] = _swap_transpose\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -2448,14 +2448,13 @@ def pp_kv_pairs(kv_pairs, context: JaxprPpContext, settings: JaxprPpSettings) ->\n)\ndef pp_eqn(eqn, context: JaxprPpContext, settings: JaxprPpSettings) -> pp.Doc:\n- lhs = pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\nannotation = (source_info_util.summarize(eqn.source_info)\nif settings.source_info else None)\nrule = pp_eqn_rules.get(eqn.primitive)\nname_stack_annotation = f'[{eqn.source_info.name_stack}]' if settings.name_stack else None\nif rule and settings.custom_pp_eqn_rules:\n- rhs = rule(eqn, context, settings)\n- else:\n+ return pp.concat(rule(eqn, context, settings))\n+ lhs = pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\nrhs = [pp.text(eqn.primitive.name, annotation=name_stack_annotation),\npp_kv_pairs(sorted(eqn.params.items()), context, settings),\npp.text(\" \") + pp_vars(eqn.invars, context)]\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -461,9 +461,13 @@ def _pp_xla_call(eqn: core.JaxprEqn, context: core.JaxprPpContext,\nk == 'backend' and v is not None or\nk == 'device' and v is not None or\nk == 'donated_invars' and any(v)}\n- return [pp.text(eqn.primitive.name),\n+ annotation = (source_info_util.summarize(eqn.source_info)\n+ if settings.source_info else None)\n+ lhs = core.pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\n+ rhs = [pp.text(eqn.primitive.name),\ncore.pp_kv_pairs(sorted(printed_params.items()), context, settings),\npp.text(\" \") + core.pp_vars(eqn.invars, context)]\n+ return [lhs, pp.text(\" = \", annotation=annotation), *rhs]\ncore.pp_eqn_rules[xla_call_p] = _pp_xla_call\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -29,13 +29,16 @@ import jax\nfrom jax import core\nfrom jax.errors import UnexpectedTracerError\nfrom jax import lax\n+from jax import linear_util as lu\nfrom jax import random\nfrom jax._src import test_util as jtu\nfrom jax import tree_util\nfrom jax._src.util import unzip2\nfrom jax.experimental import maps\n+from jax.interpreters import partial_eval as pe\nimport jax.numpy as jnp # scan tests use numpy\nimport jax.scipy as jsp\n+from jax._src.lax.control_flow import for_loop\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -2443,5 +2446,161 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nreturn lax.cond(x < 0., lambda x: x, lambda x: x, x)\njax.vmap(jax.jacrev(lambda x: cond_id(cond_id(x))))(jnp.ones(1))\n+\n+class ForLoopTest(jtu.JaxTestCase):\n+\n+ def test_cant_eval_get_primitive(self):\n+ with self.assertRaises(ValueError):\n+ for_loop.get_p.bind(jnp.ones(5))\n+\n+ def test_cant_eval_swap_primitive(self):\n+ with self.assertRaises(ValueError):\n+ for_loop.swap_p.bind(jnp.ones(5), jnp.zeros(5))\n+\n+ def test_cant_eval_addupdate_primitive(self):\n+ with self.assertRaises(ValueError):\n+ for_loop.addupdate_p.bind(jnp.ones(5), jnp.zeros(5))\n+\n+ def test_get_abstract_eval(self):\n+ ref_aval = for_loop.ShapedArrayRef((1, 2, 3), jnp.float32)\n+ out_aval, effect = for_loop.get_p.abstract_eval(ref_aval, 0)\n+ self.assertSetEqual(effect, {for_loop.State})\n+ self.assertTupleEqual(out_aval.shape, (2, 3))\n+ self.assertEqual(out_aval.dtype, jnp.float32)\n+\n+ def test_get_abstract_aval_must_take_in_refs(self):\n+ with self.assertRaises(ValueError):\n+ for_loop.get_p.abstract_eval(core.ShapedArray((1, 2, 3), jnp.float32))\n+\n+ def test_swap_abstract_eval(self):\n+ ref_aval = for_loop.ShapedArrayRef((1, 2, 3), jnp.float32)\n+ val_aval = core.ShapedArray((2, 3), jnp.float32)\n+ out_aval, effect = for_loop.swap_p.abstract_eval(ref_aval, val_aval, 0)\n+ self.assertSetEqual(effect, {for_loop.State})\n+ self.assertTupleEqual(out_aval.shape, (2, 3))\n+ self.assertEqual(out_aval.dtype, jnp.float32)\n+\n+ def test_swap_abstract_eval_must_take_in_refs(self):\n+ with self.assertRaises(ValueError):\n+ for_loop.swap_p.abstract_eval(core.ShapedArray((1, 2, 3), jnp.float32),\n+ core.ShapedArray((1, 2, 3), jnp.float32))\n+\n+ def test_swap_checks_for_correct_shapes(self):\n+ with self.assertRaises(ValueError):\n+ for_loop.swap_p.abstract_eval(\n+ for_loop.ShapedArrayRef((1, 2, 3), jnp.float32),\n+ core.ShapedArray((2, 3), jnp.float32))\n+ with self.assertRaises(ValueError):\n+ for_loop.swap_p.abstract_eval(\n+ for_loop.ShapedArrayRef((1, 2, 3), jnp.float32),\n+ core.ShapedArray((1, 2, 3, 4), jnp.float32))\n+ for_loop.swap_p.abstract_eval(\n+ for_loop.ShapedArrayRef((1, 2, 3), jnp.float32),\n+ core.ShapedArray((2, 3), jnp.float32), 1)\n+\n+ def test_addupdate_abstract_eval(self):\n+ ref_aval = for_loop.ShapedArrayRef((1, 2, 3), jnp.float32)\n+ val_aval = core.ShapedArray((2, 3), jnp.float32)\n+ out_avals, effect = for_loop.addupdate_p.abstract_eval(ref_aval, val_aval,\n+ 0)\n+ self.assertSetEqual(effect, {for_loop.State})\n+ self.assertListEqual(out_avals, [])\n+\n+ def test_addupdate_abstract_eval_must_take_in_refs(self):\n+ with self.assertRaises(ValueError):\n+ for_loop.addupdate_p.abstract_eval(core.ShapedArray((1, 2, 3), jnp.float32),\n+ core.ShapedArray((1, 2, 3), jnp.float32))\n+\n+ def test_addupdate_checks_for_correct_shapes(self):\n+ with self.assertRaises(ValueError):\n+ for_loop.addupdate_p.abstract_eval(\n+ for_loop.ShapedArrayRef((1, 2, 3), jnp.float32),\n+ core.ShapedArray((2, 3), jnp.float32))\n+ with self.assertRaises(ValueError):\n+ for_loop.addupdate_p.abstract_eval(\n+ for_loop.ShapedArrayRef((1, 2, 3), jnp.float32),\n+ core.ShapedArray((1, 2, 3, 4), jnp.float32))\n+ for_loop.addupdate_p.abstract_eval(\n+ for_loop.ShapedArrayRef((1, 2, 3), jnp.float32),\n+ core.ShapedArray((2, 3), jnp.float32), 1)\n+\n+ def test_can_represent_get_and_swap_in_jaxprs(self):\n+\n+ def body(x):\n+ x[()] = 1\n+ x[()] = 2\n+ return (x[()],)\n+ jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(\n+ lu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n+ self.assertLen(consts, 0)\n+ self.assertListEqual(out_avals, [core.ShapedArray((), jnp.int32)])\n+ self.assertEqual(jaxpr.eqns[0].primitive, for_loop.swap_p)\n+ self.assertEqual(jaxpr.eqns[1].primitive, for_loop.swap_p)\n+ self.assertEqual(jaxpr.eqns[2].primitive, for_loop.get_p)\n+\n+ def test_can_represent_addupdate_in_jaxprs(self):\n+\n+ def body(x):\n+ for_loop.ref_addupdate(x, (), 1)\n+ return (x[()],)\n+ jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(\n+ lu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n+ self.assertLen(consts, 0)\n+ self.assertListEqual(out_avals, [core.ShapedArray((), jnp.int32)])\n+ self.assertEqual(jaxpr.eqns[0].primitive, for_loop.addupdate_p)\n+\n+ def test_get_jvp(self):\n+\n+ def f(r):\n+ x = r[()]\n+ return jnp.cos(x)\n+\n+ def g(r, rdot):\n+ return jax.jvp(f, (r,), (rdot,))\n+\n+ in_avals = [for_loop.ShapedArrayRef((), jnp.dtype('float32')),\n+ for_loop.ShapedArrayRef((), jnp.dtype('float32'))]\n+ jaxpr, _, _ = pe.trace_to_jaxpr_dynamic(lu.wrap_init(g), in_avals)\n+ self.assertEqual(jaxpr.eqns[0].primitive, for_loop.get_p)\n+ self.assertEqual(jaxpr.eqns[1].primitive, for_loop.get_p)\n+\n+ def test_swap_jvp(self):\n+\n+ def f(a):\n+ x = a[()]\n+ a[()] = jnp.sin(x)\n+ return a[()]\n+\n+ def g(r, rdot):\n+ return jax.jvp(f, (r,), (rdot,))\n+\n+ in_avals = [for_loop.ShapedArrayRef((), jnp.dtype('float32')),\n+ for_loop.ShapedArrayRef((), jnp.dtype('float32'))]\n+ jaxpr, _, _ = pe.trace_to_jaxpr_dynamic(lu.wrap_init(g), in_avals)\n+ self.assertEqual(jaxpr.eqns[0].primitive, for_loop.get_p)\n+ self.assertEqual(jaxpr.eqns[1].primitive, for_loop.get_p)\n+ self.assertEqual(jaxpr.eqns[2].primitive, lax.sin_p)\n+ self.assertEqual(jaxpr.eqns[3].primitive, lax.cos_p)\n+ self.assertEqual(jaxpr.eqns[4].primitive, lax.mul_p)\n+ self.assertEqual(jaxpr.eqns[5].primitive, for_loop.swap_p)\n+ self.assertEqual(jaxpr.eqns[6].primitive, for_loop.swap_p)\n+\n+ def test_addupdate_jvp(self):\n+\n+ def f(a):\n+ for_loop.ref_addupdate(a, (), 1.)\n+ return a[()]\n+\n+ def g(r, rdot):\n+ return jax.jvp(f, (r,), (rdot,))\n+\n+ in_avals = [for_loop.ShapedArrayRef((), jnp.dtype('float32')),\n+ for_loop.ShapedArrayRef((), jnp.dtype('float32'))]\n+ jaxpr, _, _ = pe.trace_to_jaxpr_dynamic(lu.wrap_init(g), in_avals)\n+ self.assertEqual(jaxpr.eqns[0].primitive, for_loop.addupdate_p)\n+ self.assertEqual(jaxpr.eqns[1].primitive, for_loop.addupdate_p)\n+ self.assertEqual(jaxpr.eqns[2].primitive, for_loop.get_p)\n+ self.assertEqual(jaxpr.eqns[3].primitive, for_loop.get_p)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add stateful for loop primitives (#10982) Adds a `get/swap/addupdate` primitive, along with impl, abstract_eval and jvp rules. Co-authored-by: Matthew Johnson <mattjj@google.com>
260,510
16.06.2022 13:01:57
25,200
e705462e79ea54eb517653a074b83bebae61f73a
Add `discharge_state` to convert stateful jaxprs into pure jaxprs
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "\"\"\"Module for the `for_loop` primitive.\"\"\"\nfrom functools import partial\n-from typing import Any, List, Tuple\n+from typing import Any, Dict, List, Sequence, Tuple\nfrom jax import core\n+from jax import lax\n+from jax import linear_util as lu\nfrom jax.interpreters import ad\n+from jax.interpreters import partial_eval as pe\nfrom jax._src import ad_util\nfrom jax._src import pretty_printer as pp\n+from jax._src import util\n+## JAX utilities\n+\n+map, unsafe_map = util.safe_map, map\n+zip, unsafe_zip = util.safe_zip, zip\n## Helpful type aliases\nRef = Any\n@@ -204,11 +212,11 @@ def _swap_pp_rule(eqn, context, settings):\n# In the case of a set (ignored return value),\n# pretty print `_ = swap x v i` as `x[i] <- v`\ndel y\n- return pp.concat([\n+ return [\npp_ref(pp.concat([\npp.text(core.pp_var(x, context)),\npp.text('['), pp.text(idx), pp.text(']')\n- ])), pp.text(' <- '), pp.text(core.pp_var(v, context))])\n+ ])), pp.text(' <- '), pp.text(core.pp_var(v, context))]\nelse:\n# pretty-print `y:T = swap x v i` as `y:T, x[i] <- x[i], v`\nx_i = pp.concat([pp.text(core.pp_var(x, context)),\n@@ -273,3 +281,95 @@ def _swap_transpose(g, ref, x, *idx):\nx_bar = ref_swap(ref, idx, ad_util.instantiate(g))\nreturn [None, x_bar] + [None] * len(idx)\nad.primitive_transposes[swap_p] = _swap_transpose\n+\n+\n+## Discharging state\n+\n+# Let's say we have a jaxpr that takes in `Ref`s and outputs regular JAX values\n+# (`Ref`s should never be outputs from jaxprs). We'd like to convert that jaxpr\n+# into a \"pure\" jaxpr that takes in and outputs values and no longer has the\n+# `State` effect.\n+\n+def discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any]) -> Tuple[core.Jaxpr, List[Any]]:\n+ \"\"\"Converts a jaxpr that takes in `Ref`s into one that doesn't.\"\"\"\n+ in_avals = [core.ShapedArray(v.aval.shape, v.aval.dtype)\n+ if type(v.aval) is ShapedArrayRef\n+ else v.aval for v in jaxpr.invars]\n+ eval_jaxpr = lu.wrap_init(partial(_eval_jaxpr_discharge_state, jaxpr, consts))\n+ new_jaxpr, _ , new_consts = pe.trace_to_jaxpr_dynamic(eval_jaxpr, in_avals)\n+ return new_jaxpr, new_consts\n+\n+def _dynamic_index(x, idx):\n+ if not idx: return x\n+ ndim = len(x.shape)\n+ starts = [*idx] + [lax.full_like(idx[0], 0, shape=())] * (ndim - len(idx))\n+ sizes = (1,) * len(idx) + x.shape[len(idx):]\n+ out = lax.dynamic_slice(x, starts, sizes)\n+ return out.reshape(x.shape[len(idx):])\n+\n+def _dynamic_update_index(x, idx, val):\n+ if not idx: return val\n+ ndim = len(x.shape)\n+ starts = [*idx] + [lax.full_like(idx[0], 0, shape=())] * (ndim - len(idx))\n+ update = val.reshape((1,) * len(idx) + x.shape[len(idx):])\n+ return lax.dynamic_update_slice(x, update, starts)\n+\n+def _eval_jaxpr_discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any],\n+ *args: Any):\n+ env: Dict[core.Var, Any] = {}\n+\n+ def read(v: core.Atom) -> Any:\n+ if type(v) is core.Literal:\n+ return v.val\n+ assert isinstance(v, core.Var)\n+ return env[v]\n+\n+ def write(v: core.Var, val: Any) -> None:\n+ env[v] = val\n+\n+ map(write, jaxpr.constvars, consts)\n+ # Here some args may correspond to `Ref` avals but they'll be treated like\n+ # regular values in this interpreter.\n+ map(write, jaxpr.invars, args)\n+\n+ for eqn in jaxpr.eqns:\n+ in_vals = map(read, eqn.invars)\n+ if eqn.primitive is get_p:\n+ # `y <- x[i]` becomes `y = ds x i`\n+ x, *idx = in_vals\n+ write(eqn.outvars[0], _dynamic_index(x, idx))\n+ elif eqn.primitive is swap_p:\n+ # `z, x[i] <- x[i], val` becomes:\n+ # z = ds x i\n+ # x = dus x i val\n+ x, val, *idx = in_vals\n+ write(eqn.outvars[0], _dynamic_index(x, idx))\n+ assert isinstance(eqn.invars[0], core.Var)\n+ write(eqn.invars[0], _dynamic_update_index(x, idx, val))\n+ elif eqn.primitive is addupdate_p:\n+ # `x[i] += val` becomes:\n+ # y = ds x ii\n+ # z = y + val\n+ # x = dus x i z\n+ x, val, *idx = in_vals\n+ ans = _dynamic_update_index(x, idx, val + _dynamic_index(x, idx))\n+ assert isinstance(eqn.invars[0], core.Var)\n+ write(eqn.invars[0], ans)\n+ else:\n+ # Default primitive rule, similar to `core.eval_jaxpr`. Note that here\n+ # we assume any higher-order primitives inside of the jaxpr are *not*\n+ # stateful.\n+ # TODO(sharadmv): enable discharging state in higher order primitives\n+ subfuns, bind_params = eqn.primitive.get_bind_params(eqn.params)\n+ ans = eqn.primitive.bind(*subfuns, *map(read, eqn.invars), **bind_params)\n+ if eqn.primitive.multiple_results:\n+ map(write, eqn.outvars, ans)\n+ else:\n+ write(eqn.outvars[0], ans)\n+ # By convention, we return the outputs of the jaxpr first and then the final\n+ # values of the `Ref`s. Callers to this function should be able to split\n+ # them up by looking at `len(jaxpr.outvars)`.\n+ out_vals = map(read, jaxpr.outvars)\n+ ref_vals = map(\n+ read, [v for v in jaxpr.invars if type(v.aval) is ShapedArrayRef])\n+ return out_vals + ref_vals\n" } ]
Python
Apache License 2.0
google/jax
Add `discharge_state` to convert stateful jaxprs into pure jaxprs Co-authored-by: Matthew Johnson <mattjj@google.com>
260,510
16.06.2022 13:02:20
25,200
f84230e6e4dc07f2e5d7259e70c1bb4a191f1ffb
Add tests for discharging state
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -2549,6 +2549,38 @@ class ForLoopTest(jtu.JaxTestCase):\nself.assertListEqual(out_avals, [core.ShapedArray((), jnp.int32)])\nself.assertEqual(jaxpr.eqns[0].primitive, for_loop.addupdate_p)\n+ def test_get_custom_pretty_printing_rule(self):\n+ def body(x_ref):\n+ x = x_ref[()]\n+ return [x]\n+ jaxpr, _ , _ = pe.trace_to_jaxpr_dynamic(\n+ lu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n+ self.assertIn(\"b:i32[] <- a[]\", jaxpr.pretty_print(use_color=False))\n+\n+ def test_set_custom_pretty_printing_rule(self):\n+ def body(x_ref):\n+ x_ref[()] = 2\n+ return []\n+ jaxpr, _ , _ = pe.trace_to_jaxpr_dynamic(\n+ lu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n+ self.assertIn(\"a[] <- 2\", jaxpr.pretty_print(use_color=False))\n+\n+ def test_swap_custom_pretty_printing_rule(self):\n+ def body(x_ref):\n+ x = for_loop.ref_swap(x_ref, (), 2)\n+ return [x]\n+ jaxpr, _ , _ = pe.trace_to_jaxpr_dynamic(\n+ lu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n+ self.assertIn(\"b:i32[], a[] <- a[], 2\", jaxpr.pretty_print(use_color=False))\n+\n+ def test_addupdate_custom_pretty_printing_rule(self):\n+ def body(x_ref):\n+ for_loop.ref_addupdate(x_ref, (), 2)\n+ return []\n+ jaxpr, _ , _ = pe.trace_to_jaxpr_dynamic(\n+ lu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n+ self.assertIn(\"a[] += 2\", jaxpr.pretty_print(use_color=False))\n+\ndef test_get_jvp(self):\ndef f(r):\n@@ -2602,5 +2634,128 @@ class ForLoopTest(jtu.JaxTestCase):\nself.assertEqual(jaxpr.eqns[2].primitive, for_loop.get_p)\nself.assertEqual(jaxpr.eqns[3].primitive, for_loop.get_p)\n+ def test_discharge_get(self):\n+ def f(a_ref):\n+ a = for_loop.ref_get(a_ref, ())\n+ return [a + 1]\n+ in_avals = [for_loop.ShapedArrayRef((), jnp.dtype('float32'))]\n+ stateful_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(lu.wrap_init(f),\n+ in_avals)\n+ # Discharging should just turn this into a jaxpr that just adds 1.\n+ discharged_jaxpr, _ = for_loop.discharge_state(stateful_jaxpr, consts)\n+ self.assertLen(discharged_jaxpr.invars, 1)\n+ self.assertLen(discharged_jaxpr.outvars, 2)\n+ self.assertEqual(discharged_jaxpr.eqns[0].primitive, lax.add_p)\n+ # Should be able to evaluate this jaxpr\n+ self.assertListEqual(core.eval_jaxpr(discharged_jaxpr, (), 1.), [2., 1.])\n+\n+ def test_discharge_get_with_slice(self):\n+ def f(a_ref):\n+ a = for_loop.ref_get(a_ref, (0, 1))\n+ return [a + 1]\n+ in_avals = [for_loop.ShapedArrayRef((4, 3, 2), jnp.dtype('float32'))]\n+ stateful_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(lu.wrap_init(f),\n+ in_avals)\n+ # Discharging should just turn this into a jaxpr that just adds 1.\n+ discharged_jaxpr, _ = for_loop.discharge_state(stateful_jaxpr, consts)\n+ self.assertLen(discharged_jaxpr.invars, 1)\n+ self.assertLen(discharged_jaxpr.outvars, 2)\n+ self.assertIn(lax.dynamic_slice_p,\n+ set(eqn.primitive for eqn in discharged_jaxpr.eqns))\n+ # Should be able to evaluate this jaxpr\n+ inval = jnp.arange(24.).reshape((4, 3, 2))\n+ outval, refval = core.eval_jaxpr(discharged_jaxpr, (), inval)\n+ self.assertTrue((outval == inval[0, 1] + 1).all())\n+ self.assertTrue((refval == inval).all())\n+\n+ def test_discharge_set(self):\n+ def f(a_ref, b):\n+ for_loop.ref_set(a_ref, (), b + 1)\n+ return []\n+ in_avals = [for_loop.ShapedArrayRef((), jnp.dtype('float32')),\n+ core.ShapedArray((), jnp.dtype('float32'))]\n+ stateful_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(lu.wrap_init(f),\n+ in_avals)\n+ # Discharging should just turn this into a jaxpr that ignores the first\n+ # value and returns second value plus 1.\n+ discharged_jaxpr, _ = for_loop.discharge_state(stateful_jaxpr, consts)\n+ self.assertLen(discharged_jaxpr.invars, 2)\n+ self.assertLen(discharged_jaxpr.outvars, 1)\n+ self.assertEqual(core.eval_jaxpr(discharged_jaxpr, (), 0., 1.)[0], 2.)\n+ self.assertEqual(core.eval_jaxpr(discharged_jaxpr, (), 2., 1.)[0], 2.)\n+\n+ def test_discharge_set_with_slice(self):\n+ def f(a_ref):\n+ for_loop.ref_set(a_ref, (0, 1), jnp.ones(2))\n+ return []\n+ in_avals = [for_loop.ShapedArrayRef((4, 3, 2), jnp.dtype('float32'))]\n+ stateful_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(lu.wrap_init(f),\n+ in_avals)\n+ # Discharging should just turn this into a jaxpr that just adds 1.\n+ discharged_jaxpr, _ = for_loop.discharge_state(stateful_jaxpr, consts)\n+ self.assertLen(discharged_jaxpr.invars, 1)\n+ self.assertLen(discharged_jaxpr.outvars, 1)\n+ self.assertIn(lax.dynamic_update_slice_p,\n+ set(eqn.primitive for eqn in discharged_jaxpr.eqns))\n+ self.assertIn(lax.dynamic_slice_p,\n+ set(eqn.primitive for eqn in discharged_jaxpr.eqns))\n+ # Should be able to evaluate this jaxpr\n+ inval = jnp.arange(24.).reshape((4, 3, 2))\n+ refval, = core.eval_jaxpr(discharged_jaxpr, (), inval)\n+ self.assertTrue((refval == inval.at[0, 1].set(1.)).all())\n+\n+ def test_discharge_addupdate(self):\n+ def f(a_ref, b):\n+ for_loop.ref_addupdate(a_ref, (), b + 1)\n+ return []\n+ in_avals = [for_loop.ShapedArrayRef((), jnp.dtype('float32')),\n+ core.ShapedArray((), jnp.dtype('float32'))]\n+ stateful_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(lu.wrap_init(f),\n+ in_avals)\n+ # Discharging should just turn this into a jaxpr that adds the first value,\n+ # second value, and 1.\n+ discharged_jaxpr, _ = for_loop.discharge_state(stateful_jaxpr, consts)\n+ self.assertLen(discharged_jaxpr.invars, 2)\n+ self.assertLen(discharged_jaxpr.outvars, 1)\n+ self.assertEqual(core.eval_jaxpr(discharged_jaxpr, (), 0., 1.)[0], 2.)\n+ self.assertEqual(core.eval_jaxpr(discharged_jaxpr, (), 2., 1.)[0], 4.)\n+\n+ def test_discharge_addupdate_with_slice(self):\n+ def f(a_ref):\n+ for_loop.ref_addupdate(a_ref, (0, 1), jnp.ones(2))\n+ return []\n+ in_avals = [for_loop.ShapedArrayRef((4, 3, 2), jnp.dtype('float32'))]\n+ stateful_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(lu.wrap_init(f),\n+ in_avals)\n+ discharged_jaxpr, _ = for_loop.discharge_state(stateful_jaxpr, consts)\n+ self.assertLen(discharged_jaxpr.invars, 1)\n+ self.assertLen(discharged_jaxpr.outvars, 1)\n+ self.assertIn(lax.dynamic_update_slice_p,\n+ set(eqn.primitive for eqn in discharged_jaxpr.eqns))\n+ self.assertIn(lax.add_p,\n+ set(eqn.primitive for eqn in discharged_jaxpr.eqns))\n+ self.assertIn(lax.dynamic_slice_p,\n+ set(eqn.primitive for eqn in discharged_jaxpr.eqns))\n+ inval = jnp.arange(24.).reshape((4, 3, 2))\n+ refval, = core.eval_jaxpr(discharged_jaxpr, (), inval)\n+ self.assertTrue((refval == inval.at[0, 1].add(1.)).all())\n+\n+ def test_discharge_jaxpr_with_multiple_outputs(self):\n+ def f(a_ref):\n+ a = for_loop.ref_get(a_ref, ())\n+ b = a + 1\n+ return [a, b]\n+ in_avals = [for_loop.ShapedArrayRef((4,), jnp.dtype('float32'))]\n+ stateful_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(lu.wrap_init(f),\n+ in_avals)\n+ discharged_jaxpr, _ = for_loop.discharge_state(stateful_jaxpr, consts)\n+ self.assertLen(discharged_jaxpr.invars, 1)\n+ self.assertLen(discharged_jaxpr.outvars, 3)\n+ inval = jnp.arange(4.)\n+ a, b, refval = core.eval_jaxpr(discharged_jaxpr, (), inval)\n+ self.assertTrue((a == inval).all())\n+ self.assertTrue((b == inval + 1).all())\n+ self.assertTrue((refval == inval).all())\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add tests for discharging state
260,510
16.06.2022 13:03:35
25,200
f0595323955ddfad01e59e2a534034b8ea1ae50b
fixup! Add `discharge_state` to convert stateful jaxprs into pure jaxprs
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "@@ -359,7 +359,6 @@ def _eval_jaxpr_discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any],\n# Default primitive rule, similar to `core.eval_jaxpr`. Note that here\n# we assume any higher-order primitives inside of the jaxpr are *not*\n# stateful.\n- # TODO(sharadmv): enable discharging state in higher order primitives\nsubfuns, bind_params = eqn.primitive.get_bind_params(eqn.params)\nans = eqn.primitive.bind(*subfuns, *map(read, eqn.invars), **bind_params)\nif eqn.primitive.multiple_results:\n" } ]
Python
Apache License 2.0
google/jax
fixup! Add `discharge_state` to convert stateful jaxprs into pure jaxprs
260,335
17.06.2022 11:11:00
25,200
72a67906bf0b0553d18c9b05d9937de249c759bc
optimize grad-of-jit not to pass input-residuals as intermediate-residuals
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -204,7 +204,7 @@ class JaxprTrace(Trace):\n# which were unknown to the first call (corresponding to in_avals).\n# Wrap f to perform the partial evaluation and plumb out aux data.\n- f_ = trace_to_subjaxpr_nounits(f, self.main, False)\n+ f_ = trace_to_subjaxpr_nounits_fwd(f, self.main, False)\nf_, aux = partial_eval_wrapper_nounits(f_, tuple(in_knowns), tuple(in_avals))\n# Adjust parameters (e.g. donated_invars) for the call to be evaluated now.\nconst_params = update_params(params, in_knowns, 0)\n@@ -212,16 +212,22 @@ class JaxprTrace(Trace):\n# Run the call, getting known out vals and aux data used for staged-out call\nout = primitive.bind(_update_annotation(f_, f.in_type, in_knowns),\n*in_consts, **const_params)\n- out_knowns, out_avals, jaxpr, env = aux()\n- # Split apart known outputs from the original call and residuals.\n- out_consts, res = split_list(out, [len(out) - len(jaxpr.constvars)])\n+ fwds, out_knowns, out_avals, jaxpr, env = aux()\n+ # Split apart known outputs from the original call and non-fwded residuals.\n+ out_consts, non_fwd_res_ = split_list(out, [sum(out_knowns)])\n+\n+ # Form the complete list of residuals by forwarding some inputs.\n+ non_fwd_res = iter(non_fwd_res_)\n+ res = [next(non_fwd_res) if idx is None else in_consts[idx] for idx in fwds]\n+ sentinel = object()\n+ assert next(non_fwd_res, sentinel) is sentinel\n# Create the input tracers for the staged-out (unknown-value) call.\n- const_tracers = map(self.new_instantiated_const, res)\n+ res_tracers = map(self.new_instantiated_const, res)\nenv_tracers = map(self.full_raise, env)\nunknown_arg_tracers = [t for t in tracers if not t.is_known()]\n# Adjust parameters (e.g. donated_invars) for the staged-out call's args.\n- num_new_args = len(const_tracers) + len(env_tracers)\n+ num_new_args = len(res_tracers) + len(env_tracers)\nstaged_params = dict(params, call_jaxpr=convert_constvars_jaxpr(jaxpr))\nstaged_params = update_params(staged_params, map(op.not_, in_knowns),\nnum_new_args)\n@@ -230,7 +236,7 @@ class JaxprTrace(Trace):\nfor a in out_avals]\nname_stack = self._current_truncated_name_stack()\nsource = source_info_util.current().replace(name_stack=name_stack)\n- eqn = new_eqn_recipe((*const_tracers, *env_tracers, *unknown_arg_tracers),\n+ eqn = new_eqn_recipe((*res_tracers, *env_tracers, *unknown_arg_tracers),\nout_tracers, primitive, staged_params, jaxpr.effects,\nsource)\nfor t in out_tracers: t.recipe = eqn\n@@ -505,9 +511,9 @@ def partial_eval_wrapper_nounits(\nPartialVal.unknown(next(in_avals_)) for known in in_knowns]\nsentinel = object()\nassert next(in_avals_, sentinel) is next(in_consts_, sentinel) is sentinel\n- jaxpr, (out_pvals, res, env) = yield (in_pvals,), {}\n+ jaxpr, (*maybe_fwds, out_pvals, res, env) = yield (in_pvals,), {}\nout_knowns, out_avals, out_consts = partition_pvals(out_pvals)\n- yield (*out_consts, *res), (out_knowns, out_avals, jaxpr, env)\n+ yield (*out_consts, *res), (*maybe_fwds, out_knowns, out_avals, jaxpr, env)\ncustom_partial_eval_rules: Dict[Primitive, Callable] = {}\ncall_partial_eval_rules: Dict[Primitive, Callable] = {}\n@@ -621,9 +627,17 @@ def trace_to_jaxpr_nounits(\n@lu.transformation\ndef trace_to_subjaxpr_nounits(\n- main: core.MainTrace, instantiate: Union[bool, Sequence[bool]],\n+ main: core.MainTrace,\n+ instantiate: Union[bool, Sequence[bool]],\nin_pvals: Sequence[PartialVal]):\nassert all([isinstance(pv, PartialVal) for pv in in_pvals]), in_pvals\n+ out_tracers, jaxpr, out_consts, env = yield from _trace_to_subjaxpr_nounits(\n+ main, instantiate, in_pvals)\n+ out_pvals = [t.pval for t in out_tracers]\n+ del out_tracers\n+ yield jaxpr, (out_pvals, out_consts, env)\n+\n+def _trace_to_subjaxpr_nounits(main, instantiate, in_pvals):\ntrace = main.with_cur_sublevel()\nin_knowns = [pval.is_known() for pval in in_pvals]\nin_consts = [pval.get_known() for pval in in_pvals if pval.is_known()]\n@@ -638,11 +652,31 @@ def trace_to_subjaxpr_nounits(\ninstantiate = [instantiate] * len(ans)\nout_tracers = map(trace.full_raise, map(core.full_lower, ans))\nout_tracers = map(partial(instantiate_const_at, trace), instantiate, out_tracers)\n- out_pvals = [t.pval for t in out_tracers]\nout_tracers_ = [t for t in out_tracers if not t.is_known()]\n- jaxpr, consts, env = tracers_to_jaxpr(in_tracers, out_tracers_)\n- del trace, in_tracers, out_tracers, out_tracers_\n- yield jaxpr, (out_pvals, consts, env)\n+ jaxpr, out_consts, env = tracers_to_jaxpr(in_tracers, out_tracers_)\n+ return out_tracers, jaxpr, out_consts, env\n+\n+# The below variant implements an optimization where residuals which are also\n+# inputs are indicated in auxiliary data rather than passed as outputs.\n+# TODO(mattjj): update all callers to use this version, delete other version.\n+@lu.transformation\n+def trace_to_subjaxpr_nounits_fwd(\n+ main: core.MainTrace,\n+ instantiate: Union[bool, Sequence[bool]],\n+ in_pvals: Sequence[PartialVal]):\n+ assert all([isinstance(pv, PartialVal) for pv in in_pvals]), in_pvals\n+ out_tracers, jaxpr, out_consts, env = yield from _trace_to_subjaxpr_nounits(\n+ main, instantiate, in_pvals)\n+ out_pvals = [t.pval for t in out_tracers]\n+\n+ # Which out_consts (aka residuals) are just forwarded inputs? Check obj id.\n+ in_consts = [pval.get_known() for pval in in_pvals if pval.is_known()]\n+ id_map = {id(c): i for i, c in enumerate(in_consts)}\n+ fwds: List[Optional[int]] = [id_map.get(id(c)) for c in out_consts]\n+ pruned_consts = [c for c, fwd in zip(out_consts, fwds) if fwd is None]\n+\n+ del out_tracers\n+ yield jaxpr, (fwds, out_pvals, pruned_consts, env)\ndef instantiate_const_at(trace: JaxprTrace, instantiate: bool, tracer):\nif instantiate:\n" }, { "change_type": "MODIFY", "old_path": "tests/core_test.py", "new_path": "tests/core_test.py", "diff": "@@ -373,6 +373,23 @@ class CoreTest(jtu.JaxTestCase):\ndropvar, b = jaxpr.eqns[0].outvars\nself.assertEqual(dropvar.aval, aval)\n+ def test_input_residual_forwarding(self):\n+ # https://github.com/google/jax/pull/11151\n+ x = jnp.arange(3 * 4.).reshape(3, 4)\n+ y = jnp.arange(4 * 3.).reshape(4, 3)\n+\n+ g = jax.jit(jnp.dot)\n+\n+ def f(y):\n+ z, g_lin = jax.linearize(lambda y: g(x, y), y)\n+ zdot = g_lin(y)\n+ return z, zdot\n+\n+ jaxpr = jax.make_jaxpr(f)(y)\n+ e1, e2 = jaxpr.jaxpr.eqns\n+ self.assertLen(e1.outvars, 1) # only primal out, no residuals\n+ self.assertEqual(e1.outvars[0].aval.shape, (3, 3)) # only primal out shape\n+\nclass JaxprTypeChecks(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
optimize grad-of-jit not to pass input-residuals as intermediate-residuals Co-authored-by: Dougal Maclaurin <dougalm@google.com> Co-authored-by: Peter Hawkins <phawkins@google.com>
260,565
17.06.2022 16:39:21
25,200
f2a85f36f5e47d25edab205cb43654c7dd69abee
Remove spurious single quote in profiler.py Before: ``` 127.0.0.1 - - [17/Jun/2022 16:08:18] "GET /perfetto_trace.json.gz' HTTP/1.1" 404 - ``` After: ``` 127.0.0.1 - - [17/Jun/2022 16:35:54] "GET /perfetto_trace.json.gz HTTP/1.1" 200 - ```
[ { "change_type": "MODIFY", "old_path": "jax/_src/profiler.py", "new_path": "jax/_src/profiler.py", "diff": "@@ -163,7 +163,7 @@ def _host_perfetto_trace_file(log_dir):\nos.chdir(directory)\nsocketserver.TCPServer.allow_reuse_address = True\nwith socketserver.TCPServer(('127.0.0.1', port), _PerfettoServer) as httpd:\n- url = f\"https://ui.perfetto.dev/#!/?url=http://127.0.0.1:{port}/{filename}'\"\n+ url = f\"https://ui.perfetto.dev/#!/?url=http://127.0.0.1:{port}/{filename}\"\nprint(f\"Open URL in browser: {url}\")\n# Once ui.perfetto.dev acquires trace.json from this server we can close\n" } ]
Python
Apache License 2.0
google/jax
Remove spurious single quote in profiler.py Before: ``` 127.0.0.1 - - [17/Jun/2022 16:08:18] "GET /perfetto_trace.json.gz' HTTP/1.1" 404 - ``` After: ``` 127.0.0.1 - - [17/Jun/2022 16:35:54] "GET /perfetto_trace.json.gz HTTP/1.1" 200 - ```