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
12.10.2020 14:30:32
25,200
dbebc9ad04556824d75c6bc64b4f6d156e3bfc55
remove double warning with asarray dtype='int'
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -2500,6 +2500,7 @@ def _can_call_numpy_array(x):\n@_wraps(np.asarray)\ndef asarray(a, dtype=None, order=None):\nlax._check_user_dtype_supported(dtype, \"asarray\")\n+ dtype = dtypes.canonicalize_dtype(dtype) if dtype is not None else dtype\nreturn array(a, dtype=dtype, copy=False, order=order)\n" } ]
Python
Apache License 2.0
google/jax
remove double warning with asarray dtype='int'
260,335
14.10.2020 14:30:09
25,200
b99e350aed0e2c59cdcc5a1fc69d8dd8a7932f9f
add iota_p support to jax2tf
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -24,7 +24,6 @@ from jax import config\nfrom jax import core\nfrom jax import custom_derivatives\nfrom jax import dtypes\n-from jax import lax\nfrom jax import lax_linalg\nfrom jax import linear_util as lu\nfrom jax import numpy as jnp\n@@ -36,8 +35,10 @@ from jax.interpreters import ad\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import pxla\nfrom jax.interpreters import xla\n+from jax.lax import lax\nfrom jax.lax import lax_control_flow\nfrom jax.lax import lax_fft\n+from jax.lax import lax_parallel\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n@@ -447,7 +448,7 @@ for unexpected in [\ntf_not_yet_impl = [\nlax.reduce_p, lax.rng_uniform_p,\n- lax.linear_solve_p,\n+ lax_control_flow.linear_solve_p,\nlax_linalg.lu_p,\nlax_linalg.triangular_solve_p,\n@@ -455,9 +456,10 @@ tf_not_yet_impl = [\nlax.random_gamma_grad_p,\n# Not high priority?\n- lax.after_all_p, lax.all_to_all_p, lax.create_token_p, lax.cummax_p, lax.cummin_p,\n- lax.infeed_p, lax.outfeed_p, lax.pmax_p, lax.pmin_p, lax.ppermute_p, lax.psum_p,\n- lax.axis_index_p,\n+ lax.after_all_p, lax_parallel.all_to_all_p, lax.create_token_p, lax.cummax_p,\n+ lax.cummin_p, lax.infeed_p, lax.outfeed_p, lax_parallel.pmax_p,\n+ lax_parallel.pmin_p, lax_parallel.ppermute_p, lax_parallel.psum_p,\n+ lax_parallel.axis_index_p,\npxla.xla_pmap_p,\n]\n@@ -526,6 +528,17 @@ tf_impl[lax.sub_p] = wrap_binary_op(tf.math.subtract)\ntf_impl[lax.mul_p] = wrap_binary_op(tf.math.multiply)\n+def _iota(*, dtype, shape, dimension):\n+ size = shape[dimension]\n+ # Some dtypes are unsupporetd, like uint32, so we just fall back to int32.\n+ # TODO(mattjj, necula): improve tf.range dtype handling\n+ vec = tf.range(tf.cast(size, tf.int32), dtype=tf.int32)\n+ vec_shape = [-1 if i == dimension else 1 for i in range(len(shape))]\n+ return tf.cast(tf.broadcast_to(tf.reshape(vec, vec_shape), shape), dtype)\n+\n+tf_impl[lax.iota_p] = _iota\n+\n+\ndef _div(lhs, rhs):\nif lhs.dtype.is_integer:\nquotient = tf.math.floordiv(lhs, rhs)\n@@ -1249,7 +1262,7 @@ def _cond(index: TfVal, *operands: TfValOrUnit,\nres_tf: Sequence[TfVal] = tf.switch_case(index, branches_tf)\nreturn _tfval_add_unit(res_tf, branches[0].out_avals)\n-tf_impl[lax.cond_p] = _cond\n+tf_impl[lax_control_flow.cond_p] = _cond\ndef _while(*args: TfValOrUnit, cond_nconsts: int, cond_jaxpr: core.ClosedJaxpr,\n@@ -1317,10 +1330,10 @@ def _batched_cond_while(*args: TfValOrUnit,\n_tfval_remove_unit((init_pred_b, *init_carry)))\nreturn _tfval_add_unit(res_carry, body_jaxpr.out_avals)\n-tf_impl[lax.while_p] = _while\n+tf_impl[lax_control_flow.while_p] = _while\n# We use the scan impl rule to rewrite in terms of while.\n-tf_impl[lax.scan_p] = _convert_jax_impl(lax_control_flow._scan_impl)\n+tf_impl[lax_control_flow.scan_p] = _convert_jax_impl(lax_control_flow._scan_impl)\ndef _top_k(operand: TfVal, k: int) -> Tuple[TfVal, TfVal]:\n# Some types originally incompatible with tf.math.top_k can be promoted\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/correctness_stats.py", "new_path": "jax/experimental/jax2tf/tests/correctness_stats.py", "diff": "@@ -91,7 +91,7 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\npass\nreturn np.dtype(dtype)\n- if args[0] is not core.unit:\n+ if args and args[0] is not core.unit:\nnp_dtype = _to_np_dtype(args[0].dtype)\nelse:\nnp_dtype = None\n" } ]
Python
Apache License 2.0
google/jax
add iota_p support to jax2tf
260,335
14.10.2020 14:40:29
25,200
a5f906a9f69acff76203db82a6262fac7d5708c6
jax2tf import fix
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -465,7 +465,7 @@ tf_not_yet_impl = [\n]\ntry:\n- tf_impl[lax.lax.tie_in_p] = lambda x, y: y\n+ tf_impl[lax.tie_in_p] = lambda x, y: y\nexcept AttributeError:\npass\ntf_impl[ad_util.stop_gradient_p] = tf.stop_gradient\n@@ -920,8 +920,8 @@ def _select_and_gather_add(tangents: TfVal,\nconst = lambda dtype, x: tf.constant(np.array(x), dtype)\nif double_word_reduction:\n- word_dtype = lax.lax._UINT_DTYPES[nbits]\n- double_word_dtype = lax.lax._UINT_DTYPES[nbits * 2]\n+ word_dtype = lax._UINT_DTYPES[nbits]\n+ double_word_dtype = lax._UINT_DTYPES[nbits * 2]\n# Packs two values into a tuple.\ndef pack(a, b):\n" } ]
Python
Apache License 2.0
google/jax
jax2tf import fix
260,335
14.10.2020 18:51:42
25,200
f553ed24e16f0877bbaecc2d8b920ec8ae160d9c
Temporary rollback of pending a possible XLA bug it exposed in an internal test.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -25,6 +25,7 @@ from jax import config\nfrom jax import core\nfrom jax import custom_derivatives\nfrom jax import dtypes\n+from jax import lax\nfrom jax import lax_linalg\nfrom jax import linear_util as lu\nfrom jax import numpy as jnp\n@@ -37,10 +38,8 @@ from jax.interpreters import masking\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import pxla\nfrom jax.interpreters import xla\n-from jax.lax import lax\nfrom jax.lax import lax_control_flow\nfrom jax.lax import lax_fft\n-from jax.lax import lax_parallel\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n@@ -610,7 +609,7 @@ for unexpected in [\ntf_not_yet_impl = [\nlax.reduce_p, lax.rng_uniform_p,\n- lax_control_flow.linear_solve_p,\n+ lax.linear_solve_p,\nlax_linalg.lu_p,\nlax_linalg.triangular_solve_p,\n@@ -618,16 +617,15 @@ tf_not_yet_impl = [\nlax.random_gamma_grad_p,\n# Not high priority?\n- lax.after_all_p, lax_parallel.all_to_all_p, lax.create_token_p, lax.cummax_p,\n- lax.cummin_p, lax.infeed_p, lax.outfeed_p, lax_parallel.pmax_p,\n- lax_parallel.pmin_p, lax_parallel.ppermute_p, lax_parallel.psum_p,\n- lax_parallel.axis_index_p,\n+ lax.after_all_p, lax.all_to_all_p, lax.create_token_p, lax.cummax_p, lax.cummin_p,\n+ lax.infeed_p, lax.outfeed_p, lax.pmax_p, lax.pmin_p, lax.ppermute_p, lax.psum_p,\n+ lax.axis_index_p,\npxla.xla_pmap_p,\n]\ntry:\n- tf_impl[lax.tie_in_p] = lambda x, y: y\n+ tf_impl[lax.lax.tie_in_p] = lambda x, y: y\nexcept AttributeError:\npass\ntf_impl[ad_util.stop_gradient_p] = tf.stop_gradient\n@@ -690,17 +688,6 @@ tf_impl[lax.sub_p] = wrap_binary_op(tf.math.subtract)\ntf_impl[lax.mul_p] = wrap_binary_op(tf.math.multiply)\n-def _iota(*, dtype, shape, dimension):\n- size = shape[dimension]\n- # Some dtypes are unsupporetd, like uint32, so we just fall back to int32.\n- # TODO(mattjj, necula): improve tf.range dtype handling\n- vec = tf.range(tf.cast(size, tf.int32), dtype=tf.int32)\n- vec_shape = [-1 if i == dimension else 1 for i in range(len(shape))]\n- return tf.cast(tf.broadcast_to(tf.reshape(vec, vec_shape), shape), dtype)\n-\n-tf_impl[lax.iota_p] = _iota\n-\n-\ndef _div(lhs, rhs):\nif lhs.dtype.is_integer:\nquotient = tf.math.floordiv(lhs, rhs)\n@@ -1240,8 +1227,8 @@ def _select_and_gather_add(tangents: TfVal,\nconst = lambda dtype, x: tf.constant(np.array(x), dtype)\nif double_word_reduction:\n- word_dtype = lax._UINT_DTYPES[nbits]\n- double_word_dtype = lax._UINT_DTYPES[nbits * 2]\n+ word_dtype = lax.lax._UINT_DTYPES[nbits]\n+ double_word_dtype = lax.lax._UINT_DTYPES[nbits * 2]\n# Packs two values into a tuple.\ndef pack(a, b):\n@@ -1549,7 +1536,7 @@ def _cond(index: TfVal, *operands: TfVal,\nfor jaxpr in branches]\nreturn tf.switch_case(index, branches_tf)\n-tf_impl[lax_control_flow.cond_p] = _cond\n+tf_impl[lax.cond_p] = _cond\ndef _while(*args: TfVal, cond_nconsts: int, cond_jaxpr: core.ClosedJaxpr,\n@@ -1616,10 +1603,10 @@ def _batched_cond_while(*args: TfVal,\n(init_pred_b, *init_carry))\nreturn res_carry\n-tf_impl[lax_control_flow.while_p] = _while\n+tf_impl[lax.while_p] = _while\n# We use the scan impl rule to rewrite in terms of while.\n-tf_impl_with_avals[lax_control_flow.scan_p] = _convert_jax_impl(lax_control_flow._scan_impl)\n+tf_impl_with_avals[lax.scan_p] = _convert_jax_impl(lax_control_flow._scan_impl)\ndef _top_k(operand: TfVal, k: int) -> Tuple[TfVal, TfVal]:\n# Some types originally incompatible with tf.math.top_k can be promoted\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/correctness_stats.py", "new_path": "jax/experimental/jax2tf/tests/correctness_stats.py", "diff": "@@ -91,7 +91,7 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\npass\nreturn np.dtype(dtype)\n- if args and args[0] is not core.unit:\n+ if args[0] is not core.unit:\nnp_dtype = _to_np_dtype(args[0].dtype)\nelse:\nnp_dtype = None\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1412,11 +1412,6 @@ def iota(dtype: DType, size: int) -> Array:\n<https://www.tensorflow.org/xla/operation_semantics#iota>`_\noperator.\n\"\"\"\n- if config.omnistaging_enabled:\n- dtype = dtypes.canonicalize_dtype(dtype)\n- size = core.concrete_or_error(int, size, \"size argument of lax.iota\")\n- return iota_p.bind(dtype=dtype, shape=(size,), dimension=0)\n- else:\nsize = size if type(size) is masking.Poly else int(size)\nshape = canonicalize_shape((size,))\ndtype = dtypes.canonicalize_dtype(dtype)\n@@ -1428,54 +1423,41 @@ def broadcasted_iota(dtype: DType, shape: Shape, dimension: int) -> Array:\n\"\"\"Convenience wrapper around ``iota``.\"\"\"\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = canonicalize_shape(shape)\n- dimension = core.concrete_or_error(\n- int, dimension, \"dimension argument of lax.broadcasted_iota\")\n- return iota_p.bind(dtype=dtype, shape=shape, dimension=dimension)\n+ dimension = int(dimension)\n+ return broadcast_in_dim(iota(dtype, shape[dimension]), shape, [dimension])\ndef _eye(dtype: DType, shape: Shape, offset: int) -> Array:\n- \"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\"\"\"\n+ \"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\n+\n+ This function exists for creating lazy identity matrices; that is,\n+ materialization of the array is delayed and it may be fused into consumers to\n+ avoid materialization at all.\"\"\"\nN, M = tuple(map(int, shape))\noffset = int(offset)\ndtype = dtypes.canonicalize_dtype(dtype)\n- if config.omnistaging_enabled:\n- bool_eye = eq(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n- broadcasted_iota(np.int32, (N, M), 1))\n- return convert_element_type_p.bind(bool_eye, new_dtype=dtype,\n- old_dtype=np.bool_)\n- else:\nlazy_expr = lazy.eye(dtype, (N, M), offset)\naval = ShapedArray((N, M), dtype)\nreturn xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\ndef _delta(dtype: DType, shape: Shape, axes: Sequence[int]) -> Array:\n- \"\"\"This utility function exists for creating Kronecker delta arrays.\"\"\"\n+ \"\"\"This function exists for creating lazy Kronecker delta arrays, particularly\n+ for use in jax.numpy.einsum to express traces. It differs from ``eye`` in that\n+ it can create arrays of any rank, but doesn't allow offsets.\"\"\"\nshape = tuple(map(int, shape))\naxes = tuple(map(int, axes))\ndtype = dtypes.canonicalize_dtype(dtype)\nbase_shape = tuple(np.take(shape, axes))\n- if config.omnistaging_enabled:\n- iotas = [broadcasted_iota(np.uint32, base_shape, i)\n- for i in range(len(base_shape))]\n- eyes = [eq(i1, i2) for i1, i2 in zip(iotas[:-1], iotas[1:])]\n- result = convert_element_type_p.bind(_reduce(operator.and_, eyes),\n- new_dtype=dtype, old_dtype=np.bool_)\n- return broadcast_in_dim(result, shape, axes)\n- else:\nlazy_expr = lazy.broadcast(lazy.delta(dtype, base_shape), shape, axes)\naval = ShapedArray(shape, dtype)\nreturn xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\ndef _tri(dtype: DType, shape: Shape, offset: int) -> Array:\n- \"\"\"Like numpy.tri, create a 2D array with ones below a diagonal.\"\"\"\n+ \"\"\"Like numpy.tri, create a 2D array with ones below a diagonal.\n+ This function exists for creating lazy triangular matrices, particularly for\n+ use in jax.numpy.tri.\"\"\"\nN, M = tuple(map(int, shape))\noffset = int(offset)\ndtype = dtypes.canonicalize_dtype(dtype)\n- if config.omnistaging_enabled:\n- bool_tri = ge(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n- broadcasted_iota(np.int32, (N, M), 1))\n- return convert_element_type_p.bind(bool_tri, old_dtype=np.int32,\n- new_dtype=dtype)\n- else:\nlazy_expr = lazy.tri(dtype, (N, M), offset)\naval = ShapedArray((N, M), dtype)\nreturn xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\n@@ -5808,7 +5790,6 @@ outfeed_p.def_impl(partial(xla.apply_primitive, outfeed_p))\noutfeed_p.def_abstract_eval(_outfeed_abstract_eval)\nxla.translations[outfeed_p] = _outfeed_translation_rule\n-\ndef rng_uniform(a, b, shape):\n\"\"\"Stateful PRNG generator. Experimental and its use is discouraged.\n@@ -5841,30 +5822,6 @@ rng_uniform_p.def_impl(partial(xla.apply_primitive, rng_uniform_p))\nrng_uniform_p.def_abstract_eval(_rng_uniform_abstract_eval)\nxla.translations[rng_uniform_p] = _rng_uniform_translation_rule\n-\n-def _iota_abstract_eval(*, dtype, shape, dimension):\n- _check_shapelike(\"iota\", \"shape\", shape)\n- if not any(dtypes.issubdtype(dtype, t) for t in _num):\n- msg = 'iota does not accept dtype {}. Accepted dtypes are subtypes of {}.'\n- typename = str(np.dtype(dtype).name)\n- accepted_typenames = (t.__name__ for t in _num)\n- raise TypeError(msg.format(typename, ', '.join(accepted_typenames)))\n- if not 0 <= dimension < len(shape):\n- raise ValueError(\"iota dimension must be between 0 and len(shape), got \"\n- f\"dimension={dimension} for shape {shape}\")\n- return ShapedArray(shape, dtype)\n-\n-def _iota_translation_rule(c, dtype, shape, dimension):\n- etype = xla_client.dtype_to_etype(dtype)\n- xla_shape = xc.Shape.array_shape(etype, shape)\n- return xops.Iota(c, xla_shape, dimension)\n-\n-iota_p = Primitive('iota')\n-iota_p.def_impl(partial(xla.apply_primitive, iota_p))\n-iota_p.def_abstract_eval(_iota_abstract_eval)\n-xla.translations[iota_p] = _iota_translation_rule\n-\n-\n### util\n_ndim = np.ndim\n" }, { "change_type": "MODIFY", "old_path": "jax/random.py", "new_path": "jax/random.py", "diff": "@@ -304,7 +304,6 @@ def _fold_in(key, data):\nreturn threefry_2x32(key, PRNGKey(data))\n-@partial(jit, static_argnums=(1, 2))\ndef _random_bits(key, bit_width, shape):\n\"\"\"Sample uniform random bits of given width and shape using PRNG key.\"\"\"\nif not _is_prng_key(key):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -33,7 +33,7 @@ import concurrent.futures\nimport jax\nimport jax.numpy as jnp\nfrom jax import float0, jit, grad, device_put, jacfwd, jacrev, hessian\n-from jax import api, core, lax, lax_reference, lazy\n+from jax import api, core, lax, lax_reference\nfrom jax.core import Primitive\nfrom jax.interpreters import ad\nfrom jax.interpreters import xla\n@@ -1477,7 +1477,7 @@ class APITest(jtu.JaxTestCase):\ndef test_dtype_warning(self):\n# cf. issue #1230\nif FLAGS.jax_enable_x64:\n- raise unittest.SkipTest(\"test only applies when x64 is disabled\")\n+ return # test only applies when x64 is disabled\ndef check_warning(warn, nowarn):\nwith warnings.catch_warnings(record=True) as w:\n@@ -2470,14 +2470,14 @@ class LazyTest(jtu.JaxTestCase):\nassert python_should_be_executing\nreturn jnp.sum(x)\n- x = jnp.zeros(10, dtype=jnp.int32)\n- assert not lazy.is_trivial(x._lazy_expr)\n+ x = jnp.arange(10, dtype=jnp.int32)\n+ assert xla.is_device_constant(x) # lazy iota\npython_should_be_executing = True\n_ = f(x)\npython_should_be_executing = False # should not recompile\n- x = np.zeros(10, dtype=np.int32)\n+ x = np.arange(10, dtype=np.int32)\n_ = f(x)\n@parameterized.parameters(jtu.cases_from_list(range(10000)))\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -3651,7 +3651,6 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ntype(lax.iota(np.int32, 77)))\n# test laziness for int dtypes\n- if not config.omnistaging_enabled:\nself.assertTrue(xla.is_device_constant(jnp.arange(77)))\nself.assertTrue(xla.is_device_constant(jnp.arange(77, dtype=jnp.int32)))\n" } ]
Python
Apache License 2.0
google/jax
Temporary rollback of #4535 pending a possible XLA bug it exposed in an internal test. PiperOrigin-RevId: 337219426
260,268
15.10.2020 11:06:18
14,400
f7d4063e555bf1c4f653fc104529b48e75267332
Remove expit, add logsumexp to docs
[ { "change_type": "MODIFY", "old_path": "docs/jax.nn.rst", "new_path": "docs/jax.nn.rst", "diff": "@@ -47,3 +47,4 @@ Other functions\nlog_softmax\nnormalize\none_hot\n+ logsumexp\n" }, { "change_type": "MODIFY", "old_path": "jax/nn/__init__.py", "new_path": "jax/nn/__init__.py", "diff": "@@ -19,7 +19,6 @@ from . import initializers\nfrom .functions import (\ncelu,\nelu,\n- expit,\ngelu,\nglu,\nhard_sigmoid,\n" } ]
Python
Apache License 2.0
google/jax
Remove expit, add logsumexp to docs
260,335
15.10.2020 10:53:16
25,200
3a75145fd2a269531e8f13cca97f6020803f0653
allow custom_vjp bwd to return Nones for zeros This change sets up some internal users so that we can then land
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -23,7 +23,7 @@ from .tree_util import tree_flatten, tree_unflatten, tree_map, tree_multimap\nfrom .util import safe_zip, safe_map, split_list\nfrom .api_util import flatten_fun_nokwargs, argnums_partial, wrap_hashably\nfrom .abstract_arrays import raise_to_shaped\n-from .ad_util import Zero, stop_gradient_p\n+from .ad_util import Zero, zeros_like_aval, stop_gradient_p\nfrom .interpreters import partial_eval as pe\nfrom .interpreters import ad\nfrom .interpreters import batching\n@@ -463,9 +463,10 @@ class custom_vjp:\nf_, dyn_args = lu.wrap_init(self.fun), args\nfwd, bwd = lu.wrap_init(self.fwd), lu.wrap_init(self.bwd)\nargs_flat, in_tree = tree_flatten(dyn_args)\n+ in_avals = [core.raise_to_shaped(core.get_aval(x)) for x in args_flat]\nflat_fun, out_tree = flatten_fun_nokwargs(f_, in_tree)\nflat_fwd, out_trees = _flatten_fwd(fwd, in_tree)\n- flat_bwd = _flatten_bwd(bwd, in_tree, out_trees)\n+ flat_bwd = _flatten_bwd(bwd, in_tree, in_avals, out_trees)\nif _initial_style_staging():\nout_flat = custom_vjp_call_jaxpr(flat_fun, flat_fwd, flat_bwd,\n*args_flat, out_trees=out_trees)\n@@ -493,21 +494,33 @@ def _flatten_fwd(in_tree, *args):\nyield res + out, (out_tree, res_tree)\n@lu.transformation\n-def _flatten_bwd(in_tree, out_trees, *args):\n+def _flatten_bwd(in_tree, in_avals, out_trees, *args):\nout_tree, res_tree = out_trees()\nres, cts_out = split_list(args, [res_tree.num_leaves])\npy_res = tree_unflatten(res_tree, res)\npy_cts_out = tree_unflatten(out_tree, cts_out)\npy_cts_in = yield (py_res, py_cts_out), {}\n- cts_in, in_tree2 = tree_flatten(py_cts_in)\n- if in_tree != in_tree2:\n+ # For each None in py_cts_in, indicating an argument for which the rule\n+ # produces no cotangent, we replace it with a pytree with the structure of the\n+ # corresponding subtree of in_tree and with leaves of a non-pytree sentinel\n+ # object, to be replaced with Nones in the final returned result.\n+ zero = object() # non-pytree sentinel to replace Nones in py_cts_in\n+ py_cts_in_ = tuple(zero if ct is None else ct for ct in py_cts_in)\n+ dummy = tree_unflatten(in_tree, [object()] * in_tree.num_leaves)\n+ cts_in_flat = []\n+ append_cts = lambda x, d: cts_in_flat.extend([x] * len(tree_flatten(d)[0]))\n+ try:\n+ tree_multimap(append_cts, py_cts_in_, dummy)\n+ except ValueError:\n+ _, in_tree2 = tree_flatten(py_cts_in)\nmsg = (\"Custom VJP rule must produce an output with the same container \"\n\"(pytree) structure as the args tuple of the primal function, \"\n\"and in particular must produce a tuple of length equal to the \"\n\"number of arguments to the primal function, but got VJP output \"\n\"structure {} for primal input structure {}.\")\nraise TypeError(msg.format(in_tree2, in_tree)) from None\n- yield cts_in\n+ yield [zeros_like_aval(aval.at_least_vspace()) if ct is zero else ct\n+ for aval, ct in zip(in_avals, cts_in_flat)]\nclass CustomVJPCallPrimitive(core.CallPrimitive):\n" } ]
Python
Apache License 2.0
google/jax
allow custom_vjp bwd to return Nones for zeros This change sets up some internal users so that we can then land #4008.
260,335
15.10.2020 16:18:43
25,200
867828764454ce27c3d6511af6a21ed365b6f2be
remove an extraneous replace_float0s This caused a test failure when trying to land
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -323,9 +323,6 @@ class JVPTrace(Trace):\ndef process_custom_vjp_call(self, _, __, fwd, bwd, tracers, *, out_trees):\nprimals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers)\ntangents_in = map(instantiate_zeros, tangents_in)\n- # Cast float0 to zeros with the primal dtype because custom vjp rules don't\n- # currently handle float0s\n- tangents_in = replace_float0s(primals_in, tangents_in)\nres_and_primals_out = fwd.call_wrapped(*map(core.full_lower, primals_in))\nout_tree, res_tree = out_trees()\nres, primals_out = split_list(res_and_primals_out, [res_tree.num_leaves])\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3571,6 +3571,20 @@ class CustomVJPTest(jtu.JaxTestCase):\nself.assertEqual(api.grad(foo, allow_int=True, argnums=(0, 1))(x, y),\n(2., np.zeros(shape=(), dtype=float0)))\n+ def test_float0_bwd_none(self):\n+ @api.custom_vjp\n+ def f(i, x):\n+ return jnp.sin(x)\n+ def f_fwd(i, x):\n+ return f(i, x), jnp.cos(x)\n+ def f_rev(cos_x, g):\n+ return (None, 2 * cos_x * g)\n+ f.defvjp(f_fwd, f_rev)\n+\n+ ans = api.grad(f, 1)(jnp.array([1, 2]), 3.) # doesn't crash\n+ expected = 2 * jnp.cos(3.)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nclass InvertibleADTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
remove an extraneous replace_float0s This caused a test failure when trying to land #4008.
260,335
15.10.2020 21:58:27
25,200
f3b4f43c2036df1fe885127154eb75573d95bc2c
temporarily work around a bug that will fix
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -608,6 +608,7 @@ def _custom_vjp_call_jaxpr_vmap(args, in_dims, *, fun_jaxpr, fwd_jaxpr_thunk,\nfwd_jaxpr_thunk=batched_fwd_jaxpr_thunk, bwd=batched_bwd,\nout_trees=out_trees)\nout_dims = out_dims2[0] if out_dims2 else out_dims1\n+ out_dims = out_dims[:len(batched_outs)] # TODO(mattjj): remove after #4008\nreturn batched_outs, out_dims\nbatching.primitive_batchers[custom_vjp_call_jaxpr_p] = _custom_vjp_call_jaxpr_vmap\n" } ]
Python
Apache License 2.0
google/jax
temporarily work around a bug that #4008 will fix
260,411
16.10.2020 10:52:56
-10,800
5efdaa4d85a3075f6f1f466671bfb3963ef05508
[host_callback] Added support for remat.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -613,6 +613,7 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\nmk_new_var: Callable[[core.AbstractValue], core.Var]):\n\"\"\"Rewrite an `eqn` and append equations to `eqns`.\n+ This is only called if the current primitive uses outfeed.\nAssume that the current token is in `input_token_var` and the resulting\ntoken must end in `output_token_var`.\n\"\"\"\n@@ -698,11 +699,21 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\neqn.primitive,\ndict(\neqn.params,\n- call_jaxpr=_rewrite_jaxpr(call_jaxpr, True,\n- True),\n+ call_jaxpr=_rewrite_jaxpr(call_jaxpr, True, True),\ndonated_invars=eqn.params[\"donated_invars\"] + (False,)\n),\neqn.source_info))\n+ elif eqn.primitive is pe.remat_call_p:\n+ call_jaxpr = cast(core.Jaxpr, eqn.params[\"call_jaxpr\"])\n+ eqns.append(\n+ core.new_jaxpr_eqn(\n+ eqn.invars + [input_token_var], eqn.outvars + [output_token_var],\n+ eqn.primitive,\n+ dict(\n+ eqn.params,\n+ call_jaxpr=_rewrite_jaxpr(call_jaxpr, True, True),\n+ ),\n+ eqn.source_info))\nelif eqn.primitive is custom_derivatives.custom_jvp_call_jaxpr_p:\nfun_jaxpr = eqn.params[\"fun_jaxpr\"]\nnew_invars = [*eqn.invars, input_token_var]\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -1305,9 +1305,13 @@ def _remat_translation_rule(c, axis_env, in_nodes,\nxb.parameter(dummy_subc, 0, c.get_shape(false_op), replicated=[])\ndef zeros(xla_shape):\n+ if xla_shape.is_array():\nshape, dtype = xla_shape.dimensions(), xla_shape.numpy_dtype()\nzero = xb.constant(dummy_subc, np.array(0, dtype=dtype))\nreturn xops.Broadcast(zero, shape)\n+ else:\n+ # It is a token\n+ return xops.CreateToken(dummy_subc)\nout_nodes = [zeros(s) for s in out_node_shapes]\ndummy_subc = dummy_subc.build(xops.Tuple(dummy_subc, out_nodes))\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -149,7 +149,6 @@ class HostCallbackTest(jtu.JaxTestCase):\nx1, y1 = hcb.id_print((x * 2., x * 3.), output_stream=testing_stream)\nreturn x1 + y1\n- #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(func2)(3.)))\nself.assertEqual(3. * (2. + 3.), func2(3.))\nhcb.barrier_wait()\n@@ -220,8 +219,6 @@ class HostCallbackTest(jtu.JaxTestCase):\ndef func(): # jitted function does not take arguments\nreturn hcb.id_print(42, output_stream=testing_stream)\n- #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(api.jit(func))()))\n-\nself.assertAllClose(42, api.jit(func)())\nhcb.barrier_wait()\nassertMultiLineStrippedEqual(self, \"\"\"\n@@ -232,8 +229,6 @@ class HostCallbackTest(jtu.JaxTestCase):\ndef func(x1, x2):\nreturn hcb.id_print(x1 + x2, output_stream=testing_stream)\n- #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(api.jit(func))(40, 2)))\n-\nself.assertAllClose(42, api.jit(func)(40, 2))\nhcb.barrier_wait()\nassertMultiLineStrippedEqual(self, \"\"\"\n@@ -244,8 +239,6 @@ class HostCallbackTest(jtu.JaxTestCase):\ndef func(x):\nreturn hcb.id_print(42, result=x, output_stream=testing_stream)\n- #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(api.jit(func))(5)))\n-\nself.assertAllClose(5, api.jit(func)(5))\nhcb.barrier_wait()\nassertMultiLineStrippedEqual(self, \"\"\"\n@@ -727,7 +720,6 @@ class HostCallbackTest(jtu.JaxTestCase):\ndef test_jvp(self):\njvp_fun1 = lambda x, xt: api.jvp(fun1, (x,), (xt,))\n- #assertMultiLineStrippedEqual(self, \"\")\nres_primals, res_tangents = jvp_fun1(jnp.float32(5.), jnp.float32(0.1))\nself.assertAllClose(100., res_primals, check_dtypes=False)\nself.assertAllClose(4., res_tangents, check_dtypes=False)\n@@ -790,7 +782,6 @@ class HostCallbackTest(jtu.JaxTestCase):\nreturn x * hcb.id_print(y * 3., what=\"y * 3\",\noutput_stream=testing_stream)\ngrad_func = api.grad(func)\n- #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(grad_func)(5.)))\nres_grad = grad_func(jnp.float32(5.))\nself.assertAllClose(2. * 5. * 6., res_grad, check_dtypes=False)\n@@ -837,7 +828,6 @@ class HostCallbackTest(jtu.JaxTestCase):\ndef test_vmap(self):\nvmap_fun1 = api.vmap(fun1)\nvargs = jnp.array([jnp.float32(4.), jnp.float32(5.)])\n- #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(vmap_fun1)(vargs)))\nvmap_fun1(vargs)\nhcb.barrier_wait()\nassertMultiLineStrippedEqual(self, \"\"\"\n@@ -856,7 +846,6 @@ class HostCallbackTest(jtu.JaxTestCase):\nvmap_func = api.vmap(func)\nvargs = jnp.array([jnp.float32(4.), jnp.float32(5.)])\n- #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(vmap_func)(vargs)))\n_ = vmap_func(vargs)\nhcb.barrier_wait()\nassertMultiLineStrippedEqual(self, \"\"\"\n@@ -1177,6 +1166,20 @@ class HostCallbackTest(jtu.JaxTestCase):\napi.grad(loss)(1.0) # should not fail\n+ def test_remat(self):\n+ def f(i, k):\n+ x = hcb.id_print(k + i, output_stream=testing_stream)\n+ return k * x\n+\n+ def loss(k):\n+ return lax.fori_loop(0, 2, api.remat(f), k)\n+ print(loss(3))\n+ hcb.barrier_wait()\n+ expected = \"\"\"\n+ 3\n+ 10\"\"\"\n+ self.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+\nclass OutfeedRewriterTest(jtu.JaxTestCase):\n@@ -1184,9 +1187,12 @@ class OutfeedRewriterTest(jtu.JaxTestCase):\nhas_input_token=True, has_output_token=True):\n\"\"\"Check that the rewrite of func(*args) matches expected.\"\"\"\njaxpr = api.make_jaxpr(func)(*args)\n- # TODO: re-enable when we change the host_callback rewriter\n- #rewritten = hcb._rewrite_closed_jaxpr(jaxpr,\n- # has_input_token, has_output_token)\n+ rewritten = hcb._rewrite_closed_jaxpr(jaxpr,\n+ has_input_token, has_output_token)\n+ # Since it is somewhat annoying to update the Jaxpr assertions when we change\n+ # the Jaxpr printing, we do not check these by default. It is recommended that\n+ # before making changes to the code generation and Jaxpr rewriting, turn on\n+ # the checking, update the expected Jaxpr, and then make the changes.\n#assertMultiLineStrippedEqual(self, expected, str(rewritten))\ndel jaxpr\n@@ -1543,5 +1549,38 @@ class OutfeedRewriterTest(jtu.JaxTestCase):\nunroll=1 ] * 1.00 e * b\nin (c, f) }\"\"\", api.grad(g), [arg])\n+ def test_remat_loop(self):\n+ def f(k, x):\n+ x = hcb.id_print(k + x)\n+ return -k * x\n+\n+ def loss(k):\n+ return lax.fori_loop(0, 1, api.remat(f), k)\n+\n+ self.assertRewrite(\"\"\"\n+ { lambda ; a c.\n+ let _ _ b d =\n+ while[ body_jaxpr={ lambda ; a b c f.\n+ let d = add a 1\n+ e g = remat_call[ call_jaxpr={ lambda ; a b g.\n+ let c = add a b\n+ d h = id_tap[ arg_treedef_=*\n+ has_token_=True\n+ nr_tapped_args_=1\n+ tap_func_=_print ] c g\n+ e = neg a\n+ f = mul e d\n+ in (f, h) }\n+ concrete=False\n+ name=f ] a c f\n+ in (d, b, e, g) }\n+ body_nconsts=0\n+ cond_jaxpr={ lambda ; a b c e.\n+ let d = lt a b\n+ in (d,) }\n+ cond_nconsts=0 ] 0 1 a c\n+ in (b, d) }\"\"\", loss, [2])\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[host_callback] Added support for remat.
260,273
15.10.2020 13:53:03
0
807e7a4a457feca4d40cc2757ddadad1796ec2b9
Do not promote literal dims to Poly
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/masking.py", "new_path": "jax/interpreters/masking.py", "diff": "@@ -338,7 +338,7 @@ _identifiers = frozenset(string.ascii_lowercase)\ndef _parse_id(name): return Poly({Mon({name: 1}): 1})\n-def _parse_lit(val_str): return Poly({Mon(): int(val_str)})\n+def _parse_lit(val_str): return int(val_str)\nclass MonomorphicDim(object):\ndef __str__(self): return '_'\n@@ -458,8 +458,8 @@ class UniqueIds(dict):\ndef remap_ids(names, shape_spec):\nreturn ShapeSpec(Poly({Mon({names[id] : deg for id, deg in mon.items()})\n: coeff for mon, coeff in poly.items()})\n- if poly is not _monomorphic_dim else\n- _monomorphic_dim for poly in shape_spec)\n+ if isinstance(poly, Poly) else\n+ poly for poly in shape_spec)\ndef bind_shapes(polymorphic_shapes, padded_shapes):\nenv = {}\n" } ]
Python
Apache License 2.0
google/jax
Do not promote literal dims to Poly
260,335
16.10.2020 12:41:23
25,200
3bf58ddebb765061dbe6803181acddb6952c8f02
demote polys to ints eagerly after each shape rule
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/masking.py", "new_path": "jax/interpreters/masking.py", "diff": "@@ -110,9 +110,12 @@ def eval_poly(poly, values_dict):\ndef _ensure_poly(p):\nif type(p) is Poly:\nreturn p\n-\nreturn Poly({Mon(): p})\n+def _polys_to_ints(shape):\n+ return tuple(int(d) if type(d) is Poly and d.is_constant else d\n+ for d in shape)\n+\ndef is_polymorphic(shape: Sequence[Union[int, 'Poly']]):\nreturn any(map(lambda d: type(d) is Poly, shape))\n@@ -408,9 +411,10 @@ class MaskTrace(Trace):\nif primitive.name == 'reshape': params['polymorphic_shapes'] = polymorphic_shapes\nout = masking_rule(vals, logical_shapes, **params)\nif primitive.multiple_results:\n- return map(partial(MaskTracer, self), out, (o.shape for o in out_aval))\n+ out_shapes = map(_polys_to_ints, [o.shape for o in out_aval])\n+ return map(partial(MaskTracer, self), out, out_shapes)\nelse:\n- return MaskTracer(self, out, out_aval.shape)\n+ return MaskTracer(self, out, _polys_to_ints(out_aval.shape))\ndef process_call(self, call_primitive, f, tracers, params):\nassert call_primitive.multiple_results\n" } ]
Python
Apache License 2.0
google/jax
demote polys to ints eagerly after each shape rule
260,335
16.10.2020 13:11:56
25,200
e51163af32f229fd36b74589f923215daf4a0504
only pass hashable values as static args
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/vmapped_log_probs.ipynb", "new_path": "docs/notebooks/vmapped_log_probs.ipynb", "diff": "\" beta_sample = beta_loc + jnp.exp(beta_log_scale) * epsilon\\n\",\n\" return jnp.mean(batched_log_joint(beta_sample), 0) + jnp.sum(beta_log_scale - 0.5 * np.log(2*np.pi))\\n\",\n\" \\n\",\n- \"elbo = jax.jit(elbo, static_argnums=(1, 2))\\n\",\n+ \"elbo = jax.jit(elbo)\\n\",\n\"elbo_val_and_grad = jax.jit(jax.value_and_grad(elbo, argnums=(0, 1)))\"\n],\n\"execution_count\": 0,\n" }, { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -29,7 +29,7 @@ import collections\nimport operator\nimport os\nimport types\n-from typing import Sequence, Set, Tuple, Union\n+from typing import Sequence, FrozenSet, Tuple, Union\nfrom textwrap import dedent as _dedent\nimport warnings\n@@ -2277,7 +2277,34 @@ def _pad_edge(array, pad_width):\ndef _pad(array, pad_width, mode, constant_values):\narray = asarray(array)\nnd = ndim(array)\n- pad_width = np.broadcast_to(np.asarray(pad_width), (nd, 2))\n+\n+ if nd == 0:\n+ return array\n+\n+ pad_width_shape = np.shape(pad_width)\n+ if pad_width_shape == (nd, 2):\n+ # ((before_1, after_1), ..., (before_N, after_N))\n+ pass\n+ elif pad_width_shape == (1, 2):\n+ # ((before, after),)\n+ pad_width = pad_width * nd\n+ elif pad_width_shape == (2,):\n+ # (before, after) (not in the numpy docstring but works anyway)\n+ before, after = pad_width\n+ pad_width = (pad_width,) * nd\n+ elif pad_width_shape == (1,):\n+ # (pad,)\n+ pad_width, = pad_width\n+ pad_width = ((pad_width, pad_width),) * nd\n+ elif pad_width_shape == ():\n+ # pad\n+ pad_width = ((pad_width, pad_width),) * nd\n+ else:\n+ raise ValueError(f\"pad_width given unexpected structure: {pad_width}. \"\n+ \"See docstring for valid pad_width formats.\")\n+ pad_width = np.array(pad_width)\n+ assert pad_width.shape == (nd, 2), pad_width\n+\nif np.any(pad_width < 0):\nraise ValueError(\"index can't contain negative values\")\n@@ -3291,7 +3318,7 @@ def einsum(*operands, optimize='greedy', precision=None):\n# using einsum_call=True here is an internal api for opt_einsum\noperands, contractions = opt_einsum.contract_path(\n*operands, einsum_call=True, use_blas=True, optimize=optimize)\n- contractions = tuple(data[:3] for data in contractions)\n+ contractions = tuple((a, frozenset(b), c) for a, b, c, *_ in contractions)\nreturn _einsum(operands, contractions, precision)\n@_wraps(np.einsum_path)\n@@ -3304,7 +3331,7 @@ def _removechars(s, chars):\n@partial(jit, static_argnums=(1, 2))\ndef _einsum(operands: Sequence,\n- contractions: Sequence[Tuple[Tuple[int, ...], Set[str], str]],\n+ contractions: Sequence[Tuple[Tuple[int, ...], FrozenSet[str], str]],\nprecision):\noperands = list(_promote_dtypes(*operands))\ndef sum(x, axes):\n@@ -3649,6 +3676,8 @@ def _roll(a, shift, axis):\n@_wraps(np.roll)\ndef roll(a, shift, axis=None):\n+ if isinstance(axis, list):\n+ axis = tuple(axis)\nreturn _roll(a, shift, axis)\n" }, { "change_type": "MODIFY", "old_path": "tests/generated_fun_test.py", "new_path": "tests/generated_fun_test.py", "diff": "@@ -96,7 +96,22 @@ def eval_fun(fun, *args):\ndef maybe_jit(f, num_args):\nstatic_argnums = thin(range(num_args), 0.5)\n- return jit(f, static_argnums=static_argnums)\n+\n+ def fun(*args):\n+ partial_args = list(args)\n+ for i in static_argnums:\n+ partial_args[i] = None\n+\n+ @jit\n+ def jitted_fun(*partial_args):\n+ full_args = list(partial_args)\n+ for i in static_argnums:\n+ full_args[i] = args[i]\n+ return f(*full_args)\n+\n+ return jitted_fun(*partial_args)\n+\n+ return fun\ncounter = it.count()\ndef fresh_var(ty):\n@@ -228,8 +243,7 @@ class GeneratedFunTest(jtu.JaxTestCase):\nvals = gen_vals(fun.in_vars)\nfun = partial(eval_fun, fun)\nans = fun(*vals)\n- static_argnums = thin(range(len(vals)), 0.5)\n- ans_jitted = jit(fun, static_argnums=static_argnums)(*vals)\n+ ans_jitted = maybe_jit(fun, len(vals))(*vals)\ntry:\ncheck_all_close(ans, ans_jitted)\nexcept:\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1190,43 +1190,58 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ncheck_dtypes=False)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_shape={}_mode={}_rpadwidth={}_rconstantvalues={}\".format(\n- jtu.format_shape_dtype_string(shape, dtype), mode, pad_width_rank,\n- constant_values_rank),\n+ {\"testcase_name\": \"_shape={}_mode={}_padwidth={}_constantvalues={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), mode, pad_width,\n+ constant_values),\n\"shape\": shape, \"dtype\": dtype, \"mode\": mode,\n- \"pad_width_rank\": pad_width_rank,\n- \"constant_values_rank\": constant_values_rank,\n- \"rng_factory\": jtu.rand_default,\n- \"irng_factory\": partial(jtu.rand_int, high=3)}\n- for mode, constant_values_rank, shapes in [\n- ('constant', 0, all_shapes),\n- ('constant', 1, all_shapes),\n- ('constant', 2, all_shapes),\n- ('symmetric', None, nonempty_shapes),\n- ('reflect', None, nonempty_shapes),\n- ('wrap', None, nonempty_shapes),\n- ('edge', None, nonempty_shapes),\n+ \"pad_width\": pad_width, \"constant_values\": constant_values,\n+ \"rng_factory\": jtu.rand_default}\n+ for mode, shapes in [\n+ ('constant', all_shapes),\n+ ('symmetric', nonempty_shapes),\n+ ('reflect', nonempty_shapes),\n+ ('wrap', nonempty_shapes),\n+ ('edge', nonempty_shapes),\n]\nfor shape, dtype in _shape_and_dtypes(shapes, all_dtypes)\n- for pad_width_rank in range(3)))\n- def testPad(self, shape, dtype, mode, pad_width_rank, constant_values_rank,\n- rng_factory, irng_factory):\n+ for constant_values in [\n+ # None is used for modes other than 'constant'\n+ None,\n+ # constant\n+ 0, 1,\n+ # (constant,)\n+ (0,), (2.718,),\n+ # ((before_const, after_const),)\n+ ((0, 2),), ((-1, 3.14),),\n+ # ((before_1, after_1), ..., (before_N, after_N))\n+ tuple((i / 2, -3.14 * i) for i in range(len(shape))),\n+ ]\n+ for pad_width in [\n+ # ((before_1, after_1), ..., (before_N, after_N))\n+ tuple((i % 3, (i + 1) % 3) for i in range(len(shape))),\n+ # ((before, after),)\n+ ((1, 2),), ((2, 0),),\n+ # (before, after) (not in the docstring but works in numpy)\n+ (2, 0), (0, 0),\n+ # (pad,)\n+ (1,), (2,),\n+ # pad\n+ 0, 1,\n+ ]\n+ if (pad_width != () and constant_values != () and\n+ ((mode == 'constant' and constant_values is not None) or\n+ (mode != 'constant' and constant_values is None)))))\n+ def testPad(self, shape, dtype, mode, pad_width, constant_values, rng_factory):\nrng = rng_factory(self.rng())\n- irng = irng_factory(self.rng())\n- pad_width = irng([len(shape), 2][2 - pad_width_rank:], np.int32)\n- def np_fun(x, kwargs):\n- if pad_width.size == 0:\n- return x\n- return np.pad(x, pad_width, mode=mode, **kwargs)\n- def jnp_fun(x, kwargs):\n- return jnp.pad(x, pad_width, mode=mode, **kwargs)\n-\n- def args_maker():\n- kwargs = {}\n- if constant_values_rank:\n- kwargs[\"constant_values\"] = rng(\n- [len(shape), 2][2 - constant_values_rank:], dtype)\n- return rng(shape, dtype), kwargs\n+ args_maker = lambda: [rng(shape, dtype)]\n+ if constant_values is None:\n+ np_fun = partial(np.pad, pad_width=pad_width, mode=mode)\n+ jnp_fun = partial(jnp.pad, pad_width=pad_width, mode=mode)\n+ else:\n+ np_fun = partial(np.pad, pad_width=pad_width, mode=mode,\n+ constant_values=constant_values)\n+ jnp_fun = partial(jnp.pad, pad_width=pad_width, mode=mode,\n+ constant_values=constant_values)\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker,\ncheck_dtypes=shape is not jtu.PYTHON_SCALAR_SHAPE)\n@@ -3730,6 +3745,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ndef testIssue883(self):\n# from https://github.com/google/jax/issues/883\n+ raise SkipTest(\"we decided to disallow arrays as static args\")\n@partial(api.jit, static_argnums=(1,))\ndef f(x, v):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -136,7 +136,7 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nreturn_sign=return_sign)\nargs_maker = lambda: [rng(shapes[0], dtype)]\n- self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker)\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, tol=1e-5)\nself._CompileAndCheck(lax_fun, args_maker)\n@parameterized.named_parameters(itertools.chain.from_iterable(\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -1867,13 +1867,13 @@ class PmapWithDevicesTest(jtu.JaxTestCase):\ndef testPmapStaticArgnums(self):\n@partial(pmap, axis_name='i', static_broadcasted_argnums=1)\ndef f(x, y):\n- return jnp.sin(x + y)\n+ return jnp.sin(x + y())\nshape = (xla_bridge.device_count(), 4)\nx = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n- y = np.arange(4, dtype=np.float32)\n+ y = lambda: 3.\nans = f(x, y)\n- expected = np.sin(x + y[None])\n+ expected = np.sin(x + 3.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n" }, { "change_type": "MODIFY", "old_path": "tests/polynomial_test.py", "new_path": "tests/polynomial_test.py", "diff": "from functools import partial\nimport numpy as np\n+import unittest\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -131,6 +132,7 @@ class TestPolynomial(jtu.JaxTestCase):\nfor nonzeros in [0, 3]))\n@jtu.skip_on_devices(\"gpu\")\ndef testRootsInvalid(self, zeros, nonzeros, dtype, rng_factory):\n+ raise unittest.SkipTest(\"getting segfaults on MKL\")\nrng = rng_factory(np.random.RandomState(0))\n# The polynomial coefficients here start with zero and would have to\n" } ]
Python
Apache License 2.0
google/jax
only pass hashable values as static args
260,510
16.10.2020 14:53:23
25,200
e8901d51af2ef95a13fe0826e52c4fa68c05a14b
Add default implementation of process_custom_jvp_call and process_custom_vjp_call to `jax.experimental.callback`
[ { "change_type": "MODIFY", "old_path": "jax/experimental/callback.py", "new_path": "jax/experimental/callback.py", "diff": "@@ -156,3 +156,16 @@ class CallbackTrace(Trace):\nf = callback_subtrace(f, self.main)\nvals_out = call_primitive.bind(f, *vals_in, **params)\nreturn [CallbackTracer(self, val) for val in vals_out]\n+\n+ def process_custom_jvp_call(self, primitive, fun, jvp, tracers):\n+ # This implementation just drops the custom derivative rule.\n+ # TODO(sharadmv): don't drop the custom derivative rule\n+ del primitive, jvp # Unused.\n+ return fun.call_wrapped(*tracers)\n+\n+ def process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers,\n+ out_trees):\n+ # This implementation just drops the custom derivative rule.\n+ # TODO(sharadmv): don't drop the custom derivative rule\n+ del primitive, fwd, bwd, out_trees # Unused.\n+ return fun.call_wrapped(*tracers)\n" }, { "change_type": "MODIFY", "old_path": "tests/callback_test.py", "new_path": "tests/callback_test.py", "diff": "from absl.testing import absltest\nfrom absl.testing import parameterized\n+import jax\nfrom jax import test_util as jtu\nfrom jax.experimental.callback import find_by_value, rewrite, FoundValue\nimport jax.numpy as jnp\n@@ -89,5 +90,17 @@ class CallbackTest(jtu.JaxTestCase):\nrewrite(f, {lax.mul_p: lambda x, y: x + y})(x),\njnp.array([4.0, 6.0]))\n+ def testRewriteWithCustomGradients(self):\n+ def f(x):\n+ return jax.nn.relu(x)\n+\n+ x = jnp.array([2.0, 4.0])\n+ self.assertAllClose(f(x), jnp.array([2.0, 4.0]))\n+\n+ self.assertAllClose(\n+ rewrite(f, {})(x),\n+ jnp.array([2.0, 4.0]))\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add default implementation of process_custom_jvp_call and process_custom_vjp_call to `jax.experimental.callback`
260,335
16.10.2020 15:07:02
25,200
c8a1a8ded4dd1fc49a3445ad108500bb4346f38b
remove extraneous test tol change
[ { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -136,7 +136,7 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nreturn_sign=return_sign)\nargs_maker = lambda: [rng(shapes[0], dtype)]\n- self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, tol=1e-5)\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker)\nself._CompileAndCheck(lax_fun, args_maker)\n@parameterized.named_parameters(itertools.chain.from_iterable(\n" } ]
Python
Apache License 2.0
google/jax
remove extraneous test tol change
260,335
16.10.2020 17:57:59
25,200
1ab0c3d31e1d0715335bb765ed7f9165771167cb
refine linearize aval checks
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1762,10 +1762,11 @@ def _lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args):\ntangent_avals = list(map(core.get_aval, tangents))\nfor primal_aval, tangent_aval in zip(primal_avals, tangent_avals):\ntry:\n- core.lattice_join(primal_aval, tangent_aval)\n+ core.lattice_join(primal_aval.at_least_vspace(), tangent_aval)\nexcept TypeError as e:\nmsg = (\"linearized function called on tangent values inconsistent with \"\n- \"the original primal values.\")\n+ \"the original primal values: \"\n+ f\"got {tangent_aval} for primal aval {primal_aval}\")\nraise ValueError(msg) from e\ntangents_out = eval_jaxpr(jaxpr, consts, *tangents)\nreturn tuple(map(lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),\n" } ]
Python
Apache License 2.0
google/jax
refine linearize aval checks
260,335
16.10.2020 18:21:01
25,200
a493a0f43d29ad04d34ba2b4265e312be23a41a9
ensure ConcreteArray equality stays in Python
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1025,9 +1025,12 @@ class ConcreteArray(ShapedArray):\nassert self.dtype != np.dtype('O'), val\ndef __eq__(self, other):\n- return (type(self) is type(other) and self.dtype == other.dtype\n- and self.shape == other.shape and self.weak_type == other.weak_type\n- and np.all(self.val == other.val))\n+ if (type(self) is type(other) and self.dtype == other.dtype\n+ and self.shape == other.shape and self.weak_type == other.weak_type):\n+ with eval_context(): # in case self.val is a DeviceArray\n+ return (self.val == other.val).all()\n+ else:\n+ return False\ndef __hash__(self):\nreturn id(self.val)\n" } ]
Python
Apache License 2.0
google/jax
ensure ConcreteArray equality stays in Python
260,631
17.10.2020 10:36:09
25,200
e9909ce008ec9953c1e8805606aedda76e4ef217
Copybara import of the project: by Peter Hawkins Move jax.nn implementation into jax._src.nn.
[ { "change_type": "DELETE", "old_path": "jax/_src/nn/__init__.py", "new_path": null, "diff": "-# Copyright 2020 Google LLC\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n" }, { "change_type": "DELETE", "old_path": "jax/_src/nn/initializers.py", "new_path": null, "diff": "-# Copyright 2019 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-\"\"\"\n-Common neural network layer initializers, consistent with definitions\n-used in Keras and Sonnet.\n-\"\"\"\n-\n-\n-from functools import partial\n-\n-import numpy as np\n-\n-import jax.numpy as jnp\n-from jax import lax\n-from jax import ops\n-from jax import random\n-from jax.util import prod\n-\n-def zeros(key, shape, dtype=jnp.float32): return jnp.zeros(shape, dtype)\n-def ones(key, shape, dtype=jnp.float32): return jnp.ones(shape, dtype)\n-\n-def uniform(scale=1e-2, dtype=jnp.float32):\n- def init(key, shape, dtype=dtype):\n- return random.uniform(key, shape, dtype) * scale\n- return init\n-\n-def normal(stddev=1e-2, dtype=jnp.float32):\n- def init(key, shape, dtype=dtype):\n- return random.normal(key, shape, dtype) * stddev\n- return init\n-\n-def _compute_fans(shape, in_axis=-2, out_axis=-1):\n- receptive_field_size = prod(shape) / shape[in_axis] / shape[out_axis]\n- fan_in = shape[in_axis] * receptive_field_size\n- fan_out = shape[out_axis] * receptive_field_size\n- return fan_in, fan_out\n-\n-def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1, dtype=jnp.float32):\n- def init(key, shape, dtype=dtype):\n- fan_in, fan_out = _compute_fans(shape, in_axis, out_axis)\n- if mode == \"fan_in\": denominator = fan_in\n- elif mode == \"fan_out\": denominator = fan_out\n- elif mode == \"fan_avg\": denominator = (fan_in + fan_out) / 2\n- else:\n- raise ValueError(\n- \"invalid mode for variance scaling initializer: {}\".format(mode))\n- variance = jnp.array(scale / denominator, dtype=dtype)\n- if distribution == \"truncated_normal\":\n- # constant is stddev of standard normal truncated to (-2, 2)\n- stddev = jnp.sqrt(variance) / jnp.array(.87962566103423978, dtype)\n- return random.truncated_normal(key, -2, 2, shape, dtype) * stddev\n- elif distribution == \"normal\":\n- return random.normal(key, shape, dtype) * jnp.sqrt(variance)\n- elif distribution == \"uniform\":\n- return random.uniform(key, shape, dtype, -1) * jnp.sqrt(3 * variance)\n- else:\n- raise ValueError(\"invalid distribution for variance scaling initializer\")\n- return init\n-\n-xavier_uniform = glorot_uniform = partial(variance_scaling, 1.0, \"fan_avg\", \"uniform\")\n-xavier_normal = glorot_normal = partial(variance_scaling, 1.0, \"fan_avg\", \"truncated_normal\")\n-lecun_uniform = partial(variance_scaling, 1.0, \"fan_in\", \"uniform\")\n-lecun_normal = partial(variance_scaling, 1.0, \"fan_in\", \"truncated_normal\")\n-kaiming_uniform = he_uniform = partial(variance_scaling, 2.0, \"fan_in\", \"uniform\")\n-kaiming_normal = he_normal = partial(variance_scaling, 2.0, \"fan_in\", \"truncated_normal\")\n-\n-def orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float32):\n- \"\"\"\n- Construct an initializer for uniformly distributed orthogonal matrices.\n-\n- If the shape is not square, the matrices will have orthonormal rows or columns\n- depending on which side is smaller.\n- \"\"\"\n- def init(key, shape, dtype=dtype):\n- if len(shape) < 2:\n- raise ValueError(\"orthogonal initializer requires at least a 2D shape\")\n- n_rows, n_cols = prod(shape) // shape[column_axis], shape[column_axis]\n- matrix_shape = (n_cols, n_rows) if n_rows < n_cols else (n_rows, n_cols)\n- A = random.normal(key, matrix_shape, dtype)\n- Q, R = jnp.linalg.qr(A)\n- diag_sign = lax.broadcast_to_rank(jnp.sign(jnp.diag(R)), rank=Q.ndim)\n- Q *= diag_sign # needed for a uniform distribution\n- if n_rows < n_cols: Q = Q.T\n- Q = jnp.reshape(Q, tuple(np.delete(shape, column_axis)) + (shape[column_axis],))\n- Q = jnp.moveaxis(Q, -1, column_axis)\n- return scale * Q\n- return init\n-\n-\n-def delta_orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float32):\n- \"\"\"\n- Construct an initializer for delta orthogonal kernels; see arXiv:1806.05393.\n-\n- The shape must be 3D, 4D or 5D.\n- \"\"\"\n- def init(key, shape, dtype=dtype):\n- if len(shape) not in [3, 4, 5]:\n- raise ValueError(\"Delta orthogonal initializer requires a 3D, 4D or 5D \"\n- \"shape.\")\n- if shape[-1] < shape[-2]:\n- raise ValueError(\"`fan_in` must be less or equal than `fan_out`. \")\n- ortho_init = orthogonal(scale=scale, column_axis=column_axis, dtype=dtype)\n- ortho_matrix = ortho_init(key, shape[-2:])\n- W = jnp.zeros(shape, dtype=dtype)\n- if len(shape) == 3:\n- k = shape[0]\n- return ops.index_update(W, ops.index[(k-1)//2, ...], ortho_matrix)\n- elif len(shape) == 4:\n- k1, k2 = shape[:2]\n- return ops.index_update(W, ops.index[(k1-1)//2, (k2-1)//2, ...], ortho_matrix)\n- else:\n- k1, k2, k3 = shape[:3]\n- return ops.index_update(W, ops.index[(k1-1)//2, (k2-1)//2, (k3-1)//2, ...],\n- ortho_matrix)\n- return init\n" }, { "change_type": "MODIFY", "old_path": "jax/nn/__init__.py", "new_path": "jax/nn/__init__.py", "diff": "# flake8: noqa: F401\nfrom . import initializers\n-from jax._src.nn.functions import (\n+from .functions import (\ncelu,\nelu,\ngelu,\n" }, { "change_type": "RENAME", "old_path": "jax/_src/nn/functions.py", "new_path": "jax/nn/functions.py", "diff": "" }, { "change_type": "MODIFY", "old_path": "jax/nn/initializers.py", "new_path": "jax/nn/initializers.py", "diff": "@@ -17,23 +17,111 @@ Common neural network layer initializers, consistent with definitions\nused in Keras and Sonnet.\n\"\"\"\n-# flake8: noqa: F401\n-from jax._src.nn.initializers import (\n- delta_orthogonal,\n- glorot_normal,\n- glorot_uniform,\n- he_normal,\n- he_uniform,\n- kaiming_normal,\n- kaiming_uniform,\n- lecun_normal,\n- lecun_uniform,\n- normal,\n- ones,\n- orthogonal,\n- uniform,\n- variance_scaling,\n- xavier_normal,\n- xavier_uniform,\n- zeros,\n-)\n+\n+from functools import partial\n+\n+import numpy as np\n+\n+import jax.numpy as jnp\n+from jax import lax\n+from jax import ops\n+from jax import random\n+from jax.util import prod\n+\n+def zeros(key, shape, dtype=jnp.float32): return jnp.zeros(shape, dtype)\n+def ones(key, shape, dtype=jnp.float32): return jnp.ones(shape, dtype)\n+\n+def uniform(scale=1e-2, dtype=jnp.float32):\n+ def init(key, shape, dtype=dtype):\n+ return random.uniform(key, shape, dtype) * scale\n+ return init\n+\n+def normal(stddev=1e-2, dtype=jnp.float32):\n+ def init(key, shape, dtype=dtype):\n+ return random.normal(key, shape, dtype) * stddev\n+ return init\n+\n+def _compute_fans(shape, in_axis=-2, out_axis=-1):\n+ receptive_field_size = prod(shape) / shape[in_axis] / shape[out_axis]\n+ fan_in = shape[in_axis] * receptive_field_size\n+ fan_out = shape[out_axis] * receptive_field_size\n+ return fan_in, fan_out\n+\n+def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1, dtype=jnp.float32):\n+ def init(key, shape, dtype=dtype):\n+ fan_in, fan_out = _compute_fans(shape, in_axis, out_axis)\n+ if mode == \"fan_in\": denominator = fan_in\n+ elif mode == \"fan_out\": denominator = fan_out\n+ elif mode == \"fan_avg\": denominator = (fan_in + fan_out) / 2\n+ else:\n+ raise ValueError(\n+ \"invalid mode for variance scaling initializer: {}\".format(mode))\n+ variance = jnp.array(scale / denominator, dtype=dtype)\n+ if distribution == \"truncated_normal\":\n+ # constant is stddev of standard normal truncated to (-2, 2)\n+ stddev = jnp.sqrt(variance) / jnp.array(.87962566103423978, dtype)\n+ return random.truncated_normal(key, -2, 2, shape, dtype) * stddev\n+ elif distribution == \"normal\":\n+ return random.normal(key, shape, dtype) * jnp.sqrt(variance)\n+ elif distribution == \"uniform\":\n+ return random.uniform(key, shape, dtype, -1) * jnp.sqrt(3 * variance)\n+ else:\n+ raise ValueError(\"invalid distribution for variance scaling initializer\")\n+ return init\n+\n+xavier_uniform = glorot_uniform = partial(variance_scaling, 1.0, \"fan_avg\", \"uniform\")\n+xavier_normal = glorot_normal = partial(variance_scaling, 1.0, \"fan_avg\", \"truncated_normal\")\n+lecun_uniform = partial(variance_scaling, 1.0, \"fan_in\", \"uniform\")\n+lecun_normal = partial(variance_scaling, 1.0, \"fan_in\", \"truncated_normal\")\n+kaiming_uniform = he_uniform = partial(variance_scaling, 2.0, \"fan_in\", \"uniform\")\n+kaiming_normal = he_normal = partial(variance_scaling, 2.0, \"fan_in\", \"truncated_normal\")\n+\n+def orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float32):\n+ \"\"\"\n+ Construct an initializer for uniformly distributed orthogonal matrices.\n+\n+ If the shape is not square, the matrices will have orthonormal rows or columns\n+ depending on which side is smaller.\n+ \"\"\"\n+ def init(key, shape, dtype=dtype):\n+ if len(shape) < 2:\n+ raise ValueError(\"orthogonal initializer requires at least a 2D shape\")\n+ n_rows, n_cols = prod(shape) // shape[column_axis], shape[column_axis]\n+ matrix_shape = (n_cols, n_rows) if n_rows < n_cols else (n_rows, n_cols)\n+ A = random.normal(key, matrix_shape, dtype)\n+ Q, R = jnp.linalg.qr(A)\n+ diag_sign = lax.broadcast_to_rank(jnp.sign(jnp.diag(R)), rank=Q.ndim)\n+ Q *= diag_sign # needed for a uniform distribution\n+ if n_rows < n_cols: Q = Q.T\n+ Q = jnp.reshape(Q, tuple(np.delete(shape, column_axis)) + (shape[column_axis],))\n+ Q = jnp.moveaxis(Q, -1, column_axis)\n+ return scale * Q\n+ return init\n+\n+\n+def delta_orthogonal(scale=1.0, column_axis=-1, dtype=jnp.float32):\n+ \"\"\"\n+ Construct an initializer for delta orthogonal kernels; see arXiv:1806.05393.\n+\n+ The shape must be 3D, 4D or 5D.\n+ \"\"\"\n+ def init(key, shape, dtype=dtype):\n+ if len(shape) not in [3, 4, 5]:\n+ raise ValueError(\"Delta orthogonal initializer requires a 3D, 4D or 5D \"\n+ \"shape.\")\n+ if shape[-1] < shape[-2]:\n+ raise ValueError(\"`fan_in` must be less or equal than `fan_out`. \")\n+ ortho_init = orthogonal(scale=scale, column_axis=column_axis, dtype=dtype)\n+ ortho_matrix = ortho_init(key, shape[-2:])\n+ W = jnp.zeros(shape, dtype=dtype)\n+ if len(shape) == 3:\n+ k = shape[0]\n+ return ops.index_update(W, ops.index[(k-1)//2, ...], ortho_matrix)\n+ elif len(shape) == 4:\n+ k1, k2 = shape[:2]\n+ return ops.index_update(W, ops.index[(k1-1)//2, (k2-1)//2, ...], ortho_matrix)\n+ else:\n+ k1, k2, k3 = shape[:3]\n+ return ops.index_update(W, ops.index[(k1-1)//2, (k2-1)//2, (k3-1)//2, ...],\n+ ortho_matrix)\n+ return init\n" } ]
Python
Apache License 2.0
google/jax
Copybara import of the project: -- a396cfbbd414f6f21f0c7e8a68e6e89d202c0e84 by Peter Hawkins <phawkins@google.com>: Move jax.nn implementation into jax._src.nn. PiperOrigin-RevId: 337671917
260,335
20.10.2020 15:35:03
25,200
4a19de60695037281af970d657f6c94600ce5a40
added test skips based on jaxlib version (o/w these were failing at HEAD for me)
[ { "change_type": "MODIFY", "old_path": "tests/array_interoperability_test.py", "new_path": "tests/array_interoperability_test.py", "diff": "@@ -116,6 +116,8 @@ class DLPackTest(jtu.JaxTestCase):\nfor dtype in dlpack_dtypes))\n@unittest.skipIf(not tf, \"Test requires TensorFlow\")\ndef testJaxToTensorFlow(self, shape, dtype):\n+ if jax.lib.version < (0, 1, 57):\n+ raise unittest.SkipTest(\"Requires jaxlib >= 0.1.57\");\nif not FLAGS.jax_enable_x64 and dtype in [jnp.int64, jnp.uint64,\njnp.float64]:\nself.skipTest(\"x64 types are disabled by jax_enable_x64\")\n@@ -158,6 +160,8 @@ class DLPackTest(jtu.JaxTestCase):\nfor dtype in torch_dtypes))\n@unittest.skipIf(not torch, \"Test requires PyTorch\")\ndef testJaxToTorch(self, shape, dtype):\n+ if jax.lib.version < (0, 1, 57):\n+ raise unittest.SkipTest(\"Requires jaxlib >= 0.1.57\");\nif not FLAGS.jax_enable_x64 and dtype in [jnp.int64, jnp.float64]:\nself.skipTest(\"x64 types are disabled by jax_enable_x64\")\nrng = jtu.rand_default(self.rng())\n" } ]
Python
Apache License 2.0
google/jax
added test skips based on jaxlib version (o/w these were failing at HEAD for me)
260,335
20.10.2020 16:10:56
25,200
ac6cd23b67a04e1efeaf4a0550fe5888b8acd211
improve an escaped tracer error
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -942,7 +942,7 @@ class JaxprStackFrame:\ndef find_progenitors(self, tracer):\nvar = self.tracer_to_var.get(id(tracer))\nif not var:\n- return []\n+ return None, None\nactive_vars = {var}\nfor eqn in self.eqns[::-1]:\nproduced = set(eqn.outvars) & active_vars\n@@ -1009,6 +1009,16 @@ class DynamicJaxprTrace(core.Trace):\ndef getvar(self, tracer):\nvar = self.frame.tracer_to_var.get(id(tracer))\nif var is None:\n+ if tracer.line_info is not None:\n+ detail = f\"tracer created on line {source_info_util.summarize(tracer.line_info)}\"\n+ else:\n+ detail = None\n+ raise core.escaped_tracer_error(detail)\n+ return var\n+\n+ def makevar(self, tracer):\n+ var = self.frame.tracer_to_var.get(id(tracer))\n+ assert var is None, \"a jaxpr variable must be created only once per tracer\"\nself.frame.tracers.append(tracer)\nvar = self.frame.tracer_to_var[id(tracer)] = self.frame.newvar(tracer.aval)\nreturn var\n@@ -1033,7 +1043,7 @@ class DynamicJaxprTrace(core.Trace):\nsource_info = source_info_util.current()\nout_tracers = [DynamicJaxprTracer(self, a, source_info) for a in out_avals]\ninvars = map(self.getvar, tracers)\n- outvars = map(self.getvar, out_tracers)\n+ outvars = map(self.makevar, out_tracers)\neqn = new_jaxpr_eqn(invars, outvars, primitive, params, source_info)\nself.frame.eqns.append(eqn)\nreturn out_tracers if primitive.multiple_results else out_tracers.pop()\n@@ -1046,8 +1056,8 @@ class DynamicJaxprTrace(core.Trace):\nsource_info = source_info_util.current()\nout_tracers = [DynamicJaxprTracer(self, a, source_info) for a in out_avals]\ninvars = map(self.getvar, tracers)\n- outvars = map(self.getvar, out_tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\n+ outvars = map(self.makevar, out_tracers)\nnew_params = dict(params, call_jaxpr=convert_constvars_jaxpr(jaxpr))\nupdate_params = call_param_updaters.get(call_primitive)\nif update_params:\n@@ -1072,8 +1082,8 @@ class DynamicJaxprTrace(core.Trace):\nsource_info = source_info_util.current()\nout_tracers = [DynamicJaxprTracer(self, a, source_info) for a in out_avals]\ninvars = map(self.getvar, tracers)\n- outvars = map(self.getvar, out_tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\n+ outvars = map(self.makevar, out_tracers)\nnew_mapped_invars = (False,) * len(consts) + params['mapped_invars']\nnew_params = dict(params, mapped_invars=new_mapped_invars,\ncall_jaxpr=convert_constvars_jaxpr(jaxpr))\n@@ -1096,8 +1106,8 @@ class DynamicJaxprTrace(core.Trace):\nlambda: trace_to_subjaxpr_dynamic(jvp, self.main, 2 * in_avals)[::2])\nout_tracers = [DynamicJaxprTracer(self, a) for a in out_avals]\ninvars = map(self.getvar, tracers)\n- outvars = map(self.getvar, out_tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\n+ outvars = map(self.makevar, out_tracers)\neqn = new_jaxpr_eqn([*constvars, *invars], outvars, prim.initial_style,\ndict(fun_jaxpr=closed_fun_jaxpr,\njvp_jaxpr_thunk=jvp_jaxpr_thunk,\n@@ -1117,8 +1127,8 @@ class DynamicJaxprTrace(core.Trace):\nlambda: trace_to_subjaxpr_dynamic(fwd, self.main, in_avals)[::2])\nout_tracers = [DynamicJaxprTracer(self, a) for a in out_avals]\ninvars = map(self.getvar, tracers)\n- outvars = map(self.getvar, out_tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\n+ outvars = map(self.makevar, out_tracers)\neqn = new_jaxpr_eqn([*constvars, *invars], outvars, prim.initial_style,\ndict(fun_jaxpr=closed_fun_jaxpr,\nfwd_jaxpr_thunk=fwd_jaxpr_thunk,\n" } ]
Python
Apache License 2.0
google/jax
improve an escaped tracer error
260,335
20.10.2020 17:51:51
25,200
79e3db550897972e0eee071b69aa923785bd5f85
fixes on (thanks
[ { "change_type": "MODIFY", "old_path": "docs/custom_vjp_update.md", "new_path": "docs/custom_vjp_update.md", "diff": "@@ -70,7 +70,7 @@ Here's a case where we actually need `nondiff_argnums` with `custom_vjp`:\nfrom functools import partial\nimport jax\n-@partial(jax.custom_vjp, nondiff_argnums)\n+@partial(jax.custom_vjp, nondiff_argnums=(0,))\ndef skip_app(f, x):\nreturn f(x)\n" }, { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -183,9 +183,10 @@ class custom_jvp:\nraise AttributeError(msg.format(self.__name__))\nargs = _resolve_kwargs(self.fun, args, kwargs)\nif self.nondiff_argnums:\n- args = [_stop_gradient(x) if i in self.nondiff_argnums else x\n+ nondiff_argnums = set(self.nondiff_argnums)\n+ args = [_stop_gradient(x) if i in nondiff_argnums else x\nfor i, x in enumerate(args)]\n- diff_argnums = [i for i in range(len(args)) if i not in self.nondiff_argnums]\n+ diff_argnums = [i for i in range(len(args)) if i not in nondiff_argnums]\nf_, dyn_args = argnums_partial(lu.wrap_init(self.fun), diff_argnums, args)\nstatic_args = [args[i] for i in self.nondiff_argnums]\njvp = _add_args(lu.wrap_init(self.jvp), static_args)\n@@ -455,7 +456,8 @@ class custom_vjp:\nargs = _resolve_kwargs(self.fun, args, kwargs)\nif self.nondiff_argnums:\nfor i in self.nondiff_argnums: _check_for_tracers(args[i])\n- dyn_argnums = [i for i in range(len(args)) if i not in self.nondiff_argnums]\n+ nondiff_argnums = set(self.nondiff_argnums)\n+ dyn_argnums = [i for i in range(len(args)) if i not in nondiff_argnums]\nf_, dyn_args = argnums_partial(lu.wrap_init(self.fun), dyn_argnums, args)\nstatic_args = [args[i] for i in self.nondiff_argnums]\nfwd, _ = argnums_partial(lu.wrap_init(self.fwd), dyn_argnums, args)\n" } ]
Python
Apache License 2.0
google/jax
fixes on #4008 (thanks @apaszke)
260,335
20.10.2020 19:10:41
25,200
2b62a44736d6818195e244760f46569008973280
only run test with omnistaging on
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2384,6 +2384,9 @@ class RematTest(jtu.JaxTestCase):\ndef test_escaped_tracer_remat(self):\n# b/169779185\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\ndef f():\nseq = [jnp.zeros([])]\ndef g():\n" } ]
Python
Apache License 2.0
google/jax
only run test with omnistaging on
260,335
20.10.2020 21:08:59
25,200
a46d0028ccc6f4639a733fca542b97e121f754d4
fix a custom_jvp vmap bug from
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -332,12 +332,13 @@ def _custom_jvp_call_jaxpr_vmap(\n@pe._memoize\ndef batched_jvp_jaxpr_thunk():\njvp_jaxpr = core.ClosedJaxpr(*jvp_jaxpr_thunk()) # consts can be tracers\n- _, all_batched = batching.batch_jaxpr(jvp_jaxpr, size, in_batched * 2, False)\n+ _, args_batched = split_list(in_batched, [num_consts])\n+ _, all_batched = batching.batch_jaxpr(jvp_jaxpr, size, args_batched * 2, False)\nprimals_batched, tangents_batched = split_list(all_batched, [num_out])\nout_batched = map(op.or_, primals_batched, tangents_batched)\nout_dims2.append([0 if b else not_mapped for b in out_batched])\nbatched_jvp_jaxpr, _ = batching.batch_jaxpr(\n- jvp_jaxpr, size, in_batched * 2, out_batched * 2)\n+ jvp_jaxpr, size, args_batched * 2, out_batched * 2)\nreturn batched_jvp_jaxpr.jaxpr, batched_jvp_jaxpr.consts\nbatched_outs = custom_jvp_call_jaxpr_p.bind(\n@@ -617,6 +618,7 @@ def _custom_vjp_call_jaxpr_vmap(\nelse x for x, d in zip(args, in_dims)]\nin_batched = [d is not not_mapped for d in in_dims]\n+ _, args_batched = split_list(in_batched, [num_consts])\nbatched_fun_jaxpr, out_batched = batching.batch_jaxpr(fun_jaxpr, size, in_batched, False)\nout_dims1 = [0 if b else not_mapped for b in out_batched]\nout_dims2 = []\n@@ -624,14 +626,15 @@ def _custom_vjp_call_jaxpr_vmap(\n@pe._memoize\ndef batched_fwd_jaxpr_thunk():\nfwd_jaxpr = core.ClosedJaxpr(*fwd_jaxpr_thunk()) # consts can be tracers\n- batched_fwd_jaxpr, out_batched = batching.batch_jaxpr(fwd_jaxpr, size, in_batched, False)\n+ batched_fwd_jaxpr, out_batched = batching.batch_jaxpr(\n+ fwd_jaxpr, size, args_batched, False)\nout_dims2.append([0 if b else not_mapped for b in out_batched])\nreturn batched_fwd_jaxpr.jaxpr, batched_fwd_jaxpr.consts\n- fwd_in_dims = [0 if b else not_mapped for b in in_batched]\n+ fwd_args_batched = [0 if b else not_mapped for b in args_batched]\nfwd_out_dims = lambda: out_dims2[0]\n# TODO(mattjj,apaszke): Support collectives in custom_vjp?\n- batched_bwd = batching.batch_fun(bwd, fwd_out_dims, fwd_in_dims,\n+ batched_bwd = batching.batch_fun(bwd, fwd_out_dims, fwd_args_batched,\naxis_name='__unused_axis_name', sum_match=True)\nbatched_outs = custom_vjp_call_jaxpr_p.bind(\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3388,6 +3388,27 @@ class CustomJVPTest(jtu.JaxTestCase):\nexpected = api.grad(api.grad(api.grad(g)))(2.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_initial_style_vmap_2(self):\n+ y = jnp.array([1., 2., 3.])\n+\n+ @api.custom_jvp\n+ def f(x):\n+ assert jnp.ndim(x) == 0\n+ return 3 * x * jnp.sum(y)\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ g, = tangents\n+ return f(x), 2 * g\n+ f.defjvp(f_jvp)\n+\n+ def foo(x):\n+ out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n+ return out\n+\n+ ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.ones(3))\n+ expected = 2. * jnp.ones(3)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nclass CustomVJPTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
fix a custom_jvp vmap bug from @dpfau
260,296
20.10.2020 22:58:53
25,200
da0bff2fa8e8335d5c90e22413ed4a5e8ccab674
Add `lax.conv_general_dilated_patches`
[ { "change_type": "MODIFY", "old_path": "docs/jax.lax.rst", "new_path": "docs/jax.lax.rst", "diff": "@@ -53,6 +53,7 @@ Operators\nconv\nconvert_element_type\nconv_general_dilated\n+ conv_general_dilated_patches\nconv_with_general_padding\nconv_transpose\ncos\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -551,7 +551,6 @@ def conv_general_dilated(\nIf `dimension_numbers` is `None`, the default is `('NCHW', 'OIHW', 'NCHW')`\n(for a 2D convolution).\n\"\"\"\n- dnums: ConvDimensionNumbers\ndnums = conv_dimension_numbers(lhs.shape, rhs.shape, dimension_numbers)\nif lhs_dilation is None:\nlhs_dilation = (1,) * (lhs.ndim - 2)\n@@ -5934,7 +5933,8 @@ def _canonicalize_precision(precision):\nf\"or a tuple of two lax.Precision values; got {precision}\")\n-def conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers):\n+def conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers\n+ ) -> ConvDimensionNumbers:\n\"\"\"Converts convolution `dimension_numbers` to a `ConvDimensionNumbers`.\nArgs:\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/lax/other.py", "diff": "+# Copyright 2020 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+\n+from typing import Sequence, Tuple, Union\n+import numpy as np\n+from jax._src.numpy import lax_numpy as jnp\n+from . import lax\n+\n+\n+def conv_general_dilated_patches(\n+ lhs: lax.Array,\n+ filter_shape: Sequence[int],\n+ window_strides: Sequence[int],\n+ padding: Union[str, Sequence[Tuple[int, int]]],\n+ lhs_dilation: Sequence[int] = None,\n+ rhs_dilation: Sequence[int] = None,\n+ dimension_numbers: lax.ConvGeneralDilatedDimensionNumbers = None,\n+ precision: lax.PrecisionType = None,\n+) -> lax.Array:\n+ \"\"\"Extract patches subject to the receptive field of `conv_general_dilated`.\n+\n+ Runs the input through a convolution with given parameters. The kernel of the\n+ convolution is constructed such that the output channel dimension `\"C\"`\n+ contains flattened image patches, so instead a single `\"C\"` dimension\n+ represents, for example, three dimensions `\"chw\"` collapsed. The order of\n+ these dimensions is `\"c\" + ''.join(c for c in rhs_spec if c not in 'OI')`,\n+ where `rhs_spec == dimension_numbers[1]`, and the size of this `\"C\"`\n+ dimension is therefore the size of each patch, i.e.\n+ `np.prod(filter_shape) * lhs.shape[lhs_spec.index('C')]`, where\n+ `lhs_spec == dimension_numbers[0]`.\n+\n+ Docstring below adapted from `jax.lax.conv_general_dilated`.\n+\n+ See Also:\n+ https://www.tensorflow.org/xla/operation_semantics#conv_convolution\n+\n+ Args:\n+ lhs: a rank `n+2` dimensional input array.\n+ filter_shape: a sequence of `n` integers, representing the receptive window\n+ spatial shape in the order as specified in\n+ `rhs_spec = dimension_numbers[1]`.\n+ window_strides: a sequence of `n` integers, representing the inter-window\n+ strides.\n+ padding: either the string `'SAME'`, the string `'VALID'`, or a sequence of\n+ `n` `(low, high)` integer pairs that give the padding to apply before and\n+ after each spatial dimension.\n+ lhs_dilation: `None`, or a sequence of `n` integers, giving the\n+ dilation factor to apply in each spatial dimension of `lhs`. LHS dilation\n+ is also known as transposed convolution.\n+ rhs_dilation: `None`, or a sequence of `n` integers, giving the\n+ dilation factor to apply in each spatial dimension of `rhs`. RHS dilation\n+ is also known as atrous convolution.\n+ dimension_numbers: either `None`, or a 3-tuple\n+ `(lhs_spec, rhs_spec, out_spec)`, where each element is a string\n+ of length `n+2`. `None` defaults to `(\"NCHWD..., OIHWD..., NCHWD...\")`.\n+ precision: Optional. Either ``None``, which means the default precision for\n+ the backend, or a ``lax.Precision`` enum value (``Precision.DEFAULT``,\n+ ``Precision.HIGH`` or ``Precision.HIGHEST``).\n+\n+ Returns:\n+ A rank `n+2` array containing the flattened image patches in the output\n+ channel (`\"C\"`) dimension. For example if\n+ `dimension_numbers = (\"NcHW\", \"OIwh\", \"CNHW\")`, the output has dimension\n+ numbers `\"CNHW\" = \"{cwh}NHW\"`, with the size of dimension `\"C\"` equal to\n+ the size of each patch\n+ (`np.prod(filter_shape) * lhs.shape[lhs_spec.index('C')]`).\n+\n+ \"\"\"\n+ filter_shape = tuple(filter_shape)\n+ dimension_numbers = lax.conv_dimension_numbers(\n+ lhs.shape, (1, 1) + filter_shape, dimension_numbers)\n+\n+ lhs_spec, rhs_spec, out_spec = dimension_numbers\n+\n+ spatial_size = np.prod(filter_shape)\n+ n_channels = lhs.shape[lhs_spec[1]]\n+\n+ # Move separate `lhs` spatial locations into separate `rhs` channels.\n+ rhs = jnp.eye(spatial_size, dtype=lhs.dtype).reshape(filter_shape * 2)\n+\n+ rhs = rhs.reshape((spatial_size, 1) + filter_shape)\n+ rhs = jnp.tile(rhs, (n_channels,) + (1,) * (rhs.ndim - 1))\n+ rhs = jnp.moveaxis(rhs, (0, 1), (rhs_spec[0], rhs_spec[1]))\n+\n+ out = lax.conv_general_dilated(\n+ lhs=lhs,\n+ rhs=rhs,\n+ window_strides=window_strides,\n+ padding=padding,\n+ lhs_dilation=lhs_dilation,\n+ rhs_dilation=rhs_dilation,\n+ dimension_numbers=dimension_numbers,\n+ precision=None if precision is None else (precision,\n+ lax.Precision.DEFAULT),\n+ feature_group_count=n_channels\n+ )\n+ return out\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/__init__.py", "new_path": "jax/lax/__init__.py", "diff": "@@ -338,6 +338,9 @@ from jax._src.lax.parallel import (\npsum_p,\npswapaxes,\n)\n+from jax._src.lax.other import (\n+ conv_general_dilated_patches\n+)\n# TODO(phawkins): fix callers and remove these imports.\nfrom . import lax\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -493,6 +493,190 @@ class LaxTest(jtu.JaxTestCase):\nself._CompileAndCheck(fun, args_maker)\n+ def testConvGeneralDilatedPatchesOverlapping1D(self):\n+ lhs = np.array([[1]], np.float32).reshape((1, 1))\n+ patches = lax.conv_general_dilated_patches(\n+ lhs=lhs,\n+ filter_shape=(),\n+ window_strides=(),\n+ padding='SAME'\n+ )\n+ self.assertAllClose(lhs, patches)\n+\n+ dn = ('NHC', 'OIH', 'NHC')\n+ lhs = np.array([1, 2, 3, 4, 5], np.float32).reshape((1, -1, 1))\n+\n+ patches = lax.conv_general_dilated_patches(\n+ lhs=lhs,\n+ filter_shape=(2,),\n+ window_strides=(2,),\n+ padding='VALID',\n+ dimension_numbers=dn\n+ )\n+ self.assertAllClose(\n+ np.array([[1, 2],\n+ [3, 4]], np.float32).reshape((1, 2, 2)), patches)\n+\n+ patches = lax.conv_general_dilated_patches(\n+ lhs=lhs,\n+ filter_shape=(3,),\n+ window_strides=(1,),\n+ padding='SAME',\n+ dimension_numbers=dn\n+ )\n+ self.assertAllClose(\n+ np.array([[0, 1, 2],\n+ [1, 2, 3],\n+ [2, 3, 4],\n+ [3, 4, 5],\n+ [4, 5, 0]], np.float32).reshape((1, 5, 3)), patches)\n+\n+ patches = lax.conv_general_dilated_patches(\n+ lhs=lhs,\n+ filter_shape=(3,),\n+ window_strides=(1,),\n+ padding='SAME',\n+ rhs_dilation=(2,),\n+ dimension_numbers=dn\n+ )\n+ self.assertAllClose(\n+ np.array([[0, 1, 3],\n+ [0, 2, 4],\n+ [1, 3, 5],\n+ [2, 4, 0],\n+ [3, 5, 0]], np.float32).reshape((1, 5, 3)), patches)\n+\n+ def testConvGeneralDilatedPatchesOverlapping2D(self):\n+ lhs = np.array([[1, 2, 3],\n+ [4, 5, 6]], np.float32).reshape((1, 2, 3, 1))\n+ patches = lax.conv_general_dilated_patches(\n+ lhs=lhs,\n+ filter_shape=(2, 2),\n+ window_strides=(1, 1),\n+ padding='SAME',\n+ dimension_numbers=('NHWC', 'OIHW', 'NHWC')\n+ )\n+ self.assertAllClose(np.array([[1, 2, 4, 5],\n+ [2, 3, 5, 6],\n+ [3, 0, 6, 0],\n+ [4, 5, 0, 0],\n+ [5, 6, 0, 0],\n+ [6, 0, 0, 0]],\n+ np.float32).reshape((1, 2, 3, 4)), patches)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_filter_shape={}_strides={}_padding={}\"\n+ \"_dims={}_precision={}\".format(\n+ jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(filter_shape, dtype),\n+ strides,\n+ padding,\n+ \"None\" if dim_nums is None else \",\".join(dim_nums),\n+ precision\n+ ),\n+ \"lhs_shape\": lhs_shape,\n+ \"filter_shape\": filter_shape,\n+ \"dtype\": dtype,\n+ \"strides\": strides,\n+ \"padding\": padding,\n+ \"dimension_numbers\": dim_nums,\n+ \"rng_factory\": rng_factory,\n+ \"precision\": precision\n+ }\n+ for dtype in inexact_dtypes\n+ for rng_factory in [jtu.rand_small]\n+ for lhs_shape, filter_shape, strides, padding, dim_nums in [\n+ ((2, 5), (), (), [], (\"NC\", \"OI\", \"CN\")),\n+ ((2, 3, 4), (2,), (2,), [(0, 2)], (\"CNH\", \"OHI\", \"HNC\")),\n+ ((3, 1, 4, 5), (1, 3), (1, 3), [(3, 1), (2, 2)],\n+ (\"NCHW\", \"OIHW\", \"NCHW\")),\n+ ((3, 2, 5, 6), (4, 3), (4, 3), [(5, 2), (2, 4)],\n+ None),\n+ ((1, 2, 3, 4), (1, 1), (1, 1), [(0, 0), (0, 0)],\n+ (\"NCWH\", \"OHWI\", \"CNHW\")),\n+ ((1, 2, 3, 4), (3, 2), (1, 1), [(0, 0), (0, 0)],\n+ (\"CWHN\", \"HOWI\", \"NCHW\")),\n+ ((2, 3, 4, 5, 6), (2, 1, 3), (2, 1, 3), [(1, 2), (5, 3), (3, 5)],\n+ (\"NHWDC\", \"HDIWO\", \"DCWNH\"))\n+ ]\n+ for precision in [None,\n+ lax.Precision.DEFAULT,\n+ lax.Precision.HIGH,\n+ lax.Precision.HIGHEST]\n+ ))\n+ def testConvGeneralDilatedPatchesNonOverlapping(self,\n+ lhs_shape,\n+ filter_shape,\n+ dtype,\n+ strides,\n+ padding,\n+ dimension_numbers,\n+ rng_factory,\n+ precision):\n+ rng = rng_factory(self.rng())\n+ lhs = rng(lhs_shape, dtype)\n+\n+ if dimension_numbers is None:\n+ lhs_spec, rhs_spec, out_spec = \"NCHW\", \"OIHW\", \"NCHW\"\n+ else:\n+ lhs_spec, rhs_spec, out_spec = dimension_numbers\n+\n+ filter_spec = ''.join(c for c in rhs_spec if c not in ('I', 'O'))\n+ patches_spec = out_spec.replace('C', 'C' + filter_spec.lower())\n+\n+ full_padding = []\n+ for c in lhs_spec:\n+ if c in ('N', 'C'):\n+ full_padding += [(0, 0)]\n+ else:\n+ full_padding += [padding[filter_spec.index(c)]]\n+\n+ lhs_padded = np.pad(lhs, full_padding, 'constant')\n+ out = lax.transpose(lhs_padded, [lhs_spec.index(c) for c in out_spec])\n+\n+ patches = lax.conv_general_dilated_patches(\n+ lhs=lhs,\n+ filter_shape=filter_shape,\n+ window_strides=strides,\n+ padding=padding,\n+ dimension_numbers=dimension_numbers,\n+ precision=precision\n+ )\n+\n+ source = []\n+\n+ # Test that output spatial shape is factored into `#patches x patch_size`.\n+ for c in out_spec:\n+ out_c = out.shape[out_spec.index(c)]\n+ patch_c = patches.shape[out_spec.index(c)]\n+\n+ if c == 'N':\n+ self.assertEqual(out_c, patch_c)\n+ elif c == 'C':\n+ self.assertEqual(out_c * np.prod(filter_shape), patch_c)\n+ else:\n+ self.assertEqual(out_c, patch_c * filter_shape[filter_spec.index(c)])\n+\n+ source += [patches_spec.index(c), patches_spec.index(c.lower())]\n+\n+ # Test that stacking patches together gives the source image, padded.\n+ c = out_spec.index('C')\n+ patches = patches.reshape(patches.shape[:c] +\n+ (lhs_shape[lhs_spec.index('C')],) +\n+ filter_shape +\n+ patches.shape[c + 1:]\n+ )\n+ patches = np.moveaxis(patches, source, range(len(source)))\n+ for i in range(len(filter_shape)):\n+ patches = patches.reshape(patches.shape[:i] + (-1,) +\n+ patches.shape[2 + i:])\n+ patches = np.moveaxis(\n+ patches,\n+ range(len(filter_shape)),\n+ [out_spec.index(c) for c in out_spec if c not in ('N', 'C')])\n+ self.assertAllClose(out, patches)\n+\n# TODO(mattjj): test conv_general_dilated against numpy\ndef testConv0DIsDot(self):\n" } ]
Python
Apache License 2.0
google/jax
Add `lax.conv_general_dilated_patches`
260,651
17.10.2020 23:48:39
-10,800
b7fee456e6334ec2aaf275719b5c463b1d1332a9
[impl] Add support for setdiff1d
[ { "change_type": "MODIFY", "old_path": "docs/jax.numpy.rst", "new_path": "docs/jax.numpy.rst", "diff": "@@ -316,6 +316,7 @@ Not every function in NumPy is implemented; contributions are welcome!\nsearchsorted\nselect\nset_printoptions\n+ setdiff1d\nshape\nsign\nsignbit\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1464,6 +1464,19 @@ def in1d(ar1, ar2, assume_unique=False, invert=False):\nelse:\nreturn (ar1[:, None] == ar2).any(-1)\n+@_wraps(np.setdiff1d, lax_description=\"\"\"\n+In the JAX version, the `assume_unique` argument is not referenced.\n+\"\"\")\n+def setdiff1d(ar1, ar2, assume_unique=False):\n+ ar1 = core.concrete_or_error(asarray, ar1, \"The error arose in setdiff1d()\")\n+ ar2 = core.concrete_or_error(asarray, ar2, \"The error arose in setdiff1d()\")\n+\n+ ar1 = unique(ar1)\n+ ar2 = unique(ar2)\n+\n+ idx = in1d(ar1, ar2, invert=True)\n+ return ar1[idx]\n+\n@partial(jit, static_argnums=2)\ndef _intersect1d_sorted_mask(ar1, ar2, return_indices=False):\n\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/numpy/__init__.py", "new_path": "jax/numpy/__init__.py", "diff": "@@ -55,7 +55,7 @@ from jax._src.numpy.lax_numpy import (\nprod, product, promote_types, ptp, quantile,\nrad2deg, radians, ravel, ravel_multi_index, real, reciprocal, remainder, repeat, reshape,\nresult_type, right_shift, rint, roll, rollaxis, rot90, round, row_stack,\n- save, savez, searchsorted, select, set_printoptions, shape, sign, signbit,\n+ save, savez, searchsorted, select, set_printoptions, setdiff1d, shape, sign, signbit,\nsignedinteger, sin, sinc, single, sinh, size, sometrue, sort, sort_complex, split, sqrt,\nsquare, squeeze, stack, std, subtract, sum, swapaxes, take, take_along_axis,\ntan, tanh, tensordot, tile, trace, trapz, transpose, tri, tril, tril_indices, tril_indices_from,\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1073,6 +1073,19 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_{}\".format(\n+ jtu.format_shape_dtype_string(shape1, dtype1),\n+ jtu.format_shape_dtype_string(shape2, dtype2)),\n+ \"shape1\": shape1, \"shape2\": shape2, \"dtype1\": dtype1, \"dtype2\": dtype2}\n+ for dtype1 in [s for s in default_dtypes if s != jnp.bfloat16]\n+ for dtype2 in [s for s in default_dtypes if s != jnp.bfloat16]\n+ for shape1 in all_shapes\n+ for shape2 in all_shapes))\n+ def testSetdiff1d(self, shape1, shape2, dtype1, dtype2):\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape1, dtype1), rng(shape2, dtype2)]\n+ self._CheckAgainstNumpy(np.setdiff1d, jnp.setdiff1d, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_{}_assume_unique={}_return_indices={}\".format(\n" } ]
Python
Apache License 2.0
google/jax
[impl] Add support for setdiff1d
260,335
22.10.2020 15:31:43
25,200
f40ac067178652e1eb9804ce298ad9e1b60a0392
make lax.dynamic_slice transpose handle symb zeros
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3756,11 +3756,14 @@ def _dynamic_slice_jvp(primals, tangents, *, slice_sizes):\ndef _dynamic_slice_transpose_rule(t, operand, *start_indices, slice_sizes):\nassert ad.is_undefined_primal(operand)\nassert all(not ad.is_undefined_primal(s) for s in start_indices)\n- operand_shape = operand.aval.shape\n+ operand_shape, operand_dtype = operand.aval.shape, operand.aval.dtype\nif config.omnistaging_enabled:\n- zeros = full(operand_shape, _zero(t))\n+ zeros = full(operand_shape, 0, operand_dtype)\nelse:\nzeros = full(operand_shape, tie_in(t, _zero(t)))\n+ if type(t) is ad_util.Zero:\n+ return [zeros] + [None] * len(start_indices)\n+ else:\nreturn ([dynamic_update_slice(zeros, t, start_indices)] +\n[None] * len(start_indices))\n" } ]
Python
Apache License 2.0
google/jax
make lax.dynamic_slice transpose handle symb zeros
260,335
22.10.2020 16:37:08
25,200
ced333d1d4aec2825e9afd81c2ca9721b7e3cc67
redo lazy simplification
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -1411,6 +1411,11 @@ def iota(dtype: DType, size: int) -> Array:\n<https://www.tensorflow.org/xla/operation_semantics#iota>`_\noperator.\n\"\"\"\n+ if config.omnistaging_enabled:\n+ dtype = dtypes.canonicalize_dtype(dtype)\n+ size = core.concrete_or_error(int, size, \"size argument of lax.iota\")\n+ return iota_p.bind(dtype=dtype, shape=(size,), dimension=0)\n+ else:\nsize = size if type(size) is masking.Poly else int(size)\nshape = canonicalize_shape((size,))\ndtype = dtypes.canonicalize_dtype(dtype)\n@@ -1422,41 +1427,54 @@ def broadcasted_iota(dtype: DType, shape: Shape, dimension: int) -> Array:\n\"\"\"Convenience wrapper around ``iota``.\"\"\"\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = canonicalize_shape(shape)\n- dimension = int(dimension)\n- return broadcast_in_dim(iota(dtype, shape[dimension]), shape, [dimension])\n+ dimension = core.concrete_or_error(\n+ int, dimension, \"dimension argument of lax.broadcasted_iota\")\n+ return iota_p.bind(dtype=dtype, shape=shape, dimension=dimension)\ndef _eye(dtype: DType, shape: Shape, offset: int) -> Array:\n- \"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\n-\n- This function exists for creating lazy identity matrices; that is,\n- materialization of the array is delayed and it may be fused into consumers to\n- avoid materialization at all.\"\"\"\n+ \"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\"\"\"\nN, M = tuple(map(int, shape))\noffset = int(offset)\ndtype = dtypes.canonicalize_dtype(dtype)\n+ if config.omnistaging_enabled:\n+ bool_eye = eq(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n+ broadcasted_iota(np.int32, (N, M), 1))\n+ return convert_element_type_p.bind(bool_eye, new_dtype=dtype,\n+ old_dtype=np.bool_)\n+ else:\nlazy_expr = lazy.eye(dtype, (N, M), offset)\naval = ShapedArray((N, M), dtype)\nreturn xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\ndef _delta(dtype: DType, shape: Shape, axes: Sequence[int]) -> Array:\n- \"\"\"This function exists for creating lazy Kronecker delta arrays, particularly\n- for use in jax.numpy.einsum to express traces. It differs from ``eye`` in that\n- it can create arrays of any rank, but doesn't allow offsets.\"\"\"\n+ \"\"\"This utility function exists for creating Kronecker delta arrays.\"\"\"\nshape = tuple(map(int, shape))\naxes = tuple(map(int, axes))\ndtype = dtypes.canonicalize_dtype(dtype)\nbase_shape = tuple(np.take(shape, axes))\n+ if config.omnistaging_enabled:\n+ iotas = [broadcasted_iota(np.uint32, base_shape, i)\n+ for i in range(len(base_shape))]\n+ eyes = [eq(i1, i2) for i1, i2 in zip(iotas[:-1], iotas[1:])]\n+ result = convert_element_type_p.bind(_reduce(operator.and_, eyes),\n+ new_dtype=dtype, old_dtype=np.bool_)\n+ return broadcast_in_dim(result, shape, axes)\n+ else:\nlazy_expr = lazy.broadcast(lazy.delta(dtype, base_shape), shape, axes)\naval = ShapedArray(shape, dtype)\nreturn xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\ndef _tri(dtype: DType, shape: Shape, offset: int) -> Array:\n- \"\"\"Like numpy.tri, create a 2D array with ones below a diagonal.\n- This function exists for creating lazy triangular matrices, particularly for\n- use in jax.numpy.tri.\"\"\"\n+ \"\"\"Like numpy.tri, create a 2D array with ones below a diagonal.\"\"\"\nN, M = tuple(map(int, shape))\noffset = int(offset)\ndtype = dtypes.canonicalize_dtype(dtype)\n+ if config.omnistaging_enabled:\n+ bool_tri = ge(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n+ broadcasted_iota(np.int32, (N, M), 1))\n+ return convert_element_type_p.bind(bool_tri, old_dtype=np.int32,\n+ new_dtype=dtype)\n+ else:\nlazy_expr = lazy.tri(dtype, (N, M), offset)\naval = ShapedArray((N, M), dtype)\nreturn xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\n@@ -5715,6 +5733,30 @@ rng_uniform_p.def_impl(partial(xla.apply_primitive, rng_uniform_p))\nrng_uniform_p.def_abstract_eval(_rng_uniform_abstract_eval)\nxla.translations[rng_uniform_p] = _rng_uniform_translation_rule\n+\n+def _iota_abstract_eval(*, dtype, shape, dimension):\n+ _check_shapelike(\"iota\", \"shape\", shape)\n+ if not any(dtypes.issubdtype(dtype, t) for t in _num):\n+ msg = 'iota does not accept dtype {}. Accepted dtypes are subtypes of {}.'\n+ typename = str(np.dtype(dtype).name)\n+ accepted_typenames = (t.__name__ for t in _num)\n+ raise TypeError(msg.format(typename, ', '.join(accepted_typenames)))\n+ if not 0 <= dimension < len(shape):\n+ raise ValueError(\"iota dimension must be between 0 and len(shape), got \"\n+ f\"dimension={dimension} for shape {shape}\")\n+ return ShapedArray(shape, dtype)\n+\n+def _iota_translation_rule(c, dtype, shape, dimension):\n+ etype = xla_client.dtype_to_etype(dtype)\n+ xla_shape = xc.Shape.array_shape(etype, shape)\n+ return xops.Iota(c, xla_shape, dimension)\n+\n+iota_p = Primitive('iota')\n+iota_p.def_impl(partial(xla.apply_primitive, iota_p))\n+iota_p.def_abstract_eval(_iota_abstract_eval)\n+xla.translations[iota_p] = _iota_translation_rule\n+\n+\n### util\n_ndim = np.ndim\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -25,7 +25,6 @@ from jax import config\nfrom jax import core\nfrom jax import custom_derivatives\nfrom jax import dtypes\n-from jax import lax\nfrom jax import lax_linalg\nfrom jax import linear_util as lu\nfrom jax import numpy as jnp\n@@ -38,9 +37,10 @@ from jax.interpreters import masking\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import pxla\nfrom jax.interpreters import xla\n-from jax._src.lax import lax as lax_internal\n+from jax._src.lax import lax\nfrom jax._src.lax import control_flow as lax_control_flow\nfrom jax._src.lax import fft as lax_fft\n+from jax._src.lax import parallel as lax_parallel\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n@@ -622,9 +622,11 @@ tf_not_yet_impl = [\nlax.random_gamma_grad_p,\n# Not high priority?\n- lax.after_all_p, lax.all_to_all_p, lax.create_token_p, lax.cummax_p, lax.cummin_p,\n- lax.infeed_p, lax.outfeed_p, lax.pmax_p, lax.pmin_p, lax.ppermute_p, lax.psum_p,\n- lax.axis_index_p,\n+ lax.after_all_p, lax_parallel.all_to_all_p, lax.create_token_p,\n+ lax_control_flow.cummax_p, lax_control_flow.cummin_p,\n+ lax.infeed_p, lax.outfeed_p, lax_parallel.pmax_p,\n+ lax_parallel.pmin_p, lax_parallel.ppermute_p, lax_parallel.psum_p,\n+ lax_parallel.axis_index_p,\npxla.xla_pmap_p,\n]\n@@ -693,6 +695,17 @@ tf_impl[lax.sub_p] = tf.math.subtract\ntf_impl[lax.mul_p] = tf.math.multiply\n+def _iota(*, dtype, shape, dimension):\n+ size = shape[dimension]\n+ # Some dtypes are unsupporetd, like uint32, so we just fall back to int32.\n+ # TODO(mattjj, necula): improve tf.range dtype handling\n+ vec = tf.range(tf.cast(size, tf.int32), dtype=tf.int32)\n+ vec_shape = [-1 if i == dimension else 1 for i in range(len(shape))]\n+ return tf.cast(tf.broadcast_to(tf.reshape(vec, vec_shape), shape), dtype)\n+\n+tf_impl[lax.iota_p] = _iota\n+\n+\ndef _div(lhs, rhs):\nif lhs.dtype.is_integer:\nquotient = tf.math.floordiv(lhs, rhs)\n@@ -1203,8 +1216,8 @@ tf_impl[lax.argmax_p] = functools.partial(_argminmax, tf.math.argmax)\n_add_fn = tf.function(tf.math.add, autograph=False)\n_ge_fn = tf.function(tf.math.greater_equal, autograph=False)\n-tf_impl[lax.cumsum_p] = tf.math.cumsum\n-tf_impl[lax.cumprod_p] = tf.math.cumprod\n+tf_impl[lax_control_flow.cumsum_p] = tf.math.cumsum\n+tf_impl[lax_control_flow.cumprod_p] = tf.math.cumprod\ndef _select_and_gather_add(tangents: TfVal,\noperand: TfVal,\n@@ -1231,8 +1244,8 @@ def _select_and_gather_add(tangents: TfVal,\nconst = lambda dtype, x: tf.constant(np.array(x), dtype)\nif double_word_reduction:\n- word_dtype = lax_internal._UINT_DTYPES[nbits]\n- double_word_dtype = lax_internal._UINT_DTYPES[nbits * 2]\n+ word_dtype = lax._UINT_DTYPES[nbits]\n+ double_word_dtype = lax._UINT_DTYPES[nbits * 2]\n# Packs two values into a tuple.\ndef pack(a, b):\n@@ -1605,7 +1618,7 @@ def _cond(index: TfVal, *operands: TfVal,\nfor jaxpr in branches]\nreturn tf.switch_case(index, branches_tf)\n-tf_impl[lax.cond_p] = _cond\n+tf_impl[lax_control_flow.cond_p] = _cond\ndef _while(*args: TfVal, cond_nconsts: int, cond_jaxpr: core.ClosedJaxpr,\n@@ -1672,10 +1685,10 @@ def _batched_cond_while(*args: TfVal,\n(init_pred_b, *init_carry))\nreturn res_carry\n-tf_impl[lax.while_p] = _while\n+tf_impl[lax_control_flow.while_p] = _while\n# We use the scan impl rule to rewrite in terms of while.\n-tf_impl_with_avals[lax.scan_p] = _convert_jax_impl(lax_control_flow._scan_impl)\n+tf_impl_with_avals[lax_control_flow.scan_p] = _convert_jax_impl(lax_control_flow._scan_impl)\ndef _top_k(operand: TfVal, k: int) -> Tuple[TfVal, TfVal]:\n# Some types originally incompatible with tf.math.top_k can be promoted\n@@ -1820,7 +1833,7 @@ def _linear_solve(*args: TfVal, const_lengths, jaxprs, _in_avals, _out_aval):\nreturn _convert_jax_impl(lax_control_flow._custom_linear_solve_impl)(\n*args, const_lengths=const_lengths, jaxprs=jaxprs, _in_avals=_in_avals, _out_aval=_out_aval)\n-tf_impl_with_avals[lax.linear_solve_p] = _linear_solve\n+tf_impl_with_avals[lax_control_flow.linear_solve_p] = _linear_solve\ndef _custom_jvp_call_jaxpr(*args: TfVal,\nfun_jaxpr: core.ClosedJaxpr,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/correctness_stats.py", "new_path": "jax/experimental/jax2tf/tests/correctness_stats.py", "diff": "@@ -91,7 +91,7 @@ def categorize(prim: core.Primitive, *args, **kwargs) \\\npass\nreturn np.dtype(dtype)\n- if args[0] is not core.unit:\n+ if args and args[0] is not core.unit:\nnp_dtype = _to_np_dtype(args[0].dtype)\nelse:\nnp_dtype = None\n" }, { "change_type": "MODIFY", "old_path": "jax/random.py", "new_path": "jax/random.py", "diff": "@@ -304,6 +304,7 @@ def _fold_in(key, data):\nreturn threefry_2x32(key, PRNGKey(data))\n+@partial(jit, static_argnums=(1, 2))\ndef _random_bits(key, bit_width, shape):\n\"\"\"Sample uniform random bits of given width and shape using PRNG key.\"\"\"\nif not _is_prng_key(key):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -33,7 +33,7 @@ import concurrent.futures\nimport jax\nimport jax.numpy as jnp\nfrom jax import float0, jit, grad, device_put, jacfwd, jacrev, hessian\n-from jax import api, core, lax, lax_reference\n+from jax import api, core, lax, lax_reference, lazy\nfrom jax.core import Primitive\nfrom jax.interpreters import ad\nfrom jax.interpreters import xla\n@@ -1507,7 +1507,7 @@ class APITest(jtu.JaxTestCase):\ndef test_dtype_warning(self):\n# cf. issue #1230\nif FLAGS.jax_enable_x64:\n- return # test only applies when x64 is disabled\n+ raise unittest.SkipTest(\"test only applies when x64 is disabled\")\ndef check_warning(warn, nowarn):\nwith warnings.catch_warnings(record=True) as w:\n@@ -2549,14 +2549,14 @@ class LazyTest(jtu.JaxTestCase):\nassert python_should_be_executing\nreturn jnp.sum(x)\n- x = jnp.arange(10, dtype=jnp.int32)\n- assert xla.is_device_constant(x) # lazy iota\n+ x = jnp.zeros(10, dtype=jnp.int32)\n+ assert not lazy.is_trivial(x._lazy_expr)\npython_should_be_executing = True\n_ = f(x)\npython_should_be_executing = False # should not recompile\n- x = np.arange(10, dtype=np.int32)\n+ x = np.zeros(10, dtype=np.int32)\n_ = f(x)\n@parameterized.parameters(jtu.cases_from_list(range(10000)))\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -3696,6 +3696,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ntype(lax.iota(np.int32, 77)))\n# test laziness for int dtypes\n+ if not config.omnistaging_enabled:\nself.assertTrue(xla.is_device_constant(jnp.arange(77)))\nself.assertTrue(xla.is_device_constant(jnp.arange(77, dtype=jnp.int32)))\n" } ]
Python
Apache License 2.0
google/jax
redo #4535 lazy simplification
260,287
26.10.2020 10:11:13
0
6348a99fb4829df1bda0f9ac84437f836769ab66
Add support for vmap collectives in control flow primitives All initial style primitives currently use `batch_jaxpr` in their batching rules, but that function hasn't been updated to support axis_name when I added support for vmap collectives.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -363,7 +363,8 @@ def _pred_bcast_select(c, pred, x, y, x_y_aval: core.AbstractValue):\nbcast_pred = xops.BroadcastInDim(pred, x_shape, list(range(len(pred_shape))))\nreturn xops.Select(bcast_pred, x, y)\n-def _while_loop_batching_rule(args, dims, cond_nconsts, cond_jaxpr,\n+def _while_loop_batching_rule(args, dims, axis_name,\n+ cond_nconsts, cond_jaxpr,\nbody_nconsts, body_jaxpr):\nsize, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}\norig_batched = [d is not batching.not_mapped for d in dims]\n@@ -378,10 +379,11 @@ def _while_loop_batching_rule(args, dims, cond_nconsts, cond_jaxpr,\nfor _ in range(1 + len(carry_bat)):\nbatched = bconst_bat + carry_bat\nbody_jaxpr_batched, carry_bat_out = batching.batch_jaxpr(\n- body_jaxpr, size, batched, instantiate=carry_bat)\n+ body_jaxpr, size, batched, instantiate=carry_bat, axis_name=axis_name)\ncond_jaxpr_batched, (pred_bat,) = batching.batch_jaxpr(\ncond_jaxpr, size, cconst_bat + carry_bat,\n- instantiate=bool(cond_jaxpr.out_avals[0].shape))\n+ instantiate=bool(cond_jaxpr.out_avals[0].shape),\n+ axis_name=axis_name)\ncarry_bat_out = _map(partial(operator.or_, pred_bat), carry_bat_out)\nif carry_bat_out == carry_bat:\nbreak\n@@ -547,7 +549,7 @@ ad.primitive_jvps[while_p] = _while_loop_jvp\npe.custom_partial_eval_rules[while_p] = _while_partial_eval\nxla.initial_style_translations[while_p] = _while_loop_translation_rule\nad.primitive_transposes[while_p] = _while_transpose_error\n-batching.primitive_batchers[while_p] = _while_loop_batching_rule\n+batching.initial_style_batchers[while_p] = _while_loop_batching_rule\n### cond and switch\n@@ -769,7 +771,7 @@ def _cond_index_bcast_and_select_tree(indices, branch_vals):\nindices, np.shape(branch_vals[0]), list(range(np.ndim(indices))))\nreturn _select_tree(bcast_indices, branch_vals)\n-def _cond_batching_rule(args, dims, branches, linear):\n+def _cond_batching_rule(args, dims, axis_name, branches, linear):\n# TODO: maybe avoid moving arg axes to front if we're promoting to select?\nsize, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}\nargs = [batching.moveaxis(x, d, 0) if d is not batching.not_mapped and d != 0\n@@ -779,11 +781,11 @@ def _cond_batching_rule(args, dims, branches, linear):\nindex, *ops = args\nindex_bat, *bat = orig_bat\n- branches_out_bat = [batching.batch_jaxpr(jaxpr, size, bat, False)[1]\n+ branches_out_bat = [batching.batch_jaxpr(jaxpr, size, bat, False, axis_name)[1]\nfor jaxpr in branches]\nout_bat = [any(bat) for bat in zip(*branches_out_bat)]\n- branches_batched = tuple(batching.batch_jaxpr(jaxpr, size, bat, out_bat)[0]\n+ branches_batched = tuple(batching.batch_jaxpr(jaxpr, size, bat, out_bat, axis_name)[0]\nfor jaxpr in branches)\nif index_bat:\n@@ -1107,7 +1109,7 @@ cond_p.def_custom_bind(cond_bind)\nad.primitive_jvps[cond_p] = _cond_jvp\nad.primitive_transposes[cond_p] = _cond_transpose\npe.custom_partial_eval_rules[cond_p] = _cond_partial_eval\n-batching.primitive_batchers[cond_p] = _cond_batching_rule\n+batching.initial_style_batchers[cond_p] = _cond_batching_rule\nxla.initial_style_translations[cond_p] = _cond_translation_rule\ncore.custom_typechecks[cond_p] = _cond_typecheck\n@@ -1728,7 +1730,7 @@ def _make_closed_jaxpr(traceable: lu.WrappedFun, in_avals: Sequence[core.Abstrac\nreturn core.ClosedJaxpr(jaxpr, consts)\n-def _scan_batching_rule(args, dims, reverse, length, jaxpr, num_consts,\n+def _scan_batching_rule(args, dims, axis_name, reverse, length, jaxpr, num_consts,\nnum_carry, linear, unroll):\nnum_ys = len(jaxpr.out_avals) - num_carry\nsize, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}\n@@ -1744,7 +1746,9 @@ def _scan_batching_rule(args, dims, reverse, length, jaxpr, num_consts,\nfor _ in range(1 + len(carry_batched)):\nbatched = const_batched + carry_batched + xs_batched\njaxpr_batched, batched_out = batching.batch_jaxpr(\n- jaxpr, size, batched, instantiate=carry_batched + [False] * num_ys)\n+ jaxpr, size, batched,\n+ instantiate=carry_batched + [False] * num_ys,\n+ axis_name=axis_name)\ncarry_batched_out, ys_batched = batched_out[:num_carry], batched_out[num_carry:]\nif carry_batched_out == carry_batched:\nbreak\n@@ -1865,7 +1869,7 @@ ad.primitive_jvps[scan_p] = _scan_jvp\nad.primitive_transposes[scan_p] = _scan_transpose\npe.custom_partial_eval_rules[scan_p] = _scan_partial_eval\nxla.initial_style_translations[scan_p] = xla.lower_fun_initial_style(_scan_impl)\n-batching.primitive_batchers[scan_p] = _scan_batching_rule\n+batching.initial_style_batchers[scan_p] = _scan_batching_rule\nmasking.masking_rules[scan_p] = _scan_masking_rule\ncore.custom_typechecks[scan_p] = partial(_scan_typecheck, False)\n@@ -2267,7 +2271,7 @@ def _linear_solve_transpose_rule(cotangent, *primals, const_lengths, jaxprs):\nreturn [None] * sum(const_lengths) + cotangent_b\n-def _linear_solve_batching_rule(args, dims, const_lengths, jaxprs):\n+def _linear_solve_batching_rule(args, dims, axis_name, const_lengths, jaxprs):\norig_bat = [d is not batching.not_mapped for d in dims]\nsize, = {\na.shape[d] for a, d in zip(args, dims) if d is not batching.not_mapped\n@@ -2287,23 +2291,23 @@ def _linear_solve_batching_rule(args, dims, const_lengths, jaxprs):\nfor i in range(1 + len(orig_b_bat) + len(solve.out_avals)):\n# Apply vecmat and solve -> new batched parts of x\nsolve_jaxpr_batched, solve_x_bat = batching.batch_jaxpr(\n- solve, size, solve_bat + b_bat, instantiate=x_bat)\n+ solve, size, solve_bat + b_bat, instantiate=x_bat, axis_name=axis_name)\nif vecmat is None:\nvecmat_jaxpr_batched = None\nx_bat_out = solve_x_bat\nelse:\nvecmat_jaxpr_batched, vecmat_x_bat = batching.batch_jaxpr(\n- vecmat, size, vecmat_bat + b_bat, instantiate=x_bat)\n+ vecmat, size, vecmat_bat + b_bat, instantiate=x_bat, axis_name=axis_name)\nx_bat_out = _map(operator.or_, vecmat_x_bat, solve_x_bat)\n# Apply matvec and solve_t -> new batched parts of b\nmatvec_jaxpr_batched, matvec_b_bat = batching.batch_jaxpr(\n- matvec, size, matvec_bat + x_bat_out, instantiate=b_bat)\n+ matvec, size, matvec_bat + x_bat_out, instantiate=b_bat, axis_name=axis_name)\nif solve_t is None:\nsolve_t_jaxpr_batched = None\nb_bat_out = _map(operator.or_, matvec_b_bat, orig_b_bat)\nelse:\nsolve_t_jaxpr_batched, solve_t_b_bat = batching.batch_jaxpr(\n- solve_t, size, solve_t_bat + x_bat_out, instantiate=b_bat)\n+ solve_t, size, solve_t_bat + x_bat_out, instantiate=b_bat, axis_name=axis_name)\nb_bat_out = _map(lambda m, s, o: m or s or o, matvec_b_bat, solve_t_b_bat,\norig_b_bat)\nif x_bat_out == x_bat and b_bat_out == b_bat:\n@@ -2346,7 +2350,7 @@ ad.primitive_jvps[linear_solve_p] = _custom_linear_solve_jvp\nxla.initial_style_translations[linear_solve_p] = \\\nxla.lower_fun_initial_style(_custom_linear_solve_impl)\nad.primitive_transposes[linear_solve_p] = _linear_solve_transpose_rule\n-batching.primitive_batchers[linear_solve_p] = _linear_solve_batching_rule\n+batching.initial_style_batchers[linear_solve_p] = _linear_solve_batching_rule\ndef _interleave(a, b, axis):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -782,7 +782,7 @@ def _axis_index_bind(*, axis_name):\nfor name in reversed(axis_name):\nframe = core.axis_frame(name)\nif frame.main_trace is not None:\n- trace = frame.main_trace.trace_type(frame.main_trace, core.cur_sublevel())\n+ trace = frame.main_trace.with_cur_sublevel()\nname_idx = trace.process_axis_index(frame)\nelse:\nname_idx = core.Primitive.bind(axis_index_p, axis_name=name)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -588,10 +588,12 @@ class EvalTrace(Trace):\nclass MainTrace:\nlevel: int\ntrace_type: Type[Trace]\n+ payload: Dict[str, Any]\n- def __init__(self, level, trace_type) -> None:\n+ def __init__(self, level, trace_type, **payload) -> None:\nself.level = level\nself.trace_type = trace_type\n+ self.payload = payload\ndef __repr__(self) -> str:\nreturn \"MainTrace({},{})\".format(self.level, self.trace_type.__name__)\n@@ -601,7 +603,12 @@ class MainTrace:\ndef __eq__(self, other: object) -> bool:\nreturn (isinstance(other, MainTrace) and\n- self.level == other.level and self.trace_type == other.trace_type)\n+ self.level == other.level and\n+ self.trace_type == other.trace_type and\n+ self.payload == other.payload)\n+\n+ def with_cur_sublevel(self):\n+ return self.trace_type(self, cur_sublevel(), **self.payload)\nclass TraceStack:\n# See comments in https://github.com/google/jax/pull/3370\n@@ -679,12 +686,13 @@ def cur_sublevel() -> Sublevel:\nreturn thread_local_state.trace_state.substack[-1]\n@contextmanager\n-def new_main(trace_type: Type[Trace], dynamic: bool = False,\n- ) -> Generator[MainTrace, None, None]:\n+def new_main(trace_type: Type[Trace],\n+ dynamic: bool = False,\n+ **payload) -> Generator[MainTrace, None, None]:\n# See comments in https://github.com/google/jax/pull/3370\nstack = thread_local_state.trace_state.trace_stack\nlevel = stack.next_level()\n- main = MainTrace(level, trace_type)\n+ main = MainTrace(level, trace_type, **payload)\nstack.push(main)\nif dynamic:\nprev_dynamic, stack.dynamic = stack.dynamic, main\n@@ -753,7 +761,7 @@ def find_top_trace(xs) -> Trace:\ndynamic = thread_local_state.trace_state.trace_stack.dynamic\ntop_main = (dynamic if top_main is None or dynamic.level > top_main.level\nelse top_main)\n- return top_main and top_main.trace_type(top_main, cur_sublevel()) # type: ignore\n+ return top_main and top_main.with_cur_sublevel() # type: ignore\n# -------------------- abstract values --------------------\n@@ -1148,7 +1156,7 @@ def process_env_traces(primitive: Union['CallPrimitive', 'MapPrimitive'],\nans = max(tracers, key=lambda x: x._trace.level)\nelse:\nbreak\n- trace = type(ans._trace)(ans._trace.main, cur_sublevel())\n+ trace = ans._trace.main.with_cur_sublevel()\nouts = map(trace.full_raise, outs)\nouts, cur_todo = primitive.post_process(trace, outs, params)\ntodo.append(cur_todo)\n@@ -1573,9 +1581,9 @@ def omnistaging_disabler() -> None:\nreturn True\n@contextmanager\n- def new_main(trace_type: Type[Trace], bottom=False) -> Generator[MainTrace, None, None]:\n+ def new_main(trace_type: Type[Trace], bottom=False, **payload) -> Generator[MainTrace, None, None]:\nlevel = thread_local_state.trace_state.trace_stack.next_level(bottom)\n- main = MainTrace(level, trace_type)\n+ main = MainTrace(level, trace_type, **payload)\nthread_local_state.trace_state.trace_stack.push(main, bottom)\ntry:\n@@ -1593,7 +1601,7 @@ def omnistaging_disabler() -> None:\ndef find_top_trace(xs) -> Optional[Trace]:\ntop_trace = max((x._trace for x in xs if isinstance(x, Tracer)),\nkey=attrgetter('level'), default=None)\n- return top_trace and type(top_trace)(top_trace.main, cur_sublevel())\n+ return top_trace and top_trace.main.with_cur_sublevel()\n@contextmanager\ndef eval_context():\n" }, { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -316,7 +316,7 @@ def _custom_jvp_call_jaxpr_jvp(\nad.primitive_jvps[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_jvp\ndef _custom_jvp_call_jaxpr_vmap(\n- args, in_dims, *, fun_jaxpr: core.ClosedJaxpr,\n+ args, in_dims, axis_name, *, fun_jaxpr: core.ClosedJaxpr,\njvp_jaxpr_thunk: Callable[[], Tuple[core.Jaxpr, Sequence[Any]]],\nnum_consts: int):\nsize, = {x.shape[d] for x, d in zip(args, in_dims) if d is not not_mapped}\n@@ -325,7 +325,7 @@ def _custom_jvp_call_jaxpr_vmap(\nnum_out = len(fun_jaxpr.out_avals)\nin_batched = [d is not not_mapped for d in in_dims]\n- batched_fun_jaxpr, out_batched = batching.batch_jaxpr(fun_jaxpr, size, in_batched, False)\n+ batched_fun_jaxpr, out_batched = batching.batch_jaxpr(fun_jaxpr, size, in_batched, False, axis_name)\nout_dims1 = [0 if b else not_mapped for b in out_batched]\nout_dims2 = [] # mutable cell updated by batched_jvp_jaxpr_thunk\n@@ -333,12 +333,12 @@ def _custom_jvp_call_jaxpr_vmap(\ndef batched_jvp_jaxpr_thunk():\njvp_jaxpr = core.ClosedJaxpr(*jvp_jaxpr_thunk()) # consts can be tracers\n_, args_batched = split_list(in_batched, [num_consts])\n- _, all_batched = batching.batch_jaxpr(jvp_jaxpr, size, args_batched * 2, False)\n+ _, all_batched = batching.batch_jaxpr(jvp_jaxpr, size, args_batched * 2, False, axis_name)\nprimals_batched, tangents_batched = split_list(all_batched, [num_out])\nout_batched = map(op.or_, primals_batched, tangents_batched)\nout_dims2.append([0 if b else not_mapped for b in out_batched])\nbatched_jvp_jaxpr, _ = batching.batch_jaxpr(\n- jvp_jaxpr, size, args_batched * 2, out_batched * 2)\n+ jvp_jaxpr, size, args_batched * 2, out_batched * 2, axis_name)\nreturn batched_jvp_jaxpr.jaxpr, batched_jvp_jaxpr.consts\nbatched_outs = custom_jvp_call_jaxpr_p.bind(\n@@ -346,7 +346,7 @@ def _custom_jvp_call_jaxpr_vmap(\njvp_jaxpr_thunk=batched_jvp_jaxpr_thunk, num_consts=num_consts)\nout_dims = out_dims2[0] if out_dims2 else out_dims1\nreturn batched_outs, out_dims\n-batching.primitive_batchers[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_vmap\n+batching.initial_style_batchers[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_vmap\nxla.initial_style_translations[custom_jvp_call_jaxpr_p] = \\\nxla.lower_fun_initial_style(_custom_jvp_call_jaxpr_impl)\n@@ -610,7 +610,7 @@ def _custom_vjp_call_jaxpr_jvp(\nad.primitive_jvps[custom_vjp_call_jaxpr_p] = _custom_vjp_call_jaxpr_jvp\ndef _custom_vjp_call_jaxpr_vmap(\n- args, in_dims, *, fun_jaxpr: core.ClosedJaxpr,\n+ args, in_dims, axis_name, *, fun_jaxpr: core.ClosedJaxpr,\nfwd_jaxpr_thunk: Callable[[], Tuple[core.Jaxpr, Sequence[Any]]],\nbwd: lu.WrappedFun, out_trees: Callable, num_consts: int):\nsize, = {x.shape[d] for x, d in zip(args, in_dims) if d is not not_mapped}\n@@ -619,7 +619,7 @@ def _custom_vjp_call_jaxpr_vmap(\nin_batched = [d is not not_mapped for d in in_dims]\n_, args_batched = split_list(in_batched, [num_consts])\n- batched_fun_jaxpr, out_batched = batching.batch_jaxpr(fun_jaxpr, size, in_batched, False)\n+ batched_fun_jaxpr, out_batched = batching.batch_jaxpr(fun_jaxpr, size, in_batched, False, axis_name)\nout_dims1 = [0 if b else not_mapped for b in out_batched]\nout_dims2 = []\n@@ -627,7 +627,7 @@ def _custom_vjp_call_jaxpr_vmap(\ndef batched_fwd_jaxpr_thunk():\nfwd_jaxpr = core.ClosedJaxpr(*fwd_jaxpr_thunk()) # consts can be tracers\nbatched_fwd_jaxpr, out_batched = batching.batch_jaxpr(\n- fwd_jaxpr, size, args_batched, False)\n+ fwd_jaxpr, size, args_batched, False, axis_name)\nout_dims2.append([0 if b else not_mapped for b in out_batched])\nreturn batched_fwd_jaxpr.jaxpr, batched_fwd_jaxpr.consts\n@@ -645,7 +645,7 @@ def _custom_vjp_call_jaxpr_vmap(\nif not config.omnistaging_enabled:\nout_dims = out_dims[:len(batched_outs)]\nreturn batched_outs, out_dims\n-batching.primitive_batchers[custom_vjp_call_jaxpr_p] = _custom_vjp_call_jaxpr_vmap\n+batching.initial_style_batchers[custom_vjp_call_jaxpr_p] = _custom_vjp_call_jaxpr_vmap\nxla.initial_style_translations[custom_vjp_call_jaxpr_p] = \\\nxla.lower_fun_initial_style(_custom_vjp_call_jaxpr_impl)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -37,7 +37,7 @@ def batch(fun: lu.WrappedFun, in_vals, in_dims, out_dim_dests, axis_name):\n@lu.transformation_with_aux\ndef batch_subtrace(main, in_dims, *in_vals, **params):\n- trace = BatchTrace(main, core.cur_sublevel())\n+ trace = main.with_cur_sublevel()\nin_tracers = [BatchTracer(trace, val, dim) if dim is not None else val\nfor val, dim in zip(in_vals, in_dims)]\nouts = yield in_tracers, params\n@@ -60,7 +60,7 @@ def _batch_fun(axis_name, sum_match, in_dims, out_dims_thunk, out_dim_dests,\ncanonicalize_axis(dim, np.ndim(val)) if isinstance(dim, int) else dim\nfor val, dim in zip(in_vals, in_dims)]\nsize, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\n- with core.new_main(BatchTrace) as main:\n+ with core.new_main(BatchTrace, axis_name=axis_name) as main:\nwith core.extend_axis_env(axis_name, size, main):\nout_vals = yield (main, in_dims,) + in_vals, params\ndel main\n@@ -80,7 +80,7 @@ def batch_fun2(fun : lu.WrappedFun, in_dims):\n@lu.transformation\ndef _batch_fun2(in_dims, *in_vals, **params):\n- with core.new_main(BatchTrace) as main:\n+ with core.new_main(BatchTrace, axis_name=None) as main:\nout_vals = yield (main, in_dims,) + in_vals, params\ndel main\nyield out_vals\n@@ -123,6 +123,10 @@ class BatchTracer(Tracer):\nreturn self\nclass BatchTrace(Trace):\n+ def __init__(self, *args, axis_name):\n+ super().__init__(*args)\n+ self.axis_name = axis_name\n+\ndef pure(self, val):\nreturn BatchTracer(self, val, not_mapped)\n@@ -153,7 +157,7 @@ class BatchTrace(Trace):\nresults = map(partial(BatchTracer, self), vals_out, dims_out)\nreturn results if primitive.multiple_results else results[0]\n# TODO(mattjj,phawkins): if no rule implemented, could vmap-via-map here\n- batched_primitive = get_primitive_batcher(primitive)\n+ batched_primitive = get_primitive_batcher(primitive, self.axis_name)\nval_out, dim_out = batched_primitive(vals_in, dims_in, **params)\nif primitive.multiple_results:\nreturn map(partial(BatchTracer, self), val_out, dim_out)\n@@ -175,7 +179,7 @@ class BatchTrace(Trace):\nvals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\nmain = self.main\ndef todo(vals):\n- trace = BatchTrace(main, core.cur_sublevel())\n+ trace = main.with_cur_sublevel()\nreturn map(partial(BatchTracer, trace), vals, dims)\nreturn vals, todo\n@@ -199,7 +203,7 @@ class BatchTrace(Trace):\nvals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\nmain = self.main\ndef todo(vals):\n- trace = BatchTrace(main, core.cur_sublevel())\n+ trace = main.with_cur_sublevel()\nreturn [BatchTracer(trace, v, d + 1 if d is not not_mapped else d)\nfor v, d in zip(vals, dims)]\nreturn vals, todo\n@@ -219,7 +223,7 @@ class BatchTrace(Trace):\nvals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\nmain = self.main\ndef todo(vals):\n- trace = BatchTrace(main, core.cur_sublevel())\n+ trace = main.with_cur_sublevel()\nreturn map(partial(BatchTracer, trace), vals, dims)\nreturn vals, todo\n@@ -241,8 +245,11 @@ class BatchTrace(Trace):\nBatchingRule = Callable[..., Tuple[Any, Union[int, Tuple[int, ...]]]]\nprimitive_batchers : Dict[core.Primitive, BatchingRule] = {}\n+initial_style_batchers : Dict[core.Primitive, Any] = {}\n-def get_primitive_batcher(p):\n+def get_primitive_batcher(p, axis_name):\n+ if p in initial_style_batchers:\n+ return partial(initial_style_batchers[p], axis_name=axis_name)\ntry:\nreturn primitive_batchers[p]\nexcept KeyError as err:\n@@ -378,19 +385,20 @@ def _promote_aval_rank(sz, aval):\nelse:\nreturn ShapedArray((sz,) + aval.shape, aval.dtype)\n-def batch_jaxpr(closed_jaxpr, size, batched, instantiate):\n+def batch_jaxpr(closed_jaxpr, size, batched, instantiate, axis_name):\nf = lu.wrap_init(core.jaxpr_as_fun(closed_jaxpr))\n- f, batched_out = batched_traceable(f, size, batched, instantiate)\n+ f, batched_out = batched_traceable(f, size, batched, instantiate, axis_name)\navals_in = [_promote_aval_rank(size, a) if b else a\nfor a, b in zip(closed_jaxpr.in_avals, batched)]\njaxpr_out, _, consts = pe.trace_to_jaxpr_dynamic(f, avals_in)\nreturn core.ClosedJaxpr(jaxpr_out, consts), batched_out()\n@lu.transformation_with_aux\n-def batched_traceable(size, batched, instantiate, *vals):\n+def batched_traceable(size, batched, instantiate, axis_name, *vals):\nin_dims = [0 if b else None for b in batched]\n- with core.new_main(BatchTrace) as main:\n- trace = BatchTrace(main, core.cur_sublevel())\n+ with core.new_main(BatchTrace, axis_name=axis_name) as main:\n+ with core.extend_axis_env(axis_name, size, main):\n+ trace = main.with_cur_sublevel()\nans = yield map(partial(BatchTracer, trace), vals, in_dims), {}\nout_tracers = map(trace.full_raise, ans)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n@@ -408,7 +416,7 @@ def batched_traceable(size, batched, instantiate, *vals):\n@lu.transformation_with_aux\ndef batch_custom_jvp_subtrace(main, in_dims, *in_vals):\nsize, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\n- trace = BatchTrace(main, core.cur_sublevel())\n+ trace = main.with_cur_sublevel()\nin_tracers = [BatchTracer(trace, val, dim) if dim is not None else val\nfor val, dim in zip(in_vals, in_dims * 2)]\nouts = yield in_tracers, {}\n@@ -436,9 +444,9 @@ def _merge_bdims(x, y):\ndef omnistaging_disabler() -> None:\nglobal batch_jaxpr\n- def batch_jaxpr(jaxpr, size, batched, instantiate):\n+ def batch_jaxpr(jaxpr, size, batched, instantiate, axis_name):\nf = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\n- f, batched_out = batched_traceable(f, size, batched, instantiate)\n+ f, batched_out = batched_traceable(f, size, batched, instantiate, axis_name)\navals_in = [_promote_aval_rank(size, a) if b else a\nfor a, b in zip(jaxpr.in_avals, batched)]\nin_pvals = [pe.PartialVal.unknown(aval) for aval in avals_in]\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1121,7 +1121,7 @@ def _soft_pmap_interp(chunk_size, jaxpr, consts, mapped_invars, *args):\nraise NotImplementedError # TODO\nelse:\nif any(in_mapped):\n- rule = batching.get_primitive_batcher(eqn.primitive)\n+ rule = batching.get_primitive_batcher(eqn.primitive, None)\nin_axes = [0 if m else batching.not_mapped for m in in_mapped]\nout_vals, out_axes = rule(in_vals, in_axes, **eqn.params)\nif not eqn.primitive.multiple_results:\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -18,7 +18,7 @@ from functools import partial\nimport itertools\nimport operator\nimport re\n-from unittest import SkipTest\n+from unittest import SkipTest, skipIf\nimport textwrap\nfrom absl.testing import absltest\n@@ -2520,6 +2520,20 @@ class LaxControlFlowTest(jtu.JaxTestCase):\n*_, ext_res = vjp_fun.args[0].args[0]\nself.assertIsInstance(ext_res, xla.DeviceArray)\n+ @skipIf(not config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def test_scan_vmap_collectives(self):\n+ def scan_f(state, x):\n+ s = lax.psum(state, 'i') * x\n+ return state, s\n+\n+ def scan(state, xs):\n+ return lax.scan(scan_f, state, xs)\n+\n+ scan_v = api.vmap(scan, in_axes=0, out_axes=0, axis_name='i')\n+ self.assertAllClose(\n+ scan_v(jnp.ones([1]), jnp.arange(5).reshape((1, 5))),\n+ (jnp.array([1.]), jnp.array([[0., 1., 2., 3., 4.]])))\nif __name__ == '__main__':\n" } ]
Python
Apache License 2.0
google/jax
Add support for vmap collectives in control flow primitives All initial style primitives currently use `batch_jaxpr` in their batching rules, but that function hasn't been updated to support axis_name when I added support for vmap collectives.
260,621
26.10.2020 23:58:09
-3,600
231168d4806c6d18b2153ce8c1c9add0c563096a
all changes plus test verifcation on TPU squashed
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/optimize/line_search.py", "new_path": "jax/_src/scipy/optimize/line_search.py", "diff": "@@ -112,7 +112,7 @@ def _zoom(restricted_func_and_grad, wolfe_one, wolfe_two, a_lo, phi_lo,\n# This will cause the line search to stop, and since the Wolfe conditions\n# are not satisfied the minimization should stop too.\n- state = state._replace(failed=state.failed | (dalpha <= 1e-5))\n+ state = state._replace(failed=state.failed | (dalpha <= 1e-10))\n# Cubmin is sometimes nan, though in this case the bounds check will fail.\na_j_cubic = _cubicmin(state.a_lo, state.phi_lo, state.dphi_lo, state.a_hi,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/optimize/minimize.py", "new_path": "jax/_src/scipy/optimize/minimize.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 functools import partial\nfrom typing import Any, Callable, Mapping, Optional, Tuple, Union\n-\nfrom .bfgs import minimize_bfgs\nfrom typing import NamedTuple\nimport jax.numpy as jnp\n@@ -92,7 +90,7 @@ def minimize(\nif options is None:\noptions = {}\n- fun_with_args = partial(fun, *args)\n+ fun_with_args = lambda x: fun(x, *args)\nif method.lower() == 'bfgs':\nresults = minimize_bfgs(fun_with_args, x0, **options)\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_optimize_test.py", "new_path": "tests/scipy_optimize_test.py", "diff": "@@ -86,6 +86,14 @@ class TestBFGS(jtu.JaxTestCase):\nscipy_res = scipy.optimize.minimize(func(np), x0, method='BFGS').x\nself.assertAllClose(scipy_res, jax_res, atol=2e-5, check_dtypes=False)\n+ def test_fixes4594(self):\n+ n = 2\n+ A = jnp.eye(n) * 1e4\n+ def f(x):\n+ return jnp.mean((A @ x) ** 2)\n+ results = jax.scipy.optimize.minimize(f, jnp.ones(n), method='BFGS')\n+ self.assertAllClose(results.x, jnp.zeros(n), atol=1e-6, rtol=1e-6)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
all changes plus test verifcation on TPU squashed
260,335
26.10.2020 15:32:31
25,200
7a73e99e1462165a76249ead2cda30dd2665978a
simplify select jvp also remove some coverage of broadcast_p, which jax never generates now
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3624,11 +3624,20 @@ def _select_masking_rule(padded_vals, logical_shapes):\nassert np.array_equal(pred_shape, false_shape)\nreturn select(*padded_vals)\n+def _select_jvp(primals, tangents):\n+ pred, on_true, on_false = primals\n+ _, on_true_dot, on_false_dot = tangents\n+ out = select(pred, on_true, on_false)\n+ if type(on_true_dot) is ad_util.Zero:\n+ out_dot = select(pred, _zeros(on_false_dot), on_false_dot)\n+ elif type(on_false_dot) is ad_util.Zero:\n+ out_dot = select(pred, on_true_dot, _zeros(on_true_dot))\n+ else:\n+ out_dot = select(pred, on_true_dot, on_false_dot)\n+ return out, out_dot\n+\nselect_p = standard_primitive(_select_shape_rule, _select_dtype_rule, 'select')\n-ad.defjvp(select_p,\n- None,\n- lambda g, b, x, y: select(b, g, _zeros(g)),\n- lambda g, b, x, y: select(b, _zeros(g), g))\n+ad.primitive_jvps[select_p] = _select_jvp\nad.primitive_transposes[select_p] = _select_transpose_rule\nbatching.primitive_batchers[select_p] = _select_batch_rule\nmasking.masking_rules[select_p] = _select_masking_rule\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -231,7 +231,6 @@ deflinear(lax.imag_p)\ndeflinear(lax.add_p)\ndeflinear(lax.sub_p)\ndeflinear(lax.convert_element_type_p)\n-deflinear(lax.broadcast_p)\ndeflinear(lax.broadcast_in_dim_p)\ndeflinear(lax.concatenate_p)\ndeflinear(lax.pad_p)\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/__init__.py", "new_path": "jax/lax/__init__.py", "diff": "@@ -62,7 +62,6 @@ from jax._src.lax.lax import (\nbroadcast,\nbroadcast_in_dim,\nbroadcast_in_dim_p,\n- broadcast_p,\nbroadcast_shapes,\nbroadcast_to_rank,\nbroadcasted_iota,\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -2238,6 +2238,14 @@ class LaxTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(TypeError, msg):\nlax.reduce_window(**args)\n+ def test_select_jvp_complexity(self):\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"test requires omnistaging\")\n+ jaxpr = jax.make_jaxpr(lambda x: jax.jvp(lambda x: lax.select(True, x, x),\n+ (x,), (1.,)))(1.)\n+ self.assertLen(jaxpr.jaxpr.eqns, 2)\n+\n+\nclass LazyConstantTest(jtu.JaxTestCase):\ndef _Check(self, make_const, expected):\n# check casting to ndarray works\n" } ]
Python
Apache License 2.0
google/jax
simplify select jvp also remove some coverage of broadcast_p, which jax never generates now
260,335
27.10.2020 13:26:38
25,200
1da36943c868d3a996bd53da3dc88908422ece1f
mention static_argnum values should be immutable
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -134,12 +134,13 @@ def jit(fun: Callable[..., T],\narguments to treat as static (compile-time constant). Operations that only\ndepend on static arguments will be constant-folded in Python (during\ntracing), and so the corresponding argument values can be any Python\n- object. Static arguments should be hashable, meaning both ``__hash__``\n- and ``__eq__`` are implemented. Calling the jitted function with different\n- values for these constants will trigger recompilation. If the jitted\n- function is called with fewer positional arguments than indicated by\n- ``static_argnums`` then an error is raised. Arguments that are not arrays\n- or containers thereof must be marked as static. Defaults to ().\n+ object. Static arguments should be hashable, meaning both ``__hash__`` and\n+ ``__eq__`` are implemented, and immutable. Calling the jitted function\n+ with different values for these constants will trigger recompilation. If\n+ the jitted function is called with fewer positional arguments than\n+ indicated by ``static_argnums`` then an error is raised. Arguments that\n+ are not arrays or containers thereof must be marked as static.\n+ Defaults to ().\ndevice: This is an experimental feature and the API is likely to change.\nOptional, the Device the jitted function will run on. (Available devices\ncan be retrieved via :py:func:`jax.devices`.) The default is inherited from\n" } ]
Python
Apache License 2.0
google/jax
mention static_argnum values should be immutable
260,335
29.10.2020 22:22:15
25,200
bbc85f4aca3184a5cfbd9fd5a7d7fe74a901cd88
revise pytree docs to remove contradiction
[ { "change_type": "MODIFY", "old_path": "docs/pytrees.rst", "new_path": "docs/pytrees.rst", "diff": "@@ -4,13 +4,15 @@ Pytrees\nWhat is a pytree?\n^^^^^^^^^^^^^^^^^\n-In JAX, a pytree is **a container of leaf elements and/or more pytrees**.\n-Containers include lists, tuples, and dicts (JAX can be extended to consider\n-other container types as pytrees, see `Extending pytrees`_ below). A leaf\n-element is anything that's not a pytree, e.g. an array. In other words, a pytree\n-is just **a possibly-nested standard or user-registered Python container**. If\n-nested, note that the container types do not need to match. A single \"leaf\",\n-i.e. a non-container object, is also considered a pytree.\n+In JAX, we use the term *pytree* to refer to a tree-like structure of\n+container-like Python objects. Classes are considered container-like if they\n+are in a pytree registry, which by default includes lists, tuples, and dicts.\n+That is:\n+\n+1. any object whose type is _not_ in the pytree container registry is\n+ considered a _leaf_ pytree;\n+2. any object whose type is in the pytree container registry, and which\n+ contains pytrees, is considered a pytree.\nExample pytrees::\n@@ -20,35 +22,40 @@ Example pytrees::\n[1, {\"k1\": 2, \"k2\": (3, 4)}, 5] # 5 leaves\n+JAX can be extended to consider other container types as pytrees; see\n+`Extending pytrees`_ below.\n+\nPytrees and JAX functions\n^^^^^^^^^^^^^^^^^^^^^^^^^\n-Many JAX functions, including all function transformations, operate over pytrees\n-of arrays (other leaf types are sometimes allowed as well). Transformations are\n-only applied to the leaf arrays while preserving the original pytree structure;\n-for example, ``vmap`` and ``pmap`` only map over arrays, but automatically map\n-over arrays inside of standard Python sequences, and can return mapped Python\n-sequences.\n+Many JAX functions, like ``jax.lax.scan``, operate over pytrees of arrays.\n+JAX function transformations can be applied to functions that accept as input\n+and produce as output pytrees of arrays.\nApplying optional parameters to pytrees\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nSome JAX function transformations take optional parameters that specify how\ncertain input or output values should be treated (e.g. the ``in_axes`` and\n-``out_axes`` arguments to ``vmap``). These parameters are also pytrees, and the\n-leaf values are \"matched up\" with the corresponding input or output leaf arrays.\n-For example, if we pass the following input to vmap (note that the input\n-arguments to a function are considered a tuple)::\n+``out_axes`` arguments to ``vmap``). These parameters can also be pytrees, and\n+their structure must correspond to the pytree structure of the corresponding\n+arguments. In particular, to be able to \"match up\" leaves in these parameter\n+pytrees with values in the argument pytrees, the parameter pytrees are often\n+constrained to be tree prefixes of the argument pytrees.\n+\n+For example, if we pass the following input to ``vmap`` (note that the input\n+arguments to a function considered a tuple)::\n(a1, {\"k1\": a2, \"k2\": a3})\n-We can use the following ``in_axes`` pytree to specify that only the \"k2\"\n-argument is mapped (axis=0) and the rest aren't mapped over (axis=None)::\n+We can use the following ``in_axes`` pytree to specify that only the ``k2``\n+argument is mapped (``axis=0``) and the rest aren't mapped over\n+(``axis=None``)::\n(None, {\"k1\": None, \"k2\": 0})\n-Note that the optional parameter pytree structure must match that of the main\n-input pytree. However, the optional parameters can optionally be specified as a\n+The optional parameter pytree structure must match that of the main input\n+pytree. However, the optional parameters can optionally be specified as a\n\"prefix\" pytree, meaning that a single leaf value can be applied to an entire\nsub-pytree. For example, if we have the same ``vmap`` input as above, but wish\nto only map over the dictionary argument, we can use::\n@@ -60,11 +67,10 @@ value that is applied over the entire argument tuple pytree::\n0\n-This happens to be the default ``in_axes`` value!\n+This happens to be the default ``in_axes`` value for ``vmap``!\nThe same logic applies to other optional parameters that refer to specific input\n-or output values of a transformed function, e.g. ``vmap``'s ``out_axes`` and\n-``pmaps``'s ``in_axes``.\n+or output values of a transformed function, e.g. ``vmap``'s ``out_axes``.\nDeveloper information\n@@ -77,16 +83,16 @@ container types with JAX. Some of these details may change.*\nInternal pytree handling\n------------------------\n-JAX canonicalizes pytrees into flat lists of numeric or array types at the\n-`api.py` boundary (and also in control flow primitives). This keeps downstream\n-JAX internals simpler: `vmap` etc. can handle user functions that accept and\n-return Python containers, while all the other parts of the system can operate on\n-functions that only take (multiple) array arguments and always return a flat\n-list of arrays.\n+JAX flattens pytrees into lists of leaves at the ``api.py`` boundary (and also\n+in control flow primitives). This keeps downstream JAX internals simpler:\n+transformations like ``grad``, ``jit``, and ``vmap`` can handle user functions\n+that accept and return the myriad different Python containers, while all the\n+other parts of the system can operate on functions that only take (multiple)\n+array arguments and always return a flat list of arrays.\n-When JAX flattens a pytree it will produce a list of leaves and a `treedef`\n-object that encodes the structure of the original value. The `treedef` can then\n-be used to construct a matching structured value after transforming the\n+When JAX flattens a pytree it will produce a list of leaves and a ``treedef``\n+object that encodes the structure of the original value. The ``treedef`` can\n+then be used to construct a matching structured value after transforming the\nleaves. Pytrees are tree-like, rather than DAG-like or graph-like, in that we\nhandle them assuming referential transparency and that they can't contain\nreference cycles.\n@@ -170,9 +176,8 @@ treated as leaves::\nExtending pytrees\n-----------------\n-By default, any part of a structured value that is not recognized as an internal\n-pytree node is treated as a leaf (and such containers could not be passed to\n-JAX-traceable functions)::\n+By default, any part of a structured value that is not recognized as an\n+internal pytree node (i.e. container-like) is treated as a leaf::\nclass Special(object):\ndef __init__(self, x, y):\n" } ]
Python
Apache License 2.0
google/jax
revise pytree docs to remove contradiction
260,335
29.10.2020 22:26:23
25,200
95687753dd1f0df1892e27ec5dba9e874a4de0f7
add another brief para about the registry
[ { "change_type": "MODIFY", "old_path": "docs/pytrees.rst", "new_path": "docs/pytrees.rst", "diff": "@@ -14,6 +14,12 @@ That is:\n2. any object whose type is in the pytree container registry, and which\ncontains pytrees, is considered a pytree.\n+For each entry in the pytree container registry, a container-like type is\n+registered with a pair of functions which specify how to convert an instance of\n+the container type to a ``(children, metadata)`` pair and how to convert such a\n+pair back to an instance of the container type. Using these functions, JAX can\n+canonicalize any tree of reigstered container types into tuples.\n+\nExample pytrees::\n[1, \"a\", object()] # 3 leaves\n" } ]
Python
Apache License 2.0
google/jax
add another brief para about the registry
260,335
12.06.2020 10:35:59
25,200
a4ce2813c876326643c49a8032b1e0fb69641fba
link to nn libraries in readme
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "[**Quickstart**](#quickstart-colab-in-the-cloud)\n| [**Transformations**](#transformations)\n| [**Install guide**](#installation)\n+| [**Neural net libraries**](#neural-network-libraries)\n| [**Change logs**](https://jax.readthedocs.io/en/latest/CHANGELOG.html)\n| [**Reference docs**](https://jax.readthedocs.io/en/latest/)\n| [**Code search**](https://cs.opensource.google/jax/jax)\n@@ -77,6 +78,7 @@ perex_grads = jit(vmap(grad_fun, in_axes=(None, 0, 0))) # fast per-example grad\n* [Transformations](#transformations)\n* [Current gotchas](#current-gotchas)\n* [Installation](#installation)\n+* [Neural net libraries](#neural-net-libraries)\n* [Citing JAX](#citing-jax)\n* [Reference documentation](#reference-documentation)\n@@ -443,6 +445,11 @@ if you run into any errors or problems with the prebuilt wheels.\nSee [Building JAX from\nsource](https://jax.readthedocs.io/en/latest/developer.html#building-from-source).\n+## Neural network libraries\n+\n+There are lots of great deep learning libraries built on top of JAX!\n+\n+If you want a batteries-included library for neural network training, try [Flax](https://github.com/google/flax) by a Google Brain team in Amsterdam. Another good option is DeepMind's [Haiku](https://github.com/deepmind/dm-haiku), a JAX version of Sonnet focused solely on neural network layers. Finally, [Trax](https://github.com/google/trax) by a Brain team in California is a configuration-driven framework focused on sequence model research and reinforcement learning as a successor to Tensor2Tensor.\n## Citing JAX\n" } ]
Python
Apache License 2.0
google/jax
link to nn libraries in readme Co-authored-by: Skye Wanderman-Milne <skyewm@google.com> Co-authored-by: James Bradbury <jekbradbury@google.com>
260,335
30.10.2020 08:42:04
25,200
a7d1963bc84a3321e9d2f47c9e0f8de050553d12
update neural network libraries text
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -447,9 +447,21 @@ source](https://jax.readthedocs.io/en/latest/developer.html#building-from-source\n## Neural network libraries\n-There are lots of great deep learning libraries built on top of JAX!\n-\n-If you want a batteries-included library for neural network training, try [Flax](https://github.com/google/flax) by a Google Brain team in Amsterdam. Another good option is DeepMind's [Haiku](https://github.com/deepmind/dm-haiku), a JAX version of Sonnet focused solely on neural network layers. Finally, [Trax](https://github.com/google/trax) by a Brain team in California is a configuration-driven framework focused on sequence model research and reinforcement learning as a successor to Tensor2Tensor.\n+Multiple Google research groups develop and share libraries for training neural\n+networks in JAX. If you want a fully featured library for neural network\n+training with examples and how-to guides, try\n+[Flax](https://github.com/google/flax). Another option is\n+[Trax](https://github.com/google/trax), a combinator-based framework focused on\n+ease-of-use and end-to-end single-command examples, especially for sequence\n+models and reinforcement learning. Finally,\n+[Objax](https://github.com/google/objax) is a minimalist object-oriented\n+framework with a PyTorch-like interface.\n+\n+DeepMind has open-sourced an ecosystem of libraries around JAX including\n+[Haiku](https://github.com/deepmind/dm-haiku) for neural network modules,\n+[Optax](https://github.com/deepmind/optax) for gradient processing and\n+optimization, [RLax](https://github.com/deepmind/rlax) for RL algorithms, and\n+[chex](https://github.com/deepmind/chex) for reliable code and testing.\n## Citing JAX\n@@ -460,7 +472,7 @@ To cite this repository:\nauthor = {James Bradbury and Roy Frostig and Peter Hawkins and Matthew James Johnson and Chris Leary and Dougal Maclaurin and Skye Wanderman-Milne},\ntitle = {{JAX}: composable transformations of {P}ython+{N}um{P}y programs},\nurl = {http://github.com/google/jax},\n- version = {0.1.55},\n+ version = {0.2.5},\nyear = {2018},\n}\n```\n" } ]
Python
Apache License 2.0
google/jax
update neural network libraries text Co-authored-by: George Necula <necula@google.com>
260,285
02.11.2020 19:07:50
-3,600
d29b69a3f89f008fbafcd767cd84d90be1397df9
Support polynomial division for mask Add support for multivariate polynomial division on polymorphic sizes without remainder, allowing `mask` of `jnp.reshape` with -1 size and `lax.slice` for polymorphic stride for sizes `poly * stride`, i. e. `(n^2+2n)//n = n+2` Also clean up `Poly` class, improve error messages.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3681,9 +3681,9 @@ def _slice_shape_rule(operand, *, start_indices, limit_indices, strides):\nmsg = \"slice strides must be positive, got {}\"\nraise TypeError(msg.format(strides))\n- result_shape = np.floor_divide(\n- np.add(np.subtract(limit_indices, start_indices), strides) - 1, strides)\n- return tuple(result_shape)\n+ diff = np.subtract(limit_indices, start_indices)\n+ # Not np.divmod since Poly.__rdivmod__ is ignored by NumPy, breaks poly stride\n+ return tuple(q + (r > 0) for q, r in map(divmod, diff, strides))\ndef _slice_translation_rule(c, operand, *, start_indices, limit_indices,\nstrides):\n@@ -3732,6 +3732,7 @@ def _slice_batching_rule(batched_args, batch_dims, *, start_indices,\ndef _slice_masking_rule(\npadded_vals, logical_shapes, start_indices, limit_indices, strides):\noperand, = padded_vals\n+ strides = masking.padded_shape_as_value(strides) if strides else None\nreturn slice(operand,\nstart_indices=masking.padded_shape_as_value(start_indices),\nlimit_indices=masking.padded_shape_as_value(limit_indices),\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1231,9 +1231,8 @@ def _compute_newshape(a, newshape):\nreturn size if type(size) is Poly else core.concrete_or_error(\nint, size, \"The error arose in jax.numpy.reshape.\")\nnewshape = [check(size) for size in newshape] if iterable else check(newshape)\n- newsize = _prod((newshape,) if type(newshape) is Poly else newshape)\n- if newsize < 0:\n- fix = a.size // -newsize\n+ if np.any(np.equal(newshape, -1)):\n+ fix = -a.size // (newshape if type(newshape) is Poly else _prod(newshape))\nreturn [d if d != -1 else fix for d in newshape]\nelse:\nreturn newshape\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/masking.py", "new_path": "jax/interpreters/masking.py", "diff": "@@ -18,7 +18,7 @@ from functools import partial, reduce\nfrom itertools import chain, product\nimport operator as op\nimport string\n-from typing import Callable, Dict, Sequence, Union\n+from typing import Callable, Dict, Sequence, Union, Tuple\nimport numpy as np\n@@ -107,80 +107,91 @@ def eval_poly_shape(shape, values_dict):\ndef eval_poly(poly, values_dict):\nreturn poly.evaluate(values_dict) if type(poly) is Poly else poly\n-def _ensure_poly(p):\n- if type(p) is Poly:\n- return p\n+def _ensure_poly(p: 'Size') -> 'Poly':\n+ if isinstance(p, Poly): return p\nreturn Poly({Mon(): p})\ndef _polys_to_ints(shape):\nreturn tuple(int(d) if type(d) is Poly and d.is_constant else d\nfor d in shape)\n-def is_polymorphic(shape: Sequence[Union[int, 'Poly']]):\n+def is_polymorphic(shape: Sequence['Size']):\nreturn any(map(lambda d: type(d) is Poly, shape))\nclass Poly(dict):\n- \"\"\"Polynomial with nonnegative integer coefficients for polymorphic shapes.\"\"\"\n+ \"\"\"Polynomial with integer coefficients for polymorphic shapes.\"\"\"\n- def __init__(self, coeffs):\n+ def __init__(self, coeffs: Dict['Mon', int]):\n# Makes sure Polynomials are always in canonical form\ncoeffs = {mon: op.index(coeff)\nfor mon, coeff in coeffs.items() if coeff != 0}\ncoeffs = coeffs or {Mon(): 0}\nsuper().__init__(coeffs)\n- def __add__(self, other):\n+ def __add__(self, other: 'Size') -> 'Poly':\ncoeffs = self.copy()\nfor mon, coeff in _ensure_poly(other).items():\ncoeffs[mon] = coeffs.get(mon, 0) + coeff\nreturn Poly(coeffs)\n- def __sub__(self, other):\n+ def __sub__(self, other: 'Size') -> 'Poly':\nreturn self + -other\n- def __neg__(self):\n+ def __neg__(self) -> 'Poly':\nreturn Poly({mon: -coeff for mon, coeff in self.items()})\n- def __mul__(self, other):\n+ def __mul__(self, other: 'Size') -> 'Poly':\nother = _ensure_poly(other)\n- coeffs = {}\n+ coeffs: Dict[Mon, int] = {}\nfor (mon1, coeff1), (mon2, coeff2) in product(self.items(), other.items()):\nmon = mon1 * mon2\ncoeffs[mon] = coeffs.get(mon, 0) + coeff1 * coeff2\nreturn Poly(coeffs)\n- def __rmul__(self, other):\n+ def __rmul__(self, other: 'Size') -> 'Poly':\nreturn self * other # multiplication commutes\n- def __radd__(self, other):\n+ def __radd__(self, other: 'Size') -> 'Poly':\nreturn self + other # addition commutes\n- def __rsub__(self, other):\n+ def __rsub__(self, other: 'Size') -> 'Poly':\nreturn _ensure_poly(other) - self\n- def __floordiv__(self, divisor):\n- q, _ = divmod(self, divisor) # pytype: disable=wrong-arg-types\n+ def __floordiv__(self, divisor: 'Size') -> 'Poly':\n+ q, _ = divmod(self, divisor)\nreturn q\n- def __mod__(self, divisor):\n- _, r = divmod(self, divisor) # pytype: disable=wrong-arg-types\n+ def __mod__(self, divisor: 'Size') -> int:\n+ _, r = divmod(self, divisor)\nreturn r\n- def __divmod__(self, divisor):\n- if self.is_constant:\n- return divmod(int(self), divisor)\n- else:\n- def divided(count):\n- q, r = divmod(count, divisor)\n- if r != 0:\n- raise ValueError('shapecheck and masking currently only support '\n- 'strides that exactly divide the strided axis '\n- 'length.')\n- return q\n-\n- return Poly(\n- {k: coeff // divisor if k.degree == 0 else divided(coeff)\n- for k, coeff in self.items()}), self.get(Mon(), 0) % divisor\n+ def __divmod__(self, divisor: 'Size') -> Tuple['Poly', int]:\n+ \"\"\"\n+ Floor division with remainder (divmod) generalized to polynomials. To allow\n+ ensuring '0 <= remainder < divisor' for consistency with integer divmod, the\n+ divisor must divide the dividend (up to a constant for constant divisors).\n+ :return: Quotient resulting from polynomial division and integer remainder.\n+ \"\"\"\n+ divisor = _ensure_poly(divisor)\n+ dmon, dcount = divisor._leading_term\n+ dividend, quotient, remainder = self, _ensure_poly(0), _ensure_poly(0)\n+ while dividend != 0: # invariant: dividend == divisor*quotient + remainder\n+ mon, count = dividend._leading_term\n+ qcount, rcount = divmod(count, dcount)\n+ try:\n+ qmon = mon // dmon\n+ except ValueError:\n+ raise ValueError(f\"Stride {divisor} must divide size {self} \"\n+ f\"(up to a constant for constant divisors).\")\n+ r = Poly({mon: rcount})\n+ q = Poly({qmon: qcount})\n+ quotient += q\n+ remainder += r\n+ dividend -= q * divisor + r\n+ return quotient, int(remainder)\n+\n+ def __rdivmod__(self, dividend: 'Size') -> Tuple['Poly', int]:\n+ return divmod(_ensure_poly(dividend), self)\ndef __hash__(self):\nreturn hash(tuple(sorted(self.items())))\n@@ -191,39 +202,28 @@ class Poly(dict):\ndef __ne__(self, other):\nreturn not self == other\n- def __ge__(self, other):\n- other = _ensure_poly(other)\n-\n- if other.is_constant and self.is_constant:\n- return int(self) >= int(other)\n- elif other.is_constant and int(other) <= 1:\n- # Assume nonzero polynomials are positive, allows use in shape rules\n- return True\n- elif self.is_constant and int(self) <= 0:\n- return False # See above.\n- elif self == other:\n- return True\n- else:\n+ def __ge__(self, other: 'Size'):\ndiff = self - other\n- if diff.is_constant:\n- return int(diff) >= 0\n+ if diff.is_constant: return int(diff) >= 0\n+\n+ # Assume nonconstant polynomials are positive, allows use in shape rules:\n+ if _ensure_poly(other).is_constant and other <= 1: return True\n+ elif self.is_constant and self <= 0: return False\n- raise ValueError('Polynomials comparison \"{} >= {}\" is inconclusive.'\n- .format(self, other))\n+ raise ValueError(f\"Polynomial comparison {self} >= {other} is inconclusive.\")\n- def __le__(self, other):\n+ def __le__(self, other: 'Size'):\nreturn _ensure_poly(other) >= self\n- def __lt__(self, other):\n+ def __lt__(self, other: 'Size'):\nreturn not (self >= other)\n- def __gt__(self, other):\n+ def __gt__(self, other: 'Size'):\nreturn not (_ensure_poly(other) >= self)\ndef __str__(self):\n- return ' + '.join('{} {}'.format(v, k)\n- if (v != 1 or k.degree == 0) else str(k)\n- for k, v in sorted(self.items())).strip()\n+ return ' + '.join(f'{c} {mon}' if c != 1 or mon.degree == 0 else str(mon)\n+ for mon, c in sorted(self.items(), reverse=True)).strip()\ndef __repr__(self):\nreturn str(self)\n@@ -242,6 +242,13 @@ class Poly(dict):\ndef is_constant(self):\nreturn len(self) == 1 and next(iter(self)).degree == 0\n+ @property\n+ def _leading_term(self) -> Tuple['Mon', int]:\n+ \"\"\"Returns the highest degree term that comes first lexicographically.\"\"\"\n+ return max(self.items())\n+\n+Size = Union[int, Poly]\n+\ndef pow(x, deg):\ntry:\ndeg = int(deg)\n@@ -261,28 +268,46 @@ def mul(coeff, mon):\nabstract_arrays._DIMENSION_TYPES.add(Poly)\n-\nclass Mon(dict):\n+ \"\"\"Represents a multivariate monomial, such as n^3 * m.\"\"\"\ndef __hash__(self):\nreturn hash(frozenset(self.items()))\ndef __str__(self):\n- return ' '.join('{}**{}'.format(k, v) if v != 1 else str(k)\n- for k, v in sorted(self.items()))\n+ return ' '.join(f'{key}^{exponent}' if exponent != 1 else str(key)\n+ for key, exponent in sorted(self.items()))\n- def __lt__(self, other):\n- # sort by total degree, then lexicographically on indets\n+ def __lt__(self, other: 'Mon'):\n+ \"\"\"\n+ Comparison to another monomial in graded reverse lexicographic order.\n+ \"\"\"\nself_key = -self.degree, tuple(sorted(self))\nother_key = -other.degree, tuple(sorted(other))\n- return self_key < other_key\n+ return self_key > other_key\n- def __mul__(self, other):\n+ def __mul__(self, other: 'Mon') -> 'Mon':\n+ \"\"\"\n+ Returns the product with another monomial. Example: (n^2*m) * n == n^3 * m.\n+ \"\"\"\nreturn Mon(Counter(self) + Counter(other))\n@property\ndef degree(self):\nreturn sum(self.values())\n+ def __floordiv__(self, divisor: 'Mon') -> 'Mon':\n+ \"\"\"\n+ Divides by another monomial. Raises a ValueError if impossible.\n+ For example, (n^3 * m) // n == n^2*m, but n // m fails.\n+ \"\"\"\n+ d = Counter(self)\n+ for key, exponent in divisor.items():\n+ diff = self.get(key, 0) - exponent\n+ if diff < 0: raise ValueError(f\"Cannot divide {self} by {divisor}.\")\n+ elif diff == 0: del d[key]\n+ elif diff > 0: d[key] = diff\n+ return Mon(d)\n+\nclass ShapeError(Exception): pass\nclass ShapeSyntaxError(Exception): pass\n" }, { "change_type": "MODIFY", "old_path": "tests/masking_test.py", "new_path": "tests/masking_test.py", "diff": "@@ -64,7 +64,7 @@ class PolyTest(jtu.JaxTestCase):\n['m + n', 'ShapeSpec(m + n)'],\n['m + n * k', 'ShapeSpec(k n + m)'],\n['m + 3 * k', 'ShapeSpec(3 k + m)'],\n- ['-3 + k + k * k', 'ShapeSpec(k**2 + k + -3)'],\n+ ['-3 + k + k * k', 'ShapeSpec(k^2 + k + -3)'],\n['', 'ShapeSpec()'],\n['_', 'ShapeSpec(_)'],\n])\n@@ -95,6 +95,14 @@ class PolyTest(jtu.JaxTestCase):\nassert not len(set(hash(Mon({'a': i})) for i in range(10))) == 1\nassert hash(Mon({'a': 1, 'b': 1})) == hash(Mon({'b': 1, 'a': 1}))\n+ @parameterized.parameters([\n+ (Mon({'a': 1}), Mon({'b': 1})),\n+ (Mon({'a': 2, 'b': 1}), Mon({'b': 1})),\n+ ])\n+ def test_Mon_floordiv(self, divisor, quotient):\n+ dividend = quotient * divisor\n+ self.assertEqual(quotient, dividend // divisor)\n+\ndef test_Poly_compare(self):\npoly = Poly({Mon(): 3, Mon({'n': 1}): 4})\n# Assume poly > 0 to make various shape rules work with polymorphic shapes:\n@@ -113,11 +121,33 @@ class PolyTest(jtu.JaxTestCase):\nself.assertRaisesRegex(ValueError, \"\", lambda: poly >= 2)\nself.assertRaisesRegex(ValueError, \"\", lambda: poly > 1)\n- def test_Poly_divmod(self):\nn = Poly({Mon({'n': 1}): 1})\n- assert (n, 1) == divmod(2*n+1, 2)\n- assert (2*n, 0) == divmod(10*n, 5)\n- assert (2*n+4, 3) == divmod(10*n+23, 5)\n+ m = Poly({Mon({'m': 1}): 1})\n+\n+ must_divide_msg = \" must divide size\"\n+\n+ @parameterized.parameters([\n+ (1, constant_poly(0), 0),\n+ (n, 0, 0),\n+ (2, n, 1),\n+ (5, 2 * n, 0),\n+ (5, 2 * n + 4, 3),\n+ (n * n, n + 1, 0),\n+ (2 * n + 1, 2 * n + 1, n + 2, must_divide_msg),\n+ (n * m + 1, m + n + 1, n - 1, must_divide_msg),\n+ (n, n, 0),\n+ (n, n, 1, must_divide_msg),\n+ (n + 1, -n + 1, -1, must_divide_msg),\n+ ])\n+ def test_Poly_divmod(self, divisor, quotient, remainder, error_message=None):\n+ dividend = quotient * divisor + remainder\n+ expected = (quotient, remainder)\n+ if dividend.is_constant: dividend = int(dividend)\n+ if error_message:\n+ with self.assertRaisesRegex(ValueError, error_message):\n+ divmod(dividend, divisor)\n+ else:\n+ self.assertEqual(expected, divmod(dividend, divisor))\ndef test_Poly_rsub(self):\nn = Poly({Mon({'n': 1}): 1})\n@@ -594,7 +624,11 @@ class MaskingTest(jtu.JaxTestCase):\ndef test_lax_slice(self):\nself.check(lambda x: lax.slice(x, (1,), (x.shape[0],)), ['n'], 'n+-1',\n{'n': 2}, [(3,)], ['float_'], jtu.rand_default(self.rng()))\n- # TODO: self.check(lambda x: lax.slice(x, (x.shape[0] // 2,), (x.shape[0],)), ['2*n'], dict(n=jnp.array([2, 3])), 'n')\n+ # TODO self.check(lambda x: lax.slice(x, (x.shape[0] // 2,), (x.shape[0],)),\n+ # ['2*n'], 'n', {'n': 2}, [(6,)], ['float_'], jtu.rand_default(self.rng()))\n+ self.check(lambda x: lax.slice(x, (0,), (x.shape[0],), (x.shape[0],)),\n+ ['n'], '1', {'n': 2}, [(5,)], ['float_'],\n+ jtu.rand_default(self.rng()))\ndef test_reshape(self):\nself.check(lambda x: jnp.reshape(x, (x.shape[1], 2, 4, 1)),\n@@ -633,8 +667,6 @@ class MaskingTest(jtu.JaxTestCase):\n['2, n'], '2 * n', dict(n=2), [(2, 3)],\n['float_'], jtu.rand_default(self.rng()))\n- if False:\n- # TODO fix lax._compute_newshape on polymorphic shapes:\nself.check(lambda x: jnp.reshape(x, (x.shape[0], -1)),\n['n, 3, 1, 2'], 'n, 6', dict(n=1), [(2, 3, 1, 2)],\n['float_'], jtu.rand_default(self.rng()))\n" } ]
Python
Apache License 2.0
google/jax
Support polynomial division for mask Add support for multivariate polynomial division on polymorphic sizes without remainder, allowing `mask` of - `jnp.reshape` with -1 size and - `lax.slice` for polymorphic stride for sizes `poly * stride`, i. e. `(n^2+2n)//n = n+2` Also clean up `Poly` class, improve error messages.
260,411
03.11.2020 09:31:10
-7,200
4ee7a296c3dafe74578a779950e62086b0b52b63
[jax2tf] Expanded the SavedModel library to allow the compilation of models. This is important for use with TensorFlow serving. Also removed the servo_main.py (only applies to OSS TF Serving, which does not yet support XLA)
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/README.md", "new_path": "jax/experimental/jax2tf/examples/README.md", "diff": "+Getting started with jax2tf\n+===========================\nThis directory contains a number of examples of using the jax2tf converter to:\n* save SavedModel from trained MNIST models, using both pure JAX and Flax.\n- * load the SavedModel into the TensorFlow model server and use it for\n- inference. We show also how to use a batch-polymorphic saved model.\n* reuse the feature-extractor part of the trained MNIST model in\nTensorFlow Hub, and in a larger TensorFlow Keras model.\n-Preparing the model for jax2tf\n-==============================\n+It is also possible to use jax2tf-generated SavedModel with TensorFlow serving.\n+At the moment, the open-source TensorFlow model server is missing XLA support,\n+but the Google version can be used, as described in README_serving.md.\n+\n+# Preparing the model for jax2tf\n+\nThe most important detail for using jax2tf with SavedModel is to express\nthe trained model as a pair:\n@@ -16,7 +20,9 @@ the trained model as a pair:\n* `func`: a two-argument function with signature:\n`(params: Parameters, inputs: Inputs) -> Outputs`.\nBoth arguments must be a `numpy.ndarray` or\n- nested tuple/list/dictionaries thereof.\n+ nested tuple/list/dictionaries thereof. In particular, it is important\n+ for models that take multiple inputs to be adapted to take their inputs\n+ as a single tuple/list/dictionary of `numpy.ndarray`.\n* `params`: of type `Parameters`, the model parameters, to be used as the\nfirst input for `func`.\n@@ -25,8 +31,7 @@ implementations of MNIST, one using pure JAX (`PureJaxMNIST`) and a CNN\none using Flax (`FlaxMNIST`). Other Flax models can be arranged similarly,\nand the same strategy should work for other neural-network libraries for JAX.\n-Generating TensorFlow SavedModel\n-=====================\n+# Generating TensorFlow SavedModel\nOnce you have the model in this form, you can use the\n`saved_model_lib.save_model` function [saved_model_lib.py](saved_model_lib.py)\n@@ -36,19 +41,24 @@ into functions that behave as if they had been written with TensorFlow.\nTherefore, if you are familiar with how to generate SavedModel, you can most\nlikely just use your own code for this.\n-The file `saved_model_main.py` is an executable that shows who to perform the following\n-sequence of steps:\n+The file `saved_model_main.py` is an executable that shows how to perform the\n+following sequence of steps:\n- * train an MNIST model, and obtain a pair of an inference function and the parameters.\n+ * train an MNIST model, and obtain a pair of an inference function and the\n+ parameters.\n* convert the inference function with jax2tf, for one of more batch sizes.\n* save a SavedModel and dump its contents.\n* reload the SavedModel and run it with TensorFlow to test that the inference\nfunction produces the same results as the JAX inference function.\n* optionally plot images with the training digits and the inference results.\n+\n+\nThere are a number of flags to select the Flax model (`--model=mnist_flag`),\nto skip the training and just test a previously loaded\nSavedModel (`--nogenerate_model`), to choose the saving path, etc.\n+The default saving location is `/tmp/jax2tf/saved_models/1`.\n+\nBy default, this example will convert the inference function for three separate\nbatch sizes: 1, 16, 128. You can see this in the dumped SavedModel. If you\n@@ -58,42 +68,8 @@ be done using jax2tf's\nAs a result, the inference function will be traced only once and the SavedModel\nwill contain a single batch-polymorphic TensorFlow graph.\n-Using the TensorFlow model server\n-=================================\n-\n-The executable `servo_main.py` extends the `saved_model_main.py` with code to\n-show how to use the SavedModel with TensorFlow model server. All the flags\n-of `saved_model_main.py` also apply to `servo_main.py`. In particular, you\n-can select the Flax MNIST model: `--model=mnist_flax`,\n-batch-polymorphic conversion to TensorFlow `--serving_batch_size=-1`,\n-skip the training, reuse a previously trained model: `--nogenerate_model`.\n-\n-If you want to start your own model server, you should pass the\n-`--nostart_model_server` flag and also `--serving_url` to point to the\n-HTTP REST API end point of your model server. You can see the path of the\n-trained and saved model in the output.\n-\n-Open-source model server\n-------------------------\n-\n-We have tried this example with the OSS model server, using a\n-[TensorFlow Serving with Docker](https://www.tensorflow.org/tfx/serving/docker).\n-Specifically, you need to install Docker and run\n-\n-```\n-docker pull tensorflow/serving\n-```\n-\n-The actual starting of the model server is done by the `servo_main.py` script.\n-The script also does a sanity check that the model server is serving a model\n-with the right batch size and image shapes, and makes a few requests to the\n-server to perform inference.\n-\n-Instructions for using the Google internal version of the model server: TBA.\n-\n-Reusing models with TensorFlow Hub and TensorFlow Keras\n-=======================================================\n+# Reusing models with TensorFlow Hub and TensorFlow Keras\nThe SavedModel produced by the example in `saved_model_main.py` already\nimplements the [reusable saved models interface](https://www.tensorflow.org/hub/reusable_saved_models).\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "diff": "@@ -31,40 +31,64 @@ def save_model(jax_fn: Callable,\n*,\ninput_signatures: Sequence[tf.TensorSpec],\nshape_polymorphic_input_spec: Optional[str] = None,\n- with_gradient: bool = False):\n+ with_gradient: bool = False,\n+ compile_model: bool = True):\n\"\"\"Saves the SavedModel for a function.\nIn order to use this wrapper you must first convert your model to a function\nwith two arguments: the parameters and the input on which you want to do\n- inference. Both arguments may be tuples/lists/dictionaries of np.ndarray.\n+ inference. Both arguments may be np.ndarray or\n+ (nested) tuples/lists/dictionaries thereof.\n+\n+ If you want to save the model for a function with multiple parameters and\n+ multiple inputs, you have to collect the parameters and the inputs into\n+ one argument, e.g., adding a tuple or dictionary at top-level.\n+\n+ ```\n+ def jax_fn_multi(param1, param2, input1, input2):\n+ # JAX model with multiple parameters and multiple inputs. They all can\n+ # be (nested) tuple/list/dictionaries of np.ndarray.\n+ ...\n+\n+ def jax_fn_for_save_model(params, inputs):\n+ # JAX model with parameters and inputs collected in a tuple each. We can\n+ # use dictionaries also (in which case the keys would appear as the names\n+ # of the inputs)\n+ param1, param2 = params\n+ input1, input2 = inputs\n+ return jax_fn_multi(param1, param2, input1, input2)\n+ save_model(jax_fn_for_save_model, (param1, param2), ...)\n+ ```\nSee examples in mnist_lib.py and saved_model.py.\nArgs:\njax_fn: a JAX function taking two arguments, the parameters and the inputs.\n- Both arguments may be tuples/lists/dictionaries of np.ndarray.\n+ Both arguments may be (nested) tuples/lists/dictionaries of np.ndarray.\nparams: the parameters, to be used as first argument for `jax_fn`. These\n- must be tuples/lists/dictionaries of np.ndarray, and will be saved as the\n- variables of the SavedModel.\n+ must be (nested) tuples/lists/dictionaries of np.ndarray, and will be\n+ saved as the variables of the SavedModel.\nmodel_dir: the directory where the model should be saved.\ninput_signatures: the input signatures for the second argument of `jax_fn`\n(the input). A signature must be a `tensorflow.TensorSpec` instance, or a\n- tuple/list/dictionary thereof with a structure matching the second\n- argument of `jax_fn`. The first input_signature will be saved as the\n- default serving signature. The additional signatures will be used only to\n- ensure that the `jax_fn` is traced and converted to TF for the\n+ (nested) tuple/list/dictionary thereof with a structure matching the\n+ second argument of `jax_fn`. The first input_signature will be saved as\n+ the default serving signature. The additional signatures will be used\n+ only to ensure that the `jax_fn` is traced and converted to TF for the\ncorresponding input shapes.\nshape_polymorphic_input_spec: if given then it will be used as the\n`in_shapes` argument to jax2tf.convert for the second parameter of\n`jax_fn`. In this case, a single `input_signatures` is supported, and\nshould have `None` in the polymorphic dimensions. Should be a string, or a\n- tuple/list/dictionary thereof with a structure matching the second\n- argument of `jax_fn`.\n+ (nesteD) tuple/list/dictionary thereof with a structure matching the\n+ second argument of `jax_fn`.\nwith_gradient: whether the SavedModel should support gradients. If True,\nthen a custom gradient is saved. If False, then a\ntf.raw_ops.PreventGradient is saved to error if a gradient is attempted.\n(At the moment due to a bug in SavedModel, custom gradients are not\nsupported.)\n+ compile_model: use TensorFlow experimental_compiler on the SavedModel. This\n+ is needed if the SavedModel will be used for TensorFlow serving.\n\"\"\"\nif not input_signatures:\nraise ValueError(\"At least one input_signature must be given\")\n@@ -77,49 +101,46 @@ def save_model(jax_fn: Callable,\nwith_gradient=with_gradient,\nin_shapes=[None, shape_polymorphic_input_spec])\n- wrapper = _ExportWrapper(tf_fn, params, params_trainable=with_gradient)\n+ # Create tf.Variables for the parameters.\n+ param_vars = tf.nest.map_structure(\n+ # If with_gradient=False, we mark the variables behind as non-trainable,\n+ # to ensure that users of the SavedModel will not try to fine tune them.\n+ lambda param: tf.Variable(param, trainable=with_gradient),\n+ params)\n+ tf_graph = tf.function(lambda inputs: tf_fn(param_vars, inputs),\n+ autograph=False,\n+ experimental_compile=compile_model)\n+\nsignatures = {}\nsignatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \\\n- wrapper.__call__.get_concrete_function(input_signatures[0])\n+ tf_graph.get_concrete_function(input_signatures[0])\nfor input_signature in input_signatures[1:]:\n# If there are more signatures, trace and cache a TF function for each one\n- wrapper.__call__.get_concrete_function(input_signature)\n+ tf_graph.get_concrete_function(input_signature)\n+ wrapper = _ReusableSavedModelWrapper(tf_graph, param_vars)\ntf.saved_model.save(wrapper, model_dir, signatures=signatures)\n-class _ExportWrapper(tf.train.Checkpoint):\n+class _ReusableSavedModelWrapper(tf.train.Checkpoint):\n\"\"\"Wraps a function and its parameters for saving to a SavedModel.\nImplements the interface described at\nhttps://www.tensorflow.org/hub/reusable_saved_models.\n\"\"\"\n- def __init__(self, tf_fn: Callable, params, params_trainable: bool):\n+ def __init__(self, tf_graph, param_vars):\n\"\"\"Args:\n- tf_fn: a TF function taking two arguments, the parameters and the inputs.\n- Both arguments may be tuples/lists/dictionaries of np.ndarray of tensors.\n- params: the parameters, to be used as first argument for `tf_fn`. These\n- must be tuples/lists/dictionaries of np.ndarray, and will be saved as the\n- variables of the SavedModel.\n+ tf_fn: a tf.function taking one argument (the inputs), which can be\n+ be tuples/lists/dictionaries of np.ndarray or tensors.\n+ params: the parameters, as tuples/lists/dictionaries of tf.Variable,\n+ and will be saved as the variables of the SavedModel.\n\"\"\"\nsuper().__init__()\n- self._fn = tf_fn\n- # Create tf.Variables for the parameters.\n- self._params = tf.nest.map_structure(\n- # If with_gradient=False, we mark the variables behind as non-trainable,\n- # to ensure that users of the SavedModel will not try to fine tune them.\n- lambda param: tf.Variable(param, trainable=params_trainable),\n- params)\n-\n# Implement the interface from https://www.tensorflow.org/hub/reusable_saved_models\n- self.variables = tf.nest.flatten(self._params)\n+ self.variables = tf.nest.flatten(param_vars)\nself.trainable_variables = [v for v in self.variables if v.trainable]\n# If you intend to prescribe regularization terms for users of the model,\n# add them as @tf.functions with no inputs to this list. Else drop this.\nself.regularization_losses = []\n-\n- @tf.function(autograph=False)\n- def __call__(self, inputs):\n- outputs = self._fn(self._params, inputs)\n- return outputs\n+ self.__call__ = tf_graph\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "diff": "@@ -55,6 +55,10 @@ flags.DEFINE_integer(\"num_epochs\", 3, \"For how many epochs to train.\")\nflags.DEFINE_boolean(\n\"generate_model\", True,\n\"Train and save a new model. Otherwise, use an existing SavedModel.\")\n+flags.DEFINE_boolean(\n+ \"compile_model\", True,\n+ \"Enable TensorFlow experimental_compiler for the SavedModel. This is \"\n+ \"necessary if you want to use the model for TensorFlow serving.\")\nflags.DEFINE_boolean(\"show_model\", True, \"Show details of saved SavedModel.\")\nflags.DEFINE_boolean(\n\"show_images\", False,\n@@ -111,7 +115,8 @@ def train_and_save():\npredict_params,\nmodel_dir,\ninput_signatures=input_signatures,\n- shape_polymorphic_input_spec=shape_polymorphic_input_spec)\n+ shape_polymorphic_input_spec=shape_polymorphic_input_spec,\n+ compile_model=FLAGS.compile_model)\nif FLAGS.test_savedmodel:\ntf_accelerator, tolerances = tf_accelerator_and_tolerances()\n@@ -134,9 +139,7 @@ def train_and_save():\npure_restored_model(tf.convert_to_tensor(test_input)),\npredict_fn(predict_params, test_input), **tolerances)\n- assert os.path.isdir(model_dir)\nif FLAGS.show_model:\n-\ndef print_model(model_dir: str):\ncmd = f\"saved_model_cli show --all --dir {model_dir}\"\nprint(cmd)\n@@ -165,14 +168,9 @@ def model_description() -> str:\ndef savedmodel_dir(with_version: bool = True) -> str:\n\"\"\"The directory where we save the SavedModel.\"\"\"\n- if FLAGS.model == \"mnist_pure_jax\":\n- model_class = mnist_lib.PureJaxMNIST\n- elif FLAGS.model == \"mnist_flax\":\n- model_class = mnist_lib.FlaxMNIST\n-\nmodel_dir = os.path.join(\nFLAGS.model_path,\n- f\"{model_class.name}{'' if FLAGS.model_classifier_layer else '_features'}\"\n+ f\"{'mnist' if FLAGS.model_classifier_layer else 'mnist_features'}\"\n)\nif with_version:\nmodel_dir = os.path.join(model_dir, str(FLAGS.model_version))\n" }, { "change_type": "DELETE", "old_path": "jax/experimental/jax2tf/examples/servo_main.py", "new_path": null, "diff": "-# Copyright 2020 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-\"\"\"Demonstrates use of a jax2tf model in TensorFlow model server.\n-\n-Includes the flags from saved_model_main.py.\n-\n-If you want to start your own model server, you should pass the\n-`--nostart_model_server` flag and also `--serving_url` to point to the\n-HTTP REST API end point of your model server. You can see the path of the\n-trained and saved model in the output.\n-\n-See README.md.\n-\"\"\"\n-import atexit\n-import logging\n-import subprocess\n-import threading\n-import time\n-from absl import app\n-from absl import flags\n-\n-from jax.experimental.jax2tf.examples import mnist_lib\n-from jax.experimental.jax2tf.examples import saved_model_main\n-\n-import numpy as np\n-import requests\n-\n-import tensorflow as tf # type: ignore\n-import tensorflow_datasets as tfds # type: ignore\n-\n-\n-flags.DEFINE_integer(\"count_images\", 10, \"How many images to test\")\n-flags.DEFINE_bool(\"start_model_server\", True,\n- \"Whether to start/stop the model server.\")\n-flags.DEFINE_string(\"serving_url\", \"http://localhost:8501/v1/models/jax_model\",\n- \"The HTTP endpoint for the model server\")\n-\n-FLAGS = flags.FLAGS\n-\n-\n-def mnist_predict_request(serving_url: str, images):\n- \"\"\"Predicts using the model server.\n-\n- Args:\n- serving_url: The URL for the model server.\n- images: A batch of images of shape F32[B, 28, 28, 1]\n-\n- Returns:\n- a batch of one-hot predictions, of shape F32[B, 10]\n- \"\"\"\n- request = {\"inputs\": images.tolist()}\n- response = requests.post(f\"{serving_url}:predict\", json=request)\n- response_json = response.json()\n- if response.status_code != 200:\n- raise RuntimeError(\"Model server error: \" + response_json[\"error\"])\n-\n- predictions = np.array(response_json[\"outputs\"])\n- return predictions\n-\n-\n-def main(_):\n- if FLAGS.count_images % FLAGS.serving_batch_size != 0:\n- raise ValueError(\"count_images must be a multiple of serving_batch_size\")\n-\n- saved_model_main.train_and_save()\n- # Strip the version number from the model directory\n- servo_model_dir = saved_model_main.savedmodel_dir(with_version=False)\n-\n- if FLAGS.start_model_server:\n- model_server_proc = _start_localhost_model_server(servo_model_dir)\n-\n- try:\n- _mnist_sanity_check(FLAGS.serving_url, FLAGS.serving_batch_size)\n- test_ds = mnist_lib.load_mnist(\n- tfds.Split.TEST, batch_size=FLAGS.serving_batch_size)\n- images_and_labels = tfds.as_numpy(\n- test_ds.take(FLAGS.count_images // FLAGS.serving_batch_size))\n-\n- for (images, labels) in images_and_labels:\n- predictions_one_hot = mnist_predict_request(FLAGS.serving_url, images)\n- predictions_digit = np.argmax(predictions_one_hot, axis=1)\n- label_digit = np.argmax(labels, axis=1)\n- logging.info(\n- f\" predicted = {predictions_digit} labelled digit {label_digit}\")\n- finally:\n- if FLAGS.start_model_server:\n- model_server_proc.kill()\n- model_server_proc.communicate()\n-\n-\n-def _mnist_sanity_check(serving_url: str, serving_batch_size: int):\n- \"\"\"Checks that we can reach a model server with a model that matches MNIST.\"\"\"\n- logging.info(\"Checking that model server serves a compatible model.\")\n- response = requests.get(f\"{serving_url}/metadata\")\n- response_json = response.json()\n- if response.status_code != 200:\n- raise IOError(\"Model server error: \" + response_json[\"error\"])\n-\n- try:\n- signature_def = response_json[\"metadata\"][\"signature_def\"][\"signature_def\"]\n- serving_default = signature_def[\n- tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\n- assert serving_default[\"method_name\"] == \"tensorflow/serving/predict\"\n- inputs, = serving_default[\"inputs\"].values()\n- b, w, h, c = [int(d[\"size\"]) for d in inputs[\"tensor_shape\"][\"dim\"]]\n- assert b == -1 or b == serving_batch_size, (\n- f\"Found input batch size {b}. Expecting {serving_batch_size}\")\n- assert (w, h, c) == mnist_lib.input_shape\n- except Exception as e:\n- raise IOError(\n- f\"Unexpected response from model server: {response_json}\") from e\n-\n-\n-def _start_localhost_model_server(model_dir):\n- \"\"\"Starts the model server on localhost, using docker.\n-\n- Ignore this if you have a different way to start the model server.\n- \"\"\"\n- cmd = (\"docker run -p 8501:8501 --mount \"\n- f\"type=bind,source={model_dir}/,target=/models/jax_model \"\n- \"-e MODEL_NAME=jax_model -t --rm --name=serving tensorflow/serving\")\n- cmd_args = cmd.split(\" \")\n- logging.info(\"Starting model server\")\n- logging.info(f\"Running {cmd}\")\n- proc = subprocess.Popen(\n- cmd_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n- model_server_ready = False\n-\n- def model_server_output_reader():\n- for line in iter(proc.stdout.readline, b\"\"):\n- line_str = line.decode(\"utf-8\").strip()\n- if \"Exporting HTTP/REST API at:localhost:8501\" in line_str:\n- nonlocal model_server_ready\n- model_server_ready = True\n- logging.info(f\"Model server: {line_str}\")\n-\n- output_thread = threading.Thread(target=model_server_output_reader, args=())\n- output_thread.start()\n-\n- def _stop_model_server():\n- logging.info(\"Stopping the model server\")\n- subprocess.run(\"docker container stop serving\".split(\" \"),\n- check=True)\n-\n- atexit.register(_stop_model_server)\n-\n- wait_iteration_sec = 2\n- wait_remaining_sec = 10\n- while not model_server_ready and wait_remaining_sec > 0:\n- logging.info(\"Waiting for the model server to be ready...\")\n- time.sleep(wait_iteration_sec)\n- wait_remaining_sec -= wait_iteration_sec\n-\n- if wait_remaining_sec <= 0:\n- raise IOError(\"Model server failed to start properly\")\n- return proc\n-\n-\n-if __name__ == \"__main__\":\n- app.run(main)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Expanded the SavedModel library to allow the compilation of models. This is important for use with TensorFlow serving. Also removed the servo_main.py (only applies to OSS TF Serving, which does not yet support XLA) Co-authored-by: Benjamin Chetioui <3920784+bchetioui@users.noreply.github.com>
260,287
03.11.2020 12:11:03
0
b85e605ff1a9c5e6fed3d3dea6dd0c94074a66c1
Add support for collectives in xmap
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -128,6 +128,9 @@ class ClosedJaxpr:\ndef literals(self):\nreturn self.consts # backwards compatible alias\n+ def map_jaxpr(self, f):\n+ return ClosedJaxpr(f(self.jaxpr), self.consts)\n+\ndef __str__(self): return str(self.jaxpr)\ndef __repr__(self): return repr(self.jaxpr)\n@@ -1259,7 +1262,7 @@ def axis_frame(axis_name):\n]\nraise NameError(\nf'unbound axis name: {axis_name}. The following axis names (e.g. defined '\n- 'by pmap) are available to collectives operations:'\n+ 'by pmap) are available to collective operations:'\nf'{named_axis}')\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/general_map.py", "new_path": "jax/experimental/general_map.py", "diff": "@@ -16,9 +16,9 @@ import enum\nimport threading\nimport contextlib\nfrom collections import namedtuple\n-from typing import Callable, Iterable, List, Tuple, Optional, Dict\n+from typing import Callable, Iterable, List, Tuple, Optional, Dict, Any\nfrom warnings import warn\n-from functools import wraps\n+from functools import wraps, partial\nimport jax\nfrom .. import numpy as jnp\n@@ -46,13 +46,6 @@ class ResourceEnv(threading.local):\nself.axes : Dict[ResourceAxisName, int] = {}\nthread_resource_env = ResourceEnv()\n-# This is really a Dict[AxisName, int], but we don't define a\n-# pytree instance for it, so that it is treated as a leaf.\n-class AxisNamePos(dict):\n- pass\n-\n-A = AxisNamePos\n-\n@contextlib.contextmanager\ndef resources(**axes):\nold_axes = thread_resource_env.axes\n@@ -62,6 +55,13 @@ def resources(**axes):\nfinally:\nthread_resource_env.axes = old_axes\n+# This is really a Dict[AxisName, int], but we don't define a\n+# pytree instance for it, so that it is treated as a leaf.\n+class AxisNamePos(dict):\n+ pass\n+\n+A = AxisNamePos\n+\n# TODO: Some syntactic sugar to make the API more usable in a single-axis case?\n# TODO: Are the resource axes scoped lexically or dynamically? Dynamically for now!\ndef xmap(fun: Callable,\n@@ -72,11 +72,8 @@ def xmap(fun: Callable,\n_check_callable(fun)\ndef fun_mapped(*args, **kwargs):\n- f = lu.wrap_init(fun)\nargs_flat, in_tree = tree_flatten((args, kwargs))\nfor arg in args_flat: _check_arg(arg)\n- f, out_tree = flatten_fun(f, in_tree)\n- # TODO: We've skipped axis_size analysis and schedule parsing\n# TODO: Check that:\n# - every scheduled axis name appears in at least one input\n# - every used resource axis name appears in the resource env\n@@ -109,27 +106,77 @@ def xmap(fun: Callable,\nresource_map['vectorize'] = (len(resource_map), None)\nmap_sequence = sorted(resource_to_axis.items(),\nkey=lambda item: resource_map[item[0]][0])\n+ axis_subst = {}\n+ for axis, resource in schedule:\n+ if axis not in axis_subst:\n+ axis_subst[axis] = []\n+ if resource == 'vectorize':\n+ resource = f'v_{axis}'\n+ else:\n+ resource = f'r_{resource}'\n+ axis_subst[axis].append(resource)\n+ axis_subst = {axis: tuple(resources) for axis, resources in axis_subst.items()}\n+\n+ axis_sizes = _get_axis_sizes(args_flat, in_axes_flat)\n+ jaxpr, out_tree = _trace_mapped_jaxpr(fun, args_flat, in_axes_flat, axis_sizes, in_tree)\n+ jaxpr = jaxpr.map_jaxpr(partial(subst_axis_names, axis_subst=axis_subst))\n+ f = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\nf = hide_mapped_axes(f, in_axes_flat, out_axes_flat)\nfor resource, resource_axes in map_sequence[::-1]:\n- # TODO: Support collectives\n# TODO: Support sequential\n# XXX: Even though multiple axes might be mapped to the 'vectorized'\n# resource, we cannot vectorize them jointly, because they\n# might require different axis sizes.\nif resource == 'vectorize':\n- maps = [[name] for name in resource_axes]\n+ maps = [(f'v_{name}', [name]) for i, name in enumerate(resource_axes)]\nelse:\n- maps = [resource_axes]\n- for axes in maps:\n+ maps = [(f'r_{resource}', resource_axes)]\n+ for raxis_name, axes in maps:\nmap_in_axes = map(lambda spec: lookup_exactly_one_of(spec, axes), in_axes_flat)\nmap_out_axes = map(lambda spec: lookup_exactly_one_of(spec, axes), out_axes_flat)\nmap_size = resource_map[resource][1]\n- f = vtile(f, map_in_axes, map_out_axes, tile_size=map_size)\n+ f = vtile(f, map_in_axes, map_out_axes, tile_size=map_size, axis_name=raxis_name)\nflat_out = f.call_wrapped(*args_flat)\n- return tree_unflatten(out_tree(), flat_out)\n+ return tree_unflatten(out_tree, flat_out)\nreturn fun_mapped\n+def _delete_aval_axes(aval, axes: AxisNamePos):\n+ assert isinstance(aval, core.ShapedArray)\n+ shape = list(aval.shape)\n+ for i in sorted(axes.values(), reverse=True):\n+ del shape[i]\n+ return core.ShapedArray(tuple(shape), aval.dtype)\n+\n+def _with_axes(axes: Iterable[Tuple[AxisName, int]], f):\n+ for name, size in axes:\n+ f = core.extend_axis_env(name, size, None)(f)\n+ return f()\n+\n+def _trace_mapped_jaxpr(fun,\n+ args_flat,\n+ in_axes_flat: List[AxisNamePos],\n+ axis_sizes: Dict[AxisName, int],\n+ in_tree):\n+ fun_flat, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n+ avals_flat = [core.raise_to_shaped(core.get_aval(arg)) for arg in args_flat]\n+ mapped_pvals = [pe.PartialVal.unknown(_delete_aval_axes(aval, in_axes))\n+ for aval, in_axes in zip(avals_flat, in_axes_flat)]\n+ jaxpr, _, consts = _with_axes(axis_sizes.items(),\n+ lambda: pe.trace_to_jaxpr(fun_flat, mapped_pvals))\n+ return core.ClosedJaxpr(jaxpr, consts), out_tree()\n+\n+def _get_axis_sizes(args_flat: Iterable[Any], in_axes_flat: Iterable[AxisNamePos]):\n+ axis_sizes: Dict[AxisName, int] = {}\n+ for arg, in_axes in zip(args_flat, in_axes_flat):\n+ for name, dim in in_axes.items():\n+ if name in axis_sizes:\n+ assert axis_sizes[name] == arg.shape[dim]\n+ else:\n+ axis_sizes[name] = arg.shape[dim]\n+ return axis_sizes\n+\n+\ndef lookup_exactly_one_of(d: AxisNamePos, names: List[AxisName]) -> Optional[int]:\nres = None\nfor name in names:\n@@ -171,7 +218,7 @@ def untile_axis(out, axis: Optional[int]):\nreturn out.reshape(shape)\n# NOTE: This divides the in_axes by the tile_size and multiplies the out_axes by it.\n-def vtile(f_flat, in_axes_flat, out_axes_flat, tile_size: Optional[int]):\n+def vtile(f_flat, in_axes_flat, out_axes_flat, tile_size: Optional[int], axis_name):\n@lu.transformation\ndef _map_to_tile(*args_flat):\nreal_tile_size = tile_size\n@@ -189,7 +236,7 @@ def vtile(f_flat, in_axes_flat, out_axes_flat, tile_size: Optional[int]):\nbatching.batch_fun(f_flat,\nin_axes_flat,\nout_axes_flat,\n- axis_name=None))\n+ axis_name=axis_name))\n# Single-dimensional generalized map\n@@ -294,7 +341,7 @@ def _apply_schedule(fun: lu.WrappedFun,\naxis_names = tuple(_GMapSubaxis(full_axis_name, i) for i in range(len(schedule)))\nif binds_axis_name:\n- jaxpr = subst_axis_names(jaxpr, full_axis_name, axis_names)\n+ jaxpr = subst_axis_names(jaxpr, {full_axis_name: (axis_names,)}) # type: ignore\nsched_fun = lambda *args: core.eval_jaxpr(jaxpr, consts, *args)\nfor (ltype, size), axis_name in list(zip(schedule, axis_names))[::-1]:\n@@ -320,17 +367,27 @@ gmap_p = core.MapPrimitive('gmap')\ngmap_p.def_impl(gmap_impl)\n-def subst_axis_names(jaxpr, replaced_name, axis_names):\n- eqns = [subst_eqn_axis_names(eqn, replaced_name, axis_names) for eqn in jaxpr.eqns]\n+def subst_axis_names(jaxpr, axis_subst: Dict[AxisName, Tuple[AxisName]]):\n+ eqns = [subst_eqn_axis_names(eqn, axis_subst) for eqn in jaxpr.eqns]\nreturn core.Jaxpr(jaxpr.constvars, jaxpr.invars, jaxpr.outvars, eqns)\n-def subst_eqn_axis_names(eqn, replaced_name, axis_names):\n+def subst_eqn_axis_names(eqn, axis_subst: Dict[AxisName, Tuple[AxisName]]):\n+ # TODO: Support custom_vjp, custom_jvp\nif isinstance(eqn.primitive, (core.CallPrimitive, core.MapPrimitive)):\n- if eqn.params.get('axis_name', None) == replaced_name: # Check for shadowing\n- return eqn\n- new_call_jaxpr = subst_axis_names(eqn.params['call_jaxpr'], replaced_name, axis_names)\n- return eqn._replace(params=dict(eqn.params, call_jaxpr=new_call_jaxpr))\n- elif eqn.params.get('axis_name', None) == replaced_name:\n- return eqn._replace(params=dict(eqn.params, axis_name=axis_names))\n+ bound_name = eqn.params.get('axis_name', None)\n+ if bound_name in axis_subst: # Check for shadowing\n+ sub_subst = dict(axis_subst)\n+ del sub_subst[bound_name]\nelse:\n+ sub_subst = axis_subst\n+ new_call_jaxpr = subst_axis_names(eqn.params['call_jaxpr'], sub_subst)\n+ return eqn._replace(params=dict(eqn.params, call_jaxpr=new_call_jaxpr))\n+ if 'axis_name' not in eqn.params:\nreturn eqn\n+ axis_names = eqn.params['axis_name']\n+ if not isinstance(axis_names, (tuple, list)):\n+ axis_names = (axis_names,)\n+ new_axis_names = sum((axis_subst.get(name, (name,)) for name in axis_names), ())\n+ if len(new_axis_names) == 1:\n+ new_axis_names = new_axis_names[0] # type: ignore\n+ return eqn._replace(params=dict(eqn.params, axis_name=new_axis_names))\n" }, { "change_type": "MODIFY", "old_path": "tests/gmap_test.py", "new_path": "tests/gmap_test.py", "diff": "@@ -148,5 +148,29 @@ class GmapTest(jtu.JaxTestCase):\nself.assertAllClose(c, (a + 2).transpose((1, 0, 2)))\nself.assertAllClose(d, (b * 4).T)\n+ @ignore_gmap_warning()\n+ @skipIf(not config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testXMapCollectives(self):\n+ def f(a, b):\n+ return lax.psum(a + 2, 'x'), b * 4\n+ with resources(r1=4, r2=2, r3=5):\n+ fm = xmap(f,\n+ in_axes=[A({'x': 0, 'z': 1}), A({'y': 1})],\n+ out_axes=[A({'z': 0}), A({'y': 0})],\n+ schedule=[\n+ ('x', 'r1'),\n+ ('x', 'r2'),\n+ ('y', 'r1'),\n+ ('z', 'r3'),\n+ ('x', 'vectorize'),\n+ ('y', 'vectorize'),\n+ ])\n+ a = jnp.arange(16*5*2).reshape((16, 5, 2))\n+ b = jnp.arange(6*16).reshape((6, 16))\n+ c, d = fm(a, b)\n+ self.assertAllClose(c, (a + 2).sum(0))\n+ self.assertAllClose(d, (b * 4).T)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add support for collectives in xmap
260,411
04.11.2020 14:43:23
-7,200
ee707de44e85a6e652ec13e3ff1bdcda42656627
[jax2tf] Small fixes to the documentation
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -421,21 +421,21 @@ There are several drawbacks of using TFXLA ops:\nWe use the following such TFXLA:\n- * ``XlaPad`` (wraps XLA Pad operator). We use this instead of ``tf.pad`` in order to\n- support ``lax.pad`` interior padding (dilation) or negative edge padding.\n- * ``XlaConv`` (wraps XLA ConvGeneralDilated operator).\n- * ``XlaGather`` (wraps XLA Gather operator). We could use ``tf.gather`` in some\n- cases but not always. Also, ``tf.gather`` has a different semantics than ``lax.gather``\n+ * `XlaPad` (wraps XLA Pad operator). We use this instead of `tf.pad` in order to\n+ support `lax.pad` interior padding (dilation) or negative edge padding.\n+ * `XlaConv` (wraps XLA ConvGeneralDilated operator).\n+ * `XlaGather` (wraps XLA Gather operator). We could use `tf.gather` in some\n+ cases but not always. Also, `tf.gather` has a different semantics than `lax.gather`\nfor index out of bounds.\n- * ``XlaScatter`` (wraps XLA Scatter operator).\n- * ``XlaSelectAndScatter`` (wraps XLA SelectAndScatter operator).\n- * ``XlaDynamicSlice`` (wraps XLA DynamicSlice operator).\n- We use this instead of ``tf.slice`` for reasons explained above for ``XlaGather``.\n- * ``XlaDynamicUpdateSlice`` (wraps XLA DynamicUpdateSlice operator).\n- * ``XlaReduceWindow`` (wraps XLA ReduceWindow operator). These are used\n- for ``lax.reduce_window_sum_p``, ``lax.reduce_window_min_p``,\n- ``lax.reduce_window_max_p``, and ``lax.reduce_window_p``.\n- * ``XlaSort`` (wraps XLA Sort operator).\n+ * `XlaScatter` (wraps XLA Scatter operator).\n+ * `XlaSelectAndScatter` (wraps XLA SelectAndScatter operator).\n+ * `XlaDynamicSlice` (wraps XLA DynamicSlice operator).\n+ We use this instead of `tf.slice` for reasons explained above for `XlaGather`.\n+ * `XlaDynamicUpdateSlice` (wraps XLA DynamicUpdateSlice operator).\n+ * `XlaReduceWindow` (wraps XLA ReduceWindow operator). These are used\n+ for `lax.reduce_window_sum_p`, `lax.reduce_window_min_p`,\n+ `lax.reduce_window_max_p`, and `lax.reduce_window_p`.\n+ * `XlaSort` (wraps XLA Sort operator).\n### Incomplete data type coverage\n@@ -451,7 +451,7 @@ There is currently no support for replicated (e.g. `pmap`) or multi-device\n### No SavedModel fine-tuning\n-Currently, TensorFlow SavedModel does not properly save the ``tf.custom_gradient``.\n+Currently, TensorFlow SavedModel does not properly save the `tf.custom_gradient`.\nIt does save however some attributes that on model restore result in a warning\nthat the model might not be differentiable, and trigger an error if differentiation\nis attempted. The plan is to fix this. Note that if no gradients are requested,\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Small fixes to the documentation
260,680
05.11.2020 18:13:44
-7,200
3bc34e4f5a106ceef24163a025b3a0733a77806c
Update scatter.py Looks like the documentation was not up to date
[ { "change_type": "MODIFY", "old_path": "jax/_src/ops/scatter.py", "new_path": "jax/_src/ops/scatter.py", "diff": "@@ -207,8 +207,8 @@ def index_min(x, idx, y, indices_are_sorted=False, unique_indices=False):\n:data:`jax.ops.index` object.\ny: the array of updates. `y` must be broadcastable to the shape of the\narray that would be returned by `x[idx]`.\n- indices_are_sorted: whether `scatter_indices` is known to be sorted\n- unique_indices: whether `scatter_indices` is known to be free of duplicates\n+ indices_are_sorted: whether `idx` is known to be sorted\n+ unique_indices: whether `idx` is known to be free of duplicates\nReturns:\nAn array.\n@@ -246,8 +246,8 @@ def index_max(x, idx, y, indices_are_sorted=False, unique_indices=False):\n:data:`jax.ops.index` object.\ny: the array of updates. `y` must be broadcastable to the shape of the\narray that would be returned by `x[idx]`.\n- indices_are_sorted: whether `scatter_indices` is known to be sorted\n- unique_indices: whether `scatter_indices` is known to be free of duplicates\n+ indices_are_sorted: whether `idx` is known to be sorted\n+ unique_indices: whether `idx` is known to be free of duplicates\nReturns:\nAn array.\n@@ -286,8 +286,8 @@ def index_update(x, idx, y, indices_are_sorted=False, unique_indices=False):\n:data:`jax.ops.index` object.\ny: the array of updates. `y` must be broadcastable to the shape of the\narray that would be returned by `x[idx]`.\n- indices_are_sorted: whether `scatter_indices` is known to be sorted\n- unique_indices: whether `scatter_indices` is known to be free of duplicates\n+ indices_are_sorted: whether `idx` is known to be sorted\n+ unique_indices: whether `idx` is known to be free of duplicates\nReturns:\nAn array.\n" } ]
Python
Apache License 2.0
google/jax
Update scatter.py Looks like the documentation was not up to date
260,299
06.11.2020 11:37:15
0
931b2ddbcb07959ce9d85731b59d61578cdd587c
Improve docs for custom_jvp and custom_vjp Correct the custom_jvp docstring to include the defjvps instance method. Add the defjvp/defvjp instance methods to the sphinx doc.
[ { "change_type": "MODIFY", "old_path": "docs/jax.rst", "new_path": "docs/jax.rst", "diff": "@@ -18,7 +18,6 @@ Subpackages\njax.ops\njax.random\njax.tree_util\n- jax.flatten_util\njax.dlpack\njax.profiler\n@@ -91,8 +90,15 @@ Parallelization (:code:`pmap`)\n.. autofunction:: jvp\n.. autofunction:: linearize\n.. autofunction:: vjp\n-.. autofunction:: custom_jvp\n-.. autofunction:: custom_vjp\n+.. autoclass:: custom_jvp\n+\n+ .. automethod:: defjvp\n+ .. automethod:: defjvps\n+\n+.. autoclass:: custom_vjp\n+\n+ .. automethod:: defvjp\n+\n.. autofunction:: checkpoint\n.. autofunction:: vmap\n" }, { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -79,10 +79,18 @@ class custom_jvp:\nThis class is meant to be used as a function decorator. Instances are\ncallables that behave similarly to the underlying function to which the\ndecorator was applied, except when a differentiation transformation (like\n- :py:func:`jax.jvp` or :py:func:`jax.grad`) is applied, in which case a custom user-supplied\n- JVP rule function is used instead of tracing into and performing automatic\n- differentiation of the underlying function's implementation. There is a single\n- instance method, ``defjvp``, which defines the custom JVP rule.\n+ :py:func:`jax.jvp` or :py:func:`jax.grad`) is applied, in which case a custom\n+ user-supplied JVP rule function is used instead of tracing into and\n+ performing automatic differentiation of the underlying function's\n+ implementation.\n+\n+ There are two instance methods available for defining the custom JVP rule:\n+ :py:func:`~jax.custom_jvp.defjvp` for defining a *single* custom JVP rule for\n+ all the function's inputs, and for convenience\n+ :py:func:`~jax.custom_jvp.defjvps`, which wraps\n+ :py:func:`~jax.custom_jvp.defjvp`, and allows you to provide seperate\n+ definitions for the partial derivatives of the function w.r.t. each of its\n+ arguments.\nFor example::\n@@ -376,7 +384,8 @@ class custom_vjp:\ntransformation (like :py:func:`jax.grad`) is applied, in which case a custom\nuser-supplied VJP rule function is used instead of tracing into and performing\nautomatic differentiation of the underlying function's implementation. There\n- is a single instance method, ``defvjp``, which defines the custom VJP rule.\n+ is a single instance method, :py:func:`~jax.custom_vjp.defvjp`, which may be\n+ used to define the custom VJP rule.\nThis decorator precludes the use of forward-mode automatic differentiation.\n" } ]
Python
Apache License 2.0
google/jax
Improve docs for custom_jvp and custom_vjp Correct the custom_jvp docstring to include the defjvps instance method. Add the defjvp/defvjp instance methods to the sphinx doc.
260,299
06.11.2020 13:43:18
0
62683959b15eaaedc8b641a7d88b45d8dc348e4b
[DOCS] Add JAX favicon to sphinx
[ { "change_type": "ADD", "old_path": "docs/_static/favicon.png", "new_path": "docs/_static/favicon.png", "diff": "Binary files /dev/null and b/docs/_static/favicon.png differ\n" }, { "change_type": "MODIFY", "old_path": "docs/conf.py", "new_path": "docs/conf.py", "diff": "@@ -210,6 +210,8 @@ html_theme_options = {\n# of the sidebar.\nhtml_logo = '_static/jax_logo_250px.png'\n+html_favicon = '_static/favicon.png'\n+\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\n" } ]
Python
Apache License 2.0
google/jax
[DOCS] Add JAX favicon to sphinx
260,287
08.11.2020 18:45:24
-3,600
5c6a588528c5d5aad47878917602dca7587b335b
Pass around the flattened args and outputs in invertible_ad The previous version worked fine when the argument list was already flat, but would fail when it was a more complicated pytree. This should fix it.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/invertible_ad.py", "new_path": "jax/interpreters/invertible_ad.py", "diff": "@@ -66,14 +66,14 @@ def invertible(fun):\n\"gradients computed correctly (their uses inside this function will be ignored)!\")\n# TODO: This requires the body to be jittable, but this shouldn't be necessary.\n# Is there a way to trace a jaxpr while running it?\n- outs = core.eval_jaxpr(jaxpr, consts, *flat_args)\n- return tree_unflatten(out_tree(), outs), (args, outs, consts, DontFlatten((jaxpr, in_tree)))\n+ flat_outs = core.eval_jaxpr(jaxpr, consts, *flat_args)\n+ return tree_unflatten(out_tree(), flat_outs), (flat_args, flat_outs, consts, DontFlatten((jaxpr, in_tree)))\ndef bwd(res, cts):\n- args, outs, consts, aux = res\n+ flat_args, flat_outs, consts, aux = res\njaxpr, in_tree = aux.val\nflat_cts, _ = tree_flatten(cts)\n- return tree_unflatten(in_tree, inv_backward_pass(jaxpr, consts, args, outs, flat_cts))\n+ return tree_unflatten(in_tree, inv_backward_pass(jaxpr, consts, flat_args, flat_outs, flat_cts))\nifun.defvjp(fwd, bwd)\n@@ -192,7 +192,6 @@ def inv_backward_pass(jaxpr: core.Jaxpr, consts, primals_in, primals_out, cotang\nfor primal in primals_out)\nshould_vjp = any(type(ct) is not ad.Zero for ct in cts_in)\nassert not eqn.primitive.call_primitive\n- assert not (should_invert ^ should_vjp) # Either both true or both false\n# Skip primals equations that are only jvp coefficients and don't affect\n# primal outputs.\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4356,6 +4356,16 @@ class InvertibleADTest(jtu.JaxTestCase):\njax.value_and_grad(lambda x: np.sum(finv(x, o)[0]))(o),\ncheck_dtypes=True)\n+ def test_invertible_pytree(self):\n+ def f(x, y):\n+ return jnp.exp(x[0]) * x[1] + y\n+\n+ finv = jax.invertible(f)\n+ o = np.ones((5,))\n+ self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f((x, x), x)[0]))(o),\n+ jax.value_and_grad(lambda x: np.sum(finv((x, x), x)[0]))(o),\n+ check_dtypes=True)\n+\nclass DeprecatedCustomTransformsTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Pass around the flattened args and outputs in invertible_ad The previous version worked fine when the argument list was already flat, but would fail when it was a more complicated pytree. This should fix it.
260,299
08.11.2020 22:22:36
0
a0a2c973e6a8a1c60de336f1b6b17134f73658e4
Fixes to jax.api docs
[ { "change_type": "MODIFY", "old_path": "docs/jax.rst", "new_path": "docs/jax.rst", "diff": "@@ -90,6 +90,7 @@ Parallelization (:code:`pmap`)\n.. autofunction:: hessian\n.. autofunction:: jvp\n.. autofunction:: linearize\n+.. autofunction:: linear_transpose\n.. autofunction:: vjp\n.. autofunction:: custom_jvp\n.. autofunction:: custom_vjp\n" }, { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -469,6 +469,13 @@ def xla_computation(fun: Callable,\nthe output of ``fun`` and where the leaves are objects with ``shape`` and\n``dtype`` attributes representing the corresponding types of the output\nleaves.\n+ donate_argnums: Specify which arguments are \"donated\" to the computation.\n+ It is safe to donate arguments 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 re-use buffers that you donate to a computation, JAX will raise\n+ an error if you try to.\nReturns:\nA wrapped version of ``fun`` that when applied to example arguments returns\n" } ]
Python
Apache License 2.0
google/jax
Fixes to jax.api docs
260,335
08.11.2020 14:48:14
28,800
0b76854be07973ed14b6192016265f0f23499abe
fix skip logic for test that requires portpicker
[ { "change_type": "MODIFY", "old_path": "tests/profiler_test.py", "new_path": "tests/profiler_test.py", "diff": "@@ -87,7 +87,7 @@ class ProfilerTest(unittest.TestCase):\nself.assertEqual(1, len(glob.glob(path)),\n'Expected one path match: ' + path)\n- @unittest.skipIf(not (portpicker or profiler_client or tf_profiler),\n+ @unittest.skipIf(not (portpicker and profiler_client and tf_profiler),\n\"Test requires tensorflow.profiler and portpicker\")\ndef testSingleWorkerSamplingMode(self, delay_ms=None):\ndef on_worker(port, worker_start):\n" } ]
Python
Apache License 2.0
google/jax
fix skip logic for test that requires portpicker
260,519
07.11.2020 18:32:28
-19,080
a3c729b97a445911d41a4a2b4375e7888c380a73
Fix + additional fixes
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/signal.py", "new_path": "jax/_src/scipy/signal.py", "diff": "@@ -68,8 +68,6 @@ def convolve(in1, in2, mode='full', method='auto',\nwarnings.warn(\"convolve() ignores method argument\")\nif jnp.issubdtype(in1.dtype, jnp.complexfloating) or jnp.issubdtype(in2.dtype, jnp.complexfloating):\nraise NotImplementedError(\"convolve() does not support complex inputs\")\n- if jnp.ndim(in1) != 1 or jnp.ndim(in2) != 1:\n- raise ValueError(\"convolve() only supports 1-dimensional inputs.\")\nreturn _convolve_nd(in1, in2, mode, precision=precision)\n@@ -92,12 +90,10 @@ def correlate(in1, in2, mode='full', method='auto',\nwarnings.warn(\"correlate() ignores method argument\")\nif jnp.issubdtype(in1.dtype, jnp.complexfloating) or jnp.issubdtype(in2.dtype, jnp.complexfloating):\nraise NotImplementedError(\"correlate() does not support complex inputs\")\n- if jnp.ndim(in1) != 1 or jnp.ndim(in2) != 1:\n- raise ValueError(\"correlate() only supports {ndim}-dimensional inputs.\")\n- return _convolve_nd(in1, in2[::-1], mode, precision=precision)\n+ return _convolve_nd(in1, jnp.flip(in2), mode, precision=precision)\n-@_wraps(osp_signal.correlate)\n+@_wraps(osp_signal.correlate2d)\ndef correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0,\nprecision=None):\nif boundary != 'fill' or fillvalue != 0:\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_signal_test.py", "new_path": "tests/scipy_signal_test.py", "diff": "@@ -29,6 +29,7 @@ config.parse_flags_with_absl()\nonedim_shapes = [(1,), (2,), (5,), (10,)]\ntwodim_shapes = [(1, 1), (2, 2), (2, 3), (3, 4), (4, 4)]\n+threedim_shapes = [(2, 2, 2), (3, 3, 2), (4, 4, 2), (5, 5, 2)]\ndefault_dtypes = jtu.dtypes.floating + jtu.dtypes.integer\n@@ -42,16 +43,17 @@ class LaxBackedScipySignalTests(jtu.JaxTestCase):\nop,\njtu.format_shape_dtype_string(xshape, dtype),\njtu.format_shape_dtype_string(yshape, dtype),\n- mode),\n+ mode), \"shapeset\": shapeset,\n\"xshape\": xshape, \"yshape\": yshape, \"dtype\": dtype, \"mode\": mode,\n\"jsp_op\": getattr(jsp_signal, op),\n\"osp_op\": getattr(osp_signal, op)}\nfor mode in ['full', 'same', 'valid']\nfor op in ['convolve', 'correlate']\nfor dtype in default_dtypes\n- for xshape in onedim_shapes\n- for yshape in onedim_shapes))\n- def testConvolutions(self, xshape, yshape, dtype, mode, jsp_op, osp_op):\n+ for shapeset in [onedim_shapes, twodim_shapes, threedim_shapes]\n+ for xshape in shapeset\n+ for yshape in shapeset))\n+ def testConvolutions(self, shapeset, xshape, yshape, dtype, mode, jsp_op, osp_op):\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: [rng(xshape, dtype), rng(yshape, dtype)]\nosp_fun = partial(osp_op, mode=mode)\n" } ]
Python
Apache License 2.0
google/jax
Fix #4775 + additional fixes
260,411
06.11.2020 16:50:50
-7,200
f5294e6f5768984043d011f00ce4e6a505f1b90c
[jax2tf] Add the convert_and_save_model to the jax2tf API. Expanded the documentation, including with a discussion for various options for creating SavedModel from Flax or Haiku models.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -16,7 +16,7 @@ Flax models and their use with TensorFlow Hub and Keras, are described in the\nSee also some internal ongoing design discussions at `go/jax2tf-doc`.\n-### Usage: converting basic functions.\n+## Usage: converting basic functions.\nAs a rule of thumb, if you can `jax.jit` your function then you should be able\nto use `jax2tf.convert`:\n@@ -49,7 +49,7 @@ The Autograph feature of `tf.function` cannot be expected to work on\nfunctions converted from JAX as above, so it is recommended to\nset `autograph=False` in order to avoid warnings or outright errors.\n-### Usage: saved model\n+## Usage: saved model\nSince jax2tf provides a regular TensorFlow function using it with SavedModel\nis trivial:\n@@ -65,6 +65,11 @@ tf.saved_model.save(my_model, '/some/directory')\nrestored_model = tf.saved_model.load('/some/directory')\n```\n+An important point is that in the above code snippet **everything is standard\n+TensorFlow code. In particular, the saving of the model is independent of JAX,\n+and one can therefore set metadata and assets as needed for their application,\n+as if the saved function had been written directly in TensorFlow**.\n+\nJust like for regular TensorFlow functions, it is possible to include in the\nSavedModel multiple versions of a function for different input shapes, by\n\"warming up\" the function on different input shapes:\n@@ -76,12 +81,8 @@ my_model.f(tf.ones([16, 28, 28])) # a batch size of 16\ntf.saved_model.save(my_model, '/some/directory')\n```\n-More involved examples of using SavedModel, including how to prepare\n-Flax models for conversion and saving, are described in the\n+For examples of how to save a Flax or Haiku model as a SavedModel see the\n[examples directory](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/README.md).\n-As part of the examples, we provide the\n-[saved_model_lib.py](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/saved_model_lib.py) library with a convenience function for converting and saving\n-a JAX function as a SavedModel.\nFor details on saving a batch-polymorphic SavedModel see [below](#shape-polymorphic-conversion).\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/README.md", "new_path": "jax/experimental/jax2tf/examples/README.md", "diff": "@@ -7,32 +7,57 @@ This directory contains a number of examples of using the\n* save SavedModel from trained MNIST models, using both pure JAX and Flax.\n* reuse the feature-extractor part of the trained MNIST model in\nTensorFlow Hub, and in a larger TensorFlow Keras model.\n+ * use jax2tf with TensorFlow Serving and TensorFlow JavaScript.\n-It is also possible to use jax2tf-generated SavedModel with TensorFlow serving.\n-At the moment, the open-source TensorFlow model server is missing XLA support,\n-but the Google version can be used, as shown in the\n-[serving examples](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/serving/README.md).\n+# Generating TensorFlow SavedModel\n-A jax2tf-generated SavedModel can also be converted to a format usable with\n-TensorFlow.js in some cases where the conversion does not require XLA support,\n-as shown in the [Quickdraw TensorFlow.js example](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/tf_js/quickdraw/README.md).\n+The functions generated by `jax2tf.convert` are standard TensorFlow functions\n+and you can save them in a SavedModel using standard TensorFlow code, as shown\n+in the [jax2tf documentation](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/README.md#usage-saved-model).\n+This decoupling of jax2tf from SavedModel is important, because it **allows\n+the user to have full control over what metadata is saved in the SavedModel**.\n-# Preparing the model for jax2tf\n+As an example, we provide the function `convert_and_save_model`\n+(see [saved_model_lib.py](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/saved_model_lib.py).)\n+For serious uses, you will probably want to copy and expand this\n+function as needed.\n+\n+The `convert_and_saved_model` example function allows you to control\n+which model parameters you want to save separately as variables,\n+as opposed to having them embedded as constants in the function.\n+This is useful for two reasons:\n+the parameters could be very large and exceed the limits of the\n+GraphDef part of the SavedModel, or you may want to fine-tune the\n+model and change the value of the parameters.\n-The most important detail for using jax2tf with SavedModel is to express\n-the trained model as a pair:\n+To achieve this you should extract a pair from your trained model:\n- * `func`: a two-argument function with signature:\n+ * `predict_fn`: a two-argument function with signature:\n`(params: Parameters, inputs: Inputs) -> Outputs`.\nBoth arguments must be a `numpy.ndarray` or\n- (nested) tuple/list/dictionaries thereof. In particular, it is important\n- for models that take multiple inputs to be packaged as a fuunction with\n- just two arguments, e.g., by taking their inputs\n+ (nested) tuple/list/dictionaries thereof. In particular,\n+ it is important for models that take multiple inputs to be packaged\n+ as a function with just two arguments, e.g., by taking their inputs\nas a single tuple/list/dictionary.\n* `params`: of type `Parameters`, the model parameters, to be used as the\n- first input for `func`. This also can be a `numpy.ndarray` or\n+ first input for `predict_fn`, and to be saved as the variables of the\n+ SavedModel. This must also be a `numpy.ndarray` or\n(nested) tuple/list/dictionary thereof.\n+## Usage: saved models from Flax\n+\n+If you are using Flax, then the recipe to obtain this pair is as follows:\n+\n+ ```\n+ class MyModel(nn.Module):\n+ ...\n+\n+ model = MyModel(*config_args, **kwargs) # Construct the model\n+ optimizer = ... # Train the model\n+ params = optimizer.target # These are the parameters\n+ predict_fn = lambda params, input: model.apply({\"params\": params}, input)\n+ ```\n+\nYou can see in\n[mnist_lib.py](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/mnist_lib.py)\nhow this can be done for two\n@@ -40,7 +65,46 @@ implementations of MNIST, one using pure JAX (`PureJaxMNIST`) and a CNN\none using Flax (`FlaxMNIST`). Other Flax models can be arranged similarly,\nand the same strategy should work for other neural-network libraries for JAX.\n-# Generating TensorFlow SavedModel\n+If your Flax model takes multiple inputs, then you need to change the last\n+line above to:\n+\n+ ```\n+ predict_fn = lambda params, input: model.apply({\"params\": params}, *input)\n+ ```\n+\n+(Notice that `predict_fn` takes a single tuple input, and expands it to\n+pass it to `model.apply` as multiple inputs.)\n+\n+You can control which parameters you want to save as variables, and\n+which you want to embed in the computation graph. For example, to\n+embed all parameters in the graph:\n+\n+ ```\n+ params = ()\n+ predict_fn = lambda _, input: model.apply({\"params\": optimizer.target}, input)\n+ ```\n+\n+(The MNIST Flax examples from\n+[mnist_lib.py](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/mnist_lib.py)\n+normally has a GraphDef of 150k and a variables section of 3Mb. If we embed the\n+parameters as constants in the GraphDef as shown above, the variables section\n+becomes empty and the GraphDef becomes 13Mb. This embedding may allow\n+the compiler to generate faster code by constant-folding some computations.)\n+\n+## Usage: saved models from Haiku\n+\n+If you are using Haiku, then the recipe is along these lines:\n+\n+ ```\n+ model_fn = ...define your Haiku model...\n+ net = hk.transform(model_fn) # get a pair of init and apply functions\n+ params = ... train your model starting from net.init() ...\n+ predict_fn = hk.without_apply_rng(net).apply\n+ ```\n+\n+\n+# Preparing the model for jax2tf\n+\nOnce you have the model in this form, you can use the\n`saved_model_lib.save_model` function from\n@@ -79,7 +143,6 @@ be done using jax2tf's\nAs a result, the inference function will be traced only once and the SavedModel\nwill contain a single batch-polymorphic TensorFlow graph.\n-\n# Reusing models with TensorFlow Hub and TensorFlow Keras\nThe SavedModel produced by the example in `saved_model_main.py` already\n@@ -106,3 +169,16 @@ a `tf.GradientTape` and doing gradient updates manually).\nAll the flags of `saved_model_main.py` also apply to `keras_reuse_main.py`.\nIn particular, you can select the Flax MNIST model: `--model=mnist_flax`.\n+\n+# Using jax2tf with TensorFlow serving\n+\n+It is also possible to use jax2tf-generated SavedModel with TensorFlow serving.\n+At the moment, the open-source TensorFlow model server is missing XLA support,\n+but the Google version can be used, as shown in the\n+[serving examples](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/serving/README.md).\n+\n+# Using jax2tf with TensorFlow JavaScript\n+\n+A jax2tf-generated SavedModel can also be converted to a format usable with\n+TensorFlow.js in some cases where the conversion does not require XLA support,\n+as shown in the [Quickdraw TensorFlow.js example](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/tf_js/quickdraw/README.md).\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/mnist_lib.py", "new_path": "jax/experimental/jax2tf/examples/mnist_lib.py", "diff": "@@ -204,9 +204,12 @@ class FlaxMNIST:\nx = nn.log_softmax(x)\nreturn x\n+ # Create the model and save it\n+ model = Module()\n+\n@staticmethod\ndef predict(params, inputs, with_classifier=True):\n- return FlaxMNIST.Module().apply({\"params\": params},\n+ return FlaxMNIST.model.apply({\"params\": params},\ninputs,\nwith_classifier=with_classifier)\n@@ -238,7 +241,7 @@ class FlaxMNIST:\nmomentum_mass = 0.9\ninit_shape = jnp.ones((1,) + input_shape, jnp.float32)\n- initial_params = FlaxMNIST.Module().init(rng, init_shape)[\"params\"]\n+ initial_params = FlaxMNIST.model.init(rng, init_shape)[\"params\"]\noptimizer_def = flax.optim.Momentum(\nlearning_rate=step_size, beta=momentum_mass)\noptimizer = optimizer_def.create(initial_params)\n@@ -257,8 +260,11 @@ class FlaxMNIST:\nlogging.info(f\"{FlaxMNIST.name}: Training set accuracy {train_acc}\")\nlogging.info(f\"{FlaxMNIST.name}: Test set accuracy {test_acc}\")\n- return (functools.partial(\n- FlaxMNIST.predict, with_classifier=with_classifier), optimizer.target)\n+ # See discussion in README.md for packaging Flax models for conversion\n+ predict_fn = functools.partial(FlaxMNIST.predict,\n+ with_classifier=with_classifier)\n+ params = optimizer.target\n+ return (predict_fn, params)\ndef plot_images(ds,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/requirements.txt", "new_path": "jax/experimental/jax2tf/examples/requirements.txt", "diff": "tensorflow_datasets\ntensorflow_hub\nflax\n-\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_lib.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-\"\"\"Defines a helper function for creating a SavedModel from the jax2tf trained model.\n+\"\"\"Defines a helper function for creating a SavedModel from a jax2tf trained model.\n+\n+This has been tested with TensorFlow Hub, TensorFlow JavaScript,\n+and TensorFlow Serving.\n+\n+Note that the code in this file is provided only as an example. The functions\n+generated by `jax2tf.convert` are standard TensorFlow functions and you can\n+save them in a SavedModel using standard TensorFlow code. This decoupling\n+of jax2tf from SavedModel is important, because it allows the user to have full\n+control over what metadata is saved in the SavedModel. In fact, for serious\n+uses you will probably want to copy and expand this function as needed.\n-This has been tested with TensorFlow Hub and TensorFlow model server.\n-There is very little in this file that is specific to jax2tf. If you\n-are familiar with how to generate SavedModel, you can most likely use your\n-own code for this purpose.\n\"\"\"\n-from typing import Callable, Sequence, Optional\n+from typing import Any, Callable, Sequence, Optional\nfrom jax.experimental import jax2tf # type: ignore[import]\nimport tensorflow as tf # type: ignore[import]\n-def save_model(jax_fn: Callable,\n+def convert_and_save_model(\n+ jax_fn: Callable[[Any, Any], Any],\nparams,\nmodel_dir: str,\n*,\n@@ -33,35 +40,26 @@ def save_model(jax_fn: Callable,\nshape_polymorphic_input_spec: Optional[str] = None,\nwith_gradient: bool = False,\nenable_xla: bool = True,\n- compile_model: bool = True):\n- \"\"\"Saves the SavedModel for a function.\n+ compile_model: bool = True,\n+ save_model_options: Optional[tf.saved_model.SaveOptions] = None):\n+ \"\"\"Convert a JAX function and saves a SavedModel.\n+\n+ This is an example, for serious uses you will likely want to copy and\n+ expand it as needed (see note at the top of the model).\n+\n+ Use this function if you have a trained ML model that has both a prediction\n+ function and trained parameters, which you want to save separately from the\n+ function graph as variables (e.g., to avoid limits on the size of the\n+ GraphDef, or to enable fine-tuning.) If you don't have such parameters,\n+ you can still use this library function but probably don't need it\n+ (see jax2tf/README.md for some simple examples).\nIn order to use this wrapper you must first convert your model to a function\nwith two arguments: the parameters and the input on which you want to do\n- inference. Both arguments may be np.ndarray or\n- (nested) tuples/lists/dictionaries thereof.\n-\n- If you want to save the model for a function with multiple parameters and\n- multiple inputs, you have to collect the parameters and the inputs into\n- one argument, e.g., adding a tuple or dictionary at top-level.\n-\n- ```\n- def jax_fn_multi(param1, param2, input1, input2):\n- # JAX model with multiple parameters and multiple inputs. They all can\n- # be (nested) tuple/list/dictionaries of np.ndarray.\n- ...\n-\n- def jax_fn_for_save_model(params, inputs):\n- # JAX model with parameters and inputs collected in a tuple each. We can\n- # use dictionaries also (in which case the keys would appear as the names\n- # of the inputs)\n- param1, param2 = params\n- input1, input2 = inputs\n- return jax_fn_multi(param1, param2, input1, input2)\n- save_model(jax_fn_for_save_model, (param1, param2), ...)\n- ```\n-\n- See examples in mnist_lib.py and saved_model.py.\n+ inference. Both arguments may be np.ndarray or (nested)\n+ tuples/lists/dictionaries thereof.\n+\n+ See the README.md for a discussion of how to prepare Flax and Haiku models.\nArgs:\njax_fn: a JAX function taking two arguments, the parameters and the inputs.\n@@ -93,6 +91,7 @@ def save_model(jax_fn: Callable,\nexception if it is not possible. (default: True)\ncompile_model: use TensorFlow experimental_compiler on the SavedModel. This\nis needed if the SavedModel will be used for TensorFlow serving.\n+ save_model_options: options to pass to savedmodel.save.\n\"\"\"\nif not input_signatures:\nraise ValueError(\"At least one input_signature must be given\")\n@@ -106,10 +105,13 @@ def save_model(jax_fn: Callable,\nin_shapes=[None, shape_polymorphic_input_spec],\nenable_xla=enable_xla)\n- # Create tf.Variables for the parameters.\n+ # Create tf.Variables for the parameters. If you want more useful variable\n+ # names, you can use `tree.map_structure_with_path` from the `dm-tree` package\nparam_vars = tf.nest.map_structure(\n- # If with_gradient=False, we mark the variables behind as non-trainable,\n- # to ensure that users of the SavedModel will not try to fine tune them.\n+ # Due to a bug in SavedModel it is not possible to use tf.GradientTape on\n+ # a function converted with jax2tf and loaded from SavedModel. Thus, we\n+ # mark the variables as non-trainable to ensure that users of the\n+ # SavedModel will not try to fine tune them.\nlambda param: tf.Variable(param, trainable=with_gradient),\nparams)\ntf_graph = tf.function(lambda inputs: tf_fn(param_vars, inputs),\n@@ -117,13 +119,15 @@ def save_model(jax_fn: Callable,\nexperimental_compile=compile_model)\nsignatures = {}\n+ # This signature is needed for TensorFlow Serving use.\nsignatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \\\ntf_graph.get_concrete_function(input_signatures[0])\nfor input_signature in input_signatures[1:]:\n# If there are more signatures, trace and cache a TF function for each one\ntf_graph.get_concrete_function(input_signature)\nwrapper = _ReusableSavedModelWrapper(tf_graph, param_vars)\n- tf.saved_model.save(wrapper, model_dir, signatures=signatures)\n+ tf.saved_model.save(wrapper, model_dir, signatures=signatures,\n+ options=save_model_options)\nclass _ReusableSavedModelWrapper(tf.train.Checkpoint):\n@@ -136,10 +140,11 @@ class _ReusableSavedModelWrapper(tf.train.Checkpoint):\ndef __init__(self, tf_graph, param_vars):\n\"\"\"Args:\n- tf_fn: a tf.function taking one argument (the inputs), which can be\n- be tuples/lists/dictionaries of np.ndarray or tensors.\n- params: the parameters, as tuples/lists/dictionaries of tf.Variable,\n- and will be saved as the variables of the SavedModel.\n+ tf_graph: a tf.function taking one argument (the inputs), which can be\n+ be tuples/lists/dictionaries of np.ndarray or tensors. The function\n+ may have references to the tf.Variables in `param_vars`.\n+ param_vars: the parameters, as tuples/lists/dictionaries of tf.Variable,\n+ to be saved as the variables of the SavedModel.\n\"\"\"\nsuper().__init__()\n# Implement the interface from https://www.tensorflow.org/hub/reusable_saved_models\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "diff": "@@ -29,6 +29,7 @@ import os\nfrom absl import app\nfrom absl import flags\n+from jax.experimental import jax2tf\nfrom jax.experimental.jax2tf.examples import mnist_lib # type: ignore\nfrom jax.experimental.jax2tf.examples import saved_model_lib # type: ignore\n@@ -110,7 +111,7 @@ def train_and_save():\n]\nshape_polymorphic_input_spec = None\nlogging.info(f\"Saving model for {model_descr}\")\n- saved_model_lib.save_model(\n+ saved_model_lib.convert_and_save_model(\npredict_fn,\npredict_params,\nmodel_dir,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.py", "new_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.py", "diff": "@@ -134,7 +134,7 @@ def main(*args):\nmodel_dir = os.path.join(base_model_path, \"saved_models\")\n# the model must be converted with with_gradient set to True to be able to\n# convert the saved model to TF.js, as \"PreventGradient\" is not supported\n- saved_model_lib.save_model(predict, flax_params, model_dir,\n+ saved_model_lib.convert_and_save_model(predict, flax_params, model_dir,\ninput_signatures=[tf.TensorSpec([1, 28, 28, 1])],\nwith_gradient=True, compile_model=False,\nenable_xla=False)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Add the convert_and_save_model to the jax2tf API. Expanded the documentation, including with a discussion for various options for creating SavedModel from Flax or Haiku models.
260,287
05.11.2020 11:54:05
0
f637263059b97baed5f38070e85c4aa917553324
Add some type annotations in parallel_callable
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -511,8 +511,16 @@ def xla_pmap_impl(fun: lu.WrappedFun, *args, backend, axis_name, axis_size,\nreturn compiled_fun(*args)\n@lu.cache\n-def parallel_callable(fun, backend, axis_name, axis_size, global_axis_size,\n- devices, name, mapped_invars, donated_invars, *avals):\n+def parallel_callable(fun: lu.WrappedFun,\n+ backend_name: Optional[str],\n+ axis_name,\n+ axis_size: int,\n+ global_axis_size: Optional[int],\n+ devices: Optional[Sequence[Any]],\n+ name: str,\n+ mapped_invars: Iterable[bool],\n+ donated_invars: Iterable[bool],\n+ *avals):\nif devices is not None and len(devices) == 0:\nraise ValueError(\"'devices' argument to pmap must be non-empty, or None.\")\n@@ -551,7 +559,7 @@ def parallel_callable(fun, backend, axis_name, axis_size, global_axis_size,\nlocal_devices = [d for d in devices if d.host_id == xb.host_id()]\nassert len(local_devices) > 0\nelse:\n- local_devices = None\n+ local_devices = None # type: ignore\nif config.omnistaging_enabled:\nsharded_avals = tuple(shard_aval(axis_size, aval) if m else aval\n@@ -570,8 +578,8 @@ def parallel_callable(fun, backend, axis_name, axis_size, global_axis_size,\npvals = [pe.PartialVal.unknown(aval) for aval in sharded_avals]\n# We add a dummy first invar, to carry the trace details to `dynamic_fun`\npval = pe.PartialVal.unknown(core.abstract_unit) # dummy value for axis env\n- jaxpr, out_pvals, consts = pe.trace_to_jaxpr(\n- dynamic_fun, [pval] + pvals, instantiate=False, stage_out=True, bottom=True) # type: ignore\n+ jaxpr, out_pvals, consts = pe.trace_to_jaxpr( # type: ignore\n+ dynamic_fun, [pval] + pvals, instantiate=False, stage_out=True, bottom=True)\njaxpr.invars = jaxpr.invars[1:] # ignore dummy\njaxpr = xla.apply_outfeed_rewriter(jaxpr)\n@@ -580,7 +588,7 @@ def parallel_callable(fun, backend, axis_name, axis_size, global_axis_size,\n# TODO(skye,mattjj): allow more collectives on multi-host as we test them, but\n# for now raise an error\nif devices is not None:\n- is_multi_host_pmap = any(d.host_id != xb.host_id() for d in devices)\n+ is_multi_host_pmap = len(local_devices) != len(devices)\nelse:\nis_multi_host_pmap = xb.host_count() > 1\nif is_multi_host_pmap:\n@@ -597,8 +605,8 @@ def parallel_callable(fun, backend, axis_name, axis_size, global_axis_size,\n# out multi-replica XLA computations regardless of the hardware available.\n# The 'None' values here are just dummies we know will be ignored.\nhandlers = [\n- _pval_to_result_handler(axis_size, None, None, None, pval, local_devices,\n- backend) for pval in out_pvals # type: ignore\n+ _pval_to_result_handler(axis_size, None, None, None, pval, local_devices, # type: ignore\n+ backend_name) for pval in out_pvals\n]\nresults = [handler(None) for handler in handlers]\nreturn lambda *_: results\n@@ -652,14 +660,14 @@ def parallel_callable(fun, backend, axis_name, axis_size, global_axis_size,\nmap(op.not_, mapped_invars), arg_parts,\ndonated_invars=donated_invars)\nwith maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\n- out_nodes = xla.jaxpr_subcomp(c, jaxpr, backend, axis_env, xla_consts,\n+ out_nodes = xla.jaxpr_subcomp(c, jaxpr, backend_name, axis_env, xla_consts,\nextend_name_stack(wrap_name(name, 'pmap')), *xla_args)\nbuild_out_tuple = partial(xops.Tuple, c, out_nodes)\nif out_parts is not None:\nout_tuple = xb.with_sharding(c, out_parts, build_out_tuple)\nelse:\nout_tuple = build_out_tuple()\n- backend = xb.get_backend(backend)\n+ backend = xb.get_backend(backend_name)\nif backend.platform in (\"gpu\", \"tpu\"):\ndonated_invars = xla.set_up_aliases(c, xla_args, out_tuple, donated_invars, tuple_args)\nbuilt = c.Build(out_tuple)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -512,7 +512,7 @@ def jaxpr_replicas(jaxpr):\nFor a eqn, multiply the `axis_size` with the `jaxpr_replicas` of the\nsubjaxprs. For a list of eqns, take the maximum number of replicas.\n\"\"\"\n- return max(it.chain([1], (eqn_replicas(eqn) for eqn in jaxpr.eqns)))\n+ return max((eqn_replicas(eqn) for eqn in jaxpr.eqns), default=1)\n# TODO(mattjj): this function assumes that only pmap has a parameter named\n# axis_size, and that it corresponds to cross-replica mapping\n" } ]
Python
Apache License 2.0
google/jax
Add some type annotations in parallel_callable
260,299
10.11.2020 11:10:06
0
b8920a11c36b2b263c7c80bee8b48d4688b327d0
Rm old attribute annotations from TraceStack
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -618,9 +618,6 @@ class MainTrace:\nclass TraceStack:\n# See comments in https://github.com/google/jax/pull/3370\n- upward: List[MainTrace]\n- downward: List[MainTrace]\n-\ndef __init__(self):\neval_trace = MainTrace(0, EvalTrace)\nself.stack = [eval_trace]\n" } ]
Python
Apache License 2.0
google/jax
Rm old attribute annotations from TraceStack
260,349
10.11.2020 15:14:58
-3,600
06ab965ad17ea42b290649a896d98ee07fc6bcec
Add description how to view pytree definition
[ { "change_type": "MODIFY", "old_path": "docs/pytrees.rst", "new_path": "docs/pytrees.rst", "diff": "@@ -78,6 +78,12 @@ This happens to be the default ``in_axes`` value for ``vmap``!\nThe same logic applies to other optional parameters that refer to specific input\nor output values of a transformed function, e.g. ``vmap``'s ``out_axes``.\n+Viewing the pytree definition of an object\n+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n+To view the pytree definition of an arbitrary ``object`` for debugging purposes, you can use::\n+\n+ from jax.tree_util import tree_structure\n+ print(tree_structure(object))\nDeveloper information\n^^^^^^^^^^^^^^^^^^^^^^\n" } ]
Python
Apache License 2.0
google/jax
Add description how to view pytree definition
260,335
13.11.2020 07:23:02
28,800
8b006f6a906c2c6c1abc95aafaf445649e963268
add correct annotations to core.TraceStack
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -618,6 +618,9 @@ class MainTrace:\nclass TraceStack:\n# See comments in https://github.com/google/jax/pull/3370\n+ stack: List[MainTrace]\n+ dynamic: MainTrace\n+\ndef __init__(self):\neval_trace = MainTrace(0, EvalTrace)\nself.stack = [eval_trace]\n" } ]
Python
Apache License 2.0
google/jax
add correct annotations to core.TraceStack
260,424
13.11.2020 17:07:15
-3,600
91777c331c797b22743ee95e6bc4c46a32aa5e0c
Fix select_and_gather_add_transpose rule. Fixes a 'jax.ad_util.Zero' is not a valid JAX type error.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -5387,6 +5387,8 @@ def _select_and_gather_add_transpose(\nmsg = (\"VJP not implemented for select_and_gather (MaxPool) with window \"\n\"dilation, got window_dilation={}.\")\nraise NotImplementedError(msg.format(window_dilation))\n+ if type(t) is ad_util.Zero:\n+ return [ad_util.Zero, None]\nhas_base_dilation = any(d != 1 for d in base_dilation)\nif has_base_dilation:\nselect_identity = (_get_max_identity if select_prim is ge_p\n" } ]
Python
Apache License 2.0
google/jax
Fix select_and_gather_add_transpose rule. Fixes a 'jax.ad_util.Zero' is not a valid JAX type error.
260,335
13.11.2020 14:22:17
28,800
df081393ebded602c9007361f5d988945ea2e95d
update concatenate shape rule for sound mask test
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3224,11 +3224,12 @@ def _concatenate_shape_rule(*operands, **kwargs):\nif len({operand.ndim for operand in operands}) != 1:\nmsg = \"Cannot concatenate arrays with different ranks, got {}.\"\nraise TypeError(msg.format(\", \".join(str(o.ndim) for o in operands)))\n- shapes = np.array([operand.shape for operand in operands])\n- if not 0 <= dimension < shapes.shape[1]:\n+ if not 0 <= dimension < operands[0].ndim:\nmsg = \"concatenate dimension out of bounds: dimension {} for shapes {}.\"\nraise TypeError(msg.format(dimension, \", \".join(map(str, shapes))))\n- if not np.all(np.delete(shapes[0] == shapes, dimension, axis=1)):\n+ shapes = [operand.shape[:dimension] + operand.shape[dimension+1:]\n+ for operand in operands]\n+ if not all(s1 == s2 for s1, s2 in zip(shapes[:-1], shapes[1:])):\nmsg = (\"Cannot concatenate arrays with shapes that differ in dimensions \"\n\"other than the one being concatenated: dimension {} for shapes {}.\")\nraise TypeError(msg.format(dimension, \", \".join(map(str, shapes))))\n" } ]
Python
Apache License 2.0
google/jax
update concatenate shape rule for sound mask test
260,335
13.11.2020 14:55:04
28,800
799325bbba352842a56ca225f02b6eb970f45712
revise lax broadcasting to work with sound masking
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -63,13 +63,21 @@ DType = Any\nShape = Sequence[int]\ndef _try_broadcast_shapes(shapes):\n- for sizes in zip(*shapes):\n+ assert shapes\n+ if len(shapes) == 1: return shapes[0]\n+ rank, *others = {len(shape) for shape in shapes}\n+ if others: return None # must have consistent rank\n+ if not rank: return () # scalar case\n+ result_shape = [None] * rank\n+ for i, sizes in enumerate(zip(*shapes)):\n+ if sizes[:-1] == sizes[1:]:\n+ result_shape[i] = sizes[0] # all equal sizes for this dimension\n+ else:\nsizes = [d for d in sizes if d != 1]\nif sizes[:-1] != sizes[1:]:\n- break\n- else:\n- return tuple(next((d for d in sizes if d != 1), 1)\n- for sizes in zip(*shapes))\n+ return None # must have equal sizes other than 1-sized axes\n+ result_shape[i] = sizes[0] if sizes else 1\n+ return tuple(result_shape)\n@cache()\ndef broadcast_shapes(*shapes):\n@@ -2010,8 +2018,8 @@ def naryop_dtype_rule(result_dtype, accepted_dtypes, name, *avals, **kwargs):\ndef _broadcasting_shape_rule(name, *avals):\n- shapes = np.array([aval.shape for aval in avals if aval.shape])\n- if not shapes.size:\n+ shapes = [aval.shape for aval in avals if aval.shape]\n+ if not shapes:\nreturn ()\nif len({len(shape) for shape in shapes}) != 1:\nmsg = '{} got arrays of different rank: {}.'\n@@ -3229,9 +3237,11 @@ def _concatenate_shape_rule(*operands, **kwargs):\nraise TypeError(msg.format(dimension, \", \".join(map(str, shapes))))\nshapes = [operand.shape[:dimension] + operand.shape[dimension+1:]\nfor operand in operands]\n- if not all(s1 == s2 for s1, s2 in zip(shapes[:-1], shapes[1:])):\n+ if not shapes[:-1] == shapes[1:]:\nmsg = (\"Cannot concatenate arrays with shapes that differ in dimensions \"\n- \"other than the one being concatenated: dimension {} for shapes {}.\")\n+ \"other than the one being concatenated: concatenating along \"\n+ \"dimension {} for shapes {}.\")\n+ shapes = [operand.shape for operand in operands]\nraise TypeError(msg.format(dimension, \", \".join(map(str, shapes))))\nconcat_size = sum(o.shape[dimension] for o in operands)\n" } ]
Python
Apache License 2.0
google/jax
revise lax broadcasting to work with sound masking
260,335
13.11.2020 15:02:55
28,800
8bd74a245a878dbd1aff4d5de491fcdd3f889dd3
adapt broadcast_in_dim shape rule mask soundness
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3158,8 +3158,8 @@ def _broadcast_in_dim_shape_rule(operand, *, shape, broadcast_dimensions):\nmsg = ('broadcast_in_dim broadcast_dimensions must be a subset of output '\n'dimensions, got {} for operand ndim {} and shape {}.')\nraise TypeError(msg.format(broadcast_dimensions, operand_ndim, shape))\n- if any(operand.shape[i] != 1 and operand.shape[i] != shape[broadcast_dimensions[i]]\n- for i in range(operand_ndim)):\n+ if any(operand.shape[i] != shape[broadcast_dimensions[i]] and\n+ operand.shape[i] != 1 for i in range(operand_ndim)):\nmsg = (\n\"broadcast_in_dim operand dimension sizes must either be 1, or be \"\n\"equal to their corresponding dimensions in the target broadcast \"\n" } ]
Python
Apache License 2.0
google/jax
adapt broadcast_in_dim shape rule mask soundness
260,335
13.11.2020 15:21:59
28,800
9a0207ab30d3b08476edd032f945984e2a3b8381
adapt masking rev tests for soundness
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -746,11 +746,6 @@ def slice(operand: Array, start_indices: Sequence[int],\n<https://www.tensorflow.org/xla/operation_semantics#slice>`_\noperator.\n\"\"\"\n- if (np.all(np.equal(start_indices, 0))\n- and np.all(np.equal(limit_indices, operand.shape))\n- and strides is None):\n- return operand\n- else:\nreturn slice_p.bind(operand, start_indices=tuple(start_indices),\nlimit_indices=tuple(limit_indices),\nstrides=None if strides is None else tuple(strides))\n" }, { "change_type": "MODIFY", "old_path": "tests/masking_test.py", "new_path": "tests/masking_test.py", "diff": "@@ -615,6 +615,17 @@ class MaskingTest(jtu.JaxTestCase):\nself.check(lambda x: x[..., -1], ['(n,3)'], 'n', {'n': 2}, [(3, 4)], ['float_'])\ndef test_rev(self):\n+ @shapecheck(['n'], 'n')\n+ def rev(x):\n+ return lax.rev(x, (0,))\n+\n+ @shapecheck(['(m, n)'], '(m, n)')\n+ def rev(x):\n+ return lax.rev(x, (1,))\n+\n+ def test_rev_by_indexing(self):\n+ raise SkipTest\n+\n@shapecheck(['n'], 'n+-1')\ndef rev(x):\nreturn x[:0:-1]\n" } ]
Python
Apache License 2.0
google/jax
adapt masking rev tests for soundness
260,335
16.11.2020 19:01:00
28,800
c2a98c18206c0308c85869101a6a3fc2151a9028
update jax repository citation Add all full-time JAX team members.
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -469,7 +469,7 @@ To cite this repository:\n```\n@software{jax2018github,\n- author = {James Bradbury and Roy Frostig and Peter Hawkins and Matthew James Johnson and Chris Leary and Dougal Maclaurin and Skye Wanderman-Milne},\n+ author = {James Bradbury and Roy Frostig and Peter Hawkins and Matthew James Johnson and Chris Leary and Dougal Maclaurin and George Necula and Adam Paszke and Jake VanderPlas and Skye Wanderman-Milne and Qiao Zhang},\ntitle = {{JAX}: composable transformations of {P}ython+{N}um{P}y programs},\nurl = {http://github.com/google/jax},\nversion = {0.2.5},\n" } ]
Python
Apache License 2.0
google/jax
update jax repository citation Add all full-time JAX team members.
260,411
17.11.2020 06:08:09
28,800
3bf3e352bc45cd6d61bc322501502595b42b3da5
Disable the remaining failing tests, remove jax2tf documentation
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/README.md", "new_path": "jax/experimental/jax2tf/examples/README.md", "diff": "@@ -136,12 +136,7 @@ The default saving location is `/tmp/jax2tf/saved_models/1`.\nBy default, this example will convert the inference function for three separate\n-batch sizes: 1, 16, 128. You can see this in the dumped SavedModel. If you\n-pass the argument `--serving_batch_size=-1`, then the conversion to TF will\n-be done using jax2tf's\n-[experimental shape-polymorphism feature](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/README.md#shape-polymorphic-conversion).\n-As a result, the inference function will be traced only once and the SavedModel\n-will contain a single batch-polymorphic TensorFlow graph.\n+batch sizes: 1, 16, 128. You can see this in the dumped SavedModel.\n# Reusing models with TensorFlow Hub and TensorFlow Keras\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "diff": "@@ -49,8 +49,7 @@ flags.DEFINE_integer(\"model_version\", 1,\n(\"The version number for the SavedModel. Needed for \"\n\"serving, larger versions will take precedence\"))\nflags.DEFINE_integer(\"serving_batch_size\", 1,\n- (\"For what batch size to prepare the serving signature. \"\n- \"Use -1 for batch-polymorphic saving.\"))\n+ (\"For what batch size to prepare the serving signature. \"))\nflags.DEFINE_integer(\"num_epochs\", 3, \"For how many epochs to train.\")\nflags.DEFINE_boolean(\n\"generate_model\", True,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main_test.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main_test.py", "diff": "@@ -42,7 +42,7 @@ class SavedModelMainTest(tf_test_util.JaxToTfTestCase):\nmodel=model,\nserving_batch_size=serving_batch_size)\nfor model in [\"mnist_pure_jax\", \"mnist_flax\"]\n- for serving_batch_size in [1, -1])\n+ for serving_batch_size in [1])\ndef test_train_and_save_full(self,\nmodel=\"mnist_pure_jax\",\nserving_batch_size=1):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "diff": "@@ -197,6 +197,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ndef test_with_custom_vjp(self):\n\"\"\"Shape-polymorphic custom VJP.\"\"\"\n+ raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\n@jax.custom_vjp\ndef f(x):\n# x: [b1, b2, d1, d2] (a batch of matrices)\n@@ -287,6 +288,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nself.assertEqual((None, 3, 4), tuple(tf_grad.output_shapes[1][\"grad\"]))\ndef test_cond(self):\n+ raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\n# Test the primitive under conditional\ndef f(x, y):\n# x: f32[B, H], y : f32[H]\n@@ -301,6 +303,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ndef test_shape_error(self):\n\"\"\"Some of the examples from the README.\"\"\"\n+ raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\nwith self.assertRaisesRegex(TypeError,\nre.escape(\"add got incompatible shapes for broadcasting: (v,), (4,)\")):\nself.CheckShapePolymorphism(\n@@ -427,6 +430,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n\"\"\"Tests for primitives that take shape values as parameters.\"\"\"\ndef test_matmul(self):\n+ raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\ndef f_jax(x, y):\nreturn jnp.matmul(x, y)\n@@ -437,6 +441,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec([None, 8, None]))\ndef test_reshape(self):\n+ raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\ndef f_jax(x):\ny = jnp.sin(x)\nreturn y.reshape([2, -1])\n@@ -454,6 +459,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec([2, None]))\ndef test_reshape_compiled(self):\n+ raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\n# We compile the result of conversion, hence we need to involve the compiler\n# twice, but we trace only once with shape polymorphism\ntraced = False\n@@ -485,6 +491,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ndef test_add(self):\n+ raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\ndef f_jax(x, y):\nreturn jnp.add(x, y)\n@@ -500,6 +507,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(f_jax(x, y), f_tf(x, y))\ndef test_squeeze(self):\n+ raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\ndef f_jax(x):\nreturn jnp.squeeze(x, axis=1)\nx = np.ones((4, 1))\n@@ -525,6 +533,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec([None]))\ndef test_broadcast(self):\n+ raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\ndef f_jax(x):\nreturn jnp.broadcast_to(x, [x.shape[0], x.shape[0], x.shape[1]])\n" }, { "change_type": "MODIFY", "old_path": "tests/masking_test.py", "new_path": "tests/masking_test.py", "diff": "@@ -282,6 +282,7 @@ class MaskingTest(jtu.JaxTestCase):\njtu.rand_default(self.rng()))\ndef test_arithmetic(self):\n+ raise SkipTest(\"Failing after fixing Poly unsoundness #4878\")\n@partial(mask, in_shapes=['(n, m)', 'm'], out_shape='(n, m)')\ndef times(x, y):\nreturn x * y\n@@ -480,6 +481,7 @@ class MaskingTest(jtu.JaxTestCase):\n(((-1, -2, 2),), (5,)),\n(((-1, -2, 1), (1, 2, 2)), (4, 2))))\ndef test_pad(self, padding_config, shape):\n+ raise SkipTest(\"Failing after fixing Poly unsoundness #4878\")\ndef pad(x):\nreturn lax.pad(x, jnp.array(1., x.dtype), padding_config)\n@@ -524,6 +526,7 @@ class MaskingTest(jtu.JaxTestCase):\ndef test_conv(\nself, padding, lhs_dilation, dimension_numbers, lhs_perm,\nrhs_perm, out_perm):\n+ raise SkipTest(\"Failing after fixing Poly unsoundness #4878\")\ndef conv(lhs, rhs):\nreturn lax.conv_general_dilated(\nlhs, rhs, (1, 1), padding, lhs_dilation=lhs_dilation,\n@@ -571,6 +574,7 @@ class MaskingTest(jtu.JaxTestCase):\ndef test_conv_strided(\nself, padding, lhs_dilation, dimension_numbers, lhs_perm,\nrhs_perm, out_perm):\n+ raise SkipTest(\"Failing after fixing Poly unsoundness #4878\")\ndef conv(lhs, rhs):\nreturn lax.conv_general_dilated(\nlhs, rhs, (2, 1), padding, lhs_dilation=lhs_dilation,\n@@ -639,6 +643,7 @@ class MaskingTest(jtu.JaxTestCase):\n# self.check(lambda x: x[-2::-1], ['n'], dict(n=jnp.array([2, 3])), 'n+-1')\ndef test_lax_slice(self):\n+ raise SkipTest(\"Failing after fixing Poly unsoundness #4878\")\nself.check(lambda x: lax.slice(x, (1,), (x.shape[0],)), ['n'], 'n+-1',\n{'n': 2}, [(3,)], ['float_'], jtu.rand_default(self.rng()))\n# TODO self.check(lambda x: lax.slice(x, (x.shape[0] // 2,), (x.shape[0],)),\n@@ -648,6 +653,7 @@ class MaskingTest(jtu.JaxTestCase):\njtu.rand_default(self.rng()))\ndef test_reshape(self):\n+ raise SkipTest(\"Failing after fixing Poly unsoundness #4878\")\nself.check(lambda x: jnp.reshape(x, (x.shape[1], 2, 4, 1)),\n['1, n, 4, 2'], 'n, 2, 4, 1', dict(n=2), [(1, 3, 4, 2)],\n['float_'], jtu.rand_default(self.rng()))\n" } ]
Python
Apache License 2.0
google/jax
Disable the remaining failing tests, remove jax2tf documentation
260,411
17.11.2020 06:57:47
28,800
64022922bd18eacfcd9befd2e1810a80512f85ef
Fix float indices in lax.slice
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1650,6 +1650,7 @@ def _split(op, ary, indices_or_sections, axis=0):\n+ ((r + 1) * (part_size + 1) - 1)])\nelse:\nraise ValueError(\"array split does not result in an equal division\")\n+ split_indices = split_indices.astype(int)\nstarts, ends = [0] * ndim(ary), shape(ary)\n_subval = lambda x, i, v: subvals(x, [(i, v)])\nreturn [lax.slice(ary, _subval(starts, axis, start), _subval(ends, axis, end))\n" } ]
Python
Apache License 2.0
google/jax
Fix float indices in lax.slice
260,510
10.11.2020 15:57:19
28,800
590e629f10c0c5c1fe88930a19289c766d0517af
Add support for XLA variadic reduce
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -28,9 +28,11 @@ import jax\nfrom jax import core\nfrom jax import ad_util\nfrom jax import api\n+from jax import api_util\nfrom jax import linear_util as lu\nfrom jax import dtypes\nfrom jax import lazy\n+from jax import tree_util\nfrom jax.config import flags, config\nfrom jax.core import Primitive, _canonicalize_dimension\nfrom jax.abstract_arrays import (UnshapedArray, ShapedArray, ConcreteArray, array_types,\n@@ -42,7 +44,8 @@ from jax.interpreters import ad\nfrom jax.interpreters import invertible_ad as iad\nfrom jax.interpreters import batching\nfrom jax.interpreters import masking\n-from jax.util import cache, safe_zip, partial, prod, safe_map, canonicalize_axis\n+from jax.util import (cache, safe_zip, partial, prod, safe_map, canonicalize_axis,\n+ split_list)\nfrom jax.tree_util import tree_map\nfrom jax.lib import pytree\nfrom jax.lib import xla_bridge\n@@ -1088,19 +1091,30 @@ def argmax(operand: Array, axis: int,\nreturn argmax_p.bind(operand, axes=(axis,),\nindex_dtype=dtypes.canonicalize_dtype(index_dtype))\n-def reduce(operand: Array, init_value: Array, computation: Callable,\n+def reduce(operands: Array, init_values: Array, computation: Callable,\ndimensions: Sequence[int]) -> Array:\n\"\"\"Wraps XLA's `Reduce\n<https://www.tensorflow.org/xla/operation_semantics#reduce>`_\noperator.\n\"\"\"\n- monoid_reducer = _get_monoid_reducer(computation, init_value)\n+ flat_operands, operand_tree = tree_util.tree_flatten(operands)\n+ flat_init_values, init_value_tree = tree_util.tree_flatten(init_values)\n+ if operand_tree != init_value_tree:\n+ raise ValueError('Operands must have the same tree structure as init_values:'\n+ f' {operand_tree} vs. {init_value_tree}')\n+ if len(flat_operands) != len(flat_init_values):\n+ raise ValueError('Must have same total number of operands as init_values: '\n+ f' {len(flat_operands)} vs. {len(flat_init_values)}')\n+ monoid_reducer = _get_monoid_reducer(computation, flat_init_values)\nif monoid_reducer:\n- return monoid_reducer(operand, dimensions)\n+ return monoid_reducer(*flat_operands, dimensions)\nelse:\n- jaxpr, consts = _reduction_jaxpr(computation, _abstractify(init_value))\n- return reduce_p.bind(operand, init_value, computation=computation,\n+ flat_init_avals = safe_map(_abstractify, flat_init_values)\n+ jaxpr, consts, out_tree = _variadic_reduction_jaxpr(\n+ computation, tuple(flat_init_avals), init_value_tree)\n+ out = reduce_p.bind(*(flat_operands + flat_init_values), computation=computation,\njaxpr=jaxpr, consts=consts, dimensions=tuple(dimensions))\n+ return tree_util.tree_unflatten(out_tree, out)\n@cache()\ndef _reduction_jaxpr(computation, aval):\n@@ -1109,12 +1123,27 @@ def _reduction_jaxpr(computation, aval):\njaxpr, _, consts = pe.trace_to_jaxpr(comp, (pval, pval), instantiate=False)\nreturn jaxpr, consts\n-def _get_monoid_reducer(monoid_op: Callable, x: Array) -> Optional[Callable]:\n+@cache()\n+def _variadic_reduction_jaxpr(computation, flat_avals, aval_tree):\n+ avals = tree_util.tree_unflatten(aval_tree, flat_avals)\n+ flat_in_avals, in_tree = tree_util.tree_flatten((avals, avals))\n+ pvals = safe_map(pe.PartialVal.unknown, flat_in_avals)\n+ comp = lu.wrap_init(computation)\n+ flat_comp, out_tree = api_util.flatten_fun_nokwargs(comp, in_tree)\n+ jaxpr, _, consts = pe.trace_to_jaxpr(flat_comp, tuple(pvals),\n+ instantiate=False)\n+ return jaxpr, consts, out_tree()\n+\n+def _get_monoid_reducer(monoid_op: Callable, xs: Array) -> Optional[Callable]:\n+ if len(xs) != 1:\n+ return None\n+ x, = xs\naval = core.get_aval(x)\ndtype = _dtype(x)\nif (type(aval) is ConcreteArray) and aval.shape == ():\nif monoid_op is add:\n- return np.equal(aval.val, 0) and _reduce_sum\n+ return np.equal(aval.val, 0) and partial(\n+ _reduce_sum)\nif monoid_op is mul:\nreturn np.equal(aval.val, 1) and _reduce_prod\nelif monoid_op is bitwise_or and dtype == np.bool_:\n@@ -1939,8 +1968,10 @@ _input_dtype = lambda *args, **_: dtypes.canonicalize_dtype(args[0].dtype)\n_fixed_dtype = lambda dtype: lambda *args, **kwargs: dtypes.canonicalize_dtype(dtype)\n_complex_basetype = lambda dtype: np.abs(np.zeros((), dtype)).dtype\n-def standard_primitive(shape_rule, dtype_rule, name, translation_rule=None):\n+def standard_primitive(shape_rule, dtype_rule, name, translation_rule=None,\n+ multiple_results=False):\nprim = Primitive(name)\n+ prim.multiple_results = multiple_results\nprim.def_impl(partial(xla.apply_primitive, prim))\nprim.def_abstract_eval(partial(standard_abstract_eval, prim, shape_rule, dtype_rule))\nxla.translations[prim] = translation_rule or partial(standard_translate, name)\n@@ -1952,13 +1983,25 @@ def standard_abstract_eval(prim, shape_rule, dtype_rule, *args, **kwargs):\nleast_specialized = _max(\nmap(type, args), key=operator.attrgetter('array_abstraction_level'))\nif least_specialized is ConcreteArray:\n- return ConcreteArray(prim.impl(*[x.val for x in args], **kwargs))\n+ out_vals = prim.impl(*[x.val for x in args], **kwargs)\n+ if not prim.multiple_results:\n+ out_vals = [out_vals]\n+ out_avals = safe_map(ConcreteArray, out_vals)\nelif least_specialized is ShapedArray:\n- return ShapedArray(shape_rule(*args, **kwargs), dtype_rule(*args, **kwargs))\n+ shapes, dtypes = shape_rule(*args, **kwargs), dtype_rule(*args, **kwargs)\n+ if not prim.multiple_results:\n+ shapes, dtypes = [shapes], [dtypes]\n+ out_avals = safe_map(ShapedArray, shapes, dtypes)\nelif least_specialized is UnshapedArray:\n- return UnshapedArray(dtype_rule(*args, **kwargs))\n+ dtypes = dtype_rule(*args, **kwargs)\n+ if not prim.multiple_results:\n+ dtypes = [dtypes]\n+ out_avals = safe_map(UnshapedArray, dtypes)\nelse:\nraise TypeError(args, least_specialized)\n+ if not prim.multiple_results:\n+ return out_avals[0]\n+ return out_avals\ndef standard_translate(name, c, *args, **kwargs):\n@@ -4681,52 +4724,92 @@ batching.primitive_batchers[scatter_p] = (\npartial(_scatter_batching_rule, scatter))\n-def _reduce_shape_rule(operand, init_value, *, computation, jaxpr, consts,\n- dimensions):\n- return tuple(np.delete(operand.shape, dimensions))\n+def _reduce_shape_rule(*args, computation, jaxpr, consts, dimensions):\n+ operand_args, init_value_args = split_list(args, [len(args) // 2])\n+ if any(arg.shape != () for arg in init_value_args):\n+ init_value_shapes = [a.shape for a in init_value_args]\n+ raise ValueError(f'Found non-scalar init_value: {init_value_shapes}')\n+ return [\n+ tuple(np.delete(op_arg.shape, dimensions))\n+ for op_arg in operand_args\n+ ]\n+\n-def _reduce_translation_rule(c, operand, init_value, *, computation, jaxpr,\n+def _reduce_dtype_rule(*args, computation, jaxpr, consts, dimensions):\n+ _, init_value_args = split_list(args, [len(args) // 2])\n+ return [\n+ dtypes.canonicalize_dtype(in_arg.dtype)\n+ for in_arg in init_value_args\n+ ]\n+\n+\n+def _reduce_translation_rule(c, *values, computation, jaxpr,\nconsts, dimensions):\n+ operands, init_values = split_list(values, [len(values) // 2])\n+ if len(operands) == 1:\n+ init_value = init_values[0]\nxla_computation = _reduction_computation(c, jaxpr, consts, init_value)\n- return xops.Reduce(c, [operand], [init_value], xla_computation, dimensions)\n+ out = xops.Reduce(c, operands, init_values, xla_computation, dimensions)\n+ return xops.Tuple(c, (out,))\n+ xla_computation = _reduction_computation(c, jaxpr, consts, init_values, singleton=False)\n+ return xops.Reduce(c, operands, init_values, xla_computation, dimensions)\n-def _reduce_batch_rule(batched_args, batch_dims, *, computation, jaxpr, consts,\n- dimensions):\n- operand, init_value = batched_args\n- operand_bdim, init_value_bdim = batch_dims\n- if init_value_bdim is None:\n- assert operand_bdim is not None\n+\n+def _reduce_batch_rule(batched_args, batch_dims, *, computation, jaxpr,\n+ consts, dimensions):\n+ num_operands = len(batched_args) // 2\n+ operands, init_values = split_list(batched_args, [num_operands])\n+ operand_bdims, init_value_bdims = split_list(batch_dims, [num_operands])\n+ if all(init_value_bdim is None for init_value_bdim in init_value_bdims):\n+ # Assume all batch dims are the same for each of the operands\n+ assert all(operand_bdim is not None for operand_bdim in operand_bdims)\n+ assert all(operand_bdim == operand_bdims[0] for operand_bdim in operand_bdims)\n+ # TODO(sharadmv): handle the case when batch dims are different across\n+ # operands or when some are unbatched\n+ operand_bdim = operand_bdims[0]\nnew_dimensions = [d + bool(d >= operand_bdim) for d in dimensions]\nnew_operand_bdim = operand_bdim - int(np.sum(np.less(dimensions, operand_bdim)))\n- return reduce(operand, init_value, computation, new_dimensions), new_operand_bdim\n+ new_operand_bdims = [new_operand_bdim] * num_operands\n+ return reduce_p.bind(*(operands + init_values),\n+ computation=computation, dimensions=tuple(new_dimensions),\n+ consts=consts,\n+ jaxpr=jaxpr), new_operand_bdims\nelse:\nraise NotImplementedError # loop and stack\n-def _reduction_computation(c, jaxpr, consts, init_value):\n- shape = c.get_shape(init_value)\n+\n+def _reduction_computation(c, jaxpr, consts, init_values, singleton=True):\n+ if singleton:\n+ init_values = [init_values]\n+ shapes = safe_map(c.get_shape, init_values + init_values)\naxis_env = xla.AxisEnv(1, (), (), None) # no parallel primitives inside reductions\nsubc = xla_bridge.make_computation_builder(\"reduction_computation\")\nassert len(consts) == 0, \"Reduction computations cannot have constants\"\n- args = [xb.parameter(subc, 0, shape), xb.parameter(subc, 1, shape)]\n- out, = xla.jaxpr_subcomp(subc, jaxpr, None, axis_env, consts, '', *args)\n- return subc.build(out)\n+ args = [xb.parameter(subc, i, shape) for i, shape in enumerate(shapes)]\n+ out_nodes = xla.jaxpr_subcomp(subc, jaxpr, None, axis_env, consts, '', *args)\n+ if singleton:\n+ return subc.build(out_nodes[0])\n+ out_nodes = xops.Tuple(subc, out_nodes)\n+ return subc.build(out_nodes)\ndef _masking_defreducer(prim, identity):\nmasking.masking_rules[prim] = partial(_reducer_masking_rule, prim, identity)\ndef _reducer_masking_rule(prim, identity, padded_vals, logical_shapes,\n- axes, input_shape=None):\n+ axes, input_shape=None, **reduce_kwargs):\n(padded_val,), (logical_shape,) = padded_vals, logical_shapes\npadded_shape = masking.padded_shape_as_value(padded_val.shape)\nmasks = [broadcasted_iota(np.int32, padded_shape, i) < d\nfor i, d in enumerate(logical_shape) if i in axes]\nmask = _reduce(operator.and_, masks)\nmasked_val = select(mask, padded_val, identity(padded_shape, padded_val.dtype))\n- bind = prim.bind if input_shape is None else partial(prim.bind, input_shape=padded_shape)\n+ prim_bind = partial(prim.bind, **reduce_kwargs)\n+ bind = prim_bind if input_shape is None else partial(prim_bind, input_shape=padded_shape)\nreturn bind(masked_val, axes=axes)\n-reduce_p = standard_primitive(_reduce_shape_rule, _input_dtype, 'reduce',\n- _reduce_translation_rule)\n+reduce_p = standard_primitive(_reduce_shape_rule, _reduce_dtype_rule,\n+ 'reduce', translation_rule=_reduce_translation_rule,\n+ multiple_results=True)\nbatching.primitive_batchers[reduce_p] = _reduce_batch_rule\n@@ -4740,7 +4823,8 @@ def _reduce_sum_shape_rule(operand, *, axes):\nreturn _reduce_op_shape_rule(operand, axes=axes)\ndef _reduce_sum_translation_rule(c, operand, *, axes):\n- dtype = c.get_shape(operand).numpy_dtype()\n+ shape = c.get_shape(operand)\n+ dtype = shape.numpy_dtype()\nscalar = ShapedArray((), dtype)\nreturn xops.Reduce(c, [operand], [xb.constant(c, np.array(0, dtype))],\nxla.primitive_subcomputation(add_p, scalar, scalar),\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -29,6 +29,7 @@ from jax import core\nfrom jax import dtypes\nfrom jax import lax\nfrom jax import test_util as jtu\n+from jax import tree_util\nfrom jax import lax_reference\nfrom jax.test_util import check_grads\nimport jax.util\n@@ -2238,6 +2239,31 @@ class LaxTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(TypeError, msg):\nlax.reduce_window(**args)\n+ def test_reduce_correctly_works_with_pytrees(self):\n+ operands = {'x': [np.ones(5), np.arange(5)]}\n+ init_values = {'x': [0., 0]}\n+ result = lax.reduce(operands, init_values,\n+ lambda x, y: tree_util.tree_multimap(lax.add, x, y),\n+ [0])\n+ self.assertDictEqual(result, {'x': [5., 10.]})\n+\n+ def test_reduce_with_mismatched_pytrees_errors(self):\n+ operands = {'x': np.ones(5)}\n+ bad_init_values = {'y': 0.}\n+\n+ with self.assertRaisesRegex(ValueError, 'Operands must have the same '\n+ 'tree structure as init_values'):\n+ lax.reduce(operands, bad_init_values,\n+ lambda x, y: dict(x=x['x'] + y['x']), [0])\n+\n+ def test_reduce_with_nonscalar_inits_errors(self):\n+ operands = {'x': np.ones(5)}\n+ bad_init_values = {'x': np.ones(5)}\n+\n+ with self.assertRaisesRegex(ValueError, 'Found non-scalar init_value'):\n+ lax.reduce(operands, bad_init_values,\n+ lambda x, y: dict(x=x['x'] + y['x']), [0])\n+\ndef test_select_jvp_complexity(self):\nif not config.omnistaging_enabled:\nraise SkipTest(\"test requires omnistaging\")\n" } ]
Python
Apache License 2.0
google/jax
Add support for XLA variadic reduce
260,684
18.11.2020 16:18:43
28,800
f54e531cc40c4314156bfa02cb10f2635dbc9010
Add vector-valued gradient example.
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/quickstart.ipynb", "new_path": "docs/notebooks/quickstart.ipynb", "diff": "\"from jax import grad, jit, vmap\\n\",\n\"from jax import random\"\n],\n- \"execution_count\": 0,\n+ \"execution_count\": 5,\n\"outputs\": []\n},\n{\n\"execution_count\": 0,\n\"outputs\": []\n},\n+ {\n+ \"source\": [\n+ \"If you're interested in taking vector-valued gradients (like `tf.gradients`):\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": 26,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"from jax import vjp\\n\",\n+ \"def vgrad(f, x):\\n\",\n+ \" y, vjp_fn = vjp(f, x)\\n\",\n+ \" return vjp_fn(jnp.ones(y.shape))[0]\\n\",\n+ \"\\n\",\n+ \"print(vgrad(lambda x: 3*x**2, jnp.ones((2, 2))))\"\n+ ]\n+ },\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {\n" } ]
Python
Apache License 2.0
google/jax
Add vector-valued gradient example.
260,287
19.11.2020 11:36:35
0
b55b44d39414b3650aff31ce2f61e35da6bfb9bd
Remove devices from xla.AxisEnv In most cases they were not even filled in, and they are not used anywhere.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -4809,7 +4809,7 @@ def _reduction_computation(c, jaxpr, consts, init_values, singleton=True):\nif singleton:\ninit_values = [init_values]\nshapes = safe_map(c.get_shape, init_values + init_values)\n- axis_env = xla.AxisEnv(1, (), (), None) # no parallel primitives inside reductions\n+ axis_env = xla.AxisEnv(1, (), ()) # no parallel primitives inside reductions\nsubc = xla_bridge.make_computation_builder(\"reduction_computation\")\nassert len(consts) == 0, \"Reduction computations cannot have constants\"\nargs = [xb.parameter(subc, i, shape) for i, shape in enumerate(shapes)]\n" }, { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -564,11 +564,11 @@ def xla_computation(fun: Callable,\ndef make_axis_env(nreps):\nif axis_env is None:\n- return xla.AxisEnv(nreps, (), (), None)\n+ return xla.AxisEnv(nreps, (), ())\nelse:\nnreps = nreps * prod(size for name, size in axis_env)\nnames, sizes = unzip2(axis_env)\n- return xla.AxisEnv(nreps, names, sizes, None)\n+ return xla.AxisEnv(nreps, names, sizes)\ndef abstractify(x):\nreturn ShapedArray(np.shape(x), dtypes.result_type(x))\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -652,7 +652,7 @@ def parallel_callable(fun: lu.WrappedFun,\nf\"args {avals}. (num_replicas={num_global_replicas} \"\nf\"num_partitions={num_partitions}\")\n- axis_env = xla.AxisEnv(num_global_replicas, (axis_name,), (global_axis_size,), devices)\n+ axis_env = xla.AxisEnv(num_global_replicas, (axis_name,), (global_axis_size,))\ntuple_args = len(sharded_avals) > 100 # pass long arg lists as tuple for TPU\n@@ -1112,7 +1112,7 @@ def _soft_pmap_callable(fun, axis_name, axis_size, in_axes, *avals):\nchunked_avals = [core.unmapped_aval(chunk_size, in_axis, aval) if in_axis is not None else aval\nfor in_axis, aval in zip(in_axes, mapped_avals)]\nxla_args, _ = xla._xla_callable_args(c, chunked_avals, tuple_args)\n- axis_env = xla.AxisEnv(num_devices, (axis_name,), (num_devices,), None)\n+ axis_env = xla.AxisEnv(num_devices, (axis_name,), (num_devices,))\nout_nodes = xla.jaxpr_subcomp(c, jaxpr, None, axis_env, xla_consts,\n'soft_pmap', *xla_args)\nbuilt = c.Build(xops.Tuple(c, out_nodes))\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/sharded_jit.py", "new_path": "jax/interpreters/sharded_jit.py", "diff": "@@ -152,7 +152,7 @@ def _sharded_callable(\nc = xb.make_computation_builder(\"spjit_{}\".format(fun.__name__))\nxla_consts = _map(partial(xb.constant, c), consts)\nxla_args = _xla_sharded_args(c, global_abstract_args, in_parts)\n- axis_env = xla.AxisEnv(nrep, (), (), None)\n+ axis_env = xla.AxisEnv(nrep, (), ())\nout_nodes = xla.jaxpr_subcomp(\nc, jaxpr, None, axis_env, xla_consts,\nextend_name_stack(wrap_name(name, \"sharded_jit\")), *xla_args)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "# limitations under the License.\n-from collections import defaultdict, deque, namedtuple\n+from collections import defaultdict, deque\nimport itertools as it\nimport operator as op\n-from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Tuple\n+from typing import (Any, Callable, Dict, List, Optional, Sequence, Set, Type,\n+ Tuple, NamedTuple)\nfrom warnings import warn\nfrom absl import logging\n@@ -275,7 +276,7 @@ def xla_primitive_callable(prim, *arg_specs: Tuple[core.AbstractValue,\nf\"compiling a primitive computation `{prim}` that requires {nreps} \"\nf\"replicas, but only {xb.device_count(backend)} XLA devices are \"\nf\"available on backend {backend.platform}.\")\n- built_c = primitive_computation(prim, AxisEnv(nreps, (), (), None), backend,\n+ built_c = primitive_computation(prim, AxisEnv(nreps, (), ()), backend,\ntuple_args, *avals, **params)\noptions = xb.get_compile_options(\nnum_replicas=nreps,\n@@ -337,7 +338,7 @@ def primitive_computation(prim, axis_env, backend, tuple_args, *avals, **params)\nraise RuntimeError(msg) from e\ndef primitive_subcomputation(prim, *avals, **params):\n- axis_env = AxisEnv(1, (), (), None)\n+ axis_env = AxisEnv(1, (), ())\nreturn primitive_computation(prim, axis_env, None, False, *avals, **params)\ndef backend_compile(backend, built_c, options):\n@@ -478,10 +479,14 @@ def check_backend_params(params, outer_backend):\nreturn {k: params[k] for k in params if k != 'backend'}\n-AxisEnv = namedtuple('AxisEnv', ['nreps', 'names', 'sizes', 'devices'])\n+class AxisEnv(NamedTuple):\n+ \"\"\"Represents a pmap mesh (only along the replica axes).\"\"\"\n+ nreps: int\n+ names: Tuple[Any, ...]\n+ sizes: Tuple[int, ...]\n-def extend_axis_env(env, name, size):\n- return AxisEnv(env.nreps, env.names + (name,), env.sizes + (size,), env.devices)\n+def extend_axis_env(env: AxisEnv, name, size: int):\n+ return AxisEnv(env.nreps, env.names + (name,), env.sizes + (size,))\ndef axis_read(axis_env, axis_name):\ntry:\n@@ -489,21 +494,29 @@ def axis_read(axis_env, axis_name):\nexcept ValueError:\nraise NameError(\"unbound axis name: {}\".format(axis_name)) from None\n-def axis_groups(axis_env, name):\n- if isinstance(name, (list, tuple)):\n+def axis_groups(axis_env: AxisEnv, name):\n+ if not isinstance(name, (list, tuple)):\n+ name = (name,)\nmesh_axes = tuple(unsafe_map(partial(axis_read, axis_env), name))\n- else:\n- mesh_axes = (axis_read(axis_env, name),)\n- return _axis_groups(axis_env.nreps, axis_env.sizes, mesh_axes)\n-\n-def _axis_groups(nrep, mesh_spec, mesh_axes):\n- trailing_size, ragged = divmod(nrep, prod(mesh_spec))\n+ trailing_size, ragged = divmod(axis_env.nreps, prod(axis_env.sizes))\nassert not ragged\n- full_spec = list(mesh_spec) + [trailing_size]\n- iota = np.arange(prod(full_spec)).reshape(full_spec)\n+ mesh_spec = axis_env.sizes + (trailing_size,)\n+ return _axis_groups(mesh_spec, mesh_axes)\n+\n+def _axis_groups(mesh_spec, mesh_axes):\n+ \"\"\"Computes replica group ids for a collective performed over a subset of the mesh.\n+\n+ Arguments:\n+ mesh_spec: A sequence of integers representing the mesh shape.\n+ mesh_axes: A sequence of integers between 0 and `len(mesh_spec)` (exclusive)\n+ indicating over which axes the collective is performed.\n+ Returns:\n+ A tuple of replica groups (i.e. tuples containing replica ids).\n+ \"\"\"\n+ iota = np.arange(prod(mesh_spec)).reshape(mesh_spec)\ngroups = np.reshape(\nnp.moveaxis(iota, mesh_axes, np.arange(len(mesh_axes))),\n- (prod(np.take(full_spec, mesh_axes)), -1))\n+ (prod(np.take(mesh_spec, mesh_axes)), -1))\nreturn tuple(unsafe_map(tuple, groups.T))\ndef jaxpr_replicas(jaxpr):\n@@ -686,7 +699,7 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\nxla_consts = _xla_consts(c, consts)\nxla_args, donated_invars = _xla_callable_args(c, abstract_args, tuple_args, donated_invars=donated_invars)\nout_nodes = jaxpr_subcomp(\n- c, jaxpr, backend, AxisEnv(nreps, (), (), None), xla_consts,\n+ c, jaxpr, backend, AxisEnv(nreps, (), ()), xla_consts,\nextend_name_stack(wrap_name(name, 'jit')), *xla_args)\nout_tuple = xops.Tuple(c, out_nodes)\nbackend = xb.get_backend(backend)\n@@ -921,7 +934,7 @@ def lower_fun(fun, multiple_results, parallel=False):\naxis_env = params.pop('axis_env')\ndel params['platform']\nelse:\n- axis_env = AxisEnv(1, (), (), None)\n+ axis_env = AxisEnv(1, (), ())\nwrapped_fun = lu.wrap_init(fun, params)\nif not multiple_results:\nwrapped_fun = _tuple_output(wrapped_fun)\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -635,7 +635,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected)\ndef testAxisGroups(self):\n- axis_env = xla.AxisEnv(8, ('i', 'j'), (4, 2), None)\n+ axis_env = xla.AxisEnv(8, ('i', 'j'), (4, 2))\ngroups = xla.axis_groups(axis_env, 'i')\nself.assertEqual(groups, ((0, 2, 4, 6), (1, 3, 5, 7)))\n" } ]
Python
Apache License 2.0
google/jax
Remove devices from xla.AxisEnv In most cases they were not even filled in, and they are not used anywhere.
260,287
20.11.2020 13:51:17
0
94fcd7f2ab3af8eeb881bb2b3d446a9fbc1a8ae1
Use taggedtuple instead of namedtuple when defining ShardingSpecs Because namedtuples don't take the class into account when comparing for equality!
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -34,7 +34,7 @@ import itertools as it\nimport operator as op\nimport threading\nfrom typing import (Any, Callable, Dict, List, Optional, Sequence, Set, Tuple,\n- Type, Union, Iterable, no_type_check, NamedTuple)\n+ Type, Union, Iterable, no_type_check, NamedTuple, TYPE_CHECKING)\nfrom absl import logging\nimport numpy as np\n@@ -47,7 +47,7 @@ from ..abstract_arrays import array_types\nfrom ..core import ConcreteArray, ShapedArray, Var, Literal\nfrom ..util import (partial, unzip2, unzip3, prod, safe_map, safe_zip,\nextend_name_stack, wrap_name, assert_unreachable,\n- tuple_insert, tuple_delete)\n+ tuple_insert, tuple_delete, taggedtuple)\nfrom ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\nfrom ..tree_util import tree_flatten, tree_map\n@@ -67,11 +67,15 @@ unsafe_map, map = map, safe_map # type: ignore\nIndex = Union[int, slice, Tuple[Union[int, slice], ...]]\n+# mypy is very unhappy about taggedtuple\n+if TYPE_CHECKING:\nclass Unstacked(NamedTuple):\nsize: int\n-\nclass Chunked(NamedTuple):\nchunks: int\n+else:\n+ Unstacked = taggedtuple('Unstacked', ('size',))\n+ Chunked = taggedtuple('Chunked', ('chunks',))\n\"\"\"\nRepresents all the ways we can shard a dimension.\n@@ -83,11 +87,15 @@ Represents all the ways we can shard a dimension.\n\"\"\"\nAvalDimSharding = Union[Unstacked, Chunked, None]\n+# mypy is very unhappy about taggedtuple\n+if TYPE_CHECKING:\nclass ShardedAxis(NamedTuple):\naxis: int\n-\nclass Replicated(NamedTuple):\nreplicas: int\n+else:\n+ ShardedAxis = taggedtuple('ShardedAxis', ('axis',))\n+ Replicated = taggedtuple('Replicated', ('replicas',))\n\"\"\"\nAssigns sharded axes to mesh dimensions.\n" }, { "change_type": "MODIFY", "old_path": "jax/lazy.py", "new_path": "jax/lazy.py", "diff": "from collections import namedtuple\nimport functools\nimport operator as op\n-from typing import Any, Callable, Optional, Sequence\n+from typing import Optional, Sequence\nimport numpy as np\n-from .util import safe_map, safe_zip, unzip2, subvals\n+from .util import safe_map, safe_zip, unzip2, subvals, taggedtuple\nfrom .lib import xla_bridge as xb\nfrom .lib import xla_client as xc\n@@ -33,21 +33,6 @@ map = safe_map\nzip = safe_zip\n-### util\n-\n-# TODO(mattjj): replace with dataclass when Python 2 support is removed\n-def taggedtuple(name, fields) -> Callable[..., Any]:\n- \"\"\"Lightweight version of namedtuple where equality depends on the type.\"\"\"\n- def __new__(cls, *xs):\n- return tuple.__new__(cls, (cls,) + xs)\n- def __str__(self):\n- return '{}{}'.format(name, tuple.__str__(self[1:]))\n- class_namespace = {'__new__' : __new__, '__str__': __str__}\n- for i, f in enumerate(fields):\n- class_namespace[f] = property(op.itemgetter(i+1)) # type: ignore\n- return type(name, (tuple,), class_namespace)\n-\n-\n### lazy sublanguage\n# There are two components to a LazyExpr: an input and a reindexing\n" }, { "change_type": "MODIFY", "old_path": "jax/util.py", "new_path": "jax/util.py", "diff": "@@ -17,6 +17,7 @@ import functools\nimport itertools as it\nimport operator\nimport types\n+from typing import Any, Callable\nimport numpy as np\n@@ -291,3 +292,15 @@ def tuple_insert(t, idx, val):\ndef tuple_delete(t, idx):\nreturn t[:idx] + t[idx + 1:]\n+\n+# TODO(mattjj): replace with dataclass when Python 2 support is removed\n+def taggedtuple(name, fields) -> Callable[..., Any]:\n+ \"\"\"Lightweight version of namedtuple where equality depends on the type.\"\"\"\n+ def __new__(cls, *xs):\n+ return tuple.__new__(cls, (cls,) + xs)\n+ def __str__(self):\n+ return '{}{}'.format(name, tuple.__str__(self[1:]))\n+ class_namespace = {'__new__' : __new__, '__str__': __str__}\n+ for i, f in enumerate(fields):\n+ class_namespace[f] = property(operator.itemgetter(i+1)) # type: ignore\n+ return type(name, (tuple,), class_namespace)\n" } ]
Python
Apache License 2.0
google/jax
Use taggedtuple instead of namedtuple when defining ShardingSpecs Because namedtuples don't take the class into account when comparing for equality!
260,677
24.11.2020 16:57:35
0
8d1daba901468093ce41850501c4805ba7a17f5f
Add complex types to gradient of slogdet
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/linalg.py", "new_path": "jax/_src/numpy/linalg.py", "diff": "@@ -139,10 +139,13 @@ def slogdet(a):\ndef _slogdet_jvp(primals, tangents):\nx, = primals\ng, = tangents\n- if jnp.issubdtype(jnp._dtype(x), jnp.complexfloating):\n- raise NotImplementedError # TODO(pfau): make this work for complex types\nsign, ans = slogdet(x)\n- sign_dot, ans_dot = jnp.zeros_like(sign), jnp.trace(solve(x, g), axis1=-1, axis2=-2)\n+ ans_dot = jnp.trace(solve(x, g), axis1=-1, axis2=-2)\n+ if jnp.issubdtype(jnp._dtype(x), jnp.complexfloating):\n+ sign_dot = (ans_dot - np.real(ans_dot)) * sign\n+ ans_dot = np.real(ans_dot)\n+ else:\n+ sign_dot = jnp.zeros_like(sign)\nreturn (sign, ans), (sign_dot, ans_dot)\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -198,7 +198,7 @@ class NumpyLinalgTest(jtu.JaxTestCase):\n\"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n\"shape\": shape, \"dtype\": dtype, \"rng_factory\": rng_factory}\nfor shape in [(1, 1), (4, 4), (5, 5), (2, 7, 7)]\n- for dtype in float_types\n+ for dtype in float_types + complex_types\nfor rng_factory in [jtu.rand_default]))\n@jtu.skip_on_devices(\"tpu\")\n@jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n" } ]
Python
Apache License 2.0
google/jax
Add complex types to gradient of slogdet
260,287
19.11.2020 18:22:35
0
c5433b0e4ec806fbad11a728d6b12502240ec3f1
Make xmap into a primitive Add a compilation cache. Also make sure that it raises a clear error when you try to use it with other transforms. Also, add a bunch of checks to make sure that the arguments are valid.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/general_map.py", "new_path": "jax/experimental/general_map.py", "diff": "@@ -16,6 +16,7 @@ import enum\nimport threading\nimport contextlib\nimport numpy as np\n+import itertools as it\nfrom collections import namedtuple, OrderedDict\nfrom typing import Callable, Iterable, List, Tuple, Optional, Dict, Any, Set\nfrom warnings import warn\n@@ -26,29 +27,56 @@ from .. import numpy as jnp\nfrom .. import core\nfrom .. import linear_util as lu\nfrom ..api import _mapped_axis_size, _check_callable, _check_arg\n-from ..tree_util import tree_flatten, tree_unflatten\n-from ..api_util import flatten_fun\n+from ..tree_util import tree_flatten, tree_unflatten, tree_leaves\n+from ..api_util import flatten_fun, flatten_fun_nokwargs, flatten_axes\nfrom ..interpreters import partial_eval as pe\nfrom ..interpreters import batching\nfrom ..interpreters import pxla\nfrom ..util import safe_map, safe_zip, curry\n-map = safe_map\n+map, unsafe_map = safe_map, map\nzip = safe_zip\n-# Multi-dimensional generalized map\n+class FrozenDict: # dataclasses might remove some boilerplate here\n+ def __init__(self, *args, **kwargs):\n+ self.contents = dict(*args, **kwargs)\n+\n+ allowed_methods = {'items', 'values', 'keys', 'get'}\n+ def __getattr__(self, name):\n+ if name in self.allowed_methods:\n+ return getattr(self.contents, name)\n+ raise AttributeError(name)\n+\n+ def __iter__(self):\n+ return self.contents.__iter__()\n+\n+ def __len__(self):\n+ return self.contents.__len__()\n+\n+ def __getitem__(self, name):\n+ return self.contents.__getitem__(name)\n+\n+ def __eq__(self, other):\n+ return isinstance(other, FrozenDict) and self.contents == other.contents\n+\n+ def __hash__(self):\n+ return hash(tuple(self.contents.items()))\n-# TODO: Use a more concrete type annotation (we need __eq__ and __hash__)\n-AxisName = Any\n-ResourceAxisName = Any\n+# Multi-dimensional generalized map\n+AxisName = core.AxisName\n+ResourceAxisName = AxisName # Different name just for documentation purposes\nMesh = pxla.Mesh\n# TODO: Support sequential mapping\n-class ResourceEnv(threading.local):\n- def __init__(self):\n- self.physical_mesh : Mesh = Mesh(np.empty((), dtype=object), ())\n- self.fake_resources : Dict[ResourceAxisName, int] = {}\n+class ResourceEnv:\n+ __slots__ = ('physical_mesh', 'fake_resources')\n+ physical_mesh: Mesh\n+ fake_resources: FrozenDict\n+\n+ def __init__(self, physical_mesh: Mesh, fake_resources: FrozenDict):\n+ super().__setattr__('physical_mesh', physical_mesh)\n+ super().__setattr__('fake_resources', fake_resources)\n@property\ndef physical_resource_axes(self) -> Set[ResourceAxisName]:\n@@ -68,26 +96,40 @@ class ResourceEnv(threading.local):\nshape.update((name, size) for name, size in self.fake_resources.items())\nreturn shape\n-# TODO: Make this thread local\n-thread_resource_env = ResourceEnv()\n+ def __setattr__(self, name, value):\n+ raise RuntimeError(\"ResourceEnv is immutable!\")\n+\n+ def __delattr__(self):\n+ raise RuntimeError(\"ResourceEnv is immutable!\")\n+\n+ def __eq__(self, other):\n+ return (type(other) is ResourceEnv and\n+ self.physical_mesh == other.physical_mesh and\n+ self.fake_resources == other.fake_resources)\n+\n+ def __hash__(self):\n+ return hash((self.physical_mesh, self.fake_resources))\n+\n+thread_resources = threading.local()\n+thread_resources.env = ResourceEnv(Mesh(np.empty((), dtype=object), ()), FrozenDict())\n@contextlib.contextmanager\ndef fake_resources(**axes):\n- old_axes = thread_resource_env.fake_resources\n- thread_resource_env.fake_resources = axes\n+ old_env = thread_resources.env\n+ thread_resources.env = ResourceEnv(old_env.physical_mesh, FrozenDict(axes))\ntry:\nyield\nfinally:\n- thread_resource_env.axes = old_axes\n+ thread_resources.env = old_env\n@contextlib.contextmanager\ndef mesh(*args, **kwargs):\n- old = thread_resource_env.physical_mesh\n- thread_resource_env.physical_mesh = Mesh(*args, **kwargs)\n+ old_env = thread_resources.env\n+ thread_resources.env = ResourceEnv(Mesh(*args, **kwargs), old_env.fake_resources)\ntry:\nyield\nfinally:\n- thread_resource_env.physical_mesh = old\n+ thread_resources.env = old_env\n_next_resource_id = 0\nclass UniqueResourceName:\n@@ -103,41 +145,107 @@ def fresh_resource_name():\n# This is really a Dict[AxisName, int], but we don't define a\n# pytree instance for it, so that it is treated as a leaf.\n-class AxisNamePos(dict):\n+class AxisNamePos(FrozenDict):\npass\nA = AxisNamePos\n+\n# TODO: Some syntactic sugar to make the API more usable in a single-axis case?\n# TODO: Are the resource axes scoped lexically or dynamically? Dynamically for now!\ndef xmap(fun: Callable,\nin_axes, # PyTree[AxisNamePos]\nout_axes, # PyTree[AxisNamePos],\n- schedule: Iterable[Tuple[AxisName, ResourceAxisName]]):\n+ schedule: Iterable[Tuple[AxisName, ResourceAxisName]],\n+ backend: Optional[str] = None):\nwarn(\"xmap is an experimental feature and probably has bugs!\")\n_check_callable(fun)\n- def fun_mapped(*args, **kwargs):\n+ frozen_schedule = tuple(tuple(x) for x in schedule)\n+\n+ if isinstance(in_axes, list):\n+ # To be a tree prefix of the positional args tuple, in_axes can never be a\n+ # list: if in_axes is not a leaf, it must be a tuple of trees. However,\n+ # in cases like these users expect tuples and lists to be treated\n+ # essentially interchangeably, so we canonicalize lists to tuples here\n+ # rather than raising an error. https://github.com/google/jax/issues/2367\n+ in_axes = tuple(in_axes)\n+\n+ in_axes_entries = tree_leaves(in_axes)\n+ out_axes_entries = tree_leaves(out_axes)\n+ # Check that {in|out}_axes have the right types, and don't use the same positional axis twice\n+ if not all(isinstance(x, A) for x in in_axes_entries):\n+ raise TypeError(f\"xmap in_axes must be AxisNamePos (A) instances or (nested) \"\n+ f\"containers with those types as leaves, but got {in_axes}\")\n+ if not all(isinstance(x, A) for x in out_axes_entries):\n+ raise TypeError(f\"xmap out_axes must be AxisNamePos (A) instances or (nested) \"\n+ f\"containers with those types as leaves, but got {in_axes}\")\n+ for x in in_axes_entries:\n+ if len(set(x.values())) != len(x):\n+ raise ValueError(f\"Positional dimension indices should be unique within each \"\n+ f\"in_axes dictionary, but one of the entries is: {x}\")\n+ for x in out_axes_entries:\n+ if len(set(x.values())) != len(x):\n+ raise ValueError(f\"Positional dimension indices should be unique within each \"\n+ f\"in_axes dictionary, but one of the entries is: {x}\")\n+\n+ in_axes_names = set(it.chain(*(spec.keys() for spec in in_axes_entries)))\n+ scheduled_axes = set(x[0] for x in frozen_schedule)\n+ if scheduled_axes != in_axes_names:\n+ raise ValueError(\"The set of axes names appearing in in_axes has to equal the \"\n+ \"set of scheduled axes, but {in_axes_names} != {scheduled_axes}\")\n+\n+ necessary_resources = set(x[1] for x in frozen_schedule if x[1] != 'vectorize')\n+ if len(set(frozen_schedule)) != len(frozen_schedule):\n+ raise ValueError(f\"xmap schedule contains duplicate entries: {frozen_schedule}\")\n+\n+ def fun_mapped(*args):\n# Putting this outside of fun_mapped would make resources lexically scoped\n- resource_env = thread_resource_env\n+ resource_env = thread_resources.env\n+ available_resources = set(resource_env.shape.keys())\n- args_flat, in_tree = tree_flatten((args, kwargs))\n+ if necessary_resources > available_resources:\n+ raise ValueError(f\"In-scope resources are insufficient to execute the \"\n+ f\"xmapped function. The missing resources are: \"\n+ f\"{necessary_resources - available_resources}\")\n+\n+ args_flat, in_tree = tree_flatten(args)\nfor arg in args_flat: _check_arg(arg)\n+ fun_flat, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\n# TODO: Check that:\n- # - every scheduled axis name appears in at least one input\n- # - every used resource axis name appears in the resource env\n- # - every axis name is scheduled to a single resource axis only once\n- # - every out axis has a distinct index\n# - two axes mapped to the same resource never coincide (even inside f)\n- in_axes_flat, in_axes_tree = tree_flatten(in_axes)\n- # TODO: Verify that in_axes are equal, or better expand their prefix\n- # assert in_axes_tree == in_tree\n+ in_axes_flat = flatten_axes(\"xmap in_axes\", in_tree, in_axes)\nout_axes_flat, out_axes_tree = tree_flatten(out_axes)\n# TODO: Verify that out_axes are equal, or better expand their prefix\n# assert out_axes_tree == out_tree\n-\naxis_sizes = _get_axis_sizes(args_flat, in_axes_flat)\n- jaxpr, out_tree = _trace_mapped_jaxpr(fun, args_flat, in_axes_flat, axis_sizes, in_tree)\n+ out_flat = xmap_p.bind(\n+ fun_flat, *args_flat,\n+ in_axes=tuple(in_axes_flat),\n+ out_axes=tuple(out_axes_flat),\n+ axis_sizes=FrozenDict(axis_sizes),\n+ schedule=frozen_schedule,\n+ resource_env=resource_env,\n+ backend=backend)\n+ return tree_unflatten(out_tree(), out_flat)\n+\n+ return fun_mapped\n+\n+def xmap_impl(fun: lu.WrappedFun, *args, in_axes, out_axes, axis_sizes, schedule, resource_env, backend):\n+ in_avals = [core.raise_to_shaped(core.get_aval(arg)) for arg in args]\n+ return make_xmap_callable(fun, in_axes, out_axes, axis_sizes, schedule,\n+ resource_env, backend, *in_avals)(*args)\n+\n+@lu.cache\n+def make_xmap_callable(fun: lu.WrappedFun,\n+ in_axes, out_axes, axis_sizes,\n+ schedule, resource_env, backend,\n+ *in_avals):\n+ mapped_in_avals = [_delete_aval_axes(aval, in_axes)\n+ for aval, in_axes in zip(in_avals, in_axes)]\n+ with core.extend_axis_env_nd(axis_sizes.items()):\n+ raw_jaxpr, _, consts = pe.trace_to_jaxpr_final(fun, mapped_in_avals)\n+ jaxpr = core.ClosedJaxpr(raw_jaxpr, consts)\n# TODO: The order of maps should be derived from the schedule, not from the\n# resource env. This doesn't really matter for as long as we only support\n@@ -160,10 +268,8 @@ def xmap(fun: Callable,\nresource = fresh_resource_name()\nvectorized[axis] = resource\nelif resource in resource_env.physical_resource_axes:\n- # TODO: Make sure that axis was not in the set?\nphysical_resource_map.setdefault(resource, set()).add(axis)\nelif resource in resource_env.fake_resource_axes:\n- # TODO: Make sure that axis was not in the set?\nfake_resource_map.setdefault(resource, set()).add(axis)\nelse:\nraise ValueError(f\"Mapping axis {axis} to an undefined resource axis {resource}. \"\n@@ -174,23 +280,22 @@ def xmap(fun: Callable,\njaxpr = jaxpr.map_jaxpr(partial(subst_axis_names, axis_subst=axis_subst_t))\nf = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\n- f = hide_mapped_axes(f, in_axes_flat, out_axes_flat)\n+ f = hide_mapped_axes(f, tuple(in_axes), tuple(out_axes))\nfor naxis, raxis in vectorized.items():\n- map_in_axes = map(lambda spec: spec.get(naxis, None), in_axes_flat)\n- map_out_axes = map(lambda spec: spec.get(naxis, None), out_axes_flat)\n+ map_in_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), in_axes))\n+ map_out_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), out_axes))\nf = vtile(f, map_in_axes, map_out_axes, tile_size=None, axis_name=raxis)\nresource_env_shape = resource_env.shape\nfor raxis, naxes in fake_resource_map.items():\n- map_in_axes = map(lambda spec: lookup_exactly_one_of(spec, naxes), in_axes_flat)\n- map_out_axes = map(lambda spec: lookup_exactly_one_of(spec, naxes), out_axes_flat)\n+ map_in_axes = tuple(unsafe_map(lambda spec: lookup_exactly_one_of(spec, naxes), in_axes))\n+ map_out_axes = tuple(unsafe_map(lambda spec: lookup_exactly_one_of(spec, naxes), out_axes))\nmap_size = resource_env_shape[raxis]\nf = vtile(f, map_in_axes, map_out_axes, tile_size=map_size, axis_name=raxis)\nif physical_resource_map:\nsubmesh = resource_env.physical_mesh[tuple(physical_resource_map.keys())]\n- in_avals = [core.raise_to_shaped(core.get_aval(arg)) for arg in args_flat]\ndef to_mesh_axes(axes):\nmesh_axes = {}\nfor paxis, naxes in physical_resource_map.items():\n@@ -198,22 +303,41 @@ def xmap(fun: Callable,\nif axis is None:\ncontinue\nmesh_axes[paxis] = axis\n- return mesh_axes\n- mesh_in_axes = map(to_mesh_axes, in_axes)\n- mesh_out_axes = map(to_mesh_axes, out_axes)\n- f = pxla.mesh_tiled_callable(*in_avals, fun=f,\n- transformed_name=f.__name__,\n- backend_name=None,\n- mesh=submesh,\n- in_axes=mesh_in_axes,\n- out_axes_thunk=lambda: mesh_out_axes)\n- flat_out = f(*args_flat)\n+ return A(mesh_axes)\n+ mesh_in_axes = tuple(unsafe_map(to_mesh_axes, in_axes))\n+ mesh_out_axes = tuple(unsafe_map(to_mesh_axes, out_axes))\n+ return pxla.mesh_tiled_callable(f,\n+ f.__name__,\n+ backend,\n+ submesh,\n+ mesh_in_axes,\n+ mesh_out_axes,\n+ *in_avals)\nelse:\n- flat_out = f.call_wrapped(*args_flat)\n+ return f.call_wrapped\n- return tree_unflatten(out_tree, flat_out)\n+# xmap has a different set of parameters than pmap, so we make it its own primitive type\n+class XMapPrimitive(core.Primitive):\n+ multiple_results = True\n- return fun_mapped\n+ def __init__(self):\n+ super().__init__('xmap')\n+ self.def_impl(xmap_impl)\n+ self.def_custom_bind(partial(core.call_bind, self))\n+\n+ def bind(self, fun, *args, **params):\n+ assert len(params['in_axes']) == len(args)\n+ return core.call_bind(self, fun, *args, **params)\n+\n+ def process(self, trace, fun, tracers, params):\n+ return trace.process_xmap(self, fun, tracers, params)\n+\n+ def post_process(self, trace, out_tracers, params):\n+ raise NotImplementedError\n+ return trace.post_process_xmap(self, out_tracers, params)\n+\n+xmap_p = XMapPrimitive()\n+core.EvalTrace.process_xmap = core.EvalTrace.process_call # type: ignore\ndef _delete_aval_axes(aval, axes: AxisNamePos):\nassert isinstance(aval, core.ShapedArray)\n@@ -222,19 +346,7 @@ def _delete_aval_axes(aval, axes: AxisNamePos):\ndel shape[i]\nreturn core.ShapedArray(tuple(shape), aval.dtype)\n-def _trace_mapped_jaxpr(fun,\n- args_flat,\n- in_axes_flat: List[AxisNamePos],\n- axis_sizes: Dict[AxisName, int],\n- in_tree):\n- fun_flat, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n- avals_flat = [core.raise_to_shaped(core.get_aval(arg)) for arg in args_flat]\n- mapped_avals = [_delete_aval_axes(aval, in_axes)\n- for aval, in_axes in zip(avals_flat, in_axes_flat)]\n- with core.extend_axis_env_nd(axis_sizes.items()):\n- jaxpr, _, consts = pe.trace_to_jaxpr_final(fun_flat, mapped_avals)\n- return core.ClosedJaxpr(jaxpr, consts), out_tree()\n-\n+# TODO: pmap has some very fancy error messages for this function!\ndef _get_axis_sizes(args_flat: Iterable[Any], in_axes_flat: Iterable[AxisNamePos]):\naxis_sizes: Dict[AxisName, int] = {}\nfor arg, in_axes in zip(args_flat, in_axes_flat):\n@@ -286,7 +398,10 @@ def untile_axis(out, axis: Optional[int]):\nreturn out.reshape(shape)\n# NOTE: This divides the in_axes by the tile_size and multiplies the out_axes by it.\n-def vtile(f_flat, in_axes_flat, out_axes_flat, tile_size: Optional[int], axis_name):\n+def vtile(f_flat,\n+ in_axes_flat: Tuple[AxisNamePos, ...],\n+ out_axes_flat: Tuple[AxisNamePos, ...],\n+ tile_size: Optional[int], axis_name):\n@lu.transformation\ndef _map_to_tile(*args_flat):\nreal_tile_size = tile_size\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1223,14 +1223,13 @@ def untile_aval_nd(axis_sizes, out_axes: AxisNameMap, aval):\nshape[axis] *= axis_sizes[name]\nreturn ShapedArray(tuple(shape), aval.dtype)\n-# TODO(apaszke): Cache compilation\n-def mesh_tiled_callable(*in_avals,\n- fun: lu.WrappedFun,\n+def mesh_tiled_callable(fun: lu.WrappedFun,\ntransformed_name: str,\nbackend_name: Optional[str],\nmesh: Mesh,\nin_axes: Sequence[AxisNameMap],\n- out_axes_thunk: Callable[[], Sequence[AxisNameMap]]):\n+ out_axes: Sequence[AxisNameMap],\n+ *in_avals):\nassert config.omnistaging_enabled\nlocal_mesh = mesh.local_mesh\n@@ -1244,7 +1243,6 @@ def mesh_tiled_callable(*in_avals,\nfor aval_in_axes, aval in zip(in_axes, in_avals))\nwith core.extend_axis_env_nd(mesh.shape.items()):\njaxpr, out_sharded_avals, consts = pe.trace_to_jaxpr_final(fun, sharded_avals)\n- out_axes = out_axes_thunk()\nassert len(out_axes) == len(out_sharded_avals)\n# TODO(apaszke): What about outfeed?\n# jaxpr = xla.apply_outfeed_rewriter(jaxpr)\n" }, { "change_type": "MODIFY", "old_path": "tests/gmap_test.py", "new_path": "tests/gmap_test.py", "diff": "@@ -31,7 +31,7 @@ from jax import vmap\nfrom jax import lax\nfrom jax.experimental.general_map import gmap, fake_resources, Mesh, mesh, xmap, A\nfrom jax.lib import xla_bridge\n-from jax.util import curry\n+from jax.util import curry, unzip2\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -86,6 +86,19 @@ def check_default_schedules(cond, fun):\n{\"testcase_name\": \"_\" + name, \"schedule\": schedule}\nfor name, schedule in schedules)(fun)\n+@curry\n+def with_mesh(named_shape, f):\n+ def new_f(*args, **kwargs):\n+ axis_names, shape = unzip2(named_shape)\n+ size = np.prod(shape)\n+ local_devices = list(jax.local_devices())\n+ if len(local_devices) < size:\n+ raise SkipTest(f\"Test requires {size} local devices\")\n+ mesh_devices = np.array(local_devices[:size]).reshape(shape)\n+ with mesh(mesh_devices, axis_names):\n+ return f(*args, **kwargs)\n+ return new_f\n+\nclass GmapTest(jtu.JaxTestCase):\n@@ -227,5 +240,22 @@ class GmapTest(jtu.JaxTestCase):\nself.assertAllClose(c, (a * 2).sum(0))\nself.assertAllClose(d, b * 4)\n+ @ignore_gmap_warning()\n+ @with_mesh([('x', 2)])\n+ def testXMapCompilationCache(self):\n+ def f(x):\n+ assert python_should_be_executing\n+ return x * 2\n+ fm = xmap(f,\n+ in_axes=[A({'a': 0})],\n+ out_axes=[A({'a': 0})],\n+ schedule=[('a', 'x'), ('a', 'vectorize')])\n+ x = np.arange(8).reshape((2, 2, 2))\n+ python_should_be_executing = True\n+ fm(x)\n+ python_should_be_executing = False\n+ fm(x)\n+\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Make xmap into a primitive Add a compilation cache. Also make sure that it raises a clear error when you try to use it with other transforms. Also, add a bunch of checks to make sure that the arguments are valid.
260,287
20.11.2020 11:43:11
0
5ee2de167503b2e22e3531ed3d5d76e2f32071e0
Forbid pmap/soft_pmap/sharded_jit inside xmap
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -312,6 +312,13 @@ def extract_call_jaxpr(\nreturn (params[\"call_jaxpr\"], new_params)\n+def traverse_jaxpr_params(f, params):\n+ \"\"\"Applies f to each jaxpr parameter and returns a tuple of returned values.\"\"\"\n+ return tuple(f(param if type(param) is Jaxpr else param.jaxpr)\n+ for param in params.values()\n+ if type(param) in (Jaxpr, ClosedJaxpr))\n+\n+\ndef eval_jaxpr(jaxpr: Jaxpr, consts, *args):\ndef read(v):\nif type(v) is Literal:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/general_map.py", "new_path": "jax/experimental/general_map.py", "diff": "@@ -327,17 +327,19 @@ class XMapPrimitive(core.Primitive):\ndef bind(self, fun, *args, **params):\nassert len(params['in_axes']) == len(args)\n- return core.call_bind(self, fun, *args, **params)\n+ return core.call_bind(self, fun, *args, **params) # type: ignore\ndef process(self, trace, fun, tracers, params):\nreturn trace.process_xmap(self, fun, tracers, params)\ndef post_process(self, trace, out_tracers, params):\nraise NotImplementedError\n- return trace.post_process_xmap(self, out_tracers, params)\nxmap_p = XMapPrimitive()\ncore.EvalTrace.process_xmap = core.EvalTrace.process_call # type: ignore\n+def _process_xmap_default(self, call_primitive, f, tracers, params):\n+ raise NotImplementedError(f\"{type(self)} must override process_xmap to handle xmap\")\n+core.Trace.process_xmap = _process_xmap_default # type: ignore\ndef _delete_aval_axes(aval, axes: AxisNamePos):\nassert isinstance(aval, core.ShapedArray)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1243,9 +1243,9 @@ def mesh_tiled_callable(fun: lu.WrappedFun,\nfor aval_in_axes, aval in zip(in_axes, in_avals))\nwith core.extend_axis_env_nd(mesh.shape.items()):\njaxpr, out_sharded_avals, consts = pe.trace_to_jaxpr_final(fun, sharded_avals)\n+ _sanitize_mesh_jaxpr(jaxpr)\n+ jaxpr = xla.apply_outfeed_rewriter(jaxpr)\nassert len(out_axes) == len(out_sharded_avals)\n- # TODO(apaszke): What about outfeed?\n- # jaxpr = xla.apply_outfeed_rewriter(jaxpr)\nis_multi_host = local_mesh.shape == mesh.shape\nif is_multi_host:\n@@ -1310,6 +1310,19 @@ def mesh_tiled_callable(fun: lu.WrappedFun,\nreturn partial(execute_replicated, compiled, backend, handle_args, handle_outs)\n+_forbidden_primitives = {\n+ 'xla_pmap': 'pmap',\n+ 'soft_pmap': 'soft_pmap',\n+ 'sharded_call': 'sharded_jit',\n+}\n+def _sanitize_mesh_jaxpr(jaxpr):\n+ for eqn in jaxpr.eqns:\n+ if eqn.primitive.name in _forbidden_primitives:\n+ raise RuntimeError(f\"Nesting {_forbidden_primitives[eqn.primitive.name]} \"\n+ f\"inside xmaps not supported!\")\n+ core.traverse_jaxpr_params(_sanitize_mesh_jaxpr, eqn.params)\n+\n+\ndef mesh_sharding_specs(local_axis_sizes, axis_names):\nmesh_axis_pos = {name: i for i, name in enumerate(axis_names)}\n# NOTE: This takes in the non-sharded avals!\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -524,7 +524,7 @@ def jaxpr_replicas(jaxpr):\nFor a eqn, multiply the `axis_size` with the `jaxpr_replicas` of the\nsubjaxprs. For a list of eqns, take the maximum number of replicas.\n\"\"\"\n- return max((eqn_replicas(eqn) for eqn in jaxpr.eqns), default=1)\n+ return max(unsafe_map(eqn_replicas, jaxpr.eqns), default=1)\n# TODO(mattjj): this function assumes that only pmap has a parameter named\n# axis_size, and that it corresponds to cross-replica mapping\n@@ -538,10 +538,7 @@ def eqn_replicas(eqn):\nreturn 1\ndef initial_style_primitive_replicas(params):\n- nums = (jaxpr_replicas(param if type(param) is core.Jaxpr else param.jaxpr)\n- for param in params.values()\n- if type(param) in (core.Jaxpr, core.ClosedJaxpr))\n- return max(it.chain([1], nums))\n+ return max(core.traverse_jaxpr_params(jaxpr_replicas, params), default=1)\n# TODO(mattjj,skyewm): the functions here are utilities for checking if\n# not-yet-supported features are used with multi-host programming\n" } ]
Python
Apache License 2.0
google/jax
Forbid pmap/soft_pmap/sharded_jit inside xmap
260,335
24.11.2020 10:45:03
28,800
50cb604f2e9797c36a14d93a08068581427e201d
fix doc test failure
[ { "change_type": "MODIFY", "old_path": "docs/jaxpr.rst", "new_path": "docs/jaxpr.rst", "diff": "@@ -448,7 +448,7 @@ captured using the ``xla_pmap`` primitive. Consider this example\nshape=(1,) ] 1.0\ne = add c d\nf = psum[ axis_index_groups=None\n- axis_name=rows ] b\n+ axis_name=('rows',) ] b\ng = div e f\nin (g,) }\ndevices=None\n" } ]
Python
Apache License 2.0
google/jax
fix doc test failure
260,335
24.11.2020 15:07:22
28,800
809731859bf0a5ed6d10562bd3e91b7615ce7b0e
cleanup: unify pmin/pmax implementations with psum
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -139,8 +139,10 @@ def pmax(x, axis_name, *, axis_index_groups=None):\nif not isinstance(axis_name, (tuple, list)):\naxis_name = (axis_name,)\n_validate_axis_index_groups(axis_index_groups)\n- return tree_util.tree_map(partial(\n- pmax_p.bind, axis_name=axis_name, axis_index_groups=axis_index_groups), x)\n+ leaves, treedef = tree_util.tree_flatten(x)\n+ out_flat = pmax_p.bind(*leaves, axis_name=axis_name,\n+ axis_index_groups=axis_index_groups)\n+ return tree_util.tree_unflatten(treedef, out_flat)\ndef pmin(x, axis_name, *, axis_index_groups=None):\n\"\"\"Compute an all-reduce min on ``x`` over the pmapped axis ``axis_name``.\n@@ -164,8 +166,10 @@ def pmin(x, axis_name, *, axis_index_groups=None):\nif not isinstance(axis_name, (tuple, list)):\naxis_name = (axis_name,)\n_validate_axis_index_groups(axis_index_groups)\n- return tree_util.tree_map(partial(\n- pmin_p.bind, axis_name=axis_name, axis_index_groups=axis_index_groups), x)\n+ leaves, treedef = tree_util.tree_flatten(x)\n+ out_flat = pmin_p.bind(*leaves, axis_name=axis_name,\n+ axis_index_groups=axis_index_groups)\n+ return tree_util.tree_unflatten(treedef, out_flat)\ndef _validate_axis_index_groups(axis_index_groups):\nif axis_index_groups is None:\n@@ -344,16 +348,6 @@ def _allreduce_soft_pmap_rule(prim, reducer, vals, mapped, chunk_size,\naxis_index_groups=axis_index_groups)\nreturn outs, (False,) * len(vals)\n-def _allreduce_translation_rule(prim, c, val, *, axis_name, axis_index_groups,\n- axis_env, platform):\n- replica_groups = _replica_groups(axis_env, axis_name, axis_index_groups)\n- dtype = c.get_shape(val).numpy_dtype()\n- scalar = ShapedArray((), dtype)\n- computation = xla.primitive_subcomputation(prim, scalar, scalar)\n- replica_groups_protos = xc.make_replica_groups(replica_groups)\n- return xops.AllReduce(val, computation, replica_groups_protos, None, None)\n-\n-\n# This is only used for collectives that do not include the vmapped axis name,\n# which is why the rule is so simple.\ndef _collective_batcher(prim, args, dims, **params):\n@@ -375,23 +369,6 @@ def _batched_reduction_collective(\naxis_index_groups=None)\nreturn vals_out, [batching.not_mapped] * len(vals_out)\n-# TODO(mattjj): update pmin/pmax to have multiple_results like psum, delete this\n-def _batched_reduction_collective2(\n- prim, if_mapped, if_unmapped, frame, vals_in, dims_in, axis_name,\n- axis_index_groups):\n- assert not prim.multiple_results # cf. _batched_reduction_collective\n- if axis_index_groups is not None:\n- raise NotImplementedError(\"axis_index_groups not supported in vmap collectives. \"\n- \"Please open a feature request!\")\n- (v,), (d,) = vals_in, dims_in\n- val_out = (if_mapped(v, d) if d is not batching.not_mapped\n- else if_unmapped(v, frame.size))\n- if len(axis_name) > 1:\n- remaining_axis_names = tuple(n for n in axis_name if n != frame.name)\n- val_out = prim.bind(val_out, axis_name=remaining_axis_names,\n- axis_index_groups=None)\n- return val_out, batching.not_mapped\n-\ndef _replica_groups(axis_env, axis_name, axis_index_groups):\nreplica_groups = xla.axis_groups(axis_env, axis_name)\nif axis_index_groups is not None:\n@@ -400,13 +377,13 @@ def _replica_groups(axis_env, axis_name, axis_index_groups):\nfor axis_index_group in axis_index_groups]\nreturn replica_groups\n-# psum translation rule has special handling for complex dtypes\n-def _psum_translation_rule(c, *args, axis_name, axis_index_groups, axis_env,\n- platform):\n+def _allreduce_translation_rule(prim, c, *args, axis_name, axis_index_groups,\n+ axis_env, platform):\nif platform in (\"cpu\", \"tpu\"):\n- return _notuple_psum_translation_rule(c, *args, axis_name=axis_name,\n- axis_index_groups=axis_index_groups,\n- axis_env=axis_env, platform=platform)\n+ return _notuple_allreduce_translation_rule(\n+ prim, c, *args, axis_name=axis_name,\n+ axis_index_groups=axis_index_groups, axis_env=axis_env,\n+ platform=platform)\n# XLA's tuple all-reduce doesn't support different dtypes in the same\n# allreduce. Instead, we perform once all-reduce for each argument input type.\n@@ -423,14 +400,15 @@ def _psum_translation_rule(c, *args, axis_name, axis_index_groups, axis_env,\nfor dtype, (indices, dtype_args) in sorted(args_by_type.items()):\nis_complex = dtypes.issubdtype(dtype, np.complexfloating)\nn = len(dtype_args)\n- if is_complex:\n+ if is_complex and prim is lax.add_p:\n+ # we handle complex-dtype sum-reduction directly as a special case\ndtype_args = ([xops.Real(x) for x in dtype_args] +\n[xops.Imag(x) for x in dtype_args])\nscalar = ShapedArray((), c.get_shape(dtype_args[0]).numpy_dtype())\n- computation = xla.primitive_subcomputation(lax.add_p, scalar, scalar)\n+ computation = xla.primitive_subcomputation(prim, scalar, scalar)\nall_reduce = xops.AllReduce(xops.Tuple(c, dtype_args), computation,\nreplica_groups_protos, None, None)\n- if is_complex:\n+ if is_complex and prim is lax.add_p:\nxs = [xops.Complex(xops.GetTupleElement(all_reduce, i),\nxops.GetTupleElement(all_reduce, n + i)) for i in range(n)]\nelse:\n@@ -439,22 +417,25 @@ def _psum_translation_rule(c, *args, axis_name, axis_index_groups, axis_env,\nout[i] = x\nreturn xops.Tuple(c, out)\n-# TODO(b/150476027): CPU doesn't support tuple all-reduce correctly. But\n-# fortunately we don't really need it in that case because CPU doesn't support\n-# cross-task communication either.\n# TODO(b/155446630): An XLA:TPU optimization pass also doesn't support\n# tuple all-reduce yet. Meanwhile, rely on deterministic compiler behavior.\n-def _notuple_psum_translation_rule(c, *args, axis_name, axis_env,\n+def _notuple_allreduce_translation_rule(prim, c, *args, axis_name, axis_env,\naxis_index_groups, platform):\ndef _translate(val):\n- psum = partial(_allreduce_translation_rule, lax.add_p, c,\n- axis_name=axis_name, axis_env=axis_env,\n- axis_index_groups=axis_index_groups, platform=platform)\n+ replica_groups = _replica_groups(axis_env, axis_name, axis_index_groups)\ndtype = c.get_shape(val).numpy_dtype()\n- if dtypes.issubdtype(dtype, np.complexfloating):\n- return xops.Complex(psum(xops.Real(val)), psum(xops.Imag(val)))\n+ scalar = ShapedArray((), dtype)\n+ computation = xla.primitive_subcomputation(prim, scalar, scalar)\n+ replica_groups_protos = xc.make_replica_groups(replica_groups)\n+ all_reduce = lambda x: xops.AllReduce(x, computation, replica_groups_protos,\n+ None, None)\n+\n+ if dtypes.issubdtype(dtype, np.complexfloating) and prim is lax.add_p:\n+ # we handle complex-dtype sum-reduction directly as a special case\n+ return xops.Complex(all_reduce(xops.Real(val)),\n+ all_reduce(xops.Imag(val)))\nelse:\n- return psum(val)\n+ return all_reduce(val)\nreturn xops.Tuple(c, list(map(_translate, args)))\ndef _psum_transpose_rule(cts, axis_name, axis_index_groups):\n@@ -468,7 +449,7 @@ psum_p.multiple_results = True\npsum_p.def_abstract_eval(lambda *args, **params: map(raise_to_shaped, args))\npxla.soft_pmap_rules[psum_p] = \\\npartial(_allreduce_soft_pmap_rule, psum_p, lax._reduce_sum)\n-xla.parallel_translations[psum_p] = _psum_translation_rule\n+xla.parallel_translations[psum_p] = partial(_allreduce_translation_rule, lax.add_p)\nad.deflinear(psum_p, _psum_transpose_rule)\npxla.multi_host_supported_collectives.add(psum_p)\nbatching.primitive_batchers[psum_p] = partial(_collective_batcher, psum_p)\n@@ -495,29 +476,25 @@ def psum_bind(*args, axis_name, axis_index_groups):\npmax_p = core.Primitive('pmax')\n-pmax_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\n-xla.parallel_translations[pmax_p] = \\\n- partial(_allreduce_translation_rule, lax.max_p)\n+pmax_p.multiple_results = True\n+pmax_p.def_abstract_eval(lambda *args, **params: map(raise_to_shaped, args))\n+xla.parallel_translations[pmax_p] = partial(_allreduce_translation_rule, lax.max_p)\npxla.multi_host_supported_collectives.add(pmax_p)\nbatching.primitive_batchers[pmax_p] = partial(_collective_batcher, pmax_p)\nbatching.collective_rules[pmax_p] = \\\n- partial(_batched_reduction_collective2,\n- pmax_p,\n- lambda v, d: v.max(d),\n- lambda v, axis_size: v)\n+ partial(_batched_reduction_collective, pmax_p,\n+ lambda v, d: v.max(d), lambda v, axis_size: v)\npmin_p = core.Primitive('pmin')\n-pmin_p.def_abstract_eval(lambda x, **params: raise_to_shaped(x))\n-xla.parallel_translations[pmin_p] = \\\n- partial(_allreduce_translation_rule, lax.min_p)\n+pmin_p.multiple_results = True\n+pmin_p.def_abstract_eval(lambda *args, **params: map(raise_to_shaped, args))\n+xla.parallel_translations[pmin_p] = partial(_allreduce_translation_rule, lax.min_p)\npxla.multi_host_supported_collectives.add(pmin_p)\nbatching.primitive_batchers[pmin_p] = partial(_collective_batcher, pmin_p)\nbatching.collective_rules[pmin_p] = \\\n- partial(_batched_reduction_collective2,\n- pmin_p,\n- lambda v, d: v.min(d),\n- lambda v, axis_size: v)\n+ partial(_batched_reduction_collective, pmin_p,\n+ lambda v, d: v.min(d), lambda v, axis_size: v)\ndef _ppermute_translation_rule(c, x, *, axis_name, axis_env, perm, platform):\n" } ]
Python
Apache License 2.0
google/jax
cleanup: unify pmin/pmax implementations with psum
260,335
25.11.2020 10:16:40
28,800
3053f4bc1ee51ece49f091ec26fb02a95fb6bd79
add link to XLA bug about complex dtype allreduce
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -401,7 +401,8 @@ def _allreduce_translation_rule(prim, c, *args, axis_name, axis_index_groups,\nis_complex = dtypes.issubdtype(dtype, np.complexfloating)\nn = len(dtype_args)\nif is_complex and prim is lax.add_p:\n- # we handle complex-dtype sum-reduction directly as a special case\n+ # TODO(b/141575627): we handle complex-dtype sum-reduction directly as a\n+ # special case because it's not currently handled by XLA:GPU or XLA:CPU\ndtype_args = ([xops.Real(x) for x in dtype_args] +\n[xops.Imag(x) for x in dtype_args])\nscalar = ShapedArray((), c.get_shape(dtype_args[0]).numpy_dtype())\n@@ -431,7 +432,8 @@ def _notuple_allreduce_translation_rule(prim, c, *args, axis_name, axis_env,\nNone, None)\nif dtypes.issubdtype(dtype, np.complexfloating) and prim is lax.add_p:\n- # we handle complex-dtype sum-reduction directly as a special case\n+ # TODO(b/141575627): we handle complex-dtype sum-reduction directly as a\n+ # special case because it's not currently handled by XLA:GPU or XLA:CPU\nreturn xops.Complex(all_reduce(xops.Real(val)),\nall_reduce(xops.Imag(val)))\nelse:\n" } ]
Python
Apache License 2.0
google/jax
add link to XLA bug about complex dtype allreduce
260,335
25.11.2020 10:25:22
28,800
7266fcbdc5846001ea692b9cabc5f1a6cf97ec40
when resetting stores in nan debugging, check None
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -582,7 +582,7 @@ def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name, donated_inv\n# by any transformation_with_aux's applied to fun. Since this is\n# intentional here, to avoid \"Store occupied\" errors we reset the stores to\n# be empty.\n- for store in fun.stores: store.reset()\n+ for store in fun.stores: store and store.reset()\nreturn fun.call_wrapped(*args) # probably won't return\ndef flatten_shape(s: XlaShape) -> Sequence[Tuple[Sequence[int], XlaShape]]:\n" } ]
Python
Apache License 2.0
google/jax
when resetting stores in nan debugging, check None
260,335
25.11.2020 14:17:27
28,800
8d884e24802347b3f45ad6c144d7a7c0114cf1e1
silence weird type error
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -450,7 +450,7 @@ psum_p.multiple_results = True\npsum_p.def_abstract_eval(lambda *args, **params: map(raise_to_shaped, args))\npxla.soft_pmap_rules[psum_p] = \\\npartial(_allreduce_soft_pmap_rule, psum_p, lax._reduce_sum)\n-xla.parallel_translations[psum_p] = partial(_allreduce_translation_rule, lax.add_p)\n+xla.parallel_translations[psum_p] = partial(_allreduce_translation_rule, lax.add_p) # type: ignore\nad.deflinear(psum_p, _psum_transpose_rule)\npxla.multi_host_supported_collectives.add(psum_p)\nbatching.primitive_batchers[psum_p] = partial(_collective_batcher, psum_p)\n" } ]
Python
Apache License 2.0
google/jax
silence weird type error
260,287
27.11.2020 16:32:03
0
ed86ae4950259a8955d68856d601f08f20ea17db
Add proper support for out_axes in xmap
[ { "change_type": "MODIFY", "old_path": "jax/experimental/general_map.py", "new_path": "jax/experimental/general_map.py", "diff": "@@ -36,7 +36,7 @@ from ..interpreters import pxla\nfrom ..interpreters import xla\nfrom ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\n-from ..util import safe_map, safe_zip, curry\n+from ..util import safe_map, safe_zip, curry, HashableFunction\nfrom .._src.lax.parallel import _axis_index_translation_rule\nmap, unsafe_map = safe_map, map\n@@ -170,13 +170,15 @@ def xmap(fun: Callable,\nfrozen_schedule = tuple(tuple(x) for x in schedule)\n- if isinstance(in_axes, list):\n# To be a tree prefix of the positional args tuple, in_axes can never be a\n# list: if in_axes is not a leaf, it must be a tuple of trees. However,\n# in cases like these users expect tuples and lists to be treated\n# essentially interchangeably, so we canonicalize lists to tuples here\n# rather than raising an error. https://github.com/google/jax/issues/2367\n+ if isinstance(in_axes, list):\nin_axes = tuple(in_axes)\n+ if isinstance(out_axes, list):\n+ out_axes = tuple(out_axes)\nin_axes_entries = tree_leaves(in_axes)\nout_axes_entries = tree_leaves(out_axes)\n@@ -222,15 +224,15 @@ def xmap(fun: Callable,\n# TODO: Check that:\n# - two axes mapped to the same resource never coincide (even inside f)\nin_axes_flat = flatten_axes(\"xmap in_axes\", in_tree, in_axes)\n- out_axes_flat, out_axes_tree = tree_flatten(out_axes)\n- # TODO: Verify that out_axes are equal, or better expand their prefix\n- # assert out_axes_tree == out_tree\n+ out_axes_thunk = HashableFunction(\n+ lambda: tuple(flatten_axes(\"xmap out_axes\", out_tree(), out_axes)),\n+ key=out_axes)\naxis_sizes = _get_axis_sizes(args_flat, in_axes_flat)\nout_flat = xmap_p.bind(\nfun_flat, *args_flat,\nname=fun.__name__,\nin_axes=tuple(in_axes_flat),\n- out_axes=tuple(out_axes_flat),\n+ out_axes_thunk=out_axes_thunk,\naxis_sizes=FrozenDict(axis_sizes),\nschedule=frozen_schedule,\nresource_env=resource_env,\n@@ -239,23 +241,26 @@ def xmap(fun: Callable,\nreturn fun_mapped\n-def xmap_impl(fun: lu.WrappedFun, *args, name, in_axes, out_axes, axis_sizes, schedule, resource_env, backend):\n+def xmap_impl(fun: lu.WrappedFun, *args, name, in_axes, out_axes_thunk, axis_sizes, schedule, resource_env, backend):\nin_avals = [core.raise_to_shaped(core.get_aval(arg)) for arg in args]\n- return make_xmap_callable(fun, name, in_axes, out_axes, axis_sizes, schedule,\n+ return make_xmap_callable(fun, name, in_axes, out_axes_thunk, axis_sizes, schedule,\nresource_env, backend, *in_avals)(*args)\n@lu.cache\ndef make_xmap_callable(fun: lu.WrappedFun,\nname,\n- in_axes, out_axes, axis_sizes,\n+ in_axes, out_axes_thunk, axis_sizes,\nschedule, resource_env, backend,\n*in_avals):\nplan = EvaluationPlan.from_schedule(schedule, resource_env)\n+ # TODO: Making axis substitution final style would allow us to avoid\n+ # tracing to jaxpr here\nmapped_in_avals = [_delete_aval_axes(aval, in_axes)\nfor aval, in_axes in zip(in_avals, in_axes)]\nwith core.extend_axis_env_nd(axis_sizes.items()):\njaxpr, _, consts = pe.trace_to_jaxpr_final(fun, mapped_in_avals)\n+ out_axes = out_axes_thunk()\njaxpr = subst_axis_names(jaxpr, plan.axis_subst)\nf = lu.wrap_init(core.jaxpr_as_fun(core.ClosedJaxpr(jaxpr, consts)))\n@@ -353,6 +358,7 @@ class EvaluationPlan(NamedTuple):\n# xmap has a different set of parameters than pmap, so we make it its own primitive type\nclass XMapPrimitive(core.Primitive):\nmultiple_results = True\n+ map_primitive = True # Not really, but it gives us a few good behaviors\ndef __init__(self):\nsuper().__init__('xmap')\n@@ -376,18 +382,6 @@ def _process_xmap_default(self, call_primitive, f, tracers, params):\ncore.Trace.process_xmap = _process_xmap_default # type: ignore\n-# This is necessary for various functions such as core.eval_jaxpr to\n-# recognize that xmap is a map-like primitive.\n-def _extract_call_jaxpr(primitive, params):\n- if primitive is xmap_p:\n- new_params = dict(params)\n- call_jaxpr = new_params.pop('call_jaxpr')\n- return (call_jaxpr, new_params)\n- return _old_extract_call_jaxpr(primitive, params)\n-_old_extract_call_jaxpr = core.extract_call_jaxpr\n-core.extract_call_jaxpr = _extract_call_jaxpr\n-\n-\n# This is DynamicJaxprTrace.process_map with some very minor modifications\ndef _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nfrom jax.interpreters.partial_eval import (\n@@ -401,16 +395,18 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nwith core.extend_axis_env_nd(params['axis_sizes'].items()):\njaxpr, mapped_out_avals, consts = trace_to_subjaxpr_dynamic(\nf, self.main, mapped_in_avals)\n+ out_axes = params['out_axes_thunk']()\nout_avals = [_insert_aval_axes(a, a_out_axes, axis_sizes)\n- for a, a_out_axes in zip(mapped_out_avals, params['out_axes'])]\n+ for a, a_out_axes in zip(mapped_out_avals, out_axes)]\nsource_info = source_info_util.current()\nout_tracers = [DynamicJaxprTracer(self, a, source_info) for a in out_avals]\ninvars = map(self.getvar, tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\noutvars = map(self.makevar, out_tracers)\nnew_in_axes = (None,) * len(consts) + params['in_axes']\n- new_params = dict(params, in_axes=new_in_axes,\n+ new_params = dict(params, in_axes=new_in_axes, out_axes=out_axes,\ncall_jaxpr=convert_constvars_jaxpr(jaxpr))\n+ del new_params['out_axes_thunk']\nupdate_params = call_param_updaters.get(primitive)\nif update_params:\nnew_params = update_params(new_params, [True] * len(tracers))\n" }, { "change_type": "MODIFY", "old_path": "tests/gmap_test.py", "new_path": "tests/gmap_test.py", "diff": "@@ -249,8 +249,8 @@ class GmapTest(jtu.JaxTestCase):\nassert python_should_be_executing\nreturn x * 2\nfm = xmap(f,\n- in_axes=[A({'a': 0})],\n- out_axes=[A({'a': 0})],\n+ in_axes=A({'a': 0}),\n+ out_axes=A({'a': 0}),\nschedule=[('a', 'x'), ('a', 'vectorize')])\nx = np.arange(8).reshape((2, 2, 2))\npython_should_be_executing = True\n@@ -261,11 +261,11 @@ class GmapTest(jtu.JaxTestCase):\n@ignore_gmap_warning()\n@with_mesh([('x', 2)])\ndef testNestedXMapBasic(self):\n- @partial(xmap, in_axes=[A({'a': 1})], out_axes=[A({'a': 0})],\n+ @partial(xmap, in_axes=A({'a': 1}), out_axes=A({'a': 0}),\nschedule=[('a', 'x')])\ndef f(x):\ny = x * 2\n- @partial(xmap, in_axes=[A({'b': 0})], out_axes=[A({'b': 1})],\n+ @partial(xmap, in_axes=A({'b': 0}), out_axes=A({'b': 1}),\nschedule=[('b', 'vectorize')])\ndef h(y):\nreturn jnp.sin(y)\n@@ -278,11 +278,11 @@ class GmapTest(jtu.JaxTestCase):\n@ignore_gmap_warning()\n@with_mesh([('x', 2), ('y', 3)])\ndef testNestedXMapMesh(self):\n- @partial(xmap, in_axes=[A({'a': 1})], out_axes=[A({'a': 0})],\n+ @partial(xmap, in_axes=A({'a': 1}), out_axes=A({'a': 0}),\nschedule=[('a', 'y')])\ndef f(x):\ny = x * 2\n- @partial(xmap, in_axes=[A({'b': 0})], out_axes=[A({'b': 1})],\n+ @partial(xmap, in_axes=A({'b': 0}), out_axes=A({'b': 1}),\nschedule=[('b', 'x')])\ndef h(y):\nreturn jnp.sin(y)\n@@ -300,11 +300,11 @@ class GmapTest(jtu.JaxTestCase):\n@ignore_gmap_warning()\n@with_mesh([('x', 2)])\ndef testNestedXMapDifferentResources(self):\n- @partial(xmap, in_axes=[A({'a': 0})], out_axes=[A({'a': 0})],\n+ @partial(xmap, in_axes=A({'a': 0}), out_axes=A({'a': 0}),\nschedule=[('a', 'x')])\ndef f(x):\nwith mesh(np.empty((), dtype=np.object), ()):\n- @partial(xmap, in_axes=[A({'b': 0})], out_axes=[A({'b': 0})],\n+ @partial(xmap, in_axes=A({'b': 0}), out_axes=A({'b': 0}),\nschedule=[('b', 'vectorize')])\ndef h(x):\nreturn x\n" } ]
Python
Apache License 2.0
google/jax
Add proper support for out_axes in xmap
260,335
25.11.2020 15:23:00
28,800
58e441bed78a0661f081e93ccfe9cf4370c5f5d5
add experimental pdot primitive, basic tests
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3032,14 +3032,23 @@ def _dot_general_transpose_rhs(g, x, *, dimension_numbers, precision):\ndef _dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers,\nprecision):\n+ lhs, rhs = batched_args\n+ new_dimension_numbers, result_batch_dim = _dot_general_batch_dim_nums(\n+ (lhs.ndim, rhs.ndim), batch_dims, dimension_numbers)\n+ batched_out = dot_general(lhs, rhs, new_dimension_numbers,\n+ precision=precision)\n+ return batched_out, result_batch_dim\n+\n+def _dot_general_batch_dim_nums(ndims, batch_dims, dimension_numbers):\n# there are three kinds of dimensions in a dot_general:\n# - contraction dimensions appear in lhs and rhs but not the result\n# - batch dimensions appear in lhs, rhs, and result\n# - tensor product dimensions appear in the result and one of lhs or rhs\n- (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n- lhs, rhs = batched_args\n+ lhs_ndim, rhs_ndim = ndims\nlbd, rbd = batch_dims\nassert lbd is not None or rbd is not None\n+ (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n+\ndef bump_dims(dims, b):\nreturn tuple(np.add(dims, np.greater_equal(dims, b)))\n@@ -3053,23 +3062,21 @@ def _dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers,\nelse:\n# adding a tensor product dimension\nif lbd is not None:\n- other = tuple(d for d in range(lhs.ndim)\n+ other = tuple(d for d in range(lhs_ndim)\nif d not in lhs_batch and d not in lhs_contract)\nresult_batch_dim = (len(lhs_batch) + sum(np.less(other, lbd)))\nlhs_batch = bump_dims(lhs_batch, lbd)\nlhs_contract = bump_dims(lhs_contract, lbd)\nelse:\n- other = tuple(d for d in range(rhs.ndim)\n+ other = tuple(d for d in range(rhs_ndim)\nif d not in rhs_batch and d not in rhs_contract)\n- result_batch_dim = (lhs.ndim - len(lhs_contract) +\n+ result_batch_dim = (lhs_ndim - len(lhs_contract) +\nsum(np.less(other, rbd)))\nrhs_batch = bump_dims(rhs_batch, rbd)\nrhs_contract = bump_dims(rhs_contract, rbd)\nnew_dimension_numbers = ((lhs_contract, rhs_contract), (lhs_batch, rhs_batch))\n- batched_out = dot_general(lhs, rhs, new_dimension_numbers,\n- precision=precision)\n- return batched_out, int(result_batch_dim)\n+ return new_dimension_numbers, int(result_batch_dim)\ndef _dot_using_sum_of_products(lhs, rhs, *, dimension_numbers):\ncontract_dims, batch_dims = dimension_numbers\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -337,6 +337,13 @@ def axis_index(axis_name):\nreturn axis_index_p.bind(axis_name=axis_name)\n+def pdot(x, y, axis_name, pos_contract=((), ())):\n+ if not isinstance(axis_name, (list, tuple)):\n+ axis_name = (axis_name,)\n+ return pdot_p.bind(x, y, axis_name=axis_name,\n+ pos_contract=pos_contract, pos_batch=[(), ()])\n+\n+\n### parallel primitives\ndef _allreduce_soft_pmap_rule(prim, reducer, vals, mapped, chunk_size,\n@@ -749,6 +756,72 @@ def _process_axis_index(self, frame):\nbatching.BatchTrace.process_axis_index = _process_axis_index # type: ignore\n+pdot_p = core.Primitive('pdot')\n+\n+@pdot_p.def_impl\n+def _pdot_impl(x, y, *, axis_name, pos_contract, pos_batch):\n+ if axis_name: raise NameError(f\"unbound axis name: {axis_name[0]}\")\n+ return lax.dot_general(x, y, [pos_contract, pos_batch])\n+\n+@pdot_p.def_abstract_eval\n+def _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch):\n+ # TODO: avals with names, check inputs are mapped along axis_name, eliminate\n+ return lax.dot_general_p.abstract_eval(\n+ x, y, dimension_numbers=[pos_contract, pos_batch],\n+ precision=None)\n+\n+def _pdot_vmap_collective_rule(frame, vals_in, dims_in, *, axis_name,\n+ pos_contract, pos_batch):\n+ x, y = vals_in\n+ x_dim, y_dim = dims_in\n+ x_pos_contract, y_pos_contract = pos_contract\n+ x_pos_contract = [x_dim] + [d + (d >= x_dim) for d in x_pos_contract]\n+ y_pos_contract = [y_dim] + [d + (d >= y_dim) for d in y_pos_contract]\n+ x_pos_batch, y_pos_batch = pos_batch\n+ x_pos_batch = [d + (d >= x_dim) for d in x_pos_batch]\n+ y_pos_batch = [d + (d >= y_dim) for d in y_pos_batch]\n+ remaining_axis_names = tuple(n for n in axis_name if n != frame.name)\n+ out = pdot_p.bind(x, y, axis_name=remaining_axis_names,\n+ pos_contract=[x_pos_contract, y_pos_contract],\n+ pos_batch=[x_pos_batch, y_pos_batch])\n+ return out, None\n+batching.collective_rules[pdot_p] = _pdot_vmap_collective_rule\n+\n+def _pdot_vmap_batching_rule(vals_in, dims_in, *, axis_name, pos_contract,\n+ pos_batch):\n+ x, y = vals_in\n+ (pos_contract, pos_batch), result_batch_dim = lax._dot_general_batch_dim_nums(\n+ (x.ndim, y.ndim), dims_in, [pos_contract, pos_batch])\n+ out = pdot_p.bind(x, y, axis_name=axis_name, pos_contract=pos_contract,\n+ pos_batch=pos_batch)\n+ return out, result_batch_dim\n+batching.primitive_batchers[pdot_p] = _pdot_vmap_batching_rule\n+\n+def _pdot_translation_rule(c, x, y, *, axis_name, pos_contract, pos_batch,\n+ axis_env, platform):\n+ assert axis_name\n+ local_out = lax._dot_general_translation_rule(\n+ c, x, y, dimension_numbers=[pos_contract, pos_batch], precision=None)\n+ out_tup = xla.parallel_translations[psum_p](\n+ c, local_out, axis_name=axis_name, axis_index_groups=None,\n+ axis_env=axis_env, platform=platform)\n+ out, = xla.xla_destructure(c, out_tup)\n+ return out\n+xla.parallel_translations[pdot_p] = _pdot_translation_rule\n+\n+def _pdot_transpose_lhs(g, y, *, axis_name, pos_contract, pos_batch):\n+ # TODO: avals with names, call pbroadcast with axis_name\n+ return lax._dot_general_transpose_lhs(\n+ g, y, dimension_numbers=[pos_contract, pos_batch], precision=None)\n+def _pdot_transpose_rhs(g, x, *, axis_name, pos_contract, pos_batch):\n+ # TODO: avals with names, call pbroadcast with axis_name\n+ return lax._dot_general_transpose_rhs(\n+ g, x, dimension_numbers=[pos_contract, pos_batch], precision=None)\n+ad.defbilinear(pdot_p, _pdot_transpose_lhs, _pdot_transpose_rhs)\n+\n+pxla.multi_host_supported_collectives.add(pdot_p)\n+\n+\n@config.register_omnistaging_disabler\ndef omnistaging_disabler() -> None:\nglobal axis_index\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/general_map.py", "new_path": "jax/experimental/general_map.py", "diff": "@@ -534,7 +534,6 @@ def _delete_aval_axes(aval, axes: AxisNamePos):\ndel shape[i]\nreturn core.ShapedArray(tuple(shape), aval.dtype)\n-\ndef _insert_aval_axes(aval, axes: AxisNamePos, axis_sizes):\nassert isinstance(aval, core.ShapedArray)\nshape = list(aval.shape)\n@@ -802,3 +801,27 @@ def subst_eqn_axis_names(eqn, axis_subst: Dict[AxisName, Tuple[AxisName]]):\naxis_names = (axis_names,)\nnew_axis_names = sum((axis_subst.get(name, (name,)) for name in axis_names), ())\nreturn eqn._replace(params=dict(eqn.params, axis_name=new_axis_names))\n+\n+\n+def _dynamic_jaxpr_trace_process_xmap(trace, prim, fun, tracers, params):\n+ in_avals = [t.aval for t in tracers]\n+ mapped_in_avals = [_delete_aval_axes(aval, in_axes)\n+ for aval, in_axes in zip(in_avals, params['in_axes'])]\n+ with core.extend_axis_env_nd(params['axis_sizes'].items()):\n+ jaxpr, reduced_out_avals, consts = pe.trace_to_jaxpr_final(fun, mapped_in_avals)\n+ if consts: raise NotImplementedError # TODO(mattjj): handle consts\n+ out_avals = [_insert_aval_axes(aval, out_axes, params['axis_sizes'])\n+ for aval, out_axes in zip(reduced_out_avals, params['out_axes'])]\n+ source_info = pe.source_info_util.current()\n+ out_tracers = [pe.DynamicJaxprTracer(trace, a, source_info) for a in out_avals]\n+ invars = map(trace.getvar, tracers)\n+ constvars = map(trace.getvar, map(trace.instantiate_const, consts))\n+ outvars = map(trace.makevar, out_tracers)\n+ new_in_axes = (None,) * len(consts) + params['in_axes']\n+ new_params = dict(params, in_axes=new_in_axes,\n+ call_jaxpr=pe.convert_constvars_jaxpr(jaxpr))\n+ eqn = pe.new_jaxpr_eqn([*constvars, *invars], outvars, prim,\n+ new_params, source_info)\n+ trace.frame.eqns.append(eqn)\n+ return out_tracers\n+pe.DynamicJaxprTrace.process_xmap = _dynamic_jaxpr_trace_process_xmap # type: ignore\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1105,13 +1105,15 @@ class DynamicJaxprTrace(core.Trace):\ndef process_map(self, map_primitive, f, tracers, params):\nin_avals = [t.aval for t in tracers]\naxis_name, axis_size = params['axis_name'], params['axis_size']\n- reduced_in_avals = [core.mapped_aval(axis_size, in_axis, a) if in_axis is not None else a\n+ reduced_in_avals = [core.mapped_aval(axis_size, in_axis, a)\n+ if in_axis is not None else a\nfor a, in_axis in zip(in_avals, params['in_axes'])]\nwith core.extend_axis_env(axis_name, axis_size, None): # type: ignore\njaxpr, reduced_out_avals, consts = trace_to_subjaxpr_dynamic(\nf, self.main, reduced_in_avals)\nout_axes = params['out_axes_thunk']()\n- out_avals = [core.unmapped_aval(params['axis_size'], out_axis, a) if out_axis is not None else a\n+ out_avals = [core.unmapped_aval(params['axis_size'], out_axis, a)\n+ if out_axis is not None else a\nfor a, out_axis in zip(reduced_out_avals, out_axes)]\nsource_info = source_info_util.current()\nout_tracers = [DynamicJaxprTracer(self, a, source_info) for a in out_avals]\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/__init__.py", "new_path": "jax/lax/__init__.py", "diff": "@@ -337,6 +337,7 @@ from jax._src.lax.parallel import (\npsum,\npsum_p,\npswapaxes,\n+ pdot,\n)\nfrom jax._src.lax.other import (\nconv_general_dilated_patches\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -1111,6 +1111,69 @@ class BatchingTest(jtu.JaxTestCase):\nvmap(lambda x: x - lax.axis_index('i'), axis_name='i')(x),\nx - np.arange(x.shape[0]))\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testCollectivePdot(self):\n+ def f(x, y):\n+ return lax.pdot(x, y, 'i')\n+\n+ rng = np.random.RandomState(0)\n+\n+ x = rng.randn(3, 4)\n+ y = rng.randn(4, 5)\n+ z = vmap(f, axis_name='i', in_axes=(1, 0), out_axes=None)(x, y)\n+ self.assertAllClose(z, jnp.dot(x, y))\n+\n+ x = rng.randn(4, 3)\n+ y = rng.randn(4, 5)\n+ z = vmap(f, axis_name='i', in_axes=(0, 0), out_axes=None)(x, y)\n+ self.assertAllClose(z, jnp.dot(x.T, y))\n+\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testCollectivePdotBatching(self):\n+ def f(x, y):\n+ return lax.pdot(x, y, 'i')\n+\n+ rng = np.random.RandomState(1)\n+ xs = rng.randn(2, 8, 3)\n+ ys = rng.randn(2, 3, 5)\n+ zs = vmap(vmap(f, axis_name='i', in_axes=(1, 0), out_axes=None))(xs, ys)\n+ self.assertAllClose(zs, jnp.einsum('nij,njk->nik', xs, ys))\n+\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testPdotJvp(self):\n+ def f(x, y):\n+ return lax.pdot(x, y, 'i')\n+\n+ rng = np.random.RandomState(1)\n+ x = rng.randn(3, 4)\n+ x_dot = rng.randn(*x.shape)\n+ y = rng.randn(4, 5)\n+ y_dot = rng.randn(*y.shape)\n+\n+ z, z_dot = vmap(lambda x, y, x_dot, y_dot: jvp(f, (x, y), (x_dot, y_dot)),\n+ axis_name='i', in_axes=(1, 0, 1, 0), out_axes=None)(x, y, x_dot, y_dot)\n+ self.assertAllClose(z, jnp.dot(x, y))\n+ self.assertAllClose(z_dot, jnp.dot(x_dot, y) + jnp.dot(x, y_dot))\n+\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testPdotVjp(self):\n+ def f(x, y):\n+ return lax.pdot(x, y, 'i')\n+\n+ rng = np.random.RandomState(1)\n+ x = rng.randn(3, 4)\n+ y = rng.randn(4, 5)\n+ z_bar = rng.randn(3, 5)\n+\n+ x_bar, y_bar = vmap(lambda x, y, z_bar: vjp(f, x, y)[1](z_bar),\n+ axis_name='i', in_axes=(1, 0, None), out_axes=(1, 0))(x, y, z_bar)\n+ self.assertAllClose(x_bar, jnp.dot(z_bar, y.T))\n+ self.assertAllClose(y_bar, jnp.dot(x.T, z_bar))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "tests/gmap_test.py", "new_path": "tests/gmap_test.py", "diff": "@@ -30,7 +30,7 @@ import jax.numpy as jnp\nfrom jax import test_util as jtu\nfrom jax import vmap\nfrom jax import lax\n-from jax.experimental.general_map import gmap, fake_resources, Mesh, mesh, xmap, A\n+from jax.experimental.general_map import gmap, Mesh, mesh, xmap, A\nfrom jax.lib import xla_bridge\nfrom jax.util import curry, unzip2\nfrom jax.interpreters import pxla\n@@ -143,10 +143,10 @@ class GmapTest(jtu.JaxTestCase):\n@ignore_gmap_warning()\n@skipIf(not config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\n+ @with_mesh([('r1', 4), ('r2', 2), ('r3', 5)])\ndef testXMap(self):\ndef f(a, b):\nreturn a + 2, b * 4\n- with fake_resources(r1=4, r2=2, r3=5):\nfm = xmap(f,\nin_axes=[A({'x': 0, 'z': 1}), A({'y': 1})],\nout_axes=[A({'x': 1, 'z': 0}), A({'y': 0})],\n@@ -167,10 +167,10 @@ class GmapTest(jtu.JaxTestCase):\n@ignore_gmap_warning()\n@skipIf(not config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\n+ @with_mesh([('r1', 4), ('r2', 2), ('r3', 5)])\ndef testXMapCollectives(self):\ndef f(a, b):\nreturn lax.psum(a + 2, 'x'), b * 4\n- with fake_resources(r1=4, r2=2, r3=5):\nfm = xmap(f,\nin_axes=[A({'x': 0, 'z': 1}), A({'y': 1})],\nout_axes=[A({'z': 0}), A({'y': 0})],\n@@ -315,6 +315,45 @@ class GmapTest(jtu.JaxTestCase):\n\"Changing the resource environment.*\"):\nf(x)\n+ @ignore_gmap_warning()\n+ @skipIf(not config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ @with_mesh([('r1', 2)])\n+ def testPdotBasic(self):\n+ def f(x, y):\n+ return lax.pdot(x, y, 'i')\n+\n+ f_mapped = xmap(f, in_axes=[A({'i': 1}), A({'i': 0})], out_axes=A(),\n+ schedule=[('i', 'r1'), ('i', 'vectorize')])\n+\n+ rng = np.random.RandomState(0)\n+ x = rng.randn(3, 8)\n+ y = rng.randn(8, 5)\n+\n+ z = f_mapped(x, y)\n+\n+ self.assertAllClose(z, jnp.dot(x, y))\n+\n+ @ignore_gmap_warning()\n+ @skipIf(not config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ @with_mesh([('r1', 2)])\n+ def testPdotBatching(self):\n+ def f(x, y):\n+ return lax.pdot(x, y, 'i')\n+\n+ rng = np.random.RandomState(0)\n+ x = rng.randn(2, 3, 8)\n+ y = rng.randn(2, 8, 5)\n+\n+ f_mapped = xmap(f,\n+ in_axes=[A({'i': 2, 'j': 0}), A({'i': 1, 'j': 0})],\n+ out_axes=A({'j': 0}),\n+ schedule=[('j', 'vectorize'), ('i', 'r1'), ('i', 'vectorize')])\n+\n+ z = f_mapped(x, y)\n+\n+ self.assertAllClose(z, jnp.einsum('nij,njk->nik', x, y))\nif __name__ == '__main__':\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -109,6 +109,9 @@ ignore_jit_of_pmap_warning = partial(\nignore_slow_all_to_all_warning = partial(\njtu.ignore_warning, message=\"all_to_all.*expect significant slowdowns.*\")\n+ignore_xmap_warning = partial(\n+ jtu.ignore_warning, message=\".*is an experimental.*\")\n+\nclass PmapTest(jtu.JaxTestCase):\ndef _getMeshShape(self, device_mesh_shape):\ndevice_count = xla_bridge.device_count()\n@@ -1573,6 +1576,20 @@ class PmapTest(jtu.JaxTestCase):\nindices = np.array([[[2], [1]], [[0], [0]]])\nmapped_fn(indices) # doesn't crash\n+ @ignore_xmap_warning()\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testPdotBasic(self):\n+ num_devices = jax.device_count()\n+\n+ def f(x, y):\n+ return lax.pdot(x, y, 'i')\n+\n+ x = jnp.arange(num_devices * 3).reshape(num_devices, 3)\n+ y = jnp.arange(num_devices * 5).reshape(num_devices, 5)\n+ z = pmap(f, axis_name='i', out_axes=None)(x, y)\n+ self.assertAllClose(z, jnp.dot(x.T, y))\n+\nclass VmapOfPmapTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add experimental pdot primitive, basic tests
260,335
27.11.2020 11:28:49
28,800
29648fa50b364c7814c967812e13de4545f850bd
remove DynamicJaxprTrace.process_xmap
[ { "change_type": "MODIFY", "old_path": "jax/experimental/general_map.py", "new_path": "jax/experimental/general_map.py", "diff": "@@ -801,27 +801,3 @@ def subst_eqn_axis_names(eqn, axis_subst: Dict[AxisName, Tuple[AxisName]]):\naxis_names = (axis_names,)\nnew_axis_names = sum((axis_subst.get(name, (name,)) for name in axis_names), ())\nreturn eqn._replace(params=dict(eqn.params, axis_name=new_axis_names))\n-\n-\n-def _dynamic_jaxpr_trace_process_xmap(trace, prim, fun, tracers, params):\n- in_avals = [t.aval for t in tracers]\n- mapped_in_avals = [_delete_aval_axes(aval, in_axes)\n- for aval, in_axes in zip(in_avals, params['in_axes'])]\n- with core.extend_axis_env_nd(params['axis_sizes'].items()):\n- jaxpr, reduced_out_avals, consts = pe.trace_to_jaxpr_final(fun, mapped_in_avals)\n- if consts: raise NotImplementedError # TODO(mattjj): handle consts\n- out_avals = [_insert_aval_axes(aval, out_axes, params['axis_sizes'])\n- for aval, out_axes in zip(reduced_out_avals, params['out_axes'])]\n- source_info = pe.source_info_util.current()\n- out_tracers = [pe.DynamicJaxprTracer(trace, a, source_info) for a in out_avals]\n- invars = map(trace.getvar, tracers)\n- constvars = map(trace.getvar, map(trace.instantiate_const, consts))\n- outvars = map(trace.makevar, out_tracers)\n- new_in_axes = (None,) * len(consts) + params['in_axes']\n- new_params = dict(params, in_axes=new_in_axes,\n- call_jaxpr=pe.convert_constvars_jaxpr(jaxpr))\n- eqn = pe.new_jaxpr_eqn([*constvars, *invars], outvars, prim,\n- new_params, source_info)\n- trace.frame.eqns.append(eqn)\n- return out_tracers\n-pe.DynamicJaxprTrace.process_xmap = _dynamic_jaxpr_trace_process_xmap # type: ignore\n" } ]
Python
Apache License 2.0
google/jax
remove DynamicJaxprTrace.process_xmap
260,424
30.11.2020 14:23:52
-3,600
d7743140a350bec479eeeea89d18dc403cb43e4a
Add named_call autofunction description to docs
[ { "change_type": "MODIFY", "old_path": "docs/jax.rst", "new_path": "docs/jax.rst", "diff": "@@ -82,6 +82,7 @@ Parallelization (:code:`pmap`)\n.. autofunction:: make_jaxpr\n.. autofunction:: eval_shape\n.. autofunction:: device_put\n+.. autofunction:: named_call\n.. autofunction:: grad\n.. autofunction:: value_and_grad\n" } ]
Python
Apache License 2.0
google/jax
Add named_call autofunction description to docs
260,287
26.11.2020 17:11:01
0
34965839abbffcd747faf7fb9873c2e054099503
Add an experimental xmap lowering via the SPMD partitioner As suggested by The SPMD partitioner might allow us to avoid writing partitioning formulas on the JAX level and can result in better performance by giving the compiler more flexibility.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/general_map.py", "new_path": "jax/experimental/general_map.py", "diff": "@@ -31,12 +31,11 @@ from ..api import _mapped_axis_size, _check_callable, _check_arg\nfrom ..tree_util import tree_flatten, tree_unflatten, tree_leaves\nfrom ..api_util import flatten_fun, flatten_fun_nokwargs, flatten_axes\nfrom ..interpreters import partial_eval as pe\n-from ..interpreters import batching\nfrom ..interpreters import pxla\nfrom ..interpreters import xla\nfrom ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\n-from ..util import safe_map, safe_zip, curry, HashableFunction\n+from ..util import safe_map, safe_zip, HashableFunction\nfrom .._src.lax.parallel import _axis_index_translation_rule\nmap, unsafe_map = safe_map, map\n@@ -44,6 +43,8 @@ zip = safe_zip\nxops = xc.ops\n+EXPERIMENTAL_SPMD_LOWERING = False\n+\nclass FrozenDict: # dataclasses might remove some boilerplate here\ndef __init__(self, *args, **kwargs):\nself.contents = dict(*args, **kwargs)\n@@ -278,6 +279,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\nsubmesh,\nmesh_in_axes,\nmesh_out_axes,\n+ EXPERIMENTAL_SPMD_LOWERING,\n*in_avals)\nelse:\nreturn f.call_wrapped\n@@ -326,14 +328,14 @@ class EvaluationPlan(NamedTuple):\nfor naxis, raxis in self.vectorized.items():\nmap_in_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), in_axes))\nmap_out_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), out_axes))\n- f = vtile(f, map_in_axes, map_out_axes, tile_size=None, axis_name=raxis)\n+ f = pxla.vtile(f, map_in_axes, map_out_axes, tile_size=None, axis_name=raxis)\nresource_env_shape = resource_env.shape\nfor raxis, naxes in self.fake_resource_map.items():\nmap_in_axes = tuple(unsafe_map(lambda spec: lookup_exactly_one_of(spec, naxes), in_axes))\nmap_out_axes = tuple(unsafe_map(lambda spec: lookup_exactly_one_of(spec, naxes), out_axes))\nmap_size = resource_env_shape[raxis]\n- f = vtile(f, map_in_axes, map_out_axes, tile_size=map_size, axis_name=raxis)\n+ f = pxla.vtile(f, map_in_axes, map_out_axes, tile_size=map_size, axis_name=raxis)\nreturn f\n@@ -419,7 +421,14 @@ pe.DynamicJaxprTrace.process_xmap = _dynamic_jaxpr_process_xmap # type: ignore\n# -------- nested xmap handling --------\n-def _xmap_translation_rule(c, axis_env,\n+def _xmap_translation_rule(*args, **kwargs):\n+ if EXPERIMENTAL_SPMD_LOWERING:\n+ return _xmap_translation_rule_spmd(*args, **kwargs)\n+ else:\n+ return _xmap_translation_rule_replica(*args, **kwargs)\n+xla.call_translations[xmap_p] = _xmap_translation_rule\n+\n+def _xmap_translation_rule_replica(c, axis_env,\nin_nodes, name_stack, *,\ncall_jaxpr, name,\nin_axes, out_axes, axis_sizes,\n@@ -461,7 +470,6 @@ def _xmap_translation_rule(c, axis_env,\nin zip(call_jaxpr.outvars, tiled_outs, mesh_out_axes)]\nreturn xops.Tuple(c, outs)\n-xla.call_translations[xmap_p] = _xmap_translation_rule\ndef _xla_tile(c, axis_env, x, in_axes, axis_sizes):\nif not in_axes:\n@@ -520,6 +528,17 @@ def _xla_untile(c, axis_env, x, out_axes, axis_sizes, backend):\nout = xops.ConvertElementType(nonzero, xb.dtype_to_etype(np.bool_))\nreturn out\n+def _xmap_translation_rule_spmd(c, axis_env,\n+ in_nodes, name_stack, *,\n+ call_jaxpr, name,\n+ in_axes, out_axes, axis_sizes,\n+ schedule, resource_env, backend):\n+ # TODO(apaszke): This is quite difficult to implement given the current lowering\n+ # in mesh_tiled_callable. There, we vmap the mapped axes, but we\n+ # have no idea which positional axes they end up being in this\n+ # translation rule!\n+ raise NotImplementedError\n+\n# -------- helper functions --------\n@@ -578,44 +597,6 @@ def hide_mapped_axes(flat_in_axes, flat_out_axes, *flat_args):\nyield map(_unsqueeze_mapped_axes, flat_outputs, flat_out_axes)\n-# NOTE: This divides the in_axes by the tile_size and multiplies the out_axes by it.\n-def vtile(f_flat,\n- in_axes_flat: Tuple[AxisNamePos, ...],\n- out_axes_flat: Tuple[AxisNamePos, ...],\n- tile_size: Optional[int], axis_name):\n- if tile_size == 1:\n- return f_flat\n-\n- @curry\n- def tile_axis(arg, axis: Optional[int], tile_size):\n- if axis is None:\n- return arg\n- shape = list(arg.shape)\n- shape[axis:axis+1] = [tile_size, shape[axis] // tile_size]\n- return arg.reshape(shape)\n-\n- def untile_axis(out, axis: Optional[int]):\n- if axis is None:\n- return out\n- shape = list(out.shape)\n- shape[axis:axis+2] = [shape[axis] * shape[axis+1]]\n- return out.reshape(shape)\n-\n- @lu.transformation\n- def _map_to_tile(*args_flat):\n- sizes = (x.shape[i] for x, i in zip(args_flat, in_axes_flat) if i is not None)\n- tile_size_ = tile_size or next(sizes, None)\n- assert tile_size_ is not None, \"No mapped arguments?\"\n- outputs_flat = yield map(tile_axis(tile_size=tile_size_), args_flat, in_axes_flat), {}\n- yield map(untile_axis, outputs_flat, out_axes_flat)\n-\n- return _map_to_tile(\n- batching.batch_fun(f_flat,\n- in_axes_flat,\n- out_axes_flat,\n- axis_name=axis_name))\n-\n-\ndef _schedule_resources(schedule) -> Set[ResourceAxisName]:\nreturn {resource for _, resource in schedule}\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -47,7 +47,7 @@ from ..abstract_arrays import array_types\nfrom ..core import ConcreteArray, ShapedArray, Var, Literal\nfrom ..util import (partial, unzip2, unzip3, prod, safe_map, safe_zip,\nextend_name_stack, wrap_name, assert_unreachable,\n- tuple_insert, tuple_delete, taggedtuple)\n+ tuple_insert, tuple_delete, taggedtuple, curry)\nfrom ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\nfrom ..tree_util import tree_flatten, tree_map\n@@ -130,6 +130,77 @@ class ShardingSpec:\nself.sharding = tuple(sharding)\nself.mesh_mapping = tuple(mesh_mapping)\n+ @property\n+ def mesh_shape(self):\n+ sharded_axis_sizes = []\n+ for sharding in self.sharding:\n+ if sharding is None:\n+ continue\n+ elif isinstance(sharding, Unstacked):\n+ sharded_axis_sizes.append(sharding.size)\n+ elif isinstance(sharding, Chunked):\n+ sharded_axis_sizes.append(sharding.chunks)\n+ else:\n+ assert_unreachable(sharding)\n+ return tuple(sharded_axis_sizes[a.axis] if isinstance(a, ShardedAxis) else a.replicas\n+ for a in self.mesh_mapping)\n+\n+ def sharding_proto(self):\n+ \"\"\"Converts a ShardingSpec to an OpSharding proto.\n+\n+ See\n+ https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/xla_data.proto#L601\n+ for details on the OpSharding proto.\n+ Unfortunately the semantics are not very well described in the proto spec, but the code here might help:\n+ https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/experimental/xla_sharding/xla_sharding.py\n+ \"\"\"\n+ mesh_shape = self.mesh_shape\n+ mesh = np.arange(np.prod(mesh_shape)).reshape(mesh_shape)\n+\n+ sharded_axes = {} # maps sharded axis identifiers to mesh axis indices to which they're mapped\n+ replicated_maxes = [] # lists mesh axis identifiers to replicate over\n+ for maxis, assignment in enumerate(self.mesh_mapping):\n+ if isinstance(assignment, Replicated):\n+ replicated_maxes.append(maxis)\n+ elif isinstance(assignment, ShardedAxis):\n+ sharded_axes[assignment.axis] = maxis\n+ else:\n+ assert_unreachable(assignment)\n+\n+ proto = xc.OpSharding()\n+ if len(replicated_maxes) == len(self.mesh_mapping):\n+ proto.type = xc.OpSharding.Type.REPLICATED\n+ return proto\n+ else:\n+ proto.type = xc.OpSharding.Type.OTHER\n+\n+ mesh_permutation = []\n+ new_mesh_shape = []\n+ next_sharded_axis = 0\n+ for axis, sharding in enumerate(self.sharding):\n+ if sharding is None:\n+ new_mesh_shape.append(1) # Add a dummy mesh axis we won't be sharding over\n+ elif isinstance(sharding, Chunked):\n+ maxis = sharded_axes[next_sharded_axis]\n+ mesh_permutation.append(maxis)\n+ new_mesh_shape.append(mesh_shape[maxis])\n+ next_sharded_axis += 1\n+ elif isinstance(sharding, Unstacked):\n+ raise RuntimeError(\"Cannot convert unstacked sharding specs to XLA OpSharding\")\n+ else:\n+ assert_unreachable(sharding)\n+\n+ # Create the partial sharding proto if tensor is replicated over some mesh axes\n+ if replicated_maxes:\n+ new_mesh_shape.append(-1)\n+ mesh_permutation.extend(replicated_maxes)\n+ proto.replicate_on_last_tile_dim = True\n+\n+ proto_mesh = mesh.transpose(mesh_permutation).reshape(new_mesh_shape)\n+ proto.tile_assignment_dimensions = list(proto_mesh.shape)\n+ proto.tile_assignment_devices = list(proto_mesh.flat)\n+ return proto\n+\ndef indices(self, shape: Tuple[int, ...]) -> np.ndarray:\n\"\"\"Returns NumPy-style indices corresponding to a sharding spec.\n@@ -712,7 +783,8 @@ def parallel_callable(fun: lu.WrappedFun,\nxla_consts = map(partial(xb.constant, c), consts)\nreplicated_args = [axis is None for axis in in_axes]\nxla_args, donated_invars = xla._xla_callable_args(c, global_sharded_avals, tuple_args,\n- replicated_args, arg_parts,\n+ replicated=replicated_args,\n+ partitions=arg_parts,\ndonated_invars=donated_invars)\nwith maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\nout_nodes = xla.jaxpr_subcomp(c, jaxpr, backend_name, axis_env, xla_consts,\n@@ -1246,86 +1318,163 @@ def mesh_tiled_callable(fun: lu.WrappedFun,\nmesh: Mesh,\nin_axes: Sequence[AxisNameMap],\nout_axes: Sequence[AxisNameMap],\n- *in_avals):\n+ spmd_lowering,\n+ *local_in_untiled_avals):\nassert config.omnistaging_enabled\nlocal_mesh = mesh.local_mesh\n-\n- # TODO: We might want to select a submesh instead of replicating over all devices.\n- # We need at least (1) the axes over which we shard inputs/outputs (2) the\n- # axes used in nested invocations. Should this happen here, or in caller APIs?\n-\nglobal_axis_sizes = mesh.shape\nlocal_axis_sizes = local_mesh.shape\n- sharded_avals = tuple(tile_aval_nd(local_axis_sizes, aval_in_axes, aval)\n- for aval_in_axes, aval in zip(in_axes, in_avals))\n- with core.extend_axis_env_nd(mesh.shape.items()):\n- jaxpr, out_sharded_avals, consts = pe.trace_to_jaxpr_final(fun, sharded_avals)\n- _sanitize_mesh_jaxpr(jaxpr)\n- jaxpr = xla.apply_outfeed_rewriter(jaxpr)\n- assert len(out_axes) == len(out_sharded_avals)\n-\n- is_multi_host = local_mesh.shape == mesh.shape\n- if is_multi_host:\n- check_multihost_collective_allowlist(jaxpr)\nlog_priority = logging.WARNING if FLAGS.jax_log_compiles else logging.DEBUG\nlogging.log(log_priority,\nf\"Compiling {fun.__name__} for {tuple(global_axis_sizes.items())} \"\n- f\"mesh with args {in_avals}. Argument mapping: {in_axes}.\")\n-\n- axis_env = xla.AxisEnv(nreps=mesh.size,\n- names=tuple(global_axis_sizes.keys()),\n- sizes=tuple(global_axis_sizes.values()))\n- tuple_args = len(sharded_avals) > 100 # pass long arg lists as tuple for TPU\n+ f\"mesh with args {local_in_untiled_avals}. Argument mapping: {in_axes}.\")\n+\n+ # 1. Trace to jaxpr and preprocess/verify it\n+ in_tiled_avals = [tile_aval_nd(local_axis_sizes, aval_in_axes, aval)\n+ for aval, aval_in_axes in zip(local_in_untiled_avals, in_axes)]\n+ if spmd_lowering:\n+ # TODO: Consider handling xmap's 'vectorize' in here. We can vmap once instead of vtile twice!\n+ for name, size in reversed(mesh.shape.items()):\n+ fun = vtile(fun,\n+ tuple(a.get(name, None) for a in in_axes),\n+ tuple(a.get(name, None) for a in out_axes),\n+ tile_size=size, axis_name=name)\n+ global_in_untiled_avals = [untile_aval_nd(global_axis_sizes, aval_in_axes, aval)\n+ for aval, aval_in_axes in zip(in_tiled_avals, in_axes)]\n+ in_jaxpr_avals = global_in_untiled_avals\n+ else:\n+ in_jaxpr_avals = in_tiled_avals\n+ with core.extend_axis_env_nd(mesh.shape.items()):\n+ jaxpr, out_jaxpr_avals, consts = pe.trace_to_jaxpr_final(fun, in_jaxpr_avals)\n+ assert len(out_axes) == len(out_jaxpr_avals)\n+ if spmd_lowering:\n+ global_out_untiled_avals = out_jaxpr_avals\n+ out_tiled_avals = [tile_aval_nd(global_axis_sizes, aval_out_axes, aval)\n+ for aval, aval_out_axes in zip(global_out_untiled_avals, out_axes)]\n+ else:\n+ out_tiled_avals = out_jaxpr_avals\n+ local_out_untiled_avals = [untile_aval_nd(local_axis_sizes, aval_out_axes, aval)\n+ for aval, aval_out_axes in zip(out_tiled_avals, out_axes)]\n+ _sanitize_mesh_jaxpr(jaxpr)\n+ if local_mesh.shape != mesh.shape:\n+ check_multihost_collective_allowlist(jaxpr)\n+ jaxpr = xla.apply_outfeed_rewriter(jaxpr)\n+ # 3. Build up the HLO\nc = xb.make_computation_builder(f\"xmap_{fun.__name__}\")\nxla_consts = map(partial(xb.constant, c), consts)\n+ donated_invars = (False,) * len(in_jaxpr_avals) # TODO(apaszke): support donation\n+ tuple_args = len(in_jaxpr_avals) > 100 # pass long arg lists as tuple for TPU\n+ in_partitions: Optional[List]\n+ if spmd_lowering:\n+ replicated_args = [False] * len(in_jaxpr_avals)\n+ global_sharding_spec = mesh_sharding_specs(global_axis_sizes, mesh.axis_names)\n+ in_partitions = [global_sharding_spec(aval, aval_in_axes).sharding_proto()\n+ if aval is not core.abstract_unit else None\n+ for aval, aval_in_axes in zip(global_in_untiled_avals, in_axes)]\n+ out_partitions = [global_sharding_spec(aval, aval_out_axes).sharding_proto()\n+ for aval, aval_out_axes in zip(global_out_untiled_avals, out_axes)]\n+ partitions_proto = True\n+ axis_env = xla.AxisEnv(nreps=1, names=(), sizes=()) # All named axes have been vmapped\n+ else:\nreplicated_args = [not axis for axis in in_axes]\n- donated_invars = (False,) * len(sharded_avals) # TODO(apaszke): support donation\n- xla_args, donated_invars = xla._xla_callable_args(c, sharded_avals, tuple_args,\n- replicated_args,\n- partitions=None, # TODO(apaszke): partitions\n+ in_partitions = None\n+ partitions_proto = False\n+ axis_env = xla.AxisEnv(nreps=mesh.size,\n+ names=tuple(global_axis_sizes.keys()),\n+ sizes=tuple(global_axis_sizes.values()))\n+ xla_args, donated_invars = xla._xla_callable_args(\n+ c, in_jaxpr_avals, tuple_args,\n+ replicated=replicated_args,\n+ partitions=in_partitions,\n+ partitions_proto=partitions_proto,\ndonated_invars=donated_invars)\nwith core.extend_axis_env_nd(mesh.shape.items()):\n- out_nodes = xla.jaxpr_subcomp(c, jaxpr, backend_name, axis_env, xla_consts,\n+ out_nodes = xla.jaxpr_subcomp(\n+ c, jaxpr, backend_name, axis_env, xla_consts,\nextend_name_stack(wrap_name(transformed_name, 'xmap')), *xla_args)\n- # TODO(apaszke): partitions\n- out_tuple = xops.Tuple(c, out_nodes)\nbackend = xb.get_backend(backend_name)\n+ if spmd_lowering:\n+ out_partitions_t = xb.tuple_sharding_proto(out_partitions)\n+ out_tuple = xb.with_sharding_proto(c, out_partitions_t, xops.Tuple, c, out_nodes)\n+ else:\n+ out_tuple = xops.Tuple(c, out_nodes)\n+ # TODO(apaszke): Does that work with SPMD sharding?\nif backend.platform in (\"gpu\", \"tpu\"):\ndonated_invars = xla.set_up_aliases(c, xla_args, out_tuple, donated_invars, tuple_args)\nbuilt = c.Build(out_tuple)\n- # We add a dummy second dimension to represent the partition dimension.\n- device_assignment = mesh.device_ids.reshape((mesh.size, 1)) # TODO(apaszke): partitions\n+ # 4. Compile the HLO\n+ if spmd_lowering:\n+ num_replicas, num_partitions = 1, mesh.size\n+ num_local_replicas, num_local_partitions = 1, local_mesh.size\n+ else:\n+ num_replicas, num_partitions = mesh.size, 1\n+ num_local_replicas, num_local_partitions = local_mesh.size, 1\n+ device_assignment = mesh.device_ids.reshape((num_replicas, num_partitions))\ncompile_options = xb.get_compile_options(\n- num_replicas=mesh.size,\n- num_partitions=1,\n+ num_replicas=num_replicas,\n+ num_partitions=num_partitions,\ndevice_assignment=device_assignment,\n- use_spmd_partitioning=False, # TODO(apaszke): partitions\n+ use_spmd_partitioning=spmd_lowering,\n)\ncompile_options.parameter_is_tupled_arguments = tuple_args\ncompiled = xla.backend_compile(backend, built, compile_options)\n- # Argument specs and handler\n- get_sharding_spec = mesh_sharding_specs(local_axis_sizes, mesh.axis_names)\n- input_specs = [get_sharding_spec(aval, aval_in_axes)\n+ # 5. Argument sharding / output wrapping\n+ local_sharding_spec = mesh_sharding_specs(local_axis_sizes, mesh.axis_names)\n+ local_input_specs = [local_sharding_spec(aval, aval_in_axes)\nif aval is not core.abstract_unit else None\n- for aval, aval_in_axes in zip(in_avals, in_axes)]\n+ for aval, aval_in_axes in zip(local_in_untiled_avals, in_axes)]\ninput_indices = [spec_to_indices(aval.shape, spec)\nif spec is not None else None\n- for aval, spec in zip(in_avals, input_specs)]\n+ for aval, spec in zip(local_in_untiled_avals, local_input_specs)]\nhandle_args = partial(shard_args, compiled.local_devices(), input_indices)\n- # Output specs and handler\n- output_avals = [untile_aval_nd(local_axis_sizes, aval_out_axes, aval)\n- for aval_out_axes, aval in zip(out_axes, out_sharded_avals)]\n- output_specs = [get_sharding_spec(aval, aval_out_axes)\n- for aval_out_axes, aval in zip(out_axes, output_avals)]\n- handle_outs = avals_to_results_handler(local_mesh.size, 1, output_specs, output_avals)\n+ local_output_specs = [local_sharding_spec(aval, aval_out_axes)\n+ for aval, aval_out_axes in zip(local_out_untiled_avals, out_axes)]\n+ handle_outs = avals_to_results_handler(num_local_replicas, num_local_partitions,\n+ local_output_specs, local_out_untiled_avals)\nreturn partial(execute_replicated, compiled, backend, handle_args, handle_outs)\n+# NOTE: This divides the in_axes by the tile_size and multiplies the out_axes by it.\n+def vtile(f_flat,\n+ in_axes_flat: Tuple[Optional[int], ...],\n+ out_axes_flat: Tuple[Optional[int], ...],\n+ tile_size: Optional[int], axis_name):\n+ if tile_size == 1:\n+ return f_flat\n+\n+ @curry\n+ def tile_axis(arg, axis: Optional[int], tile_size):\n+ if axis is None:\n+ return arg\n+ shape = list(arg.shape)\n+ shape[axis:axis+1] = [tile_size, shape[axis] // tile_size]\n+ return arg.reshape(shape)\n+\n+ def untile_axis(out, axis: Optional[int]):\n+ if axis is None:\n+ return out\n+ shape = list(out.shape)\n+ shape[axis:axis+2] = [shape[axis] * shape[axis+1]]\n+ return out.reshape(shape)\n+\n+ @lu.transformation\n+ def _map_to_tile(*args_flat):\n+ sizes = (x.shape[i] for x, i in zip(args_flat, in_axes_flat) if i is not None)\n+ tile_size_ = tile_size or next(sizes, None)\n+ assert tile_size_ is not None, \"No mapped arguments?\"\n+ outputs_flat = yield map(tile_axis(tile_size=tile_size_), args_flat, in_axes_flat), {}\n+ yield map(untile_axis, outputs_flat, out_axes_flat)\n+\n+ return _map_to_tile(\n+ batching.batch_fun(f_flat,\n+ in_axes_flat,\n+ out_axes_flat,\n+ axis_name=axis_name))\n_forbidden_primitives = {\n'xla_pmap': 'pmap',\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -768,8 +768,10 @@ def _xla_callable_device(nreps, backend, device, arg_devices):\n_replicated_param = object()\ndef _xla_callable_args(\n- c, avals, tuple_args, replicated=None,\n- partitions: Optional[Sequence[Optional[Sequence[int]]]] = None,\n+ c, avals, tuple_args, *,\n+ replicated=None,\n+ partitions=None,\n+ partitions_proto: bool = False,\ndonated_invars=None):\nassert partitions is None or len(partitions) == len(avals)\nif not tuple_args:\n@@ -777,11 +779,13 @@ def _xla_callable_args(\nreplicated = [None] * len(avals)\nif partitions is None:\nparts: List[object] = [None] * len(avals)\n+ elif partitions_proto:\n+ parts = partitions\nelse:\nparts = [_replicated_param if part is None else part\nfor part in partitions]\ncounts = it.count()\n- xla_args = [_xla_param(c, next(counts), xla_shape, r, p)\n+ xla_args = [_xla_param(c, next(counts), xla_shape, r, p, partitions_proto)\nif a is not abstract_token else xops.CreateToken(c)\nfor (a, r, p) in safe_zip(avals, replicated, parts)\nfor xla_shape in aval_to_xla_shapes(a)]\n@@ -794,25 +798,31 @@ def _xla_callable_args(\nif replicated is not None:\nreplicated = [r for a, r in zip(avals, replicated)\nif a is not abstract_token]\n- tuple_parts = tuple(partitions) if partitions is not None else None\n+ if partitions is None:\n+ tuple_parts = None\n+ elif partitions_proto:\n+ tuple_parts = xb.tuple_sharding_proto(partitions)\n+ else:\n+ tuple_parts = tuple(partitions)\ntuple_shape = xc.Shape.tuple_shape(\n[shape for a in avals for shape in aval_to_xla_shapes(a) if a is not abstract_token])\n- tuple_param = _xla_param(c, 0, tuple_shape, replicated, tuple_parts)\n+ tuple_param = _xla_param(c, 0, tuple_shape, replicated, tuple_parts, partitions_proto)\nxla_inputs = iter(xla_destructure(c, tuple_param))\nxla_args = [next(xla_inputs) if a is not abstract_token else\nxops.CreateToken(c) for a in avals]\nassert next(xla_inputs, None) is None\nreturn xla_args, donated_invars\n-def _xla_param(builder, param_num, xla_shape, replicated, partitions):\n+def _xla_param(builder, param_num, xla_shape, replicated, partitions, parts_proto):\nmake_param = partial(xb.parameter, builder, param_num, xla_shape,\nreplicated=replicated)\n+ with_sharding = xb.with_sharding_proto if parts_proto else xb.with_sharding\nif partitions is None:\nreturn make_param()\nelif partitions is _replicated_param:\n- return xb.with_sharding(builder, None, make_param)\n+ return with_sharding(builder, None, make_param)\nelse:\n- return xb.with_sharding(builder, partitions, make_param)\n+ return with_sharding(builder, partitions, make_param)\ndef _execute_compiled(compiled: XlaExecutable, avals, handlers, *args):\ndevice, = compiled.local_devices()\n" }, { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -352,10 +352,7 @@ def _sharding_to_proto(sharding: SpatialSharding):\nproto = xla_client.OpSharding()\nif isinstance(sharding, tuple) and not isinstance(sharding[0], int):\nassert all(s is None or isinstance(s, tuple) for s in sharding)\n- sub_protos = [_sharding_to_proto(s) for s in sharding] # type: ignore\n- proto.type = xla_client.OpSharding.Type.TUPLE\n- proto.tuple_shardings = sub_protos\n- return proto\n+ return tuple_sharding_proto(list(map(_sharding_to_proto, sharding))) # type: ignore\nif sharding is None:\nproto.type = xla_client.OpSharding.Type.REPLICATED\n@@ -365,21 +362,36 @@ def _sharding_to_proto(sharding: SpatialSharding):\nproto.tile_assignment_devices = list(range(np.product(sharding)))\nreturn proto\n-def set_sharding(builder, op, sharding: SpatialSharding):\n+def tuple_sharding_proto(elems):\n+ proto = xla_client.OpSharding()\n+ assert all(isinstance(e, type(proto)) for e in elems)\n+ proto.type = xla_client.OpSharding.Type.TUPLE\n+ proto.tuple_shardings = elems\n+ return proto\n+\n+def set_sharding_proto(builder, op, sharding_proto):\n\"\"\"Uses CustomCall to annotate a value as sharded.\"\"\"\n# \"Sharding\" is a built-in custom call target that acts like an identity\n# function, and is used to attach an OpSharding to.\n- return with_sharding(builder, sharding, xops.CustomCall,\n+ return with_sharding_proto(builder, sharding_proto, xops.CustomCall,\nbuilder, b\"Sharding\", [op], builder.get_shape(op))\n-def with_sharding(builder, sharding: SpatialSharding, op_fn, *args, **kwargs):\n+def with_sharding_proto(builder, sharding_proto, op_fn, *args, **kwargs):\n\"\"\"Builds op_fn(*args, **kwargs) with sharding annotation.\"\"\"\n- builder.set_sharding(_sharding_to_proto(sharding))\n+ builder.set_sharding(sharding_proto)\ntry:\nreturn op_fn(*args, **kwargs)\nfinally:\nbuilder.clear_sharding()\n+def set_sharding(builder, op, sharding: SpatialSharding):\n+ \"\"\"Uses CustomCall to annotate a value as sharded.\"\"\"\n+ return set_sharding_proto(builder, op, _sharding_to_proto(sharding))\n+\n+def with_sharding(builder, sharding: SpatialSharding, op_fn, *args, **kwargs):\n+ \"\"\"Builds op_fn(*args, **kwargs) with sharding annotation.\"\"\"\n+ return with_sharding_proto(builder, _sharding_to_proto(sharding), op_fn, *args, **kwargs)\n+\ndef make_computation_builder(name):\nreturn xla_client.XlaBuilder(name)\n" }, { "change_type": "MODIFY", "old_path": "tests/gmap_test.py", "new_path": "tests/gmap_test.py", "diff": "@@ -101,6 +101,19 @@ def with_mesh(named_shape, f):\nreturn f(*args, **kwargs)\nreturn new_f\n+def use_spmd_lowering(f):\n+ def new_f(*args, **kwargs):\n+ if jtu.device_under_test() != \"tpu\":\n+ raise SkipTest\n+ jax.experimental.general_map.make_xmap_callable.cache_clear()\n+ old = jax.experimental.general_map.EXPERIMENTAL_SPMD_LOWERING\n+ jax.experimental.general_map.EXPERIMENTAL_SPMD_LOWERING = True\n+ try:\n+ return f(*args, **kwargs)\n+ finally:\n+ jax.experimental.general_map.EXPERIMENTAL_SPMD_LOWERING = old\n+ return new_f\n+\nclass GmapTest(jtu.JaxTestCase):\n@@ -140,6 +153,8 @@ class GmapTest(jtu.JaxTestCase):\nself.assertAllClose(gmap(gmap(f, s, axis_name='i'), s, axis_name='j')(x),\nvmap(vmap(f, axis_name='i'), axis_name='j')(x))\n+class XMapTest(jtu.JaxTestCase):\n+\n@ignore_gmap_warning()\n@skipIf(not config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\n@@ -215,6 +230,8 @@ class GmapTest(jtu.JaxTestCase):\nself.assertAllClose(c, a * 2)\nself.assertAllClose(d, b * 4)\n+ testXMapMeshBasicSPMD = use_spmd_lowering(testXMapMeshBasic)\n+\n@ignore_gmap_warning()\ndef testXMapMeshCollectives(self):\nlocal_devices = list(jax.local_devices())\n@@ -242,6 +259,8 @@ class GmapTest(jtu.JaxTestCase):\nself.assertAllClose(c, (a * 2).sum(0))\nself.assertAllClose(d, b * 4)\n+ testXMapMeshCollectivesSPMD = use_spmd_lowering(testXMapMeshCollectives)\n+\n@ignore_gmap_warning()\n@with_mesh([('x', 2)])\ndef testXMapCompilationCache(self):\n@@ -316,6 +335,5 @@ class GmapTest(jtu.JaxTestCase):\nf(x)\n-\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add an experimental xmap lowering via the SPMD partitioner As suggested by @jekbradbury. The SPMD partitioner might allow us to avoid writing partitioning formulas on the JAX level and can result in better performance by giving the compiler more flexibility.
260,335
30.11.2020 08:55:55
28,800
ac0f07139eda6679cf2c829736a933dce7f780eb
add pdot_p to unsupported jax2tf primitives
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -837,7 +837,7 @@ tf_not_yet_impl = [\nlax.after_all_p, lax_parallel.all_to_all_p, lax.create_token_p,\nlax.infeed_p, lax.outfeed_p, lax_parallel.pmax_p,\nlax_parallel.pmin_p, lax_parallel.ppermute_p, lax_parallel.psum_p,\n- lax_parallel.axis_index_p,\n+ lax_parallel.axis_index_p, lax_parallel.pdot_p,\npxla.xla_pmap_p,\n]\n" } ]
Python
Apache License 2.0
google/jax
add pdot_p to unsupported jax2tf primitives
260,519
13.11.2020 13:17:16
-19,080
2c822203dfc89f81f7632572e7385d58f3939104
More stable implementation of np.hypot
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -986,7 +986,10 @@ def heaviside(x1, x2):\ndef hypot(x1, x2):\n_check_arraylike(\"hypot\", x1, x2)\nx1, x2 = _promote_dtypes_inexact(x1, x2)\n- return lax.sqrt(x1*x1 + x2*x2)\n+ x1 = lax.abs(x1)\n+ x2 = lax.abs(x2)\n+ x1, x2 = maximum(x1, x2), minimum(x1, x2)\n+ return lax.select(x1 == 0, x1, x1 * lax.sqrt(1 + lax.square(lax.div(x2, lax.select(x1 == 0, ones_like(x1), x1)))))\n@_wraps(np.reciprocal)\n" } ]
Python
Apache License 2.0
google/jax
More stable implementation of np.hypot
260,335
02.12.2020 00:36:39
28,800
8cd855507179e21bfdc0e518025bf8957fc8e342
improve sinc jvp at zero, fixes
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1005,10 +1005,24 @@ def sinc(x):\n_check_arraylike(\"sinc\", x)\nx, = _promote_dtypes_inexact(x)\neq_zero = lax.eq(x, lax._const(x, 0))\n- safe_x = where(eq_zero, lax._const(x, 0), x)\n- pi_x = lax.mul(lax._const(x, pi), safe_x)\n- return where(eq_zero,\n- lax._const(x, 1), lax.div(lax.sin(pi_x), pi_x))\n+ pi_x = lax.mul(lax._const(x, pi), x)\n+ safe_pi_x = where(eq_zero, lax._const(x, 0), pi_x)\n+ return where(eq_zero, _sinc_maclaurin(0, pi_x),\n+ lax.div(lax.sin(safe_pi_x), safe_pi_x))\n+\n+@partial(custom_jvp, nondiff_argnums=(0,))\n+def _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+ if k % 2:\n+ return lax._const(x, 0)\n+ else:\n+ return lax._const(x, (-1) ** (k // 2) / (k + 1))\n+\n+@_sinc_maclaurin.defjvp\n+def _sinc_maclaurin_jvp(k, primals, tangents):\n+ (x,), (t,) = primals, tangents\n+ return _sinc_maclaurin(k, x), _sinc_maclaurin(k + 1, x) * t\n@_wraps(np.transpose)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -4531,6 +4531,33 @@ class NumpyGradTests(jtu.JaxTestCase):\ncheck_grads(op, (special_value,), order, [\"fwd\", \"rev\"],\natol={np.float32: 3e-3})\n+ def testSincAtZero(self):\n+ # Some manual tests for sinc at zero, since it doesn't have well-behaved\n+ # numerical derivatives at zero\n+ def deriv(f):\n+ return lambda x: api.jvp(f, (x,), (1.,))[1]\n+\n+ def apply_all(fns, x):\n+ for f in fns:\n+ x = f(x)\n+ return x\n+\n+ d1 = 0.\n+ for ops in itertools.combinations_with_replacement([deriv, api.grad], 1):\n+ self.assertAllClose(apply_all(ops, jnp.sinc)(0.), d1)\n+\n+ d2 = -np.pi ** 2 / 3\n+ for ops in itertools.combinations_with_replacement([deriv, api.grad], 2):\n+ self.assertAllClose(apply_all(ops, jnp.sinc)(0.), d2)\n+\n+ d3 = 0.\n+ for ops in itertools.combinations_with_replacement([deriv, api.grad], 3):\n+ self.assertAllClose(apply_all(ops, jnp.sinc)(0.), d3)\n+\n+ d4 = np.pi ** 4 / 5\n+ for ops in itertools.combinations_with_replacement([deriv, api.grad], 4):\n+ self.assertAllClose(apply_all(ops, jnp.sinc)(0.), d4)\n+\ndef testTakeAlongAxisIssue1521(self):\n# https://github.com/google/jax/issues/1521\nidx = jnp.repeat(jnp.arange(3), 10).reshape((30, 1))\n" } ]
Python
Apache License 2.0
google/jax
improve sinc jvp at zero, fixes #5054
260,287
27.11.2020 16:44:08
0
d3136b44c85705eec6ed4d13e8c1bfd283ac4009
Remove fake xmap resources, remove gmap xmap can now handle real devices, so there's no point in maintaining the simulated codepaths. Also, remove single-dimensional gmap as it will have to be superseeded by a more xmap-friendly alternative.
[ { "change_type": "MODIFY", "old_path": "jax/BUILD", "new_path": "jax/BUILD", "diff": "@@ -86,8 +86,8 @@ pytype_library(\n)\npytype_library(\n- name = \"general_map\",\n- srcs = [\"experimental/general_map.py\"],\n+ name = \"maps\",\n+ srcs = [\"experimental/maps.py\"],\nsrcs_version = \"PY3\",\ndeps = [\":jax\"],\n)\n" }, { "change_type": "RENAME", "old_path": "jax/experimental/general_map.py", "new_path": "jax/experimental/maps.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-import enum\nimport threading\nimport contextlib\nimport numpy as np\nimport itertools as it\n-from collections import namedtuple, OrderedDict\n+from collections import OrderedDict\nfrom typing import (Callable, Iterable, List, Tuple, Optional, Dict, Any, Set,\nNamedTuple)\nfrom warnings import warn\nfrom functools import wraps, partial\n-import jax\nfrom .. import numpy as jnp\nfrom .. import core\nfrom .. import linear_util as lu\n-from ..api import _mapped_axis_size, _check_callable, _check_arg\n+from ..api import _check_callable, _check_arg\nfrom ..tree_util import tree_flatten, tree_unflatten, tree_leaves\n-from ..api_util import flatten_fun, flatten_fun_nokwargs, flatten_axes\n+from ..api_util import flatten_fun_nokwargs, flatten_axes\nfrom ..interpreters import partial_eval as pe\nfrom ..interpreters import pxla\nfrom ..interpreters import xla\n@@ -78,31 +76,23 @@ Mesh = pxla.Mesh\n# TODO: Support sequential mapping\nclass ResourceEnv:\n- __slots__ = ('physical_mesh', 'fake_resources')\n+ __slots__ = ('physical_mesh',)\nphysical_mesh: Mesh\n- fake_resources: FrozenDict\n- def __init__(self, physical_mesh: Mesh, fake_resources: FrozenDict):\n+ def __init__(self, physical_mesh: Mesh):\nsuper().__setattr__('physical_mesh', physical_mesh)\n- super().__setattr__('fake_resources', fake_resources)\n@property\ndef physical_resource_axes(self) -> Set[ResourceAxisName]:\nreturn set(self.physical_mesh.axis_names)\n- @property\n- def fake_resource_axes(self) -> Set[ResourceAxisName]:\n- return set(self.fake_resources.keys())\n-\n@property\ndef resource_axes(self) -> Set[ResourceAxisName]:\n- return self.physical_resource_axes | self.fake_resource_axes\n+ return self.physical_resource_axes\n@property\ndef shape(self):\n- shape = OrderedDict(self.physical_mesh.shape)\n- shape.update((name, size) for name, size in self.fake_resources.items())\n- return shape\n+ return OrderedDict(self.physical_mesh.shape)\ndef __setattr__(self, name, value):\nraise RuntimeError(\"ResourceEnv is immutable!\")\n@@ -112,28 +102,18 @@ class ResourceEnv:\ndef __eq__(self, other):\nreturn (type(other) is ResourceEnv and\n- self.physical_mesh == other.physical_mesh and\n- self.fake_resources == other.fake_resources)\n+ self.physical_mesh == other.physical_mesh)\ndef __hash__(self):\n- return hash((self.physical_mesh, self.fake_resources))\n+ return hash(self.physical_mesh)\nthread_resources = threading.local()\n-thread_resources.env = ResourceEnv(Mesh(np.empty((), dtype=object), ()), FrozenDict())\n-\n-@contextlib.contextmanager\n-def fake_resources(**axes):\n- old_env = thread_resources.env\n- thread_resources.env = ResourceEnv(old_env.physical_mesh, FrozenDict(axes))\n- try:\n- yield\n- finally:\n- thread_resources.env = old_env\n+thread_resources.env = ResourceEnv(Mesh(np.empty((), dtype=object), ()))\n@contextlib.contextmanager\ndef mesh(*args, **kwargs):\nold_env = thread_resources.env\n- thread_resources.env = ResourceEnv(Mesh(*args, **kwargs), old_env.fake_resources)\n+ thread_resources.env = ResourceEnv(Mesh(*args, **kwargs))\ntry:\nyield\nfinally:\n@@ -209,6 +189,7 @@ def xmap(fun: Callable,\nif len(set(frozen_schedule)) != len(frozen_schedule):\nraise ValueError(f\"xmap schedule contains duplicate entries: {frozen_schedule}\")\n+ @wraps(fun)\ndef fun_mapped(*args):\n# Putting this outside of fun_mapped would make resources lexically scoped\nresource_env = thread_resources.env\n@@ -266,7 +247,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\nf = lu.wrap_init(core.jaxpr_as_fun(core.ClosedJaxpr(jaxpr, consts)))\nf = hide_mapped_axes(f, tuple(in_axes), tuple(out_axes))\n- f = plan.vectorize(f, in_axes, out_axes, resource_env)\n+ f = plan.vectorize(f, in_axes, out_axes)\nused_resources = _jaxpr_resources(jaxpr, resource_env) | _schedule_resources(schedule)\nused_mesh_axes = used_resources & resource_env.physical_resource_axes\n@@ -286,7 +267,6 @@ def make_xmap_callable(fun: lu.WrappedFun,\nclass EvaluationPlan(NamedTuple):\n\"\"\"Encapsulates preprocessing common to top-level xmap invocations and its translation rule.\"\"\"\n- fake_resource_map: Dict[ResourceAxisName, Set[AxisName]]\nphysical_resource_map: Dict[ResourceAxisName, Set[AxisName]]\nvectorized: Dict[AxisName, ResourceAxisName]\naxis_subst: Dict[AxisName, Tuple[ResourceAxisName, ...]]\n@@ -303,7 +283,6 @@ class EvaluationPlan(NamedTuple):\n# the schedule to break ties.\n# Technically the order doesn't matter right now, but we use the ordered dict\n# to at least limit the amount of non-determinism in this code.\n- fake_resource_map: Dict[ResourceAxisName, Set[AxisName]] = OrderedDict()\nphysical_resource_map: Dict[ResourceAxisName, Set[AxisName]] = OrderedDict()\nvectorized: Dict[AxisName, ResourceAxisName] = OrderedDict()\n@@ -315,28 +294,18 @@ class EvaluationPlan(NamedTuple):\nvectorized[axis] = resource\nelif resource in resource_env.physical_resource_axes:\nphysical_resource_map.setdefault(resource, set()).add(axis)\n- elif resource in resource_env.fake_resource_axes:\n- fake_resource_map.setdefault(resource, set()).add(axis)\nelse:\nraise ValueError(f\"Mapping axis {axis} to an undefined resource axis {resource}. \"\nf\"The resource axes currently in scope are: {resource_env.resource_axes}\")\naxis_subst.setdefault(axis, []).append(resource)\naxis_subst_t = {name: tuple(axes) for name, axes in axis_subst.items()}\n- return cls(fake_resource_map, physical_resource_map, vectorized, axis_subst_t)\n+ return cls(physical_resource_map, vectorized, axis_subst_t)\n- def vectorize(self, f: lu.WrappedFun, in_axes, out_axes, resource_env):\n+ def vectorize(self, f: lu.WrappedFun, in_axes, out_axes):\nfor naxis, raxis in self.vectorized.items():\nmap_in_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), in_axes))\nmap_out_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), out_axes))\nf = pxla.vtile(f, map_in_axes, map_out_axes, tile_size=None, axis_name=raxis)\n-\n- resource_env_shape = resource_env.shape\n- for raxis, naxes in self.fake_resource_map.items():\n- map_in_axes = tuple(unsafe_map(lambda spec: lookup_exactly_one_of(spec, naxes), in_axes))\n- map_out_axes = tuple(unsafe_map(lambda spec: lookup_exactly_one_of(spec, naxes), out_axes))\n- map_size = resource_env_shape[raxis]\n- f = pxla.vtile(f, map_in_axes, map_out_axes, tile_size=map_size, axis_name=raxis)\n-\nreturn f\ndef to_mesh_axes(self, in_axes, out_axes):\n@@ -448,7 +417,7 @@ def _xmap_translation_rule_replica(c, axis_env,\nin zip(call_jaxpr.invars, in_axes, mesh_in_axes)]\nf = lu.wrap_init(core.jaxpr_as_fun(core.ClosedJaxpr(call_jaxpr, ())))\nf = hide_mapped_axes(f, tuple(in_axes), tuple(out_axes))\n- f = plan.vectorize(f, in_axes, out_axes, resource_env)\n+ f = plan.vectorize(f, in_axes, out_axes)\nvectorized_jaxpr, _, consts = pe.trace_to_jaxpr_final(f, local_avals)\nassert not consts\n@@ -614,148 +583,6 @@ def _jaxpr_resources(jaxpr, resource_env) -> Set[ResourceAxisName]:\nused_resources |= update\nreturn used_resources\n-\n-# Single-dimensional generalized map\n-\n-def gmap(fun: Callable, schedule, axis_name = None) -> Callable:\n- warn(\"gmap is an experimental feature and probably has bugs!\")\n- _check_callable(fun)\n- binds_axis_name = axis_name is not None\n- axis_name = core._TempAxisName(fun) if axis_name is None else axis_name\n-\n- @wraps(fun)\n- def f_gmapped(*args, **kwargs):\n- f = lu.wrap_init(fun)\n- args_flat, in_tree = tree_flatten((args, kwargs))\n- in_axes = (0,) * len(args_flat)\n- axis_size = _mapped_axis_size(in_tree, args_flat, (0,) * len(args_flat), \"gmap\")\n- parsed_schedule = _normalize_schedule(schedule, axis_size, binds_axis_name)\n- for arg in args_flat: _check_arg(arg)\n- flat_fun, out_tree = flatten_fun(f, in_tree)\n- outs = gmap_p.bind(\n- flat_fun, *args_flat,\n- axis_name=axis_name,\n- axis_size=axis_size,\n- in_axes=in_axes,\n- out_axes_thunk=lambda: (0,) * out_tree().num_leaves,\n- schedule=parsed_schedule,\n- binds_axis_name=binds_axis_name)\n- return tree_unflatten(out_tree(), outs)\n- return f_gmapped\n-\n-\n-class LoopType(enum.Enum):\n- vectorized = enum.auto()\n- parallel = enum.auto()\n- sequential = enum.auto()\n-\n-Loop = namedtuple('Loop', ['type', 'size'])\n-\n-\n-def _normalize_schedule(schedule, axis_size, binds_axis_name):\n- if not schedule:\n- raise ValueError(\"gmap expects a non-empty schedule\")\n-\n- scheduled = 1\n- seen_none = False\n- for loop in schedule:\n- if loop[1] is not None:\n- scheduled *= loop[1]\n- elif seen_none:\n- raise ValueError(\"gmap schedule can only contain at most a single None size specification\")\n- else:\n- seen_none = True\n- unscheduled = axis_size // scheduled\n-\n- new_schedule = []\n- for i, loop in enumerate(schedule):\n- loop_type = _parse_name(loop[0])\n- if loop_type is LoopType.vectorized and i < len(schedule) - 1:\n- raise ValueError(\"vectorized loops can only appear as the last component of the schedule\")\n- if loop_type is LoopType.sequential and binds_axis_name:\n- raise ValueError(\"gmaps that bind a new axis name cannot have sequential components in the schedule\")\n- new_schedule.append(Loop(loop_type, loop[1] or unscheduled))\n- return tuple(new_schedule)\n-\n-def _parse_name(name):\n- if isinstance(name, LoopType):\n- return name\n- try:\n- return LoopType[name]\n- except KeyError as err:\n- raise ValueError(f\"Unrecognized loop type: {name}\") from err\n-\n-\n-def gmap_impl(fun: lu.WrappedFun, *args, axis_size, axis_name,\n- binds_axis_name, in_axes, out_axes_thunk, schedule):\n- avals = [core.raise_to_shaped(core.get_aval(arg)) for arg in args]\n- scheduled_fun = _apply_schedule(fun, axis_size, axis_name, binds_axis_name,\n- in_axes, out_axes_thunk, schedule, *avals)\n- return scheduled_fun(*args)\n-\n-class _GMapSubaxis:\n- def __init__(self, axis_name, index):\n- self.axis_name = axis_name\n- self.index = index\n- def __repr__(self):\n- return f'<subaxis {self.index} of {self.axis_name}>'\n- def __hash__(self):\n- return hash((self.axis_name, self.index))\n- def __eq__(self, other):\n- return (isinstance(other, _GMapSubaxis) and\n- self.axis_name == other.axis_name and\n- self.index == other.index)\n-\n-@lu.cache\n-def _apply_schedule(fun: lu.WrappedFun,\n- axis_size, full_axis_name, binds_axis_name,\n- in_axes,\n- out_axes_thunk,\n- schedule,\n- *avals):\n- mapped_avals = [core.mapped_aval(axis_size, in_axis, aval)\n- if in_axis is not None else aval\n- for aval, in_axis in zip(avals, in_axes)]\n- with core.extend_axis_env(full_axis_name, axis_size, None):\n- jaxpr, _, consts = pe.trace_to_jaxpr_final(fun, mapped_avals)\n- out_axes = out_axes_thunk()\n- assert all(out_axis == 0 for out_axis in out_axes)\n-\n- axis_names = tuple(_GMapSubaxis(full_axis_name, i) for i in range(len(schedule)))\n- if binds_axis_name:\n- jaxpr = subst_axis_names(jaxpr, {full_axis_name: axis_names}) # type: ignore\n-\n- sched_fun = lambda *args: core.eval_jaxpr(jaxpr, consts, *args)\n- for (ltype, size), axis_name in list(zip(schedule, axis_names))[::-1]:\n- if ltype is LoopType.vectorized:\n- sched_fun = jax.vmap(sched_fun, axis_name=axis_name, in_axes=in_axes)\n- elif ltype is LoopType.parallel:\n- sched_fun = jax.pmap(sched_fun, axis_name=axis_name, in_axes=in_axes)\n- elif ltype is LoopType.sequential:\n- if binds_axis_name:\n- raise NotImplementedError(\"gmaps with sequential components of the schedule don't support \"\n- \"collectives yet. Please open a feature request!\")\n- assert not binds_axis_name\n- sched_fun = lambda *args, sched_fun=sched_fun: _sequential_map(sched_fun, in_axes, args)\n-\n- dim_sizes = tuple(loop.size for loop in schedule)\n- def sched_fun_wrapper(*args):\n- split_args = [arg.reshape(arg.shape[:in_axis] + dim_sizes + arg.shape[in_axis + 1:])\n- for arg, in_axis in zip(args, in_axes)]\n- results = sched_fun(*split_args)\n- return [res.reshape((axis_size,) + res.shape[len(dim_sizes):]) for res in results]\n- return sched_fun_wrapper\n-\n-gmap_p = core.MapPrimitive('gmap')\n-gmap_p.def_impl(gmap_impl)\n-\n-def _sequential_map(f, flat_in_axes, args):\n- flat_args, treedef = tree_flatten(args)\n- flat_args_leading = [jnp.moveaxis(arg, in_axis, 0)\n- for arg, in_axis in zip(flat_args, flat_in_axes)]\n- args_leading = tree_unflatten(treedef, flat_args_leading)\n- return jax.lax.map(lambda xs: f(*xs), args_leading)\n-\ndef subst_axis_names(jaxpr, axis_subst: Dict[AxisName, Tuple[AxisName]]):\neqns = [subst_eqn_axis_names(eqn, axis_subst) for eqn in jaxpr.eqns]\nreturn core.Jaxpr(jaxpr.constvars, jaxpr.invars, jaxpr.outvars, eqns)\n" }, { "change_type": "RENAME", "old_path": "tests/gmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -30,7 +30,7 @@ import jax.numpy as jnp\nfrom jax import test_util as jtu\nfrom jax import vmap\nfrom jax import lax\n-from jax.experimental.general_map import gmap, Mesh, mesh, xmap, A\n+from jax.experimental.maps import Mesh, mesh, xmap, A\nfrom jax.lib import xla_bridge\nfrom jax.util import curry, unzip2\nfrom jax.interpreters import pxla\n@@ -38,7 +38,7 @@ from jax.interpreters import pxla\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n-ignore_gmap_warning = functools.partial(\n+ignore_xmap_warning = functools.partial(\njtu.ignore_warning, message=\".*is an experimental.*\")\n# TODO(mattjj): de-duplicate setUpModule and tearDownModule with pmap_test.py\n@@ -63,31 +63,6 @@ def tearDownModule():\nxla_bridge.get_backend.cache_clear()\n-@curry\n-def skip_insufficient_devices(axis_size, fun):\n- @functools.wraps(fun)\n- def wrapper(*args, schedule, **kwargs):\n- for loop, n in schedule:\n- approx_n = axis_size if n is None else n\n- if loop == 'parallel' and approx_n > xla_bridge.device_count():\n- raise SkipTest(\"this test requires more XLA devices\")\n- return fun(*args, schedule=schedule, **kwargs)\n- return wrapper\n-\n-@curry\n-def check_default_schedules(cond, fun):\n- schedules = [\n- ('seq', [('sequential', None)]),\n- ('vec', [('vectorized', None)]),\n- ('par', [('parallel', None)]),\n- ('lim_vmap', [('sequential', None), ('vectorized', 2)]),\n- ('soft_pmap', [('parallel', 2), ('vectorized', None)])\n- ]\n- schedules = [s for s in schedules if cond(s[1])]\n- return parameterized.named_parameters(\n- {\"testcase_name\": \"_\" + name, \"schedule\": schedule}\n- for name, schedule in schedules)(fun)\n-\n@curry\ndef with_mesh(named_shape, f):\ndef new_f(*args, **kwargs):\n@@ -105,106 +80,24 @@ def use_spmd_lowering(f):\ndef new_f(*args, **kwargs):\nif jtu.device_under_test() != \"tpu\":\nraise SkipTest\n- jax.experimental.general_map.make_xmap_callable.cache_clear()\n- old = jax.experimental.general_map.EXPERIMENTAL_SPMD_LOWERING\n- jax.experimental.general_map.EXPERIMENTAL_SPMD_LOWERING = True\n+ jax.experimental.maps.make_xmap_callable.cache_clear()\n+ old = jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING\n+ jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = True\ntry:\nreturn f(*args, **kwargs)\nfinally:\n- jax.experimental.general_map.EXPERIMENTAL_SPMD_LOWERING = old\n+ jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = old\nreturn new_f\n-class GmapTest(jtu.JaxTestCase):\n-\n- @check_default_schedules(lambda _: True)\n- @skip_insufficient_devices(8)\n- @ignore_gmap_warning()\n- @skipIf(not config.omnistaging_enabled,\n- \"vmap collectives only supported when omnistaging is enabled\")\n- def testBasicSchedules(self, schedule):\n- def f(x):\n- return jnp.dot(jnp.sin(x), x.T) * 4 + x\n-\n- x = jnp.arange(800).reshape((8, 10, 10))\n-\n- self.assertAllClose(gmap(f, schedule)(x), vmap(f)(x), rtol=3e-5)\n-\n- @check_default_schedules(lambda s: not any(c[0] == 'sequential' for c in s))\n- @skip_insufficient_devices(8)\n- @ignore_gmap_warning()\n- @skipIf(not config.omnistaging_enabled,\n- \"vmap collectives only supported when omnistaging is enabled\")\n- def testAxisName(self, schedule):\n- def f(x):\n- return x - lax.psum(x, 'i')\n- x = jnp.arange(8)\n- self.assertAllClose(gmap(f, schedule, axis_name='i')(x),\n- vmap(f, axis_name='i')(x))\n-\n- @ignore_gmap_warning()\n- @skipIf(not config.omnistaging_enabled,\n- \"vmap collectives only supported when omnistaging is enabled\")\n- def testAxisName2d(self):\n- def f(x):\n- return x - lax.psum(x, 'i') + lax.pmax(x, 'j')\n- x = jnp.arange(8 * 8).reshape((8, 8))\n- s = [('vectorized', None)]\n- self.assertAllClose(gmap(gmap(f, s, axis_name='i'), s, axis_name='j')(x),\n- vmap(vmap(f, axis_name='i'), axis_name='j')(x))\n-\nclass XMapTest(jtu.JaxTestCase):\n- @ignore_gmap_warning()\n- @skipIf(not config.omnistaging_enabled,\n- \"vmap collectives only supported when omnistaging is enabled\")\n- @with_mesh([('r1', 4), ('r2', 2), ('r3', 5)])\n- def testXMap(self):\n- def f(a, b):\n- return a + 2, b * 4\n- fm = xmap(f,\n- in_axes=[A({'x': 0, 'z': 1}), A({'y': 1})],\n- out_axes=[A({'x': 1, 'z': 0}), A({'y': 0})],\n- schedule=[\n- ('x', 'r1'),\n- ('x', 'r2'),\n- ('y', 'r1'),\n- ('z', 'r3'),\n- ('x', 'vectorize'),\n- ('y', 'vectorize'),\n- ])\n- a = jnp.arange(16*5*2).reshape((16, 5, 2))\n- b = jnp.arange(6*16).reshape((6, 16))\n- c, d = fm(a, b)\n- self.assertAllClose(c, (a + 2).transpose((1, 0, 2)))\n- self.assertAllClose(d, (b * 4).T)\n-\n- @ignore_gmap_warning()\n- @skipIf(not config.omnistaging_enabled,\n- \"vmap collectives only supported when omnistaging is enabled\")\n- @with_mesh([('r1', 4), ('r2', 2), ('r3', 5)])\n- def testXMapCollectives(self):\n- def f(a, b):\n- return lax.psum(a + 2, 'x'), b * 4\n- fm = xmap(f,\n- in_axes=[A({'x': 0, 'z': 1}), A({'y': 1})],\n- out_axes=[A({'z': 0}), A({'y': 0})],\n- schedule=[\n- ('x', 'r1'),\n- ('x', 'r2'),\n- ('y', 'r1'),\n- ('z', 'r3'),\n- ('x', 'vectorize'),\n- ('y', 'vectorize'),\n- ])\n- a = jnp.arange(16*5*2).reshape((16, 5, 2))\n- b = jnp.arange(6*16).reshape((6, 16))\n- c, d = fm(a, b)\n- self.assertAllClose(c, (a + 2).sum(0))\n- self.assertAllClose(d, (b * 4).T)\n+ def setUp(self):\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"xmap requires omnistaging\")\n- @ignore_gmap_warning()\n- def testXMapMeshBasic(self):\n+ @ignore_xmap_warning()\n+ def testBasic(self):\nlocal_devices = list(jax.local_devices())\nif len(local_devices) < 4:\nraise SkipTest(\"Test requires at least 4 local devices\")\n@@ -230,10 +123,10 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(c, a * 2)\nself.assertAllClose(d, b * 4)\n- testXMapMeshBasicSPMD = use_spmd_lowering(testXMapMeshBasic)\n+ testBasicSPMD = use_spmd_lowering(testBasic)\n- @ignore_gmap_warning()\n- def testXMapMeshCollectives(self):\n+ @ignore_xmap_warning()\n+ def testBasicCollective(self):\nlocal_devices = list(jax.local_devices())\nif len(local_devices) < 4:\nraise SkipTest(\"Test requires at least 4 local devices\")\n@@ -259,11 +152,11 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(c, (a * 2).sum(0))\nself.assertAllClose(d, b * 4)\n- testXMapMeshCollectivesSPMD = use_spmd_lowering(testXMapMeshCollectives)\n+ testBasicCollectiveSPMD = use_spmd_lowering(testBasicCollective)\n- @ignore_gmap_warning()\n+ @ignore_xmap_warning()\n@with_mesh([('x', 2)])\n- def testXMapCompilationCache(self):\n+ def testCompilationCache(self):\ndef f(x):\nassert python_should_be_executing\nreturn x * 2\n@@ -277,9 +170,9 @@ class XMapTest(jtu.JaxTestCase):\npython_should_be_executing = False\nfm(x)\n- @ignore_gmap_warning()\n+ @ignore_xmap_warning()\n@with_mesh([('x', 2)])\n- def testNestedXMapBasic(self):\n+ def testNestedVectorize(self):\n@partial(xmap, in_axes=A({'a': 1}), out_axes=A({'a': 0}),\nschedule=[('a', 'x')])\ndef f(x):\n@@ -294,9 +187,9 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(f(x),\njnp.sin(x * 2).transpose((1, 2, 0)))\n- @ignore_gmap_warning()\n+ @ignore_xmap_warning()\n@with_mesh([('x', 2), ('y', 3)])\n- def testNestedXMapMesh(self):\n+ def testNestedMesh(self):\n@partial(xmap, in_axes=A({'a': 1}), out_axes=A({'a': 0}),\nschedule=[('a', 'y')])\ndef f(x):\n@@ -316,9 +209,9 @@ class XMapTest(jtu.JaxTestCase):\nself.assertEqual(y.sharding_spec.mesh_mapping,\n(pxla.Replicated(2), pxla.ShardedAxis(0)))\n- @ignore_gmap_warning()\n+ @ignore_xmap_warning()\n@with_mesh([('x', 2)])\n- def testNestedXMapDifferentResources(self):\n+ def testNestedDifferentResources(self):\n@partial(xmap, in_axes=A({'a': 0}), out_axes=A({'a': 0}),\nschedule=[('a', 'x')])\ndef f(x):\n@@ -334,9 +227,7 @@ class XMapTest(jtu.JaxTestCase):\n\"Changing the resource environment.*\"):\nf(x)\n- @ignore_gmap_warning()\n- @skipIf(not config.omnistaging_enabled,\n- \"vmap collectives only supported when omnistaging is enabled\")\n+ @ignore_xmap_warning()\n@with_mesh([('r1', 2)])\ndef testPdotBasic(self):\ndef f(x, y):\n@@ -353,9 +244,7 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(z, jnp.dot(x, y))\n- @ignore_gmap_warning()\n- @skipIf(not config.omnistaging_enabled,\n- \"vmap collectives only supported when omnistaging is enabled\")\n+ @ignore_xmap_warning()\n@with_mesh([('r1', 2)])\ndef testPdotBatching(self):\ndef f(x, y):\n" } ]
Python
Apache License 2.0
google/jax
Remove fake xmap resources, remove gmap xmap can now handle real devices, so there's no point in maintaining the simulated codepaths. Also, remove single-dimensional gmap as it will have to be superseeded by a more xmap-friendly alternative.
260,287
02.12.2020 14:13:05
0
ca8028950ecfd3118f7801e7e85a111fba4e4fc0
Fix pmap compilation cache regressions from AD didn't use `HashableFunction` enough, tripping up the compilation cache. I've also used the occasion to make function hashing a little safer by including the Python bytecode of the wrapped function as part of the key.
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1516,11 +1516,11 @@ def pmap(fun: Callable[..., T],\n# out_axes == 0 path working as we look for a better solution.\nout_axes_thunk = HashableFunction(\nlambda: (0,) * out_tree().num_leaves,\n- key=out_axes)\n+ closure=out_axes)\nelse:\nout_axes_thunk = HashableFunction(\nlambda: tuple(flatten_axes(\"pmap out_axes\", out_tree(), out_axes)),\n- key=out_axes)\n+ closure=out_axes)\nout = pxla.xla_pmap(\nflat_fun, *args, backend=backend, axis_name=axis_name,\naxis_size=local_axis_size, global_axis_size=axis_size,\n@@ -1557,7 +1557,7 @@ def soft_pmap(fun: Callable, axis_name: Optional[AxisName] = None, in_axes=0\n# See note about out_axes_thunk in pmap for the explanation of why we choose this key\nout_axes_thunk = HashableFunction(\nlambda: tuple(flatten_axes(\"soft_pmap out_axes\", out_tree(), 0)),\n- key=())\n+ closure=())\nouts = pxla.soft_pmap(flat_fun, *args_flat, axis_name=axis_name,\naxis_size=axis_size, in_axes=tuple(in_axes_flat),\nout_axes_thunk=out_axes_thunk)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -34,7 +34,8 @@ from . import linear_util as lu\nfrom jax._src import source_info_util\nfrom .util import (safe_zip, safe_map, partial, curry, prod, partialmethod,\n- tuple_insert, tuple_delete, as_hashable_function)\n+ tuple_insert, tuple_delete, as_hashable_function,\n+ HashableFunction)\nfrom ._src.pprint_util import pp, vcat, PrettyPrint\nfrom ._src import traceback_util\n@@ -341,7 +342,9 @@ def eval_jaxpr(jaxpr: Jaxpr, consts, *args):\nelse:\nsubfuns = []\nif eqn.primitive.map_primitive:\n- bind_params = dict(params, out_axes_thunk=lambda: params['out_axes'])\n+ out_axes_thunk = HashableFunction(lambda: params['out_axes'],\n+ closure=params['out_axes'])\n+ bind_params = dict(params, out_axes_thunk=out_axes_thunk)\ndel bind_params['out_axes']\nelse:\nbind_params = params\n@@ -1200,7 +1203,7 @@ def call_bind(primitive: Union['CallPrimitive', 'MapPrimitive'],\n# The new thunk depends deterministically on the old thunk and the wrapped function.\n# Any caching already has to include the wrapped function as part of the key, so we\n# only use the previous thunk for equality checks.\n- @as_hashable_function(key=out_axes_thunk)\n+ @as_hashable_function(closure=out_axes_thunk)\ndef new_out_axes_thunk():\nout_axes = out_axes_thunk()\nfor t in out_axes_transforms:\n@@ -1688,7 +1691,7 @@ def omnistaging_disabler() -> None:\n# The new thunk depends deterministically on the old thunk and the wrapped function.\n# Any caching already has to include the wrapped function as part of the key, so we\n# only use the previous thunk for equality checks.\n- @as_hashable_function(key=out_axes_thunk)\n+ @as_hashable_function(closure=out_axes_thunk)\ndef new_out_axes_thunk():\nout_axes = out_axes_thunk()\nfor t in out_axes_transforms:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/general_map.py", "new_path": "jax/experimental/general_map.py", "diff": "@@ -227,7 +227,7 @@ def xmap(fun: Callable,\nin_axes_flat = flatten_axes(\"xmap in_axes\", in_tree, in_axes)\nout_axes_thunk = HashableFunction(\nlambda: tuple(flatten_axes(\"xmap out_axes\", out_tree(), out_axes)),\n- key=out_axes)\n+ closure=out_axes)\naxis_sizes = _get_axis_sizes(args_flat, in_axes_flat)\nout_flat = xmap_p.bind(\nfun_flat, *args_flat,\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -257,6 +257,12 @@ def get_primitive_transpose(p):\n\"Transpose rule (for reverse-mode differentiation) for '{}' \"\n\"not implemented\".format(p)) from err\n+@lu.transformation_with_aux\n+def nonzero_tangent_outputs(*args, **kwargs):\n+ results = (_, tangents_out) = yield args, kwargs\n+ yield results, [type(r) is not Zero for r in tangents_out]\n+\n+\nclass JVPTrace(Trace):\ndef pure(self, val):\n@@ -286,31 +292,27 @@ class JVPTrace(Trace):\nassert call_primitive.multiple_results\nprimals, tangents = unzip2((t.primal, t.tangent) for t in tracers)\nnonzero_tangents, tangent_tree_def = tree_flatten(tangents)\n- f_jvp, out_tree_def = traceable(jvp_subtrace(f, self.main),\n- len(primals), tangent_tree_def)\nnz_tangents = [type(t) is not Zero for t in tangents]\nparams = dict(params, name=wrap_name(params['name'], 'jvp'))\n+ f_jvp = jvp_subtrace(f, self.main)\nif isinstance(call_primitive, core.MapPrimitive):\nin_axes = params['in_axes']\ntangent_in_axes = [ax for ax, nz in zip(in_axes, nz_tangents) if nz]\nout_axes_thunk = params['out_axes_thunk']\n-\n- @lu.transformation_with_aux\n- def populate_outputs(*args, **kwargs):\n- results = yield args, kwargs\n- _, tangents_out = tree_unflatten(out_tree_def(), results)\n- yield results, [type(t) is not Zero for t in tangents_out]\n- f_jvp, nz_tangents_out = populate_outputs(f_jvp)\n+ f_jvp, nz_tangents_out = nonzero_tangent_outputs(f_jvp)\n# The new thunk depends deterministically on the old thunk and the wrapped function.\n# Any caching already has to include the wrapped function as part of the key, so we\n# only use the previous thunk for equality checks.\n- @as_hashable_function(key=out_axes_thunk)\n+ # NOTE: This assumes that the output tangents being zero is a deterministic\n+ # function of which input tangents were zero.\n+ @as_hashable_function(closure=(tuple(nz_tangents), out_axes_thunk))\ndef new_out_axes_thunk():\nout_axes = out_axes_thunk()\nreturn (*out_axes, *(ax for ax, nz in zip(out_axes, nz_tangents_out()) if nz))\nparams = dict(params,\nin_axes=(*in_axes, *tangent_in_axes),\nout_axes_thunk=new_out_axes_thunk)\n+ f_jvp, out_tree_def = traceable(f_jvp, len(primals), tangent_tree_def)\nupdate_params = call_param_updaters.get(call_primitive)\nnew_params = update_params(params, nz_tangents) if update_params else params\nresult = call_primitive.bind(f_jvp, *primals, *nonzero_tangents, **new_params)\n@@ -582,15 +584,16 @@ def remat_transpose(params, call_jaxpr, primals_in, cotangents_in, cotangent_in_\nreturn tree_unflatten(out_tree(), flat_cotangents_out)\nprimitive_transposes[pe.remat_call_p] = remat_transpose\n+@lu.transformation_with_aux\n+def nonzero_outputs(*args, **kwargs):\n+ results = yield args, kwargs\n+ yield results, [type(r) is not Zero for r in results]\n+\ndef map_transpose(primitive, params, call_jaxpr, args, ct, _):\nall_args, in_tree_def = tree_flatten(((), args, ct)) # empty consts\nfun = lu.hashable_partial(lu.wrap_init(backward_pass), call_jaxpr)\n- @lu.transformation_with_aux\n- def find_nonzero_results(*args, **kwargs):\n- results = yield args, kwargs\n- yield results, [type(r) is not Zero for r in results]\n- fun, nz_arg_cts = find_nonzero_results(fun)\n+ fun, nz_arg_cts = nonzero_outputs(fun)\nfun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\n# Preserve axis for primal arguments, skip tangents (represented as undefined primals).\nin_axes, out_axes = params['in_axes'], params['out_axes']\n@@ -601,6 +604,9 @@ def map_transpose(primitive, params, call_jaxpr, args, ct, _):\n# The interim strategy we use below (until avals-with-names) only works\n# when all outputs are mapped.\nassert all(out_axis is not None for out_axis in out_axes), out_axes\n+ # NOTE: This assumes that the output cotangents being zero is a deterministic\n+ # function of which input cotangents were zero.\n+ @as_hashable_function(closure=(in_axes, tuple(type(c) is Zero for c in ct)))\ndef out_axes_thunk():\nreturn tuple(axis or 0 for axis, nz in zip(in_axes, nz_arg_cts()) if nz)\nnew_params = dict(params, name=wrap_name(params['name'], 'transpose'),\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -198,7 +198,10 @@ class BatchTrace(Trace):\nfor d, in_axis in zip(dims, params['in_axes']))\nf, dims_out = batch_subtrace(f, self.main, new_dims)\nout_axes_thunk = params['out_axes_thunk']\n- @as_hashable_function(key=out_axes_thunk)\n+ # NOTE: This assumes that the choice of the dimensions over which outputs\n+ # are batched is entirely dependent on the function and not e.g. on the\n+ # data or its shapes.\n+ @as_hashable_function(closure=out_axes_thunk)\ndef new_out_axes_thunk():\nreturn tuple(out_axis + 1 if both_mapped(out_axis, d) and d < out_axis else out_axis\nfor out_axis, d in zip(out_axes_thunk(), dims_out()))\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -181,7 +181,7 @@ class JaxprTrace(Trace):\ndef app(f, *args):\nf, num_outputs = count_outputs(f)\nout_axes_thunk = params['out_axes_thunk']\n- @as_hashable_function(key=out_axes_thunk)\n+ @as_hashable_function(closure=out_axes_thunk)\ndef new_out_axes_thunk():\nout_axes = out_axes_thunk()\nreturn out_axes + (0,) * (num_outputs() - len(out_axes))\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/sharded_jit.py", "new_path": "jax/interpreters/sharded_jit.py", "diff": "@@ -362,14 +362,14 @@ def sharded_jit(fun: Callable, in_parts, out_parts, num_partitions: int = None,\n# there a better way?\nout_parts_thunk = HashableFunction(\nlambda: tuple(flatten_axes(\"sharded_jit out_parts\", out_tree(), out_parts)),\n- key=out_parts)\n+ closure=out_parts)\nif local_out_parts:\nlocal_out_parts_thunk = HashableFunction(\nlambda: tuple(flatten_axes(\"sharded_jit local_out_parts\",\nout_tree(), local_out_parts)),\n- key=local_out_parts)\n+ closure=local_out_parts)\nelse:\n- local_out_parts_thunk = HashableFunction(lambda: None, key=None)\n+ local_out_parts_thunk = HashableFunction(lambda: None, closure=None)\nout = sharded_call(\nflat_fun,\n" }, { "change_type": "MODIFY", "old_path": "jax/test_util.py", "new_path": "jax/test_util.py", "diff": "@@ -344,6 +344,13 @@ def count_jit_and_pmap_compiles():\nfinally:\nxla.jaxpr_subcomp = jaxpr_subcomp\n+@contextmanager\n+def assert_num_jit_and_pmap_compilations(times):\n+ with count_jit_and_pmap_compiles() as count:\n+ yield\n+ if count[0] != times:\n+ raise AssertionError(f\"Expected exactly {times} XLA compilations, \"\n+ f\"but executed {count[0]}\")\ndef device_under_test():\nreturn FLAGS.jax_test_dut or xla_bridge.get_backend().platform\n" }, { "change_type": "MODIFY", "old_path": "jax/util.py", "new_path": "jax/util.py", "diff": "@@ -308,22 +308,41 @@ def taggedtuple(name, fields) -> Callable[..., Any]:\nreturn type(name, (tuple,), class_namespace)\nclass HashableFunction:\n- \"\"\"Makes a function hashable based on the provided key.\"\"\"\n- def __init__(self, f, key):\n+ \"\"\"Decouples function equality and hash from its identity.\n+\n+ Local lambdas and functiond defs are reallocated on each function call, making\n+ the functions created on different calls compare as unequal. This breaks our\n+ caching logic, which should really only care about comparing the semantics and\n+ not actual identity.\n+\n+ This class makes it possible to compare different functions based on their\n+ semantics. The parts that are taken into account are: the bytecode of\n+ the wrapped function (which is cached by the CPython interpreter and is stable\n+ across the invocations of the surrounding function), and `closure` which should\n+ contain all values in scope that affect the function semantics. In particular\n+ `closure` should contain all elements of the function closure, or it should be\n+ possible to derive the relevant elements of the true function closure based\n+ solely on the contents of the `closure` argument (e.g. in case some closed-over\n+ values are not hashable, but are entirely determined by hashable locals).\n+ \"\"\"\n+\n+ def __init__(self, f, closure):\nself.f = f\n- self.key = key\n+ self.closure = closure\ndef __eq__(self, other):\n- return type(other) is HashableFunction and self.key == other.key\n+ return (type(other) is HashableFunction and\n+ self.f.__code__ == other.f.__code__ and\n+ self.closure == other.closure)\ndef __hash__(self):\n- return hash(self.key)\n+ return hash((self.f.__code__, self.closure))\ndef __call__(self, *args, **kwargs):\nreturn self.f(*args, **kwargs)\ndef __repr__(self):\n- return f'<HashableFunction with key={self.key}>'\n+ return f'<hashable {self.f.__name__} with closure={self.closure}>'\n-def as_hashable_function(key):\n- return lambda f: HashableFunction(f, key)\n+def as_hashable_function(closure):\n+ return lambda f: HashableFunction(f, closure)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1726,28 +1726,37 @@ class APITest(jtu.JaxTestCase):\ndef test_pmap_global_cache(self):\ndef f(x, y):\n- assert python_should_be_executing\nreturn x, y\nx = np.ones((1, 1, 1))\n- python_should_be_executing = True\n- api.pmap(f)(x, x)\n- python_should_be_executing = False\n+ # All defaults\n+ with jtu.assert_num_jit_and_pmap_compilations(1):\n+ for _ in range(2):\napi.pmap(f)(x, x)\n- python_should_be_executing = True\n- api.pmap(f, 'i')(x, x)\n- python_should_be_executing = False\n+ # With axis name\n+ with jtu.assert_num_jit_and_pmap_compilations(1):\n+ for _ in range(2):\napi.pmap(f, 'i')(x, x)\n+ # With in_axes and out_axes\nif config.omnistaging_enabled:\nfor x_in, y_in, x_out, y_out in it.product(*((0, 1, 2) for _ in range(4))):\n- python_should_be_executing = True\n- api.pmap(f, 'i', in_axes=(x_in, y_in), out_axes=(x_out, y_out))(x, x)\n- python_should_be_executing = False\n+ with jtu.assert_num_jit_and_pmap_compilations(1):\n+ for _ in range(2):\napi.pmap(f, 'i', in_axes=(x_in, y_in), out_axes=(x_out, y_out))(x, x)\n+ # Forward-mode AD on the outside\n+ with jtu.assert_num_jit_and_pmap_compilations(1):\n+ for _ in range(2):\n+ api.jvp(api.pmap(f), (x, x), (x, x))\n+\n+ # Reverse-mode AD on the outside. One compilation for forward, one for backward.\n+ with jtu.assert_num_jit_and_pmap_compilations(2):\n+ for _ in range(2):\n+ api.vjp(api.pmap(f), x, x)[1]((x, x))\n+\ndef test_device_array_repr(self):\nrep = repr(jnp.ones(()) + 1.)\nself.assertStartsWith(rep, 'DeviceArray')\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -845,7 +845,7 @@ class PmapTest(jtu.JaxTestCase):\ndevice_count = xla_bridge.device_count()\nf = pmap(lambda x: 3)\nx = jnp.arange(device_count)\n- with jtu.count_jit_and_pmap_compiles() as count:\n+ with jtu.count_jit_and_pmap_compiles() as count: # noqa: F841\nans = f(x)\n# self.assertEqual(count[0], 0) # TODO(mattjj): fix this\nexpected = np.repeat(3, device_count)\n@@ -853,9 +853,8 @@ class PmapTest(jtu.JaxTestCase):\nf = pmap(lambda x: (x, 3))\nx = np.arange(device_count)\n- with jtu.count_jit_and_pmap_compiles() as count: # noqa: F841\n+ with jtu.assert_num_jit_and_pmap_compilations(1):\n_, ans = f(x)\n- self.assertEqual(count[0], 1)\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testPmapConstantDevices(self):\n" }, { "change_type": "MODIFY", "old_path": "tests/sharded_jit_test.py", "new_path": "tests/sharded_jit_test.py", "diff": "@@ -249,10 +249,9 @@ class ShardedJitTest(jtu.JaxTestCase):\nshape = (2,)\nx = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n- with jtu.count_jit_and_pmap_compiles() as count:\n+ with jtu.assert_num_jit_and_pmap_compilations(1):\nsharded_f(x)\nsharded_f(x)\n- self.assertEqual(count[0], 1)\n# TODO(skye): add more error tests\n" } ]
Python
Apache License 2.0
google/jax
Fix pmap compilation cache regressions from #4904. AD didn't use `HashableFunction` enough, tripping up the compilation cache. I've also used the occasion to make function hashing a little safer by including the Python bytecode of the wrapped function as part of the key.
260,335
02.12.2020 08:55:14
28,800
e6c01aeacd70064bd3e6a160892ee51a713c1cda
fix broadcasting bug in sinc jvp rule
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1015,9 +1015,9 @@ def _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)\nif k % 2:\n- return lax._const(x, 0)\n+ return lax.full_like(x, 0)\nelse:\n- return lax._const(x, (-1) ** (k // 2) / (k + 1))\n+ return lax.full_like(x, (-1) ** (k // 2) / (k + 1))\n@_sinc_maclaurin.defjvp\ndef _sinc_maclaurin_jvp(k, primals, tangents):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -4558,6 +4558,10 @@ class NumpyGradTests(jtu.JaxTestCase):\nfor ops in itertools.combinations_with_replacement([deriv, api.grad], 4):\nself.assertAllClose(apply_all(ops, jnp.sinc)(0.), d4)\n+ def testSincGradArrayInput(self):\n+ # tests for a bug almost introduced in #5077\n+ jax.grad(lambda x: jnp.sinc(x).sum())(jnp.arange(10.)) # doesn't crash\n+\ndef testTakeAlongAxisIssue1521(self):\n# https://github.com/google/jax/issues/1521\nidx = jnp.repeat(jnp.arange(3), 10).reshape((30, 1))\n" } ]
Python
Apache License 2.0
google/jax
fix broadcasting bug in sinc jvp rule
260,449
04.12.2020 11:23:32
-19,080
42780cf2776630bc3c03f4a63143419fd5a27364
added prepend and append to diff
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1115,7 +1115,7 @@ def angle(z):\n@_wraps(np.diff)\n-def diff(a, n=1, axis=-1):\n+def diff(a, n=1, axis=-1, prepend=None, append=None):\n_check_arraylike(\"diff\", a)\nif n == 0:\nreturn a\n@@ -1126,6 +1126,28 @@ def diff(a, n=1, axis=-1):\nnd = a.ndim\n+ combined = []\n+ if prepend is not None:\n+ _check_arraylike(\"diff\", prepend)\n+ if isscalar(prepend):\n+ shape = list(a.shape)\n+ shape[axis] = 1\n+ prepend = broadcast_to(prepend, tuple(shape))\n+ combined.append(prepend)\n+\n+ combined.append(a)\n+\n+ if append is not None:\n+ _check_arraylike(\"diff\", append)\n+ if isscalar(append):\n+ shape = list(a.shape)\n+ shape[axis] = 1\n+ append = broadcast_to(append, tuple(shape))\n+ combined.append(append)\n+\n+ if len(combined) > 1:\n+ a = concatenate(combined, axis)\n+\nslice1 = [slice(None)] * nd\nslice2 = [slice(None)] * nd\nslice1[axis] = slice(1, None)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -296,7 +296,6 @@ JAX_COMPOUND_OP_RECORDS = [\ncheck_dtypes=False),\nop_record(\"true_divide\", 2, all_dtypes, all_shapes, jtu.rand_nonzero,\n[\"rev\"], inexact=True),\n- op_record(\"diff\", 1, number_dtypes + bool_dtypes, nonzerodim_shapes, jtu.rand_default, [\"rev\"]),\nop_record(\"ediff1d\", 3, [np.int32], all_shapes, jtu.rand_default, []),\nop_record(\"unwrap\", 1, float_dtypes, nonempty_nonscalar_array_shapes,\njtu.rand_default, [\"rev\"],\n@@ -2328,6 +2327,44 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_shape={}_n={}_axis={}_prepend={}_append={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype),\n+ n, axis, prepend, append),\n+ \"shape\": shape, \"dtype\": dtype, \"n\": n, \"axis\": axis,\n+ \"prepend\": prepend, \"append\": append,\n+ \"rng_factory\": jtu.rand_default}\n+ for shape, dtype in _shape_and_dtypes(nonempty_nonscalar_array_shapes, default_dtypes)\n+ for n in [0, 1, 2]\n+ for axis in list(range(-len(shape), max(1, len(shape))))\n+ for prepend in [None, 1, np.zeros(shape, dtype=dtype)]\n+ for append in [None, 1, np.zeros(shape, dtype=dtype)]\n+ ))\n+ def testDiff(self, shape, dtype, n, axis, prepend, append, rng_factory):\n+ rng = rng_factory(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+\n+ def np_fun(x, n=n, axis=axis, prepend=prepend, append=append):\n+ if prepend is None:\n+ prepend = np._NoValue\n+ elif not np.isscalar(prepend) and prepend.dtype == jnp.bfloat16:\n+ prepend = prepend.astype(np.float32)\n+\n+ if append is None:\n+ append = np._NoValue\n+ elif not np.isscalar(append) and append.dtype == jnp.bfloat16:\n+ append = append.astype(np.float32)\n+\n+ if x.dtype == jnp.bfloat16:\n+ return np.diff(x.astype(np.float32), n=n, axis=axis, prepend=prepend, append=append).astype(jnp.bfloat16)\n+ else:\n+ return np.diff(x, n=n, axis=axis, prepend=prepend, append=append)\n+\n+ jnp_fun = lambda x: jnp.diff(x, n=n, axis=axis, prepend=prepend, append=append)\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)\n+ self._CompileAndCheck(jnp_fun, args_maker)\n+\n@parameterized.named_parameters(\njtu.cases_from_list(\n{\"testcase_name\": (\"_op={}_shape={}_dtype={}\").format(op, shape, dtype),\n@@ -4599,7 +4636,6 @@ class NumpySignaturesTest(jtu.JaxTestCase):\n'broadcast_to': ['subok', 'array'],\n'clip': ['kwargs'],\n'corrcoef': ['ddof', 'bias'],\n- 'diff': ['prepend', 'append'],\n'empty_like': ['subok', 'order'],\n'einsum': ['kwargs'],\n'einsum_path': ['einsum_call'],\n" } ]
Python
Apache License 2.0
google/jax
added prepend and append to diff
260,335
04.12.2020 12:53:36
28,800
dc610e45167b928e372d1cd56ee76c9144f57856
add jax.device_put_replicated Also move tests for device_put_sharded into pmap_test.py, since that file tests with multiple devices even in our OSS CI. Add both device_put_replicated and device_put_sharded to jax/__init__.py.
[ { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -36,6 +36,8 @@ from .api import (\ndevice_count,\ndevice_get,\ndevice_put,\n+ device_put_sharded,\n+ device_put_replicated,\ndevices,\ndisable_jit,\neval_shape,\n" }, { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -2060,9 +2060,9 @@ def device_put_sharded(shards: Sequence[Any], devices: Sequence[xc.Device]):\ncontaining a stacked version of the inputs:\n>>> from jax import api, numpy as jnp\n- >>> devices = api.local_devices()\n+ >>> devices = jax.local_devices()\n>>> x = [jnp.ones(5) for device in devices]\n- >>> y = api.device_put_sharded(x, devices)\n+ >>> y = jax.device_put_sharded(x, devices)\n>>> np.allclose(y, jnp.stack(x))\nTrue\n@@ -2071,11 +2071,11 @@ def device_put_sharded(shards: Sequence[Any], devices: Sequence[xc.Device]):\nall entries in the list to have the same tree structure:\n>>> x = [(i, jnp.arange(i, i + 4)) for i in range(len(devices))]\n- >>> y = api.device_put_sharded(x, devices)\n+ >>> y = jax.device_put_sharded(x, devices)\n>>> type(y)\n<class 'tuple'>\n- >>> y0 = api.device_put_sharded([a for a, b in x], devices)\n- >>> y1 = api.device_put_sharded([b for a, b in x], devices)\n+ >>> y0 = jax.device_put_sharded([a for a, b in x], devices)\n+ >>> y1 = jax.device_put_sharded([b for a, b in x], devices)\n>>> np.allclose(y[0], y0)\nTrue\n>>> np.allclose(y[1], y1)\n@@ -2108,6 +2108,47 @@ def device_put_sharded(shards: Sequence[Any], devices: Sequence[xc.Device]):\nreturn tree_multimap(_device_put_sharded, *shards)\n+def device_put_replicated(x: Any, devices: Sequence[xc.Device]):\n+ \"\"\"Transfer array(s) to each specified device and form ShardedDeviceArray(s).\n+\n+ Args:\n+ x: an array, scalar, or (nested) standard Python container thereof\n+ representing the array to be replicated to form the output.\n+ devices: A sequence of :py:class:`Device` instances representing the devices\n+ to which ``x`` will be transferred.\n+\n+ Returns:\n+ A ShardedDeviceArray or (nested) Python container thereof representing the\n+ value of ``x`` broadcasted along a new leading axis of size\n+ ``len(devices)``, with each slice along that new leading axis backed by\n+ memory on the device specified by the corresponding entry in ``devices``.\n+\n+ Examples:\n+ Passing an array:\n+\n+ >>> from jax import api, numpy as jnp\n+ >>> devices = jax.local_devices()\n+ >>> x = jnp.array([1., 2., 3.])\n+ >>> y = api.device_put_replicated(x, devices)\n+ >>> np.allclose(y, jnp.stack([x for _ in devices]))\n+ True\n+\n+ See also:\n+ - device_put\n+ - device_put_sharded\n+ \"\"\"\n+ if not isinstance(devices, Sequence) or not devices:\n+ raise ValueError(\"`devices` argument to `device_put_replicated must be \"\n+ \"a non-empty sequence.\")\n+ def _device_put_replicated(x) -> pxla.ShardedDeviceArray:\n+ aval = core.unmapped_aval(len(devices), 0,\n+ core.raise_to_shaped(core.get_aval(x)))\n+ buf, = xla.device_put(x, devices[0]) # assuming single-buf repr\n+ rest_bufs = [buf.copy_to_device(d) for d in devices[1:]]\n+ return pxla.ShardedDeviceArray(aval, [buf, *rest_bufs])\n+ return tree_map(_device_put_replicated, x)\n+\n+\n# TODO(mattjj): consider revising\ndef _device_get(x):\nif isinstance(x, core.Tracer):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -710,25 +710,6 @@ class APITest(jtu.JaxTestCase):\nx = api.device_put(val, device=cpu_device)\nself.assertEqual(x.device_buffer.device(), cpu_device)\n- def test_device_put_sharded_array(self):\n- devices = api.local_devices()\n- n_devices = len(devices)\n- x = [np.arange(i, i + 4) for i in range(n_devices)]\n- y = api.device_put_sharded(x, devices)\n- self.assertEqual(len(y.device_buffers), len(devices))\n- self.assertTrue(all(b.device() == d for b, d in zip(y.device_buffers, devices)))\n- self.assertAllClose(y, jnp.stack(x))\n-\n- def test_device_put_sharded_pytree(self):\n- devices = api.local_devices()\n- n_devices = len(devices)\n- x = [(i, np.arange(i, i + 4)) for i in range(n_devices)]\n- y1, y2 = api.device_put_sharded(x, devices)\n- self.assertAllClose(y1, jnp.array([a for a, _ in x]))\n- self.assertTrue(all(b.device() == d for b, d in zip(y1.device_buffers, devices)))\n- self.assertAllClose(y2, jnp.vstack([b for _, b in x]))\n- self.assertTrue(all(b.device() == d for b, d in zip(y2.device_buffers, devices)))\n-\n@jtu.skip_on_devices(\"tpu\")\ndef test_jacobian(self):\nR = np.random.RandomState(0).randn\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -2043,6 +2043,56 @@ class ShardedDeviceArrayTest(jtu.JaxTestCase):\nself.assertIsInstance(sharded_x[i], jax.interpreters.xla.DeviceArray)\nself.assertIsNone(sharded_x._npy_value)\n+ def test_device_put_sharded_array(self):\n+ devices = jax.local_devices()\n+ n_devices = len(devices)\n+ x = [np.arange(i, i + 4) for i in range(n_devices)]\n+ y = jax.device_put_sharded(x, devices)\n+ self.assertIsInstance(y, pxla.ShardedDeviceArray)\n+ self.assertEqual(len(y.device_buffers), len(devices))\n+ self.assertTrue(all(b.device() == d for b, d in zip(y.device_buffers, devices)))\n+ self.assertAllClose(y, jnp.stack(x))\n+\n+ def test_device_put_sharded_pytree(self):\n+ devices = jax.local_devices()\n+ n_devices = len(devices)\n+ x = [(i, np.arange(i, i + 4)) for i in range(n_devices)]\n+ y1, y2 = jax.device_put_sharded(x, devices)\n+ self.assertIsInstance(y1, pxla.ShardedDeviceArray)\n+ self.assertAllClose(y1, jnp.array([a for a, _ in x]))\n+ self.assertTrue(all(b.device() == d for b, d in zip(y1.device_buffers, devices)))\n+ self.assertIsInstance(y2, pxla.ShardedDeviceArray)\n+ self.assertAllClose(y2, jnp.vstack([b for _, b in x]))\n+ self.assertTrue(all(b.device() == d for b, d in zip(y2.device_buffers, devices)))\n+\n+ def test_device_put_replicated_array(self):\n+ devices = jax.local_devices()\n+ n_devices = len(devices)\n+ x = np.arange(1, 5)\n+ y = jax.device_put_replicated(x, devices)\n+ self.assertIsInstance(y, pxla.ShardedDeviceArray)\n+ self.assertEqual(len(y.device_buffers), len(devices))\n+ self.assertTrue(all(b.device() == d for b, d in zip(y.device_buffers, devices)))\n+ self.assertAllClose(y, np.stack([x for _ in devices]))\n+\n+ def test_device_put_replicated_pytree(self):\n+ devices = jax.local_devices()\n+ n_devices = len(devices)\n+ xs = {'a': np.arange(1, 5), 'b': np.arange(3)}\n+ ys = jax.device_put_replicated(xs, devices)\n+ self.assertIsInstance(ys, dict)\n+ y1, y2 = ys['a'], ys['b']\n+\n+ self.assertIsInstance(y1, pxla.ShardedDeviceArray)\n+ self.assertEqual(len(y1.device_buffers), len(devices))\n+ self.assertTrue(all(b.device() == d for b, d in zip(y1.device_buffers, devices)))\n+ self.assertAllClose(y1, np.stack([xs['a'] for _ in devices]))\n+\n+ self.assertIsInstance(y2, pxla.ShardedDeviceArray)\n+ self.assertEqual(len(y2.device_buffers), len(devices))\n+ self.assertTrue(all(b.device() == d for b, d in zip(y2.device_buffers, devices)))\n+ self.assertAllClose(y2, np.stack([xs['b'] for _ in devices]))\n+\nclass SpecToIndicesTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add jax.device_put_replicated Also move tests for device_put_sharded into pmap_test.py, since that file tests with multiple devices even in our OSS CI. Add both device_put_replicated and device_put_sharded to jax/__init__.py.
260,335
04.12.2020 13:34:07
28,800
5f4f08feef36bcd390c4e86b01edb6e3f491a9a2
update jax2tf convert_element_type, remove test
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1094,8 +1094,7 @@ tf_impl[lax.lt_p] = tf.math.less\ntf_impl[lax_linalg.cholesky_p] = tf.linalg.cholesky\n-def _convert_element_type(operand, new_dtype, old_dtype):\n- del old_dtype\n+def _convert_element_type(operand, new_dtype):\nreturn tf.dtypes.cast(operand, to_tf_dtype(new_dtype))\ntf_impl[lax.convert_element_type_p] = _convert_element_type\n@@ -1484,8 +1483,8 @@ def _select_and_gather_add(tangents: TfVal,\ndef pack(a, b):\na = _bitcast_convert_type(a, word_dtype)\nb = _bitcast_convert_type(b, word_dtype)\n- a = _convert_element_type(a, double_word_dtype, word_dtype)\n- b = _convert_element_type(b, double_word_dtype, word_dtype)\n+ a = _convert_element_type(a, double_word_dtype)\n+ b = _convert_element_type(b, double_word_dtype)\na = tf.bitwise.left_shift(a, const(double_word_dtype, nbits))\nreturn tf.bitwise.bitwise_or(a, b)\n@@ -1494,13 +1493,13 @@ def _select_and_gather_add(tangents: TfVal,\nassert t.dtype == double_word_dtype\nst = _shift_right_logical(t, const(double_word_dtype, nbits))\nreturn _bitcast_convert_type(\n- _convert_element_type(st, word_dtype, double_word_dtype), dtype\n+ _convert_element_type(st, word_dtype), dtype\n)\n# Unpacks the second element of a tuple.\ndef snd(t):\nreturn _bitcast_convert_type(\n- _convert_element_type(t, word_dtype, double_word_dtype), dtype\n+ _convert_element_type(t, word_dtype), dtype\n)\nelse:\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -2343,15 +2343,6 @@ class LazyConstantTest(jtu.JaxTestCase):\nmake_const = lambda: lax.broadcast_in_dim(arr, (2, 1, 3), (0, 2))\nself._Check(make_const, expected)\n- def testConvertElementTypeMismatchedDTypeOldDType(self):\n- raise SkipTest(\"test is no longer relevant after removing old_dtype param\")\n- arr = np.ones((2, 2), dtype=np.float32)\n- with self.assertRaisesRegex(\n- TypeError, \"operand dtype and old_dtype must be the same, but got \"\n- \"operand.dtype=float32 and old_dtype=complex64\"):\n- lax.convert_element_type_p.bind(arr, old_dtype=np.complex64,\n- new_dtype=np.bool_)\n-\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_fn={}_indexdtype={}\"\n.format(jax_fn.__name__, np.dtype(index_dtype).name),\n" } ]
Python
Apache License 2.0
google/jax
update jax2tf convert_element_type, remove test
260,335
04.12.2020 16:42:49
28,800
6992ae182c5c8bf78494fb692f40651613acbc73
switch assertions per reviewer comment
[ { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -2051,7 +2051,7 @@ class ShardedDeviceArrayTest(jtu.JaxTestCase):\nself.assertIsInstance(y, pxla.ShardedDeviceArray)\nself.assertEqual(len(y.device_buffers), len(devices))\nself.assertTrue(all(b.device() == d for b, d in zip(y.device_buffers, devices)))\n- self.assertAllClose(y, jnp.stack(x))\n+ self.assertArrayEqual(y, jnp.stack(x))\ndef test_device_put_sharded_pytree(self):\ndevices = jax.local_devices()\n@@ -2059,10 +2059,10 @@ class ShardedDeviceArrayTest(jtu.JaxTestCase):\nx = [(i, np.arange(i, i + 4)) for i in range(n_devices)]\ny1, y2 = jax.device_put_sharded(x, devices)\nself.assertIsInstance(y1, pxla.ShardedDeviceArray)\n- self.assertAllClose(y1, jnp.array([a for a, _ in x]))\n+ self.assertArrayEqual(y1, jnp.array([a for a, _ in x]))\nself.assertTrue(all(b.device() == d for b, d in zip(y1.device_buffers, devices)))\nself.assertIsInstance(y2, pxla.ShardedDeviceArray)\n- self.assertAllClose(y2, jnp.vstack([b for _, b in x]))\n+ self.assertArrayEqual(y2, jnp.vstack([b for _, b in x]))\nself.assertTrue(all(b.device() == d for b, d in zip(y2.device_buffers, devices)))\ndef test_device_put_replicated_array(self):\n@@ -2073,7 +2073,7 @@ class ShardedDeviceArrayTest(jtu.JaxTestCase):\nself.assertIsInstance(y, pxla.ShardedDeviceArray)\nself.assertEqual(len(y.device_buffers), len(devices))\nself.assertTrue(all(b.device() == d for b, d in zip(y.device_buffers, devices)))\n- self.assertAllClose(y, np.stack([x for _ in devices]))\n+ self.assertArrayEqual(y, np.stack([x for _ in devices]))\ndef test_device_put_replicated_pytree(self):\ndevices = jax.local_devices()\n@@ -2086,12 +2086,12 @@ class ShardedDeviceArrayTest(jtu.JaxTestCase):\nself.assertIsInstance(y1, pxla.ShardedDeviceArray)\nself.assertEqual(len(y1.device_buffers), len(devices))\nself.assertTrue(all(b.device() == d for b, d in zip(y1.device_buffers, devices)))\n- self.assertAllClose(y1, np.stack([xs['a'] for _ in devices]))\n+ self.assertArrayEqual(y1, np.stack([xs['a'] for _ in devices]))\nself.assertIsInstance(y2, pxla.ShardedDeviceArray)\nself.assertEqual(len(y2.device_buffers), len(devices))\nself.assertTrue(all(b.device() == d for b, d in zip(y2.device_buffers, devices)))\n- self.assertAllClose(y2, np.stack([xs['b'] for _ in devices]))\n+ self.assertArrayEqual(y2, np.stack([xs['b'] for _ in devices]))\nclass SpecToIndicesTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
switch assertions per reviewer comment
260,335
04.12.2020 21:25:51
28,800
8b64c3c679566990e46be5e8155f9a7dc2e9fe77
fix inherited repr method for ShardedDeviceArray fixes
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -1167,8 +1167,7 @@ for device_array in [_DeviceArray, _CppDeviceArray]:\ndef __repr__(self):\nline_width = np.get_printoptions()[\"linewidth\"]\n- # TODO(jblespia): Should we put back self.__class__.__name__ ?\n- prefix = '{}('.format(\"DeviceArray\")\n+ prefix = '{}('.format(self.__class__.__name__.lstrip('_'))\ns = np.array2string(self._value, prefix=prefix, suffix=',',\nseparator=', ', max_line_width=line_width)\ndtype_str = 'dtype={})'.format(self.dtype.name)\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -2091,6 +2091,10 @@ class ShardedDeviceArrayTest(jtu.JaxTestCase):\nself.assertTrue(all(b.device() == d for b, d in zip(y2.device_buffers, devices)))\nself.assertArraysEqual(y2, np.stack([xs['b'] for _ in devices]))\n+ def test_repr(self):\n+ x = jax.device_put_replicated(1, jax.devices())\n+ self.assertStartsWith(repr(x), 'ShardedDeviceArray')\n+\nclass SpecToIndicesTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
fix inherited repr method for ShardedDeviceArray fixes #5102
260,411
06.12.2020 15:39:30
-7,200
f51db5cd756bf90720c72432b65f596ec106b6d1
Update lax_test.py
[ { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -2127,7 +2127,7 @@ class LaxTest(jtu.JaxTestCase):\ndef test_window_strides_dimension_shape_rule(self):\n# https://github.com/google/jax/issues/5087\nmsg = (\"conv_general_dilated window and window_strides must have \"\n- \"the same number of dimension\")\n+ \"the same number of dimensions\")\nlhs = jax.numpy.zeros((1, 1, 3, 3))\nrhs = np.zeros((1, 1, 1, 1))\nwith self.assertRaisesRegex(ValueError, msg):\n" } ]
Python
Apache License 2.0
google/jax
Update lax_test.py
260,411
06.12.2020 15:41:02
-7,200
2cd21885e2eb2065ae62798c6259d5e2e963eefc
Update docs/profiling.md
[ { "change_type": "MODIFY", "old_path": "docs/profiling.md", "new_path": "docs/profiling.md", "diff": "@@ -12,6 +12,7 @@ GPU and TPU. The end result looks something like this:\n### Installation\n+Install specific nightly versions of TensorBoard, TensorBoard profiler, TensorFlow, as well as the What-If Tool TensorBoard, as follows:\n```shell\n# Profiling is known to work with the following packages.\npip install --upgrade tb-nightly==2.5.0a20201203 tbp-nightly==2.4.0a20201203 tf-nightly==2.5.0.dev20201203 tensorboard-plugin-wit==1.7.0\n" } ]
Python
Apache License 2.0
google/jax
Update docs/profiling.md Co-authored-by: 8bitmp3 <19637339+8bitmp3@users.noreply.github.com>
260,308
01.12.2020 02:06:15
0
85fbc6d790dd44af4e3182620ee10cf2813da9dd
Add axis_index_groups argument to all_to_all.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -233,14 +233,16 @@ def pshuffle(x, axis_name, perm):\nreturn ppermute(x, axis_name, list(zip(perm, range(len(perm)))))\n-def pswapaxes(x, axis_name, axis):\n+def pswapaxes(x, axis_name, axis, *, axis_index_groups=None):\n\"\"\"Swap the pmapped axis ``axis_name`` with the unmapped axis ``axis``.\nIf ``x`` is a pytree then the result is equivalent to mapping this function to\neach leaf in the tree.\n- The mapped axis size must be equal to the size of the unmapped axis; that is,\n- we must have ``lax.psum(1, axis_name) == x.shape[axis]``.\n+ The group size of the mapped axis size must be equal to the size of the\n+ unmapped axis; that is, we must have\n+ ``lax.psum(1, axis_name, axis_index_groups=axis_index_groups) == x.shape[axis]``.\n+ By default, when ``axis_index_groups=None``, this encompasses all the devices.\nThis function is a special case of ``all_to_all`` where the pmapped axis of\nthe input is placed at the position ``axis`` in the output. That is, it is\n@@ -252,13 +254,17 @@ def pswapaxes(x, axis_name, axis):\n:func:`jax.pmap` documentation for more details).\naxis: int indicating the unmapped axis of ``x`` to map with the name\n``axis_name``.\n+ axis_index_groups: optional list of lists containing axis indices (e.g. for\n+ an axis of size 4, [[0, 1], [2, 3]] would run pswapaxes over the first\n+ two and last two replicas). Groups must cover all axis indices exactly\n+ once, and all groups must be the same size.\nReturns:\nArray(s) with the same shape as ``x``.\n\"\"\"\n- return all_to_all(x, axis_name, axis, axis)\n+ return all_to_all(x, axis_name, axis, axis, axis_index_groups=axis_index_groups)\n-def all_to_all(x, axis_name, split_axis, concat_axis):\n+def all_to_all(x, axis_name, split_axis, concat_axis, *, axis_index_groups=None):\n\"\"\"Materialize the mapped axis and map a different axis.\nIf ``x`` is a pytree then the result is equivalent to mapping this function to\n@@ -268,8 +274,10 @@ def all_to_all(x, axis_name, split_axis, concat_axis):\nlogical axis position ``concat_axis``, and the input unmapped axis at position\n``split_axis`` is mapped with the name ``axis_name``.\n- The input mapped axis size must be equal to the size of the axis to be mapped;\n- that is, we must have ``lax.psum(1, axis_name) == x.shape[split_axis]``.\n+ The group size of the mapped axis size must be equal to the size of the\n+ unmapped axis; that is, we must have\n+ ``lax.psum(1, axis_name, axis_index_groups=axis_index_groups) == x.shape[axis]``.\n+ By default, when ``axis_index_groups=None``, this encompasses all the devices.\nArgs:\nx: array(s) with a mapped axis named ``axis_name``.\n@@ -279,6 +287,10 @@ def all_to_all(x, axis_name, split_axis, concat_axis):\n``axis_name``.\nconcat_axis: int indicating the position in the output to materialize the\nmapped axis of the input with the name ``axis_name``.\n+ axis_index_groups: optional list of lists containing axis indices (e.g. for\n+ an axis of size 4, [[0, 1], [2, 3]] would run all_to_all over the first\n+ two and last two replicas). Groups must cover all axis indices exactly\n+ once, and all groups must be the same size.\nReturns:\nArray(s) with shape given by the expression::\n@@ -289,12 +301,15 @@ def all_to_all(x, axis_name, split_axis, concat_axis):\nthe input ``x``, i.e. ``axis_size = lax.psum(1, axis_name)``.\n\"\"\"\ndef bind(x):\n- if psum(1, axis_name) != x.shape[split_axis]:\n+ group_size = psum(1, axis_name, axis_index_groups=axis_index_groups)\n+ if group_size != x.shape[split_axis]:\nmsg = (\"all_to_all requires the size of the mapped axis axis_name to \"\n\"equal x.shape[split_axis], but they are {} and {} respectively.\")\n- raise ValueError(msg.format(psum(1, axis_name), x.shape[split_axis]))\n+ raise ValueError(msg.format(group_size, x.shape[split_axis]))\nreturn all_to_all_p.bind(x, split_axis=split_axis, concat_axis=concat_axis,\n- axis_name=axis_name)\n+ axis_name=axis_name,\n+ axis_index_groups=axis_index_groups)\n+\nreturn tree_util.tree_map(bind, x)\ndef axis_index(axis_name):\n@@ -548,16 +563,18 @@ def _moveaxis(src, dst, x):\nperm.insert(dst, src)\nreturn lax.transpose(x, perm)\n-def _all_to_all_via_all_gather(x, *, axis_name, split_axis, concat_axis):\n- global_full = all_gather(x, axis_name)\n+def _all_to_all_via_all_gather(x, *, axis_name, split_axis, concat_axis, axis_index_groups):\n+ global_full = all_gather(x, axis_name, axis_index_groups=axis_index_groups)\nidx = axis_index(axis_name)\n+ if axis_index_groups:\n+ idx = idx % len(axis_index_groups[0])\nlocal_slice = lax.dynamic_index_in_dim(global_full, idx, split_axis + 1, keepdims=False)\nreturn _moveaxis(0, concat_axis, local_slice)\ndef _all_to_all_translation_rule(c, x, *, split_axis, concat_axis, axis_name,\n- axis_env, platform):\n+ axis_index_groups, axis_env, platform):\n# Workaround for AllToAll not being implemented on CPU.\n- replica_groups = _replica_groups(axis_env, axis_name, None)\n+ replica_groups = _replica_groups(axis_env, axis_name, axis_index_groups)\nif len(replica_groups[0]) == 1:\nreturn x\nelif platform != 'tpu':\n@@ -567,7 +584,7 @@ def _all_to_all_translation_rule(c, x, *, split_axis, concat_axis, axis_name,\nlowering = xla.lower_fun(_all_to_all_via_all_gather, multiple_results=False, parallel=True)\nreturn lowering(c, x,\nsplit_axis=split_axis, concat_axis=concat_axis, axis_name=axis_name,\n- axis_env=axis_env, platform=platform)\n+ axis_index_groups=axis_index_groups, axis_env=axis_env, platform=platform)\nelse:\nsplit_count = len(replica_groups[0])\nif not all(split_count == len(g) for g in replica_groups):\n@@ -586,10 +603,16 @@ def _all_to_all_translation_rule(c, x, *, split_axis, concat_axis, axis_name,\nx = xla.lower_fun(partial(lax.squeeze, dimensions=(split_axis,)), multiple_results=False)(c, x)\nreturn x\n-def _all_to_all_transpose_rule(cts, axis_name, split_axis, concat_axis):\n- return (all_to_all(cts, axis_name=axis_name, split_axis=concat_axis, concat_axis=split_axis),)\n+def _all_to_all_transpose_rule(cts, axis_name, split_axis, concat_axis, axis_index_groups):\n+ return (all_to_all(\n+ cts,\n+ axis_name=axis_name,\n+ split_axis=concat_axis,\n+ concat_axis=split_axis,\n+ axis_index_groups=axis_index_groups),)\n-def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_axis, concat_axis):\n+\n+def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_axis, concat_axis, axis_index_groups):\nx, = vals_in\nd, = dims_in\nif d <= split_axis:\n@@ -602,11 +625,17 @@ def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_axis, concat_axis)\nd -= 1\nelif concat_axis < d < split_axis:\nd += 1\n- result = all_to_all_p.bind(x, axis_name=axis_name, split_axis=split_axis, concat_axis=concat_axis)\n+ result = all_to_all_p.bind(\n+ x,\n+ axis_name=axis_name,\n+ split_axis=split_axis,\n+ concat_axis=concat_axis,\n+ axis_index_groups=axis_index_groups)\nreturn result, d\ndef _all_to_all_batched_collective(frame, vals_in, dims_in,\n- axis_name, split_axis, concat_axis):\n+ axis_name, split_axis, concat_axis,\n+ axis_index_groups):\nif isinstance(axis_name, (list, tuple)) and len(axis_name) > 1:\nraise NotImplementedError(\"update after #4835\") # TODO(mattjj,apaszke)\nx, = vals_in\n@@ -619,7 +648,7 @@ def _all_to_all_batched_collective(frame, vals_in, dims_in,\nsplit_axis_adj += 1\nreturn _moveaxis(d, concat_axis_adj, x), split_axis_adj\n-def _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis):\n+def _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis, axis_index_groups):\ninput_aval = raise_to_shaped(x)\nshape = list(input_aval.shape)\nsize = shape.pop(split_axis)\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -1039,7 +1039,7 @@ class BatchingTest(jtu.JaxTestCase):\nshape = (2, 3, 4, 5)\nx = np.arange(np.prod(shape)).reshape(shape)\nrule = batching.collective_rules[lax.all_to_all_p]\n- y, out_d = rule(None, (x,), (d,), None, split_axis, concat_axis)\n+ y, out_d = rule(None, (x,), (d,), None, split_axis, concat_axis, None)\nexp_shape = shape_fun(x, out_d)\nself.assertEqual(y.shape, exp_shape)\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -1162,6 +1162,57 @@ class PmapTest(jtu.JaxTestCase):\nexpected = np.tile(w, reps=device_count).reshape(shape)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testAllToAllReplicaGroups(self):\n+ # If num_devices = 4, these would be the inputs/outputs:\n+ # input = [[0, 1], [2, 3], [4, 5], [6, 7]]\n+ # axis_index_groups = [[0, 1], [2, 3]]\n+ # output = [[0, 2], [1, 3], [4, 6], [5, 7]]\n+ #\n+ # This is essentially like spliting the number of rows in the input in two\n+ # groups of rows, and swaping the two inner axes (axis=1 and axis=2), which\n+ # is exactly what the test case checks.\n+ device_count = xla_bridge.device_count()\n+ if device_count % 2 != 0:\n+ raise SkipTest('test requires an even number of devices')\n+ shape = (device_count, device_count // 2)\n+ x = np.arange(prod(shape)).reshape(shape)\n+\n+ axis_index_groups = np.arange(device_count, dtype=np.int32)\n+ axis_index_groups = axis_index_groups.reshape((2, device_count // 2))\n+ axis_index_groups = axis_index_groups.tolist()\n+\n+ @partial(pmap, axis_name='i')\n+ def fn(x):\n+ return lax.all_to_all(x, 'i', 0, 0, axis_index_groups=axis_index_groups)\n+\n+ expected = np.swapaxes(\n+ x.reshape((2, device_count // 2, device_count // 2)),\n+ 1, 2).reshape(shape)\n+ self.assertAllClose(fn(x), expected, check_dtypes=False)\n+\n+ def testGradOfAllToAllReplicaGroups(self):\n+ device_count = xla_bridge.device_count()\n+ if device_count % 2 != 0:\n+ raise SkipTest('test requires an even number of devices')\n+ shape = (device_count, device_count // 2, 1)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ w = np.arange(device_count, dtype=np.float32)\n+\n+ axis_index_groups = np.arange(device_count, dtype=np.int32)\n+ axis_index_groups = axis_index_groups.reshape((2, device_count // 2))\n+ axis_index_groups = axis_index_groups.tolist()\n+\n+ @partial(pmap, axis_name='i')\n+ def fn(x, w):\n+ g = lambda x: jnp.sum(lax.all_to_all(x, 'i', 0, 1, axis_index_groups=axis_index_groups) * w)\n+ return grad(g)(x)\n+\n+ expected = np.ones_like(x) * w[:, np.newaxis, np.newaxis]\n+ expected = np.swapaxes(\n+ expected.reshape((2, device_count // 2, device_count // 2)),\n+ 1, 2).reshape(shape)\n+ self.assertAllClose(fn(x, w), expected, check_dtypes=False)\n+\ndef testReshardInput(self):\nif xla_bridge.device_count() < 6:\nraise SkipTest(\"testReshardInput requires 6 devices\")\n" } ]
Python
Apache License 2.0
google/jax
Add axis_index_groups argument to all_to_all.
260,684
07.12.2020 10:06:08
28,800
df411ff49b09bcafedc04bd6236e119dc86183e4
Update autodiff_cookbook.ipynb
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/autodiff_cookbook.ipynb", "new_path": "docs/notebooks/autodiff_cookbook.ipynb", "diff": "\"name\": \"python\",\n\"nbconvert_exporter\": \"python\",\n\"pygments_lexer\": \"ipython3\",\n- \"version\": \"3.7.4-final\"\n+ \"version\": \"3.7.3\"\n},\n\"accelerator\": \"GPU\"\n},\n\"\\n\",\n\"key = random.PRNGKey(0)\"\n],\n- \"execution_count\": 2,\n- \"outputs\": [\n- {\n- \"output_type\": \"stream\",\n- \"name\": \"stderr\",\n- \"text\": [\n- \"WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)\\n\"\n- ]\n- }\n- ]\n+ \"execution_count\": 1,\n+ \"outputs\": []\n},\n{\n\"cell_type\": \"markdown\",\n" } ]
Python
Apache License 2.0
google/jax
Update autodiff_cookbook.ipynb
260,287
09.12.2020 12:38:39
0
f3bfdf8968b7f591b00bd8fde8f03bb2d371d082
Expose `is_leaf` predicate for `pytree.flatten` and add tests for it. The change has already been landed in the TF code, where the C++ pytree components live. This is why I needed to bump the commit.
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -37,10 +37,10 @@ http_archive(\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"8bee4fec72ed5eebd1ab022514741ae9033f8b7da99d25a0958f6f7b9fa560cf\",\n- strip_prefix = \"tensorflow-b34e7144ed6dd0ab51c03df783aa14009589e800\",\n+ sha256 = \"687d0d60e7237f3b024162f6681dc76338a7f43cade1ae1f42ad7ed80982b314\",\n+ strip_prefix = \"tensorflow-6e28513ec1e1d7d895bea8478f08f84265a113e9\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/b34e7144ed6dd0ab51c03df783aa14009589e800.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/6e28513ec1e1d7d895bea8478f08f84265a113e9.tar.gz\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.rst", "new_path": "docs/CHANGELOG.rst", "diff": "@@ -97,6 +97,7 @@ jaxlib 0.1.58 (Unreleased)\n* Fixed a bug that meant JAX sometimes return platform-specific types (e.g.,\n`np.cint`) instead of standard types (e.g., `np.int32`). (#4903)\n* Fixed a crash when constant-folding certain int16 operations. (#4971)\n+* Added an `is_leaf` predicate to `pytree.flatten`.\njaxlib 0.1.57 (November 12 2020)\n--------------------------------\n" }, { "change_type": "MODIFY", "old_path": "jax/tree_util.py", "new_path": "jax/tree_util.py", "diff": "@@ -39,6 +39,7 @@ for examples.\nimport functools\nimport collections\nimport operator as op\n+from typing import Optional, Callable, Any\nfrom .lib import pytree\n@@ -48,17 +49,24 @@ from ._src import traceback_util\ntraceback_util.register_exclusion(__file__)\n-def tree_flatten(tree):\n+def tree_flatten(tree, is_leaf: Optional[Callable[[Any], bool]] = None):\n\"\"\"Flattens a pytree.\nArgs:\ntree: a pytree to flatten.\n+ is_leaf: an optionally specified function that will be called at each\n+ flattening step. It should return a boolean, which indicates whether\n+ the flattening should traverse the current object, or if it should be\n+ stopped immediately, with the whole subtree being treated as a leaf.\nReturns:\nA pair where the first element is a list of leaf values and the second\nelement is a treedef representing the structure of the flattened tree.\n\"\"\"\n- return pytree.flatten(tree)\n+ # We skip the second argument in support of old jaxlibs\n+ # TODO: Remove once 0.1.58 becomes the minimum supported jaxlib version\n+ return pytree.flatten(tree) if is_leaf is None else pytree.flatten(tree, is_leaf)\n+\ndef tree_unflatten(treedef, leaves):\n\"\"\"Reconstructs a pytree from the treedef and the leaves.\n" }, { "change_type": "MODIFY", "old_path": "tests/tree_util_tests.py", "new_path": "tests/tree_util_tests.py", "diff": "import collections\n+from unittest import skipIf\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n+import jax\nfrom jax import test_util as jtu\nfrom jax import tree_util\n@@ -192,6 +194,32 @@ class TreeTest(jtu.JaxTestCase):\nself.assertEqual(out, (((1, [3]), (2, None)),\n((3, {\"foo\": \"bar\"}), (4, 7), (5, [5, 6]))))\n+ @skipIf(jax.lib.version < (0, 1, 58), \"test requires Jaxlib >= 0.1.58\")\n+ def testFlattenIsLeaf(self):\n+ x = [(1, 2), (3, 4), (5, 6)]\n+ leaves, _ = tree_util.tree_flatten(x, is_leaf=lambda t: False)\n+ self.assertEqual(leaves, [1, 2, 3, 4, 5, 6])\n+ leaves, _ = tree_util.tree_flatten(\n+ x, is_leaf=lambda t: isinstance(t, tuple))\n+ self.assertEqual(leaves, x)\n+ leaves, _ = tree_util.tree_flatten(x, is_leaf=lambda t: isinstance(t, list))\n+ self.assertEqual(leaves, [x])\n+ leaves, _ = tree_util.tree_flatten(x, is_leaf=lambda t: True)\n+ self.assertEqual(leaves, [x])\n+\n+ y = [[[(1,)], [[(2,)], {\"a\": (3,)}]]]\n+ leaves, _ = tree_util.tree_flatten(\n+ y, is_leaf=lambda t: isinstance(t, tuple))\n+ self.assertEqual(leaves, [(1,), (2,), (3,)])\n+\n+ @skipIf(jax.lib.version < (0, 1, 58), \"test requires Jaxlib >= 0.1.58\")\n+ @parameterized.parameters(*TREES)\n+ def testRoundtripIsLeaf(self, tree):\n+ xs, treedef = tree_util.tree_flatten(\n+ tree, is_leaf=lambda t: isinstance(t, tuple))\n+ recon_tree = tree_util.tree_unflatten(treedef, xs)\n+ self.assertEqual(recon_tree, tree)\n+\n@parameterized.parameters(*TREES)\ndef testAllLeavesWithTrees(self, tree):\nleaves = tree_util.tree_leaves(tree)\n" } ]
Python
Apache License 2.0
google/jax
Expose `is_leaf` predicate for `pytree.flatten` and add tests for it. The change has already been landed in the TF code, where the C++ pytree components live. This is why I needed to bump the commit.
260,287
30.11.2020 14:32:28
0
8fcacd645cf7c25888323eef8c8c883e02019dee
Support mapping a single logical axis to multiple mesh axes in xmap
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -224,6 +224,11 @@ def xmap(fun: Callable,\nf\"in_axes, but the following are missing: \"\nf\"{out_axes_names - in_axes_names}\")\n+ for axis, resources in frozen_axis_resources.items():\n+ if len(set(resources)) != len(resources):\n+ raise ValueError(f\"Resource assignment of a single axis must be a tuple of \"\n+ f\"distinct resources, but specified {resources} for axis {axis}\")\n+\n@wraps(fun)\ndef fun_mapped(*args):\n# Putting this outside of fun_mapped would make resources lexically scoped\n@@ -303,20 +308,15 @@ def make_xmap_callable(fun: lu.WrappedFun,\nclass EvaluationPlan(NamedTuple):\n\"\"\"Encapsulates preprocessing common to top-level xmap invocations and its translation rule.\"\"\"\n- physical_resource_map: Dict[ResourceAxisName, Set[AxisName]]\n+ physical_axis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]]\naxis_subst: Dict[AxisName, Tuple[ResourceAxisName, ...]]\n@classmethod\ndef from_axis_resources(cls, axis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]], resource_env):\n- physical_resource_map: Dict[ResourceAxisName, Set[AxisName]] = {}\n- for axis, resources in axis_resources.items():\n- for resource in resources:\n- if resource not in resource_env.physical_resource_axes:\n- raise ValueError(f\"Mapping axis {axis} to an undefined resource axis {resource}. \"\n- f\"The resource axes currently in scope are: {resource_env.resource_axes}\")\n- physical_resource_map.setdefault(resource, set()).add(axis)\n+ # TODO: Support sequential resources\n+ physical_axis_resources = axis_resources # NB: We only support physical resources at the moment\naxis_subst = {name: axes + (fresh_resource_name(name),) for name, axes in axis_resources.items()}\n- return cls(physical_resource_map, axis_subst)\n+ return cls(physical_axis_resources, axis_subst)\ndef vectorize(self, f: lu.WrappedFun, in_axes, out_axes):\nfor naxis, raxes in self.axis_subst.items():\n@@ -332,13 +332,9 @@ class EvaluationPlan(NamedTuple):\nin/out_axes that range over the mesh dimensions.\n\"\"\"\ndef to_mesh(axes):\n- mesh_axes = {}\n- for paxis, naxes in self.physical_resource_map.items():\n- axis = lookup_exactly_one_of(axes, naxes)\n- if axis is None:\n- continue\n- mesh_axes[paxis] = axis\n- return AxisNamePos(mesh_axes)\n+ return OrderedDict((physical_axis, pos_axis)\n+ for logical_axis, pos_axis in axes.items()\n+ for physical_axis in self.physical_axis_resources[logical_axis])\nreturn (tuple(unsafe_map(to_mesh, in_axes)),\ntuple(unsafe_map(to_mesh, out_axes)))\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "# This encoding is assumed by various parts of the system, e.g. generating\n# replica groups for collective operations.\n+import sys\nfrom contextlib import contextmanager\nfrom collections import defaultdict, OrderedDict\nimport itertools as it\n@@ -57,6 +58,10 @@ from . import partial_eval as pe\nfrom . import xla\nfrom . import ad\n+if sys.version_info >= (3, 9):\n+ OrderedDictType = OrderedDict\n+else:\n+ OrderedDictType = Dict\nxops = xc.ops\n@@ -71,11 +76,31 @@ Index = Union[int, slice, Tuple[Union[int, slice], ...]]\nif TYPE_CHECKING:\nclass Unstacked(NamedTuple):\nsize: int\n- class Chunked(NamedTuple):\n- chunks: int\nelse:\nUnstacked = taggedtuple('Unstacked', ('size',))\n- Chunked = taggedtuple('Chunked', ('chunks',))\n+\n+class Chunked:\n+ chunks: Tuple[int, ...]\n+\n+ def __init__(self, chunks: Union[int, Tuple[int, ...]]):\n+ if isinstance(chunks, int):\n+ chunks = (chunks,)\n+ object.__setattr__(self, 'chunks', chunks)\n+\n+ def __setattr__(self, name, value):\n+ raise RuntimeError(\"Chunked is immutable\")\n+\n+ def __delattr__(self, name):\n+ raise RuntimeError(\"Chunked is immutable\")\n+\n+ def __hash__(self):\n+ return hash(self.chunks)\n+\n+ def __eq__(self, other):\n+ return type(other) is Chunked and self.chunks == other.chunks\n+\n+ def __repr__(self):\n+ return f'Chunked({self.chunks})'\n\"\"\"\nRepresents all the ways we can shard a dimension.\n@@ -139,7 +164,7 @@ class ShardingSpec:\nelif isinstance(sharding, Unstacked):\nsharded_axis_sizes.append(sharding.size)\nelif isinstance(sharding, Chunked):\n- sharded_axis_sizes.append(sharding.chunks)\n+ sharded_axis_sizes.extend(sharding.chunks)\nelse:\nassert_unreachable(sharding)\nreturn tuple(sharded_axis_sizes[a.axis] if isinstance(a, ShardedAxis) else a.replicas\n@@ -181,10 +206,12 @@ class ShardingSpec:\nif sharding is None:\nnew_mesh_shape.append(1) # Add a dummy mesh axis we won't be sharding over\nelif isinstance(sharding, Chunked):\n+ for nchunks in sharding.chunks:\nmaxis = sharded_axes[next_sharded_axis]\n+ assert mesh_shape[maxis] == nchunks\nmesh_permutation.append(maxis)\n- new_mesh_shape.append(mesh_shape[maxis])\nnext_sharded_axis += 1\n+ new_mesh_shape.append(int(np.prod(sharding.chunks)))\nelif isinstance(sharding, Unstacked):\nraise RuntimeError(\"Cannot convert unstacked sharding specs to XLA OpSharding\")\nelse:\n@@ -208,9 +235,10 @@ class ShardingSpec:\nshape: The shape of the logical array being sharded.\nReturns:\n- An ndarray with a NumPy-style index for each element of the logical mesh.\n- Each element is an int, a slice object with step=1, or a tuple thereof, to\n- be treated as an index into the full logical array.\n+ An ndarray with the same shape as the logical mesh (as derived form\n+ `mesh_mapping`). Each entry is a NumPy-style index selecting the subset of\n+ the data array to be placed on a corresponding device. The indices can be\n+ ints, slice objects with step=1, or tuples of those.\n\"\"\"\nassert len(shape) == len(self.sharding), (shape, self.sharding)\n@@ -227,11 +255,12 @@ class ShardingSpec:\naxis_indices.append(range(axis_size))\nshard_indices_shape.append(axis_size)\nelif isinstance(sharding, Chunked):\n- shard_size, ragged = divmod(axis_size, sharding.chunks)\n- assert not ragged, (axis_size, sharding.chunks, dim)\n+ total_chunks = int(np.prod(sharding.chunks))\n+ shard_size, ragged = divmod(axis_size, total_chunks)\n+ assert not ragged, (axis_size, total_chunks, dim)\naxis_indices.append([slice(i * shard_size, (i + 1) * shard_size)\n- for i in range(sharding.chunks)])\n- shard_indices_shape.append(sharding.chunks)\n+ for i in range(total_chunks)])\n+ shard_indices_shape.extend(sharding.chunks)\nelse:\nassert_unreachable(sharding)\n@@ -258,6 +287,12 @@ class ShardingSpec:\nreturn (np.broadcast_to(shard_indices, replica_sizes + shard_indices.shape)\n.transpose(perm))\n+ def __eq__(self, other):\n+ return (self.sharding, self.mesh_mapping) == (other.sharding, other.mesh_mapping)\n+\n+ def __hash__(self):\n+ return hash((self.sharding, self.mesh_mapping))\n+\ndef __repr__(self):\nreturn f'ShardingSpec({self.sharding}, {self.mesh_mapping})'\n@@ -1239,13 +1274,28 @@ def _unravel_index(c, axis_env):\n# ------------------- xmap -------------------\n-AxisName = Any\n-AxisNameMap = Any # Dict[AxisName, int]\n+MeshAxisName = Any\n+\"\"\"\n+ArrayMapping specifies how an ndarray should map to mesh axes.\n+\n+Note that the ordering is crucial for the cases when this mapping is non-injective\n+(i.e. when multiple mesh axes map to the same positional axis). Then, the\n+order of entries of the mapping determines a major-to-minor order on mesh axes,\n+according to which chunks of the value along the repeated dimension will be assigned.\n+\n+For example, consider a mapping {'x': 1, 'y': 1} and a mesh with shape {'x': 2, 'y': 3}.\n+The second dimension of the value would get chunked into 6 pieces, and assigned to the\n+mesh in a way that treats 'y' as the fastest changing (minor) dimension. In this case,\n+that would mean that a flat list of chunks would get assigned to a flattened list of\n+mesh devices without any modifications. If the mapping was {'y': 1, 'x': 1}, then the\n+mesh devices ndarray would have to be transposed before flattening and assignment.\n+\"\"\"\n+ArrayMapping = OrderedDictType[MeshAxisName, int]\nclass Mesh:\n__slots__ = ('devices', 'axis_names')\n- def __init__(self, devices: np.ndarray, axis_names: Sequence[AxisName]):\n+ def __init__(self, devices: np.ndarray, axis_names: Sequence[MeshAxisName]):\nassert devices.ndim == len(axis_names)\n# TODO: Make sure that devices are unique? At least with the quick and\n# dirty check that the array size is not larger than the number of\n@@ -1297,7 +1347,7 @@ class Mesh:\ndef device_ids(self):\nreturn np.vectorize(lambda d: d.id, otypes=[int])(self.devices)\n-def tile_aval_nd(axis_sizes, in_axes: AxisNameMap, aval):\n+def tile_aval_nd(axis_sizes, in_axes: ArrayMapping, aval):\nif aval is core.abstract_unit:\nreturn aval\nassert isinstance(aval, ShapedArray)\n@@ -1307,7 +1357,7 @@ def tile_aval_nd(axis_sizes, in_axes: AxisNameMap, aval):\nshape[axis] //= axis_sizes[name]\nreturn ShapedArray(tuple(shape), aval.dtype)\n-def untile_aval_nd(axis_sizes, out_axes: AxisNameMap, aval):\n+def untile_aval_nd(axis_sizes, out_axes: ArrayMapping, aval):\nif aval is core.abstract_unit:\nreturn aval\nassert isinstance(aval, ShapedArray)\n@@ -1320,8 +1370,8 @@ def mesh_tiled_callable(fun: lu.WrappedFun,\ntransformed_name: str,\nbackend_name: Optional[str],\nmesh: Mesh,\n- in_axes: Sequence[AxisNameMap],\n- out_axes: Sequence[AxisNameMap],\n+ in_axes: Sequence[ArrayMapping],\n+ out_axes: Sequence[ArrayMapping],\nspmd_lowering,\n*local_in_untiled_avals):\nassert config.omnistaging_enabled\n@@ -1493,29 +1543,26 @@ def _sanitize_mesh_jaxpr(jaxpr):\ncore.traverse_jaxpr_params(_sanitize_mesh_jaxpr, eqn.params)\n-def mesh_sharding_specs(local_axis_sizes, axis_names):\n+def mesh_sharding_specs(axis_sizes, axis_names):\nmesh_axis_pos = {name: i for i, name in enumerate(axis_names)}\n# NOTE: This takes in the non-sharded avals!\ndef mk_sharding_spec(aval, aval_axes):\nsharding = [None] * len(aval.shape)\n- pre_mesh_mapping = [None] * len(local_axis_sizes)\n- for name, axis in aval_axes.items():\n- if sharding[axis] is not None:\n- raise NotImplementedError(\"A single named dimension can only be mapped to \"\n- \"a single physical resource at the moment.\")\n- assert aval.shape[axis] % local_axis_sizes[name] == 0, (local_axis_sizes[name], aval.shape[axis])\n- sharding[axis] = Chunked(local_axis_sizes[name])\n- pre_mesh_mapping[mesh_axis_pos[name]] = axis\n-\n- sharded_axis_idx = {}\n- sharded_axis_count = 0\n- for axis, dim_sharding in enumerate(sharding):\n- if dim_sharding is not None:\n- sharded_axis_idx[axis] = sharded_axis_count\n- sharded_axis_count += 1\n-\n- mesh_mapping = [Replicated(axis_size) if m is None else ShardedAxis(sharded_axis_idx[m])\n- for m, axis_size in zip(pre_mesh_mapping, local_axis_sizes.values())]\n+ mesh_mapping = [Replicated(axis_size) for axis_size in axis_sizes.values()]\n+ next_sharded_axis = 0\n+ aval_shape = list(aval.shape)\n+ # NOTE: sorted is stable, which is important when multiple resources\n+ # map to the same axis.\n+ for name, axis in sorted(aval_axes.items(), key=lambda x: x[1]):\n+ assert aval_shape[axis] % axis_sizes[name] == 0, (axis_sizes[name], aval.shape[axis])\n+ aval_shape[axis] //= axis_sizes[name]\n+ if sharding[axis] is None:\n+ sharding[axis] = Chunked(())\n+ sharding[axis] = Chunked(sharding[axis].chunks + (axis_sizes[name],))\n+ assert isinstance(mesh_mapping[mesh_axis_pos[name]], Replicated), \\\n+ \"Value mapped to the same mesh axis twice\"\n+ mesh_mapping[mesh_axis_pos[name]] = ShardedAxis(next_sharded_axis)\n+ next_sharded_axis += 1\nreturn ShardingSpec(sharding, mesh_mapping)\nreturn mk_sharding_spec\n" }, { "change_type": "MODIFY", "old_path": "jax/util.py", "new_path": "jax/util.py", "diff": "@@ -300,9 +300,9 @@ def taggedtuple(name, fields) -> Callable[..., Any]:\n\"\"\"Lightweight version of namedtuple where equality depends on the type.\"\"\"\ndef __new__(cls, *xs):\nreturn tuple.__new__(cls, (cls,) + xs)\n- def __str__(self):\n+ def __repr__(self):\nreturn '{}{}'.format(name, tuple.__str__(self[1:]))\n- class_namespace = {'__new__' : __new__, '__str__': __str__}\n+ class_namespace = {'__new__' : __new__, '__repr__': __repr__}\nfor i, f in enumerate(fields):\nclass_namespace[f] = property(operator.itemgetter(i+1)) # type: ignore\nreturn type(name, (tuple,), class_namespace)\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -142,6 +142,41 @@ class XMapTest(jtu.JaxTestCase):\ntestBasicCollectiveSPMD = use_spmd_lowering(testBasicCollective)\n+ @ignore_xmap_warning()\n+ @with_mesh([('x', 2), ('y', 2)])\n+ def testOneLogicalTwoMeshAxesBasic(self):\n+ def f(v):\n+ return lax.psum(v * 2, 'a'), v * 4\n+ fm = xmap(f, in_axes=['a', ...], out_axes=[{}, {1: 'a'}],\n+ axis_resources={'a': ('x', 'y')})\n+ vshape = (4, 5)\n+ v = jnp.arange(np.prod(vshape)).reshape(vshape)\n+ ans, ans2 = fm(v)\n+ self.assertAllClose(ans, (v * 2).sum(0))\n+ self.assertAllClose(ans2, v.T * 4)\n+\n+ @ignore_xmap_warning()\n+ @with_mesh([('x', 2), ('y', 2)])\n+ def testOneLogicalTwoMeshAxesSharding(self):\n+ def f(v):\n+ return v * 4\n+ fxy = xmap(f, in_axes=['a', ...], out_axes={1: 'a'},\n+ axis_resources={'a': ('x', 'y')})\n+ fyx = xmap(f, in_axes=['a', ...], out_axes={1: 'a'},\n+ axis_resources={'a': ('y', 'x')})\n+ vshape = (4, 5)\n+ v = jnp.arange(np.prod(vshape)).reshape(vshape)\n+ zxy = fxy(v)\n+ self.assertEqual(\n+ zxy.sharding_spec,\n+ pxla.ShardingSpec((None, pxla.Chunked((2, 2))),\n+ (pxla.ShardedAxis(0), pxla.ShardedAxis(1))))\n+ zyx = fyx(v)\n+ self.assertEqual(\n+ zyx.sharding_spec,\n+ pxla.ShardingSpec((None, pxla.Chunked((2, 2))),\n+ (pxla.ShardedAxis(1), pxla.ShardedAxis(0))))\n+\n@ignore_xmap_warning()\n@with_mesh([('x', 2)])\ndef testCompilationCache(self):\n@@ -248,5 +283,17 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(z, jnp.einsum('nij,njk->nik', x, y))\n+class XMapErrorTest(jtu.JaxTestCase):\n+\n+ @ignore_xmap_warning()\n+ @with_mesh([('x', 2)])\n+ def testRepeatedAxisResource(self):\n+ def f(v):\n+ return v * 4\n+ with self.assertRaisesRegex(ValueError, r\"distinct resources.*specified \\('x', 'x'\\) for axis a\"):\n+ fxy = xmap(f, in_axes=['a', ...], out_axes=['a', ...],\n+ axis_resources={'a': ('x', 'x')})\n+\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Support mapping a single logical axis to multiple mesh axes in xmap
260,634
13.12.2020 17:03:07
-3,600
269676ee4e6753b63da4846ef63100e9140a0af4
Typo ? I removed "-e" option from "pip install -e dist/*.whl # installs jaxlib (includes XLA)" line 58. It is now coherent with lines 69-70. When I tried the command with the "-e" it threw an error, without "-e" it worked fine.
[ { "change_type": "MODIFY", "old_path": "docs/developer.rst", "new_path": "docs/developer.rst", "diff": "@@ -55,7 +55,7 @@ You can install the necessary Python dependencies using ``pip``::\nTo build ``jaxlib`` with CUDA support, you can run::\npython build/build.py --enable_cuda\n- pip install -e dist/*.whl # installs jaxlib (includes XLA)\n+ pip install dist/*.whl # installs jaxlib (includes XLA)\nSee ``python build/build.py --help`` for configuration options, including ways to\n" } ]
Python
Apache License 2.0
google/jax
Typo ? I removed "-e" option from "pip install -e dist/*.whl # installs jaxlib (includes XLA)" line 58. It is now coherent with lines 69-70. When I tried the command with the "-e" it threw an error, without "-e" it worked fine.
260,335
14.12.2020 17:09:25
28,800
7342318774c6f1195f0e238f1209425109ea8944
check for __jax_array__ method for conversion
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -437,6 +437,9 @@ def convert_element_type(operand: Array, new_dtype: DType = None,\nmsg = \"Casting complex values to real discards the imaginary part\"\nwarnings.warn(msg, np.ComplexWarning, stacklevel=2)\n+ if hasattr(operand, '__jax_array__'):\n+ operand = operand.__jax_array__()\n+\nif not isinstance(operand, (core.Tracer, xla.DeviceArray)):\nreturn _device_put_raw(np.asarray(operand, dtype=new_dtype),\nweak_type=new_weak_type)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -300,9 +300,11 @@ def _result_dtype(op, *args):\nreturn _dtype(op(*args))\n-def _arraylike(x): return isinstance(x, ndarray) or isscalar(x)\n+def _arraylike(x):\n+ return isinstance(x, ndarray) or isscalar(x) or hasattr(x, '__jax_array__')\n+\ndef _check_arraylike(fun_name, *args):\n- \"\"\"Check if all args fit JAX's definition of arraylike (ndarray or scalar).\"\"\"\n+ \"\"\"Check if all args fit JAX's definition of arraylike.\"\"\"\nassert isinstance(fun_name, str), f\"fun_name must be a string. Got {fun_name}\"\nif _any(not _arraylike(arg) for arg in args):\npos, arg = next((i, arg) for i, arg in enumerate(args)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -859,6 +859,8 @@ def concrete_aval(x):\nfor typ in type(x).mro():\nhandler = pytype_aval_mappings.get(typ)\nif handler: return handler(x)\n+ if hasattr(x, '__jax_array__'):\n+ return concrete_aval(x.__jax_array__())\nraise TypeError(f\"{type(x)} is not a valid JAX type\")\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -122,10 +122,13 @@ xla_result_handlers: Dict[Type[core.AbstractValue], Callable[..., Callable]] = {\n}\ndef device_put(x, device: Optional[Device] = None) -> Tuple[Any]:\n+ handler = device_put_handlers.get(type(x))\n+ if handler:\nx = canonicalize_dtype(x)\n- try:\n- return device_put_handlers[type(x)](x, device)\n- except KeyError as err:\n+ return handler(x, device)\n+ elif hasattr(x, '__jax_array__'):\n+ return device_put(x.__jax_array__(), device)\n+ else:\nraise TypeError(f\"No device_put handler for type: {type(x)}\") from err\ndef _device_put_array(x, device: Optional[Device]):\n@@ -151,6 +154,8 @@ def canonicalize_dtype(x):\nfor typ in typ.mro():\nhandler = canonicalize_dtype_handlers.get(typ)\nif handler: return handler(x)\n+ if hasattr(x, '__jax_array__'):\n+ return canonicalize_dtype(x.__jax_array__())\nraise TypeError(f\"No canonicalize_dtype handler for type: {type(x)}\")\ndef _canonicalize_ndarray_dtype(x):\n@@ -173,6 +178,8 @@ def abstractify(x) -> core.AbstractValue:\nfor typ in typ.mro():\naval_fn = pytype_aval_mappings.get(typ)\nif aval_fn: return aval_fn(x)\n+ if hasattr(x, '__jax_array__'):\n+ return abstractify(x.__jax_array__())\nraise TypeError(f\"Argument '{x}' of type '{type(x)}' is not a valid JAX type\")\ndef _make_abstract_python_scalar(typ, _):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2068,6 +2068,27 @@ class APITest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, \"tangent values inconsistent\"):\nf_jvp(np.ones(2, np.int32))\n+ def test_dunder_jax_array(self):\n+ # https://github.com/google/jax/pull/4725\n+\n+ class AlexArray:\n+ def __init__(self, jax_val):\n+ self.jax_val = jax_val\n+ def __jax_array__(self):\n+ return self.jax_val\n+ dtype = property(lambda self: self.jax_val.dtype)\n+ shape = property(lambda self: self.jax_val.shape)\n+\n+ x = AlexArray(jnp.array([1., 2., 3.]))\n+ y = jnp.sin(x)\n+ self.assertAllClose(y, jnp.sin(jnp.array([1., 2., 3.])))\n+ y = api.grad(api.jit(lambda x: jnp.sin(x).sum()))(x)\n+ self.assertAllClose(y, jnp.cos(jnp.array([1., 2., 3.])))\n+\n+ x = AlexArray(jnp.array([[1., 2., 3.]]))\n+ y = api.pmap(jnp.sin)(x)\n+ self.assertAllClose(y, jnp.sin(jnp.array([[1., 2., 3.]])))\n+\nclass RematTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
check for __jax_array__ method for conversion
260,335
15.12.2020 20:46:09
28,800
5eb36855e53d8d4e81e281d08dc9264d2671f21f
ensure some jnp funs duck-type with __jax_array__
[ { "change_type": "MODIFY", "old_path": "jax/dtypes.py", "new_path": "jax/dtypes.py", "diff": "@@ -280,6 +280,9 @@ def is_python_scalar(x):\ntry:\nreturn x.aval.weak_type and np.ndim(x) == 0\nexcept AttributeError:\n+ if hasattr(x, '__jax_array__'):\n+ return is_python_scalar(x.__jax_array__())\n+ else:\nreturn type(x) in python_scalar_dtypes\ndef dtype(x):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2089,6 +2089,11 @@ class APITest(jtu.JaxTestCase):\ny = api.pmap(jnp.sin)(x)\nself.assertAllClose(y, jnp.sin(jnp.array([[1., 2., 3.]])))\n+ x = jnp.array(1)\n+ a = AlexArray(x)\n+ for f in [jnp.isscalar, jnp.size, jnp.shape, jnp.dtype]:\n+ self.assertEqual(f(x), f(a))\n+\nclass RematTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
ensure some jnp funs duck-type with __jax_array__
260,631
15.12.2020 23:13:03
28,800
7c294e62f4a5134e9e747760caf5cafb62fdbb92
Copybara import of the project: by Matthew Johnson check for __jax_array__ method for conversion by Matthew Johnson fix typo by Matthew Johnson ensure some jnp funs duck-type with __jax_array__
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -437,9 +437,6 @@ def convert_element_type(operand: Array, new_dtype: DType = None,\nmsg = \"Casting complex values to real discards the imaginary part\"\nwarnings.warn(msg, np.ComplexWarning, stacklevel=2)\n- if hasattr(operand, '__jax_array__'):\n- operand = operand.__jax_array__()\n-\nif not isinstance(operand, (core.Tracer, xla.DeviceArray)):\nreturn _device_put_raw(np.asarray(operand, dtype=new_dtype),\nweak_type=new_weak_type)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -300,11 +300,9 @@ def _result_dtype(op, *args):\nreturn _dtype(op(*args))\n-def _arraylike(x):\n- return isinstance(x, ndarray) or isscalar(x) or hasattr(x, '__jax_array__')\n-\n+def _arraylike(x): return isinstance(x, ndarray) or isscalar(x)\ndef _check_arraylike(fun_name, *args):\n- \"\"\"Check if all args fit JAX's definition of arraylike.\"\"\"\n+ \"\"\"Check if all args fit JAX's definition of arraylike (ndarray or scalar).\"\"\"\nassert isinstance(fun_name, str), f\"fun_name must be a string. Got {fun_name}\"\nif _any(not _arraylike(arg) for arg in args):\npos, arg = next((i, arg) for i, arg in enumerate(args)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -859,8 +859,6 @@ def concrete_aval(x):\nfor typ in type(x).mro():\nhandler = pytype_aval_mappings.get(typ)\nif handler: return handler(x)\n- if hasattr(x, '__jax_array__'):\n- return concrete_aval(x.__jax_array__())\nraise TypeError(f\"{type(x)} is not a valid JAX type\")\n" }, { "change_type": "MODIFY", "old_path": "jax/dtypes.py", "new_path": "jax/dtypes.py", "diff": "@@ -280,9 +280,6 @@ def is_python_scalar(x):\ntry:\nreturn x.aval.weak_type and np.ndim(x) == 0\nexcept AttributeError:\n- if hasattr(x, '__jax_array__'):\n- return is_python_scalar(x.__jax_array__())\n- else:\nreturn type(x) in python_scalar_dtypes\ndef dtype(x):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -122,14 +122,11 @@ xla_result_handlers: Dict[Type[core.AbstractValue], Callable[..., Callable]] = {\n}\ndef device_put(x, device: Optional[Device] = None) -> Tuple[Any]:\n- handler = device_put_handlers.get(type(x))\n- if handler:\nx = canonicalize_dtype(x)\n- return handler(x, device)\n- elif hasattr(x, '__jax_array__'):\n- return device_put(x.__jax_array__(), device)\n- else:\n- raise TypeError(f\"No device_put handler for type: {type(x)}\")\n+ try:\n+ return device_put_handlers[type(x)](x, device)\n+ except KeyError as err:\n+ raise TypeError(f\"No device_put handler for type: {type(x)}\") from err\ndef _device_put_array(x, device: Optional[Device]):\nbackend = xb.get_device_backend(device)\n@@ -154,8 +151,6 @@ def canonicalize_dtype(x):\nfor typ in typ.mro():\nhandler = canonicalize_dtype_handlers.get(typ)\nif handler: return handler(x)\n- if hasattr(x, '__jax_array__'):\n- return canonicalize_dtype(x.__jax_array__())\nraise TypeError(f\"No canonicalize_dtype handler for type: {type(x)}\")\ndef _canonicalize_ndarray_dtype(x):\n@@ -178,8 +173,6 @@ def abstractify(x) -> core.AbstractValue:\nfor typ in typ.mro():\naval_fn = pytype_aval_mappings.get(typ)\nif aval_fn: return aval_fn(x)\n- if hasattr(x, '__jax_array__'):\n- return abstractify(x.__jax_array__())\nraise TypeError(f\"Argument '{x}' of type '{type(x)}' is not a valid JAX type\")\ndef _make_abstract_python_scalar(typ, _):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2077,32 +2077,6 @@ class APITest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, \"tangent values inconsistent\"):\nf_jvp(np.ones(2, np.int32))\n- def test_dunder_jax_array(self):\n- # https://github.com/google/jax/pull/4725\n-\n- class AlexArray:\n- def __init__(self, jax_val):\n- self.jax_val = jax_val\n- def __jax_array__(self):\n- return self.jax_val\n- dtype = property(lambda self: self.jax_val.dtype)\n- shape = property(lambda self: self.jax_val.shape)\n-\n- x = AlexArray(jnp.array([1., 2., 3.]))\n- y = jnp.sin(x)\n- self.assertAllClose(y, jnp.sin(jnp.array([1., 2., 3.])))\n- y = api.grad(api.jit(lambda x: jnp.sin(x).sum()))(x)\n- self.assertAllClose(y, jnp.cos(jnp.array([1., 2., 3.])))\n-\n- x = AlexArray(jnp.array([[1., 2., 3.]]))\n- y = api.pmap(jnp.sin)(x)\n- self.assertAllClose(y, jnp.sin(jnp.array([[1., 2., 3.]])))\n-\n- x = jnp.array(1)\n- a = AlexArray(x)\n- for f in [jnp.isscalar, jnp.size, jnp.shape, jnp.dtype]:\n- self.assertEqual(f(x), f(a))\n-\nclass RematTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Copybara import of the project: -- 7342318774c6f1195f0e238f1209425109ea8944 by Matthew Johnson <mattjj@google.com>: check for __jax_array__ method for conversion -- 6742016382b0511f5ac9ec21f67d2122a9f37cb7 by Matthew Johnson <mattjj@google.com>: fix typo -- 5eb36855e53d8d4e81e281d08dc9264d2671f21f by Matthew Johnson <mattjj@google.com>: ensure some jnp funs duck-type with __jax_array__ PiperOrigin-RevId: 347763582
260,411
16.12.2020 09:29:50
-7,200
24d850815fa3ae828b16dc15e1c10f521bd37f30
[host_callback] Remove deprecated outfeed_receiver context manager
[ { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.rst", "new_path": "docs/CHANGELOG.rst", "diff": "@@ -21,6 +21,8 @@ jax 0.2.8 (Unreleased)\noptional parameter for ``id_tap`` and ``id_print`` to request that the\ndevice from which the value is tapped be passed as a keyword argument\nto the tap function (`#5182 <https://github.com/google/jax/pull/5182>`_).\n+ * ``host_callback.outfeed_receiver`` has been removed (it is not necessary,\n+ and was deprecated a few months ago).\njax 0.2.7 (Dec 4 2020)\n----------------------\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -176,7 +176,8 @@ for the C++ outfeed `receiver backend\nbehave like INFO logs. This may be too much, but you will see which\nmodules are logging relevant info, and then you can select which modules\nto log from:\n- * `TF_CPP_VMODULE=<module_name>=3``\n+ * `TF_CPP_VMODULE=<module_name>=3`` (the module name can be either C++ or\n+ Python, without the extension).\nYou should also use the ``--verbosity=2`` flag so that you see the logs from Python.\n@@ -187,7 +188,6 @@ TF_CPP_MIN_LOG_LEVEL=0 TF_CPP_VMODULE=outfeed_receiver=3,host_callback=3,outfeed\n\"\"\"\nfrom absl import logging\nimport atexit\n-import contextlib\nimport functools\nimport itertools\n@@ -907,30 +907,6 @@ class TapFunctionException(Exception):\npass\n-@contextlib.contextmanager\n-def outfeed_receiver():\n- \"\"\"Implements a barrier after a block of code.\n-\n- DEPRECATED:\n- This function is not necessary anymore, it is here for backwards compatiblity.\n- At the moment it implements a ``barrier_wait`` after the body of the\n- context manager finishes.\n- \"\"\"\n- warnings.warn(\n- \"outfeed_receiver is unnecessary and deprecated. In the latest \"\n- \"version the outfeer receiver mechanism is started automatically. Use \"\n- \"barrier_wait if instead you want to wait for outfeeds after \"\n- \"a computation\", DeprecationWarning)\n- _initialize_outfeed_receiver()\n- # We will deprecate the outfeed_receiver context manager, but for now\n- # we just turn it into a barrier.\n- try:\n- yield\n- finally:\n- # We put a barrier, which will also raise the TapFunctionException\n- barrier_wait(\"outfeed_receiver_stop\")\n-\n-\n# For now we keep a single outfeed receiver\nclass _OutfeedReceiverData:\n\"\"\"Keep track of the outfeed receiver data.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -1353,18 +1353,6 @@ class HostCallbackTest(jtu.JaxTestCase):\n\"\"\", testing_stream.output)\ntesting_stream.reset()\n- def test_outfeed_receiver(self):\n- \"\"\"Test the deprecated outfeed_receiver\"\"\"\n- with hcb.outfeed_receiver():\n- self.assertAllClose((5. * 2.) ** 2, fun1(5.), check_dtypes=True)\n- assertMultiLineStrippedEqual(self, \"\"\"\n- what: a * 2\n- 10.00\n- what: y * 3\n- 30.00\"\"\", testing_stream.output)\n- testing_stream.reset()\n-\n-\ndef test_callback_delay(self):\nhcb.callback_extra = lambda dev: time.sleep(1)\n" } ]
Python
Apache License 2.0
google/jax
[host_callback] Remove deprecated outfeed_receiver context manager
260,335
17.12.2020 12:10:04
28,800
d7b5e3b5d493fbc21ea399c2ec9fc5acc0607aed
add add_any to jet rules table fixes
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -229,6 +229,7 @@ deflinear(lax.complex_p)\ndeflinear(lax.conj_p)\ndeflinear(lax.imag_p)\ndeflinear(lax.add_p)\n+deflinear(ad_util.add_jaxvals_p)\ndeflinear(lax.sub_p)\ndeflinear(lax.convert_element_type_p)\ndeflinear(lax.broadcast_in_dim_p)\n" }, { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -19,6 +19,7 @@ from absl.testing import absltest\nimport numpy as np\nimport unittest\n+import jax\nfrom jax import test_util as jtu\nimport jax.numpy as jnp\nimport jax.scipy.special\n@@ -379,6 +380,14 @@ class JetTest(jtu.JaxTestCase):\nassert g_out_primals == f_out_primals\nassert g_out_series == f_out_series\n+ def test_add_any(self):\n+ # https://github.com/google/jax/issues/5217\n+ f = lambda x, eps: x * eps + eps + x\n+ def g(eps):\n+ x = jnp.array(1.)\n+ return jax.grad(f)(x, eps)\n+ jet(g, (1.,), ([1.],)) # doesn't crash\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
add add_any to jet rules table fixes #5217
260,613
18.12.2020 16:26:31
0
c89f3810762458ccb56160a25dd7db653766aec9
add flag for inf checking
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -62,6 +62,9 @@ FLAGS = flags.FLAGS\nflags.DEFINE_bool('jax_debug_nans',\nbool_env('JAX_DEBUG_NANS', False),\n'Add nan checks to every operation.')\n+flags.DEFINE_bool('jax_debug_infs',\n+ bool_env('JAX_DEBUG_infs', False),\n+ 'Add inf checks to every operation.')\nflags.DEFINE_bool('jax_log_compiles',\nbool_env('JAX_LOG_COMPILES', False),\n'Print a message each time a `jit` computation is compiled.')\n@@ -350,6 +353,7 @@ def _execute_compiled_primitive(prim, compiled, result_handler, *args):\ninput_bufs = list(it.chain.from_iterable(device_put(x, device) for x in args if x is not token))\nout_bufs = compiled.execute(input_bufs)\nif FLAGS.jax_debug_nans: check_nans(prim, out_bufs)\n+ if FLAGS.jax_debug_infs: check_infs(prim, out_bufs)\nreturn result_handler(*out_bufs)\ndef _execute_replicated_primitive(prim, compiled, result_handler, *args):\n@@ -372,6 +376,18 @@ def _check_nans(name, xla_shape, buf):\nif np.any(np.isnan(buf.to_py())):\nraise FloatingPointError(f\"invalid value (nan) encountered in {name}\")\n+def check_infs(prim, bufs):\n+ for buf in bufs:\n+ # TODO(jblespiau): We can simply use buf.xla_shape() when version 0.1.58 is\n+ # the default.\n+ _check_infs(prim.name, getattr(buf, \"xla_shape\", buf.shape)(), buf)\n+\n+def _check_infs(name, xla_shape, buf):\n+ assert not xla_shape.is_tuple()\n+ if dtypes.issubdtype(xla_shape.element_type(), np.inexact):\n+ if np.any(np.isinf(buf.to_py())):\n+ raise FloatingPointError(f\"invalid value (inf) encountered in {name}\")\n+\n### compiling jaxprs\ndef prefetch(x):\n@@ -571,7 +587,7 @@ def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name, donated_inv\ntry:\nreturn compiled_fun(*args)\nexcept FloatingPointError:\n- assert FLAGS.jax_debug_nans # compiled_fun can only raise in this case\n+ assert FLAGS.jax_debug_nans or FLAGS.jax_debug_infs # compiled_fun can only raise in this case\nprint(\"Invalid value encountered in the output of a jit function. \"\n\"Calling the de-optimized version.\")\n# We want to run the wrapped function again (after _xla_callable already ran\n@@ -829,6 +845,7 @@ def _execute_compiled(compiled: XlaExecutable, avals, handlers, *args):\ninput_bufs = list(it.chain.from_iterable(device_put(x, device) for x in args if x is not token))\nout_bufs = compiled.execute(input_bufs)\nif FLAGS.jax_debug_nans: check_nans(xla_call_p, out_bufs)\n+ if FLAGS.jax_debug_infs: check_infs(xla_call_p, out_bufs)\nreturn [handler(*bs) for handler, bs in zip(handlers, _partition_outputs(avals, out_bufs))]\ndef _execute_replicated(compiled: XlaExecutable, avals, handlers, *args):\n@@ -837,6 +854,7 @@ def _execute_replicated(compiled: XlaExecutable, avals, handlers, *args):\nfor device in compiled.local_devices()]\nout_bufs = compiled.execute_on_local_devices(input_bufs)[0]\nif FLAGS.jax_debug_nans: check_nans(xla_call_p, out_bufs)\n+ if FLAGS.jax_debug_infs: check_infs(xla_call_p, out_bufs)\nreturn [handler(*bs) for handler, bs in zip(handlers, _partition_outputs(avals, out_bufs))]\ndef _execute_trivial(jaxpr, device: Optional[Device], consts, avals, handlers, *args):\n" } ]
Python
Apache License 2.0
google/jax
add flag for inf checking
260,424
17.12.2020 18:16:12
-3,600
d1cdd7756ca6cfb8bebcd3e5a902135b94a9c087
Fix UnexpectedTracer omnistaging error.
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -779,8 +779,13 @@ def full_lower(val):\nreturn val\ndef find_top_trace(xs) -> Trace:\n- top_main = max((x._trace.main for x in xs if isinstance(x, Tracer)),\n- default=None, key=attrgetter('level'))\n+ top_tracer = max((x for x in xs if isinstance(x, Tracer)),\n+ default=None, key=attrgetter('_trace.level'))\n+ if top_tracer is not None:\n+ top_tracer._assert_live()\n+ top_main = top_tracer._trace.main # type: Optional[MainTrace]\n+ else:\n+ top_main = None\ndynamic = thread_local_state.trace_state.trace_stack.dynamic\ntop_main = (dynamic if top_main is None or dynamic.level > top_main.level\nelse top_main)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1960,6 +1960,25 @@ class APITest(jtu.JaxTestCase):\n\"tracer created on line\"):\ng()\n+ def test_escaped_tracer_omnistaging_top_trace(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test is omnistaging-specific\")\n+\n+ count = 1\n+\n+ def f(_, __):\n+ nonlocal count\n+ count = jnp.add(count, 1)\n+ return None, None\n+\n+ lax.scan(f, None, None, length=2) # leaked a tracer! (of level 1!)\n+\n+ with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ \"tracer created on line\"):\n+ # The following call will try and raise the ones array to the count tracer\n+ # level, which is no longer live.\n+ jax.jit(jnp.add)(jnp.ones(()), count)\n+\ndef test_pmap_static_kwarg_error_message(self):\n# https://github.com/google/jax/issues/3007\ndef f(a, b):\n" } ]
Python
Apache License 2.0
google/jax
Fix UnexpectedTracer omnistaging error.