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,299
25.09.2019 16:19:26
-7,200
d2d0576892a5796daffbb01d288a27f6ba100b65
Ensure cache hits for gcd, lcm
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -2819,23 +2819,24 @@ hanning = _wrap_numpy_nullary_function(onp.hanning)\n# TODO: lower `kaiser` via lax to allow non-constant beta values.\nkaiser = _wrap_numpy_nullary_function(onp.kaiser)\n-\n-@_wraps(getattr(onp, \"gcd\", None))\n-def gcd(x1, x2):\n- if (not issubdtype(_dtype(x1), integer) or\n- not issubdtype(_dtype(x2), integer)):\n- raise ValueError(\"Arguments to gcd must be integers.\")\n- def cond_fn(xs):\n+def _gcd_cond_fn(xs):\nx1, x2 = xs\nreturn any(x2 != 0)\n- def body_fn(xs):\n+\n+def _gcd_body_fn(xs):\nx1, x2 = xs\nx1, x2 = (where(x2 != 0, x2, x1),\nwhere(x2 != 0, lax.rem(x1, x2), lax._const(x2, 0)))\nreturn (where(x1 < x2, x2, x1), where(x1 < x2, x1, x2))\n+\n+@_wraps(getattr(onp, \"gcd\", None))\n+def gcd(x1, x2):\n+ if (not issubdtype(_dtype(x1), integer) or\n+ not issubdtype(_dtype(x2), integer)):\n+ raise ValueError(\"Arguments to gcd must be integers.\")\nx1, x2 = _promote_dtypes(lax.abs(x1), lax.abs(x2))\nx1, x2 = broadcast_arrays(x1, x2)\n- gcd, _ = lax.while_loop(cond_fn, body_fn, (x1, x2))\n+ gcd, _ = lax.while_loop(_gcd_cond_fn, _gcd_body_fn, (x1, x2))\nreturn gcd\n" } ]
Python
Apache License 2.0
google/jax
Ensure cache hits for gcd, lcm
260,387
25.09.2019 10:30:19
14,400
3610c4aee7c08c4f917a6ccca156f4d5235e0345
Fixed typo in initial_step_size method. See the reference in the docstring for details.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ode.py", "new_path": "jax/experimental/ode.py", "diff": "@@ -124,7 +124,7 @@ def initial_step_size(fun, t0, y0, order, rtol, atol, f0):\nf1 = fun(y1, t0 + h0)\nd2 = (np.linalg.norm(f1 - f0) / scale) / h0\n- h1 = np.where(np.all(np.asarray([d0 <= 1e-15, d1 < 1e-15])),\n+ h1 = np.where(np.all(np.asarray([d1 <= 1e-15, d2 < 1e-15])),\nnp.maximum(1e-6, h0 * 1e-3),\n(0.01 / np.max(d1 + d2))**order_pow)\n" } ]
Python
Apache License 2.0
google/jax
Fixed typo in initial_step_size method. See the reference in the docstring for details.
260,299
26.09.2019 11:25:51
-7,200
b24d6cacd3c4c408cd5d19926d346e254127d92a
Ensure LU decomposition cache hits in op-by-op
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax_control_flow.py", "new_path": "jax/lax/lax_control_flow.py", "diff": "@@ -79,6 +79,20 @@ class FixedPointError(Exception): pass\n### fori_loop and while_loop\n+@cache()\n+def _make_fori_cond(upper):\n+ def while_cond_fun(loop_carry):\n+ i, _ = loop_carry\n+ return lax.lt(i, upper)\n+ return while_cond_fun\n+\n+@cache()\n+def _make_fori_body(body_fun):\n+ def while_body_fun(loop_carry):\n+ i, x = loop_carry\n+ return lax.add(i, lax._const(i, 1)), body_fun(i, x)\n+ return while_body_fun\n+\ndef fori_loop(lower, upper, body_fun, init_val):\n\"\"\"Loop from ``lower`` to ``upper`` by reduction to ``while_loop``.\n@@ -108,15 +122,8 @@ def fori_loop(lower, upper, body_fun, init_val):\nReturns:\nLoop value from the final iteration, of type ``a``.\n\"\"\"\n- def while_cond_fun(loop_carry):\n- i, _ = loop_carry\n- return lax.lt(i, upper)\n-\n- def while_body_fun(loop_carry):\n- i, x = loop_carry\n- return lax.add(i, lax._const(i, 1)), body_fun(i, x)\n-\n- _, result = while_loop(while_cond_fun, while_body_fun, (lower, init_val))\n+ _, result = while_loop(_make_fori_cond(int(upper)),\n+ _make_fori_body(body_fun), (lower, init_val))\nreturn result\n" }, { "change_type": "MODIFY", "old_path": "jax/lax_linalg.py", "new_path": "jax/lax_linalg.py", "diff": "@@ -593,6 +593,17 @@ xla.backend_specific_translations['gpu'][lu_p] = partial(\n_lu_cpu_gpu_translation_rule, cusolver.getrf)\n+# Define this outside lu_pivots_to_permutation to ensure fori_loop cache hits\n+def _lu_pivots_body_fn(i, permutation_and_swaps):\n+ permutation, swaps = permutation_and_swaps\n+ batch_dims = swaps.shape[:-1]\n+ j = swaps[..., i]\n+ iotas = np.ix_(*(lax.iota(np.int32, b) for b in batch_dims))\n+ x = permutation[..., i]\n+ y = permutation[iotas + (j,)]\n+ permutation = ops.index_update(permutation, ops.index[..., i], y)\n+ return ops.index_update(permutation, ops.index[iotas + (j,)], x), swaps\n+\ndef lu_pivots_to_permutation(swaps, m):\n\"\"\"Converts the pivots (row swaps) returned by LU to a permutation.\n@@ -609,18 +620,12 @@ def lu_pivots_to_permutation(swaps, m):\nbatch_dims = swaps.shape[:-1]\nk = swaps.shape[-1]\n- def body_fn(i, permutation):\n- j = swaps[..., i]\n- iotas = np.ix_(*(lax.iota(np.int32, b) for b in batch_dims))\n- x = permutation[..., i]\n- y = permutation[iotas + (j,)]\n- permutation = ops.index_update(permutation, ops.index[..., i], y)\n- return ops.index_update(permutation, ops.index[iotas + (j,)], x)\n-\npermutation = lax.broadcasted_iota(np.int32, batch_dims + (m,),\nlen(batch_dims))\n- return lax.fori_loop(\n- onp.array(0, onp.int32), onp.array(k, onp.int32), body_fn, permutation)\n+ result, _ = lax.fori_loop(\n+ onp.array(0, onp.int32), onp.array(k, onp.int32), _lu_pivots_body_fn,\n+ (permutation, swaps))\n+ return result\n# QR decomposition\n" } ]
Python
Apache License 2.0
google/jax
Ensure LU decomposition cache hits in op-by-op
260,299
26.09.2019 13:34:57
-7,200
806ebd4ed4bab2025b3776908119a1b466e3b962
Fix and test for fori_loop op-by-op caching
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax_control_flow.py", "new_path": "jax/lax/lax_control_flow.py", "diff": "@@ -79,18 +79,15 @@ class FixedPointError(Exception): pass\n### fori_loop and while_loop\n-@cache()\n-def _make_fori_cond(upper):\n- def while_cond_fun(loop_carry):\n- i, _ = loop_carry\n+def _fori_cond_fun(loop_carry):\n+ i, upper, _ = loop_carry\nreturn lax.lt(i, upper)\n- return while_cond_fun\n@cache()\n-def _make_fori_body(body_fun):\n+def _fori_body_fun(body_fun):\ndef while_body_fun(loop_carry):\n- i, x = loop_carry\n- return lax.add(i, lax._const(i, 1)), body_fun(i, x)\n+ i, upper, x = loop_carry\n+ return lax.add(i, lax._const(i, 1)), upper, body_fun(i, x)\nreturn while_body_fun\ndef fori_loop(lower, upper, body_fun, init_val):\n@@ -122,8 +119,8 @@ def fori_loop(lower, upper, body_fun, init_val):\nReturns:\nLoop value from the final iteration, of type ``a``.\n\"\"\"\n- _, result = while_loop(_make_fori_cond(int(upper)),\n- _make_fori_body(body_fun), (lower, init_val))\n+ _, _, result = while_loop(_fori_cond_fun, _fori_body_fun(body_fun),\n+ (lower, upper, init_val))\nreturn result\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -300,19 +300,17 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testForiLoopBasic(self):\n- def count(num):\ndef body_fun(i, tot):\nreturn lax.add(tot, i)\n- return lax.fori_loop(0, num, body_fun, 0)\n- cfun = api.jit(count)\n+ def count(num):\n+ return lax.fori_loop(0, num, body_fun, 0)\nself.assertEqual(count(2), 1)\n- self.assertEqual(count(2), cfun(2))\nself.assertEqual(count(3), 3)\n- self.assertEqual(count(3), cfun(3))\nself.assertEqual(count(4), 6)\n- self.assertEqual(count(4), cfun(4))\n+ for args_maker in [lambda: [2], lambda: [3], lambda: [4]]:\n+ self._CompileAndCheck(count, args_maker, True)\ndef testForiLoopClosure(self):\ndef count(num):\n" } ]
Python
Apache License 2.0
google/jax
Fix and test for fori_loop op-by-op caching
260,299
26.09.2019 13:39:35
-7,200
57d9fd6ab4608336403e8d98fb4639d19bfb6805
Googly indentation
[ { "change_type": "MODIFY", "old_path": "jax/lax_linalg.py", "new_path": "jax/lax_linalg.py", "diff": "@@ -622,9 +622,8 @@ def lu_pivots_to_permutation(swaps, m):\npermutation = lax.broadcasted_iota(np.int32, batch_dims + (m,),\nlen(batch_dims))\n- result, _ = lax.fori_loop(\n- onp.array(0, onp.int32), onp.array(k, onp.int32), _lu_pivots_body_fn,\n- (permutation, swaps))\n+ result, _ = lax.fori_loop(onp.array(0, onp.int32), onp.array(k, onp.int32),\n+ _lu_pivots_body_fn, (permutation, swaps))\nreturn result\n" } ]
Python
Apache License 2.0
google/jax
Googly indentation
260,389
27.09.2019 12:11:18
14,400
b82673dcdbd4472b0a531a8918f4fd1e3f6e1eef
add check_dtypes
[ { "change_type": "MODIFY", "old_path": "tests/nn_test.py", "new_path": "tests/nn_test.py", "diff": "@@ -35,4 +35,4 @@ class NNTest(jtu.JaxTestCase):\ncheck_grads(nn.softplus, (1e-8,), 4)\ndef testSoftplusValue(self):\nval = nn.softplus(89.)\n- self.assertAllClose(val, 89.)\n+ self.assertAllClose(val, 89., check_dtypes=False)\n" } ]
Python
Apache License 2.0
google/jax
add check_dtypes
260,299
01.10.2019 17:56:44
-3,600
f66aa275a62f62afb038170c486647d1248284ec
Rm duplicates from end_nodes in toposort
[ { "change_type": "MODIFY", "old_path": "jax/util.py", "new_path": "jax/util.py", "diff": "@@ -107,6 +107,7 @@ def curry(f):\ndef toposort(end_nodes):\nif not end_nodes: return []\n+ end_nodes = _remove_duplicates(end_nodes)\nchild_counts = {}\nstack = list(end_nodes)\n@@ -141,6 +142,15 @@ def check_toposort(nodes):\nassert all(id(parent) in visited for parent in node.parents)\nvisited.add(id(node))\n+def _remove_duplicates(node_list):\n+ seen = set()\n+ out = []\n+ for n in node_list:\n+ if id(n) not in seen:\n+ seen.add(id(n))\n+ out.append(n)\n+ return out\n+\ndef split_merge(predicate, xs):\nsides = list(map(predicate, xs))\nlhs = [x for x, s in zip(xs, sides) if s]\n" } ]
Python
Apache License 2.0
google/jax
Rm duplicates from end_nodes in toposort
260,280
03.10.2019 11:04:09
10,800
d21efd3cc75fa765183847546a353e6070cf711c
Fixes the parameters descriptions
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -272,6 +272,22 @@ def _wraps(fun):\n\"{summary}\\n\\nLAX-backend implementation of :func:`{fun}`. \"\n\"Original docstring below.\\n\\n{body}\".format(\nsummary=summary, fun=fun.__name__, body=body))\n+\n+ begin_idx = docstr.find(\"Parameters\")\n+ begin_idx += docstr[begin_idx:].find(\"--\\n\") + 2\n+ end_idx = docstr.find(\"Returns\")\n+\n+ parameters = docstr[begin_idx:end_idx]\n+ param_list = parameters.replace('\\n ', '@@').split('\\n')\n+\n+ for idx, p in enumerate(param_list):\n+ param, *_ = p.split(' : ')\n+ if param not in op.__code__.co_varnames:\n+ param_list[idx] = ''\n+ param_list = [param for param in param_list if param != '']\n+ parameters = '\\n'.join(param_list).replace('@@', '\\n ')\n+ docstr = docstr[:begin_idx + 1] + parameters + docstr[end_idx - 2:]\n+\nop.__name__ = fun.__name__\nop.__doc__ = docstr\nfinally:\n" } ]
Python
Apache License 2.0
google/jax
Fixes the parameters descriptions
260,646
03.10.2019 23:43:34
25,200
f20521326b39ff34c8c65d38464c39a658ab42a5
Fix typo in initial_step_size d2 calculation
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ode.py", "new_path": "jax/experimental/ode.py", "diff": "@@ -122,9 +122,9 @@ def initial_step_size(fun, t0, y0, order, rtol, atol, f0):\ny1 = y0 + h0 * f0\nf1 = fun(y1, t0 + h0)\n- d2 = (np.linalg.norm(f1 - f0) / scale) / h0\n+ d2 = np.linalg.norm((f1 - f0) / scale) / h0\n- h1 = np.where(np.all(np.asarray([d1 <= 1e-15, d2 < 1e-15])),\n+ h1 = np.where(np.all(np.asarray([d1 <= 1e-15, d2 <= 1e-15])),\nnp.maximum(1e-6, h0 * 1e-3),\n(0.01 / np.max(d1 + d2))**order_pow)\n" } ]
Python
Apache License 2.0
google/jax
Fix typo in initial_step_size d2 calculation (#1428)
260,280
04.10.2019 22:19:31
10,800
a0bb2c0ea452975be76e0ba2c6055f5be4439aa3
Add a pylintrc to make it easier to use linter
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -103,13 +103,11 @@ class _ArrayMeta(type(onp.ndarray)):\nexcept AttributeError:\nreturn isinstance(instance, _arraylike_types)\n-# pylint: disable=invalid-name\nclass ndarray(six.with_metaclass(_ArrayMeta, onp.ndarray)):\ndef __init__(shape, dtype=None, buffer=None, offset=0, strides=None,\norder=None):\nraise TypeError(\"jax.numpy.ndarray() should not be instantiated explicitly.\"\n\" Use jax.numpy.array, or jax.numpy.zeros instead.\")\n-# pylint: enable=invalid-name\nisscalar = onp.isscalar\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pylintrc", "diff": "+[MASTER]\n+\n+# A comma-separated list of package or module names from where C extensions may\n+# be loaded. Extensions are loading into the active Python interpreter and may\n+# run arbitrary code\n+extension-pkg-whitelist=numpy\n+\n+\n+[MESSAGES CONTROL]\n+\n+# Disable the message, report, category or checker with the given id(s). You\n+# can either give multiple identifiers separated by comma (,) or put this\n+# option multiple times (only on the command line, not in the configuration\n+# file where it should appear only once).You can also use \"--disable=all\" to\n+# disable everything first and then reenable specific checks. For example, if\n+# you want to run only the similarities checker, you can use \"--disable=all\n+# --enable=similarities\". If you want to run only the classes checker, but have\n+# no Warning level messages displayed, use\"--disable=all --enable=classes\n+# --disable=W\"\n+disable=missing-docstring,\n+ too-many-locals,\n+ invalid-name,\n+ redefined-outer-name,\n+ redefined-builtin,\n+ protected-name,\n+ no-else-return,\n+ fixme,\n+ protected-access,\n+ too-many-arguments,\n+ blacklisted-name,\n+ too-few-public-methods,\n+ unnecessary-lambda,\n+\n+\n+# Enable the message, report, category or checker with the given id(s). You can\n+# either give multiple identifier separated by comma (,) or put this option\n+# multiple time (only on the command line, not in the configuration file where\n+# it should appear only once). See also the \"--disable\" option for examples.\n+enable=c-extension-no-member\n+\n+\n+[FORMAT]\n+\n+# String used as indentation unit. This is usually \" \" (4 spaces) or \"\\t\" (1\n+# tab).\n+indent-string=\" \"\n\\ No newline at end of file\n" } ]
Python
Apache License 2.0
google/jax
Add a pylintrc to make it easier to use linter (#1442)
260,389
08.10.2019 10:57:36
25,200
bc0e79767b94dd5d82091cdf9402e9388a1429d6
fix XLA metadata for primitives with many args
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -19,6 +19,7 @@ from __future__ import print_function\nfrom operator import attrgetter\nfrom contextlib import contextmanager\nfrom collections import namedtuple, Counter, defaultdict\n+import itertools as it\nfrom weakref import ref\nimport threading\nimport types\n@@ -87,6 +88,25 @@ JaxprEqn = namedtuple('JaxprEqn', ['eqn_id', 'invars', 'outvars', 'primitive',\nJaxprEqn.__repr__ = JaxprEqn.__str__ = lambda eqn: str(pp_eqn(eqn))[:-1]\n+class Var(object):\n+ def __init__(self, count, suffix):\n+ self.count = count\n+ self.suffix = suffix\n+\n+ def __repr__(self):\n+ rem = self.count\n+ s = ''\n+ while True:\n+ rem, i = rem // 26, rem % 26\n+ s = chr(97 + i % 26) + s\n+ if not rem:\n+ break\n+ return s + self.suffix\n+\n+def gensym(suffix):\n+ counter = it.count()\n+ return lambda: Var(next(counter), suffix)\n+\nclass Literal(object):\n__slots__ = [\"val\", \"hash\"]\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -382,7 +382,7 @@ def eqn_tracer_to_var(var, eqn):\ndef tracers_to_jaxpr(in_tracers, out_tracers):\n- newvar = gensym('')\n+ newvar = core.gensym('')\nt_to_var = defaultdict(newvar)\nvar = lambda t: t_to_var[id(t)]\nsorted_tracers = toposort(out_tracers)\n@@ -421,25 +421,6 @@ def tracers_to_jaxpr(in_tracers, out_tracers):\nreturn jaxpr, const_vals, env_vals\n-def gensym(suffix):\n- counter = it.count()\n- return lambda: Var(next(counter), suffix)\n-\n-class Var(object):\n- def __init__(self, count, suffix):\n- self.count = count\n- self.suffix = suffix\n-\n- def __repr__(self):\n- rem = self.count\n- s = ''\n- while True:\n- rem, i = rem // 26, rem % 26\n- s = chr(97 + i % 26) + s\n- if not rem:\n- break\n- return s + self.suffix\n-\ndef eqn_parents(eqn):\nsubjaxpr_tracers = [it.chain(c, f) for _, c, f in eqn.bound_subjaxprs]\nreturn list(it.chain(eqn.invars, *subjaxpr_tracers))\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -143,11 +143,12 @@ def primitive_computation(prim, *xla_shapes, **params):\nbackend = params.get('backend', None)\nnew_params = {k: params[k] for k in params if k != 'backend'}\nc = xb.make_computation_builder(\"primitive_computation_{}\".format(prim.name))\n+ newvar = core.gensym('')\nc.SetOpMetadata(xc.OpMetadata(\nop_type=prim.name,\nop_name=str(core.new_jaxpr_eqn(\n- [chr(ord('a') + i) for i in range(len(xla_shapes))],\n- [chr(ord('a') + len(xla_shapes))],\n+ [newvar() for i in range(len(xla_shapes))],\n+ [newvar()],\nprim, (), params))\n))\nplatform = xb.get_backend(backend).platform\n" } ]
Python
Apache License 2.0
google/jax
fix XLA metadata for primitives with many args
260,389
08.10.2019 11:08:42
25,200
245d29b40d77bdb5fefcb596251f316dfcdead93
add test for the case that failed
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -72,6 +72,17 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertEqual(cloop(2), limit - 2)\nself.assertEqual(cloop(3), limit - 3)\n+ def testWhileWithManyArgs(self):\n+ nargs = 256\n+\n+ def loop_cond(state):\n+ return lax.lt(state[0], 2)\n+\n+ def loop_body(state):\n+ return tuple(lax.add(s, 1) for s in state)\n+\n+ _ = lax.while_loop(loop_cond, loop_body, (0,) * nargs)\n+\ndef testNestedWhile(self):\ndef outer_loop(num): # pylint: disable=missing-docstring\n" } ]
Python
Apache License 2.0
google/jax
add test for the case that failed
260,646
09.10.2019 15:00:27
25,200
6e55c4e7bac26778543c988f8a2de2df9b0fd326
Move variables inside functions to avoid flags errors, remove matplotlib dependency
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ode.py", "new_path": "jax/experimental/ode.py", "diff": "@@ -35,34 +35,17 @@ import jax.lax\nimport jax.numpy as np\nimport jax.ops\nfrom jax.test_util import check_vjp\n-import matplotlib.pyplot as plt\nimport numpy as onp\nimport scipy.integrate as osp_integrate\n-# Dopri5 Butcher tableaux\n-alpha = np.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0])\n-beta = np.array(\n- [[1 / 5, 0, 0, 0, 0, 0, 0],\n- [3 / 40, 9 / 40, 0, 0, 0, 0, 0],\n- [44 / 45, -56 / 15, 32 / 9, 0, 0, 0, 0],\n- [19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729, 0, 0, 0],\n- [9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656, 0, 0],\n- [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0]])\n-c_sol = np.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84,\n- 0])\n-c_error = np.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085,\n- 125 / 192 - 451 / 720, -2187 / 6784 - -12231 / 42400,\n- 11 / 84 - 649 / 6300, -1. / 60.])\n+@jax.jit\n+def interp_fit_dopri(y0, y1, k, dt):\n+ # Fit a polynomial to the results of a Runge-Kutta step.\ndps_c_mid = np.array([\n6025192743 / 30085553152 / 2, 0, 51252292925 / 65400821598 / 2,\n-2691868925 / 45128329728 / 2, 187940372067 / 1594534317056 / 2,\n-1776094331 / 19743644256 / 2, 11237099 / 235043384 / 2])\n-\n-\n-@jax.jit\n-def interp_fit_dopri(y0, y1, k, dt):\n- # Fit a polynomial to the results of a Runge-Kutta step.\ny_mid = y0 + dt * np.dot(dps_c_mid, k)\nreturn np.array(fit_4th_order_polynomial(y0, y1, y_mid, k[0], k[-1], dt))\n@@ -151,6 +134,21 @@ def runge_kutta_step(func, y0, f0, t0, dt):\ny1_error: estimated error at t1\nk: list of Runge-Kutta coefficients `k` used for calculating these terms.\n\"\"\"\n+ # Dopri5 Butcher tableaux\n+ alpha = np.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0])\n+ beta = np.array(\n+ [[1 / 5, 0, 0, 0, 0, 0, 0],\n+ [3 / 40, 9 / 40, 0, 0, 0, 0, 0],\n+ [44 / 45, -56 / 15, 32 / 9, 0, 0, 0, 0],\n+ [19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729, 0, 0, 0],\n+ [9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656, 0, 0],\n+ [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0]])\n+ c_sol = np.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84,\n+ 0])\n+ c_error = np.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085,\n+ 125 / 192 - 451 / 720, -2187 / 6784 - -12231 / 42400,\n+ 11 / 84 - 649 / 6300, -1. / 60.])\n+\ndef _fori_body_fun(i, val):\nti = t0 + dt * alpha[i-1]\nyi = y0 + dt * np.dot(beta[i-1, :], val)\n@@ -469,30 +467,6 @@ def plot_gradient_field(ax, func, xlimits, ylimits, numticks=30):\nax.set_ylim(ylimits)\n-def plot_demo():\n- \"\"\"Demo plot of simple ode integration and gradient field.\"\"\"\n- def f(y, t, arg1, arg2):\n- return y - np.sin(t) - np.cos(t) * arg1 + arg2\n-\n- t0 = 0.\n- t1 = 5.0\n- ts = np.linspace(t0, t1, 100)\n- y0 = np.array([1.])\n- fargs = (1.0, 0.0)\n-\n- ys = odeint(f, y0, ts, *fargs, atol=0.001, rtol=0.001)\n-\n- # Set up figure.\n- fig = plt.figure(figsize=(8, 6), facecolor='white')\n- ax = fig.add_subplot(111, frameon=False)\n- f_no_args = lambda y, t: f(y, t, *fargs)\n- plot_gradient_field(ax, f_no_args, xlimits=[t0, t1], ylimits=[-1.1, 1.1])\n- ax.plot(ts, ys, 'g-')\n- ax.set_xlabel('t')\n- ax.set_ylabel('y')\n- plt.show()\n-\n-\n@jax.jit\ndef pend(y, t, arg1, arg2):\n\"\"\"Simple pendulum system for odeint testing.\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
Move variables inside functions to avoid flags errors, remove matplotlib dependency (#1479)
260,280
11.10.2019 16:25:23
10,800
245f40678ed79ff958481dd87b10e03673bdeaa6
Adds dirichlet to __init__.py, making it usable
[ { "change_type": "MODIFY", "old_path": "jax/scipy/stats/__init__.py", "new_path": "jax/scipy/stats/__init__.py", "diff": "@@ -16,6 +16,7 @@ from __future__ import absolute_import\nfrom . import bernoulli\nfrom . import beta\nfrom . import cauchy\n+from . import dirichlet\nfrom . import expon\nfrom . import gamma\nfrom . import laplace\n" } ]
Python
Apache License 2.0
google/jax
Adds dirichlet to __init__.py, making it usable
260,411
13.10.2019 09:34:51
-7,200
858a411982f64ec021785669d28054d67058adc9
Add a separate build matrix entry for documentation testing. * Add a separate build matrix entry for documentation testing. This way we parallelize the unit tests with the documentation tests.
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -9,6 +9,11 @@ python:\nenv:\n- JAX_ENABLE_X64=0 JAX_NUM_GENERATED_CASES=25\n- JAX_ENABLE_X64=1 JAX_NUM_GENERATED_CASES=25\n+matrix:\n+ include:\n+ - python: \"3.7\"\n+ env: JAX_ENABLE_X64=1 JAX_ONLY_DOCUMENTATION=true\n+\nbefore_install:\n- if [[ \"$TRAVIS_PYTHON_VERSION\" == \"2.7\" ]]; then\nwget https://repo.continuum.io/miniconda/Miniconda2-latest-Linux-x86_64.sh -O miniconda.sh;\n@@ -24,10 +29,13 @@ install:\n- pip install jaxlib\n- pip install -v .\n# The following are needed to test the Colab notebooks and the documentation building\n- - conda install --yes -c conda-forge pandoc ipykernel\n- - conda install --yes sphinx sphinx_rtd_theme nbsphinx jupyter_client matplotlib\n+ - if [[ \"$JAX_ONLY_DOCUMENTATION\" != \"\" ]]; then\n+ conda install --yes -c conda-forge pandoc ipykernel;\n+ conda install --yes sphinx sphinx_rtd_theme nbsphinx jupyter_client matplotlib;\n+ fi\nscript:\n- - pytest -n 1 tests examples -W ignore\n- - if [[ \"$TRAVIS_PYTHON_VERSION\" > \"3\" ]]; then\n- sphinx-build -M html docs build;\n+ - if [[ \"$JAX_ONLY_DOCUMENTATION\" == \"\" ]]; then\n+ pytest -n 1 tests examples -W ignore ;\n+ else\n+ sphinx-build -b html -D nbsphinx_execute=always docs docs/build/html;\nfi\n" } ]
Python
Apache License 2.0
google/jax
Add a separate build matrix entry for documentation testing. (#1495) * Add a separate build matrix entry for documentation testing. This way we parallelize the unit tests with the documentation tests.
260,280
13.10.2019 20:30:32
10,800
d6bc62bd6b56d2c37f77807c45475bd1821a95f1
Fixes Readme links to notebooks
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -37,7 +37,7 @@ are instances of such transformations. Another is [`vmap`](#auto-vectorization-w\nfor automatic vectorization, with more to come.\nThis is a research project, not an official Google product. Expect bugs and\n-[sharp edges](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb).\n+[sharp edges](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Common_Gotchas_in_JAX.ipynb).\nPlease help by trying it out, [reporting\nbugs](https://github.com/google/jax/issues), and letting us know what you\nthink!\n@@ -232,7 +232,7 @@ print(\"Trained loss: {:0.2f}\".format(loss(weights, inputs, targets)))\n```\nTo see more, check out the [quickstart\n-notebook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/quickstart.ipynb),\n+notebook](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/quickstart.ipynb),\na [simple MNIST classifier\nexample](https://github.com/google/jax/blob/master/examples/mnist_classifier.py)\nand the rest of the [JAX\n@@ -680,13 +680,13 @@ code to compile and end-to-end optimize much bigger functions.\n## Current gotchas\nFor a survey of current gotchas, with examples and explanations, we highly\n-recommend reading the [Gotchas Notebook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb).\n+recommend reading the [Gotchas Notebook](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Common_Gotchas_in_JAX.ipynb).\nSome stand-out gotchas that might surprise NumPy users:\n1. JAX enforces single-precision (32-bit, e.g. `float32`) values by default, and\nto enable double-precision (64-bit, e.g. `float64`) one needs to set the\n`jax_enable_x64` variable **at startup** (or set the environment variable\n- `JAX_ENABLE_X64=True`, see [the Gotchas Notebook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb#scrollTo=YTktlwTTMgFl))\n+ `JAX_ENABLE_X64=True`, see [the Gotchas Notebook](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Common_Gotchas_in_JAX.ipynb#scrollTo=YTktlwTTMgFl))\n2. Some of NumPy's dtype promotion semantics involving a mix of Python scalars\nand NumPy types aren't preserved, namely `np.add(1, np.array([2],\nnp.float32)).dtype` is `float64` rather than `float32`.\n@@ -697,7 +697,7 @@ Some stand-out gotchas that might surprise NumPy users:\nreasons](https://github.com/google/jax/blob/master/design_notes/prng.md), and\nnon-reuse (linearity) is not yet checked.\n-See [the notebook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb) for much more information.\n+See [the notebook](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Common_Gotchas_in_JAX.ipynb) for much more information.\n## Citing JAX\n" } ]
Python
Apache License 2.0
google/jax
Fixes Readme links to notebooks
260,335
15.10.2019 23:07:31
0
0eea9885026b7e18b07a4bd8488e32f8805741aa
try following jupyterlab/jupyter-renderers#212 to fix travis
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -22,8 +22,12 @@ before_install:\nfi\n- bash miniconda.sh -b -p $HOME/miniconda\n- export PATH=\"$HOME/miniconda/bin:$PATH\"\n- - conda update --yes conda\n+ - conda config --set always_yes yes --set changeps1 no --set show_channel_urls yes\n+ - conda config --set channel_priority strict\n+ - conda config --set add_pip_as_python_dependency yes\n+ - conda config --remove channels defaults\n- conda config --add channels conda-forge\n+ - conda update -q conda\ninstall:\n- conda install --yes python=$TRAVIS_PYTHON_VERSION pip six protobuf>=3.6.0 absl-py opt_einsum numpy scipy pytest-xdist fastcache\n- pip install jaxlib\n" } ]
Python
Apache License 2.0
google/jax
try following jupyterlab/jupyter-renderers#212 to fix travis
260,335
15.10.2019 23:49:15
0
585cefc8c014f1b04bfd1523db017f6592384910
document pmap with pytrees, fixes
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -652,7 +652,7 @@ def pmap(fun, axis_name=None, devices=None, backend=None):\ndevices available, as returned by ``jax.local_device_count()`` (unless\n``devices`` is specified, see below). For nested ``pmap`` calls, the product\nof the mapped axis sizes must be less than or equal to the number of XLA\n- devices. TODO(skye): support < # local devices on multi-host platforms\n+ devices.\n**Multi-host platforms:** On multi-host platforms such as TPU pods, ``pmap``\nis designed to be used in SPMD Python programs, where every host is running\n@@ -667,7 +667,9 @@ def pmap(fun, axis_name=None, devices=None, backend=None):\n\"sees\" only its local shard of the input and output.\nArgs:\n- fun: Function to be mapped over argument axes.\n+ fun: Function to be mapped over argument axes. Its arguments and return\n+ value should be arrays, scalars, or (nested) standard Python containers\n+ (tuple/list/dict) thereof.\naxis_name: Optional, a hashable Python object used to identify the mapped\naxis so that parallel collectives can be applied.\ndevices: This is an experimental feature and the API is likely to change.\n" } ]
Python
Apache License 2.0
google/jax
document pmap with pytrees, fixes #1486
260,335
15.10.2019 22:55:35
0
2f858bded88bc187a9a8f47b234572ae2ce3be56
handle complex dtypes in psum fixes
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax_parallel.py", "new_path": "jax/lax/lax_parallel.py", "diff": "@@ -193,11 +193,20 @@ def _allreduce_translation_rule(prim, c, val, replica_groups, backend=None):\ncomputation = xla.primitive_computation(prim, scalar, scalar, backend=backend)\nreturn c.AllReduce(val, computation, replica_groups=replica_groups)\n+# psum translation rule has special handling for complex dtypes\n+def _psum_translation_rule(c, val, replica_groups, backend=None):\n+ psum = partial(_allreduce_translation_rule, lax.add_p, c,\n+ replica_groups=replica_groups, backend=backend)\n+ dtype = c.GetShape(val).numpy_dtype()\n+ if onp.issubdtype(dtype, onp.complexfloating):\n+ return c.Complex(psum(c.Real(val)), psum(c.Imag(val)))\n+ else:\n+ return psum(val)\n+\npsum_p = standard_pmap_primitive('psum')\npxla.split_axis_rules[psum_p] = \\\npartial(_allreduce_split_axis_rule, psum_p, lax._reduce_sum)\n-xla.parallel_translations[psum_p] = \\\n- partial(_allreduce_translation_rule, lax.add_p)\n+xla.parallel_translations[psum_p] = _psum_translation_rule\npxla.parallel_pure_rules[psum_p] = lambda x, shape: x * prod(shape)\nad.deflinear(psum_p, lambda t, axis_name: [t])\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -66,6 +66,17 @@ class PmapTest(jtu.JaxTestCase):\nans = f(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testComplexPsum(self):\n+ f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i')\n+\n+ shape = (xla_bridge.device_count(), 4 * 2)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape).view(onp.complex64)\n+ expected = x - onp.sum(x, 0)\n+\n+ ans = f(x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+\ndef testNestedBasic(self):\nf = lambda x: lax.psum(lax.psum(x, 'i'), 'j')\nf = pmap(pmap(f, 'i'), 'j')\n" } ]
Python
Apache License 2.0
google/jax
handle complex dtypes in psum fixes #1409
260,335
17.10.2019 22:38:28
0
cc137ced4d89f64f346de207d69ef3ea08f93644
broadcast arguments in take_along_axis, fixes
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -2411,6 +2411,7 @@ def _take_along_axis(arr, indices, axis):\nif rank != ndim(indices):\nmsg = \"indices and arr must have the same number of dimensions; {} vs. {}\"\nraise ValueError(msg.format(ndim(indices), ndim(arr)))\n+ arr, indices = broadcast_arrays(arr, indices)\naxis = _canonicalize_axis(axis, rank)\narr_shape = list(shape(arr))\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1985,6 +1985,16 @@ class NumpyGradTests(jtu.JaxTestCase):\ndef testOpGradSpecialValue(self, op, special_value):\ncheck_grads(op, (special_value,), 2, [\"fwd\", \"rev\"])\n+ def testTakeAlongAxisIssue1521(self):\n+ # https://github.com/google/jax/issues/1521\n+ idx = lnp.repeat(lnp.arange(3), 10).reshape((30, 1))\n+\n+ def f(x):\n+ y = x * lnp.arange(3.).reshape((1, 3))\n+ return lnp.take_along_axis(y, idx, -1).sum()\n+\n+ check_grads(f, (1.,), order=1)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -2216,19 +2216,6 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nx = rng(shape, dtype)\ncheck_grads(gather, (x,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1.)\n- def testGatherGradIssue1521(self):\n- gather_indices = onp.array([[[0, 0]],\n- [[1, 1]]], onp.int32)\n- dnums = lax.GatherDimensionNumbers(offset_dims=(),\n- collapsed_slice_dims=(0, 1),\n- start_index_map=(0, 1))\n- slice_sizes = (1, 1)\n-\n- def f(x):\n- return lax.gather(x, gather_indices, dnums, tuple(slice_sizes))\n- x = onp.array([[0., 1.]])\n- check_grads(f, (x,), 1, [\"rev\"])\n-\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_idxs={}_update={}_dnums={}\".format(\njtu.format_shape_dtype_string(arg_shape, dtype),\n" } ]
Python
Apache License 2.0
google/jax
broadcast arguments in take_along_axis, fixes #1521
260,335
17.10.2019 23:23:08
0
aa0692d30774c1fb4cc5cd6e706703b3c835bbec
improve broadcast_to, add error checks (fixes
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -889,23 +889,20 @@ def broadcast_arrays(*args):\ndef broadcast_to(arr, shape):\n\"\"\"Like Numpy's broadcast_to but doesn't necessarily return views.\"\"\"\narr = arr if isinstance(arr, ndarray) or isscalar(arr) else array(arr)\n- shape = tuple(map(int, shape))\n- if _shape(arr) != shape:\n- # TODO(mattjj): revise this to call lax.broadcast_in_dim rather than\n- # lax.broadcast and lax.transpose\n- lax.broadcast_shapes(shape, _shape(arr)) # error checking\n- nlead = len(shape) - len(_shape(arr))\n- diff, = onp.where(onp.not_equal(shape[nlead:], _shape(arr)))\n-\n+ shape = tuple(map(int, shape)) # check that shape is concrete\n+ arr_shape = _shape(arr)\n+ if arr_shape == shape:\n+ return arr\n+ else:\n+ nlead = len(shape) - len(arr_shape)\n+ compatible = onp.equal(arr_shape, shape[nlead:]) | onp.equal(arr_shape, 1)\n+ if nlead < 0 or not onp.all(compatible):\n+ msg = \"Incompatible shapes for broadcasting: {} and requested shape {}\"\n+ raise ValueError(msg.format(arr_shape, shape))\n+ diff, = onp.where(onp.not_equal(shape[nlead:], arr_shape))\nnew_dims = tuple(range(nlead)) + tuple(nlead + diff)\nkept_dims = tuple(onp.delete(onp.arange(len(shape)), new_dims))\n- perm = onp.argsort(new_dims + kept_dims)\n-\n- broadcast_dims = onp.take(shape, new_dims)\n- squeezed_array = squeeze(arr, diff)\n- return lax.transpose(lax.broadcast(squeezed_array, broadcast_dims), perm)\n- else:\n- return arr\n+ return lax.broadcast_in_dim(squeeze(arr, diff), shape, kept_dims)\n@_wraps(onp.split)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1230,7 +1230,6 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nf(arr)\n-\ndef testNonArrayErrorMessage(self):\nx = [1., 2.]\ny = onp.array([3., 4.])\n@@ -1931,6 +1930,27 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nany(onp.array_equal(x, onp.full((3, 4), 2., dtype=onp.float32))\nfor x in consts))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_from={}_to={}\".format(from_shape, to_shape),\n+ \"rng\": rng, \"from_shape\": from_shape, \"to_shape\": to_shape}\n+ for from_shape, to_shape in [\n+ [(1, 3), (4, 3)],\n+ [(3,), (2, 1, 3)],\n+ [(3,), (3, 3)],\n+ [(1,), (3,)],\n+ ]\n+ for rng in [jtu.rand_default()])\n+ def testBroadcastTo(self, from_shape, to_shape, rng):\n+ args_maker = self._GetArgsMaker(rng, [from_shape], [onp.float32])\n+ onp_op = lambda x: onp.broadcast_to(x, to_shape)\n+ lnp_op = lambda x: lnp.broadcast_to(x, to_shape)\n+ self._CheckAgainstNumpy(onp_op, lnp_op, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(lnp_op, args_maker, check_dtypes=True)\n+\n+ def testBroadcastToIssue1522(self):\n+ self.assertRaisesRegex(\n+ ValueError, \"Incompatible shapes for broadcasting: .*\",\n+ lambda: lnp.broadcast_to(onp.ones((2, 3)), (1, 3)))\n# Most grad tests are at the lax level (see lax_test.py), but we add some here\n# as needed for e.g. particular compound ops of interest.\n" } ]
Python
Apache License 2.0
google/jax
improve broadcast_to, add error checks (fixes #1522)
260,622
17.10.2019 16:00:35
25,200
1090e89a86147a5ce326db68149677027b9bb0ef
sign missing from loss function definition
[ { "change_type": "MODIFY", "old_path": "examples/resnet50.py", "new_path": "examples/resnet50.py", "diff": "@@ -101,7 +101,7 @@ if __name__ == \"__main__\":\ndef loss(params, batch):\ninputs, targets = batch\nlogits = predict_fun(params, inputs)\n- return np.sum(logits * targets)\n+ return -np.sum(logits * targets)\ndef accuracy(params, batch):\ninputs, targets = batch\n" } ]
Python
Apache License 2.0
google/jax
- sign missing from loss function definition
260,335
18.10.2019 22:50:24
0
a0352f3969955b2dae0f0151506c4fe594ba1718
fix up broadcasting in take_along_axis
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -2405,20 +2405,27 @@ def _take_along_axis(arr, indices, axis):\nif axis is None:\nif ndim(indices) != 1:\nmsg = \"take_along_axis indices must be 1D if axis=None, got shape {}\"\n- raise ValueError(msg.format(shape(indices)))\n+ raise ValueError(msg.format(indices.shape))\nreturn take_along_axis(arr.ravel(), indices, 0)\nrank = ndim(arr)\nif rank != ndim(indices):\nmsg = \"indices and arr must have the same number of dimensions; {} vs. {}\"\nraise ValueError(msg.format(ndim(indices), ndim(arr)))\n- arr, indices = broadcast_arrays(arr, indices)\naxis = _canonicalize_axis(axis, rank)\n- arr_shape = list(shape(arr))\n- axis_size = arr_shape[axis]\n- arr_shape[axis] = 1\n- idx_shape = shape(indices)\n- out_shape = lax.broadcast_shapes(idx_shape, tuple(arr_shape))\n+ def replace(tup, val):\n+ lst = list(tup)\n+ lst[axis] = val\n+ return tuple(lst)\n+\n+ bcast_shape = lax.broadcast_shapes(replace(arr.shape, 1), replace(indices.shape, 1))\n+ indices = broadcast_to(indices, replace(bcast_shape, indices.shape[axis]))\n+ arr = broadcast_to(arr, replace(bcast_shape, arr.shape[axis]))\n+\n+ axis_size = arr.shape[axis]\n+ arr_shape = replace(arr.shape, 1)\n+ idx_shape = indices.shape\n+ out_shape = lax.broadcast_shapes(idx_shape, arr_shape)\nindex_dims = [i for i, idx in enumerate(idx_shape) if i == axis or idx != 1]\n" } ]
Python
Apache License 2.0
google/jax
fix up broadcasting in take_along_axis
260,335
16.10.2019 01:35:39
0
8a132b41093018e818bfa63b836c573029731f8a
try simplifying random.multivariate_normal api
[ { "change_type": "MODIFY", "old_path": "jax/random.py", "new_path": "jax/random.py", "diff": "@@ -419,41 +419,37 @@ def _normal(key, shape, dtype):\nreturn onp.array(onp.sqrt(2), dtype) * lax.erf_inv(u)\n-def multivariate_normal(key, mean=0.0, cov=1.0, shape=(), dtype=onp.float64):\n+def multivariate_normal(key, mean, cov, dtype=onp.float64):\n+ if onp.ndim(mean) != 1:\n+ msg = \"multivariate_normal requires mean.ndim == 1, got mean.ndim == {}\"\n+ raise ValueError(msg.format(onp.ndim(mean)))\n+ n, = onp.shape(mean)\n+ if onp.shape(cov) != (n, n):\n+ msg = (\"multivariate_normal requires cov.shape == (n, n) == ({n}, {n}) for \"\n+ \"mean.shape == (n,) == ({n},), but got cov.shape == {shape}.\")\n+ raise ValueError(msg.format(n=n, shape=onp.shape(cov)))\n+\ndtype = xla_bridge.canonicalize_dtype(dtype)\n- return _multivariate_normal(key, mean, cov, shape, dtype)\n+ return _multivariate_normal(key, mean, cov, dtype)\n-@partial(jit, static_argnums=(3, 4))\n-def _multivariate_normal(key, mean, cov, shape, dtype):\n- \"\"\"Sample multivariate normal random values with given shape, mean, and covariance.\n+@partial(jit, static_argnums=(3,))\n+def _multivariate_normal(key, mean, cov, dtype):\n+ \"\"\"Sample multivariate normal random values with given mean and covariance.\nArgs:\nkey: a PRNGKey used as the random key.\n- mean: optional, a scalar or array of mean values along each dimension\n- cov: optional, a scalar (isotropic), vector (diagonal covariance matrix), or full covariance matrix\n- shape: optional, a tuple of nonnegative integers representing the shape.\n+ mean: a mean vector of shape (n,).\n+ cov: a positive definite covariance matrix of shape (n, n).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\n- A random array with latent dimension of (max(asarray(mean).ndim, asarray(cov).ndim)),)\n+ A random vector of shape (n,) and the specified dtype.\n\"\"\"\n- _check_shape(\"multivariate_normal\", shape)\n- if hasattr(mean, \"shape\") and mean.ndim > 1:\n- raise ValueError(\"Mean cannot have more than 1 dimension.\")\n- if hasattr(cov, \"shape\") and cov.ndim > 0:\n- if cov.ndim > 2:\n- raise ValueError(\"Covariance matrix cannot have more than 2 dimensions.\")\n- shape = shape + cov.shape[:1]\n- normal_samples = normal(key, shape, dtype)\n- if cov.ndim == 2:\n- samples = np.tensordot(normal_samples, cholesky(cov), axes=1)\n- else:\n- samples = normal_samples * np.sqrt(cov)\n- else:\n- if hasattr(mean, \"shape\") and mean.ndim > 0:\n- shape = shape + mean.shape[:1]\n- normal_samples = normal(key, shape, dtype)\n- samples = np.sqrt(cov) * normal_samples\n- return samples + mean\n+ n, = mean.shape\n+ chol_factor = cholesky(cov)\n+ normal_samples = normal(key, (n,), dtype)\n+ return lax.dot(chol_factor, normal_samples) + mean\ndef truncated_normal(key, lower, upper, shape=(), dtype=onp.float64):\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -16,8 +16,8 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n+from functools import partial\nfrom unittest import SkipTest\n-import re\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -367,35 +367,32 @@ class LaxRandomTest(jtu.JaxTestCase):\nself._CheckKolmogorovSmirnovCDF(samples, scipy.stats.t(df).cdf)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_mean={}_cov={}_{}\".format(mean, cov, dtype),\n- \"mean\": mean, \"cov\": cov, \"dtype\": dtype}\n- for mean in [0, 5, np.asarray([1, -2, 3]), np.asarray([[1]])]\n- for cov in [.1, 5, np.asarray([4, 5, 6]),\n- np.asarray([[4.60, 2.86, 2.33],\n- [2.86, 3.04, 1.74],\n- [2.33, 1.74, 1.83]]),\n- np.asarray([[[1]]])]\n+ {\"testcase_name\": \"_{}D_{}\".format(dim, onp.dtype(dtype).name),\n+ \"dim\": dim, \"dtype\": dtype}\n+ for dim in [1, 3, 5]\nfor dtype in [onp.float32, onp.float64]))\n- def testMultivariateNormal(self, mean, cov, dtype):\n- key = random.PRNGKey(0)\n- rand = lambda key, mean, cov: random.multivariate_normal(key, mean, cov, (1000,), dtype)\n+ def testMultivariateNormal(self, dim, dtype):\n+ r = onp.random.RandomState(dim)\n+ mean = r.randn(dim)\n+ cov_factor = r.randn(dim, dim)\n+ cov = onp.dot(cov_factor, cov_factor.T) + dim * onp.eye(dim)\n+\n+ keys = random.split(random.PRNGKey(0), 1000)\n+ rand = api.vmap(partial(random.multivariate_normal, mean=mean, cov=cov))\ncrand = api.jit(rand)\n- if hasattr(cov, \"shape\") and cov.ndim > 2 or hasattr(mean, \"shape\") and mean.ndim > 1:\n- self.assertRaises(ValueError, lambda: rand(key, mean, cov))\n- self.assertRaises(ValueError, lambda: crand(key, mean, cov))\n- return\n-\n- uncompiled_samples = rand(key, mean, cov)\n- compiled_samples = crand(key, mean, cov)\n- if hasattr(cov, \"shape\") and cov.ndim == 2:\n+\n+ uncompiled_samples = rand(keys)\n+ compiled_samples = crand(keys)\n+\n+ # This is a quick-and-dirty multivariate normality check that tests that a\n+ # uniform mixture of the marginals along the covariance matrix's\n+ # eigenvectors follow a standard normal distribution.\n+ # TODO(mattjj); check for correlations, maybe use a more sophisticated test.\ninv_scale = scipy.linalg.lapack.dtrtri(onp.linalg.cholesky(cov), lower=True)[0]\n- rescale = lambda x: onp.tensordot(x, inv_scale, axes=(-1, 1))\n- else:\n- rescale = lambda x: x / np.sqrt(cov)\nfor samples in [uncompiled_samples, compiled_samples]:\n- self._CheckKolmogorovSmirnovCDF(\n- rescale(samples - mean).reshape(-1),\n- scipy.stats.norm().cdf)\n+ centered = samples - mean\n+ whitened = onp.einsum('nj,ij->ni', centered, inv_scale)\n+ self._CheckKolmogorovSmirnovCDF(whitened.ravel(), scipy.stats.norm().cdf)\ndef testIssue222(self):\nx = random.randint(random.PRNGKey(10003), (), 0, 0)\n@@ -417,7 +414,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nphi = lambda x, t: np.sqrt(2.0 / d) * np.cos(np.matmul(W, x) + w*t + b)\nreturn phi\n- self.assertRaisesRegex(ValueError, re.compile(r'.*requires a concrete.*'),\n+ self.assertRaisesRegex(ValueError, '.*requires a concrete.*',\nlambda: feature_map(5, 3))\ndef testIssue756(self):\n" } ]
Python
Apache License 2.0
google/jax
try simplifying random.multivariate_normal api
260,335
17.10.2019 20:36:51
0
ab6ac6c876968bc6b4a9b76ead4c8289ff733250
standardize shape handling in jax.random
[ { "change_type": "MODIFY", "old_path": "jax/random.py", "new_path": "jax/random.py", "diff": "@@ -240,12 +240,19 @@ def _random_bits(key, bit_width, shape):\n### random samplers\n-def _check_shape(name, shape):\n+def _check_shape(name, shape, *param_shapes):\ntry:\nshape = tuple(map(int, shape))\nexcept TypeError:\nmsg = \"{} requires a concrete tuple of integers as shape argument, got {}.\"\nraise ValueError(msg.format(name, shape))\n+ if param_shapes:\n+ shape_ = lax.broadcast_shapes(shape, *param_shapes)\n+ if shape != shape_:\n+ msg = (\"{} parameter shapes must be broadcast-compatible with shape \"\n+ \"argument, and the result of broadcasting the shapes must equal \"\n+ \"the shape argument, but got result {} for shape argument {}.\")\n+ raise ValueError(msg.format(name, shape_, shape))\ndef uniform(key, shape=(), dtype=onp.float64, minval=0., maxval=1.):\n@@ -253,7 +260,8 @@ def uniform(key, shape=(), dtype=onp.float64, minval=0., maxval=1.):\nArgs:\nkey: a PRNGKey used as the random key.\n- shape: a tuple of nonnegative integers representing the shape.\n+ shape: optional, a tuple of nonnegative integers representing the result\n+ shape. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nminval: optional, a minimum (inclusive) value for the range (default 0).\n@@ -315,7 +323,7 @@ def randint(key, shape, minval, maxval, dtype=onp.int64):\n@partial(jit, static_argnums=(1, 4))\ndef _randint(key, shape, minval, maxval, dtype):\n- _check_shape(\"randint\", shape)\n+ _check_shape(\"randint\", shape, minval.shape, maxval.shape)\nif not onp.issubdtype(dtype, onp.integer):\nraise TypeError(\"randint only accepts integer dtypes.\")\n@@ -400,7 +408,8 @@ def normal(key, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- shape: a tuple of nonnegative integers representing the shape.\n+ shape: optional, a tuple of nonnegative integers representing the result\n+ shape. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -419,37 +428,46 @@ def _normal(key, shape, dtype):\nreturn onp.array(onp.sqrt(2), dtype) * lax.erf_inv(u)\n-def multivariate_normal(key, mean, cov, dtype=onp.float64):\n- if onp.ndim(mean) != 1:\n- msg = \"multivariate_normal requires mean.ndim == 1, got mean.ndim == {}\"\n- raise ValueError(msg.format(onp.ndim(mean)))\n- n, = onp.shape(mean)\n- if onp.shape(cov) != (n, n):\n- msg = (\"multivariate_normal requires cov.shape == (n, n) == ({n}, {n}) for \"\n- \"mean.shape == (n,) == ({n},), but got cov.shape == {shape}.\")\n- raise ValueError(msg.format(n=n, shape=onp.shape(cov)))\n-\n- dtype = xla_bridge.canonicalize_dtype(dtype)\n- return _multivariate_normal(key, mean, cov, dtype)\n-\n-@partial(jit, static_argnums=(3,))\n-def _multivariate_normal(key, mean, cov, dtype):\n+def multivariate_normal(key, mean, cov, shape=(), dtype=onp.float64):\n\"\"\"Sample multivariate normal random values with given mean and covariance.\nArgs:\nkey: a PRNGKey used as the random key.\n- mean: a mean vector of shape (n,).\n- cov: a positive definite covariance matrix of shape (n, n).\n+ mean: a mean vector of shape ``(..., n)``.\n+ cov: a positive definite covariance matrix of shape ``(..., n, n)``. The\n+ shape prefix ``...`` must be broadcast-compatible with that of ``mean``.\n+ shape: optional, a tuple of nonnegative integers specifying the result\n+ batch shape; that is, the prefix of the result shape excluding the last\n+ element of value ``n``. Must be broadcast-compatible with\n+ ``mean.shape[:-1]`` and ``cov.shape[:-2]``. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nReturns:\n- A random vector of shape (n,) and the specified dtype.\n+ A random array with the specified dtype and shape given by\n+ ``shape + (mean.shape[-1],)``.\n\"\"\"\n- n, = mean.shape\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\n+ return _multivariate_normal(key, mean, cov, shape, dtype)\n+\n+@partial(jit, static_argnums=(3, 4))\n+def _multivariate_normal(key, mean, cov, shape, dtype):\n+ if not onp.ndim(mean) >= 1:\n+ msg = \"multivariate_normal requires mean.ndim >= 1, got mean.ndim == {}\"\n+ raise ValueError(msg.format(onp.ndim(mean)))\n+ if not onp.ndim(cov) >= 2:\n+ msg = \"multivariate_normal requires cov.ndim >= 2, got cov.ndim == {}\"\n+ raise ValueError(msg.format(onp.ndim(cov)))\n+ n = mean.shape[-1]\n+ if onp.shape(cov)[-2:] != (n, n):\n+ msg = (\"multivariate_normal requires cov.shape == (..., n, n) for n={n}, \"\n+ \"but got cov.shape == {shape}.\")\n+ raise ValueError(msg.format(n=n, shape=onp.shape(cov)))\n+\n+ _check_shape(\"normal\", shape, mean.shape[:-1], mean.shape[:-2])\nchol_factor = cholesky(cov)\n- normal_samples = normal(key, (n,), dtype)\n- return lax.dot(chol_factor, normal_samples) + mean\n+ normal_samples = normal(key, shape + mean.shape[-1:], dtype)\n+ return mean + np.tensordot(normal_samples, chol_factor, [-1, 1])\ndef truncated_normal(key, lower, upper, shape=(), dtype=onp.float64):\n@@ -457,9 +475,12 @@ def truncated_normal(key, lower, upper, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- lower: a floating-point lower bound for truncation.\n- upper: a floating-point upper bound for truncation.\n- shape: a tuple of nonnegative integers representing the shape.\n+ lower: a float or array of lower bound for truncation. Must be\n+ broadcast-compatible with `upper`.\n+ upper: a floating-point upper bound for truncation. Must be\n+ broadcast-compatible with `lower`.\n+ shape: optional, a tuple of nonnegative integers specifying the result\n+ shape. Must be broadcast-compatible with `lower` and `upper`. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -471,7 +492,7 @@ def truncated_normal(key, lower, upper, shape=(), dtype=onp.float64):\n@partial(jit, static_argnums=(3, 4))\ndef _truncated_normal(key, lower, upper, shape, dtype):\n- _check_shape(\"truncated_normal\", shape)\n+ _check_shape(\"truncated_normal\", shape, lower.shape, upper.shape)\nsqrt2 = onp.array(onp.sqrt(2), dtype)\na = lax.erf(lax.convert_element_type(lower, dtype) / sqrt2)\nb = lax.erf(lax.convert_element_type(upper, dtype) / sqrt2)\n@@ -486,10 +507,10 @@ def bernoulli(key, p=onp.float32(0.5), shape=()):\nArgs:\nkey: a PRNGKey used as the random key.\n- p: optional, an array-like of floating dtype broadcastable to `shape` for\n- the mean of the random variables (default 0.5).\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ p: optional, a float or array of floats for the mean of the random\n+ variables. Must be broadcast-compatible with ``shape``. Default 0.5.\n+ shape: optional, a tuple of nonnegative integers representing the shape.\n+ Default ().\nReturns:\nA random array with the specified shape and boolean dtype.\n@@ -503,11 +524,8 @@ def bernoulli(key, p=onp.float32(0.5), shape=()):\n@partial(jit, static_argnums=(2,))\ndef _bernoulli(key, p, shape):\n- _check_shape(\"bernoulli\", shape)\n- shape = shape or onp.shape(p)\n- if onp.shape(p) != shape:\n- p = np.broadcast_to(p, shape)\n- return lax.lt(uniform(key, shape, lax.dtype(p)), p)\n+ _check_shape(\"bernoulli\", shape, p.shape)\n+ return uniform(key, shape, lax.dtype(p)) < p\ndef beta(key, a, b, shape=(), dtype=onp.float64):\n@@ -515,12 +533,12 @@ def beta(key, a, b, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- a: an array-like broadcastable to `shape` and used as the shape parameter\n- alpha of the random variables.\n- b: an array-like broadcastable to `shape` and used as the shape parameter\n- beta of the random variables.\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ a: a float or array of floats broadcast-compatible with ``shape``\n+ representing the first parameter \"alpha\".\n+ b: a float or array of floats broadcast-compatible with ``shape``\n+ representing the second parameter \"beta\".\n+ shape: optional, a tuple of nonnegative integers specifying the result\n+ shape. Must be broadcast-compatible with ``a`` and ``b``. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -532,10 +550,9 @@ def beta(key, a, b, shape=(), dtype=onp.float64):\n@partial(jit, static_argnums=(3, 4))\ndef _beta(key, a, b, shape, dtype):\n- _check_shape(\"beta\", shape)\n+ _check_shape(\"beta\", shape, a.shape, b.shape)\na = lax.convert_element_type(a, dtype)\nb = lax.convert_element_type(b, dtype)\n- shape = shape or lax.broadcast_shapes(np.shape(a), np.shape(b))\nkey_a, key_b = split(key)\ngamma_a = gamma(key_a, a, shape, dtype)\ngamma_b = gamma(key_b, b, shape, dtype)\n@@ -547,8 +564,8 @@ def cauchy(key, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ shape: optional, a tuple of nonnegative integers representing the result\n+ shape. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -571,24 +588,30 @@ def dirichlet(key, alpha, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- alpha: an array-like with `alpha.shape[:-1]` broadcastable to `shape` and\n- used as the concentration parameter of the random variables.\n- shape: optional, a tuple of nonnegative integers representing the batch\n- shape (defaults to `alpha.shape[:-1]`).\n+ alpha: an array of shape ``(..., n)`` used as the concentration\n+ parameter of the random variables.\n+ shape: optional, a tuple of nonnegative integers specifying the result\n+ batch shape; that is, the prefix of the result shape excluding the last\n+ element of value ``n``. Must be broadcast-compatible with\n+ ``alpha.shape[:-1]``.\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nReturns:\n- A random array with the specified shape and dtype.\n+ A random array with the specified dtype and shape given by\n+ ``shape + (alpha.shape[-1],)``.\n\"\"\"\ndtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _dirichlet(key, alpha, shape, dtype)\n@partial(jit, static_argnums=(2, 3))\ndef _dirichlet(key, alpha, shape, dtype):\n- _check_shape(\"dirichlet\", shape)\n- alpha = asarray(alpha, dtype)\n- shape = shape or alpha.shape[:-1]\n+ if not onp.ndim(alpha) >= 1:\n+ msg = \"dirichlet requires alpha.ndim >= 1, got alpha.ndim == {}\"\n+ raise ValueError(msg.format(onp.ndim(alpha)))\n+\n+ _check_shape(\"dirichlet\", shape, alpha.shape[:-1])\n+ alpha = lax.convert_element_type(alpha, dtype)\ngamma_samples = gamma(key, alpha, shape + alpha.shape[-1:], dtype)\nreturn gamma_samples / np.sum(gamma_samples, axis=-1, keepdims=True)\n@@ -598,8 +621,8 @@ def exponential(key, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ shape: optional, a tuple of nonnegative integers representing the result\n+ shape. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -672,7 +695,6 @@ def _gamma_one(key, alpha):\nz = lax.mul(lax.mul(d, V), boost)\nreturn lax.select(lax.eq(z, zero), onp.finfo(z.dtype).tiny, z)\n-\n_bivariate_coef = [[0.16009398, -0.094634816, 0.025146379, -0.0030648348,\n1, 0.3266811, 0.10406087, 0.0014179033],\n[0.53487893, 0.12980707, 0.06573594, -0.0015649787,\n@@ -680,7 +702,6 @@ _bivariate_coef = [[0.16009398, -0.094634816, 0.025146379, -0.0030648348,\n[0.040121005, -0.0065914079, -0.002628604, -0.0013441777,\n0.017050642, -0.0021309345, 0.00085092385, -1.5248239e-07]]\n-\ndef _gamma_grad_one(z, alpha):\n# Ref 1: Pathwise Derivatives Beyond the Reparameterization Trick, Martin & Fritz\n# Ref 2: Case 4 follows https://github.com/fritzo/notebooks/blob/master/gamma-reparameterized.ipynb\n@@ -776,14 +797,12 @@ def _gamma_grad_one(z, alpha):\n_, _, grad, flag = lax.while_loop(lambda zagf: ~zagf[3], _case4, (z, alpha, grad, flag))\nreturn grad\n-\ndef _gamma_grad(sample, a):\nsamples = np.reshape(sample, -1)\nalphas = np.reshape(a, -1)\ngrads = vmap(_gamma_grad_one)(samples, alphas)\nreturn grads.reshape(a.shape)\n-\n@custom_transforms\ndef _gamma_impl(key, a):\nalphas = np.reshape(a, -1)\n@@ -791,20 +810,18 @@ def _gamma_impl(key, a):\nsamples = vmap(_gamma_one)(keys, alphas)\nreturn np.reshape(samples, np.shape(a))\n-\ndefjvp(_gamma_impl, None,\nlambda tangent, ans, key, a, **kwargs: tangent * _gamma_grad(ans, a))\n-\ndef gamma(key, a, shape=(), dtype=onp.float64):\n\"\"\"Sample Gamma random values with given shape and float dtype.\nArgs:\nkey: a PRNGKey used as the random key.\n- a: an array-like broadcastable to `shape` and used as the shape parameter\n- of the random variables.\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ a: a float or array of floats broadcast-compatible with ``shape``\n+ representing the parameter of the distribution.\n+ shape: optional, a tuple of nonnegative integers specifying the result\n+ shape. Must be broadcast-compatible with ``a``. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -816,9 +833,8 @@ def gamma(key, a, shape=(), dtype=onp.float64):\n@partial(jit, static_argnums=(2, 3))\ndef _gamma(key, a, shape, dtype):\n- _check_shape(\"gamma\", shape)\n+ _check_shape(\"gamma\", shape, a.shape)\na = lax.convert_element_type(a, dtype)\n- shape = shape or onp.shape(a)\nif onp.shape(a) != shape:\na = np.broadcast_to(a, shape)\nreturn _gamma_impl(key, a)\n@@ -829,8 +845,8 @@ def gumbel(key, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ shape: optional, a tuple of nonnegative integers representing the result\n+ shape. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -852,8 +868,8 @@ def laplace(key, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ shape: optional, a tuple of nonnegative integers representing the result\n+ shape. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -876,8 +892,8 @@ def logistic(key, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ shape: optional, a tuple of nonnegative integers representing the result\n+ shape. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -898,10 +914,10 @@ def pareto(key, b, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- b: an array-like broadcastable to `shape` and used as the shape parameter\n- of the random variables.\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ a: a float or array of floats broadcast-compatible with ``shape``\n+ representing the parameter of the distribution.\n+ shape: optional, a tuple of nonnegative integers specifying the result\n+ shape. Must be broadcast-compatible with ``b``. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -915,11 +931,8 @@ def pareto(key, b, shape=(), dtype=onp.float64):\ndef _pareto(key, b, shape, dtype):\n_check_shape(\"pareto\", shape)\nb = lax.convert_element_type(b, dtype)\n- shape = shape or onp.shape(b)\n- if onp.shape(b) != shape:\n- b = np.broadcast_to(b, shape)\ne = exponential(key, shape, dtype)\n- return lax.exp(lax.div(e, b))\n+ return lax.exp(e / b)\ndef t(key, df, shape=(), dtype=onp.float64):\n@@ -927,10 +940,10 @@ def t(key, df, shape=(), dtype=onp.float64):\nArgs:\nkey: a PRNGKey used as the random key.\n- df: an array-like broadcastable to `shape` and used as the shape parameter\n- of the random variables.\n- shape: optional, a tuple of nonnegative integers representing the shape\n- (default scalar).\n+ df: a float or array of floats broadcast-compatible with ``shape``\n+ representing the parameter of the distribution.\n+ shape: optional, a tuple of nonnegative integers specifying the result\n+ shape. Must be broadcast-compatible with ``df``. Default ().\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n@@ -942,9 +955,8 @@ def t(key, df, shape=(), dtype=onp.float64):\n@partial(jit, static_argnums=(2, 3))\ndef _t(key, df, shape, dtype):\n- _check_shape(\"t\", shape)\n+ _check_shape(\"t\", shape, df.shape)\ndf = lax.convert_element_type(df, dtype)\n- shape = shape or onp.shape(df)\nkey_n, key_g = split(key)\nn = normal(key_n, shape, dtype)\ntwo = _constant_like(n, 2)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -218,7 +218,9 @@ class LaxRandomTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_alpha={}_{}\".format(alpha, dtype),\n\"alpha\": alpha, \"dtype\": onp.dtype(dtype).name}\n- for alpha in [[0.2, 1., 5.]]\n+ for alpha in [\n+ onp.array([0.2, 1., 5.]),\n+ ]\nfor dtype in [onp.float32, onp.float64]))\ndef testDirichlet(self, alpha, dtype):\nkey = random.PRNGKey(0)\n@@ -275,8 +277,8 @@ class LaxRandomTest(jtu.JaxTestCase):\ndef testGammaGrad(self, alpha):\nrng = random.PRNGKey(0)\nalphas = onp.full((100,), alpha)\n- z = random.gamma(rng, alphas)\n- actual_grad = api.grad(lambda x: (random.gamma(rng, x)).sum())(alphas)\n+ z = random.gamma(rng, alphas, shape=(100,))\n+ actual_grad = api.grad(lambda x: random.gamma(rng, x, shape=(100,)).sum())(alphas)\neps = 0.01 * alpha / (1.0 + onp.sqrt(alpha))\ncdf_dot = (scipy.stats.gamma.cdf(z, alpha + eps)\n" } ]
Python
Apache License 2.0
google/jax
standardize shape handling in jax.random
260,335
20.10.2019 21:14:48
0
1f4e45cdcd92b205d2d42cc40f7fedb0eeb702b3
tweak shape convention again
[ { "change_type": "MODIFY", "old_path": "jax/random.py", "new_path": "jax/random.py", "diff": "@@ -428,24 +428,26 @@ def _normal(key, shape, dtype):\nreturn onp.array(onp.sqrt(2), dtype) * lax.erf_inv(u)\n-def multivariate_normal(key, mean, cov, shape=(), dtype=onp.float64):\n+def multivariate_normal(key, mean, cov, shape=None, dtype=onp.float64):\n\"\"\"Sample multivariate normal random values with given mean and covariance.\nArgs:\nkey: a PRNGKey used as the random key.\nmean: a mean vector of shape ``(..., n)``.\ncov: a positive definite covariance matrix of shape ``(..., n, n)``. The\n- shape prefix ``...`` must be broadcast-compatible with that of ``mean``.\n+ batch shape ``...`` must be broadcast-compatible with that of ``mean``.\nshape: optional, a tuple of nonnegative integers specifying the result\nbatch shape; that is, the prefix of the result shape excluding the last\n- element of value ``n``. Must be broadcast-compatible with\n- ``mean.shape[:-1]`` and ``cov.shape[:-2]``. Default ().\n+ axis. Must be broadcast-compatible with ``mean.shape[:-1]`` and\n+ ``cov.shape[:-2]``. The default (None) produces a result batch shape by\n+ broadcasting together the batch shapes of ``mean`` and ``cov``.\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified dtype and shape given by\n- ``shape + (mean.shape[-1],)``.\n+ ``shape + mean.shape[-1:]`` if ``shape`` is not None, or else\n+ ``broadcast_shapes(mean.shape[:-1], cov.shape[:-2]) + mean.shape[-1:]``.\n\"\"\"\ndtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _multivariate_normal(key, mean, cov, shape, dtype)\n@@ -464,35 +466,46 @@ def _multivariate_normal(key, mean, cov, shape, dtype):\n\"but got cov.shape == {shape}.\")\nraise ValueError(msg.format(n=n, shape=onp.shape(cov)))\n+ if shape is None:\n+ shape = lax.broadcast_shapes(mean.shape[:-1], cov.shape[:-2])\n+ else:\n_check_shape(\"normal\", shape, mean.shape[:-1], mean.shape[:-2])\n+\nchol_factor = cholesky(cov)\nnormal_samples = normal(key, shape + mean.shape[-1:], dtype)\nreturn mean + np.tensordot(normal_samples, chol_factor, [-1, 1])\n-def truncated_normal(key, lower, upper, shape=(), dtype=onp.float64):\n+def truncated_normal(key, lower, upper, shape=None, dtype=onp.float64):\n\"\"\"Sample truncated standard normal random values with given shape and dtype.\nArgs:\nkey: a PRNGKey used as the random key.\n- lower: a float or array of lower bound for truncation. Must be\n- broadcast-compatible with `upper`.\n- upper: a floating-point upper bound for truncation. Must be\n- broadcast-compatible with `lower`.\n+ lower: a float or array of floats representing the lower bound for\n+ truncation. Must be broadcast-compatible with ``upper``.\n+ upper: a float or array of floats representing the upper bound for\n+ truncation. Must be broadcast-compatible with ``lower``.\nshape: optional, a tuple of nonnegative integers specifying the result\n- shape. Must be broadcast-compatible with `lower` and `upper`. Default ().\n+ shape. Must be broadcast-compatible with ``lower`` and ``upper``. The\n+ default (None) produces a result shape by broadcasting ``lower`` and\n+ ``upper``.\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nReturns:\n- A random array with the specified shape and dtype.\n+ A random array with the specified dtype and shape given by ``shape`` if\n+ ``shape`` is not None, or else by broadcasting ``lower`` and ``upper``.\n\"\"\"\ndtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _truncated_normal(key, lower, upper, shape, dtype)\n@partial(jit, static_argnums=(3, 4))\ndef _truncated_normal(key, lower, upper, shape, dtype):\n+ if shape is None:\n+ shape = lax.broadcast_shapes(lower.shape, upper.shape)\n+ else:\n_check_shape(\"truncated_normal\", shape, lower.shape, upper.shape)\n+\nsqrt2 = onp.array(onp.sqrt(2), dtype)\na = lax.erf(lax.convert_element_type(lower, dtype) / sqrt2)\nb = lax.erf(lax.convert_element_type(upper, dtype) / sqrt2)\n@@ -502,18 +515,20 @@ def _truncated_normal(key, lower, upper, shape, dtype):\nreturn sqrt2 * lax.erf_inv(a + u * (b - a))\n-def bernoulli(key, p=onp.float32(0.5), shape=()):\n+def bernoulli(key, p=onp.float32(0.5), shape=None):\n\"\"\"Sample Bernoulli random values with given shape and mean.\nArgs:\nkey: a PRNGKey used as the random key.\np: optional, a float or array of floats for the mean of the random\nvariables. Must be broadcast-compatible with ``shape``. Default 0.5.\n- shape: optional, a tuple of nonnegative integers representing the shape.\n- Default ().\n+ shape: optional, a tuple of nonnegative integers representing the result\n+ shape. Must be broadcast-compatible with ``p.shape``. The default (None)\n+ produces a result shape equal to ``p.shape``.\nReturns:\n- A random array with the specified shape and boolean dtype.\n+ A random array with boolean dtype and shape given by ``shape`` if ``shape``\n+ is not None, or else ``p.shape``.\n\"\"\"\ndtype = xla_bridge.canonicalize_dtype(lax.dtype(p))\nif not onp.issubdtype(dtype, onp.floating):\n@@ -524,11 +539,15 @@ def bernoulli(key, p=onp.float32(0.5), shape=()):\n@partial(jit, static_argnums=(2,))\ndef _bernoulli(key, p, shape):\n+ if shape is None:\n+ shape = p.shape\n+ else:\n_check_shape(\"bernoulli\", shape, p.shape)\n+\nreturn uniform(key, shape, lax.dtype(p)) < p\n-def beta(key, a, b, shape=(), dtype=onp.float64):\n+def beta(key, a, b, shape=None, dtype=onp.float64):\n\"\"\"Sample Bernoulli random values with given shape and mean.\nArgs:\n@@ -538,19 +557,25 @@ def beta(key, a, b, shape=(), dtype=onp.float64):\nb: a float or array of floats broadcast-compatible with ``shape``\nrepresenting the second parameter \"beta\".\nshape: optional, a tuple of nonnegative integers specifying the result\n- shape. Must be broadcast-compatible with ``a`` and ``b``. Default ().\n+ shape. Must be broadcast-compatible with ``a`` and ``b``. The default\n+ (None) produces a result shape by broadcasting ``a`` and ``b``.\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nReturns:\n- A random array with the specified shape and dtype.\n+ A random array with the specified dtype and shape given by ``shape`` if\n+ ``shape`` is not None, or else by broadcasting ``a`` and ``b``.\n\"\"\"\ndtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _beta(key, a, b, shape, dtype)\n@partial(jit, static_argnums=(3, 4))\ndef _beta(key, a, b, shape, dtype):\n+ if shape is None:\n+ shape = lax.broadcast_shapes(a.shape, b.shape)\n+ else:\n_check_shape(\"beta\", shape, a.shape, b.shape)\n+\na = lax.convert_element_type(a, dtype)\nb = lax.convert_element_type(b, dtype)\nkey_a, key_b = split(key)\n@@ -583,7 +608,7 @@ def _cauchy(key, shape, dtype):\nreturn lax.tan(lax.mul(pi, lax.sub(u, _constant_like(u, 0.5))))\n-def dirichlet(key, alpha, shape=(), dtype=onp.float64):\n+def dirichlet(key, alpha, shape=None, dtype=onp.float64):\n\"\"\"Sample Cauchy random values with given shape and float dtype.\nArgs:\n@@ -593,13 +618,15 @@ def dirichlet(key, alpha, shape=(), dtype=onp.float64):\nshape: optional, a tuple of nonnegative integers specifying the result\nbatch shape; that is, the prefix of the result shape excluding the last\nelement of value ``n``. Must be broadcast-compatible with\n- ``alpha.shape[:-1]``.\n+ ``alpha.shape[:-1]``. The default (None) produces a result shape equal to\n+ ``alpha.shape``.\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified dtype and shape given by\n- ``shape + (alpha.shape[-1],)``.\n+ ``shape + (alpha.shape[-1],)`` if ``shape`` is not None, or else\n+ ``alpha.shape``.\n\"\"\"\ndtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _dirichlet(key, alpha, shape, dtype)\n@@ -610,7 +637,11 @@ def _dirichlet(key, alpha, shape, dtype):\nmsg = \"dirichlet requires alpha.ndim >= 1, got alpha.ndim == {}\"\nraise ValueError(msg.format(onp.ndim(alpha)))\n+ if shape is None:\n+ shape = alpha.shape[:-1]\n+ else:\n_check_shape(\"dirichlet\", shape, alpha.shape[:-1])\n+\nalpha = lax.convert_element_type(alpha, dtype)\ngamma_samples = gamma(key, alpha, shape + alpha.shape[-1:], dtype)\nreturn gamma_samples / np.sum(gamma_samples, axis=-1, keepdims=True)\n@@ -813,7 +844,7 @@ def _gamma_impl(key, a):\ndefjvp(_gamma_impl, None,\nlambda tangent, ans, key, a, **kwargs: tangent * _gamma_grad(ans, a))\n-def gamma(key, a, shape=(), dtype=onp.float64):\n+def gamma(key, a, shape=None, dtype=onp.float64):\n\"\"\"Sample Gamma random values with given shape and float dtype.\nArgs:\n@@ -821,19 +852,25 @@ def gamma(key, a, shape=(), dtype=onp.float64):\na: a float or array of floats broadcast-compatible with ``shape``\nrepresenting the parameter of the distribution.\nshape: optional, a tuple of nonnegative integers specifying the result\n- shape. Must be broadcast-compatible with ``a``. Default ().\n+ shape. Must be broadcast-compatible with ``a``. The default (None)\n+ produces a result shape equal to ``a.shape``.\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nReturns:\n- A random array with the specified shape and dtype.\n+ A random array with the specified dtype and with shape given by ``shape`` if\n+ ``shape`` is not None, or else by ``a.shape``.\n\"\"\"\ndtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _gamma(key, a, shape, dtype)\n@partial(jit, static_argnums=(2, 3))\ndef _gamma(key, a, shape, dtype):\n+ if shape is None:\n+ shape = a.shape\n+ else:\n_check_shape(\"gamma\", shape, a.shape)\n+\na = lax.convert_element_type(a, dtype)\nif onp.shape(a) != shape:\na = np.broadcast_to(a, shape)\n@@ -909,7 +946,7 @@ def _logistic(key, shape, dtype):\nreturn logit(uniform(key, shape, dtype))\n-def pareto(key, b, shape=(), dtype=onp.float64):\n+def pareto(key, b, shape=None, dtype=onp.float64):\n\"\"\"Sample Pareto random values with given shape and float dtype.\nArgs:\n@@ -917,19 +954,25 @@ def pareto(key, b, shape=(), dtype=onp.float64):\na: a float or array of floats broadcast-compatible with ``shape``\nrepresenting the parameter of the distribution.\nshape: optional, a tuple of nonnegative integers specifying the result\n- shape. Must be broadcast-compatible with ``b``. Default ().\n+ shape. Must be broadcast-compatible with ``b``. The default (None)\n+ produces a result shape equal to ``b.shape``.\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nReturns:\n- A random array with the specified shape and dtype.\n+ A random array with the specified dtype and with shape given by ``shape`` if\n+ ``shape`` is not None, or else by ``b.shape``.\n\"\"\"\ndtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _pareto(key, b, shape, dtype)\n@partial(jit, static_argnums=(2, 3))\ndef _pareto(key, b, shape, dtype):\n+ if shape is None:\n+ shape = b.shape\n+ else:\n_check_shape(\"pareto\", shape)\n+\nb = lax.convert_element_type(b, dtype)\ne = exponential(key, shape, dtype)\nreturn lax.exp(e / b)\n@@ -943,19 +986,25 @@ def t(key, df, shape=(), dtype=onp.float64):\ndf: a float or array of floats broadcast-compatible with ``shape``\nrepresenting the parameter of the distribution.\nshape: optional, a tuple of nonnegative integers specifying the result\n- shape. Must be broadcast-compatible with ``df``. Default ().\n+ shape. Must be broadcast-compatible with ``df``. The default (None)\n+ produces a result shape equal to ``df.shape``.\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\nReturns:\n- A random array with the specified shape and dtype.\n+ A random array with the specified dtype and with shape given by ``shape`` if\n+ ``shape`` is not None, or else by ``df.shape``.\n\"\"\"\ndtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _t(key, df, shape, dtype)\n@partial(jit, static_argnums=(2, 3))\ndef _t(key, df, shape, dtype):\n+ if shape is None:\n+ shape = df.shape\n+ else:\n_check_shape(\"t\", shape, df.shape)\n+\ndf = lax.convert_element_type(df, dtype)\nkey_n, key_g = split(key)\nn = normal(key_n, shape, dtype)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -277,8 +277,8 @@ class LaxRandomTest(jtu.JaxTestCase):\ndef testGammaGrad(self, alpha):\nrng = random.PRNGKey(0)\nalphas = onp.full((100,), alpha)\n- z = random.gamma(rng, alphas, shape=(100,))\n- actual_grad = api.grad(lambda x: random.gamma(rng, x, shape=(100,)).sum())(alphas)\n+ z = random.gamma(rng, alphas)\n+ actual_grad = api.grad(lambda x: random.gamma(rng, x).sum())(alphas)\neps = 0.01 * alpha / (1.0 + onp.sqrt(alpha))\ncdf_dot = (scipy.stats.gamma.cdf(z, alpha + eps)\n@@ -379,21 +379,22 @@ class LaxRandomTest(jtu.JaxTestCase):\ncov_factor = r.randn(dim, dim)\ncov = onp.dot(cov_factor, cov_factor.T) + dim * onp.eye(dim)\n- keys = random.split(random.PRNGKey(0), 1000)\n- rand = api.vmap(partial(random.multivariate_normal, mean=mean, cov=cov))\n+ key = random.PRNGKey(0)\n+ rand = partial(random.multivariate_normal, mean=mean, cov=cov,\n+ shape=(10000,))\ncrand = api.jit(rand)\n- uncompiled_samples = rand(keys)\n- compiled_samples = crand(keys)\n+ uncompiled_samples = onp.asarray(rand(key), onp.float64)\n+ compiled_samples = onp.asarray(crand(key), onp.float64)\n- # This is a quick-and-dirty multivariate normality check that tests that a\n- # uniform mixture of the marginals along the covariance matrix's\n- # eigenvectors follow a standard normal distribution.\n- # TODO(mattjj); check for correlations, maybe use a more sophisticated test.\ninv_scale = scipy.linalg.lapack.dtrtri(onp.linalg.cholesky(cov), lower=True)[0]\nfor samples in [uncompiled_samples, compiled_samples]:\ncentered = samples - mean\nwhitened = onp.einsum('nj,ij->ni', centered, inv_scale)\n+\n+ # This is a quick-and-dirty multivariate normality check that tests that a\n+ # uniform mixture of the marginals along the covariance matrix's\n+ # eigenvectors follow a standard normal distribution.\nself._CheckKolmogorovSmirnovCDF(whitened.ravel(), scipy.stats.norm().cdf)\ndef testIssue222(self):\n" } ]
Python
Apache License 2.0
google/jax
tweak shape convention again
260,273
21.10.2019 11:48:58
0
43be8d8ef81177d4c41b8e580e2c4f8b2afef52b
Fix NaNs in grad(jax.nn.elu) for large inputs.
[ { "change_type": "MODIFY", "old_path": "jax/nn/functions.py", "new_path": "jax/nn/functions.py", "diff": "@@ -35,7 +35,8 @@ def swish(x): return x * sigmoid(x)\ndef log_sigmoid(x): return -softplus(-x)\ndef elu(x, alpha=1.0):\n- return np.where(x > 0, x, alpha * np.expm1(x))\n+ safe_x = np.where(x > 0, 0., x)\n+ return np.where(x > 0, x, alpha * np.expm1(safe_x))\ndef leaky_relu(x, negative_slope=1e-2):\nreturn np.where(x >= 0, x, negative_slope * x)\n" }, { "change_type": "MODIFY", "old_path": "tests/nn_test.py", "new_path": "tests/nn_test.py", "diff": "@@ -29,6 +29,7 @@ from jax import test_util as jtu\nfrom jax.test_util import check_grads\nfrom jax import nn\nfrom jax import random\n+import jax\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -42,6 +43,13 @@ class NNFunctionsTest(jtu.JaxTestCase):\nval = nn.softplus(89.)\nself.assertAllClose(val, 89., check_dtypes=False)\n+ def testEluGrad(self):\n+ check_grads(nn.elu, (1e4,), 4, eps=1.)\n+\n+ def testEluValue(self):\n+ val = nn.elu(1e4)\n+ self.assertAllClose(val, 1e4, check_dtypes=False)\n+\nInitializerRecord = collections.namedtuple(\n\"InitializerRecord\",\n[\"name\", \"initializer\", \"shapes\"])\n@@ -80,3 +88,6 @@ class NNInitializersTest(jtu.JaxTestCase):\nfor dtype in [onp.float32, onp.float64]))\ndef testInitializer(self, initializer, rng, shape, dtype):\nval = initializer(rng, shape, dtype)\n+\n+if __name__ == \"__main__\":\n+ absltest.main()\n" } ]
Python
Apache License 2.0
google/jax
Fix NaNs in grad(jax.nn.elu) for large inputs.
260,335
21.10.2019 15:11:51
25,200
0601b8cdc7d7cb6a89990e40380dc469ab7103af
make lax.broadcast_in_dim work on scalars fixes
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -599,7 +599,7 @@ def broadcast(operand, sizes):\nreturn broadcast_p.bind(operand, sizes=tuple(sizes))\ndef broadcast_in_dim(operand, shape, broadcast_dimensions):\n- if operand.ndim == len(shape) and not len(broadcast_dimensions):\n+ if onp.ndim(operand) == len(shape) and not len(broadcast_dimensions):\nreturn operand\nif any(x < 0 or x >= len(shape) for x in broadcast_dimensions):\nmsg = (\"broadcast dimensions must be >= 0 and < ndim(shape), got {} for \"\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1952,6 +1952,10 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nValueError, \"Incompatible shapes for broadcasting: .*\",\nlambda: lnp.broadcast_to(onp.ones((2, 3)), (1, 3)))\n+ def testBroadcastToIntIssue1548(self):\n+ self.assertAllClose(lnp.broadcast_to(1, (3, 2)), onp.ones((3, 2)),\n+ check_dtypes=False)\n+\n# Most grad tests are at the lax level (see lax_test.py), but we add some here\n# as needed for e.g. particular compound ops of interest.\n" } ]
Python
Apache License 2.0
google/jax
make lax.broadcast_in_dim work on scalars fixes #1548
260,411
24.10.2019 10:10:04
-7,200
7cbd58b6c6f910e1d7b762d7ed51a057be138976
Improved the type checking for uses of scan. * Improved the type checking for uses of scan. Previous way of checking was done after flattening and got easily confused by tuples of different shapes, or None. Relates to
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax_control_flow.py", "new_path": "jax/lax/lax_control_flow.py", "diff": "@@ -447,7 +447,8 @@ def scan(f, init, xs):\nthe loop carry and the second represents a slice of the output.\ninit: an initial loop carry value of type ``c``, which can be a scalar,\narray, or any pytree (nested Python tuple/list/dict) thereof, representing\n- the initial loop carry value.\n+ the initial loop carry value. This value must have the same structure as\n+ the first element of the pair returned by ``f``.\nxs: the value of type ``[a]`` over which to scan along the leading axis,\nwhere ``[a]`` can be an array or any pytree (nested Python\ntuple/list/dict) thereof with consistent leading axis sizes.\n@@ -457,9 +458,9 @@ def scan(f, init, xs):\nloop carry value and the second element represents the stacked outputs of\nthe second output of ``f`` when scanned over the leading axis of the inputs.\n\"\"\"\n- num_carry = len(tree_flatten(init)[0])\n+ init_flat, init_tree = tree_flatten(init)\n+ xs_flat, _ = tree_flatten(xs)\nin_flat, in_tree = tree_flatten((init, xs))\n- init_flat, xs_flat = in_flat[:num_carry], in_flat[num_carry:]\ntry:\nlength, = {x.shape[0] for x in xs_flat}\nexcept AttributeError:\n@@ -474,13 +475,19 @@ def scan(f, init, xs):\nx_dtypes = [x.dtype for x in xs_flat]\nx_avals = tuple(_map(ShapedArray, x_shapes, x_dtypes))\njaxpr, consts, out_tree = _initial_style_jaxpr(f, in_tree, carry_avals + x_avals)\n- carry_avals_out, y_avals = split_list(jaxpr.out_avals, [num_carry])\n- if tuple(carry_avals_out) != carry_avals:\n- msg = \"scan carry output type must match carry input type, got {} and {}.\"\n- raise TypeError(msg.format(tuple(carry_avals_out), carry_avals))\n+\n+ out_tree_children = out_tree.children()\n+ if len(out_tree_children) != 2:\n+ msg = \"scan body output must be a pair, got {}.\"\n+ raise TypeError(msg.format(tree_unflatten(out_tree, jaxpr.out_avals)))\n+ _check_tree_and_avals(\"scan carry output and input\",\n+ # Extract the subtree and avals for the first element of the return tuple\n+ out_tree_children[0], jaxpr.out_avals[:out_tree_children[0].num_leaves],\n+ init_tree, carry_avals)\n+\nout = scan_p.bind(*itertools.chain(consts, in_flat),\nforward=True, length=length, jaxpr=jaxpr,\n- num_consts=len(consts), num_carry=num_carry,\n+ num_consts=len(consts), num_carry=len(init_flat),\nlinear=(False,) * (len(consts) + len(in_flat)))\nreturn tree_unflatten(out_tree, out)\n@@ -884,6 +891,22 @@ def _check_tree(func_name, expected_name, actual_tree, expected_tree):\n.format(func_name, expected_name, actual_tree, expected_tree))\n+def _check_tree_and_avals(what, tree1, avals1, tree2, avals2):\n+ \"\"\"Raises TypeError if (tree1, avals1) does not match (tree2, avals2).\n+\n+ Corresponding `tree` and `avals` must match in the sense that the number of leaves in\n+ `tree` must be equal to the length of `avals`.\n+ `what` will be prepended to details of the mismatch in TypeError.\n+ \"\"\"\n+ if tree1 != tree2:\n+ msg = (\"{} must have same type structure, got {} and {}.\")\n+ raise TypeError(msg.format(what, tree1, tree2))\n+ if not all(safe_map(typematch, avals1, avals2)):\n+ msg = (\"{} must have identical types, \"\n+ \"got {} and {}.\")\n+ raise TypeError(msg.format(what, tree_unflatten(tree1, avals1),\n+ tree_unflatten(tree2, avals2)))\n+\ndef root(f, initial_guess, solve, tangent_solve):\n\"\"\"Differentiably solve for a roots of a function.\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -708,7 +708,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nif jit_f:\nf = api.jit(f)\nif jit_scan:\n- scan = api.jit(lax.scan, (0,))\n+ scan = api.jit(lax.scan, static_argnums=(0,))\nelse:\nscan = lax.scan\n@@ -823,11 +823,35 @@ class LaxControlFlowTest(jtu.JaxTestCase):\ndef plus_one(p, iter_idx):\nreturn Point(p.x+1, p.y+1), iter_idx\n- self.assertRaisesRegexp(\n+ self.assertRaisesRegex(\nValueError,\n'scan got value with no leading axis to scan over.*',\nlambda: lax.scan(plus_one, p0, list(range(5))))\n+ @jtu.skip_on_flag('jax_enable_x64', True) # With float64 error messages are different; hard to check precisely\n+ def testScanTypeErrors(self):\n+ \"\"\"Test typing error messages for scan.\"\"\"\n+ a = np.arange(5)\n+ # Body output not a tuple\n+ with self.assertRaisesRegex(TypeError,\n+ re.escape(\"scan body output must be a pair, got ShapedArray(int32[]).\")):\n+ lax.scan(lambda c, x: 0, 0, a)\n+ with self.assertRaisesRegex(TypeError,\n+ re.escape(\"scan carry output and input must have same type structure, \"\n+ \"got PyTreeDef(tuple, [*,*,*]) and PyTreeDef(tuple, [*,PyTreeDef(tuple, [*,*])])\")):\n+ lax.scan(lambda c, x: ((0, 0, 0), x), (1, (2, 3)), a)\n+ with self.assertRaisesRegex(TypeError,\n+ re.escape(\"scan carry output and input must have same type structure, got * and PyTreeDef(None, []).\")):\n+ lax.scan(lambda c, x: (0, x), None, a)\n+ with self.assertRaisesRegex(TypeError,\n+ re.escape(\"scan carry output and input must have identical types, \"\n+ \"got ShapedArray(int32[]) and ShapedArray(float32[]).\")):\n+ lax.scan(lambda c, x: (0, x), 1.0, a)\n+ with self.assertRaisesRegex(TypeError,\n+ re.escape(\"scan carry output and input must have same type structure, got * and PyTreeDef(tuple, [*,*]).\")):\n+ lax.scan(lambda c, x: (0, x), (1, 2), np.arange(5))\n+\n+\ndef testScanHigherOrderDifferentiation(self):\nd = 0.75\ndef f(c, a):\n@@ -1246,7 +1270,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\njtu.check_grads(loss, (a, b), atol=1e-5, order=2, modes=['fwd'])\n- with self.assertRaisesRegexp(TypeError, \"transpose_solve required\"):\n+ with self.assertRaisesRegex(TypeError, \"transpose_solve required\"):\napi.grad(loss)(a, b)\ndef test_custom_linear_solve_errors(self):\n" } ]
Python
Apache License 2.0
google/jax
Improved the type checking for uses of scan. (#1551) * Improved the type checking for uses of scan. Previous way of checking was done after flattening and got easily confused by tuples of different shapes, or None. Relates to https://github.com/google/jax/issues/1534.
260,335
28.10.2019 13:02:31
25,200
38d6bf5edaf1fdd16e267d3a68de1e2f8d61577b
add test for fori_loop index batching fixes
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -312,6 +312,13 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nexpected = (onp.array([10, 11]), onp.array([20, 20]))\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testForiLoopBatchedIssue1190(self):\n+ f = lambda x: lax.fori_loop(0, 4, lambda _, x: x + 1, x)\n+ jaxpr = api.make_jaxpr(api.vmap(f))(np.arange(3))\n+ eqn = jaxpr.eqns[0]\n+ self.assertIs(eqn.primitive, lax.while_p)\n+ self.assertEqual(eqn.params['cond_jaxpr'].in_avals[0].shape, ())\n+\ndef testForiLoopBasic(self):\ndef body_fun(i, tot):\nreturn lax.add(tot, i)\n" } ]
Python
Apache License 2.0
google/jax
add test for fori_loop index batching fixes #1190
260,510
28.10.2019 12:54:04
25,200
5d5699991327afde27d2850cd6d630ea82d599e6
Add custom interpreter notebook
[ { "change_type": "MODIFY", "old_path": "docs/index.rst", "new_path": "docs/index.rst", "diff": "@@ -23,6 +23,7 @@ For an introduction to JAX, start at the\nnotebooks/Common_Gotchas_in_JAX\nnotebooks/XLA_in_Python\nnotebooks/How_JAX_primitives_work\n+ notebooks/Writing_custom_interpreters_in_Jax.ipynb\nTraining a Simple Neural Network, with Tensorflow Datasets Data Loading <https://github.com/google/jax/blob/master/docs/notebooks/neural_network_with_tfds_data.ipynb>\nnotebooks/maml\nnotebooks/score_matching\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "diff": "+{\n+ \"nbformat\": 4,\n+ \"nbformat_minor\": 0,\n+ \"metadata\": {\n+ \"colab\": {\n+ \"name\": \"Writing custom interpreters in Jax\",\n+ \"provenance\": [],\n+ \"collapsed_sections\": []\n+ },\n+ \"kernelspec\": {\n+ \"name\": \"python3\",\n+ \"display_name\": \"Python 3\"\n+ }\n+ },\n+ \"cells\": [\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"M-hPMKlwXjMr\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"# Writing custom Jaxpr interpreters in `jax`\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"r-3vMiKRYXPJ\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"`jax` offers several composable function transformations (`jit`, `grad`, `vmap`,\\n\",\n+ \"etc.) that enable writing concise, accelerated code. \\n\",\n+ \"\\n\",\n+ \"Here we will go over how the basics of writing your own custom Jaxpr interpreter.\\n\",\n+ \"\\n\",\n+ \"*Disclaimer: This colab may not be up to date and relies on Jax internals that are subject to change.*\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"s27RDKvKXFL8\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {}\n+ },\n+ \"source\": [\n+ \"import numpy as onp\\n\",\n+ \"import jax\\n\",\n+ \"import jax.numpy as np\\n\",\n+ \"from jax import jit, grad, vmap\\n\",\n+ \"from jax import random\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"jb_8mEsJboVM\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"## What is `jax` doing?\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"KxR2WK0Ubs0R\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"`jax` provides a `numpy`-like API for numerical computing which can be used as is, but `jax`'s true power comes from composable function transformations. Take the `jit` function transformation, which takes in a function and returns a semantically identical function but is lazily compiled by XLA for accelerators.\\n\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"HmlMcICOcSXR\",\n+ \"colab_type\": \"code\",\n+ \"outputId\": \"546bf21b-7d03-4364-a087-5802792abbb0\",\n+ \"colab\": {\n+ \"height\": 54\n+ }\n+ },\n+ \"source\": [\n+ \"x = random.normal(random.PRNGKey(0), (5000, 5000))\\n\",\n+ \"def f(w, b, x):\\n\",\n+ \" return np.tanh(np.dot(x, w) + b)\\n\",\n+ \"fast_f = jit(f)\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"gA8V51wZdsjh\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"When we call `fast_f`, what happens? `jax` traces the function and constructs an XLA computation graph. The graph is then JIT-compiled and executed. Other transformations work similarly in that they first trace the function and handle the output trace in some way. To learn more about Jax's tracing machinery, you can refer to the [\\\"How it works\\\"](https://github.com/google/jax#how-it-works) section in the README.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"2Th1vYLVaFBz\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"## Jaxpr tracer\\n\",\n+ \"\\n\",\n+ \"A tracer of special importance in Jax is the Jaxpr tracer, which records ops into a Jaxpr (Jax expression). A Jaxpr is a data structure that can be evaluated like a mini-functional programming language and \\n\",\n+ \"thus Jaxprs are an incredibly useful intermediate representation\\n\",\n+ \"for function transformation. \\n\",\n+ \"\\n\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"pH7s63lpaHJO\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"`jax.make_jaxpr` is essentially a \\\"pretty-printing\\\" transformation:\\n\",\n+ \"it transforms a function into one that, given example arguments, produces a Jaxpr representation of its computation.\\n\",\n+ \"Although we can't generally use the Jaxprs that it returns, it is useful for debugging and introspection.\\n\",\n+ \"Let's use it to look at how some example Jaxprs\\n\",\n+ \"are structured.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"RSxEiWi-EeYW\",\n+ \"colab_type\": \"code\",\n+ \"outputId\": \"ee3d4f5c-97d3-4db3-a012-20898920cadb\",\n+ \"colab\": {\n+ \"height\": 547\n+ }\n+ },\n+ \"source\": [\n+ \"def examine_jaxpr(jaxpr):\\n\",\n+ \" print(\\\"invars:\\\", jaxpr.invars)\\n\",\n+ \" print(\\\"outvars:\\\", jaxpr.outvars)\\n\",\n+ \" print(\\\"constvars:\\\", jaxpr.constvars)\\n\",\n+ \" print(\\\"freevars:\\\", jaxpr.freevars)\\n\",\n+ \" for eqn in jaxpr.eqns:\\n\",\n+ \" print(\\\"equation:\\\", eqn.invars, eqn.primitive, eqn.outvars, eqn.params)\\n\",\n+ \" print()\\n\",\n+ \" print(\\\"jaxpr:\\\", jaxpr)\\n\",\n+ \"\\n\",\n+ \"def foo(x):\\n\",\n+ \" return x + 1\\n\",\n+ \"print(\\\"foo\\\")\\n\",\n+ \"print(\\\"=====\\\")\\n\",\n+ \"examine_jaxpr(jax.make_jaxpr(foo)(5))\\n\",\n+ \"\\n\",\n+ \"print()\\n\",\n+ \"\\n\",\n+ \"def bar(w, b, x):\\n\",\n+ \" return np.dot(w, x) + b + np.ones(5), x\\n\",\n+ \"print(\\\"bar\\\")\\n\",\n+ \"print(\\\"=====\\\")\\n\",\n+ \"examine_jaxpr(jax.make_jaxpr(bar)(np.ones((5, 10)), np.ones(5), np.ones(10)))\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": [\n+ {\n+ \"output_type\": \"stream\",\n+ \"text\": [\n+ \"foo\\n\",\n+ \"=====\\n\",\n+ \"invars: [a]\\n\",\n+ \"outvars: [b]\\n\",\n+ \"constvars: []\\n\",\n+ \"freevars: []\\n\",\n+ \"equation: [a, 1] add [b] {}\\n\",\n+ \"\\n\",\n+ \"jaxpr: { lambda ; ; a.\\n\",\n+ \" let b = add a 1\\n\",\n+ \" in [b] }\\n\",\n+ \"\\n\",\n+ \"\\n\",\n+ \"bar\\n\",\n+ \"=====\\n\",\n+ \"invars: [a, b, c]\\n\",\n+ \"outvars: [g, c]\\n\",\n+ \"constvars: [f]\\n\",\n+ \"freevars: []\\n\",\n+ \"equation: [a, c] dot_general [d] {'dimension_numbers': (((1,), (0,)), ((), ())), 'precision': None}\\n\",\n+ \"equation: [d, b] add [e] {}\\n\",\n+ \"equation: [e, f] add [g] {}\\n\",\n+ \"\\n\",\n+ \"jaxpr: { lambda f ; ; a b c.\\n\",\n+ \" let d = dot_general[ dimension_numbers=(((1,), (0,)), ((), ()))\\n\",\n+ \" precision=None ] a c\\n\",\n+ \" e = add d b\\n\",\n+ \" g = add e f\\n\",\n+ \" in [g, c] }\\n\",\n+ \"\\n\"\n+ ],\n+ \"name\": \"stdout\"\n+ }\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"k-HxK9iagnH6\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"* `jaxpr.invars` - the `invars` of a Jaxpr are a list of the input variables to Jaxpr, analogous to arguments in Python functions\\n\",\n+ \"* `jaxpr.outvars` - the `outvars` of a Jaxpr are the variables that are returned by the Jaxpr. \\n\",\n+ \"* `jaxpr.constvars` - the `constvars` are a list of variables that are also inputs to the Jaxpr, but correspond to constants from the trace (we'll go over these in more detail later)\\n\",\n+ \"* `jaxpr.freevars` - we won't worry about these for now\\n\",\n+ \"* `jaxpr.eqns` - a list of equations. Each equation is list of input variables, a list of output variables, and a *primitive*, which is used to evaluate inputs to produce outputs. Each equation also has a set of `params`, a dictionary of keyword arguments to the primitive.\\n\",\n+ \"\\n\",\n+ \"All together, a Jaxpr encapsulates a simple program that can be evaluated with inputs to produce an output. We'll go over how exactly to do this later. The important thing to note now is that a Jaxpr is a data structure that can be manipulated and evaluated in whatever way we want.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"NwY7TurYn6sr\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"### Why are Jaxprs useful?\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"UEy6RorCgdYt\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"Jaxprs are simple and easy to transform. And because Jax lets us stage out Jaxprs from Python functions, it gives us a way to transform numerical programs written in Python.\\n\",\n+ \"\\n\",\n+ \"A helpful mental model for Jaxprs is that they are one-to-one with computation graphs, so the Jaxpr for a function is just the computation graph from its inputs to outputs.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"qizTKpbno_ua\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"# Your first interpreter: `invert`\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"OIto-KX4pD7j\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"Let's try to implement a very function \\\"inverter\\\", which takes in the output of the original function and returns the inputs that produced those outputs. For now, let's focus on simple, unary functions which are composed of other invertible unary functions.\\n\",\n+ \"\\n\",\n+ \"Goal:\\n\",\n+ \"```python\\n\",\n+ \"def f(x):\\n\",\n+ \" return np.exp(np.tanh(x))\\n\",\n+ \"f_inv = inverse(f)\\n\",\n+ \"# f_inv(f(1.0)) == 1.0\\n\",\n+ \"```\\n\",\n+ \"\\n\",\n+ \"The way we'll implement this is by 1) tracing `f` into a Jaxpr, then 2) interpret the Jaxpr *backwards*. Every time we hit a primitive, we'll look it up in a registry of invertible functions.\\n\",\n+ \"\\n\",\n+ \"## 1. Tracing a function\\n\",\n+ \"\\n\",\n+ \"We can't use `jax.make_jaxpr` for this, because we need to pull out constants created during the trace to pass into the Jaxpr. However, we can write a function that does something very similar to `make_jaxpr`.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"BHkg_3P1pXJj\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {}\n+ },\n+ \"source\": [\n+ \"# Importing Jax functions useful for tracing/interpreting.\\n\",\n+ \"import numpy as onp\\n\",\n+ \"from functools import wraps\\n\",\n+ \"\\n\",\n+ \"from jax import api_util\\n\",\n+ \"from jax import core\\n\",\n+ \"from jax import lax\\n\",\n+ \"from jax import linear_util as lu\\n\",\n+ \"from jax import tree_util\\n\",\n+ \"from jax.abstract_arrays import ShapedArray\\n\",\n+ \"from jax.interpreters import partial_eval as pe\\n\",\n+ \"from jax.util import safe_map\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"aqHqPjuBqrl9\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {}\n+ },\n+ \"source\": [\n+ \"def make_jaxpr2(fun):\\n\",\n+ \" \\n\",\n+ \" def pv_like(x):\\n\",\n+ \" # ShapedArrays are abstract values that carry around\\n\",\n+ \" # shape and dtype information\\n\",\n+ \" aval = ShapedArray(onp.shape(x), onp.result_type(x))\\n\",\n+ \" return pe.PartialVal((aval, core.unit))\\n\",\n+ \"\\n\",\n+ \" @wraps(fun)\\n\",\n+ \" def jaxpr_const_maker(*args, **kwargs):\\n\",\n+ \" # Set up fun for transformation\\n\",\n+ \" wrapped = lu.wrap_init(fun)\\n\",\n+ \" # Flatten input args\\n\",\n+ \" jax_args, in_tree = tree_util.tree_flatten((args, kwargs))\\n\",\n+ \" # Transform fun to accept flat args\\n\",\n+ \" # and return a flat list result\\n\",\n+ \" jaxtree_fun, out_tree = api_util.flatten_fun(wrapped, in_tree) \\n\",\n+ \" # Abstract and partial-val's flat args\\n\",\n+ \" pvals = safe_map(pv_like, jax_args)\\n\",\n+ \" # Trace function into Jaxpr\\n\",\n+ \" jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals) \\n\",\n+ \" return jaxpr, consts, (in_tree, out_tree())\\n\",\n+ \" return jaxpr_const_maker\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"CpTml2PTrzZ4\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"We won't go into too much detail about this function, but at a high level, it first flattens its arguments into a list, which are the abstracted and wrapped as partial values. the `pe.trace_to_jaxpr` function is used to then trace a function into a Jaxpr\\n\",\n+ \"from a list of partial value inputs.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"Tc1REN5aq_fH\",\n+ \"colab_type\": \"code\",\n+ \"outputId\": \"2e6f2833-5139-48ef-da3f-01ea9cd6a7d3\",\n+ \"colab\": {\n+ \"height\": 119\n+ }\n+ },\n+ \"source\": [\n+ \"def f(x):\\n\",\n+ \" return np.exp(np.tanh(x))\\n\",\n+ \"jaxpr, consts, _ = make_jaxpr2(f)(np.ones(5))\\n\",\n+ \"print(jaxpr)\\n\",\n+ \"print(consts)\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": [\n+ {\n+ \"output_type\": \"stream\",\n+ \"text\": [\n+ \"{ lambda ; ; a.\\n\",\n+ \" let b = tanh a\\n\",\n+ \" c = exp b\\n\",\n+ \" in [c] }\\n\",\n+ \"\\n\",\n+ \"()\\n\"\n+ ],\n+ \"name\": \"stdout\"\n+ }\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"WmZ3BcmZsbfR\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"This particular function doesn't have any example constants, but in general, this is how you both trace into a Jaxpr and extract the constants.\\n\",\n+ \"\\n\",\n+ \"## 2. Evaluating a Jaxpr\\n\",\n+ \"\\n\",\n+ \"\\n\",\n+ \"Before we write a custom Jaxpr interpreter, let's first implement the \\\"default\\\" interpreter, `eval_jaxpr`, which evaluates the Jaxpr as is, effectively running the original Python function. \\n\",\n+ \"\\n\",\n+ \"To do this, we first create an environment to store the values for each of the variables, and update the environment with each equation we evaluate in the Jaxpr.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"ACMxjIHStHwD\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {}\n+ },\n+ \"source\": [\n+ \"def eval_jaxpr(jaxpr, consts, *args):\\n\",\n+ \" env = {} # Mapping from variable -> value\\n\",\n+ \" \\n\",\n+ \" def read(var):\\n\",\n+ \" # Literals are values baked into the Jaxpr\\n\",\n+ \" if type(var) is core.Literal:\\n\",\n+ \" return var.val\\n\",\n+ \" return env[var]\\n\",\n+ \"\\n\",\n+ \" def write(var, val):\\n\",\n+ \" env[var] = val\\n\",\n+ \"\\n\",\n+ \" # Bind args and consts to environment\\n\",\n+ \" write(core.unitvar, core.unit)\\n\",\n+ \" safe_map(write, jaxpr.invars, args)\\n\",\n+ \" safe_map(write, jaxpr.constvars, consts)\\n\",\n+ \"\\n\",\n+ \" # Loop through equations and evaluate primitives using `bind`\\n\",\n+ \" for eqn in jaxpr.eqns:\\n\",\n+ \" # Read inputs to equation from environment\\n\",\n+ \" invals = safe_map(read, eqn.invars) \\n\",\n+ \" # `bind` is how a primitive is called\\n\",\n+ \" outvals = eqn.primitive.bind( \\n\",\n+ \" *invals, **eqn.params\\n\",\n+ \" )\\n\",\n+ \" # Primitives may return multiple outputs or not\\n\",\n+ \" if not eqn.primitive.multiple_results: \\n\",\n+ \" outvals = [outvals]\\n\",\n+ \" # Write the results of the primitive into the environment\\n\",\n+ \" safe_map(write, eqn.outvars, outvals) \\n\",\n+ \" # Read the final result of the Jaxpr from the environment\\n\",\n+ \" return safe_map(read, jaxpr.outvars) \"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"mGHPc3NruCFV\",\n+ \"colab_type\": \"code\",\n+ \"outputId\": \"3f459905-02ad-4f43-e70f-3db0a5ff58e4\",\n+ \"colab\": {\n+ \"height\": 51\n+ }\n+ },\n+ \"source\": [\n+ \"jaxpr, consts, _ = make_jaxpr2(f)(np.ones(5))\\n\",\n+ \"eval_jaxpr(jaxpr, consts, np.ones(5))\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": [\n+ {\n+ \"output_type\": \"execute_result\",\n+ \"data\": {\n+ \"text/plain\": [\n+ \"[DeviceArray([2.14168763, 2.14168763, 2.14168763, 2.14168763, 2.14168763],\\n\",\n+ \" dtype=float32)]\"\n+ ]\n+ },\n+ \"metadata\": {\n+ \"tags\": []\n+ },\n+ \"execution_count\": 8\n+ }\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"XhZhzbVBvAiT\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"Notice that `eval_jaxpr` will always return a list even if the original function does not. To \\\"unflatten\\\" the list into what the function was originally supposed to return, we can use the `out_tree` object returned by `trace`. \\n\",\n+ \"\\n\",\n+ \"Furthermore, this interpreter does not handle `subjaxprs`, which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/master/jax/core.py#L185-L212)) to see the edge cases that this interpreter does not cover.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"0vb2ZoGrCMM4\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"\\n\",\n+ \"## Custom `inverse` Jaxpr interpreter\\n\",\n+ \"\\n\",\n+ \"An `inverse` interpreter doesn't look too different from `eval_jaxpr`. We'll first set up the \\\"registry\\\" which will map primitives to their inverses. We'll then write a custom interpreter that looks up primitives in the registry.\\n\",\n+ \"\\n\",\n+ \"It turns out that this interpreter will also look similar to the \\\"transpose\\\" interpreter used in reverse-mode autodifferentiation [found here](https://github.com/google/jax/blob/master/jax/interpreters/ad.py#L141-L187).\\n\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"gSMIT2z1vUpO\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {}\n+ },\n+ \"source\": [\n+ \"inverse_registry = {}\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"JgrpMgDyCrC7\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"We'll now register inverses for some of the primitives. By convention, primitives in Jax end in `_p` and a lot of the popular ones live in `lax`.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"fUerorGkCqhw\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {}\n+ },\n+ \"source\": [\n+ \"inverse_registry[lax.exp_p] = np.log\\n\",\n+ \"inverse_registry[lax.tanh_p] = np.arctanh\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"mDtH_lYDC5WK\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"`inverse` will first trace the function, then custom-interpret the Jaxpr. Let's set up a simple skeleton.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"jGNfV6JJC1B3\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {}\n+ },\n+ \"source\": [\n+ \"def inverse(fun):\\n\",\n+ \" @wraps(fun)\\n\",\n+ \" def wrapped(*args, **kwargs):\\n\",\n+ \" # Since we assume unary functions, we won't\\n\",\n+ \" # worry about flattening and\\n\",\n+ \" # unflattening arguments\\n\",\n+ \" jaxpr, consts, _ = make_jaxpr2(fun)(*args, **kwargs)\\n\",\n+ \" out = inverse_jaxpr(jaxpr, consts, *args)\\n\",\n+ \" return out[0]\\n\",\n+ \" return wrapped\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"g6v6wV7SDM7g\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"Now we just need to define `inverse_jaxpr`, which will walk through the Jaxpr backward and invert primitives when it can.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"uUAd-L-BDKT5\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {}\n+ },\n+ \"source\": [\n+ \"def inverse_jaxpr(jaxpr, consts, *args):\\n\",\n+ \" env = {}\\n\",\n+ \" \\n\",\n+ \" def read(var):\\n\",\n+ \" if type(var) is core.Literal:\\n\",\n+ \" return var.val\\n\",\n+ \" return env[var]\\n\",\n+ \"\\n\",\n+ \" def write(var, val):\\n\",\n+ \" env[var] = val\\n\",\n+ \" # Args now correspond to Jaxpr outvars\\n\",\n+ \" write(core.unitvar, core.unit)\\n\",\n+ \" safe_map(write, jaxpr.outvars, args)\\n\",\n+ \" safe_map(write, jaxpr.constvars, consts)\\n\",\n+ \"\\n\",\n+ \" # Looping backward\\n\",\n+ \" for eqn in jaxpr.eqns[::-1]:\\n\",\n+ \" # outvars are now invars \\n\",\n+ \" invals = safe_map(read, eqn.outvars)\\n\",\n+ \" if eqn.primitive not in inverse_registry:\\n\",\n+ \" raise NotImplementedError(\\\"{} does not have registered inverse.\\\".format(\\n\",\n+ \" eqn.primitive\\n\",\n+ \" ))\\n\",\n+ \" # Assuming a unary function \\n\",\n+ \" outval = inverse_registry[eqn.primitive](*invals)\\n\",\n+ \" safe_map(write, eqn.invars, [outval])\\n\",\n+ \" return safe_map(read, jaxpr.invars)\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"M8i3wGbVERhA\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"That's it!\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"cjEKWso-D5Bu\",\n+ \"colab_type\": \"code\",\n+ \"outputId\": \"54e73a42-a908-448c-d6d5-e6d0fe9adbf9\",\n+ \"colab\": {\n+ \"height\": 71\n+ }\n+ },\n+ \"source\": [\n+ \"def f(x):\\n\",\n+ \" return np.exp(np.tanh(x))\\n\",\n+ \"f_inv = inverse(f)\\n\",\n+ \"print(f_inv(f(1.0)))\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": [\n+ {\n+ \"output_type\": \"stream\",\n+ \"text\": [\n+ \"0.9999999\\n\"\n+ ],\n+ \"name\": \"stdout\"\n+ }\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"Ny7Oo4WLHdXt\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"Importantly, you can trace through a Jaxpr interpreter.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"j6ov_rveHmTb\",\n+ \"colab_type\": \"code\",\n+ \"outputId\": \"a7a9b4be-f284-4e78-c469-d84e352d838d\",\n+ \"colab\": {\n+ \"height\": 238\n+ }\n+ },\n+ \"source\": [\n+ \"jax.make_jaxpr(inverse(f))(f(1.))\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": [\n+ {\n+ \"output_type\": \"execute_result\",\n+ \"data\": {\n+ \"text/plain\": [\n+ \"{ lambda ; ; a.\\n\",\n+ \" let b = log a\\n\",\n+ \" c = abs b\\n\",\n+ \" d = le c 1.0\\n\",\n+ \" e = add b 1.0\\n\",\n+ \" f = sub 1.0 b\\n\",\n+ \" g = div e f\\n\",\n+ \" h = log g\\n\",\n+ \" i = mul h 0.5\\n\",\n+ \" j = tie_in b nan\\n\",\n+ \" k = broadcast[ sizes=() ] j\\n\",\n+ \" l = select d i k\\n\",\n+ \" in [l] }\"\n+ ]\n+ },\n+ \"metadata\": {\n+ \"tags\": []\n+ },\n+ \"execution_count\": 14\n+ }\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"yfWVBsKwH0j6\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"That's all it takes to add a new transformation to a system, and you get composition with all the others for free! For example, we can use `jit`, `vmap`, and `grad` with `inverse`!\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"3tjNk21CH4yZ\",\n+ \"colab_type\": \"code\",\n+ \"outputId\": \"4c6d2090-0558-4171-8dce-0ea681ef6e53\",\n+ \"colab\": {\n+ \"height\": 51\n+ }\n+ },\n+ \"source\": [\n+ \"jit(vmap(grad(inverse(f))))((np.arange(5) + 1.) / 5.)\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": [\n+ {\n+ \"output_type\": \"execute_result\",\n+ \"data\": {\n+ \"text/plain\": [\n+ \"DeviceArray([ 0. , 15.58493137, 2.25512528, 1.31550276,\\n\",\n+ \" 1. ], dtype=float32)\"\n+ ]\n+ },\n+ \"metadata\": {\n+ \"tags\": []\n+ },\n+ \"execution_count\": 18\n+ }\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"APtG-u_6E4tK\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"source\": [\n+ \"## Exercises for the reader\\n\",\n+ \"\\n\",\n+ \"* Handle primitives with multiple arguments where inputs are partially known, for example `lax.add_p`, `lax.mul_p`.\\n\",\n+ \"* Handle `xla_call` and `pmap` primitives, which will not work with both `eval_jaxpr` and `inverse_jaxpr` as written.\"\n+ ]\n+ }\n+ ]\n+}\n" } ]
Python
Apache License 2.0
google/jax
Add custom interpreter notebook
260,510
28.10.2019 13:59:16
25,200
e2e4e6e955f0c8a2d4fa6082497ab4b9eae5fdd2
Fix title toc structure
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "new_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"# Your first interpreter: `invert`\"\n+ \"## Your first interpreter: `invert`\"\n]\n},\n{\n\"\\n\",\n\"The way we'll implement this is by 1) tracing `f` into a Jaxpr, then 2) interpret the Jaxpr *backwards*. Every time we hit a primitive, we'll look it up in a registry of invertible functions.\\n\",\n\"\\n\",\n- \"## 1. Tracing a function\\n\",\n+ \"### 1. Tracing a function\\n\",\n\"\\n\",\n\"We can't use `jax.make_jaxpr` for this, because we need to pull out constants created during the trace to pass into the Jaxpr. However, we can write a function that does something very similar to `make_jaxpr`.\"\n]\n\"source\": [\n\"This particular function doesn't have any example constants, but in general, this is how you both trace into a Jaxpr and extract the constants.\\n\",\n\"\\n\",\n- \"## 2. Evaluating a Jaxpr\\n\",\n+ \"### 2. Evaluating a Jaxpr\\n\",\n\"\\n\",\n\"\\n\",\n\"Before we write a custom Jaxpr interpreter, let's first implement the \\\"default\\\" interpreter, `eval_jaxpr`, which evaluates the Jaxpr as is, effectively running the original Python function. \\n\",\n},\n\"source\": [\n\"\\n\",\n- \"## Custom `inverse` Jaxpr interpreter\\n\",\n+ \"### Custom `inverse` Jaxpr interpreter\\n\",\n\"\\n\",\n\"An `inverse` interpreter doesn't look too different from `eval_jaxpr`. We'll first set up the \\\"registry\\\" which will map primitives to their inverses. We'll then write a custom interpreter that looks up primitives in the registry.\\n\",\n\"\\n\",\n" } ]
Python
Apache License 2.0
google/jax
Fix title toc structure
260,314
29.10.2019 00:03:36
14,400
7aa20ec273839c4505a7810577858ad9ec962e4c
support mxstep for ode
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ode.py", "new_path": "jax/experimental/ode.py", "diff": "@@ -209,21 +209,23 @@ def odeint(ofunc, y0, t, *args, **kwargs):\n**kwargs: Two relevant keyword arguments:\n'rtol': Relative local error tolerance for solver.\n'atol': Absolute local error tolerance for solver.\n+ 'mxstep': Maximum number of steps to take for each timepoint.\nReturns:\nIntegrated system values at each timepoint.\n\"\"\"\nrtol = kwargs.get('rtol', 1.4e-8)\natol = kwargs.get('atol', 1.4e-8)\n+ mxstep = kwargs.get('mxstep', np.inf)\n@functools.partial(jax.jit, static_argnums=(0,))\ndef _fori_body_fun(func, i, val):\n\"\"\"Internal fori_loop body to interpolate an integral at each timestep.\"\"\"\nt, cur_y, cur_f, cur_t, dt, last_t, interp_coeff, solution = val\n- cur_y, cur_f, cur_t, dt, last_t, interp_coeff = jax.lax.while_loop(\n- lambda x: x[2] < t[i],\n+ cur_y, cur_f, cur_t, dt, last_t, interp_coeff, _ = jax.lax.while_loop(\n+ lambda x: (x[2] < t[i]) & (x[-1] < mxstep),\nfunctools.partial(_while_body_fun, func),\n- (cur_y, cur_f, cur_t, dt, last_t, interp_coeff))\n+ (cur_y, cur_f, cur_t, dt, last_t, interp_coeff, 0.))\nrelative_output_time = (t[i] - last_t) / (cur_t - last_t)\nout_x = np.polyval(interp_coeff, relative_output_time)\n@@ -236,7 +238,7 @@ def odeint(ofunc, y0, t, *args, **kwargs):\n@functools.partial(jax.jit, static_argnums=(0,))\ndef _while_body_fun(func, x):\n\"\"\"Internal while_loop body to determine interpolation coefficients.\"\"\"\n- cur_y, cur_f, cur_t, dt, last_t, interp_coeff = x\n+ cur_y, cur_f, cur_t, dt, last_t, interp_coeff, j = x\nnext_t = cur_t + dt\nnext_y, next_f, next_y_error, k = runge_kutta_step(\nfunc, cur_y, cur_f, cur_t, dt)\n@@ -244,10 +246,11 @@ def odeint(ofunc, y0, t, *args, **kwargs):\nnew_interp_coeff = interp_fit_dopri(cur_y, next_y, k, dt)\ndt = optimal_step_size(dt, error_ratios)\n+ next_j = j + 1\nnew_rav, unravel = ravel_pytree(\n- (next_y, next_f, next_t, dt, cur_t, new_interp_coeff))\n+ (next_y, next_f, next_t, dt, cur_t, new_interp_coeff, next_j))\nold_rav, _ = ravel_pytree(\n- (cur_y, cur_f, cur_t, dt, last_t, interp_coeff))\n+ (cur_y, cur_f, cur_t, dt, last_t, interp_coeff, next_j))\nreturn unravel(np.where(np.all(error_ratios <= 1.),\nnew_rav,\n@@ -280,6 +283,7 @@ def vjp_odeint(ofunc, y0, t, *args, **kwargs):\n**kwargs: Two relevant keyword arguments:\n'rtol': Relative local error tolerance for solver.\n'atol': Absolute local error tolerance for solver.\n+ 'mxstep': Maximum number of steps to take for each timepoint.\nReturns:\nVJP function `vjp = vjp_all(g)` where `yt = ofunc(y, t, *args)`\n@@ -289,6 +293,7 @@ def vjp_odeint(ofunc, y0, t, *args, **kwargs):\n\"\"\"\nrtol = kwargs.get('rtol', 1.4e-8)\natol = kwargs.get('atol', 1.4e-8)\n+ mxstep = kwargs.get('mxstep', np.inf)\nflat_args, unravel_args = ravel_pytree(args)\nflat_func = lambda y, t, flat_args: ofunc(y, t, *unravel_args(flat_args))\n@@ -325,7 +330,8 @@ def vjp_odeint(ofunc, y0, t, *args, **kwargs):\nthis_tarray,\nflat_args,\nrtol=rtol,\n- atol=atol)\n+ atol=atol,\n+ mxstep=mxstep)\nvjp_y = aug_ans[1][state_len:2*state_len] + this_gim1\nvjp_t0 = aug_ans[1][2*state_len]\nvjp_args = aug_ans[1][2*state_len+1:]\n@@ -362,13 +368,13 @@ def vjp_odeint(ofunc, y0, t, *args, **kwargs):\nreturn tuple([result[-4], vjp_times] + list(result[-2]))\n- primals_out = odeint(flat_func, y0, t, flat_args)\n+ primals_out = odeint(flat_func, y0, t, flat_args, rtol=rtol, atol=atol, mxstep=mxstep)\nvjp_fun = lambda g: vjp_all(g, primals_out, t)\nreturn primals_out, vjp_fun\n-def build_odeint(ofunc, rtol=1.4e-8, atol=1.4e-8):\n+def build_odeint(ofunc, rtol=1.4e-8, atol=1.4e-8, mxstep=onp.inf):\n\"\"\"Return `f(y0, t, args) = odeint(ofunc(y, t, *args), y0, t, args)`.\nGiven the function ofunc(y, t, *args), return the jitted function\n@@ -383,14 +389,15 @@ def build_odeint(ofunc, rtol=1.4e-8, atol=1.4e-8):\nofunc: The function to be wrapped into an ODE integration.\nrtol: relative local error tolerance for solver.\natol: absolute local error tolerance for solver.\n+ mxstep: Maximum number of steps to take for each timepoint.\nReturns:\n`f(y0, t, args) = odeint(ofunc(y, t, *args), y0, t, args)`\n\"\"\"\nct_odeint = jax.custom_transforms(\n- lambda y0, t, *args: odeint(ofunc, y0, t, *args, rtol=rtol, atol=atol))\n+ lambda y0, t, *args: odeint(ofunc, y0, t, *args, rtol=rtol, atol=atol, mxstep=mxstep))\n- v = lambda y0, t, *args: vjp_odeint(ofunc, y0, t, *args, rtol=rtol, atol=atol)\n+ v = lambda y0, t, *args: vjp_odeint(ofunc, y0, t, *args, rtol=rtol, atol=atol, mxstep=mxstep)\njax.defvjp_all(ct_odeint, v)\nreturn jax.jit(ct_odeint)\n" } ]
Python
Apache License 2.0
google/jax
support mxstep for ode
260,411
29.10.2019 08:53:35
-3,600
8880e262b09dc85b8014c5dc98677eeb2f45ae7a
Use redthedocs links for Colabs Steer the documentation readers to readthedocs. Also, minor fixes to the wording of How_jax_primitives_work, suggested by Dougal
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -37,7 +37,7 @@ are instances of such transformations. Another is [`vmap`](#auto-vectorization-w\nfor automatic vectorization, with more to come.\nThis is a research project, not an official Google product. Expect bugs and\n-[sharp edges](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Common_Gotchas_in_JAX.ipynb).\n+[sharp edges](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html).\nPlease help by trying it out, [reporting\nbugs](https://github.com/google/jax/issues), and letting us know what you\nthink!\n@@ -83,17 +83,17 @@ open](https://github.com/google/jax) by a growing number of\n## Quickstart: Colab in the Cloud\nJump right in using a notebook in your browser, connected to a Google Cloud GPU. Here are some starter notebooks:\n-- [The basics: NumPy on accelerators, `grad` for differentiation, `jit` for compilation, and `vmap` for vectorization](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/quickstart.ipynb)\n+- [The basics: NumPy on accelerators, `grad` for differentiation, `jit` for compilation, and `vmap` for vectorization](https://jax.readthedocs.io/en/latest/notebooks/quickstart.html)\n- [Training a Simple Neural Network, with PyTorch Data Loading](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Neural_Network_and_Data_Loading.ipynb)\n- [Training a Simple Neural Network, with TensorFlow Dataset Data Loading](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/neural_network_with_tfds_data.ipynb)\nAnd for a deeper dive into JAX:\n-- [Common gotchas and sharp edges](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Common_Gotchas_in_JAX.ipynb)\n-- [The Autodiff Cookbook, Part 1: easy and powerful automatic differentiation in JAX](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/autodiff_cookbook.ipynb)\n-- [Directly using XLA in Python](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/XLA_in_Python.ipynb)\n-- [How JAX primitives work](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/How_JAX_primitives_work.ipynb)\n-- [MAML Tutorial with JAX](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/maml.ipynb)\n-- [Generative Modeling by Estimating Gradients of Data Distribution in JAX](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/score_matching.ipynb).\n+- [Common gotchas and sharp edges](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html)\n+- [The Autodiff Cookbook, Part 1: easy and powerful automatic differentiation in JAX](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html)\n+- [Directly using XLA in Python](https://jax.readthedocs.io/en/latest/notebooks/XLA_in_Python.html)\n+- [How JAX primitives work](https://jax.readthedocs.io/en/latest/notebooks/How_JAX_primitives_work.html)\n+- [MAML Tutorial with JAX](https://jax.readthedocs.io/en/latest/notebooks/maml.html)\n+- [Generative Modeling by Estimating Gradients of Data Distribution in JAX](https://jax.readthedocs.io/en/latest/notebooks/score_matching.html).\n## Installation\n@@ -239,7 +239,7 @@ print(\"Trained loss: {:0.2f}\".format(loss(weights, inputs, targets)))\n```\nTo see more, check out the [quickstart\n-notebook](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/quickstart.ipynb),\n+notebook](https://jax.readthedocs.io/en/latest/notebooks/quickstart.html),\na [simple MNIST classifier\nexample](https://github.com/google/jax/blob/master/examples/mnist_classifier.py)\nand the rest of the [JAX\n@@ -687,13 +687,13 @@ code to compile and end-to-end optimize much bigger functions.\n## Current gotchas\nFor a survey of current gotchas, with examples and explanations, we highly\n-recommend reading the [Gotchas Notebook](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Common_Gotchas_in_JAX.ipynb).\n+recommend reading the [Gotchas Notebook](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html).\nSome stand-out gotchas that might surprise NumPy users:\n1. JAX enforces single-precision (32-bit, e.g. `float32`) values by default, and\nto enable double-precision (64-bit, e.g. `float64`) one needs to set the\n`jax_enable_x64` variable **at startup** (or set the environment variable\n- `JAX_ENABLE_X64=True`, see [the Gotchas Notebook](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Common_Gotchas_in_JAX.ipynb#scrollTo=YTktlwTTMgFl))\n+ `JAX_ENABLE_X64=True`, see [the Gotchas Notebook](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#scrollTo=Double-(64bit)-precision))\n2. Some of NumPy's dtype promotion semantics involving a mix of Python scalars\nand NumPy types aren't preserved, namely `np.add(1, np.array([2],\nnp.float32)).dtype` is `float64` rather than `float32`.\n@@ -704,7 +704,7 @@ Some stand-out gotchas that might surprise NumPy users:\nreasons](https://github.com/google/jax/blob/master/design_notes/prng.md), and\nnon-reuse (linearity) is not yet checked.\n-See [the notebook](https://colab.research.google.com/github/google/jax/blob/master/docs/notebooks/Common_Gotchas_in_JAX.ipynb) for much more information.\n+See [the notebook](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html) for much more information.\n## Citing JAX\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/How_JAX_primitives_work.ipynb", "new_path": "docs/notebooks/How_JAX_primitives_work.ipynb", "diff": "\"### Forward differentiation\\n\",\n\"\\n\",\n\"JAX implements forward differentiation in the form of\\n\",\n- \"a Jacobian-vector product (see the [JAX autodiff cookbook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/autodiff_cookbook.ipynb#scrollTo=OMmi9cyhs1bj)).\\n\",\n+ \"a Jacobian-vector product (see the [JAX autodiff cookbook](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html#Jacobian-Matrix-and-Matrix-Jacobian-products)).\\n\",\n\"\\n\",\n\"If we attempt now to compute the `jvp` function we get an\\n\",\n\"error because we have not yet told JAX how to differentiate\\n\",\n\"```\\n\",\n\"\\n\",\n\"By construction, the tangent calculation is always linear in the input tangents. \\n\",\n- \"When the tangent calculation uses non-linear operations, such as multiplication,\\n\",\n- \"one or more of the operands is constant such that the computation is still linear in the non-constant arguments.\\n\",\n+ \"The only non-linear operator that may arise in the tangent calculation is multiplication,\\n\",\n+ \"but then one of the operands is constant.\\n\",\n\"\\n\",\n\"JAX will produce the reverse differentiation computation by processing the\\n\",\n\"JVP computation backwards. For each operation in the tangent computation,\\n\",\n\"of the operation:\\n\",\n\"```\\n\",\n\" # Initialize cotangents of inputs and intermediate vars\\n\",\n- \" xct = yct = act = bct = cct = 0\\n\",\n+ \" xct = yct = act = bct = cct = 0.\\n\",\n\" # Initialize cotangent of the output\\n\",\n\" fct = 1.\\n\",\n\" # Process \\\"ft = c + yt\\\"\\n\",\n\"```\\n\",\n\"\\n\",\n\"One can verify that this computation produces `xct = 4.` and `yct = 3.`, which \\n\",\n- \"are the partial derivatives of the function f. \\n\",\n+ \"are the partial derivatives of the function `f`. \\n\",\n\"\\n\",\n\"JAX knows for each primitive that may appear in a JVP calculation how to transpose it. Conceptually, if the primitive `p(x, y, z)` is linear in the arguments `y` and `z` for a constant value of `x`, e.g., `p(x, y, z) = y*cy + z*cz`, then the transposition of the primitive is:\\n\",\n\"```\\n\",\n\"p_transpose(out_ct, x, _, _) = (None, out_ct*cy, out_ct*cz)\\n\",\n\"```\\n\",\n\"\\n\",\n- \"Notice that `p_transpose` takes the cotangent of the output of the primitive and a value corresponding to each argument of the primitive. For the linear arguments, the transposition gets an undefined `_` value, and for the constant\\n\",\n+ \"Notice that `p_transpose` takes the cotangent of the output of the primitive and a value corresponding to each argument of the primitive. For the linear arguments, the transposition gets an undefined `_` value, and for the other\\n\",\n\"arguments it gets the actual constants. The transposition returns a cotangent value for each argument of the primitive, with the value `None` returned \\n\",\n\"for the constant arguments.\\n\",\n\"\\n\",\n" } ]
Python
Apache License 2.0
google/jax
Use redthedocs links for Colabs (#1572) Steer the documentation readers to readthedocs. Also, minor fixes to the wording of How_jax_primitives_work, suggested by Dougal
260,280
03.10.2019 16:01:41
10,800
a0cf482636e0d1435fd28da45ed27f36554b9d55
Adds new functionality to wraps
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -242,10 +242,45 @@ def _promote_args_like(op, *args):\ndef _constant_like(x, const):\nreturn onp.array(const, dtype=_dtype(x))\n+\n+def update_numpydoc(docstr, fun, op):\n+ '''Transforms the numpy docstring to remove references of\n+ parameters that are supported by the numpy version but not the JAX version'''\n+\n+ #Some numpy functions have an extra tab at the beginning of each line,\n+ #If this function is one of those we remove this extra tab from all the lines\n+ if docstr[:4] == ' ':\n+ lines = docstr.split('\\n')\n+ for idx, line in enumerate(lines):\n+ lines[idx] = line.replace(' ', '', 1)\n+ docstr = '\\n'.join(lines)\n+\n+ begin_idx = docstr.find(\"Parameters\")\n+ begin_idx = docstr.find(\"--\\n\", begin_idx) + 2\n+ end_idx = docstr.find(\"Returns\", begin_idx)\n+\n+ parameters = docstr[begin_idx:end_idx]\n+ param_list = parameters.replace('\\n ', '@@').split('\\n')\n+ for idx, p in enumerate(param_list):\n+ param = p[:p.find(' : ')].split(\", \")[0]\n+ if param not in op.__code__.co_varnames:\n+ param_list[idx] = ''\n+ param_list = [param for param in param_list if param != '']\n+ parameters = '\\n'.join(param_list).replace('@@', '\\n ')\n+ return docstr[:begin_idx + 1] + parameters + docstr[end_idx - 2:]\n+\n_numpy_signature_re = re.compile(r'^([\\w., ]+=)?\\s*[\\w\\.]+\\(.*\\)$')\n-def _wraps(fun):\n- \"\"\"Like functools.wraps but works with numpy.ufuncs.\"\"\"\n+def _wraps(fun, update_doc=True):\n+ \"\"\"Like functools.wraps but works with numpy.ufuncs.\n+ It is important that when wrapping numpy functions the parameters names\n+ in the original function and in the JAX version are the same\n+ Parameters:\n+ fun: The function being wrapped\n+ update_doc: whether to transform the numpy docstring to remove references of\n+ parameters that are supported by the numpy version but not the JAX version.\n+ If False, include the numpy docstring verbatim.\n+ \"\"\"\ndef wrap(op):\ntry:\n# Numpy doc comments have the form:\n@@ -268,25 +303,13 @@ def _wraps(fun):\nsummary = sections[i].strip()\nbreak\nbody = \"\\n\\n\".join(signatures + sections[i + 1:])\n+ if update_doc:\n+ body = update_numpydoc(body, fun, op)\ndocstr = (\n\"{summary}\\n\\nLAX-backend implementation of :func:`{fun}`. \"\n\"Original docstring below.\\n\\n{body}\".format(\nsummary=summary, fun=fun.__name__, body=body))\n- begin_idx = docstr.find(\"Parameters\")\n- begin_idx += docstr[begin_idx:].find(\"--\\n\") + 2\n- end_idx = docstr.find(\"Returns\")\n-\n- parameters = docstr[begin_idx:end_idx]\n- param_list = parameters.replace('\\n ', '@@').split('\\n')\n-\n- for idx, p in enumerate(param_list):\n- param, *_ = p.split(' : ')\n- if param not in op.__code__.co_varnames:\n- param_list[idx] = ''\n- param_list = [param for param in param_list if param != '']\n- parameters = '\\n'.join(param_list).replace('@@', '\\n ')\n- docstr = docstr[:begin_idx + 1] + parameters + docstr[end_idx - 2:]\nop.__name__ = fun.__name__\nop.__doc__ = docstr\n@@ -317,9 +340,9 @@ def _one_to_one_unop(numpy_fn, lax_fn, promote_like=False):\ndef _one_to_one_binop(numpy_fn, lax_fn, promote_like=False):\nif promote_like:\n- fn = lambda x, y: lax_fn(*_promote_args_like(numpy_fn, x, y))\n+ fn = lambda x1, x2: lax_fn(*_promote_args_like(numpy_fn, x1, x2))\nelse:\n- fn = lambda x, y: lax_fn(*_promote_args(numpy_fn.__name__, x, y))\n+ fn = lambda x1, x2: lax_fn(*_promote_args(numpy_fn.__name__, x1, x2))\nreturn _wraps(numpy_fn)(fn)\nabsolute = abs = _one_to_one_unop(onp.absolute, lax.abs)\n@@ -364,16 +387,16 @@ float_power = _one_to_one_binop(onp.float_power, lax.pow, True)\ndef _comparison_op(numpy_fn, lax_fn):\n- def fn(x, y):\n- x, y = _promote_args(numpy_fn.__name__, x, y)\n+ def fn(x1, x2):\n+ x1, x2 = _promote_args(numpy_fn.__name__, x1, x2)\n# Comparison on complex types are defined as a lexicographic ordering on\n# the (real, imag) pair.\n- if issubdtype(_dtype(x), complexfloating):\n- rx = lax.real(x)\n- ry = lax.real(y)\n- return lax.select(lax.eq(rx, ry), lax_fn(lax.imag(x), lax.imag(y)),\n+ if issubdtype(_dtype(x1), complexfloating):\n+ rx = lax.real(x1)\n+ ry = lax.real(x2)\n+ return lax.select(lax.eq(rx, ry), lax_fn(lax.imag(x1), lax.imag(x2)),\nlax_fn(rx, ry))\n- return lax_fn(x, y)\n+ return lax_fn(x1, x2)\nreturn _wraps(numpy_fn)(fn)\ngreater_equal = _comparison_op(onp.greater_equal, lax.ge)\n@@ -383,7 +406,7 @@ less = _comparison_op(onp.less, lax.lt)\ndef _logical_op(np_op, bitwise_op):\n- @_wraps(np_op)\n+ @_wraps(np_op, update_doc=False)\ndef op(*args):\nzero = lambda x: lax.full_like(x, shape=(), fill_value=0)\nargs = (x if onp.issubdtype(_dtype(x), onp.bool_) else lax.ne(x, zero(x))\n@@ -528,7 +551,7 @@ def remainder(x1, x2):\nlax.ne(lax.lt(trunc_mod, zero), lax.lt(x2, zero)), trunc_mod_not_zero)\nreturn lax.select(do_plus, lax.add(trunc_mod, x2), trunc_mod)\nmod = remainder\n-fmod = _wraps(onp.fmod)(lambda x, y: lax.rem(x, y))\n+fmod = _wraps(onp.fmod)(lambda x1, x2: lax.rem(x1, x2))\n@_wraps(onp.cbrt)\n@@ -560,17 +583,17 @@ radians = deg2rad\n@_wraps(onp.heaviside)\n-def heaviside(x, y):\n- x, y = _promote_to_result_dtype(onp.heaviside, x, y)\n- zero = lax._const(x, 0)\n- return where(lax.lt(x, zero), zero,\n- where(lax.gt(x, zero), lax._const(x, 1), y))\n+def heaviside(x1, x2):\n+ x1, x2 = _promote_to_result_dtype(onp.heaviside, x1, x2)\n+ zero = lax._const(x1, 0)\n+ return where(lax.lt(x1, zero), zero,\n+ where(lax.gt(x1, zero), lax._const(x1, 1), x2))\n@_wraps(onp.hypot)\n-def hypot(x, y):\n- x, y = _promote_to_result_dtype(onp.hypot, x, y)\n- return lax.sqrt(x*x + y*y)\n+def hypot(x1, x2):\n+ x1, x2 = _promote_to_result_dtype(onp.hypot, x1, x2)\n+ return lax.sqrt(x1*x1 + x2*x2)\n@_wraps(onp.reciprocal)\n@@ -579,7 +602,7 @@ def reciprocal(x):\nreturn lax.div(lax._const(x, 1), x)\n-@_wraps(onp.sinc)\n+@_wraps(onp.sinc, update_doc=False)\ndef sinc(x):\nx, = _promote_to_result_dtype(onp.sinc, x)\npi_x = lax.mul(lax._const(x, pi), x)\n@@ -629,9 +652,9 @@ def arctanh(x):\n@_wraps(onp.transpose)\n-def transpose(x, axes=None):\n- axes = onp.arange(ndim(x))[::-1] if axes is None else axes\n- return lax.transpose(x, axes)\n+def transpose(a, axes=None):\n+ axes = onp.arange(ndim(a))[::-1] if axes is None else axes\n+ return lax.transpose(a, axes)\n@_wraps(onp.rot90)\n@@ -677,13 +700,13 @@ conj = conjugate\n@_wraps(onp.imag)\n-def imag(x):\n- return lax.imag(x) if iscomplexobj(x) else zeros_like(x)\n+def imag(val):\n+ return lax.imag(val) if iscomplexobj(val) else zeros_like(val)\n@_wraps(onp.real)\n-def real(x):\n- return lax.real(x) if iscomplexobj(x) else x\n+def real(val):\n+ return lax.real(val) if iscomplexobj(val) else val\n@_wraps(onp.iscomplex)\n@@ -697,12 +720,12 @@ def isreal(x):\nreturn lax.eq(i, lax._const(i, 0))\n@_wraps(onp.angle)\n-def angle(x):\n- re = real(x)\n- im = imag(x)\n+def angle(z):\n+ re = real(z)\n+ im = imag(z)\ndtype = _dtype(re)\nif not issubdtype(dtype, inexact) or (\n- issubdtype(_dtype(x), floating) and ndim(x) == 0):\n+ issubdtype(_dtype(z), floating) and ndim(z) == 0):\ndtype = xla_bridge.canonicalize_dtype(float64)\nre = lax.convert_element_type(re, dtype)\nim = lax.convert_element_type(im, dtype)\n@@ -736,8 +759,8 @@ def diff(a, n=1, axis=-1,):\n@_wraps(onp.isrealobj)\n-def isrealobj(a):\n- return not iscomplexobj(a)\n+def isrealobj(x):\n+ return not iscomplexobj(x)\n@_wraps(onp.reshape)\n@@ -861,7 +884,7 @@ else:\n# The `jit` on `where` exists to avoid materializing constants in cases like\n# `np.where(np.zeros(1000), 7, 4)`. In op-by-op mode, we don't want to\n# materialize the broadcast forms of scalar arguments.\n-@_wraps(onp.where)\n+@_wraps(onp.where, update_doc=False)\n@jit\ndef where(condition, x=None, y=None):\nif x is None or y is None:\n@@ -933,7 +956,7 @@ def split(ary, indices_or_sections, axis=0):\nfor start, end in zip(split_indices[:-1], split_indices[1:])]\ndef _split_on_axis(onp_fun, axis):\n- @_wraps(onp_fun)\n+ @_wraps(onp_fun, update_doc=False)\ndef f(ary, indices_or_sections):\nreturn split(ary, indices_or_sections, axis=axis)\nreturn f\n@@ -965,7 +988,7 @@ def _dtype_info(dtype):\nreturn onp.finfo(dtype)\n-@_wraps(onp.round)\n+@_wraps(onp.round, update_doc=False)\ndef round(a, decimals=0):\ndtype = _dtype(a)\nif issubdtype(dtype, integer):\n@@ -1454,7 +1477,7 @@ def column_stack(tup):\nreturn concatenate(arrays, 1)\n-@_wraps(onp.atleast_1d)\n+@_wraps(onp.atleast_1d, update_doc=False)\ndef atleast_1d(*arys):\nif len(arys) == 1:\narr = array(arys[0])\n@@ -1463,7 +1486,7 @@ def atleast_1d(*arys):\nreturn [atleast_1d(arr) for arr in arys]\n-@_wraps(onp.atleast_2d)\n+@_wraps(onp.atleast_2d, update_doc=False)\ndef atleast_2d(*arys):\nif len(arys) == 1:\narr = array(arys[0])\n@@ -1472,7 +1495,7 @@ def atleast_2d(*arys):\nreturn [atleast_2d(arr) for arr in arys]\n-@_wraps(onp.atleast_3d)\n+@_wraps(onp.atleast_3d, update_doc=False)\ndef atleast_3d(*arys):\nif len(arys) == 1:\narr = array(arys[0])\n@@ -1628,7 +1651,7 @@ def _wrap_numpy_nullary_function(f):\n`f` cannot have any non-static array arguments.\n\"\"\"\n- @_wraps(f)\n+ @_wraps(f, update_doc=False)\ndef wrapper(*args, **kwargs):\nreturn asarray(f(*args, **kwargs))\nreturn wrapper\n@@ -1814,7 +1837,7 @@ def tril(m, k=0):\nreturn lax.select(lax.broadcast(mask, m_shape[:-2]), m, zeros_like(m))\n-@_wraps(onp.triu)\n+@_wraps(onp.triu, update_doc=False)\ndef triu(m, k=0):\nm_shape = shape(m)\nif len(m_shape) < 2:\n@@ -1852,7 +1875,7 @@ def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):\ndef _wrap_indices_function(f):\n- @_wraps(f)\n+ @_wraps(f, update_doc=False)\ndef wrapper(*args, **kwargs):\nreturn tuple(asarray(x) for x in f(*args, **kwargs))\nreturn wrapper\n@@ -2473,7 +2496,7 @@ def _take_along_axis(arr, indices, axis):\nreturn lax.gather(arr, gather_indices, dnums, tuple(slice_sizes))\n-@_wraps(getattr(onp, \"take_along_axis\", None))\n+@_wraps(getattr(onp, \"take_along_axis\", None), update_doc=False)\ndef take_along_axis(arr, indices, axis):\nreturn _take_along_axis(arr, indices, axis)\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/linalg.py", "new_path": "jax/scipy/linalg.py", "diff": "@@ -43,7 +43,7 @@ def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):\nreturn (cholesky(a, lower=lower), lower)\n-@_wraps(scipy.linalg.cho_solve)\n+@_wraps(scipy.linalg.cho_solve, update_doc=False)\ndef cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):\ndel overwrite_b, check_finite\nc, lower = c_and_lower\n@@ -159,7 +159,7 @@ def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):\nlu, pivots = lu_and_piv\nreturn _lu_solve(lu, pivots, b, trans)\n-@_wraps(scipy.linalg.lu)\n+@_wraps(scipy.linalg.lu, update_doc=False)\ndef lu(a, permute_l=False, overwrite_a=False, check_finite=True):\ndel overwrite_a, check_finite\na = np_linalg._promote_arg_dtypes(np.asarray(a))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/special.py", "new_path": "jax/scipy/special.py", "diff": "@@ -32,7 +32,7 @@ def gammaln(x):\nreturn lax.lgamma(x)\n-@_wraps(osp_special.digamma)\n+@_wraps(osp_special.digamma, update_doc=False)\ndef digamma(x):\nx, = _promote_args_like(osp_special.digamma, x)\nreturn lax.digamma(x)\n@@ -44,7 +44,7 @@ def erf(x):\nreturn lax.erf(x)\n-@_wraps(osp_special.erfc)\n+@_wraps(osp_special.erfc, update_doc=False)\ndef erfc(x):\nx, = _promote_args_like(osp_special.erfc, x)\nreturn lax.erfc(x)\n@@ -56,7 +56,7 @@ def erfinv(x):\nreturn lax.erf_inv(x)\n-@_wraps(osp_special.logit)\n+@_wraps(osp_special.logit, update_doc=False)\n@custom_transforms\ndef logit(x):\nx = asarray(x)\n@@ -64,7 +64,7 @@ def logit(x):\ndefjvp(logit, lambda g, ans, x: g / (x * (1 - x)))\n-@_wraps(osp_special.expit)\n+@_wraps(osp_special.expit, update_doc=False)\n@custom_transforms\ndef expit(x):\nx = asarray(x)\n@@ -93,7 +93,7 @@ def xlogy(x, y):\nreturn lax._safe_mul(x, lax.log(y))\n-@_wraps(osp_special.xlog1py)\n+@_wraps(osp_special.xlog1py, update_doc=False)\ndef xlog1py(x, y):\nx, y = _promote_args_like(osp_special.xlog1py, x, y)\nreturn lax._safe_mul(x, lax.log1p(y))\n@@ -107,7 +107,7 @@ def entr(x):\nlax.neg(xlogy(x, x)))\n-@_wraps(osp_special.multigammaln)\n+@_wraps(osp_special.multigammaln, update_doc=False)\ndef multigammaln(a, d):\na, = _promote_args_like(lambda a: osp_special.multigammaln(a, 1), a)\nd = lax.convert_element_type(d, lax.dtype(a))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/bernoulli.py", "new_path": "jax/scipy/stats/bernoulli.py", "diff": "@@ -24,7 +24,7 @@ from ...numpy import lax_numpy as np\nfrom ..special import xlogy, xlog1py\n-@np._wraps(osp_stats.bernoulli.logpmf)\n+@np._wraps(osp_stats.bernoulli.logpmf, update_doc=False)\ndef logpmf(k, p, loc=0):\nk, p, loc = np._promote_args_like(osp_stats.bernoulli.logpmf, k, p, loc)\nzero = np._constant_like(k, 0)\n@@ -34,6 +34,6 @@ def logpmf(k, p, loc=0):\nreturn np.where(np.logical_or(lax.lt(x, zero), lax.gt(x, one)),\n-np.inf, log_probs)\n-@np._wraps(osp_stats.bernoulli.pmf)\n+@np._wraps(osp_stats.bernoulli.pmf, update_doc=False)\ndef pmf(k, p, loc=0):\nreturn np.exp(pmf(k, p, loc))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/beta.py", "new_path": "jax/scipy/stats/beta.py", "diff": "@@ -25,7 +25,7 @@ from ...numpy.lax_numpy import (_promote_args_like, _constant_like, _wraps,\nfrom ..special import gammaln\n-@_wraps(osp_stats.beta.logpdf)\n+@_wraps(osp_stats.beta.logpdf, update_doc=False)\ndef logpdf(x, a, b, loc=0, scale=1):\nx, a, b, loc, scale = _promote_args_like(osp_stats.beta.logpdf, x, a, b, loc, scale)\none = _constant_like(x, 1)\n@@ -38,7 +38,7 @@ def logpdf(x, a, b, loc=0, scale=1):\nreturn where(logical_or(lax.gt(x, lax.add(loc, scale)),\nlax.lt(x, loc)), -inf, log_probs)\n-@_wraps(osp_stats.beta.pdf)\n+@_wraps(osp_stats.beta.pdf, update_doc=False)\ndef pdf(x, a, b, loc=0, scale=1):\nreturn lax.exp(logpdf(x, a, b, loc, scale))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/cauchy.py", "new_path": "jax/scipy/stats/cauchy.py", "diff": "@@ -23,7 +23,7 @@ from ... import lax\nfrom ...numpy.lax_numpy import _promote_args_like, _constant_like, _wraps\n-@_wraps(osp_stats.cauchy.logpdf)\n+@_wraps(osp_stats.cauchy.logpdf, update_doc=False)\ndef logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.cauchy.logpdf, x, loc, scale)\none = _constant_like(x, 1)\n@@ -32,6 +32,6 @@ def logpdf(x, loc=0, scale=1):\nnormalize_term = lax.log(lax.mul(pi, scale))\nreturn lax.neg(lax.add(normalize_term, lax.log1p(lax.mul(scaled_x, scaled_x))))\n-@_wraps(osp_stats.cauchy.pdf)\n+@_wraps(osp_stats.cauchy.pdf, update_doc=False)\ndef pdf(x, loc=0, scale=1):\nreturn lax.exp(logpdf(x, loc, scale))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/dirichlet.py", "new_path": "jax/scipy/stats/dirichlet.py", "diff": "@@ -29,7 +29,7 @@ def _is_simplex(x):\nreturn np.all(x > 0, axis=-1) & (x_sum <= 1) & (x_sum > 1 - 1e-6)\n-@np._wraps(osp_stats.dirichlet.logpdf)\n+@np._wraps(osp_stats.dirichlet.logpdf, update_doc=False)\ndef logpdf(x, alpha):\nargs = (onp.ones((0,), lax.dtype(x)), onp.ones((1,), lax.dtype(alpha)))\nto_dtype = lax.dtype(osp_stats.dirichlet.logpdf(*args))\n@@ -40,6 +40,6 @@ def logpdf(x, alpha):\nreturn np.where(_is_simplex(x), log_probs, -np.inf)\n-@np._wraps(osp_stats.dirichlet.pdf)\n+@np._wraps(osp_stats.dirichlet.pdf, update_doc=False)\ndef pdf(x, alpha):\nreturn lax.exp(logpdf(x, alpha))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/expon.py", "new_path": "jax/scipy/stats/expon.py", "diff": "@@ -23,7 +23,7 @@ from ... import lax\nfrom ...numpy.lax_numpy import _promote_args_like, _wraps, where, inf\n-@_wraps(osp_stats.expon.logpdf)\n+@_wraps(osp_stats.expon.logpdf, update_doc=False)\ndef logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.expon.logpdf, x, loc, scale)\nlog_scale = lax.log(scale)\n@@ -31,6 +31,6 @@ def logpdf(x, loc=0, scale=1):\nlog_probs = lax.neg(lax.add(linear_term, log_scale))\nreturn where(lax.lt(x, loc), -inf, log_probs)\n-@_wraps(osp_stats.expon.pdf)\n+@_wraps(osp_stats.expon.pdf, update_doc=False)\ndef pdf(x, loc=0, scale=1):\nreturn lax.exp(logpdf(x, loc, scale))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/gamma.py", "new_path": "jax/scipy/stats/gamma.py", "diff": "@@ -25,7 +25,7 @@ from ...numpy.lax_numpy import (_promote_args_like, _constant_like, _wraps,\nfrom ..special import gammaln\n-@_wraps(osp_stats.gamma.logpdf)\n+@_wraps(osp_stats.gamma.logpdf, update_doc=False)\ndef logpdf(x, a, loc=0, scale=1):\nx, a, loc, scale = _promote_args_like(osp_stats.gamma.logpdf, x, a, loc, scale)\none = _constant_like(x, 1)\n@@ -35,6 +35,6 @@ def logpdf(x, a, loc=0, scale=1):\nlog_probs = lax.sub(log_linear_term, shape_terms)\nreturn where(lax.lt(x, loc), -inf, log_probs)\n-@_wraps(osp_stats.gamma.pdf)\n+@_wraps(osp_stats.gamma.pdf, update_doc=False)\ndef pdf(x, a, loc=0, scale=1):\nreturn lax.exp(logpdf(x, a, loc, scale))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/laplace.py", "new_path": "jax/scipy/stats/laplace.py", "diff": "@@ -23,18 +23,18 @@ from ... import lax\nfrom ...numpy.lax_numpy import _promote_args_like, _constant_like, _wraps\n-@_wraps(osp_stats.laplace.logpdf)\n+@_wraps(osp_stats.laplace.logpdf, update_doc=False)\ndef logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.laplace.logpdf, x, loc, scale)\ntwo = _constant_like(x, 2)\nlinear_term = lax.div(lax.abs(lax.sub(x, loc)), scale)\nreturn lax.neg(lax.add(linear_term, lax.log(lax.mul(two, scale))))\n-@_wraps(osp_stats.laplace.pdf)\n+@_wraps(osp_stats.laplace.pdf, update_doc=False)\ndef pdf(x, loc=0, scale=1):\nreturn lax.exp(logpdf(x, loc, scale))\n-@_wraps(osp_stats.laplace.cdf)\n+@_wraps(osp_stats.laplace.cdf, update_doc=False)\ndef cdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.laplace.cdf, x, loc, scale)\nhalf = _constant_like(x, 0.5)\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/multivariate_normal.py", "new_path": "jax/scipy/stats/multivariate_normal.py", "diff": "@@ -25,7 +25,7 @@ from ...numpy.lax_numpy import dot, subtract, einsum\nfrom ...numpy.linalg import det, inv\n-@_wraps(osp_stats.multivariate_normal.logpdf)\n+@_wraps(osp_stats.multivariate_normal.logpdf, update_doc=False)\ndef logpdf(x, mean, cov):\n# TODO(mattjj): osp_stats.multivariate_normal.logpdf doesn't like being fed\n# empty-shape arrays, so we can't use _promote_args_like as written; consider\n@@ -47,6 +47,6 @@ def logpdf(x, mean, cov):\nquadratic = dot(dot(subtract(x, mean), inv(cov)), subtract(x, mean).T).astype(cov.dtype)\nreturn lax.div(lax.neg(lax.add(log_normalizer, quadratic)), two)\n-@_wraps(osp_stats.multivariate_normal.pdf)\n+@_wraps(osp_stats.multivariate_normal.pdf, update_doc=False)\ndef pdf(x, mean, cov):\nreturn lax.exp(logpdf(x, mean, cov))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/norm.py", "new_path": "jax/scipy/stats/norm.py", "diff": "@@ -24,7 +24,7 @@ from ... import numpy as np\nfrom ...numpy.lax_numpy import _promote_args_like, _constant_like, _wraps\nfrom .. import special\n-@_wraps(osp_stats.norm.logpdf)\n+@_wraps(osp_stats.norm.logpdf, update_doc=False)\ndef logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.norm.logpdf, x, loc, scale)\ntwo = _constant_like(x, 2)\n@@ -34,23 +34,23 @@ def logpdf(x, loc=0, scale=1):\nreturn lax.div(lax.neg(lax.add(log_normalizer, quadratic)), two)\n-@_wraps(osp_stats.norm.pdf)\n+@_wraps(osp_stats.norm.pdf, update_doc=False)\ndef pdf(x, loc=0, scale=1):\nreturn lax.exp(logpdf(x, loc, scale))\n-@_wraps(osp_stats.norm.cdf)\n+@_wraps(osp_stats.norm.cdf, update_doc=False)\ndef cdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.norm.cdf, x, loc, scale)\nreturn special.ndtr(lax.div(lax.sub(x, loc), scale))\n-@_wraps(osp_stats.norm.logcdf)\n+@_wraps(osp_stats.norm.logcdf, update_doc=False)\ndef logcdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.norm.logcdf, x, loc, scale)\nreturn special.log_ndtr(lax.div(lax.sub(x, loc), scale))\n-@_wraps(osp_stats.norm.ppf)\n+@_wraps(osp_stats.norm.ppf, update_doc=False)\ndef ppf(q, loc=0, scale=1):\nreturn np.array(special.ndtri(q) * scale + loc, 'float64')\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/pareto.py", "new_path": "jax/scipy/stats/pareto.py", "diff": "@@ -23,7 +23,7 @@ from ... import lax\nfrom ...numpy.lax_numpy import _promote_args_like, _constant_like, _wraps, inf, where\n-@_wraps(osp_stats.pareto.logpdf)\n+@_wraps(osp_stats.pareto.logpdf, update_doc=False)\ndef logpdf(x, b, loc=0, scale=1):\nx, b, loc, scale = _promote_args_like(osp_stats.pareto.logpdf, x, b, loc, scale)\none = _constant_like(x, 1)\n@@ -32,6 +32,6 @@ def logpdf(x, b, loc=0, scale=1):\nlog_probs = lax.neg(lax.add(normalize_term, lax.mul(lax.add(b, one), lax.log(scaled_x))))\nreturn where(lax.lt(x, lax.add(loc, scale)), -inf, log_probs)\n-@_wraps(osp_stats.pareto.pdf)\n+@_wraps(osp_stats.pareto.pdf, update_doc=False)\ndef pdf(x, b, loc=0, scale=1):\nreturn lax.exp(logpdf(x, b, loc, scale))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/t.py", "new_path": "jax/scipy/stats/t.py", "diff": "@@ -23,7 +23,7 @@ from ... import lax\nfrom ...numpy.lax_numpy import _promote_args_like, _constant_like, _wraps\n-@_wraps(osp_stats.t.logpdf)\n+@_wraps(osp_stats.t.logpdf, update_doc=False)\ndef logpdf(x, df, loc=0, scale=1):\nx, df, loc, scale = _promote_args_like(osp_stats.t.logpdf, x, df, loc, scale)\ntwo = _constant_like(x, 2)\n@@ -37,6 +37,6 @@ def logpdf(x, df, loc=0, scale=1):\nquadratic = lax.div(lax.mul(scaled_x, scaled_x), df)\nreturn lax.neg(lax.add(normalize_term, lax.mul(df_plus_one_over_two, lax.log1p(quadratic))))\n-@_wraps(osp_stats.t.pdf)\n+@_wraps(osp_stats.t.pdf, update_doc=False)\ndef pdf(x, df, loc=0, scale=1):\nreturn lax.exp(logpdf(x, df, loc, scale))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/uniform.py", "new_path": "jax/scipy/stats/uniform.py", "diff": "@@ -22,13 +22,13 @@ from ... import lax\nfrom ...numpy.lax_numpy import _promote_args_like, _wraps, where, inf, logical_or\n-@_wraps(osp_stats.uniform.logpdf)\n+@_wraps(osp_stats.uniform.logpdf, update_doc=False)\ndef logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.uniform.logpdf, x, loc, scale)\nlog_probs = lax.neg(lax.log(scale))\nreturn where(logical_or(lax.gt(x, lax.add(loc, scale)),\nlax.lt(x, loc)), -inf, log_probs)\n-@_wraps(osp_stats.uniform.pdf)\n+@_wraps(osp_stats.uniform.pdf, update_doc=False)\ndef pdf(x, loc=0, scale=1):\nreturn lax.exp(logpdf(x, loc, scale))\n" } ]
Python
Apache License 2.0
google/jax
Adds new functionality to wraps
260,335
28.10.2019 14:03:52
25,200
f5079a6281ec637a55f021cdfeffd48db7c3d471
improve vmap docstring and tree prefix errors fixes
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -565,21 +565,28 @@ def vmap(fun, in_axes=0, out_axes=0):\nArgs:\nfun: Function to be mapped over additional axes.\n- in_axes: Specifies which input axes to map over. Normally this is a tuple with\n- one axes specification for each function argument. An integer is interpreted\n- as a tuple with the same value for all arguments. One argument axes specification\n- can be an integer (0 means first dimension), None (means that the dimension is\n- broadcasted). If the argument is a tuple of values, then the axes specification\n- can be a matching tuple as well.\n-\n- out_axes: Specifies which output axes to map over. These may be integers,\n- `None`, or (possibly nested) tuples of integers or `None`.\n+ in_axes: A nonnegative integer, None, or (nested) standard Python container\n+ (tuple/list/dict) thereof specifying which input array axes to map over.\n+ If each positional argument to ``fun`` is an array, then ``in_axes`` can\n+ be a nonnegative integer, a None, or a tuple of integers and Nones with\n+ length equal to the number of positional arguments to ``fun``. An integer\n+ or None indicates which array axis to map over for all arguments (with\n+ None indicating not to map any axis), and a tuple indicates which axis to\n+ map for each corresponding positional argument. More generally, if the\n+ positinal arguments to ``fun`` are container types, the corresponding\n+ element of ``in_axes`` can itself be a matching container, so that\n+ distinct array axes can be mapped for different container elements. The\n+ constraint is that ``in_axes`` must be a container tree prefix of the\n+ positional argument tuple passed to ``fun``.\n+ out_axes: A nonnegative integer, None, or (nested) standard Python container\n+ (tuple/list/dict) thereof indicating where the mapped axis should appear\n+ in the output.\nReturns:\n- Batched/vectorized version of `fun` with arguments that correspond to those\n- of `fun`, but with extra array axes at positions indicated by `in_axes`, and\n- a return value that corresponds to that of `fun`, but with extra array axes\n- at positions indicated by `out_axes`.\n+ Batched/vectorized version of ``fun`` with arguments that correspond to\n+ those of ``fun``, but with extra array axes at positions indicated by\n+ ``in_axes``, and a return value that corresponds to that of ``fun``, but\n+ with extra array axes at positions indicated by ``out_axes``.\nFor example, we can implement a matrix-matrix product using a vector dot\nproduct:\n@@ -588,12 +595,47 @@ def vmap(fun, in_axes=0, out_axes=0):\n>>> mv = vmap(vv, (0, None), 0) # ([b,a], [a]) -> [b] (b is the mapped axis)\n>>> mm = vmap(mv, (None, 1), 1) # ([b,a], [a,c]) -> [b,c] (c is the mapped axis)\n- Here we use `[a,b]` to indicate an array with shape (a,b). Here are some\n+ Here we use ``[a,b]`` to indicate an array with shape (a,b). Here are some\nvariants:\n>>> mv1 = vmap(vv, (0, 0), 0) # ([b,a], [b,a]) -> [b] (b is the mapped axis)\n>>> mv2 = vmap(vv, (0, 1), 0) # ([b,a], [a,b]) -> [b] (b is the mapped axis)\n>>> mm2 = vmap(mv2, (1, 1), 0) # ([b,c,a], [a,c,b]) -> [c,b] (c is the mapped axis)\n+\n+ Here's an example of using container types in ``in_axes`` to specify which\n+ axes of the container elements to map over:\n+\n+ >>> A, B, C, D = 2, 3, 4, 5\n+ >>> x = np.ones((A, B))\n+ >>> y = np.ones((B, C))\n+ >>> z = np.ones((C, D))\n+ >>> def foo(tree_arg):\n+ ... x, (y, z) = tree_arg\n+ ... return np.dot(x, np.dot(y, z))\n+ >>> tree = (x, (y, z))\n+ >>> print(foo(tree))\n+ [[12. 12. 12. 12. 12.]\n+ [12. 12. 12. 12. 12.]]\n+ >>> from jax import vmap\n+ >>> K = 6 # batch size\n+ >>> x = np.ones((K, A, B)) # batch axis in different locations\n+ >>> y = np.ones((B, K, C))\n+ >>> z = np.ones((C, D, K))\n+ >>> tree = (x, (y, z))\n+ >>> vfoo = vmap(foo, in_axes=((0, (1, 2)),))\n+ >>> print(vfoo(tree))\n+ [[[12. 12. 12. 12. 12.]\n+ [12. 12. 12. 12. 12.]]\n+ [[12. 12. 12. 12. 12.]\n+ [12. 12. 12. 12. 12.]]\n+ [[12. 12. 12. 12. 12.]\n+ [12. 12. 12. 12. 12.]]\n+ [[12. 12. 12. 12. 12.]\n+ [12. 12. 12. 12. 12.]]\n+ [[12. 12. 12. 12. 12.]\n+ [12. 12. 12. 12. 12.]]\n+ [[12. 12. 12. 12. 12.]\n+ [12. 12. 12. 12. 12.]]]\n\"\"\"\ndocstr = (\"Vectorized version of {fun}. Takes similar arguments as {fun} \"\n\"but with additional array axes over which {fun} is mapped.\")\n@@ -620,7 +662,12 @@ def _flatten_axes(treedef, axis_tree):\ndummy = tree_unflatten(treedef, [object()] * treedef.num_leaves)\naxes = []\nadd_leaves = lambda i, x: axes.extend([i] * len(tree_flatten(x)[0]))\n+ try:\ntree_multimap(add_leaves, _replace_nones(axis_tree), dummy)\n+ except ValueError:\n+ msg = (\"axes specification must be a tree prefix of the corresponding \"\n+ \"value, got specification {} for value {}.\")\n+ raise ValueError(msg.format(axis_tree, treedef))\naxes = [None if a is _none_proxy else a for a in axes]\nreturn axes\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1093,6 +1093,12 @@ class APITest(jtu.JaxTestCase):\nb = np.dot(a + np.eye(a.shape[0]), real_x)\nprint(gf(a, b)) # doesn't crash\n+ def test_vmap_in_axes_tree_prefix_error(self):\n+ # https://github.com/google/jax/issues/795\n+ jtu.check_raises_regexp(\n+ lambda: api.vmap(lambda x: x, in_axes=(0, 0))(np.ones(3)),\n+ ValueError, \"axes specification must be a tree prefix\")\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
improve vmap docstring and tree prefix errors fixes #795
260,335
28.10.2019 15:20:49
25,200
cbadfd41cecc59c499bfbe8b86c7dcc2ad279255
allow unmapped vmap args to be arbitrary objects fixes
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -52,7 +52,8 @@ def batch_fun(fun, in_vals, in_dims):\n@transformation_with_aux\ndef batch_subtrace(master, in_dims, *in_vals):\ntrace = BatchTrace(master, core.cur_sublevel())\n- in_tracers = map(partial(BatchTracer, trace), in_vals, in_dims)\n+ in_tracers = [BatchTracer(trace, val, dim) if dim is not None else val\n+ for val, dim in zip(in_vals, in_dims)]\nouts = yield in_tracers, {}\nout_tracers = map(trace.full_raise, outs)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1099,6 +1099,13 @@ class APITest(jtu.JaxTestCase):\nlambda: api.vmap(lambda x: x, in_axes=(0, 0))(np.ones(3)),\nValueError, \"axes specification must be a tree prefix\")\n+ def test_vmap_objects_issue_183(self):\n+ # https://github.com/google/jax/issues/183\n+ fun = lambda f, x: f(x)\n+ vfun = api.vmap(fun, (None, 0))\n+ ans = vfun(lambda x: x + 1, np.arange(3))\n+ self.assertAllClose(ans, onp.arange(1, 4), check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
allow unmapped vmap args to be arbitrary objects fixes #183
260,559
30.10.2019 19:29:56
25,200
39daf07de340bcfb021571b25a9451db31887bfa
Add trivial implementations of eigvals/eigvalsh * Add trivial implementations of eigvals/eigvalsh The implementations simply delegate to eig/eigh. * Enable eigvalsh test on TPU/GPU
[ { "change_type": "MODIFY", "old_path": "jax/numpy/linalg.py", "new_path": "jax/numpy/linalg.py", "diff": "@@ -109,6 +109,12 @@ def eig(a):\nreturn w, vr\n+@_wraps(onp.linalg.eigvals)\n+def eigvals(a):\n+ w, _ = eig(a)\n+ return w\n+\n+\n@_wraps(onp.linalg.eigh)\ndef eigh(a, UPLO=None, symmetrize_input=True):\nif UPLO is None or UPLO == \"L\":\n@@ -124,6 +130,12 @@ def eigh(a, UPLO=None, symmetrize_input=True):\nreturn w, v\n+@_wraps(onp.linalg.eigvalsh)\n+def eigvalsh(a, UPLO='L'):\n+ w, _ = eigh(a, UPLO)\n+ return w\n+\n+\n@_wraps(onp.linalg.inv)\ndef inv(a):\nif np.ndim(a) < 2 or a.shape[-1] != a.shape[-2]:\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -166,6 +166,25 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nself._CompileAndCheck(partial(np.linalg.eig), args_maker,\ncheck_dtypes=True, rtol=1e-3)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype)),\n+ \"shape\": shape, \"dtype\": dtype, \"rng\": rng}\n+ for shape in [(4, 4), (5, 5), (50, 50)]\n+ for dtype in float_types + complex_types\n+ for rng in [jtu.rand_default()]))\n+ # TODO: enable when there is an eigendecomposition implementation\n+ # for GPU/TPU.\n+ @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ def testEigvals(self, shape, dtype, rng):\n+ _skip_if_unsupported_type(dtype)\n+ n = shape[-1]\n+ args_maker = lambda: [rng(shape, dtype)]\n+ a, = args_maker()\n+ w1, _ = np.linalg.eig(a)\n+ w2 = np.linalg.eigvals(a)\n+ self.assertAllClose(w1, w2, check_dtypes=True)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n\"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n@@ -217,6 +236,23 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nself._CompileAndCheck(partial(np.linalg.eigh, UPLO=uplo), args_maker,\ncheck_dtypes=True, rtol=1e-3)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype)),\n+ \"shape\": shape, \"dtype\": dtype, \"rng\": rng}\n+ for shape in [(4, 4), (5, 5), (50, 50)]\n+ for dtype in float_types + complex_types\n+ for rng in [jtu.rand_default()]))\n+ def testEigvalsh(self, shape, dtype, rng):\n+ _skip_if_unsupported_type(dtype)\n+ n = shape[-1]\n+ def args_maker():\n+ a = rng((n, n), dtype)\n+ a = (a + onp.conj(a.T)) / 2\n+ return [a]\n+ self._CheckAgainstNumpy(onp.linalg.eigvalsh, np.linalg.eigvalsh, args_maker,\n+ check_dtypes=True, tol=1e-3)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n\"_shape={}_lower={}\".format(jtu.format_shape_dtype_string(shape, dtype),\n" } ]
Python
Apache License 2.0
google/jax
Add trivial implementations of eigvals/eigvalsh (#1604) * Add trivial implementations of eigvals/eigvalsh The implementations simply delegate to eig/eigh. * Enable eigvalsh test on TPU/GPU
260,335
30.10.2019 17:31:37
25,200
eae47b2330b445d07a79fb2173084d3f13d59ebb
improve vmap error messages fixes
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -647,12 +647,43 @@ def vmap(fun, in_axes=0, out_axes=0):\n\"or a (nested) tuple of those types, got {} and {} respectively.\")\nraise TypeError(msg.format(type(in_axes), type(out_axes)))\n+ def _check_axis_sizes(tree, vals, dims):\n+ try:\n+ sizes, = {x.shape[d] for x, d in zip(vals, dims) if d is not None}\n+ except ValueError:\n+ msg = \"vmap got inconsistent sizes for array axes to be mapped:\\n{}\"\n+ # we switch the error message based on whether args is a tuple of arrays,\n+ # in which case we can produce an error message based on argument indices,\n+ # or if it has nested containers.\n+ # TODO(mattjj,phawkins): add a way to inspect pytree kind more directly\n+ if tree == tree_flatten((core.unit,) * tree.num_leaves)[1]:\n+ lines1 = [\"arg {} has shape {} and axis {} is to be mapped\"\n+ .format(i, x.shape, d) for i, (x, d) in enumerate(zip(vals, dims))]\n+ sizes = collections.defaultdict(list)\n+ for i, (x, d) in enumerate(zip(vals, dims)):\n+ if d is not None:\n+ sizes[x.shape[d]].append(i)\n+ lines2 = [\"{} {} {} {} to be mapped of size {}\".format(\n+ \"args\" if len(idxs) > 1 else \"arg\",\n+ \", \".join(map(str, idxs)),\n+ \"have\" if len(idxs) > 1 else \"has\",\n+ \"axes\" if len(idxs) > 1 else \"an axis\",\n+ size)\n+ for size, idxs in sizes.items()]\n+ raise ValueError(msg.format(\"\\n\".join(lines1 + [\"so\"] + lines2)))\n+ else:\n+ sizes = [x.shape[d] if d is not None else None for x, d in zip(vals, dims)]\n+ sizes = tree_unflatten(tree, sizes)\n+ raise ValueError(msg.format(\"the tree of axis sizes is:\\n{}\".format(sizes)))\n+\n@wraps(fun, docstr=docstr)\ndef batched_fun(*args):\nargs_flat, in_tree = tree_flatten(args)\nf = lu.wrap_init(fun)\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\n- out_flat = batching.batch(flat_fun, args_flat, _flatten_axes(in_tree, in_axes),\n+ in_axes_flat = _flatten_axes(in_tree, in_axes)\n+ _check_axis_sizes(in_tree, args_flat, in_axes_flat)\n+ out_flat = batching.batch(flat_fun, args_flat, in_axes_flat,\nlambda: _flatten_axes(out_tree(), out_axes))\nreturn tree_unflatten(out_tree(), out_flat)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -38,8 +38,8 @@ map = safe_map\ndef batch(fun, in_vals, in_dims, out_dim_dests):\n- out_vals, out_dims = batch_fun(fun, in_vals, in_dims)\nsize, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\n+ out_vals, out_dims = batch_fun(fun, in_vals, in_dims)\nreturn map(partial(matchaxis, size), out_dims, out_dim_dests(), out_vals)\ndef batch_fun(fun, in_vals, in_dims):\n@@ -163,8 +163,8 @@ def get_primitive_batcher(p):\ntry:\nreturn primitive_batchers[p]\nexcept KeyError:\n- raise NotImplementedError(\n- \"Batching rule for '{}' not implemented\".format(p))\n+ msg = \"Batching rule for '{}' not implemented\"\n+ raise NotImplementedError(msg.format(p))\ndef defvectorized(prim):\nprimitive_batchers[prim] = partial(vectorized_batcher, prim)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1106,6 +1106,29 @@ class APITest(jtu.JaxTestCase):\nans = vfun(lambda x: x + 1, np.arange(3))\nself.assertAllClose(ans, onp.arange(1, 4), check_dtypes=False)\n+ def test_vmap_error_message_issue_705(self):\n+ # https://github.com/google/jax/issues/705\n+ def h(a, b):\n+ return np.sum(a) + np.sum(b)\n+\n+ X = onp.random.randn(10, 4)\n+ U = onp.random.randn(10, 2)\n+ self.assertRaisesRegex(\n+ ValueError,\n+ \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n+ \"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\\n\"\n+ \"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\\n\"\n+ \"so\\n\"\n+ \"arg 0 has an axis to be mapped of size 10\\n\"\n+ \"arg 1 has an axis to be mapped of size 2\",\n+ lambda: api.vmap(h, in_axes=(0, 1))(X, U))\n+\n+ self.assertRaisesRegex(\n+ ValueError,\n+ \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n+ \"the tree of axis sizes is:\\n\",\n+ lambda: api.vmap(h, in_axes=(0, 1))(X, [U, U]))\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
improve vmap error messages fixes #705
260,335
31.10.2019 11:22:23
25,200
9d94c423232d9e8c7305d56f399f60332f31537e
Update jax/api.py
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -573,7 +573,7 @@ def vmap(fun, in_axes=0, out_axes=0):\nor None indicates which array axis to map over for all arguments (with\nNone indicating not to map any axis), and a tuple indicates which axis to\nmap for each corresponding positional argument. More generally, if the\n- positinal arguments to ``fun`` are container types, the corresponding\n+ positional arguments to ``fun`` are container types, the corresponding\nelement of ``in_axes`` can itself be a matching container, so that\ndistinct array axes can be mapped for different container elements. The\nconstraint is that ``in_axes`` must be a container tree prefix of the\n" } ]
Python
Apache License 2.0
google/jax
Update jax/api.py Co-Authored-By: Stephan Hoyer <shoyer@google.com>
260,335
31.10.2019 11:57:37
25,200
14acca7b519b3b7da89c563aee76b44254a78c42
address reviewer comments, fix test error
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -572,12 +572,11 @@ def vmap(fun, in_axes=0, out_axes=0):\nlength equal to the number of positional arguments to ``fun``. An integer\nor None indicates which array axis to map over for all arguments (with\nNone indicating not to map any axis), and a tuple indicates which axis to\n- map for each corresponding positional argument. More generally, if the\n- positinal arguments to ``fun`` are container types, the corresponding\n- element of ``in_axes`` can itself be a matching container, so that\n- distinct array axes can be mapped for different container elements. The\n- constraint is that ``in_axes`` must be a container tree prefix of the\n- positional argument tuple passed to ``fun``.\n+ map for each corresponding positional argument. If the positinal arguments\n+ to ``fun`` are container types, the corresponding element of ``in_axes``\n+ can itself be a matching container, so that distinct array axes can be\n+ mapped for different container elements. ``in_axes`` must be a container\n+ tree prefix of the positional argument tuple passed to ``fun``.\nout_axes: A nonnegative integer, None, or (nested) standard Python container\n(tuple/list/dict) thereof indicating where the mapped axis should appear\nin the output.\n@@ -623,19 +622,8 @@ def vmap(fun, in_axes=0, out_axes=0):\n>>> z = np.ones((C, D, K))\n>>> tree = (x, (y, z))\n>>> vfoo = vmap(foo, in_axes=((0, (1, 2)),))\n- >>> print(vfoo(tree))\n- [[[12. 12. 12. 12. 12.]\n- [12. 12. 12. 12. 12.]]\n- [[12. 12. 12. 12. 12.]\n- [12. 12. 12. 12. 12.]]\n- [[12. 12. 12. 12. 12.]\n- [12. 12. 12. 12. 12.]]\n- [[12. 12. 12. 12. 12.]\n- [12. 12. 12. 12. 12.]]\n- [[12. 12. 12. 12. 12.]\n- [12. 12. 12. 12. 12.]]\n- [[12. 12. 12. 12. 12.]\n- [12. 12. 12. 12. 12.]]]\n+ >>> print(vfoo(tree)).shape\n+ (6, 2, 5)\n\"\"\"\ndocstr = (\"Vectorized version of {fun}. Takes similar arguments as {fun} \"\n\"but with additional array axes over which {fun} is mapped.\")\n@@ -648,8 +636,9 @@ def vmap(fun, in_axes=0, out_axes=0):\nraise TypeError(msg.format(type(in_axes), type(out_axes)))\ndef _check_axis_sizes(tree, vals, dims):\n+ mapped_axis_sizes = {x.shape[d] for x, d in zip(vals, dims) if d is not None}\ntry:\n- sizes, = {x.shape[d] for x, d in zip(vals, dims) if d is not None}\n+ sizes, = mapped_axis_sizes\nexcept ValueError:\nmsg = \"vmap got inconsistent sizes for array axes to be mapped:\\n{}\"\n# we switch the error message based on whether args is a tuple of arrays,\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1099,14 +1099,14 @@ class APITest(jtu.JaxTestCase):\nlambda: api.vmap(lambda x: x, in_axes=(0, 0))(np.ones(3)),\nValueError, \"axes specification must be a tree prefix\")\n- def test_vmap_objects_issue_183(self):\n+ def test_vmap_unbatched_object_passthrough_issue_183(self):\n# https://github.com/google/jax/issues/183\nfun = lambda f, x: f(x)\nvfun = api.vmap(fun, (None, 0))\nans = vfun(lambda x: x + 1, np.arange(3))\nself.assertAllClose(ans, onp.arange(1, 4), check_dtypes=False)\n- def test_vmap_error_message_issue_705(self):\n+ def test_vmap_mismatched_axis_sizes_error_message_issue_705(self):\n# https://github.com/google/jax/issues/705\ndef h(a, b):\nreturn np.sum(a) + np.sum(b)\n@@ -1126,7 +1126,8 @@ class APITest(jtu.JaxTestCase):\nself.assertRaisesRegex(\nValueError,\n\"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n- \"the tree of axis sizes is:\\n\",\n+ \"the tree of axis sizes is:\\n\"\n+ \"\\(10, \\[2, 2\\]\\)\",\nlambda: api.vmap(h, in_axes=(0, 1))(X, [U, U]))\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -369,20 +369,22 @@ class BatchingTest(jtu.JaxTestCase):\ndef testDynamicSlice(self):\n# test dynamic_slice via numpy indexing syntax\n- x = onp.arange(30).reshape((10, 3))\n+ # see https://github.com/google/jax/issues/1613 for an explanation of why we\n+ # need to use np rather than onp to create x and idx\n+ x = np.arange(30).reshape((10, 3))\nans = vmap(lambda x, i: x[i], in_axes=(0, None))(x, 1)\nexpected = x[:, 1]\nself.assertAllClose(ans, expected, check_dtypes=False)\n- idx = onp.array([0, 1, 2, 1, 0] * 2)\n+ idx = np.array([0, 1, 2, 1, 0] * 2)\nans = vmap(lambda x, i: x[i], in_axes=(0, 0))(x, idx)\nexpected = x[onp.arange(10), idx]\nself.assertAllClose(ans, expected, check_dtypes=False)\n- x = onp.arange(3)\n- idx = onp.array([0, 1, 2, 1, 0] * 2)\n+ x = np.arange(3)\n+ idx = np.array([0, 1, 2, 1, 0] * 2)\nans = vmap(lambda x, i: x[i], in_axes=(None, 0))(x, idx)\nexpected = x[idx]\nself.assertAllClose(ans, expected, check_dtypes=False)\n" } ]
Python
Apache License 2.0
google/jax
address reviewer comments, fix test error
260,335
31.10.2019 13:04:12
25,200
213b899ef18e3426d421327acadc523609f39fee
check full error message
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1097,7 +1097,11 @@ class APITest(jtu.JaxTestCase):\n# https://github.com/google/jax/issues/795\njtu.check_raises_regexp(\nlambda: api.vmap(lambda x: x, in_axes=(0, 0))(np.ones(3)),\n- ValueError, \"axes specification must be a tree prefix\")\n+ ValueError,\n+ \"axes specification must be a tree prefix of the corresponding \"\n+ r\"value, got specification \\(0, 0\\) for value \"\n+ r\"PyTreeDef\\(tuple, \\[\\*\\]\\).\"\n+ )\ndef test_vmap_unbatched_object_passthrough_issue_183(self):\n# https://github.com/google/jax/issues/183\n" } ]
Python
Apache License 2.0
google/jax
check full error message
260,335
31.10.2019 13:20:32
25,200
d09571ebceb8f6a04830a497727768260ddd0bb6
add test case per reviewer comment
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1117,6 +1117,7 @@ class APITest(jtu.JaxTestCase):\nX = onp.random.randn(10, 4)\nU = onp.random.randn(10, 2)\n+\nself.assertRaisesRegex(\nValueError,\n\"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n@@ -1127,6 +1128,17 @@ class APITest(jtu.JaxTestCase):\n\"arg 1 has an axis to be mapped of size 2\",\nlambda: api.vmap(h, in_axes=(0, 1))(X, U))\n+ self.assertRaisesRegex(\n+ ValueError,\n+ \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n+ r\"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n+ r\"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\" \"\\n\"\n+ r\"arg 2 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n+ \"so\\n\"\n+ \"args 0, 2 have axes to be mapped of size 10\\n\"\n+ \"arg 1 has an axis to be mapped of size 2\",\n+ lambda: api.vmap(lambda x, y, z: None, in_axes=(0, 1, 0))(X, U, X))\n+\nself.assertRaisesRegex(\nValueError,\n\"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n" } ]
Python
Apache License 2.0
google/jax
add test case per reviewer comment
260,335
31.10.2019 14:09:12
25,200
979b38352f23ed2c822481900558867fe7c5baf4
make vmap structured axes work for any pytree
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -47,7 +47,8 @@ from .core import eval_jaxpr\nfrom .api_util import (wraps, flatten_fun, apply_flat_fun, flatten_fun_nokwargs,\nflatten_fun_nokwargs2, apply_flat_fun_nokwargs)\nfrom .tree_util import (tree_map, tree_flatten, tree_unflatten, tree_structure,\n- tree_transpose, tree_leaves, tree_multimap)\n+ tree_transpose, tree_leaves, tree_multimap,\n+ _replace_nones)\nfrom .util import (unzip2, unzip3, curry, partial, safe_map, safe_zip,\nWrapHashably, Hashable, prod, split_list)\nfrom .lib.xla_bridge import (canonicalize_dtype, device_count,\n@@ -678,27 +679,22 @@ def vmap(fun, in_axes=0, out_axes=0):\nreturn batched_fun\n+# TODO(mattjj,phawkins): improve this implementation\ndef _flatten_axes(treedef, axis_tree):\n+ proxy = object()\ndummy = tree_unflatten(treedef, [object()] * treedef.num_leaves)\naxes = []\nadd_leaves = lambda i, x: axes.extend([i] * len(tree_flatten(x)[0]))\ntry:\n- tree_multimap(add_leaves, _replace_nones(axis_tree), dummy)\n+ tree_multimap(add_leaves, _replace_nones(proxy, axis_tree), dummy)\nexcept ValueError:\nmsg = (\"axes specification must be a tree prefix of the corresponding \"\n\"value, got specification {} for value {}.\")\nraise ValueError(msg.format(axis_tree, treedef))\n- axes = [None if a is _none_proxy else a for a in axes]\n+ axes = [None if a is proxy else a for a in axes]\n+ assert len(axes) == treedef.num_leaves\nreturn axes\n-def _replace_nones(tuptree):\n- if type(tuptree) in (list, tuple):\n- return tuple(map(_replace_nones, tuptree))\n- else:\n- return tuptree if tuptree is not None else _none_proxy\n-class _NoneProxy(object): pass\n-_none_proxy = _NoneProxy()\n-\ndef pmap(fun, axis_name=None, devices=None, backend=None):\n\"\"\"Parallel map with support for collectives.\n" }, { "change_type": "MODIFY", "old_path": "jax/api_util.py", "new_path": "jax/api_util.py", "diff": "@@ -16,8 +16,8 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n-from .tree_util import (build_tree, process_pytree, tree_flatten,\n- tree_unflatten, treedef_is_leaf)\n+from .tree_util import (build_tree, tree_flatten, tree_unflatten,\n+ treedef_is_leaf)\nfrom .linear_util import transformation_with_aux\nfrom .util import safe_map, unzip2, partial, curry\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -25,7 +25,7 @@ from ..ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval, zeros_like\nzeros_like_p, zero, Zero)\nfrom ..abstract_arrays import raise_to_shaped\nfrom ..util import unzip2, unzip3, safe_map, safe_zip, partial, split_list\n-from ..tree_util import process_pytree, build_tree, register_pytree_node, tree_map\n+from ..tree_util import build_tree, register_pytree_node, tree_map\nfrom ..linear_util import thunk, staged, transformation, transformation_with_aux, wrap_init\nfrom ..api_util import flatten_fun, flatten_fun_nokwargs\nfrom ..tree_util import tree_flatten, tree_unflatten\n" }, { "change_type": "MODIFY", "old_path": "jax/tree_util.py", "new_path": "jax/tree_util.py", "diff": "@@ -42,7 +42,7 @@ from six.moves import reduce\nfrom .lib import pytree\n-from .util import partial, safe_zip\n+from .util import partial, safe_zip, unzip2\ndef tree_map(f, tree):\n@@ -83,7 +83,8 @@ def tree_multimap(f, tree, *rest):\ndef tree_leaves(tree):\nreturn pytree.flatten(tree)[0]\n-def process_pytree(process_node, tree):\n+# TODO(mattjj,phawkins): consider removing this function\n+def _process_pytree(process_node, tree):\nleaves, treedef = pytree.flatten(tree)\nreturn treedef.walk(process_node, None, leaves), treedef\n@@ -122,8 +123,37 @@ def treedef_tuple(trees):\ndef treedef_children(treedef):\nreturn treedef.children()\n-register_pytree_node = pytree.register_node\n-\n+def register_pytree_node(type_, to_iterable, from_iterable):\n+ pytree.register_node(type_, to_iterable, from_iterable)\n+ _registry[type_] = _RegistryEntry(to_iterable, from_iterable)\n+\n+# TODO(mattjj): remove the Python-side registry when the C++-side registry is\n+# sufficiently queryable that we can express _replace_nones. That may mean once\n+# we have a flatten_one function.\n+_RegistryEntry = collections.namedtuple(\"RegistryEntry\", [\"to_iter\", \"from_iter\"])\n+_registry = {\n+ tuple: _RegistryEntry(lambda xs: (xs, None), lambda _, xs: tuple(xs)),\n+ list: _RegistryEntry(lambda xs: (xs, None), lambda _, xs: list(xs)),\n+ dict: _RegistryEntry(lambda xs: unzip2(sorted(xs.items()))[::-1],\n+ lambda keys, xs: dict(zip(keys, xs))),\n+ type(None): _RegistryEntry(lambda z: ((), None), lambda _, xs: None),\n+}\n+def _replace_nones(sentinel, tree):\n+ if tree is None:\n+ return sentinel\n+ else:\n+ handler = _registry.get(type(tree))\n+ if handler:\n+ children, metadata = handler.to_iter(tree)\n+ proc_children = [_replace_nones(sentinel, child) for child in children]\n+ return handler.from_iter(metadata, proc_children)\n+ elif isinstance(tree, tuple) and hasattr(tree, '_fields'):\n+ # handle namedtuple as a special case, based on heuristic\n+ children = iter(tree)\n+ proc_children = [_replace_nones(sentinel, child) for child in children]\n+ return type(tree)(*proc_children)\n+ else:\n+ return tree\ndef tree_reduce(f, tree):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1146,6 +1146,41 @@ class APITest(jtu.JaxTestCase):\nr\"\\(10, \\[2, 2\\]\\)\",\nlambda: api.vmap(h, in_axes=(0, 1))(X, [U, U]))\n+ def test_vmap_structured_in_axes(self):\n+\n+ A, B, C, D = 2, 3, 4, 5\n+ K = 6 # batch size\n+ x = onp.ones((K, A, B)) # batch axis in different locations\n+ y = onp.ones((B, K, C))\n+ z = onp.ones((C, D, K))\n+\n+ def foo(tree_arg):\n+ x, (y, z) = tree_arg\n+ return np.dot(x, np.dot(y, z))\n+\n+ tree = (x, (y, z))\n+ vfoo = api.vmap(foo, in_axes=((0, (1, 2)),))\n+ self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n+\n+ Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n+ tree = (x, Point(y, z))\n+ vfoo = api.vmap(foo, in_axes=((0, Point(1, 2)),))\n+ self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n+\n+ def foo(tree_arg):\n+ x, dct = tree_arg\n+ y, z = dct['a'], dct['b']\n+ return np.dot(x, np.dot(y, z))\n+\n+ tree = (x, {'a':y, 'b':z})\n+ vfoo = api.vmap(foo, in_axes=((0, {'a':1, 'b':2}),))\n+ self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n+\n+ tree = (x, collections.OrderedDict([('a', y), ('b', z)]))\n+ vfoo = api.vmap(\n+ foo, in_axes=((0, collections.OrderedDict([('a', 1), ('b', 2)])),))\n+ self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n+\nif __name__ == '__main__':\nabsltest.main()\n" }, { "change_type": "MODIFY", "old_path": "tests/tree_util_tests.py", "new_path": "tests/tree_util_tests.py", "diff": "@@ -103,7 +103,7 @@ class TreeTest(jtu.JaxTestCase):\n@parameterized.parameters(*PYTREES)\ndef testRoundtripViaBuild(self, inputs):\n- xs, tree = tree_util.process_pytree(tuple, inputs)\n+ xs, tree = tree_util._process_pytree(tuple, inputs)\nactual = tree_util.build_tree(tree, xs)\nself.assertEqual(actual, inputs)\n" } ]
Python
Apache License 2.0
google/jax
make vmap structured axes work for any pytree
260,335
31.10.2019 16:21:02
25,200
d2156ea1c5a42bcf93f1ee068c9b29038fda1e87
improve names, avoid double lookup (thanks
[ { "change_type": "MODIFY", "old_path": "jax/linear_util.py", "new_path": "jax/linear_util.py", "diff": "@@ -197,15 +197,16 @@ def wrap_init(f, params={}):\ndef cache(call):\n- caches = weakref.WeakKeyDictionary()\n- def memoized_fun(f, *args):\n- cache = caches.setdefault(f.f, {})\n- key = (f.transforms, f.params, args)\n- if key in cache:\n- ans, stores = cache[key]\n- f.populate_stores(stores)\n+ fun_caches = weakref.WeakKeyDictionary()\n+ def memoized_fun(fun, *args):\n+ cache = fun_caches.setdefault(fun.f, {})\n+ key = (fun.transforms, fun.params, args)\n+ result = cache.get(key, None)\n+ if result is not None:\n+ ans, stores = result\n+ fun.populate_stores(stores)\nelse:\n- ans = call(f, *args)\n- cache[key] = (ans, f.stores)\n+ ans = call(fun, *args)\n+ cache[key] = (ans, fun.stores)\nreturn ans\nreturn memoized_fun\n" } ]
Python
Apache License 2.0
google/jax
improve names, avoid double lookup (thanks @hawkinsp)
260,517
01.11.2019 09:28:48
0
6f6209838ae3deb2aa14d62bed7e597cec79295b
Import nn in jax/__init__.py.
[ { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -17,5 +17,6 @@ os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL', '1')\nfrom jax.version import __version__\nfrom jax.api import *\n+from jax import nn\nfrom jax import random\nimport jax.numpy as np # side-effecting import sets up operator overloads\n" } ]
Python
Apache License 2.0
google/jax
Import nn in jax/__init__.py.
260,379
01.11.2019 15:38:24
0
a3a59a44509fdbabd1717c977e44f5f9dfe79203
Add optix to experimental optix is a composable gradient processing and optimization library
[ { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/optix.py", "diff": "+# Copyright 2018 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+\"\"\"A composable gradient processing and optimization library for JAX.\n+\n+The `optix` module implements a number of composable gradient transformations,\n+typically used in the context of optimizing neural nets.\n+\n+Each transformation defines:\n+\n+* an `init_fn`, to initialize a (possibly empty) set of statistics, or `state`.\n+* an `update_fn` to transform an input gradient and update the state.\n+\n+An (optional) `chainer` utility can be used to build custom optimizers by\n+chaining arbitrary sequences of transformations. For any sequence of\n+transformations `chainer` returns a single `init_fn` and `update_fn`.\n+\n+An (optional) `apply_updates` function can be used to eventually apply the\n+transformed gradients to the set of parameters of interest.\n+\n+Separating gradient transformations from the parameter update allows to flexibly\n+chain a sequence of transformations of the same gradients, as well as combine\n+multiple updates to the same parameters (e.g. in multi-task settings where the\n+different tasks may benefit from different sets of gradient transformations).\n+\n+Many popular optimizers can be implemented using `optix` as one-liners, and,\n+for convenience, we provide aliases for some of the most popular ones.\n+\"\"\"\n+\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+import collections\n+\n+from jax import numpy as jnp\n+from jax.tree_util import tree_leaves\n+from jax.tree_util import tree_multimap\n+\n+\n+### Composable gradient transformations. ###\n+\n+\n+ClipState = collections.namedtuple(\"ClipState\", \"\")\n+\n+\n+def clip(max_delta):\n+ \"\"\"Clip updates element-wise.\n+\n+ Args:\n+ max_delta: the maximum size of an update, for each variable\n+\n+ Returns:\n+ An (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ def init_fn(_):\n+ return ClipState()\n+\n+ def update_fn(updates, state):\n+ updates = tree_multimap(\n+ lambda g: jnp.clip_by_value(g, -max_delta, max_delta), updates)\n+ return updates, state\n+\n+ return init_fn, update_fn\n+\n+\n+ClipByGlobalNormState = collections.namedtuple(\"ClipByGlobalNormState\", \"\")\n+\n+\n+def _global_norm(items):\n+ return jnp.sqrt(jnp.sum([jnp.sum(x**2) for x in tree_leaves(items)]))\n+\n+\n+def clip_by_global_norm(max_norm):\n+ \"\"\"Clip updates using their global norm.\n+\n+ References:\n+ [Pascanu et al, 2012](https://arxiv.org/abs/1211.5063)\n+\n+ Args:\n+ max_norm: the maximum global norm for an update.\n+\n+ Returns:\n+ An (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ def init_fn(_):\n+ return ClipByGlobalNormState()\n+\n+ def update_fn(updates, state):\n+ g_norm = _global_norm(updates)\n+ trigger = g_norm < max_norm\n+ updates = tree_multimap(\n+ lambda t: jnp.where(trigger, t, t * (max_norm / g_norm)), updates)\n+ return updates, state\n+\n+ return init_fn, update_fn\n+\n+\n+TraceState = collections.namedtuple(\"TraceState\", \"trace\")\n+\n+\n+def trace(decay, nesterov):\n+ \"\"\"Compute a trace of past updates.\n+\n+ Args:\n+ decay: the decay rate for the tracing of past updates.\n+ nesterov: whether to use nesterov momentum.\n+\n+ Returns:\n+ An (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ def init_fn(params):\n+ return TraceState(trace=tree_multimap(jnp.zeros_like, params))\n+\n+ def update_fn(updates, state):\n+ f = lambda g, t: g + decay * t\n+ update_trace = tree_multimap(f, updates, state.trace)\n+ updates = (\n+ tree_multimap(f, updates, update_trace) if nesterov else update_trace)\n+ return updates, TraceState(trace=update_trace)\n+\n+ return init_fn, update_fn\n+\n+\n+ScaleByRmsState = collections.namedtuple(\"ScaleByRmsState\", \"nu\")\n+\n+\n+def _update_moment(updates, moments, decay, order):\n+ return tree_multimap(\n+ lambda g, t: (1 - decay) * (g ** order) + decay * t, updates, moments)\n+\n+\n+def scale_by_rms(decay=0.9, eps=1e-8):\n+ \"\"\"Rescale updates by the root of the exp. moving avg of the square.\n+\n+ References:\n+ [Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)\n+\n+ Args:\n+ decay: decay rate for the exponentially weighted average of squared grads.\n+ eps: term added to the denominator to improve numerical stability.\n+\n+ Returns:\n+ An (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ def init_fn(params):\n+ nu = tree_multimap(jnp.zeros_like, params) # second moment\n+ return ScaleByRmsState(nu=nu)\n+\n+ def update_fn(updates, state):\n+ nu = _update_moment(updates, state.nu, decay, 2)\n+ updates = tree_multimap(lambda g, n: g / (jnp.sqrt(n + eps)), updates, nu)\n+ return updates, ScaleByRmsState(nu=nu)\n+\n+ return init_fn, update_fn\n+\n+\n+ScaleByRStdDevState = collections.namedtuple(\"ScaleByRStdDevState\", \"mu nu\")\n+\n+\n+def scale_by_stddev(decay=0.9, eps=1e-8):\n+ \"\"\"Rescale updates by the root of the centered exp. moving average of squares.\n+\n+ References:\n+ [Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)\n+\n+ Args:\n+ decay: decay rate for the exponentially weighted average of squared grads.\n+ eps: term added to the denominator to improve numerical stability.\n+\n+ Returns:\n+ An (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ def init_fn(params):\n+ mu = tree_multimap(jnp.zeros_like, params) # First moment\n+ nu = tree_multimap(jnp.zeros_like, params) # Second moment\n+ return ScaleByRStdDevState(mu=mu, nu=nu)\n+\n+ def update_fn(updates, state):\n+ mu = _update_moment(updates, state.mu, decay, 1)\n+ nu = _update_moment(updates, state.nu, decay, 2)\n+ updates = tree_multimap(\n+ lambda g, m, n: g / jnp.sqrt(n - m**2 + eps), updates, mu, nu)\n+ return updates, ScaleByRStdDevState(mu=mu, nu=nu)\n+\n+ return init_fn, update_fn\n+\n+\n+ScaleByAdamState = collections.namedtuple(\"ScaleByAdamState\", \"count mu nu\")\n+\n+\n+def scale_by_adam(b1=0.9, b2=0.999, eps=1e-8):\n+ \"\"\"Rescale updates according to the Adam algorithm.\n+\n+ References:\n+ [Kingma et al, 2014](https://arxiv.org/abs/1412.6980)\n+\n+ Args:\n+ b1: decay rate for the exponentially weighted average of grads.\n+ b2: decay rate for the exponentially weighted average of squared grads.\n+ eps: term added to the denominator to improve numerical stability.\n+\n+ Returns:\n+ An (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ def init_fn(params):\n+ mu = tree_multimap(jnp.zeros_like, params) # First moment\n+ nu = tree_multimap(jnp.zeros_like, params) # Second moment\n+ return ScaleByAdamState(count=jnp.zeros([]), mu=mu, nu=nu)\n+\n+ def update_fn(updates, state):\n+ mu = _update_moment(updates, state.mu, b1, 1)\n+ nu = _update_moment(updates, state.nu, b2, 2)\n+ mu_hat = tree_multimap(lambda t: t / (1 - b1 ** (state.count + 1)), mu)\n+ nu_hat = tree_multimap(lambda t: t / (1 - b2 ** (state.count + 1)), nu)\n+ updates = tree_multimap(\n+ lambda m, v: m / (jnp.sqrt(v) + eps), mu_hat, nu_hat)\n+ return updates, ScaleByAdamState(count=state.count + 1, mu=mu, nu=nu)\n+\n+ return init_fn, update_fn\n+\n+\n+ScaleState = collections.namedtuple(\"ScaleState\", \"\")\n+\n+\n+def scale(step_size):\n+ \"\"\"Scale updates by some fixed scalar `step_size`.\n+\n+ Args:\n+ step_size: a scalar corresponding to a fixed scaling factor for updates.\n+\n+ Returns:\n+ An (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ def init_fn(_):\n+ return ScaleState()\n+\n+ def update_fn(updates, state):\n+ updates = tree_multimap(lambda g: step_size * g, updates)\n+ return updates, state\n+\n+ return init_fn, update_fn\n+\n+\n+ScaleByScheduleState = collections.namedtuple(\"ScaleByScheduleState\", \"count\")\n+\n+\n+def scale_by_schedule(step_size_fn):\n+ \"\"\"Scale updates using a custom schedule for the `step_size`.\n+\n+ Args:\n+ step_size_fn: a function that takes an update count as input and proposes\n+ the step_size to multiply the updates by.\n+\n+ Returns:\n+ An (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ def init_fn(_):\n+ return ScaleByScheduleState(count=jnp.zeros([]))\n+\n+ def update_fn(updates, state):\n+ updates = tree_multimap(lambda g: step_size_fn(state.count) * g, updates)\n+ return updates, ScaleByScheduleState(count=state.count + 1)\n+\n+ return init_fn, update_fn\n+\n+\n+### Utilities for building and using custom optimizers. ###\n+\n+\n+def chainer(*args):\n+ \"\"\"Applies a list of chainable update transformations.\n+\n+ Given a sequence of chainable transforms, `chainer` returns an `init_fn`\n+ that constructs a `state` by concatenating the states of the individual\n+ transforms, and returns an `update_fn` which chains the update transformations\n+ feeding the appropriate state to each.\n+\n+ Args:\n+ *args: a sequence of chainable (init_fn, update_fn) tuples.\n+\n+ Returns:\n+ A single (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ init_fns, update_fns = zip(*args)\n+\n+ def init(params):\n+ return [fn(params) for fn in init_fns]\n+\n+ def update(updates, state):\n+ new_state = []\n+ for s, fn in zip(state, update_fns):\n+ updates, new_s = fn(updates, s)\n+ new_state.append(new_s)\n+ return updates, new_state\n+\n+ return init, update\n+\n+\n+def apply_updates(params, updates):\n+ \"\"\"Applies an update to the corresponding parameters.\n+\n+ This is an (optional) utility functions that applies an update, and returns\n+ the updated parameters to the caller. The update itself is typically the\n+ result of applying any number of `chainable` transformations.\n+\n+ Args:\n+ params: a tree of parameters.\n+ updates: a tree of updates, the tree structure and the shape of the leaf\n+ nodes must match that of `params`.\n+\n+ Returns:\n+ Updated parameters, with same structure and shape as `params`.\n+ \"\"\"\n+ return tree_multimap(lambda p, u: p + u, params, updates)\n+\n+\n+### Aliases for popular optimizers. ###\n+\n+\n+def sgd(learning_rate, momentum=0., nesterov=False):\n+ return chainer(\n+ trace(decay=momentum, nesterov=nesterov),\n+ scale(-learning_rate))\n+\n+\n+def adam(learning_rate, b1=0.9, b2=0.999, eps=1e-8):\n+ return chainer(\n+ scale_by_adam(b1=b1, b2=b2, eps=eps),\n+ scale(-learning_rate))\n+\n+\n+def rmsprop(learning_rate, decay=0.9, eps=1e-8, centered=False):\n+ if not centered:\n+ return chainer(\n+ scale_by_rms(decay=decay, eps=eps),\n+ scale(-learning_rate))\n+ else:\n+ return chainer(\n+ scale_by_stddev(decay=decay, eps=eps),\n+ scale(-learning_rate))\n" } ]
Python
Apache License 2.0
google/jax
Add optix to experimental optix is a composable gradient processing and optimization library
260,379
01.11.2019 15:40:09
0
035540578674d0c731b2921fcf7081acfd2831b5
Add tests checking equivalence to optimizers.py
[ { "change_type": "ADD", "old_path": null, "new_path": "tests/optix_test.py", "diff": "+# Copyright 2018 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+\"\"\"Tests for the optix module.\"\"\"\n+\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+from absl.testing import absltest\n+from jax import numpy as jnp\n+from jax.experimental import optimizers\n+from jax.experimental import optix\n+from jax.tree_util import tree_leaves\n+import numpy as onp\n+\n+\n+STEPS = 50\n+LR = 1e-2\n+\n+\n+class OptixTest(absltest.TestCase):\n+\n+ def setUp(self):\n+ super(OptixTest, self).setUp()\n+ self.init_params = (jnp.array([1., 2.]), jnp.array([3., 4.]))\n+ self.per_step_updates = (jnp.array([500., 5.]), jnp.array([300., 3.]))\n+\n+ def test_sgd(self):\n+\n+ # experimental/optimizers.py\n+ jax_params = self.init_params\n+ opt_init, opt_update, get_params = optimizers.sgd(LR)\n+ state = opt_init(jax_params)\n+ for i in range(STEPS):\n+ state = opt_update(i, self.per_step_updates, state)\n+ jax_params = get_params(state)\n+\n+ # experimental/optix.py\n+ optix_params = self.init_params\n+ opt_init, opt_update = optix.sgd(LR, 0.0)\n+ state = opt_init(optix_params)\n+ for _ in range(STEPS):\n+ updates, state = opt_update(self.per_step_updates, state)\n+ optix_params = optix.apply_updates(optix_params, updates)\n+\n+ # Check equivalence.\n+ for x, y in zip(tree_leaves(jax_params), tree_leaves(optix_params)):\n+ onp.testing.assert_allclose(x, y, rtol=1e-5)\n+\n+ def test_adam(self):\n+ b1, b2, eps = 0.9, 0.999, 1e-8\n+\n+ # experimental/optimizers.py\n+ jax_params = self.init_params\n+ opt_init, opt_update, get_params = optimizers.adam(LR, b1, b2, eps)\n+ state = opt_init(jax_params)\n+ for i in range(STEPS):\n+ state = opt_update(i, self.per_step_updates, state)\n+ jax_params = get_params(state)\n+\n+ # experimental/optix.py\n+ optix_params = self.init_params\n+ opt_init, opt_update = optix.adam(LR, b1, b2, eps)\n+ state = opt_init(optix_params)\n+ for _ in range(STEPS):\n+ updates, state = opt_update(self.per_step_updates, state)\n+ optix_params = optix.apply_updates(optix_params, updates)\n+\n+ # Check equivalence.\n+ for x, y in zip(tree_leaves(jax_params), tree_leaves(optix_params)):\n+ onp.testing.assert_allclose(x, y, rtol=1e-5)\n+\n+ def test_rmsprop(self):\n+ decay, eps = .9, 0.1\n+\n+ # experimental/optimizers.py\n+ jax_params = self.init_params\n+ opt_init, opt_update, get_params = optimizers.rmsprop(LR, decay, eps)\n+ state = opt_init(jax_params)\n+ for i in range(STEPS):\n+ state = opt_update(i, self.per_step_updates, state)\n+ jax_params = get_params(state)\n+\n+ # experimental/optix.py\n+ optix_params = self.init_params\n+ opt_init, opt_update = optix.rmsprop(LR, decay, eps)\n+ state = opt_init(optix_params)\n+ for _ in range(STEPS):\n+ updates, state = opt_update(self.per_step_updates, state)\n+ optix_params = optix.apply_updates(optix_params, updates)\n+\n+ # Check equivalence.\n+ for x, y in zip(tree_leaves(jax_params), tree_leaves(optix_params)):\n+ onp.testing.assert_allclose(x, y, rtol=1e-5)\n+\n+\n+if __name__ == '__main__':\n+ absltest.main()\n" } ]
Python
Apache License 2.0
google/jax
Add tests checking equivalence to optimizers.py
260,335
01.11.2019 13:46:13
25,200
71b34116e5f887ad923c22bbfc4cbe053ab081f7
avoid generating a trivial gather from numpy indexing fixes
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -2548,8 +2548,10 @@ def _rewriting_take(arr, idx):\ndef _gather(arr, treedef, static_idx, dynamic_idx):\nidx = _merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx)\nindexer = _index_to_gather(shape(arr), idx) # shared with _scatter_update\n+ y = arr\n- y = lax.gather(arr, indexer.gather_indices, indexer.dnums,\n+ if indexer.gather_indices.size:\n+ y = lax.gather(y, indexer.gather_indices, indexer.dnums,\nindexer.gather_slice_shape)\n# Reverses axes with negative strides.\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_indexing_test.py", "new_path": "tests/lax_numpy_indexing_test.py", "diff": "@@ -730,6 +730,11 @@ class IndexingTest(jtu.JaxTestCase):\nself.assertAllClose(expected, primals, check_dtypes=True)\nself.assertAllClose(onp.zeros_like(x), tangents, check_dtypes=True)\n+ def testTrivialGatherIsntGenerated(self):\n+ # https://github.com/google/jax/issues/1621\n+ jaxpr = api.make_jaxpr(lambda x: x[:, None])(onp.arange(4))\n+ self.assertEqual(len(jaxpr.eqns), 1)\n+ self.assertNotIn('gather', str(jaxpr))\ndef _broadcastable_shapes(shape):\n@@ -891,6 +896,5 @@ class IndexedUpdateTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\n-\nif __name__ == \"__main__\":\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
avoid generating a trivial gather from numpy indexing fixes #1621
260,379
04.11.2019 15:43:17
0
72eb6b33fedee78a943553ff1736e98c158f5da9
Add gradient noise function
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optix.py", "new_path": "jax/experimental/optix.py", "diff": "@@ -284,6 +284,42 @@ def scale_by_schedule(step_size_fn):\nreturn init_fn, update_fn\n+AddNoiseState = collections.namedtuple(\"AddNoiseState\", \"count rng_key\")\n+\n+\n+def add_noise(eta, gamma, seed):\n+ \"\"\"Add gradient noise.\n+\n+ References:\n+ [Neelakantan et al, 2014](https://arxiv.org/abs/1511.06807)\n+\n+ Args:\n+ eta: base variance of the gaussian noise added to the gradient.\n+ gamma: decay exponent for annealing of the variance.\n+ seed: seed for random number generation.\n+\n+ Returns:\n+ An (init_fn, update_fn) tuple.\n+ \"\"\"\n+\n+ def init_fn(_):\n+ return AddNoiseState(count=jnp.zeros([]), rng_key=jrandom.PRNGKey(seed))\n+\n+ def update_fn(updates, state):\n+ num_vars = len(tree_leaves(updates))\n+ treedef = tree_structure(updates)\n+ variance = eta / (1 + state.count) ** gamma\n+ keys = jrandom.split(rng_key, num=num_vars + 1)\n+ keys = tree_unflatten(treedef, keys[1:])\n+ noise = tree_multimap(\n+ lambda g, k: jrandom.normal(k, shape=g.shape), updates, keys)\n+ updates = tree_multimap(\n+ lambda g, n: g + variance * n, updates, noise)\n+ return updates, AddNoiseState(count=state.count + 1, rng_key=keys[0])\n+\n+ return init_fn, update_fn\n+\n+\n### Utilities for building and using custom optimizers. ###\n" } ]
Python
Apache License 2.0
google/jax
Add gradient noise function
260,379
04.11.2019 15:55:14
0
b77d2a61e041d4ae50d7dbd19b5782a4dbfabdf5
create noisy_sgd variant
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optix.py", "new_path": "jax/experimental/optix.py", "diff": "@@ -380,6 +380,13 @@ def sgd(learning_rate, momentum=0., nesterov=False):\nscale(-learning_rate))\n+def noisy_sgd(learning_rate, eta=0.01, gamma=0.55, seed=42):\n+ return chainer(\n+ trace(decay=0., nesterov=False),\n+ scale(-learning_rate),\n+ add_noise(eta, gamma, seed))\n+\n+\ndef adam(learning_rate, b1=0.9, b2=0.999, eps=1e-8):\nreturn chainer(\nscale_by_adam(b1=b1, b2=b2, eps=eps),\n" } ]
Python
Apache License 2.0
google/jax
create noisy_sgd variant
260,379
04.11.2019 16:21:09
0
8d1b58334eec051eeafe73b6cd48eae7f7cdd244
missing imports for grad_noise
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optix.py", "new_path": "jax/experimental/optix.py", "diff": "@@ -45,8 +45,12 @@ from __future__ import print_function\nimport collections\nfrom jax import numpy as jnp\n+from jax import random as jrandom\n+\nfrom jax.tree_util import tree_leaves\nfrom jax.tree_util import tree_multimap\n+from jax.tree_util import tree_structure\n+from jax.tree_util import tree_unflatten\n### Composable gradient transformations. ###\n@@ -305,7 +309,7 @@ def add_noise(eta, gamma, seed):\ndef init_fn(_):\nreturn AddNoiseState(count=jnp.zeros([]), rng_key=jrandom.PRNGKey(seed))\n- def update_fn(updates, state):\n+ def update_fn(updates, state): # pylint: disable=missing-docstring\nnum_vars = len(tree_leaves(updates))\ntreedef = tree_structure(updates)\nvariance = eta / (1 + state.count) ** gamma\n" } ]
Python
Apache License 2.0
google/jax
missing imports for grad_noise
260,379
04.11.2019 17:00:26
0
cf81c834d5a42baf1814c5d8c7860b38d97deed4
fix indexing of next random key
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optix.py", "new_path": "jax/experimental/optix.py", "diff": "@@ -313,13 +313,13 @@ def add_noise(eta, gamma, seed):\nnum_vars = len(tree_leaves(updates))\ntreedef = tree_structure(updates)\nvariance = eta / (1 + state.count) ** gamma\n- keys = jrandom.split(rng_key, num=num_vars + 1)\n- keys = tree_unflatten(treedef, keys[1:])\n+ all_keys = jrandom.split(state.rng_key, num=num_vars + 1)\nnoise = tree_multimap(\n- lambda g, k: jrandom.normal(k, shape=g.shape), updates, keys)\n+ lambda g, k: jrandom.normal(k, shape=g.shape),\n+ updates, tree_unflatten(treedef, all_keys[1:]))\nupdates = tree_multimap(\nlambda g, n: g + variance * n, updates, noise)\n- return updates, AddNoiseState(count=state.count + 1, rng_key=keys[0])\n+ return updates, AddNoiseState(count=state.count + 1, rng_key=all_keys[0])\nreturn init_fn, update_fn\n" } ]
Python
Apache License 2.0
google/jax
fix indexing of next random key
260,335
05.11.2019 16:52:46
28,800
67a9247ebe76a691690dba429b5352c7dcd2af1f
avoid staging out some trivial convert_element_types
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -349,7 +349,7 @@ def convert_element_type(operand, new_dtype):\nAn array with the same shape as `operand`, cast elementwise to `new_dtype`.\n\"\"\"\nnew_dtype = xla_bridge.canonicalize_dtype(new_dtype)\n- old_dtype = _dtype(operand)\n+ old_dtype = xla_bridge.canonicalize_dtype(_dtype(operand))\nif old_dtype != new_dtype:\nif (onp.issubdtype(old_dtype, onp.complexfloating) and\nnot onp.issubdtype(new_dtype, onp.complexfloating)):\n" } ]
Python
Apache License 2.0
google/jax
avoid staging out some trivial convert_element_types
260,335
07.11.2019 10:14:16
28,800
bd851ee59f3424cf20a470f54de524b022b98255
fix indexing error after involving empty result
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -2557,7 +2557,9 @@ def _gather(arr, treedef, static_idx, dynamic_idx):\nindexer = _index_to_gather(shape(arr), idx) # shared with _scatter_update\ny = arr\n- if indexer.gather_indices.size:\n+ # We avoid generating a gather when indexer.gather_indices.size is empty\n+ # unless indexer.slice_shape also corresponds to an empty array.\n+ if indexer.gather_indices.size or not prod(indexer.slice_shape):\ny = lax.gather(y, indexer.gather_indices, indexer.dnums,\nindexer.gather_slice_shape)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_indexing_test.py", "new_path": "tests/lax_numpy_indexing_test.py", "diff": "@@ -736,6 +736,15 @@ class IndexingTest(jtu.JaxTestCase):\nself.assertEqual(len(jaxpr.eqns), 1)\nself.assertNotIn('gather', str(jaxpr))\n+ def testBooleanIndexingWithEmptyResult(self):\n+ # based on a TensorFlow Probability test that started failing after #1622\n+ x = lnp.array([-1])\n+ mask = lnp.array([False])\n+ ans = x[mask] # doesn't crash\n+\n+ expected = onp.array([-1])[onp.array([False])]\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef _broadcastable_shapes(shape):\n\"\"\"Returns all shapes that broadcast to `shape`.\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
fix indexing error after #1622 involving empty result
260,504
07.11.2019 17:03:03
18,000
4be1d1878d86f7ebaf06c08b2f9f6752659fff49
Add missing parameter to make_tuple
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -465,7 +465,7 @@ def _execute_replicated(compiled, backend, handlers, tuple_args, *args):\n[device_put(x, device, backend=backend) for x in args if x is not token]\nfor device in compiled.local_devices()]\nif tuple_args:\n- input_bufs = [[make_tuple(bufs, device)] for bufs, device in\n+ input_bufs = [[make_tuple(bufs, device, backend)] for bufs, device in\nzip(input_bufs, compiled.local_devices())]\nout_bufs = compiled.ExecutePerReplica(input_bufs)[0].destructure()\nif FLAGS.jax_debug_nans: check_nans(xla_call_p, out_bufs)\n" } ]
Python
Apache License 2.0
google/jax
Add missing parameter to make_tuple (#1642)
260,335
08.11.2019 10:15:17
28,800
1d8157810d7cdaa92dfaae7c00e5bf58dac4ca08
typo: use _prod not prod
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -2559,7 +2559,7 @@ def _gather(arr, treedef, static_idx, dynamic_idx):\n# We avoid generating a gather when indexer.gather_indices.size is empty\n# unless indexer.slice_shape also corresponds to an empty array.\n- if indexer.gather_indices.size or not prod(indexer.slice_shape):\n+ if indexer.gather_indices.size or not _prod(indexer.slice_shape):\ny = lax.gather(y, indexer.gather_indices, indexer.dnums,\nindexer.gather_slice_shape)\n" } ]
Python
Apache License 2.0
google/jax
typo: use _prod not prod
260,510
08.11.2019 13:11:17
28,800
7bc2b0878ad868ea81a31c2fa638219bdd327f4a
Update description of eqn.parmas
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "new_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "diff": "\"* `jaxpr.outvars` - the `outvars` of a Jaxpr are the variables that are returned by the Jaxpr. Every Jaxpr has multiple outputs.\\n\",\n\"* `jaxpr.constvars` - the `constvars` are a list of variables that are also inputs to the Jaxpr, but correspond to constants from the trace (we'll go over these in more detail later)\\n\",\n\"* `jaxpr.freevars` - these can arise when nesting `jit` and `pmap` transformations; we won't worry about them in this colab.\\n\",\n- \"* `jaxpr.eqns` - a list of equations, which are essentially let-bindings. Each equation is list of input variables, a list of output variables, and a *primitive*, which is used to evaluate inputs to produce outputs. Each equation also has a set of `params`, a dictionary of keyword arguments to the primitive.\\n\",\n+ \"* `jaxpr.eqns` - a list of equations, which are essentially let-bindings. Each equation is list of input variables, a list of output variables, and a *primitive*, which is used to evaluate inputs to produce outputs. Each equation also has a `params`, a dictionary of parameters.\\n\",\n\"\\n\",\n\"All together, a Jaxpr encapsulates a simple program that can be evaluated with inputs to produce an output. We'll go over how exactly to do this later. The important thing to note now is that a Jaxpr is a data structure that can be manipulated and evaluated in whatever way we want.\"\n]\n" } ]
Python
Apache License 2.0
google/jax
Update description of eqn.parmas
260,510
08.11.2019 13:15:42
28,800
6fa4cc0240e5e20bb5d64e602ee4989c7682c784
Fix np.clip broadcasting
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -986,11 +986,11 @@ def clip(a, a_min=None, a_max=None):\nif a_min is not None:\nif _dtype(a_min) != _dtype(a):\na_min = lax.convert_element_type(a_min, _dtype(a))\n- a = lax.max(a_min, a)\n+ a = maximum(a_min, a)\nif a_max is not None:\nif _dtype(a_max) != _dtype(a):\na_max = lax.convert_element_type(a_max, _dtype(a))\n- a = lax.min(a_max, a)\n+ a = minimum(a_max, a)\nreturn a\n" } ]
Python
Apache License 2.0
google/jax
Fix np.clip broadcasting
260,510
08.11.2019 14:12:28
28,800
6c305f3f481208562fc099e41ceba3bda45d16bd
Extend clip test to test broadcasting a_min and a_max
[ { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -683,7 +683,10 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n\"shape\": shape, \"dtype\": dtype, \"a_min\": a_min, \"a_max\": a_max,\n\"rng\": jtu.rand_default()}\nfor shape in all_shapes for dtype in number_dtypes\n- for a_min, a_max in [(-1, None), (None, 1), (-1, 1)]))\n+ for a_min, a_max in [(-1, None), (None, 1), (-1, 1),\n+ (-lnp.ones(1), None),\n+ (None, lnp.ones(1)),\n+ (-lnp.ones(1), lnp.ones(1))]))\ndef testClipStaticBounds(self, shape, dtype, a_min, a_max, rng):\nonp_fun = lambda x: onp.clip(x, a_min=a_min, a_max=a_max)\nlnp_fun = lambda x: lnp.clip(x, a_min=a_min, a_max=a_max)\n" } ]
Python
Apache License 2.0
google/jax
Extend clip test to test broadcasting a_min and a_max
260,335
11.11.2019 07:45:31
28,800
6434340d00d4b0a2b05c63fb48e68ee73ec0c27f
Hoist loop-invariant residuals out of scan in partial eval Fixes
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax_control_flow.py", "new_path": "jax/lax/lax_control_flow.py", "diff": "@@ -617,34 +617,81 @@ def _scan_partial_eval(trace, *tracers, **kwargs):\ncarry_uk = _map(operator.or_, carry_uk, carry_uk_out)\nelse:\nassert False, \"Fixpoint not reached\"\n+ num_res = len(jaxpr_1.out_avals) - len(jaxpr_2.out_avals)\n+\n+ # The residuals are treated as extensive outputs of jaxpr_1 (and extensive\n+ # inputs to jaxpr_2), but residuals that are loop-invariant can be hoisted.\n+ # TODO(mattjj): hoist other loop-invariant values here too (instantiate=False)\n+ invariant_pvals = [pe.PartialVal((None, core.unit if uk else t.pval[1]))\n+ for uk, t in zip(unknowns[:num_consts], tracers[:num_consts])]\n+ other_pvals = [pe.PartialVal((a, core.unit)) for a in jaxpr_1.in_avals[num_consts:]]\n+ in_pvals_1 = invariant_pvals + other_pvals\n+ untyped_jaxpr_1, out_pvals_1, consts_1 = pe.trace_to_jaxpr(\n+ lu.wrap_init(core.jaxpr_as_fun(jaxpr_1)), in_pvals_1,\n+ instantiate=[True] * (num_carry + num_ys) + [False] * num_res)\n+ const_avals_1 = [raise_to_shaped(core.get_aval(c)) for c in consts_1]\n+ in_avals_1 = [core.abstract_unit] * num_consts + jaxpr_1.in_avals[num_consts:]\n+ out_avals_1 = [core.abstract_unit if pv is None else pv for pv, c in out_pvals_1]\n+ jaxpr_1_opt = pe.TypedJaxpr(pe.closure_convert_jaxpr(untyped_jaxpr_1),\n+ (), const_avals_1 + in_avals_1, out_avals_1)\n+ num_consts_1 = num_consts + len(consts_1)\n+ # any now-known residuals are intensive, so we want to revise jaxpr_2 to take\n+ # those inputs as constants rather than as extensive inputs\n+ _, _, res_pvals = split_list(out_pvals_1, [num_carry, num_ys])\n+ intensive_residuals = [const for pv, const in res_pvals if pv is None]\n+ move = [False] * len(jaxpr_1.in_avals) + [pv is None for pv, _ in res_pvals]\n+ jaxpr_2_opt = _move_binders_to_front(jaxpr_2, move)\n+ num_consts_2 = num_consts + len(intensive_residuals)\n+\n+ in_consts = (list(consts_1) + [core.unit] * num_consts +\n+ [core.unit if uk else t.pval[1]\n+ for uk, t in zip(unknowns[num_consts:], tracers[num_consts:])])\n+ linear_1 = ([False] * len(consts_1) + [True] * num_consts +\n+ [lin or uk for uk, lin in zip(unknowns[num_consts:], linear[num_consts:])])\n+ out_flat = scan_p.bind(\n+ *in_consts, forward=forward, length=length, jaxpr=jaxpr_1_opt,\n+ num_consts=num_consts_1, num_carry=num_carry, linear=linear_1)\n+ out_carry, ys, res_and_units = split_list(out_flat, [num_carry, num_ys])\n+ extensive_residuals = [r for r, (pv, _) in zip(res_and_units, res_pvals) if pv is not None]\n- in_consts = [core.unit if uk else t.pval[1] for uk, t in zip(unknowns, tracers)]\nnew_tracers = [trace.instantiate_const(t) if uk else trace.new_instantiated_literal(core.unit)\nfor uk, t in zip(unknowns, tracers)]\n-\ncarry_avals, y_avals = split_list(jaxpr.out_avals, [num_carry])\nys_avals = _map(partial(_promote_aval_rank, length), y_avals)\nout_avals = carry_avals + ys_avals\nout_pvs = [aval if uk else None for aval, uk in zip(out_avals, out_uk)]\n- linear_1 = [lin or uk for uk, lin in zip(unknowns, linear)]\n- out_flat = scan_p.bind(\n- *in_consts, forward=forward, length=length, jaxpr=jaxpr_1,\n- num_consts=num_consts, num_carry=num_carry, linear=linear_1)\n- out_carry, ys, residuals = split_list(out_flat, [num_carry, num_ys])\nout_consts = out_carry + ys\n- residual_tracers = _map(trace.new_instantiated_const, residuals)\n+ int_res_tracers = _map(trace.new_instantiated_const, intensive_residuals)\n+ ext_res_tracers = _map(trace.new_instantiated_const, extensive_residuals)\nout_tracers = [pe.JaxprTracer(trace, pe.PartialVal((pv, const)), None)\nfor pv, const in zip(out_pvs, out_consts)]\n- linear_2 = ([lin or not uk for uk, lin in zip(unknowns, linear)]\n- + [False] * len(residual_tracers))\n- eqn = pe.new_jaxpr_eqn(new_tracers + residual_tracers, out_tracers, scan_p,\n- (), dict(forward=forward, length=length, jaxpr=jaxpr_2,\n- num_consts=num_consts, num_carry=num_carry,\n- linear=linear_2))\n+ linear_2 = ([False] * len(int_res_tracers) +\n+ [lin or not uk for uk, lin in zip(unknowns, linear)] +\n+ [False] * len(ext_res_tracers))\n+ eqn = pe.new_jaxpr_eqn(int_res_tracers + new_tracers + ext_res_tracers,\n+ out_tracers, scan_p, (),\n+ dict(forward=forward, length=length, jaxpr=jaxpr_2_opt,\n+ num_consts=num_consts_2,\n+ num_carry=num_carry, linear=linear_2))\nfor t in out_tracers: t.recipe = eqn\nreturn out_tracers\n+def _move_binders_to_front(typed_jaxpr, to_move):\n+ assert not typed_jaxpr.jaxpr.constvars and not typed_jaxpr.jaxpr.freevars\n+ assert len(typed_jaxpr.in_avals) == len(to_move)\n+ new_invars = _move_to_front(typed_jaxpr.jaxpr.invars, to_move)\n+ new_jaxpr = core.Jaxpr((), (), new_invars, typed_jaxpr.jaxpr.outvars,\n+ typed_jaxpr.jaxpr.eqns)\n+ new_in_avals = _move_to_front(typed_jaxpr.in_avals, to_move)\n+ new_typed_jaxpr = core.TypedJaxpr(new_jaxpr, typed_jaxpr.literals,\n+ new_in_avals, typed_jaxpr.out_avals)\n+ return new_typed_jaxpr\n+\n+def _move_to_front(lst, to_move):\n+ return ([elt for elt, move in zip(lst, to_move) if move] +\n+ [elt for elt, move in zip(lst, to_move) if not move])\n+\ndef _promote_aval_rank(sz, aval):\nif aval is core.abstract_unit:\nreturn core.abstract_unit\n@@ -655,54 +702,66 @@ def _scan_transpose(cts, *args, **kwargs):\nforward, length, num_consts, num_carry, jaxpr, linear = split_dict(\nkwargs, [\"forward\", \"length\", \"num_consts\", \"num_carry\", \"jaxpr\", \"linear\"])\n- # we can only transpose scans for which the nonlinear values appear in xs\n+ # we've only implemented transposing scans with specific lin/nonlin patterns\nconsts_lin, init_lin, xs_lin = split_list(linear, [num_consts, num_carry])\n- num_lin = sum(xs_lin)\n- if not all(consts_lin) or not all(init_lin) or not all(xs_lin[:num_lin]):\n+ num_ires = len(consts_lin) - sum(consts_lin)\n+ num_eres = len(xs_lin) - sum(xs_lin)\n+ if consts_lin != [False] * num_ires + [True] * (len(consts_lin) - num_ires):\n+ raise NotImplementedError\n+ if xs_lin != [True] * (len(xs_lin) - num_eres) + [False] * num_eres:\n+ raise NotImplementedError\n+ if not all(init_lin):\nraise NotImplementedError\n- consts, init, xs, res = split_list(args, [num_consts, num_carry, num_lin])\n- assert not any(r is ad.undefined_primal for r in res)\n+ consts, init, xs = split_list(args, [num_consts, num_carry])\n+ ires, consts = split_list(consts, [num_ires])\n+ xs, eres = split_list(xs, [sum(xs_lin)])\n+ assert not any(r is ad.undefined_primal for r in ires)\n+ assert not any(r is ad.undefined_primal for r in eres)\ncarry_avals, y_avals = split_list(jaxpr.out_avals, [num_carry])\nys_avals = _map(partial(_promote_aval_rank, length), y_avals)\nct_carry, ct_ys = split_list(cts, [num_carry])\nct_carry = _map(ad.instantiate_zeros_aval, carry_avals, ct_carry)\nct_ys = _map(ad.instantiate_zeros_aval, ys_avals, ct_ys)\n- ct_consts = _map(ad_util.zeros_like_aval, jaxpr.in_avals[:num_consts])\n+ ct_consts = _map(ad_util.zeros_like_aval, jaxpr.in_avals[num_ires:num_consts])\n- # jaxpr :: [T d] -> [T c] -> [T a, res] -> ([T c], [T b])\n- # jaxpr_trans :: [] -> [CT d, CT c] -> [CT b, res] -> ([CT d, CT c], [CT a])\n- jaxpr_trans = _transpose_jaxpr(num_consts, len(res), jaxpr)\n- linear_trans = ([True] * (len(ct_consts) + len(ct_carry) + len(ct_ys))\n- + [False] * len(res))\n+ # jaxpr :: [ires, T d] -> [T c] -> [T a, eres] -> ([T c], [T b])\n+ # jaxpr_trans :: [ires] -> [CT d, CT c] -> [CT b, eres] -> ([CT d, CT c], [CT a])\n+ jaxpr_trans = _transpose_jaxpr(num_ires, num_consts - num_ires, num_eres, jaxpr)\n+ linear_trans = ([False] * num_ires +\n+ [True] * (len(ct_consts) + len(ct_carry) + len(ct_ys)) +\n+ [False] * num_eres)\nouts = scan_p.bind(\n- *(ct_consts + ct_carry + ct_ys + res), forward=not forward, length=length,\n- jaxpr=jaxpr_trans, num_consts=0, num_carry=num_consts+num_carry,\n- linear=linear_trans)\n- ct_consts, ct_init, ct_xs = split_list(outs, [num_consts, num_carry])\n- return ct_consts + ct_init + ct_xs + [None] * len(res)\n-\n-# transpose_jaxpr :: ([c, a, res] -> b) -> ([CT c, CT b, res] -> [CT c, CT a]\n-def _transpose_jaxpr(num_c, num_res, jaxpr):\n- num_a = len(jaxpr.in_avals) - num_c - num_res\n- c_avals, a_avals, res_avals = split_list(jaxpr.in_avals, [num_c, num_a])\n+ *(ires + ct_consts + ct_carry + ct_ys + eres), forward=not forward,\n+ length=length, jaxpr=jaxpr_trans, num_consts=num_ires,\n+ num_carry=num_consts-num_ires+num_carry, linear=linear_trans)\n+ ct_consts, ct_init, ct_xs = split_list(outs, [num_consts - num_ires, num_carry])\n+ return [None] * num_ires + ct_consts + ct_init + ct_xs + [None] * num_eres\n+\n+# transpose_jaxpr :: ([res1, c, a, res2] -> b)\n+# -> ([res1, CT c, CT b, res2] -> [CT c, CT a])\n+def _transpose_jaxpr(num_res1, num_c, num_res2, jaxpr):\n+ num_a = len(jaxpr.in_avals) - num_res1 - num_c - num_res2\n+ res1_avals, c_avals, a_avals, res2_avals = split_list(\n+ jaxpr.in_avals, [num_res1, num_c, num_a])\nnum_b = len(jaxpr.out_avals)\nb_avals = list(jaxpr.out_avals)\n@lu.wrap_init\n- def transposed(*cbar_bbar_res):\n- c_bar, b_bar, res = split_list(cbar_bbar_res, [num_c, num_b])\n- primals = [ad.undefined_primal] * (num_c + num_a) + res\n+ def transposed(*res1_cbar_bbar_res2):\n+ res1, c_bar, b_bar, res2 = split_list(\n+ res1_cbar_bbar_res2, [num_res1, num_c, num_b])\n+ primals = res1 + [ad.undefined_primal] * (num_c + num_a) + res2\n_, cbar_abar = ad.backward_pass(jaxpr.jaxpr, jaxpr.literals, (), primals,\nb_bar)\n- new_c_bar, a_bar, _ = split_list(cbar_abar, [num_c, num_a])\n+ _, new_c_bar, a_bar, _ = split_list(cbar_abar, [num_res1, num_c, num_a])\na_bar = _map(ad.instantiate_zeros_aval, a_avals, a_bar)\nc_bar = _map(ad.instantiate_zeros_aval, c_avals,\n_map(ad.add_tangents, c_bar, new_c_bar))\nreturn c_bar + a_bar\n- return _make_typed_jaxpr(transposed, c_avals + b_avals + res_avals)\n+ return _make_typed_jaxpr(transposed, res1_avals + c_avals + b_avals + res2_avals)\ndef _make_typed_jaxpr(traceable, in_avals):\npvals = [pe.PartialVal((aval, core.unit)) for aval in in_avals]\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -1365,6 +1365,20 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, re.escape(\"matvec() output shapes\")):\napi.jvp(bad_matvec_usage, (1.0,), (1.0,))\n+ def testIssue810(self):\n+ def loss(A):\n+ def step(x, i):\n+ return A @ x, None\n+ init_x = np.zeros(A.shape[-1:])\n+ last_x, _ = lax.scan(step, init_x, np.arange(10))\n+ return np.sum(last_x)\n+\n+ A = np.zeros((3, 3))\n+ # The second DUS was unnecessarily replicating A across time.\n+ # We check XLA because _scan_impl is \"underneath\" the jaxpr language.\n+ s = str(api.xla_computation(api.grad(loss))(A).GetHloText())\n+ assert s.count(\"dynamic-update-slice(\") < 2\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
Hoist loop-invariant residuals out of scan in partial eval Fixes #810 Co-authored-by: James Bradbury <jekbradbury@google.com>
260,335
11.11.2019 13:04:36
28,800
0fa38eccc0e25deb782c7afd83b42dd9335dd6f7
use np.matmul and not `@` for py27
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -1368,7 +1368,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\ndef testIssue810(self):\ndef loss(A):\ndef step(x, i):\n- return A @ x, None\n+ return np.matmul(A, x), None\ninit_x = np.zeros(A.shape[-1:])\nlast_x, _ = lax.scan(step, init_x, np.arange(10))\nreturn np.sum(last_x)\n" } ]
Python
Apache License 2.0
google/jax
use np.matmul and not `@` for py27
260,335
11.11.2019 13:24:24
28,800
a73979f7989ea0c0791ddacdd70d7240225f7623
use onp not lnp in module-level scope fixes google import
[ { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -696,9 +696,9 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n\"rng_factory\": jtu.rand_default}\nfor shape in all_shapes for dtype in number_dtypes\nfor a_min, a_max in [(-1, None), (None, 1), (-1, 1),\n- (-lnp.ones(1), None),\n- (None, lnp.ones(1)),\n- (-lnp.ones(1), lnp.ones(1))]))\n+ (-onp.ones(1), None),\n+ (None, onp.ones(1)),\n+ (-onp.ones(1), onp.ones(1))]))\ndef testClipStaticBounds(self, shape, dtype, a_min, a_max, rng_factory):\nrng = rng_factory()\nonp_fun = lambda x: onp.clip(x, a_min=a_min, a_max=a_max)\n" } ]
Python
Apache License 2.0
google/jax
use onp not lnp in module-level scope fixes google import
260,335
09.11.2019 17:08:02
28,800
5ec07491a110de7c42da313b5623417e6aed0c7d
simplify xla op metadata, DeviceArray repr Just minor cleanup.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -143,31 +143,23 @@ def xla_primitive_callable(prim, *abstract_args, **params):\n@cache()\ndef primitive_computation(prim, *xla_shapes, **params):\n- backend = params.get('backend', None)\n- new_params = {k: params[k] for k in params if k != 'backend'}\nc = xb.make_computation_builder(\"primitive_computation_{}\".format(prim.name))\n- newvar = core.gensym('')\n- c.SetOpMetadata(xc.OpMetadata(\n- op_type=prim.name,\n- op_name=str(core.new_jaxpr_eqn(\n- [newvar() for i in range(len(xla_shapes))],\n- [newvar()],\n- prim, (), params))\n- ))\n+ c.SetOpMetadata(xc.OpMetadata(op_type=prim.name, op_name=str(params)))\n+ backend = params.pop(\"backend\", None)\nplatform = xb.get_backend(backend).platform\nxla_args = (_parameter_or_create_token(c, shape) for shape in xla_shapes)\nif prim in backend_specific_translations[platform]:\nrule = backend_specific_translations[platform][prim]\n- rule(c, *xla_args, **new_params) # return val set as a side-effect on c\n+ rule(c, *xla_args, **params) # return val set as a side-effect on c\nelif prim in translations:\nrule = translations[prim]\n- rule(c, *xla_args, **new_params) # return val set as a side-effect on c\n+ rule(c, *xla_args, **params) # return val set as a side-effect on c\nelif prim in reduction_translations:\nrule = reduction_translations[prim]\n- rule(c, *xla_args, backend=backend, **new_params) # return val set as a side-effect on c\n+ rule(c, *xla_args, backend=backend, **params) # return val set as a side-effect on c\nelif prim in initial_style_translations:\nrule = initial_style_translations[prim]\n- rule(c, AxisEnv(), *xla_args, backend=backend, **new_params) # side-effect on c\n+ rule(c, AxisEnv(), *xla_args, backend=backend, **params) # side-effect on c\nelse:\nraise NotImplementedError(\"XLA translation rule for {} not found\".format(prim))\nc.ClearOpMetadata()\n@@ -307,10 +299,7 @@ def jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, freevars, *args):\n_map(write, jaxpr.freevars, freevars)\n_map(write, jaxpr.invars, args)\nfor eqn in jaxpr.eqns:\n- c.SetOpMetadata(xc.OpMetadata(\n- op_type=eqn.primitive.name,\n- op_name=str(eqn)\n- ))\n+ c.SetOpMetadata(xc.OpMetadata( op_type=eqn.primitive.name, op_name=str(eqn)))\nin_nodes = list(map(read, eqn.invars))\nif eqn.primitive in backend_specific_translations[platform]:\nrule = backend_specific_translations[platform][eqn.primitive]\n@@ -432,7 +421,7 @@ def _xla_callable(fun, device, backend, *abstract_args):\ntuple_args = len(abstract_args) > 100\nwith core.new_master(pe.JaxprTrace, True) as master:\njaxpr, (pvals, consts, env) = pe.trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)\n- assert not env # no subtraces here (though cond might eventually need them)\n+ assert not env # no subtraces here\naxis_env = AxisEnv(jaxpr_replicas(jaxpr), [], [])\ncompiled = _compile_jaxpr(jaxpr, device, backend, axis_env, consts,\ntuple_args, *abstract_args)\n@@ -658,7 +647,7 @@ class DeviceArray(DeviceValue):\nself._npy_value = None\ndef __repr__(self):\n- return onp.array_repr(self)\n+ return onp.array_repr(self._value)\ndef item(self):\nif onp.issubdtype(self.dtype, onp.complexfloating):\n" } ]
Python
Apache License 2.0
google/jax
simplify xla op metadata, DeviceArray repr Just minor cleanup.
260,335
09.11.2019 17:08:54
28,800
46db509b30fe1c3067aa6264526a5e2a3d7f6b9d
rename TestSpec -> CallSpec to avoid warning
[ { "change_type": "MODIFY", "old_path": "tests/core_test.py", "new_path": "tests/core_test.py", "diff": "@@ -106,19 +106,19 @@ def product_io_fun(x, y):\nR = onp.random.randn\n-TestSpec = namedtuple('TestSpec', ['fun', 'args'])\n+CallSpec = namedtuple('CallSpec', ['fun', 'args'])\ntest_specs_base = [\n- TestSpec(simple_fun, (R(3, 2), R(3, 2))),\n- TestSpec(simple_fun_fanout, (R(3, 2), R(3, 2))),\n- TestSpec(product_io_fun, ({'a': R(2, 2), 'b': R(2, 2)},\n+ CallSpec(simple_fun, (R(3, 2), R(3, 2))),\n+ CallSpec(simple_fun_fanout, (R(3, 2), R(3, 2))),\n+ CallSpec(product_io_fun, ({'a': R(2, 2), 'b': R(2, 2)},\n(R(2, 2), (R(2, 2), R(2, 2))))),\n- TestSpec(fun_with_call, (R(3, 2),)),\n- TestSpec(fun_with_two_calls, (R(3, 2),)),\n- TestSpec(fun_with_call_closure, (R(3, 2),)),\n- TestSpec(fun_call_jitted, (R(1,),)),\n- TestSpec(fun_with_nested_calls, (R(),)),\n- TestSpec(fun_with_nested_calls, (R(3, 2),)),\n- TestSpec(fun_with_nested_calls_2, (R(1, 2),)),\n+ CallSpec(fun_with_call, (R(3, 2),)),\n+ CallSpec(fun_with_two_calls, (R(3, 2),)),\n+ CallSpec(fun_with_call_closure, (R(3, 2),)),\n+ CallSpec(fun_call_jitted, (R(1,),)),\n+ CallSpec(fun_with_nested_calls, (R(),)),\n+ CallSpec(fun_with_nested_calls, (R(3, 2),)),\n+ CallSpec(fun_with_nested_calls_2, (R(1, 2),)),\n]\ndef jvp_unlinearized(f, primals, tangents):\n@@ -128,10 +128,10 @@ def jvp_unlinearized(f, primals, tangents):\ntest_specs = []\nfor ts in test_specs_base:\ntest_specs.append(ts)\n- test_specs.append(TestSpec(partial(jvp, ts.fun), (ts.args, ts.args)))\n- test_specs.append(TestSpec(jit(ts.fun), ts.args))\n- test_specs.append(TestSpec(jit(jit(ts.fun)), ts.args))\n- test_specs.append(TestSpec(partial(jvp_unlinearized, ts.fun),\n+ test_specs.append(CallSpec(partial(jvp, ts.fun), (ts.args, ts.args)))\n+ test_specs.append(CallSpec(jit(ts.fun), ts.args))\n+ test_specs.append(CallSpec(jit(jit(ts.fun)), ts.args))\n+ test_specs.append(CallSpec(partial(jvp_unlinearized, ts.fun),\n(ts.args, ts.args)))\n" } ]
Python
Apache License 2.0
google/jax
rename TestSpec -> CallSpec to avoid warning
260,335
11.11.2019 15:07:46
28,800
6f47ac007f9358bcea7ff1cde3c1ad457a55475c
fix xla.lower_fun and jax.xla_computation
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -51,8 +51,8 @@ from .tree_util import (tree_map, tree_flatten, tree_unflatten, tree_structure,\n_replace_nones)\nfrom .util import (unzip2, unzip3, curry, partial, safe_map, safe_zip,\nWrapHashably, Hashable, prod, split_list)\n-from .lib.xla_bridge import (canonicalize_dtype, device_count,\n- local_device_count, devices, local_devices,\n+from .lib import xla_bridge as xb\n+from .lib.xla_bridge import (device_count, local_device_count, devices, local_devices,\nhost_id, host_ids, host_count)\nfrom .abstract_arrays import ShapedArray, raise_to_shaped\nfrom .interpreters import partial_eval as pe\n@@ -276,10 +276,7 @@ def xla_computation(fun, static_argnums=(), axis_env=None, backend=None,\n}\n\"\"\"\n_check_callable(fun)\n-\n- def pv_like(x):\n- aval = xla.abstractify(x)\n- return pe.PartialVal((aval, core.unit))\n+ fun_name = getattr(fun, '__name__', 'unknown')\ndef make_axis_env(nreps):\nif axis_env is None:\n@@ -294,11 +291,16 @@ def xla_computation(fun, static_argnums=(), axis_env=None, backend=None,\nwrapped = lu.wrap_init(fun)\njax_args, in_tree = tree_flatten((args, kwargs))\njaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)\n- pvals = map(pv_like, jax_args)\n+ avals = map(xla.abstractify, jax_args)\n+ pvals = [pe.PartialVal((aval, core.unit)) for aval in avals]\njaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals)\naxis_env_ = make_axis_env(xla.jaxpr_replicas(jaxpr))\n- return xla.build_jaxpr(jaxpr, backend, axis_env_, consts, tuple_args,\n- *map(xla.abstractify, jax_args))\n+ c = xb.make_computation_builder('xla_computation_{}'.format(fun_name))\n+ xla_consts = map(c.Constant, consts)\n+ xla_args = xla._xla_callable_args(c, avals, tuple_args)\n+ outs = xla.jaxpr_subcomp(c, jaxpr, backend, axis_env_, xla_consts, (),\n+ *xla_args)\n+ return c.Build(c.Tuple(*outs))\nreturn computation_maker\ndef grad(fun, argnums=0, has_aux=False, holomorphic=False):\n@@ -558,7 +560,7 @@ def _split(x, indices, axis):\nreturn x.split(indices, axis)\ndef _dtype(x):\n- return canonicalize_dtype(onp.result_type(x))\n+ return xb.canonicalize_dtype(onp.result_type(x))\ndef vmap(fun, in_axes=0, out_axes=0):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -498,9 +498,9 @@ def lower_fun(fun, instantiate=False, initial_style=False):\npvals = [pe.PartialVal((a, core.unit)) for a in avals]\njaxpr, _, consts = pe.trace_to_jaxpr(\nlu.wrap_init(fun, params), pvals, instantiate=True)\n- built_c = jaxpr_computation(jaxpr, backend, axis_env, consts, (),\n- xla_shapes, inner=True)\n- return c.Call(built_c, xla_args)\n+ consts = _map(c.Constant, consts)\n+ outs = jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, (), *xla_args)\n+ return c.Tuple(*outs)\nreturn f\ndef _aval_from_xla_shape(xla_shape):\n" } ]
Python
Apache License 2.0
google/jax
fix xla.lower_fun and jax.xla_computation
260,335
11.11.2019 15:17:11
28,800
d77cf175a9cbcbed54cb1e63d049dbb42348cf0c
add missing attribute in optix (for google tests)
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optix.py", "new_path": "jax/experimental/optix.py", "diff": "@@ -85,6 +85,7 @@ ClipByGlobalNormState = collections.namedtuple(\"ClipByGlobalNormState\", \"\")\ndef global_norm(items):\nreturn jnp.sqrt(jnp.sum([jnp.sum(x**2) for x in tree_leaves(items)]))\n+_global_norm = global_norm # TODO(mtthss): remove when google code updated\ndef clip_by_global_norm(max_norm):\n" } ]
Python
Apache License 2.0
google/jax
add missing attribute in optix (for google tests)
260,403
09.11.2019 00:16:18
28,800
032873047a2788fe30703e8ad86162b69e4e5490
linspace, logspace, geomspace jittable and differentiable in start and stop args
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -1677,6 +1677,7 @@ def arange(start, stop=None, step=None, dtype=None):\n# Fall back to instantiating an ndarray in host memory\nreturn onp.arange(start, stop=stop, step=step, dtype=dtype)\n+\ndef _wrap_numpy_nullary_function(f):\n\"\"\"Adapts `f` to return a DeviceArray instead of an onp.ndarray.\n@@ -1687,24 +1688,58 @@ def _wrap_numpy_nullary_function(f):\nreturn asarray(f(*args, **kwargs))\nreturn wrapper\n+\n+@_wraps(onp.linspace)\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,\naxis=0):\n+ \"\"\"Implementation of linspace differentiable in start and stop args.\"\"\"\nlax._check_user_dtype_supported(dtype, \"linspace\")\n- try:\n- out = onp.linspace(start, stop, num, endpoint, retstep, dtype, axis)\n- if retstep:\n- return asarray(out[0]), out[1]\n- else:\n- return asarray(out)\n- except TypeError: # Old versions of onp may lack axis arg.\n- out = onp.linspace(start, stop, num, endpoint, retstep, dtype)\n+ dtype = dtype or onp.result_type(start, stop, float(num))\n+ bounds_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))\n+ broadcast_start = broadcast_to(start, bounds_shape)\n+ axis = len(bounds_shape) + axis + 1 if axis < 0 else axis\n+ bounds_shape.insert(axis, 1)\n+ iota_shape = [1,] * len(bounds_shape)\n+ iota_shape[axis] = num\n+ if endpoint:\n+ delta = (stop - start) / (num - 1)\n+ else:\n+ delta = (stop - start) / num\n+ out = (reshape(broadcast_start, bounds_shape) +\n+ reshape(lax.iota(dtype, num), iota_shape) *\n+ reshape(delta, bounds_shape))\nif retstep:\n- return moveaxis(asarray(out[0]), 0, axis), out[1]\n+ return lax.convert_element_type(out, dtype), delta\nelse:\n- return moveaxis(asarray(out), 0, axis)\n+ return lax.convert_element_type(out, dtype)\n+\n+\n+@_wraps(onp.logspace)\n+def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):\n+ \"\"\"Implementation of logspace differentiable in start and stop args.\"\"\"\n+ lin = linspace(start, stop, num,\n+ endpoint=endpoint, retstep=False, dtype=None, axis=axis)\n+ if dtype is None:\n+ return power(base, lin)\n+ else:\n+ return lax.convert_element_type(power(base, lin), dtype)\n+\n+\n+@_wraps(onp.geomspace)\n+def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):\n+ \"\"\"Implementation of geomspace differentiable in start and stop args.\"\"\"\n+ dtype = dtype or onp.result_type(start, stop, float(num),\n+ zeros((), dtype))\n+ # follow the numpy geomspace convention for negative and complex endpoints\n+ signflip = 1 - (1 - sign(real(start))) * (1 - sign(real(stop))) // 2\n+ res = signflip * logspace(log10(signflip * start),\n+ log10(signflip * stop), num,\n+ endpoint=endpoint, base=10.0,\n+ dtype=dtype, axis=0)\n+ if axis != 0:\n+ res = moveaxis(res, 0, axis)\n+ return lax.convert_element_type(res, dtype)\n-logspace = _wrap_numpy_nullary_function(onp.logspace)\n-geomspace = _wrap_numpy_nullary_function(onp.geomspace)\n@_wraps(onp.meshgrid)\ndef meshgrid(*args, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -2034,6 +2034,167 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nlnp_fun = partial(lnp.meshgrid, indexing=indexing, sparse=sparse)\nself._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n+ def assertDowncastDtypeEqual(self, x, y):\n+ \"\"\"Heuristic for comparing numpy and jax downcast dtypes.\"\"\"\n+ x_dt = jtu._dtype(x)\n+ y_dt = jtu._dtype(y)\n+ testing_tpu = jtu.device_under_test().startswith(\"tpu\")\n+ testing_x32 = not jax.config.read('jax_enable_x64')\n+ to32dtype = {onp.int64: onp.int32, onp.uint64: onp.uint32,\n+ onp.float64: onp.float32, onp.float128: onp.float32,\n+ onp.complex128: onp.complex64, onp.complex256: onp.complex64}\n+ to32dtype = {onp.dtype(k): onp.dtype(v) for k,v in to32dtype.items()}\n+ if testing_tpu or testing_x32:\n+ x_dt = to32dtype.get(x_dt, x_dt)\n+ y_dt = to32dtype.get(y_dt, y_dt)\n+ assert x_dt == y_dt, \"truncated dtypes %s != %s\" % (x_dt, y_dt)\n+\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": (\"_start_shape={}_stop_shape={}_num={}_endpoint={}\"\n+ \"_retstep={}_dtype={}\").format(\n+ start_shape, stop_shape, num, endpoint, retstep, dtype),\n+ \"start_shape\": start_shape, \"stop_shape\": stop_shape,\n+ \"num\": num, \"endpoint\": endpoint, \"retstep\": retstep,\n+ \"dtype\": dtype, \"rng_factory\": rng_factory}\n+ for start_shape in [(), (2,), (2, 2)]\n+ for stop_shape in [(), (2,), (2, 2)]\n+ for num in [5, 20]\n+ for endpoint in [True, False]\n+ for retstep in [True, False]\n+ for dtype in number_dtypes + [None,]\n+ for rng_factory in [jtu.rand_default]))\n+ def testLinspace(self, start_shape, stop_shape, num, endpoint,\n+ retstep, dtype, rng_factory):\n+ rng = rng_factory()\n+ # relax default tolerances slightly\n+ tol = tolerance(dtype if dtype else onp.float32) * 10\n+ args_maker = self._GetArgsMaker(rng,\n+ [start_shape, stop_shape],\n+ [dtype, dtype])\n+ start, stop = args_maker()\n+ ndim = len(onp.shape(start + stop))\n+ for axis in range(-ndim, ndim):\n+ lnp_op = lambda start, stop: lnp.linspace(\n+ start, stop, num,\n+ endpoint=endpoint, retstep=retstep, dtype=dtype, axis=axis)\n+ onp_op = lambda start, stop: onp.linspace(\n+ start, stop, num,\n+ endpoint=endpoint, retstep=retstep, dtype=dtype, axis=axis)\n+ self._CheckAgainstNumpy(onp_op, lnp_op, args_maker,\n+ check_dtypes=False, tol=tol)\n+ # Check dtype equivalence within expected 32bit downcasting.\n+ a, b = lnp_op(start, stop), onp_op(start, stop)\n+ if retstep:\n+ self.assertDowncastDtypeEqual(a[0], b[0])\n+ self.assertDowncastDtypeEqual(a[1], b[1])\n+ else:\n+ self.assertDowncastDtypeEqual(a, b)\n+ # floating-point compute between jitted platforms and non-jit + rounding\n+ # cause unavoidable variation in integer truncation for some inputs.\n+ if dtype in (inexact_dtypes + [None,]):\n+ self._CompileAndCheck(lnp_op, args_maker,\n+ check_dtypes=False, atol=tol, rtol=tol)\n+\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": (\"_start_shape={}_stop_shape={}_num={}_endpoint={}\"\n+ \"_base={}_dtype={}\").format(\n+ start_shape, stop_shape, num, endpoint, base, dtype),\n+ \"start_shape\": start_shape,\n+ \"stop_shape\": stop_shape,\n+ \"num\": num, \"endpoint\": endpoint, \"base\": base,\n+ \"dtype\": dtype, \"rng_factory\": rng_factory}\n+ for start_shape in [(), (2,), (2, 2)]\n+ for stop_shape in [(), (2,), (2, 2)]\n+ for num in [5, 20]\n+ for endpoint in [True, False]\n+ for base in [10.0, 2, onp.e]\n+ for dtype in number_dtypes + [None,]\n+ for rng_factory in [jtu.rand_default]))\n+ def testLogspace(self, start_shape, stop_shape, num,\n+ endpoint, base, dtype, rng_factory):\n+ if (dtype in int_dtypes and\n+ jtu.device_under_test() == \"gpu\" and\n+ not FLAGS.jax_enable_x64):\n+ raise unittest.SkipTest(\"GPUx32 truncated exponentiation\"\n+ \" doesn't exactly match other platforms.\")\n+ rng = rng_factory()\n+ # relax default tolerances slightly\n+ tol = tolerance(dtype if dtype else onp.float32) * 10\n+ args_maker = self._GetArgsMaker(rng,\n+ [start_shape, stop_shape],\n+ [dtype, dtype])\n+ start, stop = args_maker()\n+ ndim = len(onp.shape(start + stop))\n+ for axis in range(-ndim, ndim):\n+ lnp_op = lambda start, stop: lnp.logspace(\n+ start, stop, num, endpoint=endpoint, base=base, dtype=dtype, axis=axis)\n+ onp_op = lambda start, stop: onp.logspace(\n+ start, stop, num, endpoint=endpoint, base=base, dtype=dtype, axis=axis)\n+ self._CheckAgainstNumpy(onp_op, lnp_op, args_maker,\n+ check_dtypes=False, tol=tol)\n+ # Check dtype equivalence within expected 32bit downcasting.\n+ a, b = lnp_op(start, stop), onp_op(start, stop)\n+ self.assertDowncastDtypeEqual(a, b)\n+ if dtype in (inexact_dtypes + [None,]):\n+ # Why do compiled and op-by-op float16 np.power numbers differ\n+ # slightly more than expected?\n+ atol = tol if dtype != onp.float16 else 10 * tol\n+ self._CompileAndCheck(lnp_op, args_maker,\n+ check_dtypes=False, atol=atol, rtol=tol)\n+\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": (\"_start_shape={}_stop_shape={}_num={}_endpoint={}\"\n+ \"_dtype={}\").format(\n+ start_shape, stop_shape, num, endpoint, dtype),\n+ \"start_shape\": start_shape,\n+ \"stop_shape\": stop_shape,\n+ \"num\": num, \"endpoint\": endpoint,\n+ \"dtype\": dtype, \"rng_factory\": rng_factory}\n+ for start_shape in [(), (2,), (2, 2)]\n+ for stop_shape in [(), (2,), (2, 2)]\n+ for num in [5, 20]\n+ for endpoint in [True, False]\n+ # NB: numpy's geomspace gives nonsense results on integer types\n+ for dtype in inexact_dtypes + [None,]\n+ for rng_factory in [jtu.rand_default]))\n+ def testGeomspace(self, start_shape, stop_shape, num,\n+ endpoint, dtype, rng_factory):\n+ rng = rng_factory()\n+ # relax default tolerances slightly\n+ tol = tolerance(dtype if dtype else onp.float32) * 10\n+ def args_maker():\n+ \"\"\"Test the set of inputs onp.geomspace is well-defined on.\"\"\"\n+ start, stop = self._GetArgsMaker(rng,\n+ [start_shape, stop_shape],\n+ [dtype, dtype])()\n+ # onp.geomspace can't handle differently ranked tensors\n+ # w. negative numbers!\n+ start, stop = lnp.broadcast_arrays(start, stop)\n+ if dtype in complex_dtypes:\n+ return start, stop\n+ # to avoid NaNs, non-complex start and stop cannot\n+ # differ in sign, elementwise\n+ start = start * lnp.sign(start) * lnp.sign(stop)\n+ return start, stop\n+ start, stop = args_maker()\n+ ndim = len(onp.shape(start + stop))\n+ for axis in range(-ndim, ndim):\n+ lnp_op = lambda start, stop: lnp.geomspace(\n+ start, stop, num, endpoint=endpoint, dtype=dtype, axis=axis)\n+ onp_op = lambda start, stop: onp.geomspace(\n+ start, stop, num, endpoint=endpoint, dtype=dtype, axis=axis)\n+ self._CheckAgainstNumpy(onp_op, lnp_op, args_maker,\n+ check_dtypes=False, tol=tol)\n+ # Check dtype equivalence within expected 32bit downcasting.\n+ a, b = lnp_op(start, stop), onp_op(start, stop)\n+ self.assertDowncastDtypeEqual(a, b)\n+ if dtype in (inexact_dtypes + [None,]):\n+ self._CompileAndCheck(lnp_op, args_maker,\n+ check_dtypes=False, atol=tol, rtol=tol)\n+\ndef testDisableNumpyRankPromotionBroadcasting(self):\ntry:\nprev_flag = FLAGS.jax_numpy_rank_promotion\n" } ]
Python
Apache License 2.0
google/jax
linspace, logspace, geomspace jittable and differentiable in start and stop args
260,335
12.11.2019 06:18:43
28,800
c4101c562739d87334632e1bd8d08f40e9c768f4
fix DeviceArray repr (for google internal test)
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -647,7 +647,10 @@ class DeviceArray(DeviceValue):\nself._npy_value = None\ndef __repr__(self):\n- return onp.array_repr(self._value)\n+ # TODO(mattjj): consider implementing array_repr ourselves\n+ s = onp.array_repr(self._value)\n+ assert s.startswith('array(')\n+ return 'DeviceArray(' + s[6:]\ndef item(self):\nif onp.issubdtype(self.dtype, onp.complexfloating):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1224,6 +1224,9 @@ class APITest(jtu.JaxTestCase):\npython_should_be_executing = False\napi.pmap(f, 'i')(x)\n+ def test_repr(self):\n+ rep = repr(np.ones(()) + 1.)\n+ self.assertStartsWith(rep, 'DeviceArray')\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
fix DeviceArray repr (for google internal test)
260,335
12.11.2019 06:55:01
28,800
938eb20ba11b48ec7a995e985492b0383fc35c65
improve DeviceArray.__repr__ with onp.array2string
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -647,10 +647,8 @@ class DeviceArray(DeviceValue):\nself._npy_value = None\ndef __repr__(self):\n- # TODO(mattjj): consider implementing array_repr ourselves\n- s = onp.array_repr(self._value)\n- assert s.startswith('array(')\n- return 'DeviceArray(' + s[6:]\n+ s = onp.array2string(self._value, prefix='DeviceArray(', suffix=')')\n+ return \"DeviceArray({})\".format(s)\ndef item(self):\nif onp.issubdtype(self.dtype, onp.complexfloating):\n" } ]
Python
Apache License 2.0
google/jax
improve DeviceArray.__repr__ with onp.array2string
260,335
12.11.2019 07:44:53
28,800
0d053f0e5b477d965bcb091345fbdc895dc1fff6
temporarily revert due to TFP test failures This commit unfortunately un-fixes but only until we sort out why a TF Probvability test started failing.
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -1689,56 +1689,76 @@ def _wrap_numpy_nullary_function(f):\nreturn wrapper\n-@_wraps(onp.linspace)\n+# TODO(mattjj,levskaya): use this version when we sort out test failure\n+# @_wraps(onp.linspace)\n+# def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,\n+# axis=0):\n+# \"\"\"Implementation of linspace differentiable in start and stop args.\"\"\"\n+# lax._check_user_dtype_supported(dtype, \"linspace\")\n+# dtype = dtype or onp.result_type(start, stop, float(num))\n+# bounds_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))\n+# broadcast_start = broadcast_to(start, bounds_shape)\n+# axis = len(bounds_shape) + axis + 1 if axis < 0 else axis\n+# bounds_shape.insert(axis, 1)\n+# iota_shape = [1,] * len(bounds_shape)\n+# iota_shape[axis] = num\n+# if endpoint:\n+# delta = (stop - start) / (num - 1)\n+# else:\n+# delta = (stop - start) / num\n+# out = (reshape(broadcast_start, bounds_shape) +\n+# reshape(lax.iota(dtype, num), iota_shape) *\n+# reshape(delta, bounds_shape))\n+# if retstep:\n+# return lax.convert_element_type(out, dtype), delta\n+# else:\n+# return lax.convert_element_type(out, dtype)\n+#\n+#\n+# @_wraps(onp.logspace)\n+# def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):\n+# \"\"\"Implementation of logspace differentiable in start and stop args.\"\"\"\n+# lin = linspace(start, stop, num,\n+# endpoint=endpoint, retstep=False, dtype=None, axis=axis)\n+# if dtype is None:\n+# return power(base, lin)\n+# else:\n+# return lax.convert_element_type(power(base, lin), dtype)\n+#\n+#\n+# @_wraps(onp.geomspace)\n+# def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):\n+# \"\"\"Implementation of geomspace differentiable in start and stop args.\"\"\"\n+# dtype = dtype or onp.result_type(start, stop, float(num),\n+# zeros((), dtype))\n+# # follow the numpy geomspace convention for negative and complex endpoints\n+# signflip = 1 - (1 - sign(real(start))) * (1 - sign(real(stop))) // 2\n+# res = signflip * logspace(log10(signflip * start),\n+# log10(signflip * stop), num,\n+# endpoint=endpoint, base=10.0,\n+# dtype=dtype, axis=0)\n+# if axis != 0:\n+# res = moveaxis(res, 0, axis)\n+# return lax.convert_element_type(res, dtype)\n+\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,\naxis=0):\n- \"\"\"Implementation of linspace differentiable in start and stop args.\"\"\"\nlax._check_user_dtype_supported(dtype, \"linspace\")\n- dtype = dtype or onp.result_type(start, stop, float(num))\n- bounds_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))\n- broadcast_start = broadcast_to(start, bounds_shape)\n- axis = len(bounds_shape) + axis + 1 if axis < 0 else axis\n- bounds_shape.insert(axis, 1)\n- iota_shape = [1,] * len(bounds_shape)\n- iota_shape[axis] = num\n- if endpoint:\n- delta = (stop - start) / (num - 1)\n- else:\n- delta = (stop - start) / num\n- out = (reshape(broadcast_start, bounds_shape) +\n- reshape(lax.iota(dtype, num), iota_shape) *\n- reshape(delta, bounds_shape))\n+ try:\n+ out = onp.linspace(start, stop, num, endpoint, retstep, dtype, axis)\nif retstep:\n- return lax.convert_element_type(out, dtype), delta\n+ return asarray(out[0]), out[1]\nelse:\n- return lax.convert_element_type(out, dtype)\n-\n+ return asarray(out)\n+ except TypeError: # Old versions of onp may lack axis arg.\n+ out = onp.linspace(start, stop, num, endpoint, retstep, dtype)\n+ if retstep:\n+ return moveaxis(asarray(out[0]), 0, axis), out[1]\n+ else:\n+ return moveaxis(asarray(out), 0, axis)\n-@_wraps(onp.logspace)\n-def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):\n- \"\"\"Implementation of logspace differentiable in start and stop args.\"\"\"\n- lin = linspace(start, stop, num,\n- endpoint=endpoint, retstep=False, dtype=None, axis=axis)\n- if dtype is None:\n- return power(base, lin)\n- else:\n- return lax.convert_element_type(power(base, lin), dtype)\n-\n-\n-@_wraps(onp.geomspace)\n-def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):\n- \"\"\"Implementation of geomspace differentiable in start and stop args.\"\"\"\n- dtype = dtype or onp.result_type(start, stop, float(num),\n- zeros((), dtype))\n- # follow the numpy geomspace convention for negative and complex endpoints\n- signflip = 1 - (1 - sign(real(start))) * (1 - sign(real(stop))) // 2\n- res = signflip * logspace(log10(signflip * start),\n- log10(signflip * stop), num,\n- endpoint=endpoint, base=10.0,\n- dtype=dtype, axis=0)\n- if axis != 0:\n- res = moveaxis(res, 0, axis)\n- return lax.convert_element_type(res, dtype)\n+logspace = _wrap_numpy_nullary_function(onp.logspace)\n+geomspace = _wrap_numpy_nullary_function(onp.geomspace)\n@_wraps(onp.meshgrid)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -2066,6 +2066,9 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfor rng_factory in [jtu.rand_default]))\ndef testLinspace(self, start_shape, stop_shape, num, endpoint,\nretstep, dtype, rng_factory):\n+ # TODO(mattjj,levskaya): re-enable when test failure is sorted out\n+ raise SkipTest(\"tfp test failures\")\n+\nrng = rng_factory()\n# relax default tolerances slightly\ntol = tolerance(dtype if dtype else onp.float32) * 10\n@@ -2114,6 +2117,9 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfor rng_factory in [jtu.rand_default]))\ndef testLogspace(self, start_shape, stop_shape, num,\nendpoint, base, dtype, rng_factory):\n+ # TODO(mattjj,levskaya): re-enable when test failure is sorted out\n+ raise SkipTest(\"tfp test failures\")\n+\nif (dtype in int_dtypes and\njtu.device_under_test() == \"gpu\" and\nnot FLAGS.jax_enable_x64):\n@@ -2162,6 +2168,9 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfor rng_factory in [jtu.rand_default]))\ndef testGeomspace(self, start_shape, stop_shape, num,\nendpoint, dtype, rng_factory):\n+ # TODO(mattjj,levskaya): re-enable when test failure is sorted out\n+ raise SkipTest(\"tfp test failures\")\n+\nrng = rng_factory()\n# relax default tolerances slightly\ntol = tolerance(dtype if dtype else onp.float32) * 10\n" } ]
Python
Apache License 2.0
google/jax
temporarily revert #1658 due to TFP test failures This commit unfortunately un-fixes #1571, but only until we sort out why a TF Probvability test started failing.
260,403
12.11.2019 16:40:29
28,800
350630fd1281844005c1f7eb066d839825861c9a
fix degenerate case behavior of linspace
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -1689,76 +1689,65 @@ def _wrap_numpy_nullary_function(f):\nreturn wrapper\n-# TODO(mattjj,levskaya): use this version when we sort out test failure\n-# @_wraps(onp.linspace)\n-# def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,\n-# axis=0):\n-# \"\"\"Implementation of linspace differentiable in start and stop args.\"\"\"\n-# lax._check_user_dtype_supported(dtype, \"linspace\")\n-# dtype = dtype or onp.result_type(start, stop, float(num))\n-# bounds_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))\n-# broadcast_start = broadcast_to(start, bounds_shape)\n-# axis = len(bounds_shape) + axis + 1 if axis < 0 else axis\n-# bounds_shape.insert(axis, 1)\n-# iota_shape = [1,] * len(bounds_shape)\n-# iota_shape[axis] = num\n-# if endpoint:\n-# delta = (stop - start) / (num - 1)\n-# else:\n-# delta = (stop - start) / num\n-# out = (reshape(broadcast_start, bounds_shape) +\n-# reshape(lax.iota(dtype, num), iota_shape) *\n-# reshape(delta, bounds_shape))\n-# if retstep:\n-# return lax.convert_element_type(out, dtype), delta\n-# else:\n-# return lax.convert_element_type(out, dtype)\n-#\n-#\n-# @_wraps(onp.logspace)\n-# def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):\n-# \"\"\"Implementation of logspace differentiable in start and stop args.\"\"\"\n-# lin = linspace(start, stop, num,\n-# endpoint=endpoint, retstep=False, dtype=None, axis=axis)\n-# if dtype is None:\n-# return power(base, lin)\n-# else:\n-# return lax.convert_element_type(power(base, lin), dtype)\n-#\n-#\n-# @_wraps(onp.geomspace)\n-# def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):\n-# \"\"\"Implementation of geomspace differentiable in start and stop args.\"\"\"\n-# dtype = dtype or onp.result_type(start, stop, float(num),\n-# zeros((), dtype))\n-# # follow the numpy geomspace convention for negative and complex endpoints\n-# signflip = 1 - (1 - sign(real(start))) * (1 - sign(real(stop))) // 2\n-# res = signflip * logspace(log10(signflip * start),\n-# log10(signflip * stop), num,\n-# endpoint=endpoint, base=10.0,\n-# dtype=dtype, axis=0)\n-# if axis != 0:\n-# res = moveaxis(res, 0, axis)\n-# return lax.convert_element_type(res, dtype)\n-\n+@_wraps(onp.linspace)\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,\naxis=0):\n+ \"\"\"Implementation of linspace differentiable in start and stop args.\"\"\"\nlax._check_user_dtype_supported(dtype, \"linspace\")\n- try:\n- out = onp.linspace(start, stop, num, endpoint, retstep, dtype, axis)\n+ if num < 0:\n+ raise ValueError(\"Number of samples, %s, must be non-negative.\" % num)\n+ dtype = dtype or onp.result_type(start, stop, float(num))\n+ bounds_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))\n+ broadcast_start = broadcast_to(start, bounds_shape)\n+ axis = len(bounds_shape) + axis + 1 if axis < 0 else axis\n+ bounds_shape.insert(axis, 1)\n+ iota_shape = [1,] * len(bounds_shape)\n+ iota_shape[axis] = num\n+ div = (num - 1) if endpoint else num\n+ if num > 1:\n+ delta = (stop - start) / div\n+ out = (reshape(broadcast_start, bounds_shape) +\n+ reshape(lax.iota(dtype, num), iota_shape) *\n+ reshape(delta, bounds_shape))\n+ elif num == 1:\n+ delta = nan\n+ out = reshape(broadcast_start, bounds_shape)\n+ else: # num == 0 degenerate case, match onp behavior\n+ empty_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))\n+ empty_shape.insert(axis, 0)\n+ delta = nan\n+ out = reshape(array([]), empty_shape).astype(dtype)\nif retstep:\n- return asarray(out[0]), out[1]\n+ return lax.convert_element_type(out, dtype), delta\nelse:\n- return asarray(out)\n- except TypeError: # Old versions of onp may lack axis arg.\n- out = onp.linspace(start, stop, num, endpoint, retstep, dtype)\n- if retstep:\n- return moveaxis(asarray(out[0]), 0, axis), out[1]\n- else:\n- return moveaxis(asarray(out), 0, axis)\n+ return lax.convert_element_type(out, dtype)\n-logspace = _wrap_numpy_nullary_function(onp.logspace)\n-geomspace = _wrap_numpy_nullary_function(onp.geomspace)\n+\n+@_wraps(onp.logspace)\n+def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):\n+ \"\"\"Implementation of logspace differentiable in start and stop args.\"\"\"\n+ lin = linspace(start, stop, num,\n+ endpoint=endpoint, retstep=False, dtype=None, axis=axis)\n+ if dtype is None:\n+ return power(base, lin)\n+ else:\n+ return lax.convert_element_type(power(base, lin), dtype)\n+\n+\n+@_wraps(onp.geomspace)\n+def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):\n+ \"\"\"Implementation of geomspace differentiable in start and stop args.\"\"\"\n+ dtype = dtype or onp.result_type(start, stop, float(num),\n+ zeros((), dtype))\n+ # follow the numpy geomspace convention for negative and complex endpoints\n+ signflip = 1 - (1 - sign(real(start))) * (1 - sign(real(stop))) // 2\n+ res = signflip * logspace(log10(signflip * start),\n+ log10(signflip * stop), num,\n+ endpoint=endpoint, base=10.0,\n+ dtype=dtype, axis=0)\n+ if axis != 0:\n+ res = moveaxis(res, 0, axis)\n+ return lax.convert_element_type(res, dtype)\n@_wraps(onp.meshgrid)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1242,7 +1242,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfor axis in set(range(-len(shape), len(shape))) | set([None])\n# `weights_shape` is either `None`, same as the averaged axis, or same as\n# that of the input\n- for weights_shape in ([None, shape] if axis is None\n+ for weights_shape in ([None, shape] if axis is None or len(shape) == 1\nelse [None, (shape[axis],), shape])\nfor returned in [False, True]))\ndef testAverage(self, shape, dtype, axis, weights_shape, returned, rng_factory):\n@@ -2059,16 +2059,13 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n\"dtype\": dtype, \"rng_factory\": rng_factory}\nfor start_shape in [(), (2,), (2, 2)]\nfor stop_shape in [(), (2,), (2, 2)]\n- for num in [5, 20]\n+ for num in [0, 1, 2, 5, 20]\nfor endpoint in [True, False]\nfor retstep in [True, False]\nfor dtype in number_dtypes + [None,]\nfor rng_factory in [jtu.rand_default]))\ndef testLinspace(self, start_shape, stop_shape, num, endpoint,\nretstep, dtype, rng_factory):\n- # TODO(mattjj,levskaya): re-enable when test failure is sorted out\n- raise SkipTest(\"tfp test failures\")\n-\nrng = rng_factory()\n# relax default tolerances slightly\ntol = tolerance(dtype if dtype else onp.float32) * 10\n@@ -2110,16 +2107,13 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n\"dtype\": dtype, \"rng_factory\": rng_factory}\nfor start_shape in [(), (2,), (2, 2)]\nfor stop_shape in [(), (2,), (2, 2)]\n- for num in [5, 20]\n+ for num in [0, 1, 2, 5, 20]\nfor endpoint in [True, False]\nfor base in [10.0, 2, onp.e]\nfor dtype in number_dtypes + [None,]\nfor rng_factory in [jtu.rand_default]))\ndef testLogspace(self, start_shape, stop_shape, num,\nendpoint, base, dtype, rng_factory):\n- # TODO(mattjj,levskaya): re-enable when test failure is sorted out\n- raise SkipTest(\"tfp test failures\")\n-\nif (dtype in int_dtypes and\njtu.device_under_test() == \"gpu\" and\nnot FLAGS.jax_enable_x64):\n@@ -2161,16 +2155,13 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n\"dtype\": dtype, \"rng_factory\": rng_factory}\nfor start_shape in [(), (2,), (2, 2)]\nfor stop_shape in [(), (2,), (2, 2)]\n- for num in [5, 20]\n+ for num in [0, 1, 2, 5, 20]\nfor endpoint in [True, False]\n# NB: numpy's geomspace gives nonsense results on integer types\nfor dtype in inexact_dtypes + [None,]\nfor rng_factory in [jtu.rand_default]))\ndef testGeomspace(self, start_shape, stop_shape, num,\nendpoint, dtype, rng_factory):\n- # TODO(mattjj,levskaya): re-enable when test failure is sorted out\n- raise SkipTest(\"tfp test failures\")\n-\nrng = rng_factory()\n# relax default tolerances slightly\ntol = tolerance(dtype if dtype else onp.float32) * 10\n" } ]
Python
Apache License 2.0
google/jax
fix degenerate case behavior of linspace
260,405
12.11.2019 18:11:39
28,800
ddbdcfb9c965d8c8b27f2114d0369e715d71380a
Add TPU Driver to jaxlib
[ { "change_type": "MODIFY", "old_path": "build/BUILD.bazel", "new_path": "build/BUILD.bazel", "diff": "@@ -28,6 +28,7 @@ sh_binary(\nsrcs = [\"install_xla_in_source_tree.sh\"],\ndata = [\n\"@org_tensorflow//tensorflow/compiler/xla/python:xla_client\",\n+ \"@org_tensorflow//tensorflow/compiler/xla/python/tpu_driver/client:py_tpu_client\",\n\"//jaxlib\",\n\"//jaxlib:lapack.so\",\n\"//jaxlib:pytree\",\n" }, { "change_type": "MODIFY", "old_path": "build/install_xla_in_source_tree.sh", "new_path": "build/install_xla_in_source_tree.sh", "diff": "@@ -62,8 +62,16 @@ cp -f \"$(rlocation __main__/jaxlib/version.py)\" \"${TARGET}/jaxlib\"\ncp -f \"$(rlocation __main__/jaxlib/cusolver.py)\" \"${TARGET}/jaxlib\"\ncp -f \"$(rlocation org_tensorflow/tensorflow/compiler/xla/python/xla_extension.so)\" \\\n\"${TARGET}/jaxlib\"\n+cp -f \"$(rlocation org_tensorflow/tensorflow/compiler/xla/python/tpu_driver/client/tpu_client_extension.so)\" \\\n+ \"${TARGET}/jaxlib\"\nsed \\\n-e 's/from tensorflow.compiler.xla.python import xla_extension as _xla/from . import xla_extension as _xla/' \\\n-e 's/from tensorflow.compiler.xla.python.xla_extension import ops/from .xla_extension import ops/' \\\n< \"$(rlocation org_tensorflow/tensorflow/compiler/xla/python/xla_client.py)\" \\\n> \"${TARGET}/jaxlib/xla_client.py\"\n+sed \\\n+ -e 's/from tensorflow.compiler.xla.python import xla_extension as _xla/from . import xla_extension as _xla/' \\\n+ -e 's/from tensorflow.compiler.xla.python import xla_client/from . import xla_client/' \\\n+ -e 's/from tensorflow.compiler.xla.python.tpu_driver.client import tpu_client_extension as _tpu_client/from . import tpu_client_extension as _tpu_client/' \\\n+ < \"$(rlocation org_tensorflow/tensorflow/compiler/xla/python/tpu_driver/client/tpu_client.py)\" \\\n+ > \"${TARGET}/jaxlib/tpu_client.py\"\n" } ]
Python
Apache License 2.0
google/jax
Add TPU Driver to jaxlib (#1673)
260,335
12.11.2019 18:38:07
28,800
6cd995e3ffe8c8fc87679ea3d23f57b488de0196
allow tokens in op-by-op by calling into _xla_callable_args
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -135,19 +135,18 @@ def xla_primitive_callable(prim, *abstract_args, **params):\nhandle_result = lambda xs: tuple(h(x) for h, x in zip(handlers, xs.destructure()))\nelse:\nhandle_result = aval_to_result_handler(aval_out)\n- xla_shapes = tuple(map(aval_to_xla_shape, abstract_args))\n- built_c = primitive_computation(prim, *xla_shapes, **params)\n+ built_c = primitive_computation(prim, *abstract_args, **params)\ncompiled = built_c.Compile(compile_options=xb.get_compile_options(),\nbackend=xb.get_backend(backend))\nreturn partial(_execute_compiled_primitive, prim, compiled, backend, handle_result)\n@cache()\n-def primitive_computation(prim, *xla_shapes, **params):\n+def primitive_computation(prim, *avals, **params):\nc = xb.make_computation_builder(\"primitive_computation_{}\".format(prim.name))\nc.SetOpMetadata(xc.OpMetadata(op_type=prim.name, op_name=str(params)))\nbackend = params.pop(\"backend\", None)\nplatform = xb.get_backend(backend).platform\n- xla_args = _map(c.ParameterWithShape, xla_shapes)\n+ xla_args = _xla_callable_args(c, avals, False)\nif prim in backend_specific_translations[platform]:\nrule = backend_specific_translations[platform][prim]\nrule(c, *xla_args, **params) # return val set as a side-effect on c\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -3345,7 +3345,7 @@ def _reduce_sum_shape_rule(operand, axes, input_shape):\ndef _reduce_sum_translation_rule(c, operand, axes, input_shape):\ndtype = c.GetShape(operand).numpy_dtype()\n- scalar = xla_client.Shape.array_shape(dtype, ())\n+ scalar = ShapedArray((), dtype)\nreturn c.Reduce(operand, c.Constant(onp.array(0, dtype)),\nxla.primitive_computation(add_p, scalar, scalar),\naxes)\n@@ -3369,7 +3369,7 @@ def _reduce_prod_shape_rule(operand, axes):\ndef _reduce_prod_translation_rule(c, operand, axes):\ndtype = c.GetShape(operand).numpy_dtype()\n- scalar = xla_client.Shape.array_shape(dtype, ())\n+ scalar = ShapedArray((), dtype)\nreturn c.Reduce(operand, c.Constant(onp.array(1, dtype)),\nxla.primitive_computation(mul_p, scalar, scalar),\naxes)\n@@ -3415,7 +3415,7 @@ def _reduce_chooser_shape_rule(operand, axes):\ndef _reduce_chooser_translation_rule(prim, identity, c, operand, axes):\ndtype = c.GetShape(operand).numpy_dtype()\n- scalar = xla_client.Shape.array_shape(dtype, ())\n+ scalar = ShapedArray((), dtype)\nreturn c.Reduce(operand, c.Constant(identity(dtype)),\nxla.primitive_computation(prim, scalar, scalar), axes)\n@@ -3452,7 +3452,7 @@ def _reduce_logical_shape_rule(operand, axes):\nreturn tuple(onp.delete(operand.shape, axes))\ndef _reduce_logical_translation_rule(prim, identity, c, operand, axes):\n- scalar = xla_client.Shape.array_shape(onp.dtype(onp.bool_), ())\n+ scalar = ShapedArray((), onp.bool_)\nreturn c.Reduce(operand, c.Constant(identity(onp.bool_)),\nxla.primitive_computation(prim, scalar, scalar), axes)\n@@ -3515,7 +3515,7 @@ def _reduce_window_sum_shape_rule(operand, window_dimensions, window_strides,\ndef _reduce_window_sum_translation_rule(c, operand, window_dimensions,\nwindow_strides, padding, input_shape):\ndtype = c.GetShape(operand).numpy_dtype()\n- scalar = xla_client.Shape.array_shape(dtype, ())\n+ scalar = ShapedArray((), dtype)\nreturn c.ReduceWindow(operand, c.Constant(onp.array(0, dtype)),\nxla.primitive_computation(add_p, scalar, scalar),\nwindow_dimensions, window_strides, padding)\n@@ -3562,7 +3562,7 @@ batching.primitive_batchers[reduce_window_sum_p] = partial(\ndef _reduce_window_chooser_translation_rule(\nprim, identity, c, operand, window_dimensions, window_strides, padding):\ndtype = c.GetShape(operand).numpy_dtype()\n- scalar = xla_client.Shape.array_shape(dtype, ())\n+ scalar = ShapedArray((), dtype)\nreturn c.ReduceWindow(operand, c.Constant(identity(dtype)),\nxla.primitive_computation(prim, scalar, scalar),\nwindow_dimensions, window_strides, padding)\n@@ -3653,7 +3653,7 @@ def _select_and_scatter_add_translation(\nc, source, operand, select_prim, window_dimensions, window_strides,\npadding):\ndtype = c.GetShape(operand).numpy_dtype()\n- scalar = xla_client.Shape.array_shape(dtype, ())\n+ scalar = ShapedArray((), dtype)\nselect = xla.primitive_computation(select_prim, scalar, scalar)\nscatter = xla.primitive_computation(add_p, scalar, scalar)\nzero = c.Constant(onp.array(0, dtype))\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax_control_flow.py", "new_path": "jax/lax/lax_control_flow.py", "diff": "@@ -205,7 +205,7 @@ def _while_loop_translation_rule(c, axis_env, *args, **kwargs):\npred, = xla.jaxpr_subcomp(cond_c, cond_jaxpr.jaxpr, backend, axis_env,\n_map(cond_c.Constant, cond_jaxpr.literals), (), *(x + z))\nif batched:\n- scalar = xla_client.Shape.array_shape(onp.dtype(onp.bool_), ())\n+ scalar = ShapedArray((), onp.bool_)\nor_ = xla.primitive_computation(lax.or_p, scalar, scalar)\npred = cond_c.Reduce(pred, cond_c.Constant(onp.array(False)), or_,\nlist(range(cond_jaxpr.out_avals[0].ndim)))\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax_parallel.py", "new_path": "jax/lax/lax_parallel.py", "diff": "@@ -189,7 +189,7 @@ def _allreduce_split_axis_rule(prim, reducer, vals, which_mapped, axis_name):\ndef _allreduce_translation_rule(prim, c, val, replica_groups, backend=None):\ndtype = c.GetShape(val).numpy_dtype()\n- scalar = xla_client.Shape.array_shape(dtype, ())\n+ scalar = ShapedArray((), dtype)\ncomputation = xla.primitive_computation(prim, scalar, scalar, backend=backend)\nreturn c.AllReduce(val, computation, replica_groups=replica_groups)\n" } ]
Python
Apache License 2.0
google/jax
allow tokens in op-by-op by calling into _xla_callable_args
260,335
13.11.2019 22:13:01
28,800
87774de3a267f37c8b3b79cec41ab73658c27fe9
disable lax.axis_index because it's buggy
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -227,6 +227,7 @@ parallel_pure_rules = {}\ndef axis_index(axis_name):\n+ raise NotImplementedError # TODO(mattjj): fix\ndynamic_axis_env = _thread_local_state.dynamic_axis_env\nframe = dynamic_axis_env[axis_name]\ndummy_arg = frame.pmap_trace.pure(core.unit)\n" }, { "change_type": "MODIFY", "old_path": "tests/parallel_test.py", "new_path": "tests/parallel_test.py", "diff": "@@ -76,6 +76,7 @@ class PapplyTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testSelect(self):\n+ raise SkipTest(\"buggy\") # TODO(mattjj): fix\np = onp.arange(15).reshape((5, 3)) % 4 == 1\nf = onp.zeros((5, 3))\n@@ -158,6 +159,7 @@ class ParallelizeTest(jtu.JaxTestCase):\nself.assertIn('psum', repr(jaxpr))\ndef testAdd(self):\n+ raise SkipTest(\"buggy\") # TODO(mattjj): fix\nx = onp.arange(10)\ny = 2 * onp.arange(10)\ndef f(x): return x + y\n@@ -166,6 +168,7 @@ class ParallelizeTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testAdd2(self):\n+ raise SkipTest(\"buggy\") # TODO(mattjj): fix\nx = onp.arange(10)\ny = 2 * onp.arange(10)\ndef f(y): return x + y\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -479,6 +479,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertEqual(c.ravel()[0], device_count * 1)\ndef testAxisIndex(self):\n+ raise SkipTest(\"buggy\") # TODO(mattjj): fix\ndevice_count = xla_bridge.device_count()\nf = pmap(lambda x: x + pxla.axis_index('i'), 'i')\nx = np.ones(device_count)\n@@ -558,6 +559,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testSoftPmapAxisIndex(self):\n+ raise SkipTest(\"buggy\") # TODO(mattjj): fix\nn = 4 * xla_bridge.device_count()\ndef f(x):\nreturn x * lax.axis_index('i')\n@@ -574,6 +576,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testSoftPmapNested(self):\n+ raise SkipTest(\"buggy\") # TODO(mattjj): fix\nn = 4 * xla_bridge.device_count()\n@partial(soft_pmap, axis_name='i')\n@@ -587,6 +590,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testGradOfSoftPmap(self):\n+ raise SkipTest(\"buggy\") # TODO(mattjj): fix\nn = 4 * xla_bridge.device_count()\n@partial(soft_pmap, axis_name='i')\n" } ]
Python
Apache License 2.0
google/jax
disable lax.axis_index because it's buggy
260,335
14.11.2019 00:22:25
28,800
483553ffd700362d4c475ccaab063e412673e4cc
patch lax.axis_index, add warning about soft_pmap
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -888,6 +888,7 @@ class _TempAxisName(object):\ndef soft_pmap(fun, axis_name=None, backend=None):\n+ warn(\"soft_pmap is an experimental feature and probably has bugs!\")\n_check_callable(fun)\naxis_name = _TempAxisName(fun) if axis_name is None else axis_name\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -187,6 +187,14 @@ class DynamicAxisEnv(list):\nelse:\nassert False\n+ @property\n+ def sizes(self):\n+ return tuple(frame.hard_size for frame in self)\n+\n+ @property\n+ def nreps(self):\n+ return prod(frame.hard_size for frame in self)\n+\nclass _ThreadLocalState(threading.local):\ndef __init__(self):\nself.dynamic_axis_env = DynamicAxisEnv()\n@@ -227,13 +235,15 @@ parallel_pure_rules = {}\ndef axis_index(axis_name):\n- raise NotImplementedError # TODO(mattjj): fix\ndynamic_axis_env = _thread_local_state.dynamic_axis_env\nframe = dynamic_axis_env[axis_name]\n+ sizes = dynamic_axis_env.sizes[:dynamic_axis_env.index(frame)+1]\n+ nreps = dynamic_axis_env.nreps\ndummy_arg = frame.pmap_trace.pure(core.unit)\nif frame.soft_trace:\ndummy_arg = frame.soft_trace.pure(dummy_arg)\n- return axis_index_p.bind(dummy_arg, hard_size=frame.hard_size,\n+\n+ return axis_index_p.bind(dummy_arg, nreps=nreps, sizes=sizes,\nsoft_size=frame.soft_size, axis_name=axis_name)\ndef _axis_index_partial_eval(trace, _, **params):\n@@ -246,9 +256,10 @@ def _axis_index_partial_eval(trace, _, **params):\nout_tracer.recipe = eqn\nreturn out_tracer\n-def _axis_index_translation_rule(c, hard_size, soft_size, axis_name):\n- unsigned_index = c.Rem(c.ReplicaId(),\n- c.Constant(onp.array(hard_size, onp.uint32)))\n+def _axis_index_translation_rule(c, nreps, sizes, soft_size, axis_name):\n+ div = c.Constant(onp.array(nreps // prod(sizes), dtype=onp.uint32))\n+ mod = c.Constant(onp.array(sizes[-1], dtype=onp.uint32))\n+ unsigned_index = c.Rem(c.Div(c.ReplicaId(), div), mod)\nreturn c.ConvertElementType(unsigned_index, xb.dtype_to_etype(onp.int32))\naxis_index_p = core.Primitive('axis_index')\n" }, { "change_type": "MODIFY", "old_path": "tests/parallel_test.py", "new_path": "tests/parallel_test.py", "diff": "@@ -76,7 +76,6 @@ class PapplyTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testSelect(self):\n- raise SkipTest(\"buggy\") # TODO(mattjj): fix\np = onp.arange(15).reshape((5, 3)) % 4 == 1\nf = onp.zeros((5, 3))\n@@ -159,7 +158,6 @@ class ParallelizeTest(jtu.JaxTestCase):\nself.assertIn('psum', repr(jaxpr))\ndef testAdd(self):\n- raise SkipTest(\"buggy\") # TODO(mattjj): fix\nx = onp.arange(10)\ny = 2 * onp.arange(10)\ndef f(x): return x + y\n@@ -168,7 +166,6 @@ class ParallelizeTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testAdd2(self):\n- raise SkipTest(\"buggy\") # TODO(mattjj): fix\nx = onp.arange(10)\ny = 2 * onp.arange(10)\ndef f(y): return x + y\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -479,7 +479,6 @@ class PmapTest(jtu.JaxTestCase):\nself.assertEqual(c.ravel()[0], device_count * 1)\ndef testAxisIndex(self):\n- raise SkipTest(\"buggy\") # TODO(mattjj): fix\ndevice_count = xla_bridge.device_count()\nf = pmap(lambda x: x + pxla.axis_index('i'), 'i')\nx = np.ones(device_count)\n@@ -559,7 +558,6 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testSoftPmapAxisIndex(self):\n- raise SkipTest(\"buggy\") # TODO(mattjj): fix\nn = 4 * xla_bridge.device_count()\ndef f(x):\nreturn x * lax.axis_index('i')\n@@ -576,7 +574,6 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testSoftPmapNested(self):\n- raise SkipTest(\"buggy\") # TODO(mattjj): fix\nn = 4 * xla_bridge.device_count()\n@partial(soft_pmap, axis_name='i')\n@@ -590,7 +587,6 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testGradOfSoftPmap(self):\n- raise SkipTest(\"buggy\") # TODO(mattjj): fix\nn = 4 * xla_bridge.device_count()\n@partial(soft_pmap, axis_name='i')\n" } ]
Python
Apache License 2.0
google/jax
patch lax.axis_index, add warning about soft_pmap
260,405
14.11.2019 14:00:08
28,800
3f0c1cd9dd22a3b3c7abcf769a0eb46d2a009fb7
Add TPU Driver as JAX backend for high-performance access to Google Cloud TPU hardware.
[ { "change_type": "MODIFY", "old_path": "jax/lib/__init__.py", "new_path": "jax/lib/__init__.py", "diff": "@@ -44,6 +44,10 @@ def _check_jaxlib_version():\n_check_jaxlib_version()\n+try:\n+ from jaxlib import tpu_client\n+except:\n+ tpu_client = None\nfrom jaxlib import xla_client\nfrom jaxlib import lapack\n" }, { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -35,6 +35,10 @@ import numpy as onp # 'onp' rather than 'np' to distinguish from autograd.numpy\nimport six\nimport threading\n+try:\n+ from . import tpu_client\n+except ImportError:\n+ tpu_client = None\nfrom . import version\nfrom . import xla_client\n@@ -44,7 +48,8 @@ flags.DEFINE_bool('jax_enable_x64',\n'Enable 64-bit types to be used.')\nflags.DEFINE_string(\n'jax_xla_backend', 'xla',\n- 'Default is \"xla\" for the XLA service directly.')\n+ 'Default is \"xla\" for the XLA service directly, '\n+ 'or \"tpu_driver\" for using high-performance access to Cloud TPU hardware.')\nflags.DEFINE_string(\n'jax_backend_target', 'local',\n'Either \"local\" or \"rpc:address\" to connect to a remote service target.')\n@@ -116,7 +121,18 @@ def _get_local_backend(platform=None):\nreturn backend\n+def _get_tpu_driver_backend(platform):\n+ del platform\n+ backend_target = FLAGS.jax_backend_target\n+ if backend_target is None:\n+ raise ValueError('When using TPU Driver as the backend, you must specify '\n+ '--jax_backend_target=<hostname>:8470.')\n+ return tpu_client.TpuBackend.create(worker=backend_target)\n+\n+\nregister_backend('xla', _get_local_backend)\n+if tpu_client:\n+ register_backend('tpu_driver', _get_tpu_driver_backend)\n_backend_lock = threading.Lock()\n" } ]
Python
Apache License 2.0
google/jax
Add TPU Driver as JAX backend for high-performance access to Google Cloud TPU hardware. (#1675)
260,335
14.11.2019 16:15:50
28,800
c19e65b7abc0508599a9cf9175aa33d1e808217d
fix shard_args logic, closes
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -16,7 +16,7 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n-from collections import namedtuple\n+from collections import namedtuple, defaultdict\nfrom contextlib import contextmanager\nimport itertools as it\nimport operator as op\n@@ -49,16 +49,16 @@ _map = safe_map\ndef identity(x): return x\ndef shard_args(backend, devices, assignments, axis_size, tuple_args, args):\n- \"\"\"Shard an argument data array arg along its leading axis.\n+ \"\"\"Shard each argument data array along its leading axis.\nArgs:\n- devices: list of Devices of length num_replicas mapping a logical replica\n- index to a physical device.\n- assignments: replica to shard assignment.\n- axis_size: int, size of the axis to be sharded.\n+ backend: the platform to be used\n+ devices: list of Devices mapping replica index to a physical device.\n+ assignments: list of integers with the same length as `devices` mapping\n+ replica index to an index along the leading axis (i.e. a shard).\n+ axis_size: int, size of the leading axis to be sharded.\nargs: a sequence of JaxTypes representing arguments to be sharded along\n- their leading axes (or the leading axess of their leaves in the tuple\n- case) and placed on `devices`.\n+ their leading axes and placed on `devices`.\nReturns:\nA list of device buffers with the same length as `devices` indexed by\n@@ -72,12 +72,28 @@ def shard_args(backend, devices, assignments, axis_size, tuple_args, args):\n# inline handling for ShardedDeviceArray as a special case for performance\nif type(arg) is ShardedDeviceArray:\nif nrep == len(arg.device_buffers):\n+ # The argument is already prepared for the right number of replicas, so\n+ # we just ensure that buf[r] is on devices[r] for each replica index r\n+ # TODO(mattjj): compared to the other case, this logic has less looping\n+ # but could incur more device-to-device data movement\nfor r, buf in enumerate(arg.device_buffers):\n- buffers[r][a] = (buf if buf.device() == devices[r]\n- else buf.copy_to_device(devices[r]))\n+ buffers[r][a] = buf if buf.device() == devices[r] else buf.copy_to_device(devices[r])\nelse:\n+ # The argument is prepared for a different number of replicas, so for\n+ # each of our replica indices we check if there's already a buffer with\n+ # the correct logical assignment on the correct device, and if not just\n+ # copy one of them\n+ prev_assignments = assign_shards_to_replicas(len(arg.device_buffers), axis_size)\n+ candidates = defaultdict(list)\nfor r, buf in enumerate(arg.device_buffers):\n- buffers[r][a] = xla.device_put(x[assignments[r]], devices[r], backend=backend)\n+ candidates[prev_assignments[r]].append(buf)\n+ for r in range(nrep):\n+ for buf in candidates[assignments[r]]:\n+ if buf.device() == devices[r]:\n+ buffers[r][a] = buf\n+ break\n+ else:\n+ buffers[r][a] = buf.copy_to_device(devices[r])\nelse:\nbufs = shard_arg_handlers[type(arg)](arg, devices, assignments, backend=backend)\nfor r, buf in enumerate(bufs):\n@@ -89,6 +105,7 @@ def shard_args(backend, devices, assignments, axis_size, tuple_args, args):\nreturn buffers\n+\nshard_arg_handlers = {}\nshard_arg_handlers[core.Unit] = \\\nlambda x, devices, _, backend=None: [\n" } ]
Python
Apache License 2.0
google/jax
fix shard_args logic, closes #1688 Co-authored-by: Skye Wanderman-Milne <skyewm@google.com>
260,335
14.11.2019 16:51:39
28,800
be28700b8babb7e4951f21f7f0356864fcda64ea
skip some tests on tpu
[ { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -1512,6 +1512,7 @@ class LaxTest(jtu.JaxTestCase):\n\"Shapes must be 1D sequences of concrete values of integer type.*\",\nlambda: lax.reshape(onp.ones(3,), (1.5, 2.0)))\n+ @jtu.skip_on_devices(\"tpu\") # S16 not supported on TPU\ndef testDynamicSliceTypeErrors(self):\nself.assertRaisesRegexp(\nTypeError,\n@@ -1519,6 +1520,7 @@ class LaxTest(jtu.JaxTestCase):\nlambda: lax.dynamic_slice(onp.ones((3, 4), dtype=onp.float32),\n(onp.int32(1), onp.int16(2)), (2, 2)))\n+ @jtu.skip_on_devices(\"tpu\") # S16 not supported on TPU\ndef testDynamicUpdateSliceTypeErrors(self):\nself.assertRaisesRegexp(\nTypeError,\n" } ]
Python
Apache License 2.0
google/jax
skip some tests on tpu
260,335
14.11.2019 21:18:23
28,800
728cb7fba86843217a67e0b2b5ffd6c1411fec71
improve grad error message without enough args fixes
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -388,6 +388,13 @@ def value_and_grad(fun, argnums=0, has_aux=False, holomorphic=False):\n@wraps(fun, docstr=docstr, argnums=argnums)\ndef value_and_grad_f(*args, **kwargs):\n+ max_argnum = argnums if type(argnums) is int else max(argnums)\n+ if max_argnum >= len(args):\n+ msg = (\"differentiating with respect to argnums={} requires at least \"\n+ \"{} positional arguments to be passed by the caller, but got only \"\n+ \"{} positional arguments.\")\n+ raise TypeError(msg.format(argnums, max_argnum + 1, len(args)))\n+\nf = lu.wrap_init(fun, kwargs)\nf_partial, dyn_args = _argnums_partial(f, argnums, args)\nif not has_aux:\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1253,5 +1253,17 @@ class APITest(jtu.JaxTestCase):\nrep = repr(np.ones(()) + 1.)\nself.assertStartsWith(rep, 'DeviceArray')\n+ def test_grad_without_enough_args_error_message(self):\n+ # https://github.com/google/jax/issues/1696\n+ def f(x, y): return x + y\n+ df = api.grad(f, argnums=0)\n+ self.assertRaisesRegexp(\n+ TypeError,\n+ \"differentiating with respect to argnums=0 requires at least 1 \"\n+ \"positional arguments to be passed by the caller, but got only 0 \"\n+ \"positional arguments.\",\n+ lambda: partial(df, x=0.)(y=1.))\n+\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
improve grad error message without enough args fixes #1696
260,335
14.11.2019 21:37:28
28,800
3ac3271381dc2628f843ea0a6120a6f9664963f4
improve docs on shape/dtype loop stability also tweak how some error messages are printed, and corresponding tests fixes
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax_control_flow.py", "new_path": "jax/lax/lax_control_flow.py", "diff": "@@ -112,6 +112,14 @@ def fori_loop(lower, upper, body_fun, init_val):\nUnlike that Python version, ``fori_loop`` is implemented in terms of a call to\n``while_loop``. See the docstring for ``while_loop`` for more information.\n+ Also unlike the Python analogue, the loop-carried value ``val`` must hold a\n+ fixed shape and dtype across all iterations (and not just be consistent up to\n+ NumPy rank/shape broadcasting and dtype promotion rules, for example). In\n+ other words, the type ``a`` in the type signature above represents an array\n+ with a fixed shape and dtype (or a nested tuple/list/dict container data\n+ structure with a fixed structure and arrays with fixed shape and dtype at the\n+ leaves).\n+\nArgs:\nlower: an integer representing the loop index lower bound (inclusive)\nupper: an integer representing the loop index upper bound (exclusive)\n@@ -155,6 +163,14 @@ def while_loop(cond_fun, body_fun, init_val):\nfor jit-compiled functions, since native Python loop constructs in an ``@jit``\nfunction are unrolled, leading to large XLA computations.\n+ Also unlike the Python analogue, the loop-carried value ``val`` must hold a\n+ fixed shape and dtype across all iterations (and not just be consistent up to\n+ NumPy rank/shape broadcasting and dtype promotion rules, for example). In\n+ other words, the type ``a`` in the type signature above represents an array\n+ with a fixed shape and dtype (or a nested tuple/list/dict container data\n+ structure with a fixed structure and arrays with fixed shape and dtype at the\n+ leaves).\n+\nAnother difference from using Python-native loop constructs is that\n``while_loop`` is not reverse-mode differentiable because XLA computations\nrequire static bounds on memory requirements.\n@@ -455,6 +471,13 @@ def scan(f, init, xs):\nfor jit-compiled functions, since native Python loop constructs in an ``@jit``\nfunction are unrolled, leading to large XLA computations.\n+ Finally, the loop-carried value ``carry`` must hold a fixed shape and dtype\n+ across all iterations (and not just be consistent up to NumPy rank/shape\n+ broadcasting and dtype promotion rules, for example). In other words, the type\n+ ``c`` in the type signature above represents an array with a fixed shape and\n+ dtype (or a nested tuple/list/dict container data structure with a fixed\n+ structure and arrays with fixed shape and dtype at the leaves).\n+\nArgs:\nf: a Python function to be scanned of type ``c -> a -> (c, b)``, meaning\nthat ``f`` accepts two arguments where the first is a value of the loop\n@@ -968,7 +991,7 @@ def _check_tree_and_avals(what, tree1, avals1, tree2, avals2):\nraise TypeError(msg.format(what, tree1, tree2))\nif not all(safe_map(typematch, avals1, avals2)):\nmsg = (\"{} must have identical types, \"\n- \"got {} and {}.\")\n+ \"got\\n{}\\nand\\n{}.\")\nraise TypeError(msg.format(what, tree_unflatten(tree1, avals1),\ntree_unflatten(tree2, avals2)))\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -202,8 +202,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(TypeError,\nre.escape(\"body_fun output and input must have same type structure, got PyTreeDef(tuple, [*,*]) and *.\")):\nlax.while_loop(lambda c: True, lambda c: (1., 1.), 0.)\n- with self.assertRaisesRegex(TypeError,\n- re.escape(\"body_fun output and input must have identical types, got ShapedArray(bool[]) and ShapedArray(float32[]).\")):\n+ with self.assertRaisesRegex(\n+ TypeError,\n+ \"body_fun output and input must have identical types, got\\\\n\"\n+ \"ShapedArray\\(bool\\[\\]\\)\\\\n\"\n+ \"and\\\\n\"\n+ \"ShapedArray\\(float32\\[\\]\\).\"):\nlax.while_loop(lambda c: True, lambda c: True, np.float32(0.))\ndef testNestedWhileWithDynamicUpdateSlice(self):\n@@ -526,8 +530,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nre.escape(\"true_fun and false_fun output must have same type structure, got * and PyTreeDef(tuple, [*,*]).\")):\nlax.cond(True,\n1., lambda top: 1., 2., lambda fop: (2., 2.))\n- with self.assertRaisesRegex(TypeError,\n- re.escape(\"true_fun and false_fun output must have identical types, got ShapedArray(float32[1]) and ShapedArray(float32[]).\")):\n+ with self.assertRaisesRegex(\n+ TypeError,\n+ \"true_fun and false_fun output must have identical types, got\\n\"\n+ \"ShapedArray\\(float32\\[1\\]\\)\\n\"\n+ \"and\\n\"\n+ \"ShapedArray\\(float32\\[\\]\\).\"):\nlax.cond(True,\n1., lambda top: np.array([1.], np.float32),\n2., lambda fop: np.float32(1.))\n@@ -903,9 +911,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(TypeError,\nre.escape(\"scan carry output and input must have same type structure, got * and PyTreeDef(None, []).\")):\nlax.scan(lambda c, x: (0, x), None, a)\n- with self.assertRaisesRegex(TypeError,\n- re.escape(\"scan carry output and input must have identical types, \"\n- \"got ShapedArray(int32[]) and ShapedArray(float32[]).\")):\n+ with self.assertRaisesRegex(\n+ TypeError,\n+ \"scan carry output and input must have identical types, got\\n\"\n+ \"ShapedArray\\(int32\\[\\]\\)\\\\n\"\n+ \"and\\\\n\"\n+ \"ShapedArray\\(float32\\[\\]\\).\"):\nlax.scan(lambda c, x: (np.int32(0), x), np.float32(1.0), a)\nwith self.assertRaisesRegex(TypeError,\nre.escape(\"scan carry output and input must have same type structure, got * and PyTreeDef(tuple, [*,*]).\")):\n" } ]
Python
Apache License 2.0
google/jax
improve docs on shape/dtype loop stability also tweak how some error messages are printed, and corresponding tests fixes #1686
260,393
15.11.2019 14:33:39
28,800
979a8d30b77e2da9cd11e49cbdeaab29fac7c3d8
Cast perm to tuple
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax_parallel.py", "new_path": "jax/lax/lax_parallel.py", "diff": "@@ -114,7 +114,7 @@ def ppermute(x, axis_name, perm):\nAn array with the same shape as ``x`` with slices along the axis\n``axis_name`` gathered from ``x`` according to the permutation ``perm``.\n\"\"\"\n- return ppermute_p.bind(x, axis_name=axis_name, perm=perm)\n+ return ppermute_p.bind(x, axis_name=axis_name, perm=tuple(perm))\ndef pswapaxes(x, axis_name, axis):\n\"\"\"Swap the pmapped axis ``axis_name`` with the unmapped axis ``axis``.\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -331,6 +331,16 @@ class PmapTest(jtu.JaxTestCase):\nexpected = onp.roll(onp.pi + onp.arange(device_count), 1)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @jtu.skip_on_devices(\"cpu\", \"gpu\")\n+ def testIssue1703(self):\n+ num_devices = xla_bridge.device_count()\n+ perm = [num_devices - 1] + list(range(num_devices - 1))\n+ f = pmap(\n+ lambda x: lax.ppermute(x, \"i\", zip(range(num_devices), perm)), \"i\")\n+ result = f(np.arange(num_devices))\n+ expected = np.asarray(perm, dtype=np.float32)\n+ self.assertAllClose(result, expected)\n+\n@jtu.skip_on_devices(\"cpu\", \"gpu\")\ndef testRule30(self):\n# This is a test of collective_permute implementing a simple halo exchange\n" } ]
Python
Apache License 2.0
google/jax
Cast perm to tuple
260,393
15.11.2019 14:35:12
28,800
3978007be85186cb579af0b9d80d85fb7b85999b
Explict typing
[ { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -337,7 +337,7 @@ class PmapTest(jtu.JaxTestCase):\nperm = [num_devices - 1] + list(range(num_devices - 1))\nf = pmap(\nlambda x: lax.ppermute(x, \"i\", zip(range(num_devices), perm)), \"i\")\n- result = f(np.arange(num_devices))\n+ result = f(np.arange(num_devices, dtype=np.float32))\nexpected = np.asarray(perm, dtype=np.float32)\nself.assertAllClose(result, expected)\n" } ]
Python
Apache License 2.0
google/jax
Explict typing
260,335
16.11.2019 14:40:25
28,800
063419ab5f6cbcad3df6b2e509b0f1c8cf6b37c3
tweak test name (cf.
[ { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -332,7 +332,8 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\n@jtu.skip_on_devices(\"cpu\", \"gpu\")\n- def testIssue1703(self):\n+ def testPpermuteWithZipObject(self):\n+ # https://github.com/google/jax/issues/1703\nnum_devices = xla_bridge.device_count()\nperm = [num_devices - 1] + list(range(num_devices - 1))\nf = pmap(\n" } ]
Python
Apache License 2.0
google/jax
tweak test name (cf. #1704)
260,335
19.11.2019 14:20:49
28,800
5edda9e66c35cbf6c5398206a4d931e904fe0b3b
remove very old "what we're working on"
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -673,17 +673,6 @@ write unrestricted Python+Numpy and still make use of a hardware accelerator.\nBut when you want to maximize performance, you can often use `jit` in your own\ncode to compile and end-to-end optimize much bigger functions.\n-## What we're working on\n-1. Documentation!\n-2. Cloud TPU support\n-3. Multi-GPU and multi-TPU support\n-4. Full NumPy coverage and some SciPy coverage\n-5. Full coverage for vmap\n-6. Make everything faster\n- * Lowering the XLA function dispatch overhead\n- * Linear algebra routines (MKL on CPU, MAGMA on GPU)\n-7. `cond` and `while` primitives with efficient automatic differentiation\n-\n## Current gotchas\nFor a survey of current gotchas, with examples and explanations, we highly\n" } ]
Python
Apache License 2.0
google/jax
remove very old "what we're working on"
260,335
20.11.2019 07:49:13
28,800
68b7dc85c3d0ecc6893ca1bab46b0f18e40a0baf
fix multi-host pmap, disambiguate nrep When inlined a function into its caller, it mixed up two distinct values referred to as `nrep` in the two functions: num_global_replicas vs num_local_replicas. The result caused errors on multi-host setups.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -464,8 +464,8 @@ def parallel_callable(fun, backend, axis_name, axis_size, devices, *avals):\njaxpr_replicas = xla.jaxpr_replicas(jaxpr)\nnum_local_replicas = axis_size * jaxpr_replicas\n- nrep = global_axis_size * jaxpr_replicas\n- axis_env = xla.AxisEnv(nrep, [axis_name], [global_axis_size], devices)\n+ num_global_replicas = global_axis_size * jaxpr_replicas\n+ axis_env = xla.AxisEnv(num_global_replicas, [axis_name], [global_axis_size], devices)\ntuple_args = len(avals) > 100 # pass long arg lists as tuple for TPU\n@@ -476,10 +476,10 @@ def parallel_callable(fun, backend, axis_name, axis_size, devices, *avals):\nbuilt = c.Build(c.Tuple(*out_nodes))\nif devices is None:\n- if nrep > xb.device_count(backend):\n+ if num_global_replicas > xb.device_count(backend):\nmsg = (\"compiling computation that requires {} replicas, but only {} XLA \"\n\"devices are available\")\n- raise ValueError(msg.format(nrep, xb.device_count(backend)))\n+ raise ValueError(msg.format(num_global_replicas, xb.device_count(backend)))\ndevice_assignment = None\nelse:\nassert any(d.host_id == xb.host_id() for d in devices)\n@@ -492,29 +492,34 @@ def parallel_callable(fun, backend, axis_name, axis_size, devices, *avals):\n\"number of local devices passed to pmap. Got axis_size=%d, \"\n\"num_local_devices=%d.\\n(Local devices passed to pmap: %s)\"\n% (axis_size, len(local_devices), local_devices_str))\n- if nrep != len(devices):\n+ if num_global_replicas != len(devices):\nraise ValueError(\"compiling computation that requires %s replicas, \"\n\"but %s devices were specified\"\n- % (nrep, len(devices)))\n+ % (num_global_replicas, len(devices)))\ndevice_assignment = tuple(d.id for d in devices)\ncompiled = built.Compile(\n- compile_options=xb.get_compile_options(nrep, device_assignment),\n+ compile_options=xb.get_compile_options(num_global_replicas, device_assignment),\nbackend=xb.get_backend(backend))\nhandle_args = partial(shard_args, backend, compiled.local_devices(),\n- assign_shards_to_replicas(nrep, axis_size),\n+ assign_shards_to_replicas(num_local_replicas, axis_size),\naxis_size, tuple_args)\n- handle_outs = _pvals_to_results_handler(axis_size, nrep, out_pvals)\n- return partial(execute_replicated, compiled, backend, nrep, handle_args, handle_outs)\n+ handle_outs = _pvals_to_results_handler(axis_size, num_local_replicas, out_pvals)\n+ return partial(execute_replicated, compiled, backend, num_local_replicas, handle_args, handle_outs)\n+\n+class ResultToPopulate(object): pass\n+result_to_populate = ResultToPopulate()\ndef _pvals_to_results_handler(size, nrep, out_pvals):\nnouts = len(out_pvals)\nhandlers = [_pval_to_result_handler(size, nrep, pval) for pval in out_pvals]\ndef handler(out_bufs):\n- buffers = [[None] * nrep for _ in range(nouts)]\n+ buffers = [[result_to_populate] * nrep for _ in range(nouts)]\nfor r, tuple_buf in enumerate(out_bufs):\nfor i, buf in enumerate(tuple_buf.destructure()):\nbuffers[i][r] = buf\n+ assert not any(buf is result_to_populate for bufs in buffers\n+ for buf in bufs)\nreturn [h(bufs) for h, bufs in zip(handlers, buffers)]\nreturn handler\n" } ]
Python
Apache License 2.0
google/jax
fix multi-host pmap, disambiguate nrep When #1667 inlined a function into its caller, it mixed up two distinct values referred to as `nrep` in the two functions: num_global_replicas vs num_local_replicas. The result caused errors on multi-host setups. Co-authored-by: Jonathan Heek <jheek@google.com>
260,335
20.11.2019 09:12:15
28,800
2353345446486c542911a8b434802200a10d85b0
only use one gensym in tracers_to_jaxpr fixes a bug in revealed by additional internal testing
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -376,43 +376,38 @@ def new_eqn_recipe(invars, outvars, primitive, bound_subjaxprs, params):\nreturn JaxprEqnRecipe(object(), invars, map(ref, outvars), primitive,\nbound_subjaxprs, params)\n-def recipe_to_eqn(unused_var, var, recipe):\n+def recipe_to_eqn(unused_var, getvar, recipe):\n_, in_tracers, out_tracer_refs, primitive, bound_subjaxprs, params = recipe\n- out_tracers = [t_ref() if t_ref() is not None else unused_var()\n- for t_ref in out_tracer_refs]\n- assert not any(t is None for t in out_tracers)\n-\n- invars = [var(t) for t in in_tracers]\n- outvars = [var(t) for t in out_tracers]\n- new_bound_subjaxprs = [(j, map(var, c), map(var, f))\n+ out_tracers = [t_ref() for t_ref in out_tracer_refs]\n+ invars = [getvar(t) for t in in_tracers]\n+ outvars = [unused_var() if t is None else getvar(t) for t in out_tracers]\n+ new_bound_subjaxprs = [(j, map(getvar, c), map(getvar, f))\nfor j, c, f in bound_subjaxprs]\nreturn new_jaxpr_eqn(invars, outvars, primitive, new_bound_subjaxprs, params)\n-\ndef tracers_to_jaxpr(in_tracers, out_tracers):\nnewvar = core.gensym('')\n- unused_var = core.gensym('_unused')\nt_to_var = defaultdict(newvar)\n- var = lambda t: t_to_var[id(t)]\n+ getvar = lambda t: t_to_var[id(t)]\nsorted_tracers = toposort(out_tracers)\n- invars = map(var, in_tracers)\n+ invars = map(getvar, in_tracers)\neqns = []\nenv = {}\nconsts = {}\nconst_to_var = defaultdict(newvar)\ndestructuring_vars = {}\n- processed_recipes = set()\n+ processed_eqn_ids = set()\nfor t in sorted_tracers:\nrecipe = t.recipe\nif isinstance(recipe, JaxprEqnRecipe):\n- if recipe.eqn_id not in processed_recipes:\n- eqns.append(recipe_to_eqn(unused_var, var, recipe))\n- processed_recipes.add(recipe.eqn_id)\n+ if recipe.eqn_id not in processed_eqn_ids:\n+ eqns.append(recipe_to_eqn(newvar, getvar, recipe))\n+ processed_eqn_ids.add(recipe.eqn_id)\nelif isinstance(recipe, LambdaBinding):\nassert any(t is in_tracer for in_tracer in in_tracers), \"Encountered unexpected tracer\"\nassert in_tracers, \"Lambda binding with no args\"\nelif isinstance(recipe, FreeVar):\n- env[var(t)] = recipe.val\n+ env[getvar(t)] = recipe.val\nelif isinstance(recipe, ConstVar):\nv = t_to_var[id(t)] = const_to_var[id(recipe.val)]\nconsts[v] = recipe.val\n@@ -425,11 +420,12 @@ def tracers_to_jaxpr(in_tracers, out_tracers):\nenv_vars, env_vals = unzip2(env.items())\nconst_vars, const_vals = unzip2(consts.items())\n- jaxpr = Jaxpr(const_vars, env_vars, invars, list(map(var, out_tracers)), eqns)\n+ jaxpr = Jaxpr(const_vars, env_vars, invars, list(map(getvar, out_tracers)), eqns)\ncore.skip_checks or core.check_jaxpr(jaxpr)\nreturn jaxpr, const_vals, env_vals\n+\ndef eqn_parents(eqn):\nsubjaxpr_tracers = [it.chain(c, f) for _, c, f in eqn.bound_subjaxprs]\nreturn list(it.chain(eqn.invars, *subjaxpr_tracers))\n" } ]
Python
Apache License 2.0
google/jax
only use one gensym in tracers_to_jaxpr fixes a bug in #1721 revealed by additional internal testing
260,322
22.11.2019 02:51:57
0
dc5a599a9c9cc7eca8a86a234debcc55f84c18a0
Fix bug in jax repeat which caused a value error for repeat arguments containing 0.
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -1958,6 +1958,7 @@ def repeat(a, repeats, axis=None):\nfor i, repeat in enumerate(repeats_tiled):\nif not isinstance(repeat, int):\nrepeat = repeat.item()\n+ if repeat != 0:\nret = concatenate((ret, tile(a_splitted[i], repeat)))\nreturn reshape(ret, new_shape)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -925,7 +925,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nm = lnp.array([1,2,3,4,5,6])\nargs_maker = lambda: [m]\n- for repeats in [2, [1,3,2,1,1,2], [2], lnp.array([1,3,2,1,1,2]), lnp.array([2])]:\n+ for repeats in [2, [1,3,2,1,1,2], [1,3,0,1,1,2], [2], lnp.array([1,3,2,1,1,2]), lnp.array([2])]:\ntest_single(m, args_maker, repeats, None)\nm_rect = m.reshape((2,3))\n" } ]
Python
Apache License 2.0
google/jax
Fix bug in jax repeat which caused a value error for repeat arguments containing 0. (#1740)
260,335
22.11.2019 10:54:03
28,800
b358c27c92f614b6ab24e7c99ea5902a4da92e39
replace x.shape with onp.shape(x) in random.py fixes (thanks
[ { "change_type": "MODIFY", "old_path": "jax/random.py", "new_path": "jax/random.py", "diff": "@@ -324,7 +324,7 @@ def randint(key, shape, minval, maxval, dtype=onp.int64):\n@partial(jit, static_argnums=(1, 4))\ndef _randint(key, shape, minval, maxval, dtype):\n- _check_shape(\"randint\", shape, minval.shape, maxval.shape)\n+ _check_shape(\"randint\", shape, onp.shape(minval), onp.shape(maxval))\nif not np.issubdtype(dtype, onp.integer):\nraise TypeError(\"randint only accepts integer dtypes.\")\n@@ -503,9 +503,9 @@ def truncated_normal(key, lower, upper, shape=None, dtype=onp.float64):\n@partial(jit, static_argnums=(3, 4))\ndef _truncated_normal(key, lower, upper, shape, dtype):\nif shape is None:\n- shape = lax.broadcast_shapes(lower.shape, upper.shape)\n+ shape = lax.broadcast_shapes(onp.shape(lower), onp.shape(upper))\nelse:\n- _check_shape(\"truncated_normal\", shape, lower.shape, upper.shape)\n+ _check_shape(\"truncated_normal\", shape, onp.shape(lower), onp.shape(upper))\nsqrt2 = onp.array(onp.sqrt(2), dtype)\na = lax.erf(lax.convert_element_type(lower, dtype) / sqrt2)\n@@ -541,9 +541,9 @@ def bernoulli(key, p=onp.float32(0.5), shape=None):\n@partial(jit, static_argnums=(2,))\ndef _bernoulli(key, p, shape):\nif shape is None:\n- shape = p.shape\n+ shape = onp.shape(p)\nelse:\n- _check_shape(\"bernoulli\", shape, p.shape)\n+ _check_shape(\"bernoulli\", shape, onp.shape(p))\nreturn uniform(key, shape, lax.dtype(p)) < p\n@@ -573,9 +573,9 @@ def beta(key, a, b, shape=None, dtype=onp.float64):\n@partial(jit, static_argnums=(3, 4))\ndef _beta(key, a, b, shape, dtype):\nif shape is None:\n- shape = lax.broadcast_shapes(a.shape, b.shape)\n+ shape = lax.broadcast_shapes(onp.shape(a), onp.shape(b))\nelse:\n- _check_shape(\"beta\", shape, a.shape, b.shape)\n+ _check_shape(\"beta\", shape, onp.shape(a), onp.shape(b))\na = lax.convert_element_type(a, dtype)\nb = lax.convert_element_type(b, dtype)\n@@ -639,12 +639,12 @@ def _dirichlet(key, alpha, shape, dtype):\nraise ValueError(msg.format(onp.ndim(alpha)))\nif shape is None:\n- shape = alpha.shape[:-1]\n+ shape = onp.shape(alpha)[:-1]\nelse:\n- _check_shape(\"dirichlet\", shape, alpha.shape[:-1])\n+ _check_shape(\"dirichlet\", shape, onp.shape(alpha)[:-1])\nalpha = lax.convert_element_type(alpha, dtype)\n- gamma_samples = gamma(key, alpha, shape + alpha.shape[-1:], dtype)\n+ gamma_samples = gamma(key, alpha, shape + onp.shape(alpha)[-1:], dtype)\nreturn gamma_samples / np.sum(gamma_samples, axis=-1, keepdims=True)\n@@ -833,14 +833,14 @@ def _gamma_grad(sample, a):\nsamples = np.reshape(sample, -1)\nalphas = np.reshape(a, -1)\ngrads = vmap(_gamma_grad_one)(samples, alphas)\n- return grads.reshape(a.shape)\n+ return grads.reshape(onp.shape(a))\n@custom_transforms\ndef _gamma_impl(key, a):\nalphas = np.reshape(a, -1)\nkeys = split(key, onp.size(alphas))\nsamples = vmap(_gamma_one)(keys, alphas)\n- return np.reshape(samples, np.shape(a))\n+ return np.reshape(samples, onp.shape(a))\ndefjvp(_gamma_impl, None,\nlambda tangent, ans, key, a, **kwargs: tangent * _gamma_grad(ans, a))\n@@ -868,9 +868,9 @@ def gamma(key, a, shape=None, dtype=onp.float64):\n@partial(jit, static_argnums=(2, 3))\ndef _gamma(key, a, shape, dtype):\nif shape is None:\n- shape = a.shape\n+ shape = onp.shape(a)\nelse:\n- _check_shape(\"gamma\", shape, a.shape)\n+ _check_shape(\"gamma\", shape, onp.shape(a))\na = lax.convert_element_type(a, dtype)\nif onp.shape(a) != shape:\n@@ -970,7 +970,7 @@ def pareto(key, b, shape=None, dtype=onp.float64):\n@partial(jit, static_argnums=(2, 3))\ndef _pareto(key, b, shape, dtype):\nif shape is None:\n- shape = b.shape\n+ shape = onp.shape(b)\nelse:\n_check_shape(\"pareto\", shape)\n@@ -1002,9 +1002,9 @@ def t(key, df, shape=(), dtype=onp.float64):\n@partial(jit, static_argnums=(2, 3))\ndef _t(key, df, shape, dtype):\nif shape is None:\n- shape = df.shape\n+ shape = onp.shape(df)\nelse:\n- _check_shape(\"t\", shape, df.shape)\n+ _check_shape(\"t\", shape, onp.shape(df))\ndf = lax.convert_element_type(df, dtype)\nkey_n, key_g = split(key)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -408,6 +408,9 @@ class LaxRandomTest(jtu.JaxTestCase):\nassert onp.unique(onp.ravel(keys)).shape == (20,)\ndef testStaticShapeErrors(self):\n+ if config.read(\"jax_disable_jit\"):\n+ raise SkipTest(\"test only relevant when jit enabled\")\n+\n@api.jit\ndef feature_map(n, d, sigma=1.0, seed=123):\nkey = random.PRNGKey(seed)\n" } ]
Python
Apache License 2.0
google/jax
replace x.shape with onp.shape(x) in random.py fixes #1748 (thanks @vitchyr)
260,335
22.11.2019 18:06:10
28,800
8f2a050e1ed0817d368d3c38c92fa4e7b4f8301c
fix cov test tol
[ { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -2079,7 +2079,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nargs_maker = self._GetArgsMaker(rng, [shape], [dtype])\nonp_fun = partial(onp.cov, rowvar=rowvar, ddof=ddof, bias=bias)\nlnp_fun = partial(lnp.cov, rowvar=rowvar, ddof=ddof, bias=bias)\n- tol = {onp.float64: 1e-13, onp.complex128: 1e-13}\n+ tol = {onp.float32: 1e-5, onp.float64: 1e-13, onp.complex128: 1e-13}\ntol = 7e-2 if jtu.device_under_test() == \"tpu\" else tol\ntol = jtu.join_tolerance(tol, jtu.tolerance(dtype))\nself._CheckAgainstNumpy(\n" } ]
Python
Apache License 2.0
google/jax
fix cov test tol Co-authored-by: Skye Wanderman-Milne <skyewm@google.com>
260,411
29.10.2019 08:56:39
-3,600
b12a8019c8711afaef9b4d1a9f437bf944575cee
Update docs/notebooks/JAX_pytrees.ipynb
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/JAX_pytrees.ipynb", "new_path": "docs/notebooks/JAX_pytrees.ipynb", "diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"Pytrees containers can be lists, tuples, dicts, namedtuple. Leaves as numeric and ndarrays:\"\n+ \"Pytrees containers can be lists, tuples, dicts, namedtuple. Numeric and ndarray values are treated as leaves:\"\n]\n},\n{\n" } ]
Python
Apache License 2.0
google/jax
Update docs/notebooks/JAX_pytrees.ipynb Co-Authored-By: Stephan Hoyer <shoyer@google.com>
260,335
25.11.2019 14:03:59
28,800
36c882ba469fc009dba1a29df640c72eec12b36b
raise an error on jit-of-multi-host-pmap
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -352,6 +352,20 @@ def eqn_replicas(eqn):\nelse:\nreturn 1\n+def jaxpr_has_pmap(jaxpr):\n+ return any(eqn_has_pmap(eqn) for eqn in jaxpr.eqns)\n+\n+def eqn_has_pmap(eqn):\n+ if eqn.bound_subjaxprs:\n+ (subjaxpr, _, _), = eqn.bound_subjaxprs\n+ return jaxpr_has_pmap(subjaxpr)\n+ elif eqn.primitive in initial_style_translations:\n+ return any(jaxpr_has_pmap(param if type(param) is core.Jaxpr else param.jaxpr)\n+ for param in eqn.params.values()\n+ if type(param) in (core.Jaxpr, core.TypedJaxpr))\n+ else:\n+ return 'pmap' in eqn.primitive.name\n+\n### xla_call underlying jit\n@@ -384,6 +398,11 @@ def _xla_callable(fun, device, backend, *abstract_args):\nraise ValueError(msg.format(num_replicas, xb.device_count(backend)))\naxis_env = AxisEnv(nreps, [], [])\n+ if xb.host_count() > 1 and (nreps > 1 or jaxpr_has_pmap(jaxpr)):\n+ raise NotImplementedError(\n+ \"jit of multi-host pmap not implemented (and jit-of-pmap can cause \"\n+ \"extra data movement anyway, so maybe you don't want it after all).\")\n+\ntuple_args = len(abstract_args) > 100 # pass long arg lists as tuple for TPU\nc = xb.make_computation_builder(\"jit_{}\".format(fun.__name__))\n@@ -392,12 +411,14 @@ def _xla_callable(fun, device, backend, *abstract_args):\nout_nodes = jaxpr_subcomp(c, jaxpr, backend, axis_env, xla_consts, (), *xla_args)\nbuilt = c.Build(c.Tuple(*out_nodes))\n+ if device is not None and nreps > 1:\n+ raise ValueError(\"can't specify device assignment for jit-of-pmap\")\noptions = xb.get_compile_options(\nnum_replicas=nreps, device_assignment=(device.id,) if device else None)\ncompiled = built.Compile(compile_options=options, backend=xb.get_backend(backend))\nresult_handlers = tuple(map(_pval_to_result_handler, pvals))\n- if axis_env.nreps == 1:\n+ if nreps == 1:\nreturn partial(_execute_compiled, compiled, backend, result_handlers, tuple_args)\nelse:\nreturn partial(_execute_replicated, compiled, backend, result_handlers, tuple_args)\n" } ]
Python
Apache License 2.0
google/jax
raise an error on jit-of-multi-host-pmap (#1761) Co-authored-by: Skye Wanderman-Milne <skyewm@google.com>
260,335
26.11.2019 07:56:48
28,800
2867e4be082237e2b184d7b533dfcbfa31b24f63
fix grad of jit caching bug
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -26,7 +26,8 @@ from ..ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval, zeros_like\nfrom ..abstract_arrays import raise_to_shaped\nfrom ..util import unzip2, unzip3, safe_map, safe_zip, partial, split_list\nfrom ..tree_util import build_tree, register_pytree_node, tree_map\n-from ..linear_util import thunk, transformation, transformation_with_aux, wrap_init\n+from ..linear_util import (thunk, transformation, transformation_with_aux,\n+ wrap_init, hashable_partial)\nfrom ..api_util import flatten_fun, flatten_fun_nokwargs\nfrom ..tree_util import tree_flatten, tree_unflatten\n@@ -451,18 +452,18 @@ def traceable(num_primals, in_tree_def, *primals_and_tangents):\nout_flat, tree_def = tree_flatten((primal_out, tangent_out))\nyield out_flat, tree_def\n+\ndef call_transpose(primitive, params, jaxpr, consts, freevar_vals, args, ct):\nall_args, in_tree_def = tree_flatten((consts, freevar_vals, args, ct))\n- fun = wrap_init(partial(backward_pass, jaxpr))\n+ fun = hashable_partial(wrap_init(backward_pass), jaxpr)\nfun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\nout_flat = primitive.bind(fun, *all_args, **params)\nreturn tree_unflatten(out_tree(), out_flat)\n-\nprimitive_transposes[core.call_p] = partial(call_transpose, call_p)\ndef map_transpose(primitive, params, jaxpr, consts, freevar_vals, args, ct):\nall_args, in_tree_def = tree_flatten((consts, freevar_vals, args, ct))\n- fun = wrap_init(partial(backward_pass, jaxpr))\n+ fun = hashable_partial(wrap_init(backward_pass), jaxpr)\nfun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\nout_flat = primitive.bind(fun, *all_args, **params)\nfreevar_cts, arg_cts = tree_unflatten(out_tree(), out_flat)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -22,6 +22,7 @@ import itertools as it\nimport operator as op\nimport os\n+from absl import logging\nimport numpy as onp\nimport six\nfrom six.moves import xrange\n@@ -381,8 +382,10 @@ def _xla_call_impl(fun, *args, **params):\n@lu.cache\ndef _xla_callable(fun, device, backend, *abstract_args):\n- if FLAGS.jax_log_compiles:\n- print(\"Compiling {} for args {}.\".format(fun.__name__, abstract_args))\n+ log_priority = logging.WARNING if FLAGS.jax_log_compiles else logging.DEBUG\n+ logging.log(log_priority,\n+ \"Compiling {} for args {}.\".format(fun.__name__, abstract_args))\n+\npvals = [pe.PartialVal((aval, core.unit)) for aval in abstract_args]\nwith core.new_master(pe.JaxprTrace, True) as master:\njaxpr, (pvals, consts, env) = pe.trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)\n" }, { "change_type": "MODIFY", "old_path": "jax/linear_util.py", "new_path": "jax/linear_util.py", "diff": "@@ -210,3 +210,8 @@ def cache(call):\ncache[key] = (ans, fun.stores)\nreturn ans\nreturn memoized_fun\n+\n+@transformation\n+def hashable_partial(x, *args):\n+ ans = yield (x,) + args, {}\n+ yield ans\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -22,6 +22,7 @@ import unittest\nimport warnings\nimport weakref\n+from absl import logging\nfrom absl.testing import absltest\nimport numpy as onp\nimport six\n@@ -1286,5 +1287,22 @@ class APITest(jtu.JaxTestCase):\ndef test_scalar_literals(self):\nself.assertLen(api.make_jaxpr(lambda x: x + 2)(42).constvars, 0)\n+ def test_grad_of_jit_compilation_caching(self):\n+ if not hasattr(self, \"assertLogs\"):\n+ raise unittest.SkipTest(\"test requires assertLogs (python 3)\")\n+\n+ lax.add(1, 2) # make sure some initial warnings are already printed\n+\n+ sin = api.jit(np.sin)\n+\n+ with self.assertLogs(level=logging.DEBUG) as l:\n+ ans1 = api.grad(sin)(2.)\n+ ans2 = api.grad(sin)(3.)\n+ self.assertLen(l.output, 2)\n+\n+ self.assertAllClose(ans1, onp.cos(2.), check_dtypes=False)\n+ self.assertAllClose(ans2, onp.cos(3.), check_dtypes=False)\n+\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
fix grad of jit caching bug Co-authored-by: Dougal Maclaurin <dougalm@google.com>
260,335
26.11.2019 17:06:57
28,800
b7579492690b1d94da89b7f1d1b6ddcfadbaacae
fix pulldown bugs
[ { "change_type": "MODIFY", "old_path": "jaxlib/BUILD", "new_path": "jaxlib/BUILD", "diff": "@@ -29,6 +29,7 @@ cc_library(\n\"-fexceptions\",\n\"-fno-strict-aliasing\",\n],\n+ features = [\"-use_header_modules\"],\ndeps = [\n\"@com_google_absl//absl/base\",\n\"@pybind11\",\n@@ -161,6 +162,7 @@ cuda_library(\n\":gpu_kernel_helpers\",\n\":kernel_helpers\",\n\"@local_config_cuda//cuda:cuda_headers\",\n+ \"@pybind11\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1295,9 +1295,14 @@ class APITest(jtu.JaxTestCase):\nsin = api.jit(np.sin)\n+ prev_level = logging.get_verbosity()\n+ try:\n+ logging.set_verbosity('DEBUG')\nwith self.assertLogs(level=logging.DEBUG) as l:\nans1 = api.grad(sin)(2.)\nans2 = api.grad(sin)(3.)\n+ finally:\n+ logging.set_verbosity(prev_level)\nself.assertLen(l.output, 2)\nself.assertAllClose(ans1, onp.cos(2.), check_dtypes=False)\n" } ]
Python
Apache License 2.0
google/jax
fix pulldown bugs
260,335
27.11.2019 15:25:49
28,800
ac251046fcbe0a940ab79fe49d58227e61f7c675
make remat_call partial-eval into one remat_call
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -187,18 +187,21 @@ def backward_pass(jaxpr, consts, freevar_vals, args, cotangents_in):\nwrite_primal(eqn.outvars[0], ans)\nelse:\n(subjaxpr, const_vars, bound_vars), = eqn.bound_subjaxprs\n+ assert not any(is_linear(v) for v in const_vars)\nif any(is_linear(v) for v in it.chain(eqn.invars, bound_vars)):\nlinear_eqns.append(eqn)\n- else:\n- assert not any(is_linear(v) for v in const_vars)\n- sub_consts = map(read_primal, const_vars)\n- sub_freevar_vals = map(read_primal, bound_vars)\n- in_vals = map(read_primal, eqn.invars)\n- all_args, in_tree_def = tree_flatten((sub_consts, sub_freevar_vals, in_vals))\n- fun = hashable_partial(wrap_init(_eval_primals), subjaxpr)\n- fun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\n- out_flat = eqn.primitive.bind(fun, *all_args, **eqn.params)\n- ans = tree_unflatten(out_tree(), out_flat)\n+ elif eqn.primitive is not pe.remat_call_p:\n+ ans = _eval_subjaxpr_primals(\n+ eqn.primitive, subjaxpr, map(read_primal, const_vars),\n+ map(read_primal, bound_vars), map(read_primal, eqn.invars), eqn.params)\n+ map(write_primal, eqn.outvars, ans)\n+\n+ # we special-case remat_call here because it can be mixed linear /\n+ # nonlinear, so we always evaluate it even if it has a linear part\n+ if eqn.primitive is pe.remat_call_p:\n+ ans = _eval_subjaxpr_primals(\n+ eqn.primitive, subjaxpr, map(read_primal, const_vars),\n+ map(read_primal, bound_vars), map(read_primal, eqn.invars), eqn.params)\nmap(write_primal, eqn.outvars, ans)\nct_env = {}\n@@ -225,6 +228,13 @@ def backward_pass(jaxpr, consts, freevar_vals, args, cotangents_in):\ncotangents_out = map(read_cotangent, jaxpr.invars)\nreturn freevar_cts, cotangents_out\n+def _eval_subjaxpr_primals(prim, jaxpr, consts, freevar_vals, in_vals, params):\n+ all_args, in_tree_def = tree_flatten((consts, freevar_vals, in_vals))\n+ fun = hashable_partial(wrap_init(_eval_primals), jaxpr)\n+ fun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\n+ out_flat = prim.bind(fun, *all_args, **params)\n+ return tree_unflatten(out_tree(), out_flat)\n+\ndef _eval_primals(jaxpr, consts, freevar_vals, args):\nprimal_env = {}\n@@ -259,14 +269,12 @@ def _eval_primals(jaxpr, consts, freevar_vals, args):\nwrite_primal(eqn.outvars[0], ans)\nelse:\n(subjaxpr, const_vars, bound_vars), = eqn.bound_subjaxprs\n- sub_consts = map(read_primal, const_vars)\n- sub_freevar_vals = map(read_primal, bound_vars)\n- in_vals = map(read_primal, eqn.invars)\n- all_args, in_tree_def = tree_flatten((sub_consts, sub_freevar_vals, in_vals))\n- fun = hashable_partial(wrap_init(_eval_primals), subjaxpr)\n- fun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\n- out_flat = eqn.primitive.bind(fun, *all_args, **eqn.params)\n- ans = tree_unflatten(out_tree(), out_flat)\n+ assert not any(is_linear(v) for v in const_vars)\n+ if (eqn.primitive is pe.remat_call_p or\n+ not any(is_linear(v) for v in it.chain(eqn.invars, bound_vars))):\n+ ans = _eval_subjaxpr_primals(\n+ eqn.primitive, subjaxpr, map(read_primal, const_vars),\n+ map(read_primal, bound_vars), map(read_primal, eqn.invars), eqn.params)\nmap(write_primal, eqn.outvars, ans)\nreturn map(read_primal, jaxpr.outvars)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -507,6 +507,9 @@ def _remat_partial_eval(trace, f, tracers, params):\njaxpr_1, jaxpr_2, out_unknowns = partial_eval_jaxpr(typed_jaxpr, in_unknowns, False)\nnum_res = len(jaxpr_1.out_avals) - len(jaxpr_2.out_avals)\n+ # First, we prune the jaxpr to be staged out not to have too many outputs.\n+ typed_jaxpr = _dce_jaxpr(typed_jaxpr, out_unknowns)\n+\n# Next, we need values for the outputs that should be known. Since consts\n# weren't passed through Python for evaluation, we need to evaluate jaxpr_1,\n# minus the residual outputs that we don't need. When `concrete=True`, as an\n@@ -521,51 +524,23 @@ def _remat_partial_eval(trace, f, tracers, params):\nout_pval_consts2 = core.jaxpr_as_fun(jaxpr_1_primals)(*in_consts)[:-num_res or None]\nout_pvals = map(_reconstruct_pval, out_pvals1, out_pval_consts2, out_unknowns)\n- # Now that we have out_pvals, the rest is just like JaxprTrace.process_call\n- # except we stage out two calls: one based on jaxpr_1 for computing the\n- # residuals (which in the case of reverse-mode ad involves no linear\n- # variables) and the other based on jaxpr_2 for evaluating everything given\n- # the residuals (which in reverse-mode ad is linear).\n+ # Now that we have out_pvals, the rest is just like JaxprTrace.process_call.\ninstantiated_tracers = env + instantiated_tracers\n- num_nonres = len(jaxpr_2.out_avals)\n- jaxpr_1_res = _dce_jaxpr(jaxpr_1, [False] * num_nonres + [True] * num_res,\n- prune_outputs=True)\n-\nconst_tracers = map(trace.new_instantiated_const, consts)\n- bound_subjaxpr_1 = (jaxpr_1_res.jaxpr, const_tracers, ())\n- res_avals = jaxpr_1.out_avals[num_nonres:]\n- res_tracers = [JaxprTracer(trace, PartialVal((aval, unit)), None)\n- for aval in res_avals]\n- tracers_1 = [t if not uk else trace.new_instantiated_literal(unit)\n- for t, uk in zip(instantiated_tracers, in_unknowns)]\n- eqn_1 = new_eqn_recipe(tracers_1, res_tracers, remat_call_p,\n- (bound_subjaxpr_1,), params)\n- for t in res_tracers: t.recipe = eqn_1\n-\n- bound_subjaxpr_2 = (jaxpr_2.jaxpr, (), ())\n+ bound_subjaxpr = (typed_jaxpr.jaxpr, const_tracers, ())\nout_tracers = [JaxprTracer(trace, out_pval, None) for out_pval in out_pvals]\n- tracers_2 = [t if uk else trace.new_instantiated_literal(unit)\n- for t, uk in zip(instantiated_tracers, in_unknowns)]\n- eqn_2 = new_eqn_recipe(tracers_2 + res_tracers, out_tracers, remat_call_p,\n- (bound_subjaxpr_2,), params)\n- for t in out_tracers: t.recipe = eqn_2\n+ eqn = new_eqn_recipe(instantiated_tracers, out_tracers, remat_call_p,\n+ (bound_subjaxpr,), params)\n+ for t in out_tracers: t.recipe = eqn\nreturn out_tracers\ncall_partial_eval_rules[remat_call_p] = _remat_partial_eval\n-# NOTE to future self: the problem with the above strategy is that the jaxpr\n-# produced wouldn't be round-trippable, in the sense that by forming two remat\n-# calls we ensured the first one would be partial-eval'd away when we tried to\n-# round-trip e.g. for partial eval of scan.\n-def _dce_jaxpr(typed_jaxpr, outputs, prune_outputs=False):\n+def _dce_jaxpr(typed_jaxpr, outputs):\n# This dead-code elimination is pretty rudimentary, and in particular doesn't\n# nontrivially DCE through scan, call, or other higher-order primitives.\n# TODO(mattjj): better DCE\njaxpr = typed_jaxpr.jaxpr\noutvars, out_avals = jaxpr.outvars, typed_jaxpr.out_avals\n- if prune_outputs:\n- out_pairs = [(var, aval) for var, aval, output\n- in zip(outvars, out_avals, outputs) if output]\n- else:\nout_pairs = [(var, aval) if output else (core.unitvar, core.abstract_unit)\nfor var, aval, output in zip(outvars, out_avals, outputs)]\nnew_outvars, new_out_avals = unzip2(out_pairs)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1470,8 +1470,7 @@ class APITest(jtu.JaxTestCase):\njaxpr = api.make_jaxpr(api.linearize(f_yesremat, 4.)[1])(1.)\nscan_eqn, = jaxpr.eqns\n- import ipdb; ipdb.set_trace()\n- self.assertIn(' sin ', str(scan_eqn.params['jaxpr']))\n+ self.assertIn(' cos ', str(scan_eqn.params['jaxpr']))\njaxpr = api.make_jaxpr(api.vjp(f_yesremat, 4.)[1])(1.)\nscan_eqn, = jaxpr.eqns\n" } ]
Python
Apache License 2.0
google/jax
make remat_call partial-eval into one remat_call
260,335
27.11.2019 19:15:53
28,800
115d365a92ef038426b5d2777943948463c2725b
raise error if we do concrete aval FLOPs w/o remat
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -18,6 +18,8 @@ from __future__ import print_function\nimport itertools as it\nfrom collections import namedtuple, Counter, defaultdict\n+import contextlib\n+import threading\nfrom weakref import ref\nimport numpy as onp\n@@ -489,6 +491,11 @@ def _remat_partial_eval(trace, f, tracers, params):\n# Using the instantiated tracers, run call_bind like JaxprTrace.process_call.\nin_pvs, in_consts = unzip2(t.pval for t in instantiated_tracers)\nfun, aux = partial_eval(f, trace, in_pvs)\n+ if concrete:\n+ # TODO(mattjj): remove `remat_context` when confident no accidental FLOPs\n+ with remat_context():\n+ out_flat = remat_call_p.bind(fun, *in_consts, **params)\n+ else:\nout_flat = remat_call_p.bind(fun, *in_consts, **params)\nout_pvs, jaxpr, env = aux()\nenv = map(trace.full_raise, env)\n@@ -568,6 +575,23 @@ def _reconstruct_pval(pval1, const2, unknown):\nelse:\nreturn PartialVal((None, const2))\n+# TODO(mattjj): for https://github.com/google/jax/pull/1749 we allowed\n+# standard_abstract_eval to perform concrete evaluation (i.e. FLOPs), but we\n+# don't think it should happen except for in a remat context\n+@contextlib.contextmanager\n+def remat_context():\n+ try:\n+ prev_state = _thread_local_state.remat\n+ _thread_local_state.remat = True\n+ yield\n+ finally:\n+ _thread_local_state.remat = prev_state\n+\n+class _ThreadLocalState(threading.local):\n+ def __init__(self):\n+ self.remat = False\n+_thread_local_state = _ThreadLocalState()\n+\ndef move_binders_to_front(typed_jaxpr, to_move):\nassert not typed_jaxpr.jaxpr.constvars and not typed_jaxpr.jaxpr.freevars\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1487,6 +1487,10 @@ 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+ msg = (\"If you see this error, please let us know by opening an issue at\\n\"\n+ \"https://github.com/google/jax/issues \\n\"\n+ \"since we thought this was unreachable!\")\n+ assert pe._thread_local_state.remat, msg\nreturn ConcreteArray(prim.impl(*[x.val for x in args], **kwargs))\nelif least_specialized is ShapedArray:\nreturn ShapedArray(shape_rule(*args, **kwargs), dtype_rule(*args, **kwargs))\n" } ]
Python
Apache License 2.0
google/jax
raise error if we do concrete aval FLOPs w/o remat
260,314
01.12.2019 09:44:45
18,000
7ec2ac58ca3fb2142dc1bf2b4eb5335f119273cc
not use custom transform for gamma sampler
[ { "change_type": "MODIFY", "old_path": "jax/random.py", "new_path": "jax/random.py", "diff": "@@ -41,7 +41,9 @@ from jax import core\nfrom jax import abstract_arrays\nfrom jax.scipy.special import logit\nfrom jax.scipy.linalg import cholesky\n+from jax.interpreters import ad\nfrom jax.interpreters import batching\n+from jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n@@ -878,18 +880,46 @@ def _gamma_grad_one(z, alpha):\ndef _gamma_grad(sample, a):\nsamples = np.reshape(sample, -1)\nalphas = np.reshape(a, -1)\n- grads = vmap(_gamma_grad_one)(samples, alphas)\n+ if np.size(alphas) == 1:\n+ grads = _gamma_grad_one(samples[0], alphas[0])\n+ else:\n+ # TODO: benchmark execute time against grads = vmap(_gamma_grad_one)(samples, alphas)\n+ grads = lax.map(lambda args: _gamma_grad_one(*args), (samples, alphas))\nreturn grads.reshape(onp.shape(a))\n-@custom_transforms\ndef _gamma_impl(key, a):\n+ if key.ndim == 2: # batch of keys and alphas\n+ size = np.size(a[0])\n+ if size > 1:\n+ key = lax.map(lambda k: split(k, size), key)\n+ else:\n+ size = np.size(a)\n+ if size > 1:\n+ key = split(key, size)\nalphas = np.reshape(a, -1)\n- keys = split(key, onp.size(alphas))\n- samples = vmap(_gamma_one)(keys, alphas)\n- return np.reshape(samples, onp.shape(a))\n-\n-defjvp(_gamma_impl, None,\n- lambda tangent, ans, key, a, **kwargs: tangent * _gamma_grad(ans, a))\n+ keys = np.reshape(key, (-1, 2))\n+ if np.size(alphas) == 1:\n+ samples = _gamma_one(keys[0], alphas[0])\n+ else:\n+ # XXX in GPU, using lax.map is slower than using vmap if alphas.size > 50000\n+ # but that usage case is rare and can be resolved by vectorizing gamma sampler\n+ samples = lax.map(lambda args: _gamma_one(*args), (keys, alphas))\n+ return np.reshape(samples, np.shape(a))\n+\n+def _gamma_batching_rule(batched_args, batch_dims):\n+ k, a = batched_args\n+ bk, ba = batch_dims\n+ size = next(t.shape[i] for t, i in zip(batched_args, batch_dims) if i is not None)\n+ k = batching.bdim_at_front(k, bk, size)\n+ a = batching.bdim_at_front(a, ba, size)\n+ return random_gamma_p.bind(k, a), 0\n+\n+random_gamma_p = core.Primitive('random_gamma')\n+random_gamma_p.def_impl(_gamma_impl) # partial(xla.apply_primitive, random_gamma_p))\n+random_gamma_p.def_abstract_eval(lambda key, a: abstract_arrays.raise_to_shaped(a))\n+ad.defjvp2(random_gamma_p, None, lambda tangent, ans, key, a, **kwargs: tangent * _gamma_grad(ans, a))\n+xla.translations[random_gamma_p] = xla.lower_fun(_gamma_impl, instantiate=True)\n+batching.primitive_batchers[random_gamma_p] = _gamma_batching_rule\ndef gamma(key, a, shape=None, dtype=onp.float64):\n\"\"\"Sample Gamma random values with given shape and float dtype.\n@@ -911,7 +941,7 @@ def gamma(key, a, shape=None, dtype=onp.float64):\ndtype = dtypes.canonicalize_dtype(dtype)\nreturn _gamma(key, a, shape, dtype)\n-@partial(jit, static_argnums=(2, 3))\n+# @partial(jit, static_argnums=(2, 3))\ndef _gamma(key, a, shape, dtype):\nif shape is None:\nshape = onp.shape(a)\n@@ -921,7 +951,7 @@ def _gamma(key, a, shape, dtype):\na = lax.convert_element_type(a, dtype)\nif onp.shape(a) != shape:\na = np.broadcast_to(a, shape)\n- return _gamma_impl(key, a)\n+ return random_gamma_p.bind(key, a)\ndef gumbel(key, shape=(), dtype=onp.float64):\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -27,10 +27,12 @@ import scipy.special\nimport scipy.stats\nfrom jax import api\n+from jax import grad\nfrom jax import lax\nfrom jax import numpy as np\nfrom jax import random\nfrom jax import test_util as jtu\n+from jax import vmap\nfrom jax.interpreters import xla\nfrom jax.config import config\n@@ -443,6 +445,12 @@ class LaxRandomTest(jtu.JaxTestCase):\nelse:\nself.assertEqual(onp.result_type(w), onp.float32)\n+ def testIssue1789(self):\n+ def f(x):\n+ return random.gamma(random.PRNGKey(0), x)\n+\n+ grad(lambda x: np.sum(vmap(f)(x)))(np.ones(2))\n+\ndef testNoOpByOpUnderHash(self):\ndef fail(*args, **kwargs): assert False\napply_primitive, xla.apply_primitive = xla.apply_primitive, fail\n" } ]
Python
Apache License 2.0
google/jax
not use custom transform for gamma sampler
260,551
02.12.2019 15:02:27
28,800
32b5d6e9db3758eba5c75b0103bc4b509dfcbef2
Memoize TPU driver backend to be consistent with other XLA clients.
[ { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -120,19 +120,27 @@ def _get_local_backend(platform=None):\nreturn backend\n+register_backend('xla', _get_local_backend)\n+\n+# memoize the TPU driver to be consistent with xla_client behavior\n+_tpu_backend = None\n+\ndef _get_tpu_driver_backend(platform):\ndel platform\n+ global _tpu_backend\n+ if _tpu_backend is None:\nbackend_target = FLAGS.jax_backend_target\nif backend_target is None:\nraise ValueError('When using TPU Driver as the backend, you must specify '\n'--jax_backend_target=<hostname>:8470.')\n- return tpu_client.TpuBackend.create(worker=backend_target)\n+ _tpu_backend = tpu_client.TpuBackend.create(worker=backend_target)\n+ return _tpu_backend\n-register_backend('xla', _get_local_backend)\nif tpu_client:\nregister_backend('tpu_driver', _get_tpu_driver_backend)\n+\n_backend_lock = threading.Lock()\n@util.memoize\n" } ]
Python
Apache License 2.0
google/jax
Memoize TPU driver backend to be consistent with other XLA clients. (#1798)
260,647
02.12.2019 16:07:23
28,800
51686f43d390e209923b476d04d352bb2a340f01
Make get_compile_options API accept 2D device assignment.
[ { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -85,7 +85,9 @@ def get_compile_options(num_replicas=None, device_assignment=None):\nmsg = \"device_assignment does not match num_replicas: {} vs {}.\"\nraise ValueError(msg.format(device_assignment, num_replicas))\ncompile_options = compile_options or xla_client.CompileOptions()\n- device_assignment = onp.array(device_assignment)[:, None]\n+ device_assignment = onp.array(device_assignment)\n+ if device_assignment.ndim == 1:\n+ device_assignment = device_assignment[:, None]\ndevice_assignment = xla_client.DeviceAssignment.create(device_assignment)\nassert num_replicas is None or device_assignment.replica_count() == num_replicas\ncompile_options.device_assignment = device_assignment\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/xla_bridge_test.py", "diff": "+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+from absl.testing import absltest\n+from jax.lib import xla_bridge as xb\n+\n+\n+class XlaBridgeTest(absltest.TestCase):\n+\n+ def test_set_device_assignment_no_partition(self):\n+ compile_options = xb.get_compile_options(\n+ num_replicas=4, device_assignment=[0, 1, 2, 3])\n+ expected_device_assignment = (\"Computations: 1 Replicas: 4\\nComputation 0: \"\n+ \"0 1 2 3 \\n\")\n+ self.assertEqual(compile_options.device_assignment.__repr__(),\n+ expected_device_assignment)\n+\n+ def test_set_device_assignment_with_partition(self):\n+ compile_options = xb.get_compile_options(\n+ num_replicas=2, device_assignment=[[0, 1], [2, 3]])\n+ expected_device_assignment = (\"Computations: 2 Replicas: 2\\nComputation 0: \"\n+ \"0 2 \\nComputation 1: 1 3 \\n\")\n+ self.assertEqual(compile_options.device_assignment.__repr__(),\n+ expected_device_assignment)\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main()\n" } ]
Python
Apache License 2.0
google/jax
Make get_compile_options API accept 2D device assignment.
260,335
02.12.2019 17:44:58
28,800
09f94a1e3d6a4f43d82f43e85ed1dc74f5290b93
add optional `length` argument to scan
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax_control_flow.py", "new_path": "jax/lax/lax_control_flow.py", "diff": "@@ -438,7 +438,7 @@ xla.initial_style_translations[cond_p] = _cond_translation_rule\n### scan\n-def scan(f, init, xs):\n+def scan(f, init, xs, length=None):\n\"\"\"Scan a function over leading array axes while carrying along state.\nThe type signature in brief is\n@@ -493,6 +493,9 @@ def scan(f, init, xs):\nxs: the value of type ``[a]`` over which to scan along the leading axis,\nwhere ``[a]`` can be an array or any pytree (nested Python\ntuple/list/dict) thereof with consistent leading axis sizes.\n+ length: optional integer specifying the number of loop iterations, which\n+ must agree with the sizes of leading axes of the arrays in ``xs`` (but can\n+ be used to perform scans where no input ``xs`` are needed).\nReturns:\nA pair of type ``(c, [b])`` where the first element represents the final\n@@ -502,14 +505,30 @@ def scan(f, init, xs):\ninit_flat, init_tree = tree_flatten(init)\nxs_flat, _ = tree_flatten(xs)\nin_flat, in_tree = tree_flatten((init, xs))\n+\ntry:\n- length, = {x.shape[0] for x in xs_flat}\n+ lengths = [x.shape[0] for x in xs_flat]\nexcept AttributeError:\nmsg = \"scan got value with no leading axis to scan over: {}.\"\n- raise ValueError(msg.format([x for x in xs_flat if not hasattr(x, 'shape')]))\n- except ValueError:\n+ raise ValueError(msg.format(', '.join(str(x) for x in xs_flat\n+ if not hasattr(x, 'shape'))))\n+\n+ if length is not None:\n+ length = int(length)\n+ if not all(length == l for l in lengths):\n+ msg = (\"scan got `length` argument of {} which disagrees with \"\n+ \"leading axis sizes {}.\")\n+ raise ValueError(msg.format(length, [x.shape[0] for x in xs_flat]))\n+ else:\n+ unique_lengths = set(lengths)\n+ if len(unique_lengths) > 1:\nmsg = \"scan got values with different leading axis sizes: {}.\"\n- raise ValueError(msg.format([x.shape[0] for x in xs_flat]))\n+ raise ValueError(msg.format(', '.join(str(x.shape[0]) for x in xs_flat)))\n+ elif len(unique_lengths) == 0:\n+ msg = \"scan got no values to scan over and `length` not provided.\"\n+ raise ValueError(msg)\n+ else:\n+ length, = unique_lengths\ncarry_avals = tuple(_map(_abstractify, init_flat))\nx_shapes = [masking.padded_shape_as_value(x.shape[1:]) for x in xs_flat]\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -1446,6 +1446,14 @@ class LaxControlFlowTest(jtu.JaxTestCase):\ns = str(api.xla_computation(api.grad(loss))(A).GetHloText())\nassert s.count(\"dynamic-update-slice(\") < 2\n+ def testScanLengthArg(self):\n+ def arange(n):\n+ return lax.scan(lambda c, _: (c + 1, c), 0, None, length=n)[1]\n+\n+ ans = arange(10)\n+ expected = onp.arange(10)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
add optional `length` argument to scan