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,389 | 23.08.2019 11:02:19 | 25,200 | 7830cedea64b1f8b1db5c2dd2a07668361cac75d | batching rule for cond | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -164,7 +164,7 @@ def while_loop(cond_fun, body_fun, init_val):\nraise TypeError(msg.format(cond_tree))\nif cond_jaxpr.out_avals != [ShapedArray((), onp.bool_)]:\nmsg = \"cond_fun must return a boolean scalar, but got output type(s) {}.\"\n- raise TypeError(msg.format(coud_jaxpr.out_avals))\n+ raise TypeError(msg.format(cond_jaxpr.out_avals))\nif not treedef_children(in_tree) == [body_tree]:\nmsg = \"body_fun output pytree structure must match init_val, got {} and {}.\"\nraise TypeError(msg.format(body_tree, treedef_children(in_tree)[0]))\n@@ -301,18 +301,6 @@ def cond(pred, true_operand, true_fun, false_operand, false_fun):\ntrue_nconsts=len(true_consts), false_nconsts=len(false_consts))\nreturn tree_unflatten(out_tree, out)\n-def _cond_impl(pred, *args, **kwargs):\n- true_jaxpr, false_jaxpr, true_nconsts, false_nconsts = split_dict(\n- kwargs, [\"true_jaxpr\", \"false_jaxpr\", \"true_nconsts\", \"false_nconsts\"])\n- true_nops = len(true_jaxpr.in_avals) - true_nconsts\n- true_consts, true_ops, false_consts, false_ops = split_list(\n- args, [true_nconsts, true_nops, false_nconsts])\n-\n- if pred:\n- return core.jaxpr_as_fun(true_jaxpr)(*(true_consts + true_ops))\n- else:\n- return core.jaxpr_as_fun(false_jaxpr)(*(false_consts + false_ops))\n-\ndef _cond_abstract_eval(*args, **kwargs):\nreturn kwargs[\"true_jaxpr\"].out_avals\n@@ -339,10 +327,47 @@ def _cond_translation_rule(c, axis_env, pred, *args, **kwargs):\nreturn c.Conditional(pred, true_op, true_c, false_op, false_c)\n+def _cond_batching_rule(args, dims, true_jaxpr, false_jaxpr, true_nconsts,\n+ false_nconsts):\n+ # TODO: maybe avoid moving arg axes to front if we're promoting to select?\n+ args = [batching.moveaxis(x, d, 0) if d is not batching.not_mapped and d != 0\n+ else x for x, d in zip(args, dims)]\n+ true_nops = len(true_jaxpr.in_avals) - true_nconsts\n+ (pred,), true_consts, true_ops, false_consts, false_ops = split_list(\n+ args, [1, true_nconsts, true_nops, false_nconsts])\n+ size, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}\n+ orig_bat = [d is not batching.not_mapped for d in dims]\n+ (pred_bat,), t_bat, tconst_bat, f_bat, fconst_bat = split_list(\n+ orig_bat, [1, true_nconsts, len(true_ops), false_nconsts])\n+\n+ _, true_out_bat = batching.batch_jaxpr(true_jaxpr, size, tconst_bat + t_bat, False)\n+ _, false_out_bat = batching.batch_jaxpr(false_jaxpr, size, fconst_bat + f_bat, False)\n+ out_bat = [a or b for a, b in zip(true_out_bat, false_out_bat)]\n+\n+ true_jaxpr_batched, _ = batching.batch_jaxpr(true_jaxpr, size, tconst_bat + t_bat, out_bat)\n+ false_jaxpr_batched, _ = batching.batch_jaxpr(false_jaxpr, size, fconst_bat + f_bat, out_bat)\n+\n+ if pred_bat:\n+ true_out = core.jaxpr_as_fun(true_jaxpr_batched)(*(true_consts + true_ops))\n+ false_out = core.jaxpr_as_fun(false_jaxpr_batched)(*(false_consts + false_ops))\n+ true_out = [batching.broadcast(x, size, 0) if not b else x\n+ for x, b in zip(true_out, out_bat)]\n+ false_out = [batching.broadcast(x, size, 0) if not b else x\n+ for x, b in zip(false_out, out_bat)]\n+ return [lax.select(pred, t, f)\n+ for t, f in zip(true_out, false_out)], [0] * len(true_out)\n+ else:\n+ out_dims = [0 if b else batching.not_mapped for b in out_bat]\n+ return cond_p.bind(\n+ *itertools.chain([pred], true_consts, true_ops, false_consts, false_ops),\n+ true_jaxpr=true_jaxpr_batched, false_jaxpr=false_jaxpr_batched,\n+ true_nconsts=len(true_consts), false_nconsts=len(false_consts)), out_dims\n+\ncond_p = lax.Primitive('cond')\ncond_p.multiple_results = True\n-cond_p.def_impl(_cond_impl)\n+cond_p.def_impl(partial(xla.apply_primitive, cond_p))\ncond_p.def_abstract_eval(_cond_abstract_eval)\n+batching.primitive_batchers[cond_p] = _cond_batching_rule\nxla.initial_style_translations[cond_p] = _cond_translation_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -475,6 +475,58 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertEqual(fun(4), cfun(4))\nself.assertEqual(cfun(4), (4, 2., 4.))\n+ def testCondBatched(self):\n+ def fun(x, y, z):\n+ pred = lax.lt(x, 3)\n+ true_fun = lambda y: y\n+ false_fun = lambda z: lax.neg(z)\n+ return lax.cond(pred, y, true_fun, z, false_fun)\n+\n+ # these cases stay as cond\n+ x = onp.array(2)\n+ y = onp.array([1, 2])\n+ z = onp.array([3, 4])\n+ ans = api.vmap(fun, (None, 0, 0))(x, y, z)\n+ jaxpr = api.make_jaxpr(api.vmap(fun, (None, 0, 0)))(x, y, z)\n+ expected = onp.array([1, 2])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+ assert \"select\" not in str(jaxpr)\n+\n+ x = onp.array(4)\n+ ans = api.vmap(fun, (None, 0, 0))(x, y, z)\n+ jaxpr = api.make_jaxpr(api.vmap(fun, (None, 0, 0)))(x, y, z)\n+ expected = onp.array([-3, -4])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+ assert \"select\" not in str(jaxpr)\n+\n+ fun = api.jit(fun)\n+ ans = api.vmap(fun, (None, 0, 0))(x, y, z)\n+ expected = onp.array([-3, -4])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ z = onp.array(5)\n+ ans = api.vmap(fun, (None, 0, None))(x, y, z)\n+ jaxpr = api.make_jaxpr(api.vmap(fun, (None, 0, None)))(x, y, z)\n+ expected = onp.array([-5, -5])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+ assert \"select\" not in str(jaxpr)\n+\n+\n+ # these cases become select\n+ x = onp.array([2, 4])\n+ ans = api.vmap(fun, (0, 0, None))(x, y, z)\n+ jaxpr = api.make_jaxpr(api.vmap(fun, (0, 0, None)))(x, y, z)\n+ expected = onp.array([1, -5])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+ assert \"select\" in str(jaxpr)\n+\n+ z = onp.array([3, 4])\n+ ans = api.vmap(fun)(x, y, z)\n+ jaxpr = api.make_jaxpr(api.vmap(fun))(x, y, z)\n+ expected = onp.array([1, -4])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+ assert \"select\" in str(jaxpr)\n+\ndef testIssue514(self):\n# just check this doesn't crash\nlax.cond(True,\n"
}
] | Python | Apache License 2.0 | google/jax | batching rule for cond
Co-authored-by: Matthew Johnson <mattjj@google.com> |
260,335 | 23.08.2019 15:47:42 | 25,200 | e66582e877df99b270d47fd22f5e1f048c242d9f | restore the behavior that Nones are pytrees | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/pytree.cc",
"new_path": "jaxlib/pytree.cc",
"diff": "@@ -159,6 +159,7 @@ class PyTreeDef {\nprivate:\nenum class Kind {\nkLeaf, // An opaque leaf node\n+ kNone, // None.\nkTuple, // A tuple\nkNamedTuple, // A collections.namedtuple\nkList, // A list\n@@ -247,7 +248,9 @@ void PyTreeDef::FlattenHelper(py::handle handle, py::list* leaves,\nNode node;\nint start_num_nodes = tree->traversal_.size();\nint start_num_leaves = leaves->size();\n- if (PyTuple_CheckExact(handle.ptr())) {\n+ if (py::isinstance<py::none>(handle)) {\n+ node.kind = Kind::kNone;\n+ } else if (PyTuple_CheckExact(handle.ptr())) {\npy::tuple tuple = py::reinterpret_borrow<py::tuple>(handle);\nnode.kind = Kind::kTuple;\nnode.arity = tuple.size();\n@@ -334,6 +337,7 @@ py::object PyTreeDef::Unflatten(py::iterable leaves) const {\n++leaf_count;\nbreak;\n+ case Kind::kNone:\ncase Kind::kTuple:\ncase Kind::kNamedTuple:\ncase Kind::kList:\n@@ -368,6 +372,9 @@ py::object PyTreeDef::Unflatten(py::iterable leaves) const {\ncase Kind::kLeaf:\nthrow std::logic_error(\"MakeNode not implemented for leaves.\");\n+ case Kind::kNone:\n+ return py::none();\n+\ncase Kind::kTuple:\ncase Kind::kNamedTuple: {\npy::tuple tuple(node.arity);\n@@ -434,6 +441,9 @@ py::list PyTreeDef::FlattenUpTo(py::handle xs) const {\n--leaf;\nbreak;\n+ case Kind::kNone:\n+ break;\n+\ncase Kind::kTuple: {\nif (!PyTuple_CheckExact(object.ptr())) {\nthrow std::invalid_argument(\n@@ -570,6 +580,7 @@ py::object PyTreeDef::Walk(const py::function& f_node, py::handle f_leaf,\nbreak;\n}\n+ case Kind::kNone:\ncase Kind::kTuple:\ncase Kind::kNamedTuple:\ncase Kind::kList:\n@@ -694,6 +705,9 @@ std::string PyTreeDef::ToString() const {\ncase Kind::kLeaf:\nagenda.push_back(\"*\");\ncontinue;\n+ case Kind::kNone:\n+ kind = \"None\";\n+ break;\ncase Kind::kNamedTuple:\nkind = \"namedtuple\";\nbreak;\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/tree_util_tests.py",
"new_path": "tests/tree_util_tests.py",
"diff": "@@ -57,10 +57,10 @@ PYTREES = [\n((),),\n(([()]),),\n((1, 2),),\n- (((1, \"foo\"), [\"bar\", (3, (), 7)]),),\n+ (((1, \"foo\"), [\"bar\", (3, None, 7)]),),\n([3],),\n- ([3, ATuple(foo=(3, ATuple(foo=3, bar=())), bar={\"baz\": 34})],),\n- ([AnObject(3, (), [4, \"foo\"])],),\n+ ([3, ATuple(foo=(3, ATuple(foo=3, bar=None)), bar={\"baz\": 34})],),\n+ ([AnObject(3, None, [4, \"foo\"])],),\n({\"a\": 1, \"b\": 2},),\n]\n@@ -112,19 +112,19 @@ class TreeTest(jtu.JaxTestCase):\nself.assertEqual([c0, c1], tree.children())\ndef testFlattenUpTo(self):\n- _, tree = tree_util.tree_flatten([(1, 2), (), ATuple(foo=3, bar=7)])\n+ _, tree = tree_util.tree_flatten([(1, 2), None, ATuple(foo=3, bar=7)])\nif not hasattr(tree, \"flatten_up_to\"):\nself.skipTest(\"Test requires Jaxlib >= 0.1.23\")\nout = tree.flatten_up_to([({\n\"foo\": 7\n- }, (3, 4)), (), ATuple(foo=(11, 9), bar=())])\n- self.assertEqual(out, [{\"foo\": 7}, (3, 4), (11, 9), ()])\n+ }, (3, 4)), None, ATuple(foo=(11, 9), bar=None)])\n+ self.assertEqual(out, [{\"foo\": 7}, (3, 4), (11, 9), None])\ndef testTreeMultimap(self):\nx = ((1, 2), (3, 4, 5))\n- y = (([3], ()), ({\"foo\": \"bar\"}, 7, [5, 6]))\n+ y = (([3], None), ({\"foo\": \"bar\"}, 7, [5, 6]))\nout = tree_util.tree_multimap(lambda *xs: tuple(xs), x, y)\n- self.assertEqual(out, (((1, [3]), (2, ())),\n+ self.assertEqual(out, (((1, [3]), (2, None)),\n((3, {\"foo\": \"bar\"}), (4, 7), (5, [5, 6]))))\n"
}
] | Python | Apache License 2.0 | google/jax | restore the behavior that Nones are pytrees |
260,403 | 23.08.2019 15:51:59 | 25,200 | dbb68bd13ae499c0951a450a2f80696cc63ec978 | be careful with params.pop | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -448,7 +448,7 @@ translations[ad_util.add_jaxvals_p] = add_jaxvals_translation_rule\ndef lower_fun(fun, instantiate=False, initial_style=False):\n\"\"\"Build a translation rule for a traceable function.\"\"\"\ndef f(c, *args, **params):\n- backend = params.pop('backend', None)\n+ backend = params.get('backend', None)\nif initial_style:\naxis_env, xla_args = args[0], args[1:]\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | be careful with params.pop |
260,335 | 23.08.2019 16:40:49 | 25,200 | 050ce59a42723f6c1bcb2115d1e95fca77120aa1 | fix an overzealous error message w/ const cond_fun | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -54,7 +54,7 @@ def _initial_style_jaxpr(fun, in_tree, in_avals):\nin_pvals = [pe.PartialVal((aval, core.unit)) for aval in in_avals]\nfun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\njaxpr, out_pvals, consts = pe.trace_to_jaxpr(fun, in_pvals, instantiate=True)\n- out_avals, _ = unzip2(out_pvals)\n+ out_avals = _map(raise_to_shaped, unzip2(out_pvals)[0])\nconst_avals = tuple(raise_to_shaped(core.get_aval(c)) for c in consts)\ntyped_jaxpr = core.TypedJaxpr(pe.closure_convert_jaxpr(jaxpr),\n(), const_avals + in_avals, out_avals)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -952,6 +952,10 @@ class LaxControlFlowTest(jtu.JaxTestCase):\npython_should_be_executing = False\nlax.while_loop(cond, body, 0)\n+ def testWhileCondConstant(self):\n+ out = lax.while_loop(lambda _: False, lambda _: (), ()) # doesn't crash\n+ self.assertEqual(out, ())\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix an overzealous error message w/ const cond_fun |
260,403 | 23.08.2019 16:51:59 | 25,200 | ba572231691047d4713bd0b8715044249a0817be | fix last mistake | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -448,7 +448,7 @@ translations[ad_util.add_jaxvals_p] = add_jaxvals_translation_rule\ndef lower_fun(fun, instantiate=False, initial_style=False):\n\"\"\"Build a translation rule for a traceable function.\"\"\"\ndef f(c, *args, **params):\n- backend = params.get('backend', None)\n+ backend = params.pop('backend', None)\nif initial_style:\naxis_env, xla_args = args[0], args[1:]\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | fix last mistake |
260,445 | 23.08.2019 16:54:59 | 25,200 | b1604459efcb072a3cffa6f4a8c3aab646317bba | Clarify the intended purpose of tree_util.
Most importantly, this removes the initial paragraph which was easy to
misinterpret to imply that this module was not JAX-specific. | [
{
"change_type": "MODIFY",
"old_path": "jax/tree_util.py",
"new_path": "jax/tree_util.py",
"diff": "\"\"\"Utilities for working with tree-like container data structures.\n-The code here is independent of JAX. The only dependence is on jax.util, which\n-itself has no JAX-specific code.\n-\nThis module provides a small set of utility functions for working with tree-like\ndata structures, such as nested tuples, lists, and dicts. We call these\nstructures pytrees. They are trees in that they are defined recursively (any\n@@ -29,6 +26,12 @@ mapped over, rather than treated as leaves) is extensible. There is a single\nmodule-level registry of types, and class hierarchy is ignored. By registering a\nnew pytree node type, that type in effect becomes transparent to the utility\nfunctions in this file.\n+\n+The primary purpose of this module is to enable the interoperability between\n+user defined data structures and JAX-primitives (e.g. `jit`). Its secondary\n+purpose is to enable writing new primitives that handle pytrees in a way that\n+mimics the existing JAX primitives. This is not meant to be a general purpose\n+tree-like data structure handling library.\n\"\"\"\nfrom __future__ import absolute_import\n"
}
] | Python | Apache License 2.0 | google/jax | Clarify the intended purpose of tree_util.
Most importantly, this removes the initial paragraph which was easy to
misinterpret to imply that this module was not JAX-specific. |
260,403 | 23.08.2019 17:29:30 | 25,200 | bd35ef23668fe0b38a7b9e3975a3650d7913777d | refactor backend check in central dispatch logic | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -234,6 +234,19 @@ def jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *arg\n*arg_shapes)\nreturn c.Build(c.Tuple(*out_nodes))\n+\n+def check_backend_params(params, outer_backend):\n+ # For nested jits, the outer jit sets the backend on all inner jits unless\n+ # an inner-jit also has a conflicting explicit backend specification.\n+ inner_backend = params.get('backend', None)\n+ if inner_backend and inner_backend != outer_backend:\n+ msg = (\n+ \"Outer-jit backend specification {} must match\"\n+ \"explicit inner-jit backend specification {}.\")\n+ raise ValueError(msg.format(outer_backend, inner_backend))\n+ return {k: params[k] for k in params if k != 'backend'}\n+\n+\ndef _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *arg_shapes):\nc = xb.make_computation_builder(\"jaxpr_computation\")\nplatform = xb.get_backend(backend).platform\n@@ -259,36 +272,27 @@ def _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *ar\n_map(write, all_freevars, map(c.ParameterWithShape, freevar_shapes))\n_map(write, jaxpr.invars, map(c.ParameterWithShape, arg_shapes))\nfor eqn in jaxpr.eqns:\n- # For nested jits, the outer jit sets the backend on all inner jits unless\n- # an inner-jit also has a conflicting explicit backend specification.\n- inner_backend = eqn.params.get('backend', None)\n- if inner_backend and inner_backend != backend:\n- msg = (\n- \"Explicit outer-jit backend specification {} must match\"\n- \"explicit inner-jit backend specification {}.\")\n- raise ValueError(msg.format(backend, inner_backend))\n-\nin_nodes = list(map(read, eqn.invars))\n-\nif eqn.primitive in backend_specific_translations[platform]:\nrule = backend_specific_translations[platform][eqn.primitive]\nans = rule(c, *in_nodes, **eqn.params)\nelif eqn.primitive in translations:\nans = translations[eqn.primitive](c, *in_nodes, **eqn.params)\nelif eqn.primitive in reduction_translations:\n- new_params = {k: eqn.params[k] for k in eqn.params if k != 'backend'}\n+ new_params = check_backend_params(eqn.params, backend)\nans = reduction_translations[eqn.primitive](c, *in_nodes, backend=backend, **new_params)\nelif eqn.primitive in initial_style_translations:\n- new_params = {k: eqn.params[k] for k in eqn.params if k != 'backend'}\n+ new_params = check_backend_params(eqn.params, backend)\nrule = initial_style_translations[eqn.primitive]\nans = rule(c, axis_env, *in_nodes, backend=backend, **new_params)\nelif eqn.primitive in parallel_translations:\n- replica_groups = axis_groups(axis_env, eqn.params['axis_name'])\n- new_params = {k: eqn.params[k] for k in eqn.params if k not in ('axis_name', 'backend')}\n+ new_params = check_backend_params(eqn.params, backend)\n+ replica_groups = axis_groups(axis_env, new_params['axis_name'])\n+ new_params = {k: new_params[k] for k in new_params if k != 'axis_name'}\nrule = parallel_translations[eqn.primitive]\nans = rule(c, *in_nodes, replica_groups=replica_groups, backend=backend, **new_params)\nelif eqn.primitive in call_translations:\n- new_params = {k: eqn.params[k] for k in eqn.params if k != 'backend'}\n+ new_params = check_backend_params(eqn.params, backend)\n(subjaxpr, const_bindings, freevar_bindings), = eqn.bound_subjaxprs\nenv_nodes = list(map(read, const_bindings + freevar_bindings))\nrule = call_translations[eqn.primitive]\n"
}
] | Python | Apache License 2.0 | google/jax | refactor backend check in central dispatch logic |
260,335 | 23.08.2019 17:05:32 | 25,200 | d700716e1909434aed41f7ca97d554d32be9017b | add option to disable rank-promotion broadcasting
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -27,12 +27,14 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n+from distutils.util import strtobool\nimport collections\nimport itertools\n+import os\nimport re\nimport string\n-import warnings\nimport types\n+import warnings\nimport numpy as onp\nimport opt_einsum\n@@ -42,12 +44,21 @@ from six.moves import builtins, xrange\nfrom jax import jit, device_put\nfrom .. import core\nfrom ..abstract_arrays import UnshapedArray, ShapedArray, ConcreteArray\n+from ..config import flags\nfrom ..interpreters.xla import DeviceArray\nfrom .. import lax\nfrom ..util import partial, get_module_functions, unzip2, prod as _prod\nfrom ..lib import xla_bridge\nfrom ..lib import xla_client\n+FLAGS = flags.FLAGS\n+flags.DEFINE_enum(\n+ 'jax_numpy_rank_promotion', os.getenv('JAX_NUMPY_RANK_PROMOTION', 'allow'),\n+ enum_values=['allow', 'warn', 'raise'],\n+ help=\n+ 'Control NumPy-style automatic rank promotion broadcasting '\n+ '(\"allow\", \"warn\", or \"raise\").')\n+\nif six.PY3:\ndef removechars(s, chars):\nreturn s.translate(str.maketrans(dict.fromkeys(chars)))\n@@ -158,9 +169,20 @@ def _promote_shapes(*args):\nreturn args\nelse:\nshapes = [shape(arg) for arg in args]\n+ ranks = [len(shp) for shp in shapes]\n+ if len(set(ranks)) == 1:\n+ return args\n+ elif FLAGS.jax_numpy_rank_promotion != \"raise\":\n+ if FLAGS.jax_numpy_rank_promotion == \"warn\":\n+ msg = \"following NumPy automatic rank promotion behavior for {}.\"\n+ warnings.warn(msg.format(' '.join(map(str, shapes))))\nnd = len(lax.broadcast_shapes(*shapes))\nreturn [lax.reshape(arg, (1,) * (nd - len(shp)) + shp)\nif shp and len(shp) != nd else arg for arg, shp in zip(args, shapes)]\n+ else:\n+ msg = (\"operands could not be broadcast together with shapes {} \"\n+ \"and with the config option jax_numpy_rank_promotion='raise'.\")\n+ raise ValueError(msg.format(' '.join(map(str, shapes))))\ndef _promote_dtypes(*args):\n\"\"\"Convenience function to apply Numpy argument dtype promotion.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -186,9 +186,15 @@ class APITest(jtu.JaxTestCase):\ndef f(x, y):\nreturn x + y\n- jtu.check_raises(lambda: grad(f)(onp.zeros(3), onp.zeros(4)),\n- ValueError,\n- \"Incompatible shapes for broadcasting: ((3,), (4,))\")\n+ jtu.check_raises(\n+ lambda: f(np.zeros(3), np.zeros(4)),\n+ TypeError,\n+ \"add got incompatible shapes for broadcasting: (3,), (4,).\")\n+\n+ jtu.check_raises(\n+ lambda: grad(f)(onp.zeros(3), onp.zeros(4)),\n+ TypeError,\n+ \"add got incompatible shapes for broadcasting: (3,), (4,).\")\ndef test_dot_mismatch(self):\ndef f(x, y):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -23,6 +23,7 @@ import itertools\nimport operator\nimport unittest\nfrom unittest import SkipTest\n+import warnings\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -1829,5 +1830,35 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nlnp_fun = partial(lnp.meshgrid, indexing=indexing, sparse=sparse)\nself._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n+ def testDisableNumpyRankPromotionBroadcasting(self):\n+ try:\n+ prev_flag = FLAGS.jax_numpy_rank_promotion\n+ FLAGS.jax_numpy_rank_promotion = \"allow\"\n+ lnp.ones(2) + lnp.ones((1, 2)) # works just fine\n+ finally:\n+ FLAGS.jax_numpy_rank_promotion = prev_flag\n+\n+ try:\n+ prev_flag = FLAGS.jax_numpy_rank_promotion\n+ FLAGS.jax_numpy_rank_promotion = \"raise\"\n+ self.assertRaises(ValueError, lambda: lnp.ones(2) + lnp.ones((1, 2)))\n+ finally:\n+ FLAGS.jax_numpy_rank_promotion = prev_flag\n+\n+ try:\n+ prev_flag = FLAGS.jax_numpy_rank_promotion\n+ FLAGS.jax_numpy_rank_promotion = \"warn\"\n+ with warnings.catch_warnings(record=True) as w:\n+ warnings.simplefilter(\"always\")\n+ lnp.ones(2) + lnp.ones((1, 2))\n+ assert len(w) > 0\n+ msg = str(w[-1].message)\n+ self.assertEqual(\n+ msg,\n+ \"following NumPy automatic rank promotion behavior for (2,) (1, 2).\")\n+ finally:\n+ FLAGS.jax_numpy_rank_promotion = prev_flag\n+\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add option to disable rank-promotion broadcasting
fixes #1236 |
260,403 | 23.08.2019 18:39:26 | 25,200 | 229fdfe919e2bf517603018f20692d5beefd6828 | just say no to pop | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -140,7 +140,8 @@ def xla_primitive_callable(prim, *abstract_args, **params):\n@cache()\ndef primitive_computation(prim, *xla_shapes, **params):\n- backend = params.pop('backend', None)\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\")\nplatform = xb.get_backend(backend).platform\nxla_args = map(c.ParameterWithShape, xla_shapes)\n@@ -455,7 +456,8 @@ translations[ad_util.add_jaxvals_p] = add_jaxvals_translation_rule\ndef lower_fun(fun, instantiate=False, initial_style=False):\n\"\"\"Build a translation rule for a traceable function.\"\"\"\ndef f(c, *args, **params):\n- backend = params.pop('backend', None)\n+ backend = params.get('backend', None)\n+ new_params = {k: params[k] for k in params if k != 'backend'}\nif initial_style:\naxis_env, xla_args = args[0], args[1:]\nelse:\n@@ -464,7 +466,7 @@ def lower_fun(fun, instantiate=False, initial_style=False):\navals = map(_aval_from_xla_shape, xla_shapes)\npvals = [pe.PartialVal((a, core.unit)) for a in avals]\njaxpr, _, consts = pe.trace_to_jaxpr(\n- lu.wrap_init(fun, params), pvals, instantiate=True)\n+ lu.wrap_init(fun, new_params), pvals, instantiate=True)\nbuilt_c = jaxpr_computation(jaxpr, backend, axis_env, consts, (), *xla_shapes)\nreturn c.Call(built_c, xla_args)\nreturn f\n"
}
] | Python | Apache License 2.0 | google/jax | just say no to pop |
260,403 | 23.08.2019 19:01:37 | 25,200 | ee2c6ccac768bbf5d5945544bc97f766badf09fb | uff actually finish last change | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -147,16 +147,16 @@ def primitive_computation(prim, *xla_shapes, **params):\nxla_args = map(c.ParameterWithShape, xla_shapes)\nif prim in backend_specific_translations[platform]:\nrule = backend_specific_translations[platform][prim]\n- rule(c, *xla_args, **params) # return val set as a side-effect on c\n+ rule(c, *xla_args, **new_params) # return val set as a side-effect on c\nelif prim in translations:\nrule = translations[prim]\n- rule(c, *xla_args, **params) # return val set as a side-effect on c\n+ rule(c, *xla_args, **new_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, **params) # return val set as a side-effect on c\n+ rule(c, *xla_args, backend=backend, **new_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(1, [], []), *xla_args, backend=backend, **params) # side-effect on c\n+ rule(c, AxisEnv(1, [], []), *xla_args, backend=backend, **new_params) # side-effect on c\nelse:\nraise NotImplementedError(\"XLA translation rule for {} not found\".format(prim))\ntry:\n"
}
] | Python | Apache License 2.0 | google/jax | uff actually finish last change |
260,403 | 23.08.2019 21:41:55 | 25,200 | a57a1a3943aeaacd56e445fa47a122039dd27b0f | increase minimum jaxlib version and remove some janky feature detection | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -643,13 +643,7 @@ def _device_array_constant_handler(c, val, canonicalize_types=True):\nreturn c.Constant(onp.asarray(val), canonicalize_types=canonicalize_types)\nxb.register_constant_handler(DeviceArray, _device_array_constant_handler)\ndef _device_put_device_array(x, device_num, backend):\n- # TODO(levskaya) remove if-condition after increasing minimum Jaxlib version to\n- # 0.1.24. We assume users with older Jaxlib won't use multiple backends.\n- if hasattr(x.device_buffer, 'platform'):\n- backend_match = xb.get_backend(backend).platform == x.device_buffer.platform()\n- else:\n- backend_match = True\n- if backend_match:\n+ if xb.get_backend(backend).platform == x.device_buffer.platform():\nif x.device_buffer.device() == device_num:\nreturn x.device_buffer\nelse:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lib/__init__.py",
"new_path": "jax/lib/__init__.py",
"diff": "import jaxlib\n-_minimum_jaxlib_version = (0, 1, 22)\n+_minimum_jaxlib_version = (0, 1, 25)\ntry:\nfrom jaxlib import version as jaxlib_version\nexcept:\n"
}
] | Python | Apache License 2.0 | google/jax | increase minimum jaxlib version and remove some janky feature detection |
260,403 | 23.08.2019 23:42:08 | 25,200 | 91a23116013ff8a35d1ae7ce1f969711d05b0c2e | clean up multibackend tests | [
{
"change_type": "MODIFY",
"old_path": "tests/multibackend_test.py",
"new_path": "tests/multibackend_test.py",
"diff": "@@ -24,6 +24,7 @@ from absl.testing import parameterized\nimport numpy as onp\nimport numpy.random as npr\nimport six\n+from unittest import SkipTest\nfrom jax import api\nfrom jax import test_util as jtu\n@@ -42,10 +43,11 @@ class MultiBackendTest(jtu.JaxTestCase):\n{\"testcase_name\": \"_backend={}\".format(backend),\n\"backend\": backend,\n}\n- for backend in ['cpu', 'gpu']\n+ for backend in ['cpu', 'gpu', 'tpu', None]\n))\n- @jtu.skip_on_devices('cpu', 'tpu')\n- def testGpuMultiBackend(self, backend):\n+ def testMultiBackend(self, backend):\n+ if backend not in ('cpu', jtu.device_under_test(), None):\n+ raise SkipTest()\n@partial(api.jit, backend=backend)\ndef fun(x, y):\nreturn np.matmul(x, y)\n@@ -54,33 +56,17 @@ class MultiBackendTest(jtu.JaxTestCase):\nz_host = onp.matmul(x, y)\nz = fun(x, y)\nself.assertAllClose(z, z_host, check_dtypes=True)\n- self.assertEqual(z.device_buffer.platform(), backend)\n-\n- @parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_backend={}\".format(backend),\n- \"backend\": backend,\n- }\n- for backend in ['cpu', 'tpu']\n- ))\n- @jtu.skip_on_devices('cpu', 'gpu')\n- def testTpuMultiBackend(self, backend):\n- @partial(api.jit, backend=backend)\n- def fun(x, y):\n- return np.matmul(x, y)\n- x = npr.uniform(size=(10,10))\n- y = npr.uniform(size=(10,10))\n- z_host = onp.matmul(x, y)\n- z = fun(x, y)\n- self.assertAllClose(z, z_host, check_dtypes=True)\n- self.assertEqual(z.device_buffer.platform(), backend)\n+ correct_platform = backend if backend else jtu.device_under_test()\n+ self.assertEqual(z.device_buffer.platform(), correct_platform)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_ordering={}\".format(ordering),\n\"ordering\": ordering,}\n- for ordering in [('cpu', None), ('tpu', None)]))\n- @jtu.skip_on_devices('cpu', 'gpu')\n- def testTpuMultiBackendNestedJit(self, ordering):\n+ for ordering in [('cpu', None), ('gpu', None), ('tpu', None), (None, None)]))\n+ def testMultiBackendNestedJit(self, ordering):\nouter, inner = ordering\n+ if outer not in ('cpu', jtu.device_under_test(), None):\n+ raise SkipTest()\n@partial(api.jit, backend=outer)\ndef fun(x, y):\n@partial(api.jit, backend=inner)\n@@ -92,56 +78,23 @@ class MultiBackendTest(jtu.JaxTestCase):\nz_host = onp.matmul(x, y) + onp.ones_like(x)\nz = fun(x, y)\nself.assertAllClose(z, z_host, check_dtypes=True)\n- self.assertEqual(z.device_buffer.platform(), outer)\n-\n- @parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_ordering={}\".format(ordering),\n- \"ordering\": ordering,}\n- for ordering in [('cpu', None), ('gpu', None)]))\n- @jtu.skip_on_devices('cpu', 'tpu')\n- def testGpuMultiBackendNestedJit(self, ordering):\n- outer, inner = ordering\n- @partial(api.jit, backend=outer)\n- def fun(x, y):\n- @partial(api.jit, backend=inner)\n- def infun(x, y):\n- return np.matmul(x, y)\n- return infun(x, y) + np.ones_like(x)\n- x = npr.uniform(size=(10,10))\n- y = npr.uniform(size=(10,10))\n- z_host = onp.matmul(x, y) + onp.ones_like(x)\n- z = fun(x, y)\n- self.assertAllClose(z, z_host, check_dtypes=True)\n- self.assertEqual(z.device_buffer.platform(), outer)\n-\n- @parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_ordering={}\".format(ordering),\n- \"ordering\": ordering,}\n- for ordering in [\n- ('cpu', 'tpu'), ('tpu', 'cpu'), (None, 'cpu'), (None, 'tpu'),\n- ]))\n- @jtu.skip_on_devices('cpu', 'gpu')\n- def testTpuMultiBackendNestedJitConflict(self, ordering):\n- outer, inner = ordering\n- @partial(api.jit, backend=outer)\n- def fun(x, y):\n- @partial(api.jit, backend=inner)\n- def infun(x, y):\n- return np.matmul(x, y)\n- return infun(x, y) + np.ones_like(x)\n- x = npr.uniform(size=(10,10))\n- y = npr.uniform(size=(10,10))\n- self.assertRaises(ValueError, lambda: fun(x, y))\n+ correct_platform = outer if outer else jtu.device_under_test()\n+ self.assertEqual(z.device_buffer.platform(), correct_platform)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_ordering={}\".format(ordering),\n\"ordering\": ordering,}\nfor ordering in [\n- ('cpu', 'gpu'), ('gpu', 'cpu'), (None, 'cpu'), (None, 'gpu'),\n+ ('cpu', 'gpu'), ('gpu', 'cpu'),\n+ ('cpu', 'tpu'), ('tpu', 'cpu'),\n+ (None, 'cpu'), (None, 'gpu'), (None, 'tpu'),\n]))\n- @jtu.skip_on_devices('cpu', 'tpu')\n- def testGpuMultiBackendNestedJitConflict(self, ordering):\n+ def testMultiBackendNestedJitConflict(self, ordering):\nouter, inner = ordering\n+ if outer not in ('cpu', jtu.device_under_test(), None):\n+ raise SkipTest()\n+ if inner not in ('cpu', jtu.device_under_test(), None):\n+ raise SkipTest()\n@partial(api.jit, backend=outer)\ndef fun(x, y):\n@partial(api.jit, backend=inner)\n@@ -155,10 +108,11 @@ class MultiBackendTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_backend={}\".format(backend),\n\"backend\": backend,}\n- for backend in ['cpu', 'gpu']\n+ for backend in ['cpu', 'gpu', 'tpu']\n))\n- @jtu.skip_on_devices('cpu', 'tpu')\ndef testGpuMultiBackendOpByOpReturn(self, backend):\n+ if backend not in ('cpu', jtu.device_under_test()):\n+ raise SkipTest()\n@partial(api.jit, backend=backend)\ndef fun(x, y):\nreturn np.matmul(x, y)\n@@ -167,24 +121,7 @@ class MultiBackendTest(jtu.JaxTestCase):\nz = fun(x, y)\nw = np.sin(z)\nself.assertEqual(z.device_buffer.platform(), backend)\n- self.assertEqual(w.device_buffer.platform(), 'gpu')\n-\n- @parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_backend={}\".format(backend),\n- \"backend\": backend,}\n- for backend in ['cpu', 'tpu']\n- ))\n- @jtu.skip_on_devices('cpu', 'gpu')\n- def testTpuMultiBackendOpByOpReturn(self, backend):\n- @partial(api.jit, backend=backend)\n- def fun(x, y):\n- return np.matmul(x, y)\n- x = npr.uniform(size=(10,10))\n- y = npr.uniform(size=(10,10))\n- z = fun(x, y)\n- w = np.sin(z)\n- self.assertEqual(z.device_buffer.platform(), backend)\n- self.assertEqual(w.device_buffer.platform(), 'tpu')\n+ self.assertEqual(w.device_buffer.platform(), jtu.device_under_test())\nif __name__ == \"__main__\":\n"
}
] | Python | Apache License 2.0 | google/jax | clean up multibackend tests |
260,335 | 22.08.2019 09:22:57 | 25,200 | e90457d737ba287d46a063aff467f2079a92b722 | add dtype warnings to array-creation routines
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/__init__.py",
"new_path": "jax/lax/__init__.py",
"diff": "@@ -18,7 +18,7 @@ from .lax import (_reduce_sum, _reduce_max, _reduce_min, _reduce_or,\n_reduce_and, _reduce_window_sum, _reduce_window_max,\n_reduce_window_min, _reduce_window_prod, _float, _complex,\n_input_dtype, _const, _eq_meet, _safe_mul,\n- _broadcasting_select)\n+ _broadcasting_select, _check_user_dtype_supported)\nfrom .lax_control_flow import *\nfrom .lax_fft import *\nfrom .lax_parallel import *\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -4408,3 +4408,15 @@ def subvals(lst, replace):\ndef _abstractify(x):\nreturn raise_to_shaped(core.get_aval(x))\n+\n+\n+def _check_user_dtype_supported(dtype, fun_name=None):\n+ if dtype is not None and onp.dtype(dtype) != xla_bridge.canonicalize_dtype(dtype):\n+ msg = (\"Explicitly requested dtype {} {} is not available, \"\n+ \"and will be truncated to dtype {}. To enable more dtypes, set the \"\n+ \"jax_enable_x64 configuration option or the JAX_ENABLE_X64 shell \"\n+ \"environment variable. \"\n+ \"See https://github.com/google/jax#current-gotchas for more.\")\n+ fun_name = \"requested in {}\".format(fun_name) if fun_name else \"\"\n+ truncated_dtype = xla_bridge.canonicalize_dtype(dtype).name\n+ warnings.warn(msg.format(dtype, fun_name , truncated_dtype))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1408,6 +1408,7 @@ def atleast_3d(*arys):\ndef array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nif order is not None and order != \"K\":\nraise NotImplementedError(\"Only implemented for order='K'\")\n+ lax._check_user_dtype_supported(dtype, \"array\")\nif isinstance(object, ndarray):\nif dtype and _dtype(object) != xla_bridge.canonicalize_dtype(dtype):\n@@ -1442,38 +1443,49 @@ def array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\n@_wraps(onp.asarray)\ndef asarray(a, dtype=None, order=None):\n+ lax._check_user_dtype_supported(dtype, \"asarray\")\nreturn array(a, dtype=dtype, copy=False, order=order)\n@_wraps(onp.zeros_like)\ndef zeros_like(x, dtype=None):\n+ lax._check_user_dtype_supported(dtype, \"zeros_like\")\nreturn lax.full_like(x, 0, dtype)\n@_wraps(onp.ones_like)\ndef ones_like(x, dtype=None):\n+ lax._check_user_dtype_supported(dtype, \"ones_like\")\nreturn lax.full_like(x, 1, dtype)\n@_wraps(onp.full)\ndef full(shape, fill_value, dtype=None):\n+ lax._check_user_dtype_supported(dtype, \"full\")\nreturn lax.full(shape, fill_value, dtype)\n@_wraps(onp.full_like)\ndef full_like(a, fill_value, dtype=None):\n+ lax._check_user_dtype_supported(dtype, \"full_like\")\nreturn lax.full_like(a, fill_value, dtype)\n@_wraps(onp.zeros)\n-def zeros(shape, dtype=onp.dtype(\"float64\")):\n+def zeros(shape, dtype=None):\nif isinstance(shape, types.GeneratorType):\nraise TypeError(\"expected sequence object with len >= 0 or a single integer\")\n+ dtype = onp.dtype(\"float64\") if dtype is None else dtype\n+ lax._check_user_dtype_supported(dtype, \"zeros\")\nshape = (shape,) if onp.isscalar(shape) else shape\nreturn lax.full(shape, 0, dtype)\n@_wraps(onp.ones)\n-def ones(shape, dtype=onp.dtype(\"float64\")):\n+def ones(shape, dtype=None):\n+ if isinstance(shape, types.GeneratorType):\n+ raise TypeError(\"expected sequence object with len >= 0 or a single integer\")\n+ lax._check_user_dtype_supported(dtype, \"ones\")\n+ dtype = onp.dtype(\"float64\") if dtype is None else dtype\nshape = (shape,) if onp.isscalar(shape) else shape\nreturn lax.full(shape, 1, dtype)\n@@ -1493,7 +1505,9 @@ empty = zeros\n@_wraps(onp.eye)\n-def eye(N, M=None, k=None, dtype=onp.dtype(\"float64\")):\n+def eye(N, M=None, k=None, dtype=None):\n+ lax._check_user_dtype_supported(dtype, \"eye\")\n+ dtype = onp.dtype(\"float64\") if dtype is None else dtype\nM = N if M is None else M\nif N < 0 or M < 0:\nmsg = \"negative dimensions are not allowed, got {} and {}\"\n@@ -1512,11 +1526,13 @@ def eye(N, M=None, k=None, dtype=onp.dtype(\"float64\")):\n@_wraps(onp.identity)\ndef identity(n, dtype=None):\n+ lax._check_user_dtype_supported(dtype, \"identity\")\nreturn eye(n, dtype=dtype)\n@_wraps(onp.arange)\ndef arange(start, stop=None, step=None, dtype=None):\n+ lax._check_user_dtype_supported(dtype, \"arange\")\n# If called like np.arange(N), we create a lazy lax._IotaConstant.\nif stop is None and step is None:\ndtype = dtype or _dtype(start)\n@@ -1538,6 +1554,7 @@ def _wrap_numpy_nullary_function(f):\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,\naxis=0):\n+ lax._check_user_dtype_supported(dtype, \"linspace\")\ntry:\nout = onp.linspace(start, stop, num, endpoint, retstep, dtype, axis)\nif retstep:\n@@ -1646,6 +1663,7 @@ def repeat(a, repeats, axis=None):\n@_wraps(onp.tri)\ndef tri(N, M=None, k=0, dtype=None):\n+ lax._check_user_dtype_supported(dtype, \"tri\")\nM = M if M is not None else N\ndtype = dtype or float32\nx = arange(N, dtype=int32)\n@@ -1679,6 +1697,7 @@ def triu(m, k=0):\ndef trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):\nif out:\nraise NotImplementedError(\"The 'out' argument to trace is not supported.\")\n+ lax._check_user_dtype_supported(dtype, \"trace\")\naxis1 = _canonicalize_axis(axis1, ndim(a))\naxis2 = _canonicalize_axis(axis2, ndim(a))\n@@ -2839,6 +2858,10 @@ def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):\nreturn quantile(a, q, axis=axis, out=out, overwrite_input=overwrite_input,\nkeepdims=keepdims)\n+def _astype(arr, dtype):\n+ lax._check_user_dtype_supported(dtype, \"astype\")\n+ return lax.convert_element_type(arr, dtype)\n+\n### track unimplemented functions\ndef _not_implemented(fun):\n@@ -2934,7 +2957,7 @@ setattr(ShapedArray, \"flatten\", core.aval_method(ravel))\nsetattr(ShapedArray, \"T\", core.aval_property(transpose))\nsetattr(ShapedArray, \"real\", core.aval_property(real))\nsetattr(ShapedArray, \"imag\", core.aval_property(imag))\n-setattr(ShapedArray, \"astype\", core.aval_method(lax.convert_element_type))\n+setattr(ShapedArray, \"astype\", core.aval_method(_astype))\n# Forward operators, methods, and properties on DeviceArray to lax_numpy\n@@ -2948,7 +2971,7 @@ setattr(DeviceArray, \"flatten\", ravel)\nsetattr(DeviceArray, \"T\", property(transpose))\nsetattr(DeviceArray, \"real\", property(real))\nsetattr(DeviceArray, \"imag\", property(imag))\n-setattr(DeviceArray, \"astype\", lax.convert_element_type)\n+setattr(DeviceArray, \"astype\", _astype)\n# Extra methods that are handy\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -19,6 +19,7 @@ from __future__ import print_function\nimport collections\nfrom functools import partial\nimport unittest\n+import warnings\nfrom absl.testing import absltest\nimport numpy as onp\n@@ -41,6 +42,7 @@ from jax import tree_util\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n+FLAGS = config.FLAGS\nclass APITest(jtu.JaxTestCase):\n@@ -975,6 +977,53 @@ class APITest(jtu.JaxTestCase):\nfor x, y in zip(xs, ys):\nself.assertAllClose(x * 2 - 3., y, check_dtypes=True)\n+ def test_issue_1230(self):\n+ if FLAGS.jax_enable_x64:\n+ return # test only applies when x64 is disabled\n+\n+ def check_warning(warn, nowarn):\n+ with warnings.catch_warnings(record=True) as w:\n+ warnings.simplefilter(\"always\")\n+\n+ nowarn() # get rid of extra startup warning\n+\n+ prev_len = len(w)\n+ nowarn()\n+ assert len(w) == prev_len\n+\n+ warn()\n+ assert len(w) > 0\n+ msg = str(w[-1].message)\n+ expected_prefix = \"Explicitly requested dtype \"\n+ self.assertEqual(expected_prefix, msg[:len(expected_prefix)])\n+\n+ prev_len = len(w)\n+ nowarn()\n+ assert len(w) == prev_len\n+\n+ check_warning(lambda: np.array([1, 2, 3], dtype=\"float64\"),\n+ lambda: np.array([1, 2, 3], dtype=\"float32\"),)\n+ check_warning(lambda: np.ones(3, dtype=onp.float64),\n+ lambda: np.ones(3))\n+ check_warning(lambda: np.ones_like(3, dtype=onp.int64),\n+ lambda: np.ones_like(3, dtype=onp.int32))\n+ check_warning(lambda: np.zeros(3, dtype=\"int64\"),\n+ lambda: np.zeros(3, dtype=\"int32\"))\n+ check_warning(lambda: np.zeros_like(3, dtype=\"float64\"),\n+ lambda: np.zeros_like(3, dtype=\"float32\"))\n+ check_warning(lambda: np.full((2, 3), 1, dtype=\"int64\"),\n+ lambda: np.full((2, 3), 1))\n+ check_warning(lambda: np.ones(3).astype(\"float64\"),\n+ lambda: np.ones(3).astype(\"float32\"))\n+ check_warning(lambda: np.eye(3, dtype=onp.float64),\n+ lambda: np.eye(3))\n+ check_warning(lambda: np.arange(3, dtype=onp.float64),\n+ lambda: np.arange(3, dtype=onp.float32))\n+ check_warning(lambda: np.linspace(0, 3, dtype=onp.float64),\n+ lambda: np.linspace(0, 3, dtype=onp.float32))\n+ check_warning(lambda: np.tri(2, dtype=\"float64\"),\n+ lambda: np.tri(2, dtype=\"float32\"))\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add dtype warnings to array-creation routines
fixes #1230 |
260,335 | 25.08.2019 13:02:18 | 25,200 | 434d175381b653d8bb65e201b0a7babff091cbcb | fix device_constant instantiation bug, fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -656,4 +656,5 @@ def _instantiate_device_constant(const, device_num=0, cutoff=1e6):\ncompiled = c.Build(xla_const).Compile((), opts, backend=xb.get_backend())\nreturn compiled.Execute(())\nelse:\n- return xc.Buffer.from_pyval(onp.asarray(const), device_num)\n+ return xc.Buffer.from_pyval(onp.asarray(const), device_num,\n+ backend=xb.get_backend())\n"
}
] | Python | Apache License 2.0 | google/jax | fix device_constant instantiation bug, fixes #1241 |
260,335 | 25.08.2019 14:28:53 | 25,200 | 3c2a73592c407a0a44d7df3273594a41fbd7ce4b | improve rank promotion warning, add doc page | [
{
"change_type": "MODIFY",
"old_path": "docs/index.rst",
"new_path": "docs/index.rst",
"diff": "@@ -15,6 +15,7 @@ For an introduction to JAX, start at the\nconcurrency\ngpu_memory_allocation\nprofiling\n+ rank_promotion_warning\n.. toctree::\n:maxdepth: 3\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/rank_promotion_warning.rst",
"diff": "+Rank promotion warning\n+======================\n+\n+`NumPy broadcasting rules\n+<https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html#general-broadcasting-rules>`_\n+allow automatic promotion of arguments from one rank (number of array axes) to\n+another. This behavior can be convenient when intended but can also lead to\n+surprising bugs where a silent rank promotion masks an underlying shape error.\n+\n+Here's an example of rank promotion:\n+\n+>>> import numpy as onp\n+>>> x = onp.arange(12).reshape(4, 3)\n+>>> y = onp.array([0, 1, 0])\n+>>> x + y\n+array([[ 0, 2, 2],\n+ [ 3, 5, 5],\n+ [ 6, 8, 8],\n+ [ 9, 11, 11]])\n+\n+To avoid potential surprises, :code:`jax.numpy` is configurable so that\n+expressions requiring rank promotion can lead to a warning, error, or can be\n+allowed just like regular NumPy. The configuration option is named\n+:code:`jax_numpy_rank_promotion` and it can take on string values\n+:code:`allow`, :code:`warn`, and :code:`raise`. The default setting is\n+:code:`warn`, which raises a warning on the first occurrence of rank promotion.\n+\n+As with most other JAX configuration options, you can set this option in\n+several ways. One is by using :code:`jax.config` in your code:\n+\n+..code-block:: python\n+\n+ from jax.config import config\n+ config.update(\"jax_numpy_rank_promotion\", \"allow\")\n+\n+You can also set the option using the environment variable\n+:code:`JAX_NUMPY_RANK_PROMOTION`, for example as\n+:code:`JAX_NUMPY_RANK_PROMOTION='raise'`. Finally, when using :code:`absl-py`\n+the option can be set with a command-line flag.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -53,7 +53,7 @@ from ..lib import xla_client\nFLAGS = flags.FLAGS\nflags.DEFINE_enum(\n- 'jax_numpy_rank_promotion', os.getenv('JAX_NUMPY_RANK_PROMOTION', 'allow'),\n+ 'jax_numpy_rank_promotion', os.getenv('JAX_NUMPY_RANK_PROMOTION', 'warn'),\nenum_values=['allow', 'warn', 'raise'],\nhelp=\n'Control NumPy-style automatic rank promotion broadcasting '\n@@ -160,29 +160,39 @@ save = onp.save\nsavez = onp.savez\nload = onp.load\n-### utility functions\n+### utility functions\n-def _promote_shapes(*args):\n+def _promote_shapes(fun_name, *args):\n\"\"\"Prepend implicit leading singleton dimensions for Numpy broadcasting.\"\"\"\nif len(args) < 2:\nreturn args\nelse:\nshapes = [shape(arg) for arg in args]\n- ranks = [len(shp) for shp in shapes]\n- if len(set(ranks)) == 1:\n+ nonscalar_ranks = [len(shp) for shp in shapes if shp]\n+ if not nonscalar_ranks or len(set(nonscalar_ranks)) == 1:\nreturn args\n- elif FLAGS.jax_numpy_rank_promotion != \"raise\":\n- if FLAGS.jax_numpy_rank_promotion == \"warn\":\n- msg = \"following NumPy automatic rank promotion behavior for {}.\"\n- warnings.warn(msg.format(' '.join(map(str, shapes))))\n- nd = len(lax.broadcast_shapes(*shapes))\n- return [lax.reshape(arg, (1,) * (nd - len(shp)) + shp)\n- if shp and len(shp) != nd else arg for arg, shp in zip(args, shapes)]\nelse:\n- msg = (\"operands could not be broadcast together with shapes {} \"\n- \"and with the config option jax_numpy_rank_promotion='raise'.\")\n- raise ValueError(msg.format(' '.join(map(str, shapes))))\n+ if FLAGS.jax_numpy_rank_promotion != \"allow\":\n+ _rank_promotion_warning_or_error(fun_name, shapes)\n+ result_rank = len(lax.broadcast_shapes(*shapes))\n+ return [lax.reshape(arg, (1,) * (result_rank - len(shp)) + shp)\n+ if shp and len(shp) != result_rank else arg\n+ for arg, shp in zip(args, shapes)]\n+\n+def _rank_promotion_warning_or_error(fun_name, shapes):\n+ if FLAGS.jax_numpy_rank_promotion == \"warn\":\n+ msg = (\"Following NumPy automatic rank promotion for {} on shapes {}. \"\n+ \"Set the jax_numpy_rank_promotion config option to 'allow' to \"\n+ \"disable this warning; for more information, see \"\n+ \"https://jax.readthedocs.io/en/latest/rank_promotion_warning.html.\")\n+ warnings.warn(msg.format(fun_name, ' '.join(map(str, shapes))))\n+ elif FLAGS.jax_numpy_rank_promotion == \"raise\":\n+ msg = (\"Operands could not be broadcast together for {} on shapes {} \"\n+ \"and with the config option jax_numpy_rank_promotion='raise'. \"\n+ \"For more information, see \"\n+ \"https://jax.readthedocs.io/en/latest/rank_promotion_warning.html.\")\n+ raise ValueError(msg.format(fun_name, ' '.join(map(str, shapes))))\ndef _promote_dtypes(*args):\n\"\"\"Convenience function to apply Numpy argument dtype promotion.\"\"\"\n@@ -219,13 +229,13 @@ def _check_arraylike(fun_name, *args):\ndef _promote_args(fun_name, *args):\n\"\"\"Convenience function to apply Numpy argument shape and dtype promotion.\"\"\"\n_check_arraylike(fun_name, *args)\n- return _promote_shapes(*_promote_dtypes(*args))\n+ return _promote_shapes(fun_name, *_promote_dtypes(*args))\ndef _promote_args_like(op, *args):\n\"\"\"Convenience function to apply shape and dtype promotion to result type.\"\"\"\n_check_arraylike(op.__name__, *args)\n- return _promote_shapes(*_promote_to_result_dtype(op, *args))\n+ return _promote_shapes(op.__name__, *_promote_to_result_dtype(op, *args))\ndef _constant_like(x, const):\n@@ -376,7 +386,7 @@ logical_xor = _logical_op(onp.logical_xor, lax.bitwise_xor)\n@_wraps(onp.true_divide)\ndef true_divide(x1, x2):\nresult_dtype = _result_dtype(onp.true_divide, x1, x2)\n- x1, x2 = _promote_shapes(x1, x2)\n+ x1, x2 = _promote_shapes(\"true_divide\", x1, x2)\nreturn lax.div(lax.convert_element_type(x1, result_dtype),\nlax.convert_element_type(x2, result_dtype))\n@@ -461,14 +471,16 @@ def power(x1, x2):\n@_wraps(onp.logaddexp)\ndef logaddexp(x1, x2):\n- x1, x2 = _promote_shapes(*_promote_to_result_dtype(onp.logaddexp, x1, x2))\n+ x1, x2 = _promote_shapes(\"logaddexp\",\n+ *_promote_to_result_dtype(onp.logaddexp, x1, x2))\namax = lax.max(x1, x2)\nreturn lax.add(amax, lax.log1p(lax.exp(-lax.abs(lax.sub(x1, x2)))))\n@_wraps(onp.logaddexp2)\ndef logaddexp2(x1, x2):\n- x1, x2 = _promote_shapes(*_promote_to_result_dtype(onp.logaddexp2, x1, x2))\n+ x1, x2 = _promote_shapes(\"logaddexp2\",\n+ *_promote_to_result_dtype(onp.logaddexp2, x1, x2))\namax = lax.max(x1, x2)\nreturn lax.add(amax, log2(lax.add(exp2(lax.sub(x1, amax)),\nexp2(lax.sub(x2, amax)))))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1853,9 +1853,13 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nlnp.ones(2) + lnp.ones((1, 2))\nassert len(w) > 0\nmsg = str(w[-1].message)\n- self.assertEqual(\n- msg,\n- \"following NumPy automatic rank promotion behavior for (2,) (1, 2).\")\n+ expected_msg = (\"Following NumPy automatic rank promotion for add on \"\n+ \"shapes (2,) (1, 2).\")\n+ self.assertEqual(msg[:len(expected_msg)], expected_msg)\n+\n+ prev_len = len(w)\n+ lnp.ones(2) + 3\n+ self.assertEqual(len(w), prev_len) # don't want to warn for scalars\nfinally:\nFLAGS.jax_numpy_rank_promotion = prev_flag\n"
}
] | Python | Apache License 2.0 | google/jax | improve rank promotion warning, add doc page |
260,335 | 25.08.2019 14:36:23 | 25,200 | c6f430a83173ada92c3eaba675f3f7f4befdf0e5 | tweak rank promotion warning docs | [
{
"change_type": "MODIFY",
"old_path": "docs/rank_promotion_warning.rst",
"new_path": "docs/rank_promotion_warning.rst",
"diff": "@@ -24,6 +24,8 @@ allowed just like regular NumPy. The configuration option is named\n:code:`jax_numpy_rank_promotion` and it can take on string values\n:code:`allow`, :code:`warn`, and :code:`raise`. The default setting is\n:code:`warn`, which raises a warning on the first occurrence of rank promotion.\n+The :code:`raise` setting raises an error on rank promotion, and :code:`allow`\n+allows rank promotion without warning or error.\nAs with most other JAX configuration options, you can set this option in\nseveral ways. One is by using :code:`jax.config` in your code:\n"
}
] | Python | Apache License 2.0 | google/jax | tweak rank promotion warning docs |
260,335 | 25.08.2019 19:59:50 | 25,200 | f639b808c44cca35ebc27308a7821159a1d86a8a | instantiate zeros for custom vjp rules | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -376,6 +376,7 @@ def defvjp_all(prim, custom_vjp):\ndef fun_lin_transpose(cts, *args, **kwargs):\nnum_res, trans_jaxpr = kwargs['num_res'], kwargs['trans_jaxpr']\nres, _ = split_list(args, [num_res])\n+ cts = map(instantiate_zeros_aval, kwargs['out_avals'], cts)\nouts = core.eval_jaxpr(trans_jaxpr, res, (), *cts)\nreturn [None] * num_res + outs\nprimitive_transposes[fun_lin_p] = fun_lin_transpose\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1025,6 +1025,18 @@ class APITest(jtu.JaxTestCase):\ncheck_warning(lambda: np.tri(2, dtype=\"float64\"),\nlambda: np.tri(2, dtype=\"float32\"))\n+ def test_custom_vjp_zeros(self):\n+ @api.custom_transforms\n+ def f(x, y):\n+ return 2 * x, 3 * y\n+\n+ def f_vjp(x, y):\n+ return (2 * x, 3 * y), lambda ts: (4 * ts[0], 5 * ts[1])\n+\n+ api.defvjp_all(f, f_vjp, )\n+\n+ api.grad(lambda x, y: f(x, y)[0])(1., 2.) # doesn't crash\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | instantiate zeros for custom vjp rules |
260,314 | 26.08.2019 01:32:18 | 14,400 | 28df8a666b8c99f7ea46842e9b8fc7ca81e0b6c9 | cast float64 to canonical dtype in np.cov | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2729,7 +2729,7 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,\nif m.ndim > 2:\nraise ValueError(\"m has more than 2 dimensions\") # same as numpy error\n- X = array(m, ndmin=2, dtype=result_type(m, onp.float64), copy=False)\n+ X = array(m, ndmin=2, dtype=xla_bridge.canonicalize_dtype(result_type(m, onp.float64)), copy=False)\nif not rowvar and X.shape[0] != 1:\nX = X.T\nif X.shape[0] == 0:\n"
}
] | Python | Apache License 2.0 | google/jax | cast float64 to canonical dtype in np.cov |
260,335 | 26.08.2019 12:35:39 | 25,200 | 94b1dda42ff5ade2a287341bb06c144d38ce837e | fix notebook link (fixes | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -92,7 +92,7 @@ And for a deeper dive into JAX:\n- [The Autodiff Cookbook, Part 1: easy and powerful automatic differentiation in JAX](https://colab.research.google.com/github/google/jax/blob/master/notebooks/autodiff_cookbook.ipynb)\n- [Directly using XLA in Python](https://colab.research.google.com/github/google/jax/blob/master/notebooks/XLA_in_Python.ipynb)\n- [MAML Tutorial with JAX](https://colab.research.google.com/github/google/jax/blob/master/notebooks/maml.ipynb)\n-- [Generative Modeling by Estimating Gradeints of Data Distribution in JAX](https://colab.research.google.com/github/google/jax/blob/master/notebooks/score-matching.ipynb).\n+- [Generative Modeling by Estimating Gradeints of Data Distribution in JAX](https://colab.research.google.com/github/google/jax/blob/master/notebooks/score_matching.ipynb).\n## Installation\nJAX is written in pure Python, but it depends on XLA, which needs to be compiled\n"
}
] | Python | Apache License 2.0 | google/jax | fix notebook link (fixes #1252) |
260,335 | 26.08.2019 13:38:08 | 25,200 | 6a81d81d9b8e752c2a983f151eb947ecfe08dd54 | fix for custom-transforms vjp nones bug | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1481,7 +1481,7 @@ def defvjp_all(fun, custom_vjp):\ncts = tree_unflatten(out_tree, cts_flat)\nargs_cts_flat, in_tree2 = tree_flatten(vjp(cts))\nassert in_tree == in_tree2\n- return [None] * num_consts + list(args_cts_flat)\n+ return [core.unit] * num_consts + list(args_cts_flat)\nreturn out_flat, vjp_flat\nad.defvjp_all(fun.prim, custom_transforms_vjp)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1034,9 +1034,32 @@ class APITest(jtu.JaxTestCase):\nreturn (2 * x, 3 * y), lambda ts: (4 * ts[0], 5 * ts[1])\napi.defvjp_all(f, f_vjp, )\n-\napi.grad(lambda x, y: f(x, y)[0])(1., 2.) # doesn't crash\n+ def test_custom_transforms_vjp_nones(self):\n+ # issue rasied by jsnoek@ and jumper@\n+ @jax.custom_transforms\n+ def solve(a, b):\n+ return np.dot(np.linalg.inv(a), b)\n+ # print(solve(a, b))\n+\n+ def solve_vjp(a, b):\n+ x = solve(a, b)\n+ def vjp(x_tangent):\n+ dx = np.dot(solve(a, x_tangent), x.T)\n+ out = (dx, b * 0.)\n+ return out\n+ return x, vjp\n+ jax.defvjp_all(solve, solve_vjp)\n+ gf = grad(lambda a,b: np.sum(solve(a, b)))\n+\n+ n = 3\n+ a_in = np.linspace(0, 1, n)[:, None]\n+ a = np.dot(a_in, a_in.T) + np.eye(n) * 0.1\n+ real_x = onp.random.RandomState(0).randn(n)\n+ b = np.dot(a + np.eye(a.shape[0]), real_x)\n+ print(gf(a, b)) # doesn't crash\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix for custom-transforms vjp nones bug
Co-authored-by: Dougal Maclaurin <dougalm@google.com> |
260,335 | 26.08.2019 14:05:17 | 25,200 | dbe56c30ac6fdc84b2729c4790ad160474081f64 | leave todos for better error messages | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1476,11 +1476,11 @@ def defvjp_all(fun, custom_vjp):\nargs = tree_unflatten(params['in_tree'], args_flat)\nout, vjp = custom_vjp(*args)\nout_flat, out_tree = tree_flatten(out)\n- assert out_tree == params['out_tree']\n+ assert out_tree == params['out_tree'] # TODO(mattjj): better error message\ndef vjp_flat(*cts_flat):\ncts = tree_unflatten(out_tree, cts_flat)\nargs_cts_flat, in_tree2 = tree_flatten(vjp(cts))\n- assert in_tree == in_tree2\n+ assert in_tree == in_tree2 # TODO(mattjj): better error message\nreturn [core.unit] * num_consts + list(args_cts_flat)\nreturn out_flat, vjp_flat\nad.defvjp_all(fun.prim, custom_transforms_vjp)\n"
}
] | Python | Apache License 2.0 | google/jax | leave todos for better error messages |
260,335 | 27.08.2019 11:21:50 | 25,200 | 1cd37bd97707ef660d4e7fdcd8147baf69060e9c | reset jax_numpy_rank_promotion to "allow" default | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -53,7 +53,7 @@ from ..lib import xla_client\nFLAGS = flags.FLAGS\nflags.DEFINE_enum(\n- 'jax_numpy_rank_promotion', os.getenv('JAX_NUMPY_RANK_PROMOTION', 'warn'),\n+ 'jax_numpy_rank_promotion', os.getenv('JAX_NUMPY_RANK_PROMOTION', 'allow'),\nenum_values=['allow', 'warn', 'raise'],\nhelp=\n'Control NumPy-style automatic rank promotion broadcasting '\n"
}
] | Python | Apache License 2.0 | google/jax | reset jax_numpy_rank_promotion to "allow" default |
260,335 | 27.08.2019 15:56:45 | 25,200 | fd9e0333a6430bb06bd7a0c9faa650c66fdf2a21 | add try/finally to pxla global state management | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/parallel.py",
"new_path": "jax/interpreters/parallel.py",
"diff": "@@ -16,7 +16,6 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n-from contextlib import contextmanager\nfrom functools import partial\nimport warnings\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -232,7 +232,9 @@ _thread_local_state = _ThreadLocalState()\ndef extend_dynamic_axis_env(axis_name, pmap_trace, hard_size):\ndynamic_axis_env = _thread_local_state.dynamic_axis_env\ndynamic_axis_env.append(DynamicAxisEnvFrame(axis_name, pmap_trace, hard_size))\n+ try:\nyield\n+ finally:\ndynamic_axis_env.pop()\ndef unmapped_device_count(backend=None):\n"
}
] | Python | Apache License 2.0 | google/jax | add try/finally to pxla global state management |
260,646 | 28.08.2019 03:37:15 | 0 | 9d4fab5c8fc0cfaecc47133e8f4d1ee2a1a0f19a | Pass check_vjp, add VJP grad and Jac, use fun(y0, t, *args) syntax | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ode.py",
"new_path": "jax/experimental/ode.py",
"diff": "@@ -18,6 +18,8 @@ Integrate systems of ordinary differential equations (ODEs) using the JAX\nautograd/diff library and the Dormand-Prince method for adaptive integration\nstepsize calculation. Provides improved integration accuracy over fixed\nstepsize integration methods.\n+\n+Adjoint algorithm based on Appendix C of https://arxiv.org/pdf/1806.07366.pdf\n\"\"\"\nfrom __future__ import absolute_import\n@@ -198,28 +200,33 @@ def optimal_step_size(last_step,\nlast_step / factor,)\n-@functools.partial(jax.jit, static_argnums=(0, 1))\n-def odeint(ofunc, args, y0, t, rtol=1.4e-8, atol=1.4e-8):\n+@functools.partial(jax.jit, static_argnums=(0,))\n+def odeint(ofunc, y0, t, *args, **kwargs):\n\"\"\"Adaptive stepsize (Dormand-Prince) Runge-Kutta odeint implementation.\nArgs:\nofunc: Function to evaluate `yt = ofunc(y, t, *args)` that\nreturns the time derivative of `y`.\n- args: Additional arguments to `ofunc`.\ny0: initial value for the state.\nt: Timespan for `ofunc` evaluation like `np.linspace(0., 10., 101)`.\n- rtol: Relative local error tolerance for solver.\n- atol: Absolute local error tolerance for solver.\n+ *args: Additional arguments to `ofunc` beyond y0 and t.\n+ **kwargs: Two relevant keyword arguments:\n+ 'rtol': Relative local error tolerance for solver.\n+ 'atol': Absolute local error tolerance for solver.\n+\nReturns:\nIntegrated system values at each timepoint.\n\"\"\"\n+ rtol = kwargs.get('rtol', 1.4e-8)\n+ atol = kwargs.get('atol', 1.4e-8)\n+\n@functools.partial(jax.jit, static_argnums=(0,))\n- def _fori_body_fun(func, i, val, rtol=1.4e-8, atol=1.4e-8):\n+ def _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\ncur_y, cur_f, cur_t, dt, last_t, interp_coeff = jax.lax.while_loop(\nlambda x: x[2] < t[i],\n- functools.partial(_while_body_fun, func, rtol=rtol, atol=atol),\n+ functools.partial(_while_body_fun, func),\n(cur_y, cur_f, cur_t, dt, last_t, interp_coeff))\nrelative_output_time = (t[i] - last_t) / (cur_t - last_t)\n@@ -231,7 +238,7 @@ def odeint(ofunc, args, y0, t, rtol=1.4e-8, atol=1.4e-8):\nout_x))\n@functools.partial(jax.jit, static_argnums=(0,))\n- def _while_body_fun(func, x, atol=atol, rtol=rtol):\n+ def _while_body_fun(func, x):\n\"\"\"Internal while_loop body to determine interpolation coefficients.\"\"\"\ncur_y, cur_f, cur_t, dt, last_t, interp_coeff = x\nnext_t = cur_t + dt\n@@ -265,24 +272,33 @@ def odeint(ofunc, args, y0, t, rtol=1.4e-8, atol=1.4e-8):\ny0)))[-1]\n-def grad_odeint(ofunc, args):\n- \"\"\"Return a function that calculates `vjp(odeint(func(y, t, args))`.\n+def vjp_odeint(ofunc, y0, t, *args, **kwargs):\n+ \"\"\"Return a function that calculates `vjp(odeint(func(y, t, *args))`.\nArgs:\nofunc: Function `ydot = ofunc(y, t, *args)` to compute the time\nderivative of `y`.\n- args: Additional arguments to `ofunc`.\n+ y0: initial value for the state.\n+ t: Timespan for `ofunc` evaluation like `np.linspace(0., 10., 101)`.\n+ *args: Additional arguments to `ofunc` beyond y0 and t.\n+ **kwargs: Two relevant keyword arguments:\n+ 'rtol': Relative local error tolerance for solver.\n+ 'atol': Absolute local error tolerance for solver.\nReturns:\n- VJP function `vjp = vjp_all(g, yt, t)` where `yt = ofunc(y, t, *args)`\n+ VJP function `vjp = vjp_all(g)` where `yt = ofunc(y, t, *args)`\nand g is used for VJP calculation. To evaluate the gradient w/ the VJP,\n- supply `g = np.ones_like(yt)`.\n+ supply `g = np.ones_like(yt)`. To evaluate the reverse Jacobian do a vmap\n+ over the standard basis of yt.\n\"\"\"\n+ rtol = kwargs.get('rtol', 1.4e-8)\n+ atol = kwargs.get('atol', 1.4e-8)\n+\nflat_args, unravel_args = ravel_pytree(args)\nflat_func = lambda y, t, flat_args: ofunc(y, t, *unravel_args(flat_args))\n@jax.jit\n- def aug_dynamics(augmented_state, t):\n+ def aug_dynamics(augmented_state, t, flat_args):\n\"\"\"Original system augmented with vjp_y, vjp_t and vjp_args.\"\"\"\nstate_len = int(np.floor_divide(\naugmented_state.shape[0] - flat_args.shape[0] - 1, 2))\n@@ -291,7 +307,7 @@ def grad_odeint(ofunc, args):\ndy_dt, vjpfun = jax.vjp(flat_func, y, t, flat_args)\nreturn np.hstack([np.ravel(dy_dt), np.hstack(vjpfun(-adjoint))])\n- rev_aug_dynamics = lambda y, t: -aug_dynamics(y, -t)\n+ rev_aug_dynamics = lambda y, t, flat_args: -aug_dynamics(y, -t, flat_args)\n@jax.jit\ndef _fori_body_fun(i, val):\n@@ -301,13 +317,19 @@ def grad_odeint(ofunc, args):\nthis_t = rev_t[i]\nthis_tarray = rev_tarray[i, :]\nthis_gi = rev_gi[i, :]\n- this_gim1 = rev_gi[i-1, :]\n+ # this is g[i-1, :] when g has been reversed\n+ this_gim1 = rev_gi[i+1, :]\nstate_len = this_yt.shape[0]\nvjp_cur_t = np.dot(flat_func(this_yt, this_t, flat_args), this_gi)\nvjp_t0 = vjp_t0 - vjp_cur_t\n# Run augmented system backwards to the previous observation.\naug_y0 = np.hstack((this_yt, vjp_y, vjp_t0, vjp_args))\n- aug_ans = odeint(rev_aug_dynamics, (), aug_y0, this_tarray)\n+ aug_ans = odeint(rev_aug_dynamics,\n+ aug_y0,\n+ this_tarray,\n+ flat_args,\n+ rtol=rtol,\n+ atol=atol)\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@@ -316,19 +338,19 @@ def grad_odeint(ofunc, args):\n@jax.jit\ndef vjp_all(g, yt, t):\n- \"\"\"Calculate the VJP g * Jac(odeint(ofunc(yt, t, *args), t).\"\"\"\n- rev_yt = yt[-1:0:-1, :]\n- rev_t = t[-1:0:-1]\n+ \"\"\"Calculate the VJP g * Jac(odeint(ofunc, y0, t, *args)).\"\"\"\n+ rev_yt = yt[-1::-1, :]\n+ rev_t = t[-1::-1]\nrev_tarray = -np.array([t[-1:0:-1], t[-2::-1]]).T\n- rev_gi = g[-1:0:-1, :]\n+ rev_gi = g[-1::-1, :]\n- vjp_y = rev_gi[-1, :]\n+ vjp_y = g[-1, :]\nvjp_t0 = 0.\nvjp_args = np.zeros_like(flat_args)\ntime_vjp_list = np.zeros_like(t)\nresult = jax.lax.fori_loop(0,\n- rev_t.shape[0],\n+ rev_t.shape[0]-1,\n_fori_body_fun,\n(rev_yt,\nrev_t,\n@@ -341,13 +363,39 @@ def grad_odeint(ofunc, args):\ntime_vjp_list = jax.ops.index_update(result[-1], -1, result[-3])\nvjp_times = np.hstack(time_vjp_list)[::-1]\n- return None, result[-4], vjp_times, unravel_args(result[-2])\n- return jax.jit(vjp_all)\n+ return tuple([result[-4], vjp_times] + list(result[-2]))\n+\n+ primals_out = odeint(flat_func, y0, t, flat_args)\n+ vjp_fun = lambda g: vjp_all(g, primals_out, t)\n+\n+ return primals_out, vjp_fun\n+\n+\n+def my_odeint_grad(fun):\n+ \"\"\"Calculate the Jacobian of an odeint.\"\"\"\n+ @jax.jit\n+ def _gradfun(*args, **kwargs):\n+ ys, pullback = vjp_odeint(fun, *args, **kwargs)\n+ my_grad = pullback(np.ones_like(ys))\n+ return my_grad\n+ return _gradfun\n+\n+\n+def my_odeint_jacrev(fun):\n+ \"\"\"Calculate the Jacobian of an odeint.\"\"\"\n+ @jax.jit\n+ def _jacfun(*args, **kwargs):\n+ ys, pullback = vjp_odeint(fun, *args, **kwargs)\n+ my_jac = jax.vmap(pullback)(jax.api._std_basis(ys))\n+ my_jac = jax.api.tree_map(\n+ functools.partial(jax.api._unravel_array_into_pytree, ys, 0), my_jac)\n+ my_jac = jax.api.tree_transpose(\n+ jax.api.tree_structure(args), jax.api.tree_structure(ys), my_jac)\n+ return my_jac\n+ return _jacfun\n-def test_grad_odeint():\n- \"\"\"Compare numerical and exact differentiation of a simple odeint.\"\"\"\ndef nd(f, x, eps=0.0001):\nflat_x, unravel = ravel_pytree(x)\ndim = len(flat_x)\n@@ -358,24 +406,27 @@ def test_grad_odeint():\ng[i] = (f(unravel(flat_x + d)) - f(unravel(flat_x - d))) / (2.0 * eps)\nreturn g\n+\n+def test_grad_vjp_odeint():\n+ \"\"\"Compare numerical and exact differentiation of a simple odeint.\"\"\"\n+\ndef f(y, t, arg1, arg2):\nreturn -np.sqrt(t) - y + arg1 - np.mean((y + arg2)**2)\ndef onearg_odeint(args):\nreturn np.sum(\n- odeint(f, args[2], args[0], args[1], atol=1e-8, rtol=1e-8))\n+ odeint(f, *args, atol=1e-8, rtol=1e-8))\ndim = 10\nt0 = 0.1\nt1 = 0.2\ny0 = np.linspace(0.1, 0.9, dim)\n- fargs = (0.1, 0.2)\n+ arg1 = 0.1\n+ arg2 = 0.2\n+ wrap_args = (y0, np.array([t0, t1]), arg1, arg2)\n- numerical_grad = nd(onearg_odeint, (y0, np.array([t0, t1]), fargs))\n- ys = odeint(f, fargs, y0, np.array([t0, t1]), atol=1e-8, rtol=1e-8)\n- ode_vjp = grad_odeint(f, fargs)\n- g = np.ones_like(ys)\n- exact_grad, _ = ravel_pytree(ode_vjp(g, ys, np.array([t0, t1])))\n+ numerical_grad = nd(onearg_odeint, wrap_args)\n+ exact_grad, _ = ravel_pytree(my_odeint_grad(f)(*wrap_args))\nassert np.allclose(numerical_grad, exact_grad)\n@@ -403,7 +454,7 @@ def plot_demo():\ny0 = np.array([1.])\nfargs = (1.0, 0.0)\n- ys = odeint(f, fargs, y0, ts, atol=0.001, rtol=0.001)\n+ ys = odeint(f, y0, ts, *fargs, atol=0.001, rtol=0.001)\n# Set up figure.\nfig = plt.figure(figsize=(8, 6), facecolor='white')\n@@ -416,17 +467,29 @@ def plot_demo():\nplt.show()\n-def pend(y, t, b, c):\n+@jax.jit\n+def pend(y, t, arg1, arg2):\n\"\"\"Simple pendulum system for odeint testing.\"\"\"\ndel t\ntheta, omega = y\n- dydt = np.array([omega, -b*omega - c*np.sin(theta)])\n+ dydt = np.array([omega, -arg1*omega - arg2*np.sin(theta)])\nreturn dydt\n-def benchmark_odeint(fun, args, y0, tspace):\n+@jax.jit\n+def swoop(y, t, arg1, arg2):\n+ return np.array(y - np.sin(t) - np.cos(t) * arg1 + arg2)\n+\n+\n+@jax.jit\n+def decay(y, t, arg1, arg2):\n+ return -np.sqrt(t) - y + arg1 - np.mean((y + arg2)**2)\n+\n+\n+\n+def benchmark_odeint(fun, y0, tspace, *args):\n\"\"\"Time performance of JAX odeint method against scipy.integrate.odeint.\"\"\"\n- n_trials = 10\n+ n_trials = 5\nfor k in range(n_trials):\nstart = time.time()\nscipy_result = osp_integrate.odeint(fun, y0, tspace, args)\n@@ -435,10 +498,7 @@ def benchmark_odeint(fun, args, y0, tspace):\nk+1, n_trials, end-start))\nfor k in range(n_trials):\nstart = time.time()\n- jax_result = odeint(fun,\n- args,\n- np.asarray(y0),\n- np.asarray(tspace))\n+ jax_result = odeint(fun, np.array(y0), np.array(tspace), *args)\njax_result.block_until_ready()\nend = time.time()\nprint('JAX odeint elapsed time ({} of {}): {}'.format(\n@@ -451,12 +511,75 @@ def benchmark_odeint(fun, args, y0, tspace):\ndef pend_benchmark_odeint():\n_, _ = benchmark_odeint(pend,\n- (0.25, 9.8),\n(onp.pi - 0.1, 0.0),\n- onp.linspace(0., 10., 101))\n+ onp.linspace(0., 10., 101),\n+ 0.25,\n+ 9.8)\n-if __name__ == '__main__':\n+def test_odeint_grad():\n+ \"\"\"Test the gradient behavior of various ODE integrations.\"\"\"\n+ def _test_odeint_grad(func, *args):\n+ def onearg_odeint(fargs):\n+ return np.sum(odeint(func, *fargs))\n+\n+ numerical_grad = nd(onearg_odeint, args)\n+ exact_grad, _ = ravel_pytree(my_odeint_grad(func)(*args))\n+ assert np.allclose(numerical_grad, exact_grad)\n+\n+ ts = np.array((0.1, 0.2))\n+ y0 = np.linspace(0.1, 0.9, 10)\n+ big_y0 = np.linspace(1.1, 10.9, 10)\n+\n+ # check pend()\n+ for cond in (\n+ (np.array((onp.pi - 0.1, 0.0)), ts, 0.25, 0.98),\n+ (np.array((onp.pi * 0.1, 0.0)), ts, 0.1, 0.4),\n+ ):\n+ _test_odeint_grad(pend, *cond)\n+\n+ # check swoop\n+ for cond in (\n+ (y0, ts, 0.1, 0.2),\n+ (big_y0, ts, 0.1, 0.3),\n+ ):\n+ _test_odeint_grad(swoop, *cond)\n+\n+ # check decay\n+ for cond in (\n+ (y0, ts, 0.1, 0.2),\n+ (big_y0, ts, 0.1, 0.3),\n+ ):\n+ _test_odeint_grad(decay, *cond)\n+\n+\n+def test_odeint_vjp():\n+ \"\"\"Use check_vjp to check odeint VJP calculations.\"\"\"\n+\n+ # check pend()\n+ y = np.array([np.pi - 0.1, 0.0])\n+ t = np.linspace(0., 10., 11)\n+ b = 0.25\n+ c = 9.8\n+ wrap_args = (y, t, b, c)\n+ pend_odeint_wrap = lambda y, t, *args: odeint(pend, y, t, *args)\n+ pend_vjp_wrap = lambda *wrap_args: vjp_odeint(pend, *wrap_args)\n+ jax.test_util.check_vjp(pend_odeint_wrap, pend_vjp_wrap, wrap_args)\n+\n+ # check swoop()\n+ y = np.array([0.1])\n+ t = np.linspace(0., 10., 11)\n+ arg1 = 0.1\n+ arg2 = 0.2\n+ wrap_args = (y, t, arg1, arg2)\n+ swoop_odeint_wrap = lambda y, t, *args: odeint(swoop, y, t, *args)\n+ swoop_vjp_wrap = lambda *wrap_args: vjp_odeint(swoop, *wrap_args)\n+ jax.test_util.check_vjp(swoop_odeint_wrap, swoop_vjp_wrap, wrap_args)\n+\n+ # decay() check_vjp hangs!\n- test_grad_odeint()\n+if __name__ == '__main__':\n+\n+ test_odeint_grad()\n+ test_odeint_vjp()\n"
}
] | Python | Apache License 2.0 | google/jax | Pass check_vjp, add VJP grad and Jac, use fun(y0, t, *args) syntax |
260,268 | 29.08.2019 19:18:50 | 25,200 | 4ceebcf4065405e31ba978e134f941bb74bb7852 | with vectorize | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/vectorize.py",
"diff": "+from jax import grad, jit, vmap\n+import jax.numpy as jnp\n+import numpy as np\n+import re\n+\n+# See http://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html\n+_DIMENSION_NAME = r'\\w+'\n+_CORE_DIMENSION_LIST = '(?:{0:}(?:,{0:})*)?'.format(_DIMENSION_NAME)\n+_ARGUMENT = r'\\({}\\)'.format(_CORE_DIMENSION_LIST)\n+_ARGUMENT_LIST = '{0:}(?:,{0:})*'.format(_ARGUMENT)\n+_SIGNATURE = '^{0:}->{0:}$'.format(_ARGUMENT_LIST)\n+\n+\n+def _parse_gufunc_signature(signature):\n+ \"\"\"\n+ Parse string signatures for a generalized universal function.\n+\n+ Arguments\n+ ---------\n+ signature : string\n+ Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)``\n+ for ``np.matmul``.\n+\n+ Returns\n+ -------\n+ Tuple of input and output core dimensions parsed from the signature, each\n+ of the form List[Tuple[str, ...]].\n+ \"\"\"\n+ if not re.match(_SIGNATURE, signature):\n+ raise ValueError(\n+ 'not a valid gufunc signature: {}'.format(signature))\n+ return tuple([tuple(re.findall(_DIMENSION_NAME, arg))\n+ for arg in re.findall(_ARGUMENT, arg_list)]\n+ for arg_list in signature.split('->'))\n+\n+\n+\n+def _update_dim_sizes(dim_sizes, arg, core_dims):\n+ \"\"\"\n+ Incrementally check and update core dimension sizes for a single argument.\n+\n+ Arguments\n+ ---------\n+ dim_sizes : Dict[str, int]\n+ Sizes of existing core dimensions. Will be updated in-place.\n+ arg : ndarray\n+ Argument to examine.\n+ core_dims : Tuple[str, ...]\n+ Core dimensions for this argument.\n+ \"\"\"\n+ if not core_dims:\n+ return\n+\n+ num_core_dims = len(core_dims)\n+ if arg.ndim < num_core_dims:\n+ raise ValueError(\n+ '%d-dimensional argument does not have enough '\n+ 'dimensions for all core dimensions %r'\n+ % (arg.ndim, core_dims))\n+\n+ core_shape = arg.shape[-num_core_dims:]\n+ for dim, size in zip(core_dims, core_shape):\n+ if dim in dim_sizes:\n+ if size != dim_sizes[dim]:\n+ raise ValueError(\n+ 'inconsistent size for core dimension %r: %r vs %r'\n+ % (dim, size, dim_sizes[dim]))\n+ else:\n+ dim_sizes[dim] = size\n+\n+\n+def _parse_input_dimensions(args, input_core_dims):\n+ \"\"\"\n+ Parse broadcast and core dimensions for vectorize with a signature.\n+\n+ Arguments\n+ ---------\n+ args : Tuple[ndarray, ...]\n+ Tuple of input arguments to examine.\n+ input_core_dims : List[Tuple[str, ...]]\n+ List of core dimensions corresponding to each input.\n+\n+ Returns\n+ -------\n+ broadcast_shape : Tuple[int, ...]\n+ Common shape to broadcast all non-core dimensions to.\n+ dim_sizes : Dict[str, int]\n+ Common sizes for named core dimensions.\n+ \"\"\"\n+ broadcast_args = []\n+ dim_sizes = {}\n+ for arg, core_dims in zip(args, input_core_dims):\n+ _update_dim_sizes(dim_sizes, arg, core_dims)\n+ ndim = arg.ndim - len(core_dims)\n+ dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim])\n+ broadcast_args.append(dummy_array)\n+ broadcast_shape = np.lib.stride_tricks._broadcast_shape(*broadcast_args)\n+ return broadcast_shape, dim_sizes\n+\n+\n+def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims):\n+ \"\"\"Helper for calculating broadcast shapes with core dimensions.\"\"\"\n+ return [broadcast_shape + tuple(dim_sizes[dim] for dim in core_dims)\n+ for core_dims in list_of_core_dims]\n+\n+\n+# adapted from np.vectorize (again authored by shoyer@)\n+def broadcast_with_core_dims(args, input_core_dims, output_core_dims):\n+ if len(args) != len(input_core_dims):\n+ raise TypeError('wrong number of positional arguments: '\n+ 'expected %r, got %r'\n+ % (len(input_core_dims), len(args)))\n+\n+ broadcast_shape, dim_sizes = _parse_input_dimensions(\n+ args, input_core_dims)\n+ input_shapes = _calculate_shapes(broadcast_shape, dim_sizes,\n+ input_core_dims)\n+ args = [jnp.broadcast_to(arg, shape)\n+ for arg, shape in zip(args, input_shapes)]\n+ return args\n+\n+def verify_axis_is_supported(input_core_dims, output_core_dims):\n+ all_core_dims = set()\n+ for input_or_output_core_dims in [input_core_dims, output_core_dims]:\n+ for core_dims in input_or_output_core_dims:\n+ all_core_dims.update(core_dims)\n+ if len(core_dims) > 1:\n+ raise ValueError('only one gufuncs with one core dim support axis')\n+\n+\n+def reorder_inputs(args, axis, input_core_dims):\n+ return tuple(jnp.moveaxis(arg, axis, -1) if core_dims else arg\n+ for arg, core_dims in zip(args, input_core_dims))\n+\n+\n+def reorder_outputs(result, axis, output_core_dims):\n+ if not isinstance(result, tuple):\n+ result = (result,)\n+ result = tuple(jnp.moveaxis(res, -1, axis) if core_dims else res\n+ for res, core_dims in zip(result, output_core_dims))\n+ if len(result) == 1:\n+ (result,) = result\n+ return result\n+\n+import functools\n+\n+\n+def vectorize(signature):\n+ \"\"\"Vectorize a function using JAX.\"\"\"\n+ input_core_dims, output_core_dims = _parse_gufunc_signature(signature)\n+\n+ def decorator(func):\n+ @functools.wraps(func)\n+ def wrapper(*args, axis=None):\n+\n+ if axis is not None:\n+ verify_axis_is_supported(input_core_dims, output_core_dims)\n+ args = reorder_inputs(args, axis, input_core_dims)\n+\n+ broadcast_args = broadcast_with_core_dims(\n+ args, input_core_dims, output_core_dims)\n+ num_batch_dims = len(broadcast_args[0].shape) - len(input_core_dims[0])\n+\n+ vectorized_func = func\n+ for _ in range(num_batch_dims):\n+ vectorized_func = vmap(vectorized_func)\n+ result = vectorized_func(*broadcast_args)\n+\n+ if axis is not None:\n+ result = reorder_outputs(result, axis, output_core_dims)\n+\n+ return result\n+ return wrapper\n+ return decorator\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/vectorize_test.py",
"diff": "+# Copyright 2019 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+\"\"\"Tests for Vectorize library.\"\"\"\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 absl.testing import parameterized\n+\n+import numpy as onp\n+\n+from jax import numpy as np\n+from jax import test_util as jtu\n+from jax import random\n+from jax.experimental.vectorize import vectorize\n+\n+from jax.config import config\n+config.parse_flags_with_absl()\n+\n+matmat = vectorize('(n,m),(m,k)->(n,k)')(np.dot)\n+matvec = vectorize('(n,m),(m)->(n)')(np.dot)\n+vecmat = vectorize('(m),(m,k)->(k)')(np.dot)\n+vecvec = vectorize('(m),(m)->()')(np.dot)\n+\n+@vectorize('(n)->()')\n+def magnitude(x):\n+ return np.dot(x, x)\n+\n+mean = vectorize('(n)->()')(np.mean)\n+\n+@vectorize('()->(n)')\n+def stack_plus_minus(x):\n+ return np.stack([x, -x])\n+\n+@vectorize('(n)->(),(n)')\n+def center(array):\n+ bias = np.mean(array)\n+ debiased = array - bias\n+ return bias, debiased\n+\n+\n+class VectorizeTest(jtu.JaxTestCase):\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_leftshape={}_rightshape={}\".format(left_shape, right_shape),\n+ \"left_shape\": left_shape, \"right_shape\": right_shape, \"result_shape\": result_shape}\n+ for left_shape, right_shape, result_shape in [\n+ ((2, 3), (3, 4), (2, 4)),\n+ ((2, 3), (1, 3, 4), (1, 2, 4)),\n+ ((5, 2, 3), (1, 3, 4), (5, 2, 4)),\n+ ((6, 5, 2, 3), (3, 4), (6, 5, 2, 4)),\n+ ]))\n+ def test_matmat(self, left_shape, right_shape, result_shape):\n+ self.assertEqual(matmat(np.zeros(left_shape),\n+ np.zeros(right_shape).shape, result_shape))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_leftshape={}_rightshape={}\".format(left_shape, right_shape),\n+ \"left_shape\": left_shape, \"right_shape\": right_shape, \"result_shape\": result_shape}\n+ for left_shape, right_shape, result_shape in [\n+ ((2, 3), (3,), (2,)),\n+ ((2, 3), (1, 3), (1, 2)),\n+ ((4, 2, 3), (1, 3), (4, 2)),\n+ ((5, 4, 2, 3), (1, 3), (5, 4, 2)),\n+ ]))\n+ def test_matvec(self, left_shape, right_shape, result_shape):\n+ self.assertEqual(matvec(np.zeros(left_shape),\n+ np.zeros(right_shape).shape, result_shape))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_leftshape={}_rightshape={}\".format(left_shape, right_shape),\n+ \"left_shape\": left_shape, \"right_shape\": right_shape, \"result_shape\": result_shape}\n+ for left_shape, right_shape, result_shape in [\n+ ((3,), (3,), ()),\n+ ((2, 3), (3,), (2,)),\n+ ((4, 2, 3), (3,), (4, 2)),\n+ ]))\n+ def test_vecvec(self, left_shape, right_shape, result_shape):\n+ self.assertEqual(vecvec(np.zeros(left_shape),\n+ np.zeros(right_shape).shape, result_shape))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}\".format(shape),\n+ \"shape\": shape, \"result_shape\": result_shape}\n+ for shape, result_shape in [\n+ ((3,), ()),\n+ ((2, 3,), (2,)),\n+ ((1, 2, 3,), (1, 2)),\n+ ]))\n+ def test_magnitude(self, shape, result_shape):\n+ size = 1\n+ for x in shape:\n+ size *= x\n+ self.assertEqual(magnitude(np.arange(size).reshape(shape)).shape, result_shape)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}\".format(shape),\n+ \"shape\": shape, \"result_shape\": result_shape}\n+ for shape, result_shape in [\n+ ((3,), ()),\n+ ((2, 3), (2,)),\n+ ((1, 2, 3, 4), (1, 2, 3)),\n+ ]))\n+ def test_mean(self, shape, result_shape):\n+ self.assertEqual(mean(np.zeros(shape)).shape, result_shape)\n+\n+ def test_mean_axis(self):\n+ self.assertEqual(mean(np.zeros((2, 3)), axis=0).shape, (3,))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}\".format(shape),\n+ \"shape\": shape, \"result_shape\": result_shape}\n+ for shape, result_shape in [\n+ ((), (2,)),\n+ ((3,), (3,2,)),\n+ ]))\n+ def test_stack_plus_minus(self, shape, result_shape):\n+ self.assertEqual(stack_plus_minus(np.zeros(shape)).shape, result_shape)\n+\n+ def test_center(self, shape, result_shapes):\n+ b, a = center(np.arange(3))\n+ self.assertEqual(a.shape, (3,))\n+ self.assertEqual(b.shape, ())\n+ self.assertEqual(np.mean(a), b)\n+\n+ X = np.arange(12).reshape((3, 4))\n+ b, a = center(X, axis=1)\n+ self.assertEqual(a.shape, (3, 4))\n+ self.assertEqual(b.shape, (3,))\n+ self.assertEqual(np.mean(a, axis=1), b)\n+\n+ b, a = center(X, axis=0)\n+ self.assertEqual(a.shape, (3, 4))\n+ self.assertEqual(b.shape, (4,))\n+ self.assertEqual(np.mean(a, axis=0), b)\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | with vectorize |
260,314 | 29.08.2019 22:28:03 | 14,400 | 92d85a8962c8582f06f207802ef86285bf103e83 | fix cond batching rule issues | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -38,6 +38,7 @@ from jax.interpreters import xla\nfrom jax.interpreters import ad\nfrom jax.lib import xla_bridge as xb\nfrom jax.lib import xla_client\n+import jax.numpy as np\nfrom jax.util import (partial, unzip2, safe_map, safe_zip, split_list,\nsplit_dict, cache)\nfrom jax.tree_util import (tree_flatten, tree_unflatten, treedef_is_leaf,\n@@ -329,6 +330,10 @@ def _cond_translation_rule(c, axis_env, pred, *args, **kwargs):\nreturn c.Conditional(pred, true_op, true_c, false_op, false_c)\n+def _cond_pred_bcast_select(pred, x, y):\n+ pred = np.broadcast_to(np.reshape(pred, np.shape(pred) + (1,) * (np.ndim(x) - np.ndim(pred))), np.shape(x))\n+ return lax.select(pred, x, y)\n+\ndef _cond_batching_rule(args, dims, true_jaxpr, false_jaxpr, true_nconsts,\nfalse_nconsts):\n# TODO: maybe avoid moving arg axes to front if we're promoting to select?\n@@ -339,7 +344,7 @@ def _cond_batching_rule(args, dims, true_jaxpr, false_jaxpr, true_nconsts,\nargs, [1, true_nconsts, true_nops, false_nconsts])\nsize, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}\norig_bat = [d is not batching.not_mapped for d in dims]\n- (pred_bat,), t_bat, tconst_bat, f_bat, fconst_bat = split_list(\n+ (pred_bat,), tconst_bat, t_bat, fconst_bat, f_bat = split_list(\norig_bat, [1, true_nconsts, len(true_ops), false_nconsts])\n_, true_out_bat = batching.batch_jaxpr(true_jaxpr, size, tconst_bat + t_bat, False)\n@@ -356,7 +361,7 @@ def _cond_batching_rule(args, dims, true_jaxpr, false_jaxpr, true_nconsts,\nfor x, b in zip(true_out, out_bat)]\nfalse_out = [batching.broadcast(x, size, 0) if not b else x\nfor x, b in zip(false_out, out_bat)]\n- return [lax.select(pred, t, f)\n+ return [_cond_pred_bcast_select(pred, t, f)\nfor t, f in zip(true_out, false_out)], [0] * len(true_out)\nelse:\nout_dims = [0 if b else batching.not_mapped for b in out_bat]\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -30,6 +30,7 @@ import numpy.random as npr\nfrom jax import api\nfrom jax import core\nfrom jax import lax\n+from jax import random\nfrom jax import test_util as jtu\nfrom jax.util import unzip2\nfrom jax.lib import xla_bridge\n@@ -527,6 +528,21 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\nassert \"select\" in str(jaxpr)\n+ def testIssue1263(self):\n+ def f(rng, x):\n+ cond = random.bernoulli(rng)\n+ return lax.cond(cond, x, lambda x: x, np.abs(x) - 1., lambda x: x)\n+\n+ def body_fn(i, state):\n+ rng, x = state\n+ key, subkey = random.split(rng)\n+ return key, f(subkey, x)\n+\n+ def g(rng, x):\n+ return lax.fori_loop(0, 10, body_fn, (rng, x))\n+\n+ api.vmap(g)(random.split(random.PRNGKey(0), 3), np.ones((3, 4)))\n+\ndef testIssue514(self):\n# just check this doesn't crash\nlax.cond(True,\n"
}
] | Python | Apache License 2.0 | google/jax | fix cond batching rule issues |
260,314 | 30.08.2019 00:21:50 | 14,400 | 16bd27258d01aa28a55c1d3771a6b6b82aa8f475 | use lax instead of numpy to avoid circular import | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -38,7 +38,6 @@ from jax.interpreters import xla\nfrom jax.interpreters import ad\nfrom jax.lib import xla_bridge as xb\nfrom jax.lib import xla_client\n-import jax.numpy as np\nfrom jax.util import (partial, unzip2, safe_map, safe_zip, split_list,\nsplit_dict, cache)\nfrom jax.tree_util import (tree_flatten, tree_unflatten, treedef_is_leaf,\n@@ -331,8 +330,9 @@ def _cond_translation_rule(c, axis_env, pred, *args, **kwargs):\nreturn c.Conditional(pred, true_op, true_c, false_op, false_c)\ndef _cond_pred_bcast_select(pred, x, y):\n- pred = np.broadcast_to(np.reshape(pred, np.shape(pred) + (1,) * (np.ndim(x) - np.ndim(pred))), np.shape(x))\n- return lax.select(pred, x, y)\n+ promote_pred = lax.reshape(pred, onp.shape(pred) + (1,) * (x.ndim - pred.ndim))\n+ bcast_pred = lax.broadcast_in_dim(promote_pred, onp.shape(x), range(x.ndim))\n+ return lax.select(bcast_pred, x, y)\ndef _cond_batching_rule(args, dims, true_jaxpr, false_jaxpr, true_nconsts,\nfalse_nconsts):\n"
}
] | Python | Apache License 2.0 | google/jax | use lax instead of numpy to avoid circular import |
260,268 | 30.08.2019 20:36:54 | 0 | 54f28ed5bcf470aa472e869e82aca33708399b36 | fixing issues with tests | [
{
"change_type": "MODIFY",
"old_path": "tests/vectorize_test.py",
"new_path": "tests/vectorize_test.py",
"diff": "@@ -64,7 +64,7 @@ class VectorizeTest(jtu.JaxTestCase):\n]))\ndef test_matmat(self, left_shape, right_shape, result_shape):\nself.assertEqual(matmat(np.zeros(left_shape),\n- np.zeros(right_shape).shape, result_shape))\n+ np.zeros(right_shape)).shape, result_shape)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_leftshape={}_rightshape={}\".format(left_shape, right_shape),\n@@ -77,7 +77,7 @@ class VectorizeTest(jtu.JaxTestCase):\n]))\ndef test_matvec(self, left_shape, right_shape, result_shape):\nself.assertEqual(matvec(np.zeros(left_shape),\n- np.zeros(right_shape).shape, result_shape))\n+ np.zeros(right_shape)).shape, result_shape)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_leftshape={}_rightshape={}\".format(left_shape, right_shape),\n@@ -89,7 +89,7 @@ class VectorizeTest(jtu.JaxTestCase):\n]))\ndef test_vecvec(self, left_shape, right_shape, result_shape):\nself.assertEqual(vecvec(np.zeros(left_shape),\n- np.zeros(right_shape).shape, result_shape))\n+ np.zeros(right_shape)).shape, result_shape)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}\".format(shape),\n@@ -129,22 +129,22 @@ class VectorizeTest(jtu.JaxTestCase):\ndef test_stack_plus_minus(self, shape, result_shape):\nself.assertEqual(stack_plus_minus(np.zeros(shape)).shape, result_shape)\n- def test_center(self, shape, result_shapes):\n+ def test_center(self):\nb, a = center(np.arange(3))\nself.assertEqual(a.shape, (3,))\nself.assertEqual(b.shape, ())\n- self.assertEqual(np.mean(a), b)\n+ self.assertAllClose(1.0, b, False)\nX = np.arange(12).reshape((3, 4))\nb, a = center(X, axis=1)\nself.assertEqual(a.shape, (3, 4))\nself.assertEqual(b.shape, (3,))\n- self.assertEqual(np.mean(a, axis=1), b)\n+ self.assertAllClose(np.mean(X, axis=1), b, True)\nb, a = center(X, axis=0)\nself.assertEqual(a.shape, (3, 4))\nself.assertEqual(b.shape, (4,))\n- self.assertEqual(np.mean(a, axis=0), b)\n+ self.assertAllClose(np.mean(X, axis=0), b, True)\nif __name__ == \"__main__\":\n"
}
] | Python | Apache License 2.0 | google/jax | fixing issues with tests |
260,268 | 30.08.2019 22:46:26 | 0 | e6854009a83ed83bcf21520c760a2f4df5ca8fac | Changed axis kwarg in wrapper for py2 compat. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/vectorize.py",
"new_path": "jax/experimental/vectorize.py",
"diff": "@@ -252,7 +252,8 @@ def vectorize(signature):\ndef decorator(func):\n@functools.wraps(func)\n- def wrapper(*args, axis=None):\n+ def wrapper(*args, **kwargs):\n+ axis = kwargs.get('axis') # for python2 compat.\nif axis is not None:\nverify_axis_is_supported(input_core_dims, output_core_dims)\n"
}
] | Python | Apache License 2.0 | google/jax | Changed axis kwarg in wrapper for py2 compat. |
260,677 | 31.08.2019 02:13:12 | -3,600 | ae2c39d081d29b6abe8eefff5c755f0f0abaad57 | Added custom jvp for np.linalg.det
For faster gradient computation for determinants, added closed-form expressing for Jacobian-vector product. Still needs a test. | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/linalg.py",
"new_path": "jax/numpy/linalg.py",
"diff": "@@ -86,9 +86,11 @@ def slogdet(a):\n@_wraps(onp.linalg.det)\n+@custom_transforms\ndef det(a):\nsign, logdet = slogdet(a)\nreturn sign * np.exp(logdet)\n+defjvp(det, lambda g, ans, x: np.trace(np.dot(g, np.linalg.inv(x)))*ans)\n@_wraps(onp.linalg.eig)\n"
}
] | Python | Apache License 2.0 | google/jax | Added custom jvp for np.linalg.det
For faster gradient computation for determinants, added closed-form expressing for Jacobian-vector product. Still needs a test. |
260,677 | 31.08.2019 03:18:24 | -3,600 | 1c264db3a35c92cf987bc588a37f6b9a0dbc1177 | Slightly cleaner implementation of jvp for det
Replaced np.dot/np.linalg.inv with a single np.linalg.solve | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/linalg.py",
"new_path": "jax/numpy/linalg.py",
"diff": "@@ -90,7 +90,7 @@ def slogdet(a):\ndef det(a):\nsign, logdet = slogdet(a)\nreturn sign * np.exp(logdet)\n-defjvp(det, lambda g, ans, x: np.trace(np.dot(g, np.linalg.inv(x)))*ans)\n+defjvp(det, lambda g, ans, x: np.trace(np.linalg.solve(x, g))*ans)\n@_wraps(onp.linalg.eig)\n"
}
] | Python | Apache License 2.0 | google/jax | Slightly cleaner implementation of jvp for det
Replaced np.dot/np.linalg.inv with a single np.linalg.solve |
260,335 | 29.08.2019 20:25:02 | 25,200 | 478832c944e03f9df12ab0428965878e07c255f8 | avoid Calls inside While/Cond
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -491,22 +491,21 @@ xla_pmap = partial(core.call_bind, xla_pmap_p)\nxla_pmap_p.def_custom_bind(xla_pmap)\nxla_pmap_p.def_impl(xla_pmap_impl)\n-def _xla_pmap_translation_rule(c, jaxpr, axis_env, env_nodes, in_nodes,\n- axis_name, axis_size, devices, backend=None):\n+def _pmap_translation_rule(c, jaxpr, axis_env, const_nodes, freevar_nodes,\n+ in_nodes, axis_name, axis_size, devices, backend=None):\n+ # We in-line here rather than generating a Call HLO as in the xla_call\n+ # translation rule just because the extra tuple stuff is a pain.\nif axis_env.devices is not None or (axis_env.names and devices is not None):\n- raise NotImplementedError(\n- \"Nested pmaps with devices argument not yet supported.\")\n+ raise ValueError(\"Nested pmaps with explicit devices argument.\")\nnew_env = xla.extend_axis_env(axis_env, axis_name, axis_size)\nin_nodes_sharded = list(map(partial(_xla_shard, c, new_env.sizes), in_nodes))\n- subc = xla.jaxpr_computation(jaxpr, backend, new_env, (),\n- tuple(map(c.GetShape, env_nodes)),\n- *map(c.GetShape, in_nodes_sharded))\n- sharded_result = c.Call(subc, env_nodes + in_nodes_sharded)\n- sharded_results = xla.xla_destructure(c, sharded_result)\n- unsharded_results = [_xla_unshard(c, xla.axis_groups(new_env, axis_name), r)\n- for r in sharded_results]\n- return c.Tuple(*unsharded_results)\n-xla.call_translations[xla_pmap_p] = _xla_pmap_translation_rule\n+ sharded_outs = xla.jaxpr_subcomp(c, jaxpr, backend, new_env, const_nodes,\n+ freevar_nodes, *in_nodes_sharded)\n+ outs = [_xla_unshard(c, xla.axis_groups(new_env, axis_name), r)\n+ for r in sharded_outs]\n+ return c.Tuple(*outs)\n+\n+xla.call_translations[xla_pmap_p] = _pmap_translation_rule\nad.primitive_transposes[xla_pmap_p] = partial(ad.map_transpose, xla_pmap_p)\npe.map_primitives.add(xla_pmap_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -39,6 +39,7 @@ from ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\nfrom . import partial_eval as pe\nfrom . import ad\n+import jaxlib\nFLAGS = flags.FLAGS\nflags.DEFINE_bool('jax_debug_nans',\n@@ -142,7 +143,7 @@ def xla_primitive_callable(prim, *abstract_args, **params):\ndef primitive_computation(prim, *xla_shapes, **params):\nbackend = params.get('backend', None)\nnew_params = {k: params[k] for k in params if k != 'backend'}\n- c = xb.make_computation_builder(\"primitive_computation\")\n+ c = xb.make_computation_builder(\"primitive_computation\") # TODO(name)\nplatform = xb.get_backend(backend).platform\nxla_args = map(c.ParameterWithShape, xla_shapes)\nif prim in backend_specific_translations[platform]:\n@@ -230,28 +231,18 @@ def eqn_literals(eqn):\nif type(v) is core.Literal:\nyield v.val\n-def jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *arg_shapes):\n- c, out_nodes = _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes,\n- *arg_shapes)\n+def jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes,\n+ *arg_shapes):\n+ c = xb.make_computation_builder(\"jaxpr_computation\") # TODO(mattjj): name\n+ _map(prefetch, it.chain(const_vals, jaxpr_literals(jaxpr)))\n+ consts = _map(c.Constant, const_vals)\n+ freevars = _map(c.ParameterWithShape, freevar_shapes)\n+ args = _map(c.ParameterWithShape, arg_shapes)\n+ out_nodes = jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, freevars, *args)\nreturn c.Build(c.Tuple(*out_nodes))\n-\n-def check_backend_params(params, outer_backend):\n- # For nested jits, the outer jit sets the backend on all inner jits unless\n- # an inner-jit also has a conflicting explicit backend specification.\n- inner_backend = params.get('backend', None)\n- if inner_backend and inner_backend != outer_backend:\n- msg = (\n- \"Outer-jit backend specification {} must match\"\n- \"explicit inner-jit backend specification {}.\")\n- raise ValueError(msg.format(outer_backend, inner_backend))\n- return {k: params[k] for k in params if k != 'backend'}\n-\n-\n-def _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *arg_shapes):\n- c = xb.make_computation_builder(\"jaxpr_computation\")\n+def jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, freevars, *args):\nplatform = xb.get_backend(backend).platform\n- _map(prefetch, it.chain(jaxpr_literals(jaxpr), const_vals))\ndef read(v):\nif type(v) is Literal:\n@@ -261,17 +252,14 @@ def _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *ar\ndef write(v, node):\nassert node is not None\n+ assert type(node) is jaxlib.xla_extension.XlaOp\nenv[v] = node\nenv = {}\nwrite(core.unitvar, c.Tuple())\n- if const_vals:\n- _map(write, jaxpr.constvars, map(c.Constant, const_vals))\n- _map(write, jaxpr.freevars, map(c.ParameterWithShape, freevar_shapes))\n- else:\n- all_freevars = it.chain(jaxpr.constvars, jaxpr.freevars)\n- _map(write, all_freevars, map(c.ParameterWithShape, freevar_shapes))\n- _map(write, jaxpr.invars, map(c.ParameterWithShape, arg_shapes))\n+ _map(write, jaxpr.constvars, consts)\n+ _map(write, jaxpr.freevars, freevars)\n+ _map(write, jaxpr.invars, args)\nfor eqn in jaxpr.eqns:\nin_nodes = list(map(read, eqn.invars))\nif eqn.primitive in backend_specific_translations[platform]:\n@@ -295,9 +283,11 @@ def _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *ar\nelif eqn.primitive in call_translations:\nnew_params = check_backend_params(eqn.params, backend)\n(subjaxpr, const_bindings, freevar_bindings), = eqn.bound_subjaxprs\n- env_nodes = list(map(read, const_bindings + freevar_bindings))\n+ const_nodes = _map(read, const_bindings)\n+ freevar_nodes = _map(read, freevar_bindings)\nrule = call_translations[eqn.primitive]\n- ans = rule(c, subjaxpr, axis_env, env_nodes, in_nodes, backend=backend, **new_params)\n+ ans = rule(c, subjaxpr, axis_env, const_nodes, freevar_nodes, in_nodes,\n+ backend=backend, **new_params)\nelse:\nmsg = \"XLA translation rule for primitive '{}' not found\"\nraise NotImplementedError(msg.format(eqn.primitive.name))\n@@ -305,12 +295,23 @@ def _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *ar\nc.GetShape(ans) # force xla to do shape error checking\nout_nodes = xla_destructure(c, ans) if eqn.primitive.multiple_results else [ans]\n_map(write, eqn.outvars, out_nodes)\n- return c, _map(read, jaxpr.outvars)\n+ return _map(read, jaxpr.outvars)\ndef xla_destructure(c, ans):\nnum_elements = len(c.GetShape(ans).tuple_shapes())\nreturn [c.GetTupleElement(ans, i) for i in range(num_elements)]\n+def check_backend_params(params, outer_backend):\n+ # For nested calls, the outermost call sets the backend for all inner calls;\n+ # it's an error if the inner call has a conflicting explicit backend spec.\n+ inner_backend = params.get('backend', None)\n+ if inner_backend and inner_backend != outer_backend:\n+ msg = (\n+ \"Outer-jit backend specification {} must match explicit inner-jit \"\n+ \"backend specification {}.\")\n+ raise ValueError(msg.format(outer_backend, inner_backend))\n+ return {k: params[k] for k in params if k != 'backend'}\n+\nclass AxisEnv(object):\ndef __init__(self, nreps=1, names=None, sizes=None, devices=None):\n@@ -418,12 +419,16 @@ xla_call = partial(core.call_bind, xla_call_p)\nxla_call_p.def_custom_bind(xla_call)\nxla_call_p.def_impl(_xla_call_impl)\n-def _xla_call_translation_rule(c, jaxpr, axis_env, env_nodes, in_nodes,\n- device_assignment=None, backend=None):\n+def _xla_call_translation_rule(c, jaxpr, axis_env, const_nodes, freevar_nodes,\n+ in_nodes, device_assignment=None, backend=None):\ndel device_assignment # Ignored.\n- subc = jaxpr_computation(jaxpr, backend, axis_env, (), _map(c.GetShape, env_nodes),\n- *map(c.GetShape, in_nodes))\n- return c.Call(subc, env_nodes + in_nodes)\n+ subc = xb.make_computation_builder(\"jaxpr_subcomputation\") # TODO(mattjj): name\n+ consts = [subc.ParameterWithShape(c.GetShape(n)) for n in const_nodes]\n+ freevars = [subc.ParameterWithShape(c.GetShape(n)) for n in freevar_nodes]\n+ args = [subc.ParameterWithShape(c.GetShape(n)) for n in in_nodes]\n+ out_nodes = jaxpr_subcomp(subc, jaxpr, backend, axis_env, consts, freevars, *args)\n+ subc = subc.Build(subc.Tuple(*out_nodes))\n+ return c.Call(subc, list(const_nodes) + list(freevar_nodes) + list(in_nodes))\nad.primitive_transposes[xla_call_p] = partial(ad.call_transpose, xla_call_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3298,8 +3298,11 @@ def _reduce_batch_rule(batched_args, batch_dims, computation, jaxpr, consts, dim\ndef _reduction_computation(c, jaxpr, backend, consts, init_value):\nshape = c.GetShape(init_value)\naxis_env = xla.AxisEnv() # no parallel primitives inside reductions\n- c, (out,) = xla._jaxpr_computation(jaxpr, backend, axis_env, consts, (), shape, shape)\n- return c.Build(out)\n+ subc = xla_bridge.make_computation_builder(\"reduction_computation\")\n+ consts = [subc.ParameterWithShape(const) for const in consts]\n+ args = [subc.ParameterWithShape(shape), subc.ParameterWithShape(shape)]\n+ out, = xla.jaxpr_subcomp(subc, jaxpr, backend, axis_env, consts, (), *args)\n+ return subc.Build(out)\nreduce_p = standard_reduction_primitive(_reduce_shape_rule, _input_dtype, 'reduce',\n_reduce_translation_rule)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -195,10 +195,8 @@ def _while_loop_translation_rule(c, axis_env, *args, **kwargs):\ncond_carry = cond_c.ParameterWithShape(c.GetShape(init_carry))\ncond_carry_elts = [cond_c.GetTupleElement(cond_carry, i) for i in range(len(args))]\nx, _, z = split_list(cond_carry_elts, [cond_nconsts, body_nconsts])\n- cond_outs = cond_c.Call(\n- xla.jaxpr_computation(cond_jaxpr.jaxpr, backend, axis_env, cond_jaxpr.literals, (),\n- *_map(cond_c.GetShape, x + z)), x + z)\n- pred = cond_c.GetTupleElement(cond_outs, 0)\n+ pred, = xla.jaxpr_subcomp(cond_c, cond_jaxpr.jaxpr, backend, axis_env,\n+ _map(cond_c.Constant, cond_jaxpr.literals), (), *(x + z))\nif batched:\nscalar = xla_client.Shape.array_shape(onp.dtype(onp.bool_), ())\nor_ = xla.primitive_computation(lax.or_p, scalar, scalar)\n@@ -209,18 +207,14 @@ def _while_loop_translation_rule(c, axis_env, *args, **kwargs):\nbody_carry = body_c.ParameterWithShape(c.GetShape(init_carry))\nbody_carry_elts = [body_c.GetTupleElement(body_carry, i) for i in range(len(args))]\nx, y, z = split_list(body_carry_elts, [cond_nconsts, body_nconsts])\n- body_out = body_c.Call(\n- xla.jaxpr_computation(body_jaxpr.jaxpr, backend, axis_env, body_jaxpr.literals, (),\n- *_map(body_c.GetShape, y + z)), y + z)\n- new_z = [body_c.GetTupleElement(body_out, i) for i in range(len(init_vals))]\n+ new_z = xla.jaxpr_subcomp(body_c, body_jaxpr.jaxpr, backend, axis_env,\n+ _map(body_c.Constant, body_jaxpr.literals), (), *(y + z))\nif batched:\n- body_cond_outs = body_c.Call(\n- xla.jaxpr_computation(cond_jaxpr.jaxpr, backend, axis_env, cond_jaxpr.literals, (),\n- *_map(body_c.GetShape, x + z)), x + z)\n- body_pred = body_c.GetTupleElement(body_cond_outs, 0)\n+ body_pred, = xla.jaxpr_subcomp(body_c, cond_jaxpr.jaxpr, backend, axis_env,\n+ _map(body_c.Constant, cond_jaxpr.literals), (), *(x + z))\nnew_z = _map(partial(_pred_bcast_select, body_c, body_pred), new_z, z)\nassert _map(body_c.GetShape, new_z) == _map(body_c.GetShape, z) # no broadcast\n- new_carry = body_c.Tuple(*(x + y + new_z))\n+ new_carry = body_c.Tuple(*itertools.chain(x, y, new_z))\nans = c.While(cond_c.Build(pred), body_c.Build(new_carry), init_carry)\nans_elts = [c.GetTupleElement(ans, i) for i in range(len(args))]\n@@ -317,9 +311,9 @@ def _cond_translation_rule(c, axis_env, pred, *args, **kwargs):\nc = xb.make_computation_builder(name)\nop = c.ParameterWithShape(op_shape)\nops = [c.GetTupleElement(op, i) for i in range(len(jaxpr.in_avals))]\n- out = c.Call(xla.jaxpr_computation(jaxpr.jaxpr, backend, axis_env, jaxpr.literals, (),\n- *_map(c.GetShape, ops)), ops)\n- return c.Build(out)\n+ outs = xla.jaxpr_subcomp(c, jaxpr.jaxpr, backend, axis_env,\n+ _map(c.Constant, jaxpr.literals), (), *ops)\n+ return c.Build(c.Tuple(*outs))\ntrue_op = c.Tuple(*(true_consts + true_ops))\ntrue_c = make_computation(\"true_comp\", true_jaxpr, c.GetShape(true_op))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -733,8 +733,8 @@ class PmapWithDevicesTest(jtu.JaxTestCase):\nreturn bar(x)\nwith self.assertRaisesRegex(\n- NotImplementedError,\n- \"Nested pmaps with devices argument not yet supported.\"):\n+ ValueError,\n+ \"Nested pmaps with explicit devices argument.\"):\nfoo(np.ones((xla_bridge.device_count(), 1)))\n# Devices specified in inner pmap\n@@ -746,8 +746,8 @@ class PmapWithDevicesTest(jtu.JaxTestCase):\nreturn bar(x)\nwith self.assertRaisesRegex(\n- NotImplementedError,\n- \"Nested pmaps with devices argument not yet supported.\"):\n+ ValueError,\n+ \"Nested pmaps with explicit devices argument.\"):\nfoo(np.ones((xla_bridge.device_count(), 1)))\ndef testJitInPmap(self):\n"
}
] | Python | Apache License 2.0 | google/jax | avoid Calls inside While/Cond
fixes #1267 |
260,335 | 29.08.2019 22:21:31 | 25,200 | 2815c55bb1bcc42bfc9fb28d8549100dd7b6cd2e | switch rolled/unrolled loops in prng hash | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -127,19 +127,54 @@ def threefry_2x32(keypair, count):\nonp.array([17, 29, 16, 24], dtype=onp.uint32)]\nks = [key1, key2, key1 ^ key2 ^ onp.uint32(0x1BD11BDA)]\n- def rotate_list(xs):\n- return xs[1:] + [xs[0]]\n+ # TODO(mattjj): see https://github.com/google/jax/issues/1267, as a hopefully\n+ # temporary workaround for the facts that (1) XLA:CPU compile time is too slow\n+ # with unrolled loops and (2) XLA:GPU execution time is too slow with rolled\n+ # loops, we switch on whether the default backend is CPU or GPU. If this kind\n+ # of switch ends up sticking around, we should take into account #1211 and put\n+ # the switch in the translation rule rather than here in the traceable.\n+ use_rolled_loops = xla_bridge.get_backend().platform == \"cpu\"\nx[0] = x[0] + ks[0]\nx[1] = x[1] + ks[1]\n+ if use_rolled_loops:\n+ def rotate_list(xs): return xs[1:] + xs[:1]\ndef step(i, state):\nx, ks, rotations = state\nfor r in rotations[0]:\nx = apply_round(x, r)\nnew_x = [x[0] + ks[0], x[1] + ks[1] + asarray(i + 1, dtype=onp.uint32)]\nreturn new_x, rotate_list(ks), rotate_list(rotations)\n- out = np.concatenate(lax.fori_loop(0, 5, step, (x, rotate_list(ks), rotations))[0])\n+ x, _, _ = lax.fori_loop(0, 5, step, (x, rotate_list(ks), rotations))\n+\n+ else:\n+ for r in rotations[0]:\n+ x = apply_round(x, r)\n+ x[0] = x[0] + ks[1]\n+ x[1] = x[1] + ks[2] + onp.uint32(1)\n+\n+ for r in rotations[1]:\n+ x = apply_round(x, r)\n+ x[0] = x[0] + ks[2]\n+ x[1] = x[1] + ks[0] + onp.uint32(2)\n+\n+ for r in rotations[0]:\n+ x = apply_round(x, r)\n+ x[0] = x[0] + ks[0]\n+ x[1] = x[1] + ks[1] + onp.uint32(3)\n+\n+ for r in rotations[1]:\n+ x = apply_round(x, r)\n+ x[0] = x[0] + ks[1]\n+ x[1] = x[1] + ks[2] + onp.uint32(4)\n+\n+ for r in rotations[0]:\n+ x = apply_round(x, r)\n+ x[0] = x[0] + ks[2]\n+ x[1] = x[1] + ks[0] + onp.uint32(5)\n+\n+ out = np.concatenate(x)\nassert out.dtype == onp.uint32\nreturn lax.reshape(out[:-1] if odd_size else out, count.shape)\n"
}
] | Python | Apache License 2.0 | google/jax | switch rolled/unrolled loops in prng hash |
260,335 | 31.08.2019 08:04:51 | 25,200 | c0627d81c34489e41b61616c5073afa0cfc6922e | remove jaxlib import (broke google3 pulldown) | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -39,7 +39,6 @@ from ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\nfrom . import partial_eval as pe\nfrom . import ad\n-import jaxlib\nFLAGS = flags.FLAGS\nflags.DEFINE_bool('jax_debug_nans',\n@@ -252,7 +251,6 @@ def jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, freevars, *args):\ndef write(v, node):\nassert node is not None\n- assert type(node) is jaxlib.xla_extension.XlaOp\nenv[v] = node\nenv = {}\n"
}
] | Python | Apache License 2.0 | google/jax | remove jaxlib import (broke google3 pulldown) |
260,335 | 31.08.2019 12:51:21 | 25,200 | f5c152b71b75424fbe181a8e0c54df6edcdfb71d | if we hit an XLA Build error, it's a JAX bug | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -162,9 +162,10 @@ def primitive_computation(prim, *xla_shapes, **params):\ntry:\nreturn c.Build()\nexcept RuntimeError as e:\n- # try for a better error message by using the abstract_eval checks\n- prim.abstract_eval(*map(_aval_from_xla_shape, shapes), **params)\n- raise e\n+ msg = (e.message + \"\\n\"\n+ \"This is a bug in JAX's shape-checking rules; please report it!\\n\"\n+ \"https://github.com/google/jax/issues\\n\")\n+ raise RuntimeError(msg)\ndef _execute_compiled_primitive(prim, compiled, backend, result_handler, *args):\ndevice_num, = compiled.DeviceOrdinals()\n"
}
] | Python | Apache License 2.0 | google/jax | if we hit an XLA Build error, it's a JAX bug |
260,335 | 31.08.2019 21:23:39 | 25,200 | 422585716635fde8ae1f5664a43b61245352a96f | add special value grad tests, sinh failing | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1399,6 +1399,18 @@ class LaxTest(jtu.JaxTestCase):\napi.jit(f)(1.) # doesn't crash\n+ def testReshapeWithUnusualShapes(self):\n+ ans = lax.reshape(onp.ones((3,), onp.float32), (lax.add(1, 2), 1))\n+ self.assertAllClose(ans, onp.ones((3, 1), onp.float32), check_dtypes=True)\n+\n+ jtu.check_raises_regexp(\n+ lambda: lax.reshape(onp.ones(3,), (onp.array([3, 1]),)), TypeError,\n+ \"Shapes must be 1D sequences of concrete values of integer type.*\")\n+\n+ jtu.check_raises_regexp(\n+ lambda: lax.reshape(onp.ones(3,), (1.5, 2.0)), TypeError,\n+ \"Shapes must be 1D sequences of concrete values of integer type.*\")\n+\nclass DeviceConstantTest(jtu.JaxTestCase):\ndef _CheckDeviceConstant(self, make_const, expected):\n@@ -1502,12 +1514,28 @@ LAX_GRAD_OPS = [\ndtypes=[onp.float64, onp.complex64]),\ngrad_test_spec(lax.log1p, nargs=1, order=2, rng=jtu.rand_positive(),\ndtypes=[onp.float64, onp.complex64]),\n+ grad_test_spec(lax.sinh, nargs=1, order=2, rng=jtu.rand_default(),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-5),\n+ grad_test_spec(lax.cosh, nargs=1, order=2, rng=jtu.rand_default(),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-5),\ngrad_test_spec(lax.tanh, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64], tol=1e-5),\n+ grad_test_spec(lax.asinh, nargs=1, order=2, rng=jtu.rand_positive(),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-5),\n+ grad_test_spec(lax.acosh, nargs=1, order=2, rng=jtu.rand_positive(),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-5),\n+ grad_test_spec(lax.atanh, nargs=1, order=2, rng=jtu.rand_uniform(-0.9, 0.9),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-5),\ngrad_test_spec(lax.sin, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\ngrad_test_spec(lax.cos, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n+ grad_test_spec(lax.tan, nargs=1, order=2, rng=jtu.rand_uniform(-1.3, 1.3),\n+ dtypes=[onp.float64, onp.complex64]),\n+ grad_test_spec(lax.asin, nargs=1, order=2, rng=jtu.rand_uniform(-1., 1.),\n+ dtypes=[onp.float64]),\n+ grad_test_spec(lax.acos, nargs=1, order=2, rng=jtu.rand_uniform(-1., 1.),\n+ dtypes=[onp.float64]),\n# TODO(proteneer): atan2 input is already a representation of a\n# complex number. Need to think harder about what this even means\n# if each input itself is a complex number.\n@@ -1556,6 +1584,26 @@ LAX_GRAD_OPS = [\n# dtypes=[onp.float64], name=\"MinSomeEqual\"),\n]\n+GradSpecialValuesTestSpec = collections.namedtuple(\n+ \"GradSpecialValuesTestSpec\", [\"op\", \"values\"])\n+\n+LAX_GRAD_SPECIAL_VALUE_TESTS = [\n+ GradSpecialValuesTestSpec(lax.sinh, [0.]),\n+ GradSpecialValuesTestSpec(lax.cosh, [0.]),\n+ GradSpecialValuesTestSpec(lax.tanh, [0., 1000.]),\n+ GradSpecialValuesTestSpec(lax.asinh, [0., 1000.]),\n+ GradSpecialValuesTestSpec(lax.acosh, [1000.]),\n+ GradSpecialValuesTestSpec(lax.atanh, [0.]),\n+ GradSpecialValuesTestSpec(lax.sin, [0., onp.pi, onp.pi/2., onp.pi/4.]),\n+ GradSpecialValuesTestSpec(lax.cos, [0., onp.pi, onp.pi/2., onp.pi/4.]),\n+ GradSpecialValuesTestSpec(lax.tan, [0.]),\n+ GradSpecialValuesTestSpec(lax.asin, [0.]),\n+ GradSpecialValuesTestSpec(lax.acos, [0.]),\n+ GradSpecialValuesTestSpec(lax.atan, [0., 1000.]),\n+ GradSpecialValuesTestSpec(lax.erf, [0., 10.]),\n+ GradSpecialValuesTestSpec(lax.erfc, [0., 10.]),\n+]\n+\ndef check_grads_bilinear(f, args, order,\nmodes=[\"fwd\", \"rev\"], atol=None, rtol=None):\n@@ -1581,13 +1629,21 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nfor dtype in rec.dtypes)\nfor rec in LAX_GRAD_OPS))\ndef testOpGrad(self, op, rng, shapes, dtype, order, tol):\n- if jtu.device_under_test() == \"tpu\":\n- if op is lax.pow:\n+ if jtu.device_under_test() == \"tpu\" and op is lax.pow:\nraise SkipTest(\"pow grad imprecise on tpu\")\ntol = 1e-1 if num_float_bits(dtype) == 32 else tol\nargs = tuple(rng(shape, dtype) for shape in shapes)\ncheck_grads(op, args, order, [\"fwd\", \"rev\"], tol, tol)\n+ @parameterized.named_parameters(itertools.chain.from_iterable(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_{}\".format(rec.op.__name__, special_value),\n+ \"op\": rec.op, \"special_value\": special_value}\n+ for special_value in rec.values)\n+ for rec in LAX_GRAD_SPECIAL_VALUE_TESTS))\n+ def testOpGradSpecialValue(self, op, special_value):\n+ check_grads(op, (special_value,), 2, [\"fwd\", \"rev\"])\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_from_dtype={}_to_dtype={}\".format(\njtu.dtype_str(from_dtype), jtu.dtype_str(to_dtype)),\n@@ -2242,17 +2298,6 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nexpected = onp.array(0.0)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- def testReshapeWithUnusualShapes(self):\n- ans = lax.reshape(onp.ones((3,), onp.float32), (lax.add(1, 2), 1))\n- self.assertAllClose(ans, onp.ones((3, 1), onp.float32), check_dtypes=True)\n-\n- jtu.check_raises_regexp(\n- lambda: lax.reshape(onp.ones(3,), (onp.array([3, 1]),)), TypeError,\n- \"Shapes must be 1D sequences of concrete values of integer type.*\")\n-\n- jtu.check_raises_regexp(\n- lambda: lax.reshape(onp.ones(3,), (1.5, 2.0)), TypeError,\n- \"Shapes must be 1D sequences of concrete values of integer type.*\")\ndef all_bdims(*shapes):\nbdims = (itertools.chain([None], range(len(shape) + 1)) for shape in shapes)\n"
}
] | Python | Apache License 2.0 | google/jax | add special value grad tests, sinh failing |
260,335 | 31.08.2019 22:08:03 | 25,200 | cac042c34a55ad8683828e1d24dabc2c5bb485ac | move asinh/acosh/atanh to lax_numpy.py only | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.lax.rst",
"new_path": "docs/jax.lax.rst",
"diff": "@@ -26,11 +26,8 @@ Operators\nabs\nadd\nacos\n- acosh\nasin\n- asinh\natan\n- atanh\natan2\nbatch_matmul\nbitcast_convert_type\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/__init__.py",
"new_path": "jax/lax/__init__.py",
"diff": "@@ -18,7 +18,8 @@ from .lax import (_reduce_sum, _reduce_max, _reduce_min, _reduce_or,\n_reduce_and, _reduce_window_sum, _reduce_window_max,\n_reduce_window_min, _reduce_window_prod, _float, _complex,\n_input_dtype, _const, _eq_meet, _safe_mul,\n- _broadcasting_select, _check_user_dtype_supported)\n+ _broadcasting_select, _check_user_dtype_supported,\n+ _one, _const)\nfrom .lax_control_flow import *\nfrom .lax_fft import *\nfrom .lax_parallel import *\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1377,41 +1377,6 @@ def cosh(x):\n# This formulation avoids overflow when e^x is inf but e^x/2 is not inf.\nreturn add(exp(add(log_half, x)), exp(sub(log_half, x)))\n-def asinh(x):\n- r\"\"\"Elementwise arc hyperbolic sine: :math:`\\mathrm{asinh}(x)`.\"\"\"\n- # asinh(x) = log(x + sqrt(x**2 + 1))\n- result = log(add(x, sqrt(add(mul(x, x), _const(x, 1)))))\n- if onp.issubdtype(_dtype(result), onp.complexfloating):\n- return result\n- a = abs(x)\n- sqrt_max_value = onp.sqrt(onp.finfo(_dtype(x)).max)\n- return select(lt(a, _const(a, sqrt_max_value)),\n- result,\n- mul(sign(x), add(log(a), _const(a, onp.log(2.)))))\n-\n-def acosh(x):\n- r\"\"\"Elementwise arc hyperbolic cosine: :math:`\\mathrm{acosh}(x)`.\"\"\"\n- # acosh(x) = log(x + sqrt((x + 1) * (x - 1))) if x < sqrt_max_value\n- # log(x) + log(2) otherwise\n- sqrt_max_value = onp.sqrt(onp.finfo(_dtype(x)).max)\n- result = log(add(x, mul(sqrt(add(x, _const(x, 1))),\n- sqrt(sub(x, _const(x, 1))))))\n- if onp.issubdtype(_dtype(result), onp.complexfloating):\n- return result\n- return select(\n- lt(x, _const(x, sqrt_max_value)),\n- result,\n- add(log(x), _const(x, onp.log(2.))))\n-\n-\n-def atanh(x):\n- r\"\"\"Elementwise arc hyperbolic tangent: :math:`\\mathrm{atanh}(x)`.\"\"\"\n- # atanh(x) = 0.5 * log((1 + x) / (1 - x))\n- result = mul(_const(x, 0.5), log(div(add(_const(x, 1), x),\n- sub(_const(x, 1), x))))\n- if onp.issubdtype(_dtype(result), onp.complexfloating):\n- return result\n- return select(le(abs(x), _one(x)), result, full_like(x, onp.nan))\n# Add some methods to ShapedArray that rely on lax primitives\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax_reference.py",
"new_path": "jax/lax_reference.py",
"diff": "@@ -57,8 +57,6 @@ acos = onp.arccos\natan = onp.arctan\nsinh = onp.sinh\ncosh = onp.cosh\n-asinh = onp.arcsinh\n-acosh = onp.arccosh\nlgamma = scipy.special.gammaln\ndigamma = scipy.special.digamma\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -41,7 +41,7 @@ import opt_einsum\nimport six\nfrom six.moves import builtins, xrange\n-from jax import jit, device_put\n+from jax import jit, device_put, custom_transforms, defjvp\nfrom .. import core\nfrom ..abstract_arrays import UnshapedArray, ShapedArray, ConcreteArray\nfrom ..config import flags\n@@ -327,9 +327,6 @@ arctan = _one_to_one_unop(onp.arctan, lax.atan, True)\nsinh = _one_to_one_unop(onp.sinh, lax.sinh, True)\ncosh = _one_to_one_unop(onp.cosh, lax.cosh, True)\ntanh = _one_to_one_unop(onp.tanh, lax.tanh, True)\n-arcsinh = _one_to_one_unop(onp.arcsinh, lax.asinh, True)\n-arccosh = _one_to_one_unop(onp.arccosh, lax.acosh, True)\n-arctanh = _one_to_one_unop(onp.arctanh, lax.atanh, True)\nsqrt = _one_to_one_unop(onp.sqrt, lax.sqrt, True)\n@@ -573,6 +570,47 @@ def sinc(x):\nlax._const(x, 1), lax.div(lax.sin(pi_x), pi_x))\n+@_wraps(onp.arcsinh)\n+@custom_transforms\n+def arcsinh(x):\n+ # asinh(x) = log(x + sqrt(x**2 + 1))\n+ x, = _promote_to_result_dtype(onp.arcsinh, x)\n+ one = lax._const(x, 1)\n+ result = lax.log(x + lax.sqrt(x * x + one))\n+ if onp.issubdtype(_dtype(result), onp.complexfloating):\n+ return result\n+ a = abs(x)\n+ sqrt_max_value = onp.sqrt(onp.finfo(_dtype(x)).max)\n+ log2 = lax._const(a, onp.log(2))\n+ return lax.select(a < sqrt_max_value, result, lax.sign(x) * (lax.log(a) + log2))\n+defjvp(arcsinh, lambda g, ans, x: g / lax.sqrt(lax._const(x, 1) + square(x)))\n+\n+\n+@_wraps(onp.arccosh)\n+def arccosh(x):\n+ # acosh(x) = log(x + sqrt((x + 1) * (x - 1))) if x < sqrt_max_value\n+ # log(x) + log(2) otherwise\n+ x, = _promote_to_result_dtype(onp.arccosh, x)\n+ one = lax._const(x, 1)\n+ result = lax.log(x + lax.sqrt((x + one) * (x - one)))\n+ if onp.issubdtype(_dtype(result), onp.complexfloating):\n+ return result\n+ sqrt_max_value = onp.sqrt(onp.finfo(_dtype(x)).max)\n+ log2 = lax._const(x, onp.log(2))\n+ return lax.select(x < sqrt_max_value, result, lax.log(x) + log2)\n+\n+\n+@_wraps(onp.arctanh)\n+def arctanh(x):\n+ # atanh(x) = 0.5 * log((1 + x) / (1 - x))\n+ x, = _promote_to_result_dtype(onp.arctanh, x)\n+ one = lax._const(x, 1)\n+ result = lax._const(x, 0.5) * lax.log((one + x) / (one - x))\n+ if onp.issubdtype(_dtype(result), onp.complexfloating):\n+ return result\n+ return lax.select(abs(x) <= 1, result, lax.full_like(x, onp.nan))\n+\n+\n@_wraps(onp.transpose)\ndef transpose(x, axes=None):\naxes = onp.arange(ndim(x))[::-1] if axes is None else axes\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -36,6 +36,7 @@ from jax import api\nfrom jax import lax\nfrom jax import numpy as lnp\nfrom jax import test_util as jtu\n+from jax.test_util import check_grads\nfrom jax.lib import xla_bridge\nfrom jax.config import config\n@@ -1864,5 +1865,59 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nFLAGS.jax_numpy_rank_promotion = prev_flag\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+\n+GradTestSpec = collections.namedtuple(\n+ \"GradTestSpec\", [\"op\", \"nargs\", \"order\", \"rng\", \"dtypes\", \"name\", \"tol\"])\n+def grad_test_spec(op, nargs, order, rng, dtypes, name=None, tol=None):\n+ return GradTestSpec(op, nargs, order, rng, dtypes, name or op.__name__, tol)\n+\n+GRAD_TEST_RECORDS = [\n+ grad_test_spec(lnp.arcsinh, nargs=1, order=2, rng=jtu.rand_positive(),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-4),\n+ grad_test_spec(lnp.arccosh, nargs=1, order=2, rng=jtu.rand_positive(),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-4),\n+ grad_test_spec(lnp.arctanh, nargs=1, order=2, rng=jtu.rand_uniform(-0.9, 0.9),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-4),\n+]\n+\n+GradSpecialValuesTestSpec = collections.namedtuple(\n+ \"GradSpecialValuesTestSpec\", [\"op\", \"values\"])\n+\n+GRAD_SPECIAL_VALUE_TEST_RECORDS = [\n+ GradSpecialValuesTestSpec(lnp.arcsinh, [0., 1000.]),\n+ GradSpecialValuesTestSpec(lnp.arccosh, [1000.]),\n+ GradSpecialValuesTestSpec(lnp.arctanh, [0.]),\n+]\n+\n+def num_float_bits(dtype):\n+ return onp.finfo(xla_bridge.canonicalize_dtype(dtype)).bits\n+\n+class NumpyGradTests(jtu.JaxTestCase):\n+ @parameterized.named_parameters(itertools.chain.from_iterable(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": jtu.format_test_name_suffix(\n+ rec.name, shapes, itertools.repeat(dtype)),\n+ \"op\": rec.op, \"rng\": rec.rng, \"shapes\": shapes, \"dtype\": dtype,\n+ \"order\": rec.order, \"tol\": rec.tol}\n+ for shapes in CombosWithReplacement(nonempty_shapes, rec.nargs)\n+ for dtype in rec.dtypes)\n+ for rec in GRAD_TEST_RECORDS))\n+ def testOpGrad(self, op, rng, shapes, dtype, order, tol):\n+ tol = 1e-1 if num_float_bits(dtype) == 32 else tol\n+ args = tuple(rng(shape, dtype) for shape in shapes)\n+ check_grads(op, args, order, [\"fwd\", \"rev\"], tol, tol)\n+\n+ @parameterized.named_parameters(itertools.chain.from_iterable(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_{}\".format(rec.op.__name__, special_value),\n+ \"op\": rec.op, \"special_value\": special_value}\n+ for special_value in rec.values)\n+ for rec in GRAD_SPECIAL_VALUE_TEST_RECORDS))\n+ def testOpGradSpecialValue(self, op, special_value):\n+ check_grads(op, (special_value,), 2, [\"fwd\", \"rev\"])\n+\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -98,8 +98,6 @@ LAX_OPS = [\nop_record(lax.atan, 1, float_dtypes, jtu.rand_small()),\nop_record(lax.sinh, 1, float_dtypes + complex_dtypes, jtu.rand_default()),\nop_record(lax.cosh, 1, float_dtypes + complex_dtypes, jtu.rand_default()),\n- op_record(lax.asinh, 1, float_dtypes + complex_dtypes, jtu.rand_positive()),\n- op_record(lax.acosh, 1, float_dtypes + complex_dtypes, jtu.rand_positive()),\nop_record(lax.lgamma, 1, float_dtypes, jtu.rand_positive()),\nop_record(lax.digamma, 1, float_dtypes, jtu.rand_positive()),\n@@ -1520,22 +1518,16 @@ LAX_GRAD_OPS = [\ndtypes=[onp.float64, onp.complex64], tol=1e-5),\ngrad_test_spec(lax.tanh, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64], tol=1e-5),\n- grad_test_spec(lax.asinh, nargs=1, order=2, rng=jtu.rand_positive(),\n- dtypes=[onp.float64, onp.complex64], tol=1e-5),\n- grad_test_spec(lax.acosh, nargs=1, order=2, rng=jtu.rand_positive(),\n- dtypes=[onp.float64, onp.complex64], tol=1e-5),\n- grad_test_spec(lax.atanh, nargs=1, order=2, rng=jtu.rand_uniform(-0.9, 0.9),\n- dtypes=[onp.float64, onp.complex64], tol=1e-5),\ngrad_test_spec(lax.sin, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\ngrad_test_spec(lax.cos, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\ngrad_test_spec(lax.tan, nargs=1, order=2, rng=jtu.rand_uniform(-1.3, 1.3),\n- dtypes=[onp.float64, onp.complex64]),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-3),\ngrad_test_spec(lax.asin, nargs=1, order=2, rng=jtu.rand_uniform(-1., 1.),\n- dtypes=[onp.float64]),\n+ dtypes=[onp.float64], tol=1e-3),\ngrad_test_spec(lax.acos, nargs=1, order=2, rng=jtu.rand_uniform(-1., 1.),\n- dtypes=[onp.float64]),\n+ dtypes=[onp.float64], tol=1e-3),\n# TODO(proteneer): atan2 input is already a representation of a\n# complex number. Need to think harder about what this even means\n# if each input itself is a complex number.\n@@ -1591,9 +1583,6 @@ LAX_GRAD_SPECIAL_VALUE_TESTS = [\nGradSpecialValuesTestSpec(lax.sinh, [0.]),\nGradSpecialValuesTestSpec(lax.cosh, [0.]),\nGradSpecialValuesTestSpec(lax.tanh, [0., 1000.]),\n- GradSpecialValuesTestSpec(lax.asinh, [0., 1000.]),\n- GradSpecialValuesTestSpec(lax.acosh, [1000.]),\n- GradSpecialValuesTestSpec(lax.atanh, [0.]),\nGradSpecialValuesTestSpec(lax.sin, [0., onp.pi, onp.pi/2., onp.pi/4.]),\nGradSpecialValuesTestSpec(lax.cos, [0., onp.pi, onp.pi/2., onp.pi/4.]),\nGradSpecialValuesTestSpec(lax.tan, [0.]),\n"
}
] | Python | Apache License 2.0 | google/jax | move asinh/acosh/atanh to lax_numpy.py only |
260,335 | 02.09.2019 07:25:06 | 25,200 | c760b05f9bffa3b6b79beaa54d6848fde2eee149 | update jaxlib version in readme
fixes
will update notebooks in | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -122,7 +122,7 @@ PYTHON_VERSION=cp37 # alternatives: cp27, cp35, cp36, cp37\nCUDA_VERSION=cuda92 # alternatives: cuda90, cuda92, cuda100\nPLATFORM=linux_x86_64 # alternatives: linux_x86_64\nBASE_URL='https://storage.googleapis.com/jax-releases'\n-pip install --upgrade $BASE_URL/$CUDA_VERSION/jaxlib-0.1.23-$PYTHON_VERSION-none-$PLATFORM.whl\n+pip install --upgrade $BASE_URL/$CUDA_VERSION/jaxlib-0.1.27-$PYTHON_VERSION-none-$PLATFORM.whl\npip install --upgrade jax # install jax\n```\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax_linalg.py",
"new_path": "jax/lax_linalg.py",
"diff": "@@ -134,12 +134,7 @@ def _nan_like(c, operand):\nnan = c.Constant(onp.array(onp.nan, dtype=dtype))\nreturn c.Broadcast(nan, shape.dimensions())\n-# TODO(phawkins): remove if-condition after increasing minimum Jaxlib version to\n-# 0.1.23.\n-if hasattr(lapack, \"potrf\"):\n_cpu_potrf = lapack.potrf\n-else:\n- _cpu_potrf = _unpack_tuple(lapack.jax_potrf, 2)\ndef cholesky_cpu_translation_rule(c, operand):\nshape = c.GetShape(operand)\n@@ -181,12 +176,7 @@ def eig_abstract_eval(operand):\nraise NotImplementedError\nreturn w, vl, vr\n-# TODO(phawkins): remove if-condition after increasing minimum Jaxlib version to\n-# 0.1.23.\n-if hasattr(lapack, \"geev\"):\n_cpu_geev = lapack.geev\n-else:\n- _cpu_geev = _unpack_tuple(lapack.jax_geev, 4)\ndef eig_cpu_translation_rule(c, operand):\nshape = c.GetShape(operand)\n@@ -294,19 +284,11 @@ eigh_p.def_abstract_eval(eigh_abstract_eval)\nxla.translations[eigh_p] = eigh_translation_rule\nad.primitive_jvps[eigh_p] = eigh_jvp_rule\n-# TODO(phawkins): remove if-condition after increasing minimum Jaxlib version to\n-# 0.1.23.\n-if hasattr(lapack, \"syevd\"):\n_cpu_syevd = lapack.syevd\n-else:\n- _cpu_syevd = _unpack_tuple(lapack.jax_syevd, 3)\nxla.backend_specific_translations['cpu'][eigh_p] = partial(\n_eigh_cpu_gpu_translation_rule, _cpu_syevd)\n-# TODO(phawkins): remove if-condition after increasing minimum Jaxlib version to\n-# 0.1.23.\n-if cusolver:\nxla.backend_specific_translations['gpu'][eigh_p] = partial(\n_eigh_cpu_gpu_translation_rule, cusolver.syevd)\nbatching.primitive_batchers[eigh_p] = eigh_batching_rule\n@@ -612,12 +594,7 @@ xla.translations[lu_p] = xla.lower_fun(_lu_python, instantiate=True)\nad.primitive_jvps[lu_p] = _lu_jvp_rule\nbatching.primitive_batchers[lu_p] = _lu_batching_rule\n-# TODO(phawkins): remove if-condition after increasing minimum Jaxlib version to\n-# 0.1.23.\n-if hasattr(lapack, \"getrf\"):\n_cpu_getrf = lapack.getrf\n-else:\n- _cpu_getrf = _unpack_tuple(lapack.jax_getrf, 3)\nxla.backend_specific_translations['cpu'][lu_p] = partial(\n_lu_cpu_gpu_translation_rule, _cpu_getrf)\n@@ -803,18 +780,10 @@ ad.primitive_jvps[svd_p] = svd_jvp_rule\nbatching.primitive_batchers[svd_p] = svd_batching_rule\nxla.translations[svd_p] = svd_translation_rule\n-# TODO(phawkins): remove if-condition after increasing minimum Jaxlib version to\n-# 0.1.23.\n-if hasattr(lapack, \"gesdd\"):\n_cpu_gesdd = lapack.gesdd\n-else:\n- _cpu_gesdd = _unpack_tuple(lapack.jax_gesdd, 4)\nxla.backend_specific_translations['cpu'][svd_p] = partial(\n_svd_cpu_gpu_translation_rule, _cpu_gesdd)\n-# TODO(phawkins): remove if-condition after increasing minimum Jaxlib version to\n-# 0.1.23.\n-if cusolver:\nxla.backend_specific_translations['gpu'][svd_p] = partial(\n_svd_cpu_gpu_translation_rule, cusolver.gesvd)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lib/__init__.py",
"new_path": "jax/lib/__init__.py",
"diff": "@@ -41,16 +41,5 @@ from jaxlib import xla_client\nfrom jaxlib import xrt\nfrom jaxlib import lapack\n-# TODO(phawkins): make the import unconditional when the minimum Jaxlib version\n-# has been increased to 0.1.23.\n-try:\nfrom jaxlib import pytree\n-except ImportError:\n- pytree = None\n-\n-# TODO(phawkins): make the import unconditional when the minimum Jaxlib version\n-# has been increased to 0.1.23.\n-try:\nfrom jaxlib import cusolver\n-except ImportError:\n- cusolver = None\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/tree_util.py",
"new_path": "jax/tree_util.py",
"diff": "@@ -46,10 +46,6 @@ from .lib import pytree\nfrom .util import unzip2, partial, safe_map\n-# TODO(phawkins): use the first case unconditionally when the minimum Jaxlib\n-# version has been increased to 0.1.23.\n-if pytree:\n-\ndef tree_map(f, tree):\n\"\"\"Map a function over a pytree to produce a new pytree.\n@@ -129,225 +125,6 @@ if pytree:\nregister_pytree_node = pytree.register_node\n-else:\n- def tree_map(f, tree):\n- \"\"\"Map a function over a pytree to produce a new pytree.\n-\n- Args:\n- f: function to be applied at each leaf.\n- tree: a pytree to be mapped over.\n-\n- Returns:\n- A new pytree with the same structure as `tree` but with the value at each\n- leaf given by `f(x)` where `x` is the value at the corresponding leaf in\n- `tree`.\n- \"\"\"\n- node_type = _get_node_type(tree)\n- if node_type:\n- children, node_spec = node_type.to_iterable(tree)\n- new_children = [tree_map(f, child) for child in children]\n- return node_type.from_iterable(node_spec, new_children)\n- else:\n- return f(tree)\n-\n- def tree_multimap(f, tree, *rest):\n- \"\"\"Map a multi-input function over pytree args to produce a new pytree.\n-\n- Args:\n- f: function that takes `1 + len(rest)` arguments, to be applied at the\n- corresponding leaves of the pytrees.\n- tree: a pytree to be mapped over, with each leaf providing the first\n- positional argument to `f`.\n- *rest: a tuple of pytrees, each with the same structure as `tree`.\n-\n- Returns:\n- A new pytree with the same structure as `tree` but with the value at each\n- leaf given by `f(x, *xs)` where `x` is the value at the corresponding leaf\n- in `tree` and `xs` is the tuple of values at corresponding leaves in `rest`.\n- \"\"\"\n- node_type = _get_node_type(tree)\n- if node_type:\n- children, aux_data = node_type.to_iterable(tree)\n- all_children = [children]\n- for other_tree in rest:\n- other_node_type = _get_node_type(other_tree)\n- if node_type != other_node_type:\n- raise TypeError('Mismatch: {} != {}'.format(other_node_type, node_type))\n- other_children, other_aux_data = node_type.to_iterable(other_tree)\n- if other_aux_data != aux_data:\n- raise TypeError('Mismatch: {} != {}'.format(other_aux_data, aux_data))\n- all_children.append(other_children)\n-\n- new_children = [tree_multimap(f, *xs) for xs in zip(*all_children)]\n- return node_type.from_iterable(aux_data, new_children)\n- else:\n- return f(tree, *rest)\n-\n- def _walk_pytree(f_node, f_leaf, tree):\n- node_type = _get_node_type(tree)\n- if node_type:\n- children, node_spec = node_type.to_iterable(tree)\n- proc_children, child_specs = unzip2([_walk_pytree(f_node, f_leaf, child)\n- for child in children])\n- tree_def = _PyTreeDef(node_type, node_spec, child_specs)\n- return f_node(proc_children), tree_def\n- else:\n- return f_leaf(tree), leaf\n-\n- def process_pytree(process_node, tree):\n- return _walk_pytree(process_node, lambda x: x, tree)\n-\n- def build_tree(treedef, xs):\n- if treedef is leaf:\n- return xs\n- else:\n- # We use 'iter' for clearer error messages\n- children = safe_map(build_tree, iter(treedef.children), iter(xs))\n- return treedef.node_type.from_iterable(treedef.node_data, children)\n-\n- def tree_leaves(tree):\n- \"\"\"Generator that iterates over all leaves of a pytree.\"\"\"\n- node_type = _get_node_type(tree)\n- if node_type:\n- children, _ = node_type.to_iterable(tree)\n- for child in children:\n- # TODO(mattjj,phawkins): use 'yield from' when PY2 is dropped\n- for leaf in tree_leaves(child):\n- yield leaf\n- else:\n- yield tree\n-\n- def tree_flatten(tree):\n- itr, treedef = _walk_pytree(it.chain.from_iterable, lambda x: (x,), tree)\n- return list(itr), treedef\n-\n- def _tree_unflatten(xs, treedef):\n- if treedef is leaf:\n- return next(xs)\n- else:\n- children = tuple(map(partial(_tree_unflatten, xs), treedef.children))\n- return treedef.node_type.from_iterable(treedef.node_data, children)\n-\n- def tree_unflatten(treedef, xs):\n- return _tree_unflatten(iter(xs), treedef)\n-\n- def tree_transpose(outer_treedef, inner_treedef, pytree_to_transpose):\n- flat, treedef = tree_flatten(pytree_to_transpose)\n- expected_treedef = _nested_treedef(inner_treedef, outer_treedef)\n- if treedef != expected_treedef:\n- raise TypeError(\"Mismatch\\n{}\\n != \\n{}\".format(treedef, expected_treedef))\n-\n- inner_size = _num_leaves(inner_treedef)\n- outer_size = _num_leaves(outer_treedef)\n- flat = iter(flat)\n- lol = [[next(flat) for _ in range(inner_size)] for __ in range(outer_size)]\n- transposed_lol = zip(*lol)\n- subtrees = map(partial(tree_unflatten, outer_treedef), transposed_lol)\n- return tree_unflatten(inner_treedef, subtrees)\n-\n- def _num_leaves(treedef):\n- return 1 if treedef is leaf else sum(map(_num_leaves, treedef.children))\n-\n- def _nested_treedef(inner, outer):\n- # just used in tree_transpose error checking\n- if outer is leaf:\n- return inner\n- else:\n- children = map(partial(_nested_treedef, inner), outer.children)\n- return _PyTreeDef(outer.node_type, outer.node_data, tuple(children))\n-\n- def tree_structure(tree):\n- _, spec = process_pytree(lambda _: None, tree)\n- return spec\n-\n-\n- class _PyTreeDef(object):\n- __slots__ = (\"node_type\", \"node_data\", \"children\")\n-\n- def __init__(self, node_type, node_data, children):\n- self.node_type = node_type\n- self.node_data = node_data\n- self.children = children\n-\n- def __repr__(self):\n- if self.node_data is None:\n- data_repr = \"\"\n- else:\n- data_repr = \"[{}]\".format(self.node_data)\n-\n- return \"PyTree({}{}, [{}])\".format(self.node_type.name, data_repr,\n- ','.join(map(repr, self.children)))\n-\n- def __hash__(self):\n- return hash((self.node_type, self.node_data, tuple(self.children)))\n-\n- def __eq__(self, other):\n- if other is leaf:\n- return False\n- else:\n- return (self.node_type == other.node_type and\n- self.node_data == other.node_data and\n- self.children == other.children)\n-\n- def __ne__(self, other):\n- return not self == other\n-\n-\n- class _PyLeaf(object):\n- __slots__ = ()\n-\n- def __repr__(self):\n- return '*'\n-\n- leaf = _PyLeaf()\n-\n- def treedef_is_leaf(treedef):\n- return treedef is leaf\n-\n- def treedef_tuple(treedefs):\n- return _PyTreeDef(node_types[tuple], None, tuple(treedefs))\n-\n- def treedef_children(treedef):\n- return treedef.children\n-\n- def dict_to_iterable(xs):\n- keys = tuple(sorted(xs.keys()))\n- return tuple(map(xs.get, keys)), keys\n-\n- class NodeType(object):\n- def __init__(self, name, to_iterable, from_iterable):\n- self.name = name\n- self.to_iterable = to_iterable\n- self.from_iterable = from_iterable\n-\n- def __repr__(self):\n- return self.name\n-\n- node_types = {}\n-\n- def register_pytree_node(py_type, to_iterable, from_iterable):\n- assert py_type not in node_types\n- node_types[py_type] = NodeType(str(py_type), to_iterable, from_iterable)\n-\n- register_pytree_node(tuple, lambda xs: (xs, None), lambda _, xs: tuple(xs))\n- register_pytree_node(list, lambda xs: (tuple(xs), None), lambda _, xs: list(xs))\n- register_pytree_node(dict, dict_to_iterable, lambda keys, xs: dict(zip(keys, xs)))\n-\n- # To handle namedtuples, we can't just use the standard table of node_types\n- # because every namedtuple creates its own type and thus would require its own\n- # entry in the table. Instead we use a heuristic check on the type itself to\n- # decide whether it's a namedtuple type, and if so treat it as a pytree node.\n- def _get_node_type(maybe_tree):\n- t = type(maybe_tree)\n- return node_types.get(t) or _namedtuple_node(t)\n-\n- def _namedtuple_node(t):\n- if issubclass(t, tuple) and hasattr(t, '_fields'):\n- return NamedtupleNode\n-\n- NamedtupleNode = NodeType('namedtuple',\n- lambda xs: (tuple(xs), type(xs)),\n- lambda t, xs: t(*xs))\ndef tree_reduce(f, tree):\n"
}
] | Python | Apache License 2.0 | google/jax | update jaxlib version in readme
fixes #1297
will update notebooks in #1260 |
260,335 | 02.09.2019 07:47:56 | 25,200 | a0095e346e847190f90cdb1107ed8ac84e6222b5 | reviewer comments: no 'install' text needed | [
{
"change_type": "MODIFY",
"old_path": "notebooks/Common_Gotchas_in_JAX.ipynb",
"new_path": "notebooks/Common_Gotchas_in_JAX.ipynb",
"diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"### Installs and Imports\"\n+ \"### Imports\"\n]\n},\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "notebooks/XLA_in_Python.ipynb",
"new_path": "notebooks/XLA_in_Python.ipynb",
"diff": "\"## Colab Setup and Imports\"\n]\n},\n- {\n- \"cell_type\": \"markdown\",\n- \"metadata\": {\n- \"colab_type\": \"text\",\n- \"id\": \"HMRkxnna8NCN\"\n- },\n- \"source\": [\n- \"First install jax and jaxlib to get its xla client:\"\n- ]\n- },\n{\n\"cell_type\": \"code\",\n\"metadata\": {\n"
},
{
"change_type": "MODIFY",
"old_path": "notebooks/gufuncs.ipynb",
"new_path": "notebooks/gufuncs.ipynb",
"diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"### Setup and imports\"\n+ \"### Imports\"\n]\n},\n{\n"
}
] | Python | Apache License 2.0 | google/jax | reviewer comments: no 'install' text needed |
260,335 | 02.09.2019 07:55:25 | 25,200 | c52027691b4651e8b43fd8147866f3ac95690cbd | jax.numpy.stack and concatenate work on array args
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1352,7 +1352,7 @@ def pad(array, pad_width, mode='constant', constant_values=0):\n@_wraps(onp.stack)\ndef stack(arrays, axis=0):\n- if not arrays:\n+ if not len(arrays):\nraise ValueError(\"Need at least one array to stack.\")\nshape0 = shape(arrays[0])\naxis = _canonicalize_axis(axis, len(shape0) + 1)\n@@ -1377,7 +1377,7 @@ def tile(a, reps):\n@_wraps(onp.concatenate)\ndef concatenate(arrays, axis=0):\n- if not arrays:\n+ if not len(arrays):\nraise ValueError(\"Need at least one array to concatenate.\")\nif ndim(arrays[0]) == 0:\nraise ValueError(\"Zero-dimensional arrays cannot be concatenated.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1864,6 +1864,18 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfinally:\nFLAGS.jax_numpy_rank_promotion = prev_flag\n+ def testStackArrayArgument(self):\n+ # tests https://github.com/google/jax/issues/1271\n+ @api.jit\n+ def foo(x):\n+ return lnp.stack(x)\n+ foo(onp.zeros(2)) # doesn't crash\n+\n+ @api.jit\n+ def foo(x):\n+ return lnp.concatenate(x)\n+ foo(onp.zeros((2, 2))) # doesn't crash\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 | jax.numpy.stack and concatenate work on array args
fixes #1271 |
260,646 | 30.08.2019 22:23:11 | 0 | 3427d2cb20abdc01b4398036285d89f2894eb6f1 | Add `build_odeint` for odeint VJP setup, plus a test | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ode.py",
"new_path": "jax/experimental/ode.py",
"diff": "@@ -35,6 +35,7 @@ from jax.flatten_util import ravel_pytree\nimport jax.lax\nimport jax.numpy as np\nimport jax.ops\n+from jax.test_util import check_vjp\nimport matplotlib.pyplot as plt\nimport numpy as onp\nimport scipy.integrate as osp_integrate\n@@ -372,6 +373,34 @@ def vjp_odeint(ofunc, y0, t, *args, **kwargs):\nreturn primals_out, vjp_fun\n+def build_odeint(ofunc, rtol=1.4e-8, atol=1.4e-8):\n+ \"\"\"Return `f(y0, t, args) = odeint(ofunc(y, t, *args), y0, t, args)`.\n+\n+ Given the function ofunc(y, t, *args), return the jitted function\n+ `f(y0, t, args) = odeint(ofunc(y, t, *args), y0, t, args)` with\n+ the VJP of `f` defined using `vjp_odeint`, where:\n+\n+ `y0` is the initial condition of the ODE integration,\n+ `t` is the time course of the integration, and\n+ `*args` are all other arguments to `ofunc`.\n+\n+ Args:\n+ ofunc: The function to be wrapped into an ODE integration.\n+ rtol: relative local error tolerance for solver.\n+ atol: absolute local error tolerance for solver.\n+\n+ Returns:\n+ `f(y0, t, args) = odeint(ofunc(y, t, *args), y0, t, args)`\n+ \"\"\"\n+ ct_odeint = jax.custom_transforms(\n+ lambda y0, t, *args: odeint(ofunc, y0, t, *args, rtol=rtol, atol=atol))\n+\n+ v = lambda y0, t, *args: vjp_odeint(ofunc, y0, t, *args, rtol=rtol, atol=atol)\n+ jax.defvjp_all(ct_odeint, v)\n+\n+ return jax.jit(ct_odeint)\n+\n+\ndef my_odeint_grad(fun):\n\"\"\"Calculate the Jacobian of an odeint.\"\"\"\n@jax.jit\n@@ -486,7 +515,6 @@ def decay(y, t, arg1, arg2):\nreturn -np.sqrt(t) - y + arg1 - np.mean((y + arg2)**2)\n-\ndef benchmark_odeint(fun, y0, tspace, *args):\n\"\"\"Time performance of JAX odeint method against scipy.integrate.odeint.\"\"\"\nn_trials = 5\n@@ -563,8 +591,8 @@ def test_odeint_vjp():\nc = 9.8\nwrap_args = (y, t, b, c)\npend_odeint_wrap = lambda y, t, *args: odeint(pend, y, t, *args)\n- pend_vjp_wrap = lambda *wrap_args: vjp_odeint(pend, *wrap_args)\n- jax.test_util.check_vjp(pend_odeint_wrap, pend_vjp_wrap, wrap_args)\n+ pend_vjp_wrap = lambda y, t, *args: vjp_odeint(pend, y, t, *args)\n+ check_vjp(pend_odeint_wrap, pend_vjp_wrap, wrap_args)\n# check swoop()\ny = np.array([0.1])\n@@ -573,12 +601,31 @@ def test_odeint_vjp():\narg2 = 0.2\nwrap_args = (y, t, arg1, arg2)\nswoop_odeint_wrap = lambda y, t, *args: odeint(swoop, y, t, *args)\n- swoop_vjp_wrap = lambda *wrap_args: vjp_odeint(swoop, *wrap_args)\n- jax.test_util.check_vjp(swoop_odeint_wrap, swoop_vjp_wrap, wrap_args)\n+ swoop_vjp_wrap = lambda y, t, *args: vjp_odeint(swoop, y, t, *args)\n+ check_vjp(swoop_odeint_wrap, swoop_vjp_wrap, wrap_args)\n# decay() check_vjp hangs!\n+def test_defvjp_all():\n+ \"\"\"Use build_odeint to check odeint VJP calculations.\"\"\"\n+ n_trials = 5\n+ swoop_build = build_odeint(swoop)\n+ jacswoop = jax.jit(jax.jacrev(swoop_build))\n+ y = np.array([0.1])\n+ t = np.linspace(0., 2., 11)\n+ arg1 = 0.1\n+ arg2 = 0.2\n+ wrap_args = (y, t, arg1, arg2)\n+ for k in range(n_trials):\n+ start = time.time()\n+ rslt = jacswoop(*wrap_args)\n+ rslt.block_until_ready()\n+ end = time.time()\n+ print('JAX jacrev elapsed time ({} of {}): {}'.format(\n+ k+1, n_trials, end-start))\n+\n+\nif __name__ == '__main__':\ntest_odeint_grad()\n"
}
] | Python | Apache License 2.0 | google/jax | Add `build_odeint` for odeint VJP setup, plus a test |
260,335 | 23.08.2019 10:28:27 | 25,200 | 5879dbc223609ef37427e89a6ba9bb5bc3206242 | trying out ideas | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "mask.py",
"diff": "+from functools import partial\n+import operator\n+\n+import numpy as onp\n+\n+from jax import core\n+from jax.core import Trace, Tracer\n+from jax.util import unzip2, prod\n+from jax import linear_util as lu\n+from jax.abstract_arrays import ShapedArray\n+from jax import lax\n+\n+\n+Var = str\n+\n+\n+def mask(fun, shape_env, in_vals, shape_exprs):\n+ with core.new_master(MaskTrace) as master:\n+ fun, out_shapes = mask_subtrace(fun, master, shape_env)\n+ out_vals = fun.call_wrapped(in_vals, shape_exprs)\n+ del master\n+ return out_vals, out_shapes()\n+\n+@lu.transformation_with_aux\n+def mask_subtrace(master, shape_env, in_vals, shape_exprs):\n+ trace = MaskTrace(master, core.cur_sublevel())\n+ in_tracers = map(partial(MaskTracer, trace, shape_env),\n+ in_vals, shape_exprs)\n+ outs = yield in_tracers, {}\n+ out_tracers = map(trace.full_raise, outs)\n+ out_vals, out_shapes = unzip2((t.val, t.shape_expr) for t in out_tracers)\n+ yield out_vals, out_shapes\n+\n+class Shape(object):\n+ def __init__(self, *shape):\n+ assert all(isinstance(s, (int, str)) for s in shape)\n+ self.shape = tuple(shape)\n+ def __iter__(self):\n+ return iter(self.shape)\n+ def __repr__(self):\n+ return 'Shape({})'.format(repr(self.shape))\n+ __str__ = __repr__\n+ def __eq__(self, other):\n+ return type(other) is Shape and self.shape == other.shape\n+\n+class MaskTracer(Tracer):\n+ __slots__ = [\"val\", \"shape_expr\", \"shape_env\"]\n+\n+ def __init__(self, trace, shape_env, val, shape_expr):\n+ self.trace = trace\n+ self.shape_env = shape_env\n+ self.val = val\n+ self.shape_expr = shape_expr\n+\n+ @property\n+ def aval(self):\n+ # TODO can avoid some blowups, also improve error messages\n+ if self.shape_env is not None:\n+ shape = [self.shape_env[d] if type(d) is Var else d\n+ for d in self.shape_expr]\n+ return ShapedArray(shape, self.val.dtype)\n+ else:\n+ return ShapedArray(self.val.shape, self.val.dtype)\n+\n+ def full_lower(self):\n+ if all(type(s) is int for s in self.shape_expr):\n+ return core.full_lower(self.val)\n+ else:\n+ return self\n+\n+class MaskTrace(Trace):\n+ def pure(self, val):\n+ return MaskTracer(self, None, val, Shape(*val.shape))\n+\n+ def lift(self, val):\n+ return MaskTracer(self, None, val, Shape(*val.shape))\n+\n+ def sublift(self, val):\n+ return MaskTracer(self, val.shape_env, val.val, val.shape_expr)\n+\n+ def process_primitive(self, primitive, tracers, params):\n+ assert not primitive.multiple_results\n+ shape_env = next(t.shape_env for t in tracers if t.shape_env is not None)\n+ vals, shape_exprs = unzip2((t.val, t.shape_expr) for t in tracers)\n+ rule = masking_rules[primitive]\n+ out, out_shape = rule(shape_env, vals, shape_exprs, **params)\n+ return MaskTracer(self, shape_env, out, out_shape)\n+\n+ def process_call(self, call_primitive, f, tracers, params):\n+ raise NotImplementedError # TODO\n+\n+masking_rules = {}\n+\n+\n+def reduce_sum_masking_rule(shape_env, vals, shape_exprs, axes, input_shape):\n+ val, = vals\n+ in_shape, = shape_exprs\n+ masks = [lax.broadcasted_iota(onp.int32, val.shape, i) < shape_env[d]\n+ for i, d in enumerate(in_shape) if type(d) is Var]\n+ mask = reduce(operator.and_, masks)\n+ masked_val = lax.select(mask, val, lax.zeros_like_array(val))\n+ out_val = lax.reduce_sum_p.bind(masked_val, axes=axes,\n+ input_shape=masked_val.shape)\n+ out_shape = Shape(*(d for i, d in enumerate(in_shape) if i not in axes))\n+ return out_val, out_shape\n+\n+masking_rules[lax.reduce_sum_p] = reduce_sum_masking_rule\n+\n+\n+###\n+\n+\n+def pad(fun, in_shapes, out_shapes):\n+ def wrapped_fun(args, shape_env):\n+ outs, out_shapes_ = mask(lu.wrap_init(fun), shape_env, args, in_shapes)\n+ assert tuple(out_shapes_) == tuple(out_shapes)\n+ return outs\n+ return wrapped_fun\n+\n+###\n+\n+import jax.numpy as np\n+from jax import vmap\n+\n+@partial(pad, in_shapes=[Shape('n')], out_shapes=[Shape()])\n+def padded_sum(x):\n+ return np.sum(x), # output shape ()\n+\n+print padded_sum([np.arange(5)], dict(n=3))\n+print vmap(padded_sum)([np.ones((5, 10))], dict(n=np.arange(5)))\n"
}
] | Python | Apache License 2.0 | google/jax | trying out ideas
Co-authored-by: Dougal Maclaurin <dougalm@google.com> |
260,335 | 27.08.2019 17:09:55 | 25,200 | f5ee804a6f679ac715ab37b93adb521c708c1fcc | fix bug in scan masking rule | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "@@ -133,13 +133,13 @@ def scan_masking_rule(shape_env, vals, shape_exprs, forward, length, jaxpr,\nconst_shapes, init_shapes, xs_shapes = split_list(shape_exprs, [num_consts, num_carry])\n_, y_avals = split_list(jaxpr.out_avals, [num_carry])\nout_shapes = _masked_scan_shape_rule(length, init_shapes, y_avals)\n- masked_jaxpr = _masked_scan_jaxpr(jaxpr, dynamic_length, num_consts, num_carry)\n+ masked_jaxpr = _masked_scan_jaxpr(jaxpr, num_consts, num_carry)\nconst_linear, init_linear, xs_linear = split_list(linear, [num_consts, num_carry])\nout_vals = lax.scan_p.bind(\n- *it.chain(consts, [0], init, xs),\n+ *it.chain([dynamic_length] + consts, [0], init, xs),\nforward=forward, length=max_length, jaxpr=masked_jaxpr,\n- num_consts=num_consts, num_carry=1 + num_carry,\n- linear=const_linear + [False] + init_linear + xs_linear)\n+ num_consts=1 + num_consts, num_carry=1 + num_carry,\n+ linear=[False] + const_linear + [False] + init_linear + xs_linear)\nreturn out_vals[1:], out_shapes\nmasking_rules[lax.scan_p] = scan_masking_rule\n@@ -147,26 +147,27 @@ def _masked_scan_shape_rule(length, carry_shapes, y_avals):\nys_shapes = [ShapeExpr(length, *y_aval.shape) for y_aval in y_avals]\nreturn carry_shapes + ys_shapes\n-def _masked_scan_jaxpr(jaxpr, dynamic_length, num_consts, num_carry):\n+def _masked_scan_jaxpr(jaxpr, num_consts, num_carry):\nfun = core.jaxpr_as_fun(jaxpr)\n@lu.wrap_init\ndef masked(*args):\n- consts, i_carry, xs = split_list(args, [num_consts, num_carry + 1])\n- i, carry = i_carry[0], i_carry[1:]\n- out = fun(*(carry + xs))\n+ [dynamic_length], consts, [i], carry, xs = split_list(\n+ args, [1, num_consts, 1, num_carry])\n+ out = fun(*(consts + carry + xs))\nnew_carry, ys = split_list(out, [num_carry])\nnew_carry = [lax.select(i < dynamic_length, new_c, c)\nfor new_c, c in zip(new_carry, carry)]\nreturn [i + 1] + new_carry + ys\n- i_aval = ShapedArray((), onp.int32)\n+ aval = ShapedArray((), onp.int32)\nconst_avals, carry_avals, x_avals = split_list(jaxpr.in_avals, [num_consts, num_carry])\n- return _make_typed_jaxpr(masked, const_avals + [i_aval] + carry_avals + x_avals)\n+ return _make_typed_jaxpr(masked, [aval] + const_avals + [aval] + carry_avals + x_avals)\ndef _make_typed_jaxpr(traceable, in_avals):\npvals = [pe.PartialVal((aval, core.unit)) for aval in in_avals]\njaxpr, pvals_out, consts = pe.trace_to_jaxpr(traceable, pvals, instantiate=True)\n+ assert not consts\nout_avals, _ = unzip2(pvals_out)\nreturn core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)\n@@ -216,6 +217,9 @@ def cumsum(x):\nprint cumsum([np.array([5, 2, 9, 1, 4])], dict(n=3))\nprint vmap(cumsum)([np.arange(6).reshape(2, 3)], dict(n=np.array([1, 2])))\n+# TODO separate shape rules (which get shape_env) from masking rules (which get\n+# dereferenced shapes, not shape variables), since they're fused together now\n+\n# notes!\n# - a shape variable is associated with a max size and a dynamic size. we carry\n"
}
] | Python | Apache License 2.0 | google/jax | fix bug in scan masking rule |
260,335 | 27.08.2019 17:32:21 | 25,200 | bd86d41abbbc5fafb9b06142fe2ff54268ed0e7c | add flattening, jit test | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "@@ -7,6 +7,7 @@ import numpy as onp\nfrom jax import core\nfrom jax.core import Trace, Tracer\nfrom jax.util import unzip2, prod, safe_map, safe_zip, split_list\n+from jax.api_util import tree_flatten, tree_unflatten, flatten_fun_nokwargs\nfrom jax import linear_util as lu\nfrom jax.abstract_arrays import ShapedArray\nfrom jax.interpreters import partial_eval as pe\n@@ -175,32 +176,38 @@ def _make_typed_jaxpr(traceable, in_avals):\n###\ndef pad(fun, in_shapes, out_shapes):\n+ in_shapes_flat, in_shapes_tree = tree_flatten(in_shapes)\n+ out_shapes_flat, out_shapes_tree = tree_flatten(out_shapes)\n+\ndef wrapped_fun(args, shape_env):\n# TODO check max sizes agree (i.e. padded / arg sizes agree) according to\n# shape vars\n- outs, out_shapes_ = mask(lu.wrap_init(fun), shape_env, args, in_shapes)\n- assert tuple(out_shapes_) == tuple(out_shapes)\n+ f = lu.wrap_init(fun)\n+ args_flat, in_tree = tree_flatten(args)\n+ assert in_tree == in_shapes_tree\n+ flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\n+ outs, out_shapes_ = mask(flat_fun, shape_env, args_flat, in_shapes_flat)\n+ assert out_shapes_flat == out_shapes\n# TODO could check max size is what we expect according to input max sizes\n- return outs\n+ return tree_unflatten(out_tree(), outs)\nreturn wrapped_fun\n###\nimport jax.numpy as np\n-from jax import vmap\n+from jax import vmap, jit\n+\n@partial(pad, in_shapes=[Shape('n')], out_shapes=[Shape()])\ndef padded_sum(x):\n- return np.sum(x), # output shape ()\n-\n+ return np.sum(x) # output shape ()\nprint padded_sum([np.arange(5)], dict(n=3))\nprint vmap(padded_sum)([np.ones((5, 10))], dict(n=np.arange(5)))\n@partial(pad, in_shapes=[Shape('n'), Shape('n')], out_shapes=[Shape('n')])\ndef addvecs(x, y):\n- return x + y,\n-\n+ return x + y\nprint addvecs([np.arange(5), np.arange(5)], dict(n=3))\n# this is an error because padded sizes must agree\n# print addvecs([np.arange(5), np.arange(6)], dict(n=3))\n@@ -209,16 +216,19 @@ print addvecs([np.arange(5), np.arange(5)], dict(n=3))\ndef cumsum_(arr):\nout, _ = lax.scan(lambda c, x: (c + x, ()), 0, arr)\nreturn out\n-\n@partial(pad, in_shapes=[Shape('n')], out_shapes=[Shape()])\ndef cumsum(x):\n- return cumsum_(x),\n-\n+ return cumsum_(x)\nprint cumsum([np.array([5, 2, 9, 1, 4])], dict(n=3))\nprint vmap(cumsum)([np.arange(6).reshape(2, 3)], dict(n=np.array([1, 2])))\n-# TODO separate shape rules (which get shape_env) from masking rules (which get\n-# dereferenced shapes, not shape variables), since they're fused together now\n+\n+@jit\n+def jit_cumsum(args, shape_env):\n+ print \"Python!\"\n+ return cumsum(args, shape_env)\n+print jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=3))\n+print jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=4))\n# notes!\n"
}
] | Python | Apache License 2.0 | google/jax | add flattening, jit test |
260,335 | 27.08.2019 18:25:29 | 25,200 | 9bd5d37aae18c890e5bdf3c818bca516913f6d1b | split shape rules and masking rules | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "@@ -42,6 +42,8 @@ class ShapeExpr(object):\nself.shape = tuple(shape)\ndef __iter__(self):\nreturn iter(self.shape)\n+ def __getitem__(self, idx):\n+ return list(self)[idx]\ndef __repr__(self):\nreturn 'ShapeExpr({})'.format(repr(self.shape))\n__str__ = __repr__\n@@ -64,8 +66,7 @@ class MaskTracer(Tracer):\ndef aval(self):\n# TODO can avoid some blowups, also improve error messages\nif self.shape_env is not None:\n- shape = [self.shape_env[d] if type(d) is Var else d\n- for d in self.shape_expr]\n+ shape = eval_shape_expr(self.shape_env, self.shape_expr)\nreturn ShapedArray(tuple(shape), self.val.dtype)\nelse:\nreturn ShapedArray(self.val.shape, self.val.dtype)\n@@ -89,8 +90,9 @@ class MaskTrace(Trace):\ndef process_primitive(self, primitive, tracers, params):\nshape_env = next(t.shape_env for t in tracers if t.shape_env is not None)\nvals, shape_exprs = unzip2((t.val, t.shape_expr) for t in tracers)\n- rule = masking_rules[primitive]\n- out, out_shape = rule(shape_env, vals, shape_exprs, **params)\n+ out_shape = shape_rules[primitive](shape_exprs, **params)\n+ logical_shapes = map(partial(eval_shape_expr, shape_env), shape_exprs)\n+ out = masking_rules[primitive](vals, logical_shapes, **params)\nif not primitive.multiple_results:\nreturn MaskTracer(self, shape_env, out, out_shape)\nelse:\n@@ -99,54 +101,70 @@ class MaskTrace(Trace):\ndef process_call(self, call_primitive, f, tracers, params):\nraise NotImplementedError # TODO\n+def eval_shape_expr(shape_env, shape_expr):\n+ return tuple(shape_env[d] if type(d) is Var else d for d in shape_expr)\n+\nmasking_rules = {}\n+shape_rules = {}\n+\n+def reduce_sum_shape_rule(shape_exprs, axes, input_shape):\n+ del input_shape # Unused.\n+ shape_expr, = shape_exprs\n+ return ShapeExpr(*(d for i, d in enumerate(shape_expr) if i not in axes))\n+shape_rules[lax.reduce_sum_p] = reduce_sum_shape_rule\n-def reduce_sum_masking_rule(shape_env, vals, shape_exprs, axes, input_shape):\n- val, = vals\n- in_shape, = shape_exprs\n- masks = [lax.broadcasted_iota(onp.int32, val.shape, i) < shape_env[d]\n- for i, d in enumerate(in_shape) if type(d) is Var]\n+def reduce_sum_masking_rule(padded_vals, logical_shapes, axes, input_shape):\n+ del input_shape # Unused.\n+ (padded_val,), (logical_shape,) = padded_vals, logical_shapes\n+ masks = [lax.broadcasted_iota(onp.int32, padded_val.shape, i) < d\n+ for i, d in enumerate(logical_shape)]\nmask = reduce(operator.and_, masks)\n- masked_val = lax.select(mask, val, lax.zeros_like_array(val))\n- out_val = lax.reduce_sum_p.bind(masked_val, axes=axes,\n- input_shape=masked_val.shape)\n- out_shape = ShapeExpr(*(d for i, d in enumerate(in_shape) if i not in axes))\n- return out_val, out_shape\n+ masked_val = lax.select(mask, padded_val, lax.zeros_like_array(padded_val))\n+ return lax.reduce_sum_p.bind(masked_val, axes=axes,\n+ input_shape=padded_val.shape)\nmasking_rules[lax.reduce_sum_p] = reduce_sum_masking_rule\n-def add_masking_rule(shape_env, vals, shape_exprs):\n- x, y = vals\n- x_shape, y_shape = shape_exprs\n- if x_shape == y_shape:\n- return x + y, x_shape\n- else:\n- raise ShapeError\n+\n+def add_shape_rule(shape_exprs):\n+ x_shape_expr, y_shape_expr = shape_exprs\n+ if not x_shape_expr == y_shape_expr: raise ShapeError\n+ return x_shape_expr\n+shape_rules[lax.add_p] = add_shape_rule\n+\n+def add_masking_rule(padded_vals, logical_shapes):\n+ del logical_shapes # Unused.\n+ padded_x, padded_y = padded_vals\n+ return padded_x + padded_y\nmasking_rules[lax.add_p] = add_masking_rule\n-def scan_masking_rule(shape_env, vals, shape_exprs, forward, length, jaxpr,\n- num_consts, num_carry, linear):\n- # TODO specialized for case where only leading extensive dimension is masked\n- # TODO assert xs_shapes[0] after deref are all length\n- dynamic_length = shape_env[length] if type(length) is Var else length\n- consts, init, xs = split_list(vals, [num_consts, num_carry])\n- max_length, = {x.shape[0] for x in xs}\n- const_shapes, init_shapes, xs_shapes = split_list(shape_exprs, [num_consts, num_carry])\n+\n+def scan_shape_rule(shape_exprs, forward, length, jaxpr, num_consts, num_carry,\n+ linear):\n+ const_shexprs, init_shexprs, xs_shexprs = split_list(shape_exprs, [num_consts, num_carry])\n+ if (any(any(type(d) is Var for d in shexpr) for shexpr in const_shexprs)\n+ or any(any(type(d) is Var for d in shexpr) for shexpr in init_shexprs)\n+ or any(any(type(d) is Var for d in shexpr[1:]) for shexpr in xs_shexprs)):\n+ raise NotImplementedError\n_, y_avals = split_list(jaxpr.out_avals, [num_carry])\n- out_shapes = _masked_scan_shape_rule(length, init_shapes, y_avals)\n+ ys_shapes = [ShapeExpr(length, *y_aval.shape) for y_aval in y_avals]\n+ return init_shexprs + ys_shapes\n+shape_rules[lax.scan_p] = scan_shape_rule\n+\n+def scan_masking_rule(padded_vals, logical_shapes, forward, length, jaxpr,\n+ num_consts, num_carry, linear):\nmasked_jaxpr = _masked_scan_jaxpr(jaxpr, num_consts, num_carry)\n+ consts, init, xs = split_list(padded_vals, [num_consts, num_carry])\n+ max_length, = {x.shape[0] for x in xs}\nconst_linear, init_linear, xs_linear = split_list(linear, [num_consts, num_carry])\nout_vals = lax.scan_p.bind(\n- *it.chain([dynamic_length] + consts, [0], init, xs),\n+ *it.chain([length] + consts, [0], init, xs),\nforward=forward, length=max_length, jaxpr=masked_jaxpr,\nnum_consts=1 + num_consts, num_carry=1 + num_carry,\nlinear=[False] + const_linear + [False] + init_linear + xs_linear)\n- return out_vals[1:], out_shapes\n+ return out_vals[1:]\nmasking_rules[lax.scan_p] = scan_masking_rule\n-def _masked_scan_shape_rule(length, carry_shapes, y_avals):\n- ys_shapes = [ShapeExpr(length, *y_aval.shape) for y_aval in y_avals]\n- return carry_shapes + ys_shapes\ndef _masked_scan_jaxpr(jaxpr, num_consts, num_carry):\nfun = core.jaxpr_as_fun(jaxpr)\n"
}
] | Python | Apache License 2.0 | google/jax | split shape rules and masking rules |
260,335 | 27.08.2019 21:43:56 | 25,200 | 75eb9b2ee46054bb5a7a2a578bfb36ed87c43d02 | add part of a dot masking rule | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "@@ -131,17 +131,46 @@ def reduce_sum_masking_rule(padded_vals, logical_shapes, axes, input_shape):\nmasking_rules[lax.reduce_sum_p] = reduce_sum_masking_rule\n-def add_shape_rule(shape_exprs):\n+def defbinop(prim):\n+ shape_rules[prim] = binop_shape_rule\n+ masking_rules[prim] = partial(binop_masking_rule, prim)\n+\n+def binop_shape_rule(shape_exprs):\nx_shape_expr, y_shape_expr = shape_exprs\nif not x_shape_expr == y_shape_expr: raise ShapeError\nreturn x_shape_expr\n-shape_rules[lax.add_p] = add_shape_rule\n-def add_masking_rule(padded_vals, logical_shapes):\n+def binop_masking_rule(prim, padded_vals, logical_shapes):\ndel logical_shapes # Unused.\npadded_x, padded_y = padded_vals\n- return padded_x + padded_y\n-masking_rules[lax.add_p] = add_masking_rule\n+ return prim.bind(padded_x, padded_y)\n+\n+defbinop(lax.add_p)\n+defbinop(lax.mul_p)\n+defbinop(lax.sub_p)\n+defbinop(lax.div_p)\n+defbinop(lax.pow_p)\n+\n+\n+def defvectorized(prim):\n+ shape_rules[prim] = vectorized_shape_rule\n+ masking_rules[prim] = partial(vectorized_masking_rule, prim)\n+\n+def vectorized_shape_rule(shape_exprs):\n+ shape_expr, = shape_exprs\n+ return shape_expr\n+\n+def vectorized_masking_rule(prim, padded_vals, logical_shapes):\n+ del logical_shapes # Unused.\n+ padded_val, = padded_vals\n+ return prim.bind(padded_val)\n+\n+defvectorized(lax.neg_p)\n+defvectorized(lax.sin_p)\n+defvectorized(lax.cos_p)\n+defvectorized(lax.exp_p)\n+defvectorized(lax.log_p)\n+defvectorized(lax.tanh_p)\ndef scan_shape_rule(shape_exprs, forward, length, jaxpr, num_consts, num_carry,\n@@ -195,6 +224,47 @@ def _make_typed_jaxpr(traceable, in_avals):\nreturn core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)\n+def dot_shape_rule(shape_exprs, precision):\n+ del precision # Unused.\n+ lhs_shape, rhs_shape = shape_exprs\n+ lhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)\n+\n+ # TODO error checks\n+ if lhs_ndim == rhs_ndim == 1:\n+ if not lhs_shape == rhs_shape: raise ShapeError\n+ return Shape()\n+ elif lhs_ndim == rhs_ndim == 2:\n+ if not lhs_shape[1] == rhs_shape[0]: raise ShapeError\n+ return Shape(lhs_shape[0], rhs_shape[1])\n+ elif rhs_ndim == 1:\n+ if not lhs_shape[1] == rhs_shape[0]: raise ShapeError\n+ return Shape(lhs_shape[0])\n+ else:\n+ if not lhs_shape[0] == rhs_shape[0]: raise ShapeError\n+ return Shape(rhs_shape[1])\n+shape_rules[lax.dot_p] = dot_shape_rule\n+\n+def dot_masking_rule(padded_vals, logical_shapes, precision):\n+ lhs, rhs = padded_vals\n+ lhs_shape, rhs_shape = logical_shapes\n+ lhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)\n+\n+ if lhs_ndim == rhs_ndim == 1:\n+ masked_lhs = lax.select(lax.iota(onp.int32, lhs.shape[0]) < lhs_shape[0],\n+ lhs, lax.zeros_like_array(lhs))\n+ return lax.dot_p.bind(masked_lhs, rhs, precision=precision)\n+ elif lhs_ndim == rhs_ndim == 2:\n+ # TODO could avoid select if we check whether contracted axis is masked\n+ masked_lhs = lax.select(lax.broadcasted_iota(onp.int32, lhs.shape, 1) < lhs_shape[1],\n+ lhs, lax.zeros_like_array(lhs))\n+ return lax.dot_p.bind(masked_lhs, rhs, precision=precision)\n+ elif rhs_ndim == 1:\n+ raise NotImplementedError\n+ else:\n+ raise NotImplementedError\n+masking_rules[lax.dot_p] = dot_masking_rule\n+\n+\n###\ndef mask(fun, in_shapes, out_shapes):\n@@ -237,6 +307,7 @@ from jax import vmap, jit\n@partial(mask, in_shapes=[Shape('n')], out_shapes=[Shape()])\ndef padded_sum(x):\nreturn np.sum(x) # output shape ()\n+\nprint(padded_sum([np.arange(5)], dict(n=3)))\nprint(vmap(padded_sum)([np.ones((5, 10))], dict(n=np.arange(5))))\n@@ -253,13 +324,14 @@ else: raise Exception\ndef cumsum_(arr):\nout, _ = lax.scan(lambda c, x: (c + x, ()), 0, arr)\nreturn out\n+\n@partial(mask, in_shapes=[Shape('n')], out_shapes=[Shape()])\ndef cumsum(x):\nreturn cumsum_(x)\n+\nprint(cumsum([np.array([5, 2, 9, 1, 4])], dict(n=3)))\nprint(vmap(cumsum)([np.arange(6).reshape(2, 3)], dict(n=np.array([1, 2]))))\n-\n@jit\ndef jit_cumsum(args, shape_env):\nprint(\"Python!\")\n@@ -268,6 +340,15 @@ print(jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=3)))\nprint(jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=4)))\n+@partial(mask, in_shapes=[Shape('m', 'k'), Shape('k', 'n')],\n+ out_shapes=[Shape('m', 'n')])\n+def dot(x, y):\n+ return lax.dot(x, y)\n+x = onp.arange(6, dtype=onp.float32).reshape((2, 3))\n+y = onp.arange(12, dtype=onp.float32).reshape((3, 4))\n+print(dot([x, y], dict(m=2, k=2, n=2))[:2, :2])\n+print(onp.dot(x[:2, :2], y[:2, :2]))\n+\n# notes!\n# - a shape variable is associated with a max size and a dynamic size. we carry\n# around the dynamic size explicitly in the shape_env attached to every\n"
}
] | Python | Apache License 2.0 | google/jax | add part of a dot masking rule |
260,335 | 28.08.2019 07:05:55 | 25,200 | cf637fd484764b2390541e6b5dc48e77fc7517de | note next steps | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "@@ -359,3 +359,10 @@ print(onp.dot(x[:2, :2], y[:2, :2]))\n# - we should probably pass the max size explicitly rather than getting it off\n# the values, e.g. the iota problem, should think of it as an independent type\n# argument\n+\n+\n+# next steps:\n+# 1. clean up shape expression language (maybe handle reshape/conat)\n+# 2. write example colab with two applications:\n+# (a) batching ragged sequences\n+# (b) jit bucketing\n"
}
] | Python | Apache License 2.0 | google/jax | note next steps |
260,335 | 28.08.2019 07:09:58 | 25,200 | 983b83f1c2be1a738828db952d87a5e92cebede8 | todo: test setup | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "@@ -362,6 +362,7 @@ print(onp.dot(x[:2, :2], y[:2, :2]))\n# next steps:\n+# 0. generic test setup\n# 1. clean up shape expression language (maybe handle reshape/conat)\n# 2. write example colab with two applications:\n# (a) batching ragged sequences\n"
}
] | Python | Apache License 2.0 | google/jax | todo: test setup |
260,335 | 28.08.2019 18:39:54 | 25,200 | 976ff5f010caded8c1125f286ebc418f24305d46 | try out a ShapeExpr with polynomials | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -705,7 +705,7 @@ def scan_bind(*args, **kwargs):\nxs_avals = _map(partial(_promote_aval_rank, length), x_avals)\nassert all(_map(typecheck, consts_avals, consts))\nassert all(_map(typecheck, init_avals, init))\n- assert all(_map(typecheck, xs_avals, xs))\n+ # assert all(_map(typecheck, xs_avals, xs))\n# check that output carry type matches input carry type\ncarry_avals, _ = split_list(jaxpr.out_avals, [num_carry])\n"
},
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "from __future__ import print_function\n-from collections import defaultdict\n+from collections import defaultdict, Counter\nfrom functools import partial\nimport itertools as it\n-import operator\n+import operator as op\nimport numpy as onp\n+import six\nfrom jax import core\nfrom jax.core import Trace, Tracer\n-from jax.util import unzip2, prod, safe_map, safe_zip, split_list\n+from jax.util import unzip2, safe_map, safe_zip, split_list\nfrom jax.api_util import tree_flatten, tree_unflatten, flatten_fun_nokwargs\nfrom jax import linear_util as lu\nfrom jax.abstract_arrays import ShapedArray\n@@ -18,9 +19,14 @@ from jax import lax\nmap = safe_map\nzip = safe_zip\n+reduce = six.moves.reduce\n+def prod(xs):\n+ xs = list(xs)\n+ return reduce(op.mul, xs) if xs else 1\n-Var = str\n+\n+### main transformation functions\ndef mask_fun(fun, shape_env, in_vals, shape_exprs):\nwith core.new_master(MaskTrace) as master:\n@@ -39,25 +45,57 @@ def mask_subtrace(master, shape_env, in_vals, shape_exprs):\nout_vals, out_shapes = unzip2((t.val, t.shape_expr) for t in out_tracers)\nyield out_vals, out_shapes\n-class ShapeExpr(object):\n- def __init__(self, *shape):\n- assert all(isinstance(s, (int, Var)) for s in shape)\n- self.shape = tuple(shape)\n- def __len__(self):\n- return len(self.shape)\n- def __iter__(self):\n- return iter(self.shape)\n- def __getitem__(self, idx):\n- return list(self)[idx]\n- def __repr__(self):\n- return 'ShapeExpr({})'.format(repr(self.shape))\n- __str__ = __repr__\n- def __eq__(self, other):\n- return type(other) is ShapeExpr and self.shape == other.shape\n-Shape = ShapeExpr\n+\n+## shape expressions are tuples of polynomials with integer coefficients\n+\n+Id = str\n+\n+class ShapeExpr(tuple): # type ShapeExpr = [Poly]\n+ def __str__(self):\n+ return 'ShapeExpr({})'.format(', '.join(map(str, self)))\n+\n+def Shape(*args):\n+ \"Convenience function for parsing a sequence of int literals or string ids.\"\n+ if not all(type(x) in (int, Id) for x in args): raise TypeError\n+ return ShapeExpr((Poly({Mon(): x}) if type(x) is int else Poly({Mon({x : 1})})\n+ for x in args))\n+\n+class Poly(Counter): # type Poly = Map Mon Int -- monomials to coeffs\n+ def __mul__(p1, p2):\n+ new_poly = Poly()\n+ for (mon1, coeff1), (mon2, coeff2) in it.product(p1.items(), p2.items()):\n+ mon = Mon(mon1 + mon2) # add monomials' id degrees\n+ coeff = coeff1 * coeff2 # multiply coeffs\n+ new_poly[mon] = new_poly.get(mon, 0) + coeff # accumulate\n+ return new_poly\n+\n+ def __add__(p1, p2):\n+ return Poly(Counter.__add__(p1, p2))\n+\n+ def __str__(self):\n+ return ' + '.join('{} {}'.format(v, k) if v != 1 else str(k)\n+ for k, v in sorted(self.items())).strip()\n+\n+class Mon(Counter): # type Mon = Map Id Int -- ids to degrees\n+ def __hash__(self):\n+ return hash(tuple(self.items()))\n+\n+ def __str__(self):\n+ return ' '.join('{}**{}'.format(k, v) if v != 1 else str(k)\n+ for k, v in sorted(self.items()))\n+\n+def eval_shape_expr(env, expr):\n+ return tuple(eval_poly(env, poly) for poly in expr)\n+\n+def eval_poly(env, poly):\n+ return sum(coeff * prod([env[id] ** deg for id, deg in mon.items()])\n+ for mon, coeff in poly.items())\nclass ShapeError(Exception): pass\n+\n+### tracer machinery\n+\nclass MaskTracer(Tracer):\n__slots__ = [\"val\", \"shape_expr\", \"shape_env\"]\n@@ -106,9 +144,6 @@ class MaskTrace(Trace):\ndef process_call(self, call_primitive, f, tracers, params):\nraise NotImplementedError # TODO\n-def eval_shape_expr(shape_env, shape_expr):\n- return tuple(shape_env[d] if type(d) is Var else d for d in shape_expr)\n-\nmasking_rules = {}\nshape_rules = {}\n@@ -124,7 +159,7 @@ def reduce_sum_masking_rule(padded_vals, logical_shapes, axes, input_shape):\n(padded_val,), (logical_shape,) = padded_vals, logical_shapes\nmasks = [lax.broadcasted_iota(onp.int32, padded_val.shape, i) < d\nfor i, d in enumerate(logical_shape)]\n- mask = reduce(operator.and_, masks)\n+ mask = reduce(op.and_, masks)\nmasked_val = lax.select(mask, padded_val, lax.zeros_like_array(padded_val))\nreturn lax.reduce_sum_p.bind(masked_val, axes=axes,\ninput_shape=padded_val.shape)\n@@ -176,9 +211,9 @@ defvectorized(lax.tanh_p)\ndef scan_shape_rule(shape_exprs, forward, length, jaxpr, num_consts, num_carry,\nlinear):\nconst_shexprs, init_shexprs, xs_shexprs = split_list(shape_exprs, [num_consts, num_carry])\n- if (any(any(type(d) is Var for d in shexpr) for shexpr in const_shexprs)\n- or any(any(type(d) is Var for d in shexpr) for shexpr in init_shexprs)\n- or any(any(type(d) is Var for d in shexpr[1:]) for shexpr in xs_shexprs)):\n+ if (any(any(type(d) is Id for d in shexpr) for shexpr in const_shexprs)\n+ or any(any(type(d) is Id for d in shexpr) for shexpr in init_shexprs)\n+ or any(any(type(d) is Id for d in shexpr[1:]) for shexpr in xs_shexprs)):\nraise NotImplementedError\n_, y_avals = split_list(jaxpr.out_avals, [num_carry])\nys_shapes = [ShapeExpr(length, *y_aval.shape) for y_aval in y_avals]\n@@ -229,7 +264,7 @@ def dot_shape_rule(shape_exprs, precision):\nlhs_shape, rhs_shape = shape_exprs\nlhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)\n- # TODO error checks\n+ assert False # TODO update w/ new ShapeExpr stuff\nif lhs_ndim == rhs_ndim == 1:\nif not lhs_shape == rhs_shape: raise ShapeError\nreturn Shape()\n@@ -275,11 +310,11 @@ def mask(fun, in_shapes, out_shapes):\nf = lu.wrap_init(fun)\nargs_flat, in_tree = tree_flatten(args)\nassert in_tree == in_shapes_tree\n- padded_sizes = _check_shape_agreement(args_flat, in_shapes_flat)\n+ # padded_sizes = _check_shape_agreement(args_flat, in_shapes_flat) # TODO\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\nouts, out_shapes_ = mask_fun(flat_fun, shape_env, args_flat, in_shapes_flat)\nassert out_shapes_flat == out_shapes\n- _check_shape_agreement(outs, out_shapes_flat, padded_sizes)\n+ # _check_shape_agreement(outs, out_shapes_flat, padded_sizes)\nreturn tree_unflatten(out_tree(), outs)\nreturn wrapped_fun\n@@ -287,7 +322,7 @@ def _check_shape_agreement(padded_args, shape_exprs, shape_values=None):\nshape_values = shape_values or defaultdict(set)\nfor arg, shexpr in zip(padded_args, shape_exprs):\nfor padded_size, size_expr in zip(arg.shape, shexpr):\n- if type(size_expr) is Var:\n+ if type(size_expr) is Id:\nshape_values[size_expr].add(padded_size)\nelif type(size_expr) is int:\nif padded_size != size_expr: raise ShapeError\n@@ -316,9 +351,9 @@ print(vmap(padded_sum)([np.ones((5, 10))], dict(n=np.arange(5))))\ndef addvecs(x, y):\nreturn x + y\nprint(addvecs([np.arange(5), np.arange(5)], dict(n=3)))\n-try: addvecs([np.arange(5), np.arange(6)], dict(n=3))\n-except ShapeError: print(\"good error\")\n-else: raise Exception\n+# try: addvecs([np.arange(5), np.arange(6)], dict(n=3)) # TODO\n+# except ShapeError: print(\"good error\")\n+# else: raise Exception\ndef cumsum_(arr):\n@@ -340,14 +375,14 @@ print(jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=3)))\nprint(jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=4)))\n-@partial(mask, in_shapes=[Shape('m', 'k'), Shape('k', 'n')],\n- out_shapes=[Shape('m', 'n')])\n-def dot(x, y):\n- return lax.dot(x, y)\n-x = onp.arange(6, dtype=onp.float32).reshape((2, 3))\n-y = onp.arange(12, dtype=onp.float32).reshape((3, 4))\n-print(dot([x, y], dict(m=2, k=2, n=2))[:2, :2])\n-print(onp.dot(x[:2, :2], y[:2, :2]))\n+# @partial(mask, in_shapes=[Shape('m', 'k'), Shape('k', 'n')],\n+# out_shapes=[Shape('m', 'n')])\n+# def dot(x, y):\n+# return lax.dot(x, y)\n+# x = onp.arange(6, dtype=onp.float32).reshape((2, 3))\n+# y = onp.arange(12, dtype=onp.float32).reshape((3, 4))\n+# print(dot([x, y], dict(m=2, k=2, n=2))[:2, :2])\n+# print(onp.dot(x[:2, :2], y[:2, :2]))\n# notes!\n# - a shape variable is associated with a max size and a dynamic size. we carry\n"
}
] | Python | Apache License 2.0 | google/jax | try out a ShapeExpr with polynomials |
260,335 | 30.08.2019 09:31:21 | 25,200 | a609ae7071ed088af3c40d438da7e0ba587d11e3 | set up a small shape language | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "@@ -4,6 +4,7 @@ from collections import defaultdict, Counter\nfrom functools import partial\nimport itertools as it\nimport operator as op\n+import string\nimport numpy as onp\nimport six\n@@ -46,27 +47,26 @@ def mask_subtrace(master, shape_env, in_vals, shape_exprs):\nyield out_vals, out_shapes\n-## shape expressions are tuples of polynomials with integer coefficients\n+### shape expressions\n-Id = str\n+# Shape expressions model tuples of formal polynomials with integer\n+# coefficients. Here are the internal data structures we use to represent them.\n+#\n+# type ShapeExpr = [Poly]\n+# type Poly = Map Mon Int\n+# type Mon = Map Str Int\nclass ShapeExpr(tuple): # type ShapeExpr = [Poly]\ndef __str__(self):\nreturn 'ShapeExpr({})'.format(', '.join(map(str, self)))\n-def Shape(*args):\n- \"Convenience function for parsing a sequence of int literals or string ids.\"\n- if not all(type(x) in (int, Id) for x in args): raise TypeError\n- return ShapeExpr((Poly({Mon(): x}) if type(x) is int else Poly({Mon({x : 1})})\n- for x in args))\n-\nclass Poly(Counter): # type Poly = Map Mon Int -- monomials to coeffs\ndef __mul__(p1, p2):\nnew_poly = Poly()\nfor (mon1, coeff1), (mon2, coeff2) in it.product(p1.items(), p2.items()):\nmon = Mon(mon1 + mon2) # add monomials' id degrees\n- coeff = coeff1 * coeff2 # multiply coeffs\n- new_poly[mon] = new_poly.get(mon, 0) + coeff # accumulate\n+ coeff = coeff1 * coeff2 # multiply integer coeffs\n+ new_poly[mon] = new_poly.get(mon, 0) + coeff # accumulate coeffs\nreturn new_poly\ndef __add__(p1, p2):\n@@ -93,6 +93,53 @@ def eval_poly(env, poly):\nclass ShapeError(Exception): pass\n+# To denote some shape expressions (for annotations) we use a small language.\n+#\n+# data Shape = Shape [Dim]\n+# data Dim = Id Str\n+# | Lit Int\n+# | Mul Dim Dim\n+\n+# We'll also make a simple concrete syntax for annotation. The grammar is\n+#\n+# shape_spec ::= '(' dims ')'\n+# dims ::= dim ',' dims | ''\n+# dim ::= str | int | dim '*' dim\n+\n+def parse_spec(spec=''):\n+ if not spec:\n+ return ShapeExpr(())\n+ if spec[0] == '(':\n+ if spec[-1] != ')': raise SyntaxError\n+ spec = spec[1:-1]\n+ dims = map(parse_dim, spec.replace(' ', '').strip(',').split(','))\n+ return ShapeExpr(dims)\n+\n+def parse_dim(spec):\n+ if '*' in spec:\n+ terms = map(parse_dim, spec.split('*'))\n+ return reduce(op.mul, terms)\n+ elif spec in digits:\n+ return parse_lit(spec)\n+ elif spec in identifiers:\n+ return parse_id(spec)\n+ else:\n+ raise SyntaxError\n+digits = frozenset(string.digits)\n+identifiers = frozenset(string.lowercase)\n+\n+def parse_id(name): return Poly({Mon({name: 1}): 1})\n+def parse_lit(val_str): return Poly({Mon(): int(val_str)})\n+\n+print(parse_spec('(m, n)')) # ShapeExpr(m, n)\n+print(parse_spec('(m * n)')) # ShapeExpr(m n)\n+print(parse_spec('(m * n,)')) # ShapeExpr(m n)\n+print(parse_spec('(3, m)')) # ShapeExpr(3, m)\n+print(parse_spec('(3 * m)')) # ShapeExpr(3 m)\n+print(parse_spec('m')) # ShapeExpr(m)\n+print(parse_spec('')) # ShapeExpr()\n+\n+Shape = parse_spec\n### tracer machinery\n@@ -300,11 +347,31 @@ def dot_masking_rule(padded_vals, logical_shapes, precision):\nmasking_rules[lax.dot_p] = dot_masking_rule\n+def reshape_shape_rule(shape_exprs, new_sizes, dimensions, old_sizes):\n+ import ipdb; ipdb.set_trace()\n+ del old_sizes # Unused.\n+ if dimensions is not None: raise NotImplementedError\n+ shape_expr, = shape_exprs\n+ if prod(shape_expr) != prod(new_sizes): raise Exception\n+ return ShapeExpr(new_sizes)\n+shape_rules[lax.reshape_p] = reshape_shape_rule\n+\n+def reshape_masking_rule(padded_vals, logical_shapes, new_sizes, dimensions,\n+ old_sizes):\n+ import ipdb; ipdb.set_trace()\n+ del new_sizes, old_sizes # Unused.\n+ if dimensions is not None: raise NotImplementedError\n+ padded_operand, = padded_vals\n+ new_shape, = logical_shapes\n+ return lax.reshape(padded_operand) # TODO\n+masking_rules[lax.reshape_p] = reshape_masking_rule\n+\n+\n###\n-def mask(fun, in_shapes, out_shapes):\n+def mask(fun, in_shapes, out_shape):\nin_shapes_flat, in_shapes_tree = tree_flatten(in_shapes)\n- out_shapes_flat, out_shapes_tree = tree_flatten(out_shapes)\n+ out_shapes_flat, out_shapes_tree = tree_flatten(out_shape)\ndef wrapped_fun(args, shape_env):\nf = lu.wrap_init(fun)\n@@ -313,7 +380,7 @@ def mask(fun, in_shapes, out_shapes):\n# padded_sizes = _check_shape_agreement(args_flat, in_shapes_flat) # TODO\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\nouts, out_shapes_ = mask_fun(flat_fun, shape_env, args_flat, in_shapes_flat)\n- assert out_shapes_flat == out_shapes\n+ assert out_shapes_flat == list(out_shapes_)\n# _check_shape_agreement(outs, out_shapes_flat, padded_sizes)\nreturn tree_unflatten(out_tree(), outs)\nreturn wrapped_fun\n@@ -339,7 +406,7 @@ import jax.numpy as np\nfrom jax import vmap, jit\n-@partial(mask, in_shapes=[Shape('n')], out_shapes=[Shape()])\n+@partial(mask, in_shapes=[Shape('n')], out_shape=Shape())\ndef padded_sum(x):\nreturn np.sum(x) # output shape ()\n@@ -347,7 +414,7 @@ print(padded_sum([np.arange(5)], dict(n=3)))\nprint(vmap(padded_sum)([np.ones((5, 10))], dict(n=np.arange(5))))\n-@partial(mask, in_shapes=[Shape('n'), Shape('n')], out_shapes=[Shape('n')])\n+@partial(mask, in_shapes=[Shape('n'), Shape('n')], out_shape=Shape('n'))\ndef addvecs(x, y):\nreturn x + y\nprint(addvecs([np.arange(5), np.arange(5)], dict(n=3)))\n@@ -360,7 +427,7 @@ def cumsum_(arr):\nout, _ = lax.scan(lambda c, x: (c + x, ()), 0, arr)\nreturn out\n-@partial(mask, in_shapes=[Shape('n')], out_shapes=[Shape()])\n+@partial(mask, in_shapes=[Shape('n')], out_shape=Shape())\ndef cumsum(x):\nreturn cumsum_(x)\n@@ -375,6 +442,11 @@ print(jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=3)))\nprint(jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=4)))\n+@partial(mask, in_shapes=[Shape('(m, n)')], out_shape=Shape('m * n'))\n+def flatten(x):\n+ pass # TODO\n+\n+\n# @partial(mask, in_shapes=[Shape('m', 'k'), Shape('k', 'n')],\n# out_shapes=[Shape('m', 'n')])\n# def dot(x, y):\n"
}
] | Python | Apache License 2.0 | google/jax | set up a small shape language |
260,335 | 30.08.2019 16:06:43 | 25,200 | fbc85af54f654e5f8489f8220c3b8d0f4a94d0f5 | made polymorphic jaxprs, reshape fail | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -580,7 +580,8 @@ def reshape(operand, new_sizes, dimensions=None):\n<https://www.tensorflow.org/xla/operation_semantics#reshape>`_\noperator.\n\"\"\"\n- new_sizes = _canonicalize_shape(new_sizes)\n+ # new_sizes = _canonicalize_shape(new_sizes) # TODO\n+ new_sizes = tuple(new_sizes)\nsame_shape = onp.shape(operand) == new_sizes\nsame_dims = dimensions is None or tuple(dimensions) == tuple(range(onp.ndim(operand)))\nif onp.shape(operand) and same_shape and same_dims:\n"
},
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "from __future__ import print_function\n-from collections import defaultdict, Counter\n+from collections import defaultdict, Counter, namedtuple\nfrom functools import partial\nimport itertools as it\nimport operator as op\n@@ -29,17 +29,17 @@ def prod(xs):\n### main transformation functions\n-def mask_fun(fun, shape_env, in_vals, shape_exprs):\n+def mask_fun(fun, shape_envs, in_vals, shape_exprs):\nwith core.new_master(MaskTrace) as master:\n- fun, out_shapes = mask_subtrace(fun, master, shape_env)\n+ fun, out_shapes = mask_subtrace(fun, master, shape_envs)\nout_vals = fun.call_wrapped(in_vals, shape_exprs)\ndel master\nreturn out_vals, out_shapes()\n@lu.transformation_with_aux\n-def mask_subtrace(master, shape_env, in_vals, shape_exprs):\n+def mask_subtrace(master, shape_envs, in_vals, shape_exprs):\ntrace = MaskTrace(master, core.cur_sublevel())\n- in_tracers = map(partial(MaskTracer, trace, shape_env),\n+ in_tracers = map(partial(MaskTracer, trace, shape_envs),\nin_vals, shape_exprs)\nouts = yield in_tracers, {}\nout_tracers = map(trace.full_raise, outs)\n@@ -72,6 +72,9 @@ class Poly(Counter): # type Poly = Map Mon Int -- monomials to coeffs\ndef __add__(p1, p2):\nreturn Poly(Counter.__add__(p1, p2))\n+ def __hash__(self):\n+ return hash(tuple(self.items()))\n+\ndef __str__(self):\nreturn ' + '.join('{} {}'.format(v, k) if v != 1 else str(k)\nfor k, v in sorted(self.items())).strip()\n@@ -85,9 +88,9 @@ class Mon(Counter): # type Mon = Map Id Int -- ids to degrees\nfor k, v in sorted(self.items()))\ndef eval_shape_expr(env, expr):\n- return tuple(eval_poly(env, poly) for poly in expr)\n+ return tuple(eval_dim_expr(env, poly) for poly in expr)\n-def eval_poly(env, poly):\n+def eval_dim_expr(env, poly):\nreturn sum(coeff * prod([env[id] ** deg for id, deg in mon.items()])\nfor mon, coeff in poly.items())\n@@ -131,35 +134,35 @@ identifiers = frozenset(string.lowercase)\ndef parse_id(name): return Poly({Mon({name: 1}): 1})\ndef parse_lit(val_str): return Poly({Mon(): int(val_str)})\n-print(parse_spec('(m, n)')) # ShapeExpr(m, n)\n-print(parse_spec('(m * n)')) # ShapeExpr(m n)\n-print(parse_spec('(m * n,)')) # ShapeExpr(m n)\n-print(parse_spec('(3, m)')) # ShapeExpr(3, m)\n-print(parse_spec('(3 * m)')) # ShapeExpr(3 m)\n-print(parse_spec('m')) # ShapeExpr(m)\n-print(parse_spec('')) # ShapeExpr()\n+Shape = parse_spec # convenience\n+\n+# Tests:\n+print(Shape('(m, n)')) # ShapeExpr(m, n)\n+print(Shape('(m * n)')) # ShapeExpr(m n)\n+print(Shape('m * n')) # ShapeExpr(m n)\n+print(Shape('(m * n,)')) # ShapeExpr(m n)\n+print(Shape('(3, m)')) # ShapeExpr(3, m)\n+print(Shape('(3 * m)')) # ShapeExpr(3 m)\n+print(Shape('m')) # ShapeExpr(m)\n+print(Shape('')) # ShapeExpr()\n-Shape = parse_spec\n### tracer machinery\n+ShapeEnvs = namedtuple(\"ShapeEnvs\", [\"logical\", \"padded\"])\n+\nclass MaskTracer(Tracer):\n- __slots__ = [\"val\", \"shape_expr\", \"shape_env\"]\n+ __slots__ = [\"val\", \"shape_expr\", \"shape_envs\", \"log_shape_env\"]\n- def __init__(self, trace, shape_env, val, shape_expr):\n+ def __init__(self, trace, shape_envs, val, shape_expr):\nself.trace = trace\n- self.shape_env = shape_env\n+ self.shape_envs = shape_envs\nself.val = val\nself.shape_expr = shape_expr\n@property\ndef aval(self):\n- # TODO can avoid some blowups, also improve error messages\n- if self.shape_env is not None:\n- shape = eval_shape_expr(self.shape_env, self.shape_expr)\n- return ShapedArray(tuple(shape), self.val.dtype)\n- else:\n- return ShapedArray(self.val.shape, self.val.dtype)\n+ return ShapedArray(self.shape_expr, self.val.dtype)\ndef full_lower(self):\nif all(type(s) is int for s in self.shape_expr):\n@@ -175,22 +178,27 @@ class MaskTrace(Trace):\nreturn MaskTracer(self, None, val, ShapeExpr(*onp.shape(val)))\ndef sublift(self, val):\n- return MaskTracer(self, val.shape_env, val.val, val.shape_expr)\n+ return MaskTracer(self, val.shape_envs, val.val, val.shape_expr)\ndef process_primitive(self, primitive, tracers, params):\n- shape_env = next(t.shape_env for t in tracers if t.shape_env is not None)\n+ shape_envs = next(t.shape_envs for t in tracers if t.shape_envs is not None)\nvals, shape_exprs = unzip2((t.val, t.shape_expr) for t in tracers)\n+ if primitive in shape_parameterized_primitive_rules:\n+ rule = shape_parameterized_primitive_rules[primitive]\n+ out, out_shape = rule(shape_envs, vals, shape_exprs, **params)\n+ else:\nout_shape = shape_rules[primitive](shape_exprs, **params)\n- logical_shapes = map(partial(eval_shape_expr, shape_env), shape_exprs)\n+ logical_shapes = map(partial(eval_shape_expr, shape_envs.logical), shape_exprs)\nout = masking_rules[primitive](vals, logical_shapes, **params)\nif not primitive.multiple_results:\n- return MaskTracer(self, shape_env, out, out_shape)\n+ return MaskTracer(self, shape_envs, out, out_shape)\nelse:\n- return map(partial(MaskTracer, self, shape_env), out, out_shape)\n+ return map(partial(MaskTracer, self, shape_envs), out, out_shape)\ndef process_call(self, call_primitive, f, tracers, params):\nraise NotImplementedError # TODO\n+shape_parameterized_primitive_rules = {}\nmasking_rules = {}\nshape_rules = {}\n@@ -255,6 +263,47 @@ defvectorized(lax.log_p)\ndefvectorized(lax.tanh_p)\n+def dot_shape_rule(shape_exprs, precision):\n+ del precision # Unused.\n+ lhs_shape, rhs_shape = shape_exprs\n+ lhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)\n+\n+ assert False # TODO update w/ new ShapeExpr stuff\n+ if lhs_ndim == rhs_ndim == 1:\n+ if not lhs_shape == rhs_shape: raise ShapeError\n+ return Shape()\n+ elif lhs_ndim == rhs_ndim == 2:\n+ if not lhs_shape[1] == rhs_shape[0]: raise ShapeError\n+ return Shape(lhs_shape[0], rhs_shape[1])\n+ elif rhs_ndim == 1:\n+ if not lhs_shape[1] == rhs_shape[0]: raise ShapeError\n+ return Shape(lhs_shape[0])\n+ else:\n+ if not lhs_shape[0] == rhs_shape[0]: raise ShapeError\n+ return Shape(rhs_shape[1])\n+shape_rules[lax.dot_p] = dot_shape_rule\n+\n+def dot_masking_rule(padded_vals, logical_shapes, precision):\n+ lhs, rhs = padded_vals\n+ lhs_shape, rhs_shape = logical_shapes\n+ lhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)\n+\n+ if lhs_ndim == rhs_ndim == 1:\n+ masked_lhs = lax.select(lax.iota(onp.int32, lhs.shape[0]) < lhs_shape[0],\n+ lhs, lax.zeros_like_array(lhs))\n+ return lax.dot_p.bind(masked_lhs, rhs, precision=precision)\n+ elif lhs_ndim == rhs_ndim == 2:\n+ # TODO could avoid select if we check whether contracted axis is masked\n+ masked_lhs = lax.select(lax.broadcasted_iota(onp.int32, lhs.shape, 1) < lhs_shape[1],\n+ lhs, lax.zeros_like_array(lhs))\n+ return lax.dot_p.bind(masked_lhs, rhs, precision=precision)\n+ elif rhs_ndim == 1:\n+ raise NotImplementedError\n+ else:\n+ raise NotImplementedError\n+masking_rules[lax.dot_p] = dot_masking_rule\n+\n+\ndef scan_shape_rule(shape_exprs, forward, length, jaxpr, num_consts, num_carry,\nlinear):\nconst_shexprs, init_shexprs, xs_shexprs = split_list(shape_exprs, [num_consts, num_carry])\n@@ -265,21 +314,24 @@ def scan_shape_rule(shape_exprs, forward, length, jaxpr, num_consts, num_carry,\n_, y_avals = split_list(jaxpr.out_avals, [num_carry])\nys_shapes = [ShapeExpr(length, *y_aval.shape) for y_aval in y_avals]\nreturn init_shexprs + ys_shapes\n-shape_rules[lax.scan_p] = scan_shape_rule\n-def scan_masking_rule(padded_vals, logical_shapes, forward, length, jaxpr,\n- num_consts, num_carry, linear):\n+def scan_masking_rule(shape_envs, padded_vals, shape_exprs, forward, length,\n+ jaxpr, num_consts, num_carry, linear):\n+ out_shape = scan_shape_rule(shape_exprs, forward, length, jaxpr, num_consts,\n+ num_carry, linear)\n+\n+ dynamic_length = eval_dim_expr(shape_envs.logical, length)\nmasked_jaxpr = _masked_scan_jaxpr(jaxpr, num_consts, num_carry)\nconsts, init, xs = split_list(padded_vals, [num_consts, num_carry])\nmax_length, = {x.shape[0] for x in xs}\nconst_linear, init_linear, xs_linear = split_list(linear, [num_consts, num_carry])\nout_vals = lax.scan_p.bind(\n- *it.chain([length] + consts, [0], init, xs),\n+ *it.chain([dynamic_length] + consts, [0], init, xs),\nforward=forward, length=max_length, jaxpr=masked_jaxpr,\nnum_consts=1 + num_consts, num_carry=1 + num_carry,\nlinear=[False] + const_linear + [False] + init_linear + xs_linear)\n- return out_vals[1:]\n-masking_rules[lax.scan_p] = scan_masking_rule\n+ return out_vals[1:], out_shape\n+shape_parameterized_primitive_rules[lax.scan_p] = scan_masking_rule\ndef _masked_scan_jaxpr(jaxpr, num_consts, num_carry):\nfun = core.jaxpr_as_fun(jaxpr)\n@@ -306,65 +358,23 @@ def _make_typed_jaxpr(traceable, in_avals):\nreturn core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)\n-def dot_shape_rule(shape_exprs, precision):\n- del precision # Unused.\n- lhs_shape, rhs_shape = shape_exprs\n- lhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)\n-\n- assert False # TODO update w/ new ShapeExpr stuff\n- if lhs_ndim == rhs_ndim == 1:\n- if not lhs_shape == rhs_shape: raise ShapeError\n- return Shape()\n- elif lhs_ndim == rhs_ndim == 2:\n- if not lhs_shape[1] == rhs_shape[0]: raise ShapeError\n- return Shape(lhs_shape[0], rhs_shape[1])\n- elif rhs_ndim == 1:\n- if not lhs_shape[1] == rhs_shape[0]: raise ShapeError\n- return Shape(lhs_shape[0])\n- else:\n- if not lhs_shape[0] == rhs_shape[0]: raise ShapeError\n- return Shape(rhs_shape[1])\n-shape_rules[lax.dot_p] = dot_shape_rule\n-\n-def dot_masking_rule(padded_vals, logical_shapes, precision):\n- lhs, rhs = padded_vals\n- lhs_shape, rhs_shape = logical_shapes\n- lhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)\n-\n- if lhs_ndim == rhs_ndim == 1:\n- masked_lhs = lax.select(lax.iota(onp.int32, lhs.shape[0]) < lhs_shape[0],\n- lhs, lax.zeros_like_array(lhs))\n- return lax.dot_p.bind(masked_lhs, rhs, precision=precision)\n- elif lhs_ndim == rhs_ndim == 2:\n- # TODO could avoid select if we check whether contracted axis is masked\n- masked_lhs = lax.select(lax.broadcasted_iota(onp.int32, lhs.shape, 1) < lhs_shape[1],\n- lhs, lax.zeros_like_array(lhs))\n- return lax.dot_p.bind(masked_lhs, rhs, precision=precision)\n- elif rhs_ndim == 1:\n- raise NotImplementedError\n- else:\n- raise NotImplementedError\n-masking_rules[lax.dot_p] = dot_masking_rule\n-\n-\n+# TODO remove this\ndef reshape_shape_rule(shape_exprs, new_sizes, dimensions, old_sizes):\n- import ipdb; ipdb.set_trace()\n- del old_sizes # Unused.\nif dimensions is not None: raise NotImplementedError\nshape_expr, = shape_exprs\n- if prod(shape_expr) != prod(new_sizes): raise Exception\n- return ShapeExpr(new_sizes)\n-shape_rules[lax.reshape_p] = reshape_shape_rule\n-\n-def reshape_masking_rule(padded_vals, logical_shapes, new_sizes, dimensions,\n- old_sizes):\n- import ipdb; ipdb.set_trace()\n- del new_sizes, old_sizes # Unused.\n+ if prod(shape_expr) != prod(new_sizes): raise ShapeError\n+ return new_sizes\n+\n+def reshape_masking_rule(shape_envs, padded_vals, shape_exprs, new_sizes,\n+ dimensions, old_sizes):\nif dimensions is not None: raise NotImplementedError\n+ new_sizes = ShapeExpr(new_sizes) # tuplified\n+ out_shape = reshape_shape_rule(shape_exprs, new_sizes, dimensions, old_sizes)\npadded_operand, = padded_vals\n- new_shape, = logical_shapes\n- return lax.reshape(padded_operand) # TODO\n-masking_rules[lax.reshape_p] = reshape_masking_rule\n+ padded_new_sizes = eval_shape_expr(shape_envs.padded, new_sizes)\n+ out = lax.reshape(padded_operand, padded_new_sizes)\n+ return out, out_shape\n+shape_parameterized_primitive_rules[lax.reshape_p] = reshape_masking_rule\n###\n@@ -373,32 +383,27 @@ def mask(fun, in_shapes, out_shape):\nin_shapes_flat, in_shapes_tree = tree_flatten(in_shapes)\nout_shapes_flat, out_shapes_tree = tree_flatten(out_shape)\n- def wrapped_fun(args, shape_env):\n+ def wrapped_fun(args, logical_shape_env):\nf = lu.wrap_init(fun)\nargs_flat, in_tree = tree_flatten(args)\nassert in_tree == in_shapes_tree\n- # padded_sizes = _check_shape_agreement(args_flat, in_shapes_flat) # TODO\n+ padded_shape_env = _bind_shapes(in_shapes_flat, [x.shape for x in args_flat])\n+ shape_envs = ShapeEnvs(logical_shape_env, padded_shape_env)\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\n- outs, out_shapes_ = mask_fun(flat_fun, shape_env, args_flat, in_shapes_flat)\n+ outs, out_shapes_ = mask_fun(flat_fun, shape_envs, args_flat, in_shapes_flat)\nassert out_shapes_flat == list(out_shapes_)\n- # _check_shape_agreement(outs, out_shapes_flat, padded_sizes)\n+ assert all(out.shape == eval_shape_expr(padded_shape_env, expr)\n+ for out, expr in zip(outs, out_shapes_flat))\nreturn tree_unflatten(out_tree(), outs)\nreturn wrapped_fun\n-def _check_shape_agreement(padded_args, shape_exprs, shape_values=None):\n- shape_values = shape_values or defaultdict(set)\n- for arg, shexpr in zip(padded_args, shape_exprs):\n- for padded_size, size_expr in zip(arg.shape, shexpr):\n- if type(size_expr) is Id:\n- shape_values[size_expr].add(padded_size)\n- elif type(size_expr) is int:\n- if padded_size != size_expr: raise ShapeError\n- else:\n- raise TypeError(size_expr)\n- for shape_var, sizes in shape_values.items():\n- if len(sizes) != 1:\n- raise ShapeError\n- return shape_values\n+def _bind_shapes(shape_exprs, shapes):\n+ env = {}\n+ for binders, shape in zip(shape_exprs, shapes):\n+ for poly, d in zip(binders, shape):\n+ (binder,), = poly\n+ if env.setdefault(binder, d) != d: raise ShapeError\n+ return env\n###\n@@ -444,7 +449,8 @@ print(jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=4)))\n@partial(mask, in_shapes=[Shape('(m, n)')], out_shape=Shape('m * n'))\ndef flatten(x):\n- pass # TODO\n+ return lax.reshape(x, (x.shape[0] * x.shape[1],))\n+print(flatten([np.arange(12).reshape(3, 4)], dict(m=2, n=3)))\n# @partial(mask, in_shapes=[Shape('m', 'k'), Shape('k', 'n')],\n@@ -468,6 +474,9 @@ def flatten(x):\n# argument\n+# TODO try to revert to the version without polymorphism in jaxprs, get rid of\n+# reshape, make Tracer.aval return an aval with evaluated shapes not shexprs\n+\n# next steps:\n# 0. generic test setup\n# 1. clean up shape expression language (maybe handle reshape/conat)\n"
}
] | Python | Apache License 2.0 | google/jax | made polymorphic jaxprs, reshape fail |
260,335 | 30.08.2019 18:03:18 | 25,200 | 20299270a38bc49a15534bc8ca4563f940fe0653 | concat is cool (packed not striped) | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "@@ -102,12 +102,13 @@ class ShapeError(Exception): pass\n# data Dim = Id Str\n# | Lit Int\n# | Mul Dim Dim\n+# | Add Dim Dim\n# We'll also make a simple concrete syntax for annotation. The grammar is\n#\n# shape_spec ::= '(' dims ')'\n# dims ::= dim ',' dims | ''\n-# dim ::= str | int | dim '*' dim\n+# dim ::= str | int | dim '*' dim | dim '+' dim\ndef parse_spec(spec=''):\nif not spec:\n@@ -119,7 +120,10 @@ def parse_spec(spec=''):\nreturn ShapeExpr(dims)\ndef parse_dim(spec):\n- if '*' in spec:\n+ if '+' in spec:\n+ terms = map(parse_dim, spec.split('+'))\n+ return reduce(op.add, terms)\n+ elif '*' in spec:\nterms = map(parse_dim, spec.split('*'))\nreturn reduce(op.mul, terms)\nelif spec in digits:\n@@ -145,6 +149,9 @@ print(Shape('(3, m)')) # ShapeExpr(3, m)\nprint(Shape('(3 * m)')) # ShapeExpr(3 m)\nprint(Shape('m')) # ShapeExpr(m)\nprint(Shape('')) # ShapeExpr()\n+print(Shape('m + n')) # ShapeExpr(m + n)\n+print(Shape('m + n * k')) # ShapeExpr(m + k n)\n+print(Shape('m + 3 * k')) # ShapeExpr(3 k + n)\n### tracer machinery\n@@ -358,24 +365,35 @@ def _make_typed_jaxpr(traceable, in_avals):\nreturn core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)\n-# TODO remove this\ndef reshape_shape_rule(shape_exprs, new_sizes, dimensions, old_sizes):\nif dimensions is not None: raise NotImplementedError\nshape_expr, = shape_exprs\nif prod(shape_expr) != prod(new_sizes): raise ShapeError\nreturn new_sizes\n-def reshape_masking_rule(shape_envs, padded_vals, shape_exprs, new_sizes,\n- dimensions, old_sizes):\n- if dimensions is not None: raise NotImplementedError\n- new_sizes = ShapeExpr(new_sizes) # tuplified\n- out_shape = reshape_shape_rule(shape_exprs, new_sizes, dimensions, old_sizes)\n- padded_operand, = padded_vals\n- padded_new_sizes = eval_shape_expr(shape_envs.padded, new_sizes)\n- out = lax.reshape(padded_operand, padded_new_sizes)\n- return out, out_shape\n-shape_parameterized_primitive_rules[lax.reshape_p] = reshape_masking_rule\n+def concat_shape_rule(shape_exprs, dimension, operand_shapes):\n+ out_shape = list(shape_exprs[0])\n+ out_shape[dimension] = reduce(op.add, [e[dimension] for e in shape_exprs])\n+ return ShapeExpr(out_shape)\n+shape_rules[lax.concatenate_p] = concat_shape_rule\n+\n+def concat_masking_rule(padded_vals, logical_shapes, dimension, operand_shapes):\n+ del operand_shapes # Unused.\n+ result = lax.concatenate(padded_vals, dimension) # fragmented\n+ offset = 0\n+ for padded_val, logical_shape in zip(padded_vals, logical_shapes):\n+ result = _memcpy(dimension, logical_shape[dimension], padded_val,\n+ result, offset)\n+ offset = offset + logical_shape[dimension]\n+ return result\n+masking_rules[lax.concatenate_p] = concat_masking_rule\n+\n+def _memcpy(axis, num, src, dst, offset):\n+ def body(i, dst):\n+ update = lax.dynamic_index_in_dim(src, i, axis)\n+ return lax.dynamic_update_index_in_dim(dst, update, i + offset, axis)\n+ return lax.fori_loop(0, num, body, dst)\n###\n@@ -391,9 +409,10 @@ def mask(fun, in_shapes, out_shape):\nshape_envs = ShapeEnvs(logical_shape_env, padded_shape_env)\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\nouts, out_shapes_ = mask_fun(flat_fun, shape_envs, args_flat, in_shapes_flat)\n- assert out_shapes_flat == list(out_shapes_)\n- assert all(out.shape == eval_shape_expr(padded_shape_env, expr)\n- for out, expr in zip(outs, out_shapes_flat))\n+ if not out_shapes_flat == list(out_shapes_): raise ShapeError\n+ if not all(out.shape == eval_shape_expr(padded_shape_env, expr)\n+ for out, expr in zip(outs, out_shapes_flat)):\n+ raise ShapeError\nreturn tree_unflatten(out_tree(), outs)\nreturn wrapped_fun\n@@ -423,9 +442,9 @@ print(vmap(padded_sum)([np.ones((5, 10))], dict(n=np.arange(5))))\ndef addvecs(x, y):\nreturn x + y\nprint(addvecs([np.arange(5), np.arange(5)], dict(n=3)))\n-# try: addvecs([np.arange(5), np.arange(6)], dict(n=3)) # TODO\n-# except ShapeError: print(\"good error\")\n-# else: raise Exception\n+try: addvecs([np.arange(5), np.arange(6)], dict(n=3))\n+except ShapeError: print(\"good error\")\n+else: raise Exception\ndef cumsum_(arr):\n@@ -447,11 +466,12 @@ print(jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=3)))\nprint(jit_cumsum([np.array([5, 2, 9, 1, 4])], dict(n=4)))\n-@partial(mask, in_shapes=[Shape('(m, n)')], out_shape=Shape('m * n'))\n-def flatten(x):\n- return lax.reshape(x, (x.shape[0] * x.shape[1],))\n-print(flatten([np.arange(12).reshape(3, 4)], dict(m=2, n=3)))\n-\n+@partial(mask, in_shapes=[Shape('n'), Shape('m'), Shape('n')],\n+ out_shape=Shape('m + 2 * n'))\n+def cat(x, y, z):\n+ return lax.concatenate([x, y, z], 0)\n+print(cat([np.array([1, 9]), np.array([2, 9]), np.array([3, 9])],\n+ dict(m=1, n=1))[:3])\n# @partial(mask, in_shapes=[Shape('m', 'k'), Shape('k', 'n')],\n# out_shapes=[Shape('m', 'n')])\n@@ -474,9 +494,6 @@ print(flatten([np.arange(12).reshape(3, 4)], dict(m=2, n=3)))\n# argument\n-# TODO try to revert to the version without polymorphism in jaxprs, get rid of\n-# reshape, make Tracer.aval return an aval with evaluated shapes not shexprs\n-\n# next steps:\n# 0. generic test setup\n# 1. clean up shape expression language (maybe handle reshape/conat)\n"
}
] | Python | Apache License 2.0 | google/jax | concat is cool (packed not striped) |
260,335 | 30.08.2019 18:26:41 | 25,200 | f4d6591ff34bd0814fca04600f46503fb9fc0253 | revive dot example | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "@@ -114,7 +114,7 @@ def parse_spec(spec=''):\nif not spec:\nreturn ShapeExpr(())\nif spec[0] == '(':\n- if spec[-1] != ')': raise SyntaxError\n+ if spec[-1] != ')': raise SyntaxError(spec)\nspec = spec[1:-1]\ndims = map(parse_dim, spec.replace(' ', '').strip(',').split(','))\nreturn ShapeExpr(dims)\n@@ -131,7 +131,7 @@ def parse_dim(spec):\nelif spec in identifiers:\nreturn parse_id(spec)\nelse:\n- raise SyntaxError\n+ raise SyntaxError(spec)\ndigits = frozenset(string.digits)\nidentifiers = frozenset(string.lowercase)\n@@ -275,19 +275,18 @@ def dot_shape_rule(shape_exprs, precision):\nlhs_shape, rhs_shape = shape_exprs\nlhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)\n- assert False # TODO update w/ new ShapeExpr stuff\nif lhs_ndim == rhs_ndim == 1:\nif not lhs_shape == rhs_shape: raise ShapeError\n- return Shape()\n+ return ShapeExpr(())\nelif lhs_ndim == rhs_ndim == 2:\nif not lhs_shape[1] == rhs_shape[0]: raise ShapeError\n- return Shape(lhs_shape[0], rhs_shape[1])\n+ return ShapeExpr((lhs_shape[0], rhs_shape[1]))\nelif rhs_ndim == 1:\nif not lhs_shape[1] == rhs_shape[0]: raise ShapeError\n- return Shape(lhs_shape[0])\n+ return ShapeExpr((lhs_shape[0],))\nelse:\nif not lhs_shape[0] == rhs_shape[0]: raise ShapeError\n- return Shape(rhs_shape[1])\n+ return ShapeExpr((rhs_shape[1],))\nshape_rules[lax.dot_p] = dot_shape_rule\ndef dot_masking_rule(padded_vals, logical_shapes, precision):\n@@ -473,14 +472,15 @@ def cat(x, y, z):\nprint(cat([np.array([1, 9]), np.array([2, 9]), np.array([3, 9])],\ndict(m=1, n=1))[:3])\n-# @partial(mask, in_shapes=[Shape('m', 'k'), Shape('k', 'n')],\n-# out_shapes=[Shape('m', 'n')])\n-# def dot(x, y):\n-# return lax.dot(x, y)\n-# x = onp.arange(6, dtype=onp.float32).reshape((2, 3))\n-# y = onp.arange(12, dtype=onp.float32).reshape((3, 4))\n-# print(dot([x, y], dict(m=2, k=2, n=2))[:2, :2])\n-# print(onp.dot(x[:2, :2], y[:2, :2]))\n+\n+@partial(mask, in_shapes=[Shape('(m, k)'), Shape(('k, n'))],\n+ out_shape=[Shape('(m, n)')])\n+def dot(x, y):\n+ return lax.dot(x, y)\n+x = onp.arange(6, dtype=onp.float32).reshape((2, 3))\n+y = onp.arange(12, dtype=onp.float32).reshape((3, 4))\n+print(dot([x, y], dict(m=2, k=2, n=2))[:2, :2])\n+print(onp.dot(x[:2, :2], y[:2, :2]))\n# notes!\n# - a shape variable is associated with a max size and a dynamic size. we carry\n"
}
] | Python | Apache License 2.0 | google/jax | revive dot example |
260,335 | 30.08.2019 21:35:56 | 25,200 | e12c8b0340e5508d16cc5d370ce8244e757eb7d6 | experiments in import-time shape checking | [
{
"change_type": "MODIFY",
"old_path": "mask.py",
"new_path": "mask.py",
"diff": "from __future__ import print_function\nfrom collections import defaultdict, Counter, namedtuple\n-from functools import partial\n+from functools import partial, wraps\nimport itertools as it\nimport operator as op\nimport string\n@@ -11,7 +11,7 @@ import six\nfrom jax import core\nfrom jax.core import Trace, Tracer\n-from jax.util import unzip2, safe_map, safe_zip, split_list\n+from jax.util import unzip2, safe_map, safe_zip, split_list, curry\nfrom jax.api_util import tree_flatten, tree_unflatten, flatten_fun_nokwargs\nfrom jax import linear_util as lu\nfrom jax.abstract_arrays import ShapedArray\n@@ -154,12 +154,12 @@ print(Shape('m + n * k')) # ShapeExpr(m + k n)\nprint(Shape('m + 3 * k')) # ShapeExpr(3 k + n)\n-### tracer machinery\n+### automasking tracer machinery\nShapeEnvs = namedtuple(\"ShapeEnvs\", [\"logical\", \"padded\"])\nclass MaskTracer(Tracer):\n- __slots__ = [\"val\", \"shape_expr\", \"shape_envs\", \"log_shape_env\"]\n+ __slots__ = [\"val\", \"shape_expr\", \"shape_envs\"]\ndef __init__(self, trace, shape_envs, val, shape_expr):\nself.trace = trace\n@@ -253,7 +253,7 @@ def defvectorized(prim):\nshape_rules[prim] = vectorized_shape_rule\nmasking_rules[prim] = partial(vectorized_masking_rule, prim)\n-def vectorized_shape_rule(shape_exprs):\n+def vectorized_shape_rule(shape_exprs, **unused_params):\nshape_expr, = shape_exprs\nreturn shape_expr\n@@ -268,6 +268,7 @@ defvectorized(lax.cos_p)\ndefvectorized(lax.exp_p)\ndefvectorized(lax.log_p)\ndefvectorized(lax.tanh_p)\n+defvectorized(lax.convert_element_type_p)\ndef dot_shape_rule(shape_exprs, precision):\n@@ -369,6 +370,7 @@ def reshape_shape_rule(shape_exprs, new_sizes, dimensions, old_sizes):\nshape_expr, = shape_exprs\nif prod(shape_expr) != prod(new_sizes): raise ShapeError\nreturn new_sizes\n+shape_rules[lax.reshape_p] = reshape_shape_rule\ndef concat_shape_rule(shape_exprs, dimension, operand_shapes):\n@@ -416,6 +418,7 @@ def mask(fun, in_shapes, out_shape):\nreturn wrapped_fun\ndef _bind_shapes(shape_exprs, shapes):\n+ # TODO this assumes input shape exprs are just binders\nenv = {}\nfor binders, shape in zip(shape_exprs, shapes):\nfor poly, d in zip(binders, shape):\n@@ -482,21 +485,95 @@ y = onp.arange(12, dtype=onp.float32).reshape((3, 4))\nprint(dot([x, y], dict(m=2, k=2, n=2))[:2, :2])\nprint(onp.dot(x[:2, :2], y[:2, :2]))\n-# notes!\n-# - a shape variable is associated with a max size and a dynamic size. we carry\n-# around the dynamic size explicitly in the shape_env attached to every\n-# tracer, while the max size we get off the val\n-# - we don't want to do the padding at the start and slicing at the end in the\n-# transformation because we want to be able to vmap it, also want to jit it\n-# - we could have a ragged array data type, or other api options\n-# - we should probably pass the max size explicitly rather than getting it off\n-# the values, e.g. the iota problem, should think of it as an independent type\n-# argument\n-\n# next steps:\n-# 0. generic test setup\n-# 1. clean up shape expression language (maybe handle reshape/conat)\n+# 0. reshape!\n+# 1. generic test setup\n# 2. write example colab with two applications:\n# (a) batching ragged sequences\n# (b) jit bucketing\n+\n+\n+### definition-time shape checker tracer machinery\n+\n+class ShapeCheckTracer(Tracer):\n+ __slots__ = [\"shape_expr\", \"dtype\"]\n+\n+ def __init__(self, trace, shape_expr):\n+ self.trace = trace\n+ self.shape_expr = shape_expr\n+ self.dtype = None # TODO dtypes\n+\n+ @property\n+ def aval(self):\n+ return ShapedArray(self.shape_expr, self.dtype)\n+\n+ def full_lower(self):\n+ return self\n+\n+class ShapeCheckTrace(Trace):\n+ def pure(self, val):\n+ return ShapeCheckTracer(self, Shape(*onp.shape(val)), onp.result_type(val))\n+\n+ def lift(self, val):\n+ return ShapeCheckTracer(self, Shape(*onp.shape(val)), onp.result_type(val))\n+\n+ def sublift(self, val):\n+ return ShapeCheckTracer(self, val.shape_expr, val.dtype)\n+\n+ def process_primitive(self, primitive, tracers, params):\n+ # TODO dtypes\n+ shape_exprs, dtypes = unzip2((t.shape_expr, t.dtype) for t in tracers)\n+ out_shape_expr = shape_rules[primitive](shape_exprs, **params)\n+ return ShapeCheckTracer(self, out_shape_expr)\n+\n+\n+class F32(object):\n+ def __getitem__(self, idx):\n+ if type(idx) is tuple:\n+ return Shape('(' + ','.join(map(str, idx)) + ')')\n+ else:\n+ return Shape(str(idx))\n+f32 = F32()\n+\n+@curry\n+def check(in_shapes, out_shape, fun):\n+ with core.new_master(ShapeCheckTrace) as master:\n+ out_shape_ = check_subtrace(lu.wrap_init(fun), master).call_wrapped(in_shapes)\n+ del master\n+ if not out_shape_ == out_shape: raise ShapeError\n+ return fun\n+\n+@lu.transformation\n+def check_subtrace(master, in_shapes):\n+ trace = ShapeCheckTrace(master, core.cur_sublevel())\n+ in_tracers = map(partial(ShapeCheckTracer, trace), in_shapes)\n+ out = yield in_tracers, {}\n+ yield trace.full_raise(out).shape_expr\n+\n+\n+@check((f32['m', 'n'], f32['n']), f32['m'])\n+def matvec(A, b):\n+ return np.dot(A, b)\n+\n+try:\n+ @check((f32['m', 'n'], f32['n']), f32['m'])\n+ def matvec(A, b):\n+ return np.dot(b, A)\n+except ShapeError: print(\"good error\")\n+else: raise Exception\n+\n+@check((f32['m', 'n'],), f32['m * n'])\n+def flatten(x):\n+ return lax.reshape(x, (x.shape[0] * x.shape[1],))\n+\n+@check((f32['m'], f32['n'], f32['m']), f32['3*m + n'])\n+def cat(x, y, z):\n+ return lax.concatenate([x, y, x, z], 0)\n+\n+try:\n+ @check((f32['m'], f32['n'], f32['m']), f32['3*m + n'])\n+ def cat(x, y, z):\n+ return lax.concatenate([x, y, x], 0)\n+except ShapeError: print(\"good error\")\n+else: raise Exception\n"
}
] | Python | Apache License 2.0 | google/jax | experiments in import-time shape checking |
260,335 | 03.09.2019 17:18:23 | 25,200 | 96b8bb2d4dffecd805b9b733a75d4f6056b94369 | fix lax._canonicalize_shape for ShapeExprs | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -81,6 +81,9 @@ def _canonicalize_shape(shape):\nReturns:\nA tuple of integers.\n\"\"\"\n+ # TODO(mattjj): this next check is a temporary workaround for masking\n+ if type(shape) is ShapeExpr or any(type(d) is masking.Poly for d in shape):\n+ return shape\ntry:\nreturn tuple(map(operator.index, shape))\nexcept TypeError:\n@@ -582,7 +585,7 @@ def reshape(operand, new_sizes, dimensions=None):\n<https://www.tensorflow.org/xla/operation_semantics#reshape>`_\noperator.\n\"\"\"\n- # new_sizes = _canonicalize_shape(new_sizes) # TODO\n+ new_sizes = _canonicalize_shape(new_sizes) # TODO\nnew_sizes = tuple(new_sizes)\nsame_shape = onp.shape(operand) == new_sizes\nsame_dims = dimensions is None or tuple(dimensions) == tuple(range(onp.ndim(operand)))\n"
}
] | Python | Apache License 2.0 | google/jax | fix lax._canonicalize_shape for ShapeExprs |
260,335 | 03.09.2019 21:56:45 | 25,200 | c3db5d71a7ddbfb9e0e632809ac445c3c40f158d | fix dtype issue, python3 issue, sorting issue | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -99,6 +99,12 @@ class Mon(Counter): # type Mon = Map Id Int -- ids to degrees\nreturn ' '.join('{}**{}'.format(k, v) if v != 1 else str(k)\nfor k, v in sorted(self.items()))\n+ def __lt__(self, other):\n+ # sort by total degree, then lexicographically on indets\n+ self_key = sum(self.values()), tuple(sorted(self))\n+ other_key = sum(other.values()), tuple(sorted(other))\n+ return self_key < other_key\n+\ndef eval_shape_expr(env, expr):\nreturn tuple(eval_dim_expr(env, poly) for poly in expr)\n@@ -145,7 +151,7 @@ def parse_dim(spec):\nelse:\nraise SyntaxError(spec)\ndigits = frozenset(string.digits)\n-identifiers = frozenset(string.lowercase)\n+identifiers = frozenset(string.ascii_lowercase)\ndef parse_id(name): return Poly({Mon({name: 1}): 1})\ndef parse_lit(val_str): return Poly({Mon(): int(val_str)})\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -735,7 +735,7 @@ def _masked_scan_jaxpr(jaxpr, num_consts, num_carry):\nfor new_c, c in zip(new_carry, carry)]\nreturn [i + 1] + new_carry + ys\n- aval = ShapedArray((), onp.int32)\n+ aval = ShapedArray((), onp.int64)\nconst_avals, carry_avals, x_avals = split_list(jaxpr.in_avals, [num_consts, num_carry])\nreturn _make_typed_jaxpr(masked, [aval] + const_avals + [aval] + carry_avals + x_avals)\n@@ -750,8 +750,7 @@ def scan_bind(*args, **kwargs):\nxs_avals = _map(partial(_promote_aval_rank, length), x_avals)\nassert all(_map(typecheck, consts_avals, consts))\nassert all(_map(typecheck, init_avals, init))\n- # assert all(_map(typecheck, xs_avals, xs))\n-\n+ assert all(_map(typecheck, xs_avals, xs))\n# check that output carry type matches input carry type\ncarry_avals, _ = split_list(jaxpr.out_avals, [num_carry])\nassert all(_map(typematch, init_avals, carry_avals))\n"
}
] | Python | Apache License 2.0 | google/jax | fix dtype issue, python3 issue, sorting issue |
260,677 | 05.09.2019 15:22:36 | -3,600 | b819bff1d3afe74320eba451dd3d79fc6854c8d6 | Imports for custom_transforms and defjvp
Can't really do this if we don't have the right imports... | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/linalg.py",
"new_path": "jax/numpy/linalg.py",
"diff": "@@ -27,6 +27,7 @@ from .. import lax_linalg\nfrom .lax_numpy import _not_implemented\nfrom .lax_numpy import _wraps\nfrom . import lax_numpy as np\n+from ..api import custom_transforms, defjvp\nfrom ..util import get_module_functions\nfrom ..lib import xla_bridge\n"
}
] | Python | Apache License 2.0 | google/jax | Imports for custom_transforms and defjvp
Can't really do this if we don't have the right imports... |
260,309 | 05.09.2019 15:10:48 | 25,200 | 8f5cfef407ccd9aa8bf6c1cc4d4d6d24af434b2b | improve numerical stability of softplus grads | [
{
"change_type": "MODIFY",
"old_path": "jax/nn/functions.py",
"new_path": "jax/nn/functions.py",
"diff": "@@ -28,7 +28,7 @@ from jax import jarrett\n# activations\ndef relu(x): return np.maximum(x, 0)\n-def softplus(x): return np.logaddexp(x, 0)\n+def softplus(x): return np.log1p(np.exp(x))\ndef soft_sign(x): return x / (np.abs(x) + 1)\ndef sigmoid(x): return expit(x)\ndef swish(x): return x * sigmoid(x)\n"
}
] | Python | Apache License 2.0 | google/jax | improve numerical stability of softplus grads |
260,296 | 06.09.2019 20:30:30 | 25,200 | dbea4b6f976d9963854017bb5f5c30d84a27c022 | Fix typos
Hit these when trying to debug NaNs, appear to be just typos. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -197,7 +197,7 @@ def compile_jaxpr(jaxpr, device_assignment, backend, axis_env, const_vals, *abst\nif axis_env.nreps > xb.device_count(backend):\nmsg = (\"compiling computation that requires {} replicas, but only {} XLA \"\n\"devices are available\")\n- raise ValueErrr(msg.format(axis_env.nreps, xb.device_count(backend)))\n+ raise ValueError(msg.format(axis_env.nreps, xb.device_count(backend)))\narg_shapes = tuple(map(aval_to_xla_shape, abstract_args))\nbuilt_c = jaxpr_computation(jaxpr, backend, axis_env, const_vals, (), *arg_shapes)\ncompile_opts = xb.get_compile_options(num_replicas=axis_env.nreps,\n@@ -401,14 +401,14 @@ def _execute_compiled(compiled, backend, handlers, *args):\ndevice_num, = compiled.DeviceOrdinals()\ninput_bufs = [device_put(x, device_num, backend=backend) for x in args]\nout_bufs = compiled.Execute(input_bufs).destructure()\n- if FLAGS.jax_debug_nans: check_nans(xla_call_p, out_buf)\n+ if FLAGS.jax_debug_nans: check_nans(xla_call_p, out_bufs)\nreturn [handler(out_buf) for handler, out_buf in zip(handlers, out_bufs)]\ndef _execute_replicated(compiled, backend, handlers, *args):\ninput_bufs = [[device_put(x, i, backend=backend) for x in args]\nfor i in compiled.DeviceOrdinals()]\nout_bufs = compiled.ExecutePerReplica(input_bufs)[0].destructure()\n- if FLAGS.jax_debug_nans: check_nans(xla_call_p, out_buf)\n+ if FLAGS.jax_debug_nans: check_nans(xla_call_p, out_bufs)\nreturn [handler(out_buf) for handler, out_buf in zip(handlers, out_bufs)]\n"
}
] | Python | Apache License 2.0 | google/jax | Fix typos
Hit these when trying to debug NaNs, appear to be just typos. |
260,296 | 06.09.2019 20:47:02 | 25,200 | 302dcc7e741ba18176ffaa92aefddbb44277b412 | Fix `check_nans` method | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -174,12 +174,12 @@ def _execute_compiled_primitive(prim, compiled, backend, result_handler, *args):\nif FLAGS.jax_debug_nans: check_nans(prim, out_buf)\nreturn result_handler(out_buf)\n-def check_nans(prim, buf):\n+def check_nans(prim, bufs):\nif prim.multiple_results:\n- shapes = buf.shape().tuple_shapes()\n- _map(partial(_check_nans, prim.name), shapes, buf.destructure())\n- else:\n+ for buf in bufs:\n_check_nans(prim.name, buf.shape(), buf)\n+ else:\n+ _check_nans(prim.name, bufs.shape(), bufs)\ndef _check_nans(name, xla_shape, buf):\nif xla_shape.is_tuple():\n"
}
] | Python | Apache License 2.0 | google/jax | Fix `check_nans` method |
260,554 | 08.09.2019 14:19:10 | 25,200 | 6f2d22fddfee26cdb1952d4589d568bbfeac5021 | Tiny change to enable vmap with dimension numbers. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2526,7 +2526,6 @@ def _reshape_batch_rule(batched_args, batch_dims, new_sizes, dimensions, **unuse\nbdim, = batch_dims\noperand = batching.moveaxis(operand, bdim, 0)\nif dimensions is not None:\n- raise NotImplementedError # TODO(mattjj): handle reshape w/ dimensions\ndimensions = (0,) + tuple(onp.add(1, dimensions))\nreturn reshape(operand, operand.shape[:1] + new_sizes, dimensions), 0\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -2538,20 +2538,25 @@ class LaxVmapTest(jtu.JaxTestCase):\nself._CheckBatching(op, 5, bdims, (inshape,), dtype, rng)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_inshape={}_outshape={}_bdims={}\".format(\n+ {\"testcase_name\": \"_inshape={}_outshape={}_dims={}_bdims={}\".format(\njtu.format_shape_dtype_string(arg_shape, dtype),\njtu.format_shape_dtype_string(out_shape, dtype),\n- bdims),\n+ dimensions, bdims),\n\"arg_shape\": arg_shape, \"out_shape\": out_shape, \"dtype\": dtype,\n- \"bdims\": bdims, \"rng\": rng}\n+ \"dimensions\": dimensions, \"bdims\": bdims, \"rng\": rng}\nfor dtype in default_dtypes\n- for arg_shape, out_shape in [\n- [(3, 4), (12,)], [(2, 1, 4), (8,)], [(2, 2, 4), (2, 8)]\n+ for arg_shape, dimensions, out_shape in [\n+ [(3, 4), None, (12,)],\n+ [(2, 1, 4), None, (8,)],\n+ [(2, 2, 4), None, (2, 8)],\n+ [(2, 2, 4), (0, 1, 2), (2, 8)],\n+ [(2, 2, 4), (1, 0, 2), (8, 2)],\n+ [(2, 2, 4), (2, 1, 0), (4, 2, 2)]\n]\nfor bdims in all_bdims(arg_shape)\nfor rng in [jtu.rand_default()]))\n- def testReshape(self, arg_shape, out_shape, dtype, bdims, rng):\n- op = lambda x: lax.reshape(x, out_shape)\n+ def testReshape(self, arg_shape, out_shape, dtype, dimensions, bdims, rng):\n+ op = lambda x: lax.reshape(x, out_shape, dimensions=dimensions)\nself._CheckBatching(op, 10, bdims, (arg_shape,), dtype, rng)\n@parameterized.named_parameters(jtu.cases_from_list(\n"
}
] | Python | Apache License 2.0 | google/jax | Tiny change to enable vmap with dimension numbers. |
260,646 | 09.09.2019 19:54:10 | 0 | bcad02ff8a3aa6b60d88786614fd8d123e1baf36 | Remove 64-bit mode for GPU performance | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ode.py",
"new_path": "jax/experimental/ode.py",
"diff": "@@ -30,7 +30,6 @@ import functools\nimport time\nimport jax\n-from jax.config import config\nfrom jax.flatten_util import ravel_pytree\nimport jax.lax\nimport jax.numpy as np\n@@ -40,8 +39,6 @@ import matplotlib.pyplot as plt\nimport numpy as onp\nimport scipy.integrate as osp_integrate\n-config.update('jax_enable_x64', True)\n-\n# Dopri5 Butcher tableaux\nalpha = np.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0])\n"
}
] | Python | Apache License 2.0 | google/jax | Remove 64-bit mode for GPU performance |
260,335 | 09.09.2019 17:47:15 | 25,200 | 74f6269ee945276ccc3fdaf7089cce3638a3bc18 | make jvp only form JVPTracers with nonzero tangent
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -61,7 +61,9 @@ def jvp_subtrace(master, primals, tangents):\nfor x in list(primals) + list(tangents):\nif isinstance(x, Tracer):\nassert x.trace.level < trace.level\n- ans = yield map(partial(JVPTracer, trace), primals, tangents), {}\n+ in_tracers = [JVPTracer(trace, x, t) if t is not zero else x\n+ for x, t in zip(primals, tangents)]\n+ ans = yield in_tracers, {}\nout_tracers = map(trace.full_raise, ans)\nyield unzip2([(out_tracer.primal, out_tracer.tangent)\nfor out_tracer in out_tracers])\n"
}
] | Python | Apache License 2.0 | google/jax | make jvp only form JVPTracers with nonzero tangent
fixes #1316 |
260,403 | 10.09.2019 23:25:12 | 25,200 | 53d4283df5327474da0b8f88daead556042039d9 | fix xla shape-checking error message | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -162,7 +162,7 @@ def primitive_computation(prim, *xla_shapes, **params):\ntry:\nreturn c.Build()\nexcept RuntimeError as e:\n- msg = (e.message + \"\\n\"\n+ msg = (\" \".join(map(str, e.args)) + \"\\n\"\n\"This is a bug in JAX's shape-checking rules; please report it!\\n\"\n\"https://github.com/google/jax/issues\\n\")\nraise RuntimeError(msg)\n"
}
] | Python | Apache License 2.0 | google/jax | fix xla shape-checking error message |
260,335 | 11.09.2019 06:01:32 | 25,200 | 6f0e244e9abf949ee2a0f801f36a3b15a1b28d5e | fix vmap-of-pmap bug
thanks and | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -139,10 +139,11 @@ class BatchTrace(Trace):\nis_batched = tuple(d is not not_mapped for d in dims)\nvals = [moveaxis(x, d, 1) if d is not not_mapped and d != 1 else x\nfor x, d in zip(vals, dims)]\n- dims = tuple(not_mapped if d is not_mapped else 1 for d in dims)\n+ dims = tuple(not_mapped if d is not_mapped else 0 for d in dims)\nf, dims_out = batch_subtrace(f, self.master, dims)\nvals_out = map_primitive.bind(f, *vals, **params)\n- return [BatchTracer(self, v, d) for v, d in zip(vals_out, dims_out())]\n+ dims_out = tuple(d + 1 if d is not not_mapped else d for d in dims_out())\n+ return [BatchTracer(self, v, d) for v, d in zip(vals_out, dims_out)]\ndef post_process_call(self, call_primitive, out_tracers, params):\nvals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -27,6 +27,7 @@ import jax.numpy as np\nfrom jax import test_util as jtu\nfrom jax import core\nfrom jax import lax\n+from jax import random\nfrom jax.api import (pmap, soft_pmap, jit, vmap, jvp, grad, make_jaxpr,\nlinearize, device_put)\nfrom jax.lib import xla_bridge\n@@ -473,6 +474,22 @@ class PmapTest(jtu.JaxTestCase):\nbx = vmap(f1)(ax)\nself.assertAllClose(ax, bx, check_dtypes=False)\n+ def testVmapOfPmap2(self):\n+ N_DEVICES = xla_bridge.device_count()\n+ keys = random.split(random.PRNGKey(1), 13) # [13, 2]\n+\n+ @pmap\n+ def g(key):\n+ params = random.normal(key, ())\n+ return 0.\n+\n+ @vmap\n+ def s(keys):\n+ keys = np.broadcast_to(keys, (N_DEVICES,) + keys.shape)\n+ return g(keys)\n+\n+ s(keys)\n+\ndef testVmapOfPmapNonLeadingAxis(self):\ndevice_count = xla_bridge.device_count()\nf0 = lambda x: x\n"
}
] | Python | Apache License 2.0 | google/jax | fix vmap-of-pmap bug
thanks @romanngg and @inoryy |
260,335 | 11.09.2019 06:22:25 | 25,200 | 37323c13ff3abbc8e140142755de809249d2cbff | check output shape in testVmapOfPmap2 | [
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -488,7 +488,8 @@ class PmapTest(jtu.JaxTestCase):\nkeys = np.broadcast_to(keys, (N_DEVICES,) + keys.shape)\nreturn g(keys)\n- s(keys)\n+ ans = s(keys) # doesn't crash\n+ self.assertEqual(ans.shape, (13, N_DEVICES))\ndef testVmapOfPmapNonLeadingAxis(self):\ndevice_count = xla_bridge.device_count()\n"
}
] | Python | Apache License 2.0 | google/jax | check output shape in testVmapOfPmap2 |
260,403 | 11.09.2019 14:15:38 | 25,200 | 4ee28cf95af6d59731725e5b4bd2ba462e013db0 | Make pxla.axis_index return signed indices for type compatibility with other jax indices. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -274,15 +274,19 @@ def _axis_index_partial_eval(trace, _, **params):\n# This partial_eval rule adds the axis_index primitive into the jaxpr formed\n# during pmap lowering. It is like the standard JaxprTrace.process_primitive\n# rule except that we don't attempt to lower out of the trace.\n- out_aval = ShapedArray((), onp.uint32)\n+ out_aval = ShapedArray((), onp.int32)\nout_tracer = pe.JaxprTracer(trace, pe.PartialVal((out_aval, core.unit)), None)\neqn = core.new_jaxpr_eqn([], [out_tracer], axis_index_p, (), 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+ return c.ConvertElementType(unsigned_index, xb.dtype_to_etype(onp.int32))\n+\naxis_index_p = core.Primitive('axis_index')\n-xla.translations[axis_index_p] = lambda c, hard_size, soft_size, axis_name: \\\n- c.Rem(c.ReplicaId(), c.Constant(onp.array(hard_size, onp.uint32)))\n+xla.translations[axis_index_p] = _axis_index_translation_rule\npe.custom_partial_eval_rules[axis_index_p] = _axis_index_partial_eval\n"
}
] | Python | Apache License 2.0 | google/jax | Make pxla.axis_index return signed indices for type compatibility with other jax indices. |
260,335 | 29.08.2019 14:29:49 | 25,200 | 0c3e9ce22a3f79139738376ab294f9649b9261b4 | sketch of root w/ parameterized solvers | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -822,3 +822,27 @@ def _memcpy(axis, num, src, dst, offset):\nreturn fori_loop(0, num, body, dst)\nmasking.masking_rules[lax.concatenate_p] = _concat_masking_rule\n+\n+\n+def root(f, initial_guess, solve=solve, tangent_solve=tangent_solve):\n+ guess_flat, in_tree = tree_flatten((initial_guess,))\n+ guess_avals = tuple(_map(_abstractify, guess_flat))\n+ jaxpr, consts, out_tree = _initial_style_jaxpr(f, in_tree, guess_avals)\n+ assert out_tree == in_tree\n+ out_flat = root_p.bind(*consts, jaxpr=jaxpr, solve=solve,\n+ tangent_solve=tangent_solve)\n+ return tree_unflatten(out_tree, out_flat)\n+\n+def _root_abstract_eval(*args, **kwargs):\n+ del kwargs # Unused.\n+ return args\n+\n+def _root_impl(*args, **kwargs):\n+ jaxpr, solve, _ = split_dict(kwargs, ['jaxpr', 'solve', 'tangent_solve'])\n+ f = core.jaxpr_as_fun(jaxpr)\n+ return solve(f, args)\n+\n+root_p = core.Primitive('root')\n+root_p.multiple_results = True\n+root_p.def_impl = _root_impl\n+xla.initial_style_translations[scan_p] = xla.lower_fun(_root_impl, initial_style=True)\n"
}
] | Python | Apache License 2.0 | google/jax | sketch of root w/ parameterized solvers
Co-authored-by: Stephan Hoyer <shoyer@google.com> |
260,677 | 14.09.2019 14:30:45 | -3,600 | c2750c1be91a9e5f68c29ff92a5c95f07fa47006 | Extended jvp for det to handle inputs with >2 dims | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/linalg.py",
"new_path": "jax/numpy/linalg.py",
"diff": "@@ -86,12 +86,16 @@ def slogdet(a):\nreturn sign, np.real(logdet)\n+def _jvp_det(g, ans, x):\n+ return np.trace(np.linalg.solve(x, g), axis1=-1, axis2=-2)*ans\n+\n+\n@_wraps(onp.linalg.det)\n@custom_transforms\ndef det(a):\nsign, logdet = slogdet(a)\nreturn sign * np.exp(logdet)\n-defjvp(det, lambda g, ans, x: np.trace(np.linalg.solve(x, g))*ans)\n+defjvp(det, _jvp_det)\n@_wraps(onp.linalg.eig)\n"
}
] | Python | Apache License 2.0 | google/jax | Extended jvp for det to handle inputs with >2 dims |
260,677 | 14.09.2019 14:35:27 | -3,600 | 0171eb7c68fc80c38a8f2eacd6ad48c3a7976631 | Replace jvp for det with jvp for slogdet | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/linalg.py",
"new_path": "jax/numpy/linalg.py",
"diff": "@@ -60,7 +60,14 @@ def svd(a, full_matrices=True, compute_uv=True):\nreturn lax_linalg.svd(a, full_matrices, compute_uv)\n+def _jvp_slogdet(g, ans, x):\n+ jvp_sign = np.zeros(x.shape[:-2])\n+ jvp_logdet = np.trace(np.linalg.solve(x, g), axis1=-1, axis2=-2)\n+ return jvp_sign, jvp_logdet\n+\n+\n@_wraps(onp.linalg.slogdet)\n+@custom_transforms\ndef slogdet(a):\na = _promote_arg_dtypes(np.asarray(a))\ndtype = lax.dtype(a)\n@@ -84,18 +91,13 @@ def slogdet(a):\nis_zero, np.array(-np.inf, dtype=dtype),\nnp.sum(np.log(np.abs(diag)), axis=-1))\nreturn sign, np.real(logdet)\n-\n-\n-def _jvp_det(g, ans, x):\n- return np.trace(np.linalg.solve(x, g), axis1=-1, axis2=-2)*ans\n+defjvp(slogdet, _jvp_slogdet)\n@_wraps(onp.linalg.det)\n-@custom_transforms\ndef det(a):\nsign, logdet = slogdet(a)\nreturn sign * np.exp(logdet)\n-defjvp(det, _jvp_det)\n@_wraps(onp.linalg.eig)\n"
}
] | Python | Apache License 2.0 | google/jax | Replace jvp for det with jvp for slogdet |
260,335 | 15.09.2019 08:45:58 | 25,200 | 5b6b72c2fb38c331199afef391a498662d4565f7 | fix broadcasting bug in rem jvp, fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1725,7 +1725,7 @@ ad.primitive_transposes[div_p] = _div_transpose_rule\nrem_p = standard_binop([_num, _num], 'rem')\nad.defjvp(rem_p,\nlambda g, x, y: _brcast(g, y),\n- lambda g, x, y: mul(neg(g), floor(div(x, y))))\n+ lambda g, x, y: mul(_brcast(neg(g), x), floor(div(x, y))))\ndef _broadcasting_select(c, which, x, y):\n"
}
] | Python | Apache License 2.0 | google/jax | fix broadcasting bug in rem jvp, fixes #1350 |
260,335 | 15.09.2019 09:24:00 | 25,200 | e945c9c11eb8b00d7c5fa80b472c181950aed946 | add some 'manual' lax.rem autodiff tests | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1501,8 +1501,6 @@ LAX_GRAD_OPS = [\ndtypes=[onp.float64]),\ngrad_test_spec(lax.round, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64]),\n- # grad_test_spec(lax.rem, nargs=2, order=2, rng=jtu.rand_default(),\n- # dtypes=[onp.float64]), # TODO(mattjj): enable\ngrad_test_spec(lax.exp, nargs=1, order=2, rng=jtu.rand_small(),\ndtypes=[onp.float64, onp.complex64]),\n@@ -2287,6 +2285,22 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nexpected = onp.array(0.0)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ # TODO(mattjj): make this a more systematic test\n+ def testRemainder(self):\n+ rng = onp.random.RandomState(0)\n+ x = rng.uniform(-0.9, 9, size=(3, 4))\n+ y = rng.uniform(0.7, 1.9, size=(3, 1))\n+ assert not set(onp.unique(x)) & set(onp.unique(y))\n+ tol = 1e-1 if num_float_bits(onp.float64) == 32 else 1e-3\n+ check_grads(lax.rem, (x, y), 2, [\"fwd\", \"rev\"], tol, tol)\n+\n+ rng = onp.random.RandomState(0)\n+ x = rng.uniform(-0.9, 9, size=(1, 4))\n+ y = rng.uniform(0.7, 1.9, size=(3, 4))\n+ assert not set(onp.unique(x)) & set(onp.unique(y))\n+ tol = 1e-1 if num_float_bits(onp.float64) == 32 else 1e-3\n+ check_grads(lax.rem, (x, y), 2, [\"fwd\", \"rev\"], tol, tol)\n+\ndef all_bdims(*shapes):\nbdims = (itertools.chain([None], range(len(shape) + 1)) for shape in shapes)\n"
}
] | Python | Apache License 2.0 | google/jax | add some 'manual' lax.rem autodiff tests |
260,335 | 11.09.2019 21:57:54 | 25,200 | 78c70ecd0ccacc64531ddc22f2eab161bd0218fc | add dynamic shape envs | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -872,22 +872,25 @@ def _parallelize(fun):\ndef mask(fun, in_shapes, out_shape):\n- in_shapes_flat, in_shapes_tree = tree_flatten(in_shapes)\n- out_shapes_flat, out_shapes_tree = tree_flatten(out_shape)\n+ in_shapes, in_shapes_tree = tree_flatten(in_shapes)\n+ out_shapes, out_shapes_tree = tree_flatten(out_shape)\n- def wrapped_fun(args, logical_shape_env):\n+ unique_ids, in_shapes = masking.rename_ids(in_shapes)\n+ out_shapes = masking.remap_ids(unique_ids, out_shapes)\n+\n+ def wrapped_fun(args, logical_env):\n+ logical_env = {unique_ids[name] : val for name, val in logical_env.items()}\nf = lu.wrap_init(fun)\nargs_flat, in_tree = tree_flatten(args)\nassert in_tree == in_shapes_tree\n- padded_shape_env = _bind_shapes(in_shapes_flat, [x.shape for x in args_flat])\n- shape_envs = masking.ShapeEnvs(logical_shape_env, padded_shape_env)\n+ padded_env = _bind_shapes(in_shapes, [x.shape for x in args_flat])\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\n- outs, out_shapes_ = masking.mask_fun(flat_fun, shape_envs, args_flat,\n- in_shapes_flat)\n- if not out_shapes_flat == list(out_shapes_):\n+ outs, out_shapes_ = masking.mask_fun(\n+ flat_fun, logical_env, padded_env, args_flat, in_shapes)\n+ if not out_shapes == list(out_shapes_):\nraise TypeError(\"pytree mismatch\")\n- if not all(out.shape == masking.eval_shape_expr(padded_shape_env, expr)\n- for out, expr in zip(outs, out_shapes_flat)):\n+ if not all(out.shape == masking.eval_shape_expr(padded_env, expr)\n+ for out, expr in zip(outs, out_shapes)):\nraise masking.ShapeError\nreturn tree_unflatten(out_tree(), outs)\nreturn wrapped_fun\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "from __future__ import print_function\n+from contextlib import contextmanager\nfrom collections import defaultdict, Counter, namedtuple\nfrom functools import partial, wraps\nimport itertools as it\n@@ -41,24 +42,54 @@ def prod(xs):\n### main transformation functions\n-def mask_fun(fun, shape_envs, in_vals, shape_exprs):\n+ShapeEnvs = namedtuple(\"ShapeEnvs\", [\"logical\", \"padded\"])\n+shape_envs = ShapeEnvs({}, {})\n+\n+@contextmanager\n+def extend_shape_envs(logical_env, padded_env):\n+ global shape_envs\n+ new_logical = dict(it.chain(shape_envs.logical.items(), logical_env.items()))\n+ new_padded = dict(it.chain(shape_envs.padded.items(), padded_env.items()))\n+ shape_envs, prev = ShapeEnvs(new_logical, new_padded), shape_envs\n+ yield\n+ shape_envs = prev\n+\n+def shape_as_value(expr):\n+ return eval_shape_expr(shape_envs.logical, expr)\n+\n+def padded_shape_as_value(expr):\n+ return eval_shape_expr(shape_envs.padded, expr)\n+\n+\n+def mask_fun(fun, logical_env, padded_env, in_vals, shape_exprs):\nwith core.new_master(MaskTrace) as master:\n- fun, out_shapes = mask_subtrace(fun, master, shape_envs)\n+ fun, out_shapes = mask_subtrace(fun, master)\n+ with extend_shape_envs(logical_env, padded_env):\nout_vals = fun.call_wrapped(in_vals, shape_exprs)\ndel master\nreturn out_vals, out_shapes()\n@lu.transformation_with_aux\n-def mask_subtrace(master, shape_envs, in_vals, shape_exprs):\n+def mask_subtrace(master, in_vals, shape_exprs):\ntrace = MaskTrace(master, core.cur_sublevel())\n- in_tracers = map(partial(MaskTracer, trace, shape_envs),\n- in_vals, shape_exprs)\n+ in_tracers = map(partial(MaskTracer, trace), in_vals, shape_exprs)\nouts = yield in_tracers, {}\nout_tracers = map(trace.full_raise, outs)\nout_vals, out_shapes = unzip2((t.val, t.shape_expr) for t in out_tracers)\nyield out_vals, out_shapes\n+def rename_ids(shapes):\n+ names = defaultdict(object)\n+ return names, remap_ids(names, shapes)\n+\n+def remap_ids(names, shapes):\n+ return [ShapeExpr(Poly({Mon({names[id] : deg for id, deg in mon.items()})\n+ : coeff for mon, coeff in poly.items()})\n+ for poly in shape_expr)\n+ for shape_expr in shapes]\n+\n+\n### shape expressions\n# Shape expressions model tuples of formal polynomials with integer\n@@ -174,14 +205,11 @@ s_ = S_()\n### automasking tracer machinery\n-ShapeEnvs = namedtuple(\"ShapeEnvs\", [\"logical\", \"padded\"])\n-\nclass MaskTracer(Tracer):\n- __slots__ = [\"val\", \"shape_expr\", \"shape_envs\"]\n+ __slots__ = [\"val\", \"shape_expr\"]\n- def __init__(self, trace, shape_envs, val, shape_expr):\n+ def __init__(self, trace, val, shape_expr):\nself.trace = trace\n- self.shape_envs = shape_envs\nself.val = val\nself.shape_expr = shape_expr\n@@ -197,16 +225,15 @@ class MaskTracer(Tracer):\nclass MaskTrace(Trace):\ndef pure(self, val):\n- return MaskTracer(self, None, val, ShapeExpr(*onp.shape(val)))\n+ return MaskTracer(self, val, ShapeExpr(*onp.shape(val)))\ndef lift(self, val):\n- return MaskTracer(self, None, val, ShapeExpr(*onp.shape(val)))\n+ return MaskTracer(self, val, ShapeExpr(*onp.shape(val)))\ndef sublift(self, val):\n- return MaskTracer(self, val.shape_envs, val.val, val.shape_expr)\n+ return MaskTracer(self, val.val, val.shape_expr)\ndef process_primitive(self, primitive, tracers, params):\n- shape_envs = next(t.shape_envs for t in tracers if t.shape_envs is not None)\nvals, shape_exprs = unzip2((t.val, t.shape_expr) for t in tracers)\nif primitive in shape_parameterized_primitive_rules:\nrule = shape_parameterized_primitive_rules[primitive]\n@@ -216,9 +243,9 @@ class MaskTrace(Trace):\nlogical_shapes = map(partial(eval_shape_expr, shape_envs.logical), shape_exprs)\nout = masking_rules[primitive](vals, logical_shapes, **params)\nif not primitive.multiple_results:\n- return MaskTracer(self, shape_envs, out, out_shape)\n+ return MaskTracer(self, out, out_shape)\nelse:\n- return map(partial(MaskTracer, self, shape_envs), out, out_shape)\n+ return map(partial(MaskTracer, self), out, out_shape)\ndef process_call(self, call_primitive, f, tracers, params):\nraise NotImplementedError # TODO mask-of-jit\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -17,13 +17,14 @@ from __future__ import division\nfrom __future__ import print_function\nfrom functools import partial\n+from unittest import SkipTest\nimport numpy as onp\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nfrom jax import test_util as jtu\n-from jax.interpreters.masking import ShapeError\n+from jax.interpreters.masking import ShapeError, shape_as_value\nfrom jax import mask, vmap, jit, Shape, shapecheck, s_\nfrom jax import lax\nimport jax.numpy as np\n@@ -182,6 +183,25 @@ class MaskingTest(jtu.JaxTestCase):\nexpected = onp.dot(x[:2, :2], y[:2, :2])\nself.assertAllClose(ans[:2, :2], expected, check_dtypes=False)\n+ def test_mean(self):\n+ @partial(mask, in_shapes=[Shape('n')], out_shape=Shape())\n+ def padded_sum(x):\n+ return np.sum(x) / shape_as_value(x.shape)[0]\n+\n+ ans = padded_sum([np.array([3, 1, 4, 1, 5])], dict(n=3))\n+ expected = 8 / 3\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def test_arange(self):\n+ raise SkipTest(\"not yet implemented\")\n+ @partial(mask, in_shapes=[Shape('n')], out_shape=Shape('n'))\n+ def padded_add(x):\n+ return x + lax.iota(x.shape[0])\n+\n+ ans = padded_add([np.array([3, 1, 4, 1, 5])], dict(n=3))\n+ expected = onp.array([3, 2, 6])\n+ self.assertAllClose(ans[:3], expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add dynamic shape envs |
260,335 | 13.09.2019 14:36:33 | 25,200 | 283299649b6cb82cda846350b973105f5a4aded7 | add a 'monomorphic dim' symbol, bug fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -60,7 +60,7 @@ from .interpreters import ad\nfrom .interpreters import batching\nfrom .interpreters import parallel\nfrom .interpreters import masking\n-from .interpreters.masking import Shape, s_, shapecheck\n+from .interpreters.masking import shapecheck\nfrom .config import flags, config\nmap = safe_map\n@@ -872,48 +872,71 @@ def _parallelize(fun):\ndef mask(fun, in_shapes, out_shape):\n- in_shapes, in_shapes_tree = tree_flatten(in_shapes)\n- out_shapes, out_shapes_tree = tree_flatten(out_shape)\n+ in_specs, in_shapes_tree = tree_flatten(in_shapes)\n+ out_specs, out_shapes_tree = tree_flatten(out_shape)\n- unique_ids, in_shapes = masking.rename_ids(in_shapes)\n- out_shapes = masking.remap_ids(unique_ids, out_shapes)\n+ in_specs = map(masking.parse_spec, in_specs)\n+ out_specs = map(masking.parse_spec, out_specs)\n+\n+ unique_ids = collections.defaultdict(object)\n+ in_specs = map(partial(_remap_ids, unique_ids), in_specs)\n+ out_specs = map(partial(_remap_ids, unique_ids), out_specs)\ndef wrapped_fun(args, logical_env):\n- logical_env = {unique_ids[name] : val for name, val in logical_env.items()}\n- f = lu.wrap_init(fun)\nargs_flat, in_tree = tree_flatten(args)\n- assert in_tree == in_shapes_tree\n+ if in_tree != in_shapes_tree: raise TypeError(\"pytree mismatch\")\n+ logical_env = {unique_ids[name] : val for name, val in logical_env.items()}\n+ in_shapes = map(masking.finalize_spec, in_specs, map(onp.shape, args_flat))\npadded_env = _bind_shapes(in_shapes, [x.shape for x in args_flat])\n+ f = lu.wrap_init(fun)\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\nouts, out_shapes_ = masking.mask_fun(\nflat_fun, logical_env, padded_env, args_flat, in_shapes)\n+ if not out_tree() == out_shapes_tree: raise TypeError(\"pytree mismatch\")\n+ out_shapes = map(masking.finalize_spec, out_specs, map(onp.shape, outs))\nif not out_shapes == list(out_shapes_):\n- raise TypeError(\"pytree mismatch\")\n- if not all(out.shape == masking.eval_shape_expr(padded_env, expr)\n+ raise masking.ShapeError\n+ if not all(onp.shape(out) == masking.eval_shape_expr(padded_env, expr)\nfor out, expr in zip(outs, out_shapes)):\nraise masking.ShapeError\nreturn tree_unflatten(out_tree(), outs)\nreturn wrapped_fun\n+def _remap_ids(names, shape_spec):\n+ ShapeSpec, Poly, Mon = masking.ShapeSpec, masking.Poly, masking.Mon\n+ mdim = masking.monomorphic_dim\n+ return ShapeSpec(Poly({Mon({names[id] : deg for id, deg in mon.items()})\n+ : coeff for mon, coeff in poly.items()})\n+ if poly is not mdim else mdim for poly in shape_spec)\n+\ndef _bind_shapes(shape_exprs, shapes):\nenv = {}\n- for binders, shape in zip(shape_exprs, shapes):\n- for poly, d in zip(binders, shape):\n- (binder,), = poly\n+ for shape_expr, shape in zip(shape_exprs, shapes):\n+ for poly, d in zip(shape_expr, shape):\n+ if masking.is_constant(poly):\n+ continue\n+ else:\n+ (binder,), = poly # TODO generalize to handle striding\nif env.setdefault(binder, d) != d: raise masking.ShapeError\nreturn env\n@curry\ndef shapecheck(in_shapes, out_shape, fun):\n- in_shapes_flat, in_tree = tree_flatten(in_shapes)\n- out_shapes_flat, out_tree = tree_flatten(out_shape)\n+ in_shapes, in_tree = tree_flatten(in_shapes)\n+ in_shapes = map(masking.parse_spec, in_shapes)\n+ out_shapes, out_tree = tree_flatten(out_shape)\n+ out_shapes = map(masking.parse_spec, out_shapes)\nflat_fun, out_tree_ = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\n- out_shapes_flat_ = masking.shapecheck(flat_fun, in_shapes_flat)\n+ out_shapes_ = masking.shapecheck(flat_fun, in_shapes)\nif out_tree != out_tree_(): raise TypeError(\"pytree mismatch\")\n- if out_shapes_flat != out_shapes_flat_: raise masking.ShapeError\n+ if not all(map(_shape_spec_consistent, out_shapes, out_shapes_)):\n+ raise masking.ShapeError\nreturn fun\n+def _shape_spec_consistent(spec, expr):\n+ return all(a == b for a, b in zip(spec, expr) if a is not masking.monomorphic_dim)\n+\ndef jvp(fun, primals, tangents):\n\"\"\"Computes a (forward-mode) Jacobian-vector product of `fun`.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -43,7 +43,7 @@ def prod(xs):\n### main transformation functions\nShapeEnvs = namedtuple(\"ShapeEnvs\", [\"logical\", \"padded\"])\n-shape_envs = ShapeEnvs({}, {})\n+shape_envs = ShapeEnvs({}, {}) # TODO(mattjj): make this a stack for efficiency\n@contextmanager\ndef extend_shape_envs(logical_env, padded_env):\n@@ -72,24 +72,14 @@ def mask_fun(fun, logical_env, padded_env, in_vals, shape_exprs):\n@lu.transformation_with_aux\ndef mask_subtrace(master, in_vals, shape_exprs):\ntrace = MaskTrace(master, core.cur_sublevel())\n- in_tracers = map(partial(MaskTracer, trace), in_vals, shape_exprs)\n+ in_tracers = [MaskTracer(trace, x, s).full_lower()\n+ for x, s in zip(in_vals, shape_exprs)]\nouts = yield in_tracers, {}\nout_tracers = map(trace.full_raise, outs)\nout_vals, out_shapes = unzip2((t.val, t.shape_expr) for t in out_tracers)\nyield out_vals, out_shapes\n-def rename_ids(shapes):\n- names = defaultdict(object)\n- return names, remap_ids(names, shapes)\n-\n-def remap_ids(names, shapes):\n- return [ShapeExpr(Poly({Mon({names[id] : deg for id, deg in mon.items()})\n- : coeff for mon, coeff in poly.items()})\n- for poly in shape_expr)\n- for shape_expr in shapes]\n-\n-\n### shape expressions\n# Shape expressions model tuples of formal polynomials with integer\n@@ -132,10 +122,16 @@ class Mon(Counter): # type Mon = Map Id Int -- ids to degrees\ndef __lt__(self, other):\n# sort by total degree, then lexicographically on indets\n- self_key = sum(self.values()), tuple(sorted(self))\n- other_key = sum(other.values()), tuple(sorted(other))\n+ self_key = self.degree(), tuple(sorted(self))\n+ other_key = other.degree(), tuple(sorted(other))\nreturn self_key < other_key\n+ def degree(self):\n+ return sum(self.values())\n+\n+def concrete_shape(shape):\n+ return ShapeExpr((Poly({Mon(): int(d)}) for d in shape))\n+\ndef eval_shape_expr(env, expr):\nreturn tuple(eval_dim_expr(env, poly) for poly in expr)\n@@ -143,30 +139,49 @@ def eval_dim_expr(env, poly):\nreturn sum(coeff * prod([env[id] ** deg for id, deg in mon.items()])\nfor mon, coeff in poly.items())\n+def is_constant(poly):\n+ try:\n+ ([], _), = poly.items()\n+ return True\n+ except (ValueError, TypeError):\n+ return False\n+\nclass ShapeError(Exception): pass\n# To denote some shape expressions (for annotations) we use a small language.\n#\n-# data Shape = Shape [Dim]\n+# data ShapeSpec = ShapeSpec [Dim]\n# data Dim = Id Str\n# | Lit Int\n# | Mul Dim Dim\n# | Add Dim Dim\n-\n+# | MonomorphicDim\n+#\n# We'll also make a simple concrete syntax for annotation. The grammar is\n#\n# shape_spec ::= '(' dims ')'\n# dims ::= dim ',' dims | ''\n-# dim ::= str | int | dim '*' dim | dim '+' dim\n+# dim ::= str | int | dim '*' dim | dim '+' dim | '_'\n+#\n+# ShapeSpecs encode ShapeExprs but can have some monomorphic dims inside them,\n+# which must be replaced with concrete shapes when known.\n+\n+class ShapeSpec(list):\n+ def __str__(self):\n+ return 'ShapeSpec({})'.format(', '.join(map(str, self)))\n+\n+def finalize_spec(spec, shape):\n+ return ShapeExpr(parse_lit(d) if e is monomorphic_dim else e\n+ for e, d in zip(spec, shape))\ndef parse_spec(spec=''):\nif not spec:\n- return ShapeExpr(())\n+ return ShapeSpec(())\nif spec[0] == '(':\nif spec[-1] != ')': raise SyntaxError(spec)\nspec = spec[1:-1]\ndims = map(parse_dim, spec.replace(' ', '').strip(',').split(','))\n- return ShapeExpr(dims)\n+ return ShapeSpec(dims)\ndef parse_dim(spec):\nif '+' in spec:\n@@ -179,6 +194,8 @@ def parse_dim(spec):\nreturn parse_lit(spec)\nelif spec in identifiers:\nreturn parse_id(spec)\n+ elif spec == '_':\n+ return monomorphic_dim\nelse:\nraise SyntaxError(spec)\ndigits = frozenset(string.digits)\n@@ -187,13 +204,15 @@ identifiers = frozenset(string.ascii_lowercase)\ndef parse_id(name): return Poly({Mon({name: 1}): 1})\ndef parse_lit(val_str): return Poly({Mon(): int(val_str)})\n+class MonomorphicDim(object):\n+ def __str__(self): return '_'\n+monomorphic_dim = MonomorphicDim()\n+\n# Two convenient ways to provide shape annotations:\n-# 1. Shape('(m, n)')\n+# 1. '(m, n)'\n# 2. s_['m', 'n']\n-Shape = parse_spec\n-\nclass S_(object):\ndef __getitem__(self, idx):\nif type(idx) is tuple:\n@@ -217,18 +236,21 @@ class MaskTracer(Tracer):\ndef aval(self):\nreturn ShapedArray(self.shape_expr, self.val.dtype)\n+ def is_pure(self):\n+ return all(is_constant(poly) for poly in self.shape_expr)\n+\ndef full_lower(self):\n- if all(type(s) is int for s in self.shape_expr):\n+ if self.is_pure():\nreturn core.full_lower(self.val)\nelse:\nreturn self\nclass MaskTrace(Trace):\ndef pure(self, val):\n- return MaskTracer(self, val, ShapeExpr(*onp.shape(val)))\n+ return MaskTracer(self, val, concrete_shape(onp.shape(val)))\ndef lift(self, val):\n- return MaskTracer(self, val, ShapeExpr(*onp.shape(val)))\n+ return MaskTracer(self, val, concrete_shape(onp.shape(val)))\ndef sublift(self, val):\nreturn MaskTracer(self, val.val, val.shape_expr)\n@@ -300,6 +322,7 @@ def check_subtrace(master, in_shapes):\nyield [t.shape_expr for t in out_tracers]\n+# TODO(mattjj): add dtypes?\nclass ShapeCheckTracer(Tracer):\n__slots__ = [\"shape_expr\"]\n@@ -316,10 +339,10 @@ class ShapeCheckTracer(Tracer):\nclass ShapeCheckTrace(Trace):\ndef pure(self, val):\n- return ShapeCheckTracer(self, Shape(*onp.shape(val)), onp.result_type(val))\n+ return ShapeCheckTracer(self, concrete_shape(onp.shape(val)))\ndef lift(self, val):\n- return ShapeCheckTracer(self, Shape(*onp.shape(val)), onp.result_type(val))\n+ return ShapeCheckTracer(self, concrete_shape(onp.shape(val)))\ndef sublift(self, val):\nreturn ShapeCheckTracer(self, val.shape_expr)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3355,7 +3355,7 @@ def _masking_defreducer(prim, identity_like):\ndef _reducer_polymorphic_shape_rule(shape_exprs, axes, **unused_params):\nshape_expr, = shape_exprs\n- return ShapeExpr(*(d for i, d in enumerate(shape_expr) if i not in axes))\n+ return ShapeExpr([d for i, d in enumerate(shape_expr) if i not in axes])\ndef _reducer_masking_rule(prim, identity_like, padded_vals, logical_shapes,\naxes, input_shape):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -24,8 +24,8 @@ from absl.testing import absltest\nfrom absl.testing import parameterized\nfrom jax import test_util as jtu\n-from jax.interpreters.masking import ShapeError, shape_as_value\n-from jax import mask, vmap, jit, Shape, shapecheck, s_\n+from jax.interpreters.masking import ShapeError, shape_as_value, parse_spec\n+from jax import mask, vmap, jit, shapecheck\nfrom jax import lax\nimport jax.numpy as np\n@@ -38,48 +38,53 @@ config.parse_flags_with_absl()\nclass MaskingTest(jtu.JaxTestCase):\n- def test_shape_parsing(self):\n- self.assertEqual(str(Shape('(m, n)')), 'ShapeExpr(m, n)')\n- self.assertEqual(str(Shape('(m * n)')), 'ShapeExpr(m n)')\n- self.assertEqual(str(Shape('m * n')), 'ShapeExpr(m n)')\n- self.assertEqual(str(Shape('(m * n,)')), 'ShapeExpr(m n)')\n- self.assertEqual(str(Shape('(3, m)')), 'ShapeExpr(3, m)')\n- self.assertEqual(str(Shape('(3 * m)')), 'ShapeExpr(3 m)')\n- self.assertEqual(str(Shape('m')), 'ShapeExpr(m)')\n- self.assertEqual(str(Shape('')), 'ShapeExpr()')\n- self.assertEqual(str(Shape('m + n')), 'ShapeExpr(m + n)')\n- self.assertEqual(str(Shape('m + n * k')), 'ShapeExpr(m + k n)')\n- self.assertEqual(str(Shape('m + 3 * k')), 'ShapeExpr(3 k + m)')\n+ @parameterized.parameters([\n+ ['(m, n)', 'ShapeSpec(m, n)'],\n+ ['(m * n)', 'ShapeSpec(m n)'],\n+ ['m * n', 'ShapeSpec(m n)'],\n+ ['(m * n,)', 'ShapeSpec(m n)'],\n+ ['(3, m)', 'ShapeSpec(3, m)'],\n+ ['(3 * m)', 'ShapeSpec(3 m)'],\n+ ['m', 'ShapeSpec(m)'],\n+ ['', 'ShapeSpec()'],\n+ ['m + n', 'ShapeSpec(m + n)'],\n+ ['m + n * k', 'ShapeSpec(m + k n)'],\n+ ['m + 3 * k', 'ShapeSpec(3 k + m)'],\n+ ['', 'ShapeSpec()'],\n+ ['_', 'ShapeSpec(_)'],\n+ ])\n+ def test_shape_parsing(self, spec, ans):\n+ self.assertEqual(str(parse_spec(spec)), ans)\ndef test_dot_shape_checking(self):\n- @shapecheck((s_['m', 'n'], s_['n']), s_['m'])\n+ @shapecheck(['(m, n)', 'n'], 'm')\ndef matvec(A, b):\nreturn np.dot(A, b)\ndef thunk():\n- @shapecheck((s_['m', 'n'], s_['n']), s_['m'])\n+ @shapecheck(['(m, n)', 'n'], 'm')\ndef matvec(A, b):\nreturn np.dot(b, A)\nself.assertRaisesRegex(ShapeError, \"\", thunk)\ndef test_flatten_shape_checking(self):\n- @shapecheck((s_['m', 'n'],), s_['m * n'])\n+ @shapecheck(['(m, n)'], 'm * n')\ndef flatten(x):\nreturn lax.reshape(x, (x.shape[0] * x.shape[1],))\ndef test_concatenate_shape_checking(self):\n- @shapecheck((s_['m'], s_['n'], s_['m']), s_['3*m + n'])\n+ @shapecheck(['m', 'n', 'm'], '3*m + n')\ndef cat(x, y, z):\nreturn lax.concatenate([x, y, x, z], 0)\ndef thunk():\n- @shapecheck((s_['m'], s_['n'], s_['m']), s_['3*m + n'])\n+ @shapecheck(['m', 'n', 'm'], '3*m + n')\ndef cat(x, y, z):\nreturn lax.concatenate([x, y, x], 0)\nself.assertRaisesRegex(ShapeError, \"\", thunk)\ndef test_sum(self):\n- @partial(mask, in_shapes=[Shape('n')], out_shape=Shape())\n+ @partial(mask, in_shapes=['n'], out_shape='')\ndef padded_sum(x):\nreturn np.sum(x)\n@@ -92,7 +97,7 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef test_sum_vmap(self):\n- @partial(mask, in_shapes=[Shape('n')], out_shape=Shape())\n+ @partial(mask, in_shapes=['n'], out_shape='')\ndef padded_sum(x):\nreturn np.sum(x)\n@@ -101,7 +106,7 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef test_add(self):\n- @partial(mask, in_shapes=[Shape('n'), Shape('n')], out_shape=Shape('n'))\n+ @partial(mask, in_shapes=['n', 'n'], out_shape='n')\ndef addvecs(x, y):\nreturn x + y\n@@ -115,7 +120,7 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertRaisesRegex(ShapeError, \"\", thunk)\ndef test_scan(self):\n- @partial(mask, in_shapes=[Shape('n')], out_shape=Shape())\n+ @partial(mask, in_shapes=['n'], out_shape='')\ndef cumsum(arr):\nout, _ = lax.scan(lambda c, x: (c + x, ()), 0, arr)\nreturn out\n@@ -125,7 +130,7 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef test_scan_vmap(self):\n- @partial(mask, in_shapes=[Shape('n')], out_shape=Shape())\n+ @partial(mask, in_shapes=['n'], out_shape='')\ndef cumsum(arr):\nout, _ = lax.scan(lambda c, x: (c + x, ()), 0, arr)\nreturn out\n@@ -135,7 +140,7 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef test_scan_jit(self):\n- @partial(mask, in_shapes=[Shape('n')], out_shape=Shape())\n+ @partial(mask, in_shapes=['n'], out_shape='')\ndef cumsum(arr):\nout, _ = lax.scan(lambda c, x: (c + x, ()), 0, arr)\nreturn out\n@@ -161,8 +166,7 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef test_concatenate(self):\n- @partial(mask, in_shapes=[Shape('n'), Shape('m'), Shape('n')],\n- out_shape=Shape('m + 2 * n'))\n+ @partial(mask, in_shapes=['n', 'm', 'n'], out_shape='m + 2 * n')\ndef cat(x, y, z):\nreturn lax.concatenate([x, y, z], 0)\n@@ -172,8 +176,7 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertAllClose(ans[:4], expected, check_dtypes=False)\ndef test_dot(self):\n- @partial(mask, in_shapes=[Shape('(m, k)'), Shape(('k, n'))],\n- out_shape=[Shape('(m, n)')])\n+ @partial(mask, in_shapes=['(m, k)', '(k, n)'], out_shape='(m, n)')\ndef dot(x, y):\nreturn lax.dot(x, y)\n@@ -184,7 +187,7 @@ class MaskingTest(jtu.JaxTestCase):\nself.assertAllClose(ans[:2, :2], expected, check_dtypes=False)\ndef test_mean(self):\n- @partial(mask, in_shapes=[Shape('n')], out_shape=Shape())\n+ @partial(mask, in_shapes=['n'], out_shape='')\ndef padded_sum(x):\nreturn np.sum(x) / shape_as_value(x.shape)[0]\n@@ -192,9 +195,36 @@ class MaskingTest(jtu.JaxTestCase):\nexpected = 8 / 3\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_monomorphic(self):\n+ @partial(mask, in_shapes=['(_, n)'], out_shape='')\n+ def padded_sum(x):\n+ return np.sum(x)\n+\n+ ans = padded_sum([np.array([[3, 4], [5, 6]])], dict(n=1))\n+ expected = 8\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def test_monomorphic2(self):\n+ @partial(mask, in_shapes=['(_, n)'], out_shape='n')\n+ def padded_sum(x):\n+ return np.sum(x, axis=0)\n+\n+ ans = padded_sum([np.array([[3, 4], [5, 6]])], dict(n=2))\n+ expected = np.array([8, 10])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def test_monomorphic3(self):\n+ @partial(mask, in_shapes=['(_, n)'], out_shape='_')\n+ def padded_sum(x):\n+ return np.sum(x, axis=1)\n+\n+ ans = padded_sum([np.array([[3, 4], [5, 6]])], dict(n=1))\n+ expected = np.array([3, 5])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef test_arange(self):\nraise SkipTest(\"not yet implemented\")\n- @partial(mask, in_shapes=[Shape('n')], out_shape=Shape('n'))\n+ @partial(mask, in_shapes=['n'], out_shape='n')\ndef padded_add(x):\nreturn x + lax.iota(x.shape[0])\n"
}
] | Python | Apache License 2.0 | google/jax | add a 'monomorphic dim' symbol, bug fixes |
260,335 | 13.09.2019 16:30:22 | 25,200 | b71181d3c08eb3c89403e14068843aeb401144ad | start writing nesting test | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -55,10 +55,16 @@ def extend_shape_envs(logical_env, padded_env):\nshape_envs = prev\ndef shape_as_value(expr):\n+ if type(expr) is ShapeExpr:\nreturn eval_shape_expr(shape_envs.logical, expr)\n+ else:\n+ return expr\ndef padded_shape_as_value(expr):\n+ if type(expr) is ShapeExpr:\nreturn eval_shape_expr(shape_envs.padded, expr)\n+ else:\n+ return expr\ndef mask_fun(fun, logical_env, padded_env, in_vals, shape_exprs):\n@@ -130,7 +136,10 @@ class Mon(Counter): # type Mon = Map Id Int -- ids to degrees\nreturn sum(self.values())\ndef concrete_shape(shape):\n- return ShapeExpr((Poly({Mon(): int(d)}) for d in shape))\n+ if type(shape) is ShapeExpr:\n+ return shape\n+ else:\n+ return ShapeExpr((Poly({Mon(): d}) for d in shape))\ndef eval_shape_expr(env, expr):\nreturn tuple(eval_dim_expr(env, poly) for poly in expr)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3361,11 +3361,12 @@ def _reducer_masking_rule(prim, identity_like, padded_vals, logical_shapes,\naxes, input_shape):\ndel input_shape # Unused.\n(padded_val,), (logical_shape,) = padded_vals, logical_shapes\n- masks = [broadcasted_iota(onp.int32, padded_val.shape, i) < d\n+ padded_shape = masking.padded_shape_as_value(padded_val.shape)\n+ masks = [broadcasted_iota(onp.int32, padded_shape, i) < d\nfor i, d in enumerate(logical_shape) if i in axes]\nmask = _reduce(operator.and_, masks)\nmasked_val = select(mask, padded_val, identity_like(padded_val))\n- return prim.bind(masked_val, axes=axes, input_shape=padded_val.shape)\n+ return prim.bind(masked_val, axes=axes, input_shape=padded_shape)\nreduce_p = standard_reduction_primitive(_reduce_shape_rule, _input_dtype, 'reduce',\n_reduce_translation_rule)\n@@ -4010,7 +4011,8 @@ tie_in_p.def_abstract_eval(lambda x, y: y)\nxla.translations[tie_in_p] = lambda c, x, y: y\nad.deflinear(tie_in_p, _tie_in_transpose_rule)\nbatching.primitive_batchers[tie_in_p] = _tie_in_batch_rule\n-\n+masking.shape_rules[tie_in_p] = lambda shape_exprs: shape_exprs[1]\n+masking.masking_rules[tie_in_p] = lambda vals, logical_shapes: vals[1]\nshaped_identity_p = Primitive('shape_id')\nshaped_identity_p.def_impl(lambda x, shape: x)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -222,8 +222,23 @@ class MaskingTest(jtu.JaxTestCase):\nexpected = np.array([3, 5])\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_nesting(self):\n+ raise SkipTest(\"not yet implemented\")\n+\n+ @partial(mask, in_shapes=['n'], out_shape='')\n+ def padded_sum(x):\n+ return np.sum(x)\n+\n+ @partial(mask, in_shapes=['n'], out_shape='')\n+ def padded_sum2(x):\n+ return padded_sum([x], dict(n=2))\n+\n+ ans = padded_sum2([np.array([3, 1, 4, 1])], dict(n=1))\n+ import ipdb; ipdb.set_trace()\n+\ndef test_arange(self):\nraise SkipTest(\"not yet implemented\")\n+\n@partial(mask, in_shapes=['n'], out_shape='n')\ndef padded_add(x):\nreturn x + lax.iota(x.shape[0])\n"
}
] | Python | Apache License 2.0 | google/jax | start writing nesting test |
260,335 | 15.09.2019 14:11:15 | 25,200 | 6e22b418e3b625efa5b58a41b29c84476dbca486 | skip problematic tests on tpu | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_indexing_test.py",
"new_path": "tests/lax_numpy_indexing_test.py",
"diff": "@@ -856,6 +856,7 @@ class IndexedUpdateTest(jtu.JaxTestCase):\nfor update_shape in _broadcastable_shapes(_update_shape(shape, indexer))\nfor update_dtype in ([dtype] if op == UpdateOps.ADD else float_dtypes)\nfor rng in [jtu.rand_default()]))\n+ @jtu.skip_on_devices(\"tpu\") # TODO(mattjj,phawkins): tpu issues\ndef testStaticIndexingGrads(self, shape, dtype, update_shape, update_dtype,\nrng, indexer, op):\njax_op = ops.index_update if op == UpdateOps.UPDATE else ops.index_add\n"
}
] | Python | Apache License 2.0 | google/jax | skip problematic tests on tpu |
260,677 | 16.09.2019 21:27:55 | -3,600 | 3e5f7869eaaeab1691f4b3c843c53f8d19bd0bab | Fixed prefix for np.linalg.solve | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/linalg.py",
"new_path": "jax/numpy/linalg.py",
"diff": "@@ -62,7 +62,7 @@ def svd(a, full_matrices=True, compute_uv=True):\ndef _jvp_slogdet(g, ans, x):\njvp_sign = np.zeros(x.shape[:-2])\n- jvp_logdet = np.trace(np.linalg.solve(x, g), axis1=-1, axis2=-2)\n+ jvp_logdet = np.trace(solve(x, g), axis1=-1, axis2=-2)\nreturn jvp_sign, jvp_logdet\n"
}
] | Python | Apache License 2.0 | google/jax | Fixed prefix for np.linalg.solve |
260,627 | 16.09.2019 14:30:28 | 25,200 | 0e7ea7e37938b91f6fc833387a929a1faa5ad9a3 | Reduce memory usage for argmax (fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2232,8 +2232,9 @@ def argmin(a, axis=None):\ndef _argminmax(op, a, axis):\nshape = [1] * a.ndim\nshape[axis] = a.shape[axis]\n- idxs = onp.arange(a.shape[axis]).reshape(shape)\n+ idxs = lax.tie_in(a, arange(a.shape[axis])).reshape(shape)\nmaxval = onp.iinfo(xla_bridge.canonicalize_dtype(idxs.dtype)).max\n+ maxval = lax.tie_in(a, maxval)\nmask_idxs = where(lax._eq_meet(a, op(a, axis, keepdims=True)), idxs, maxval)\nreturn min(mask_idxs, axis)\n"
}
] | Python | Apache License 2.0 | google/jax | Reduce memory usage for argmax (fixes #1330) |
260,335 | 16.09.2019 14:49:31 | 25,200 | 13b1bca94fef09b2399b5597d69ca61e0d79b995 | prevent device_put from being staged into jaxprs | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -681,8 +681,7 @@ def _device_put_impl(x, device_num=0, backend=None):\ndevice_put_p = core.Primitive('device_put')\ndevice_put_p.def_impl(_device_put_impl)\n-device_put_p.def_abstract_eval(lambda x, **kwargs: x)\n-translations[device_put_p] = lambda c, x, **kwargs: x\n+pe.custom_partial_eval_rules[device_put_p] = lambda trace, x, **params: x\nad.deflinear(device_put_p, lambda cotangent, **kwargs: [cotangent])\n"
}
] | Python | Apache License 2.0 | google/jax | prevent device_put from being staged into jaxprs |
260,335 | 16.09.2019 15:47:43 | 25,200 | 6662da827591aba302995fb39c66e342cdefbf55 | tweaks to simplify masked jaxprs, rnn test | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -98,6 +98,11 @@ def mask_subtrace(master, in_vals, shape_exprs):\nclass ShapeExpr(tuple): # type ShapeExpr = [Poly]\ndef __str__(self):\nreturn 'ShapeExpr({})'.format(', '.join(map(str, self)))\n+ def __getitem__(self, idx):\n+ if type(idx) is int:\n+ return super(ShapeExpr, self).__getitem__(idx)\n+ else:\n+ return ShapeExpr(super(ShapeExpr, self).__getitem__(idx))\nclass Poly(Counter): # type Poly = Map Mon Int -- monomials to coeffs\ndef __mul__(p1, p2):\n@@ -145,8 +150,25 @@ def eval_shape_expr(env, expr):\nreturn tuple(eval_dim_expr(env, poly) for poly in expr)\ndef eval_dim_expr(env, poly):\n- return sum(coeff * prod([env[id] ** deg for id, deg in mon.items()])\n- for mon, coeff in poly.items())\n+ terms = [mul(coeff, prod([pow(env[id], deg) for id, deg in mon.items()]))\n+ for mon, coeff in poly.items()]\n+ return sum(terms) if len(terms) > 1 else terms[0]\n+\n+def pow(x, deg):\n+ try:\n+ deg = int(deg)\n+ except:\n+ return x ** deg\n+ else:\n+ return 1 if deg == 0 else x if deg == 1 else x ** deg\n+\n+def mul(coeff, mon):\n+ try:\n+ coeff = int(coeff)\n+ except:\n+ return coeff * mon\n+ else:\n+ return 0 if coeff == 0 else mon if coeff == 1 else coeff * mon\ndef is_constant(poly):\ntry:\n@@ -162,7 +184,7 @@ class ShapeSyntaxError(Exception): pass\n# To denote some shape expressions (for annotations) we use a small language.\n#\n# data ShapeSpec = ShapeSpec [Dim]\n-# data Dim = Id Str\n+# data Dim = Id PyObj\n# | Lit Int\n# | Mul Dim Dim\n# | Add Dim Dim\n@@ -295,10 +317,10 @@ def vectorized_shape_rule(shape_exprs, **unused_params):\nshape_expr, = shape_exprs\nreturn shape_expr\n-def vectorized_masking_rule(prim, padded_vals, logical_shapes):\n+def vectorized_masking_rule(prim, padded_vals, logical_shapes, **params):\ndel logical_shapes # Unused.\npadded_val, = padded_vals\n- return prim.bind(padded_val)\n+ return prim.bind(padded_val, **params)\ndef defbinop(prim):\n@@ -307,8 +329,14 @@ def defbinop(prim):\ndef binop_shape_rule(shape_exprs):\nx_shape_expr, y_shape_expr = shape_exprs\n- if not x_shape_expr == y_shape_expr: raise ShapeError\n+ if x_shape_expr == y_shape_expr:\nreturn x_shape_expr\n+ elif not x_shape_expr:\n+ return y_shape_expr\n+ elif not y_shape_expr:\n+ return x_shape_expr\n+ else:\n+ raise ShapeError\ndef binop_masking_rule(prim, padded_vals, logical_shapes):\ndel logical_shapes # Unused.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3349,15 +3349,15 @@ def _reduction_computation(c, jaxpr, backend, consts, init_value):\nout, = xla.jaxpr_subcomp(subc, jaxpr, backend, axis_env, consts, (), *args)\nreturn subc.Build(out)\n-def _masking_defreducer(prim, identity_like):\n+def _masking_defreducer(prim, identity):\nmasking.shape_rules[prim] = _reducer_polymorphic_shape_rule\n- masking.masking_rules[prim] = partial(_reducer_masking_rule, prim, identity_like)\n+ masking.masking_rules[prim] = partial(_reducer_masking_rule, prim, identity)\ndef _reducer_polymorphic_shape_rule(shape_exprs, axes, **unused_params):\nshape_expr, = shape_exprs\nreturn ShapeExpr([d for i, d in enumerate(shape_expr) if i not in axes])\n-def _reducer_masking_rule(prim, identity_like, padded_vals, logical_shapes,\n+def _reducer_masking_rule(prim, identity, padded_vals, logical_shapes,\naxes, input_shape):\ndel input_shape # Unused.\n(padded_val,), (logical_shape,) = padded_vals, logical_shapes\n@@ -3365,7 +3365,7 @@ def _reducer_masking_rule(prim, identity_like, padded_vals, logical_shapes,\nmasks = [broadcasted_iota(onp.int32, padded_shape, i) < d\nfor i, d in enumerate(logical_shape) if i in axes]\nmask = _reduce(operator.and_, masks)\n- masked_val = select(mask, padded_val, identity_like(padded_val))\n+ masked_val = select(mask, padded_val, identity(padded_shape, padded_val.dtype))\nreturn prim.bind(masked_val, axes=axes, input_shape=padded_shape)\nreduce_p = standard_reduction_primitive(_reduce_shape_rule, _input_dtype, 'reduce',\n@@ -3395,7 +3395,8 @@ reduce_sum_p = standard_primitive(_reduce_sum_shape_rule, _input_dtype,\n'reduce_sum', _reduce_sum_translation_rule)\nad.deflinear(reduce_sum_p, _reduce_sum_transpose_rule)\nbatching.defreducer(reduce_sum_p)\n-_masking_defreducer(reduce_sum_p, zeros_like_array)\n+_masking_defreducer(reduce_sum_p,\n+ lambda shape, dtype: onp.broadcast_to(onp.array(0, dtype), shape))\ndef _reduce_prod_shape_rule(operand, axes):\n@@ -4262,6 +4263,9 @@ def conv_transpose_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\ndef _check_shapelike(fun_name, arg_name, obj):\n\"\"\"Check that `obj` is a shape-like value (e.g. tuple of nonnegative ints).\"\"\"\n+ if (type(obj) is masking.ShapeExpr\n+ or type(obj) is tuple and any(type(d) is masking.Poly for d in obj)):\n+ return obj\nif not isinstance(obj, (tuple, list, onp.ndarray)):\nmsg = \"{} {} must be of type tuple/list/ndarray, got {}.\"\nraise TypeError(msg.format(fun_name, arg_name, type(obj)))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -440,8 +440,9 @@ def scan(f, init, xs):\nraise ValueError(msg.format([x.shape[0] for x in xs_flat]))\ncarry_avals = tuple(_map(_abstractify, init_flat))\n- xs_avals = _map(_abstractify, xs_flat)\n- x_avals = tuple(ShapedArray(aval.shape[1:], aval.dtype) for aval in xs_avals)\n+ x_shapes = [masking.padded_shape_as_value(x.shape[1:]) for x in xs_flat]\n+ x_dtypes = [x.dtype for x in xs_flat]\n+ x_avals = tuple(_map(ShapedArray, x_shapes, x_dtypes))\njaxpr, consts, out_tree = _initial_style_jaxpr(f, in_tree, carry_avals + x_avals)\ncarry_avals_out, y_avals = split_list(jaxpr.out_avals, [num_carry])\nif tuple(carry_avals_out) != carry_avals:\n@@ -698,10 +699,6 @@ def _scan_batching_rule(args, dims, forward, length, jaxpr, num_consts,\ndef _scan_polymorphic_shape_rule(shape_exprs, forward, length, jaxpr,\nnum_consts, num_carry, linear):\nconst_shexprs, init_shexprs, xs_shexprs = split_list(shape_exprs, [num_consts, num_carry])\n- if (any(any(type(d) is Id for d in shexpr) for shexpr in const_shexprs)\n- or any(any(type(d) is Id for d in shexpr) for shexpr in init_shexprs)\n- or any(any(type(d) is Id for d in shexpr[1:]) for shexpr in xs_shexprs)):\n- raise NotImplementedError\n_, y_avals = split_list(jaxpr.out_avals, [num_carry])\nys_shapes = [ShapeExpr(length, *y_aval.shape) for y_aval in y_avals]\nreturn init_shexprs + ys_shapes\n@@ -750,7 +747,7 @@ def scan_bind(*args, **kwargs):\nxs_avals = _map(partial(_promote_aval_rank, length), x_avals)\nassert all(_map(typecheck, consts_avals, consts))\nassert all(_map(typecheck, init_avals, init))\n- assert all(_map(typecheck, xs_avals, xs))\n+ # assert all(_map(typecheck, xs_avals, xs))\n# check that output carry type matches input carry type\ncarry_avals, _ = split_list(jaxpr.out_avals, [num_carry])\nassert all(_map(typematch, init_avals, carry_avals))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -25,7 +25,7 @@ from absl.testing import parameterized\nfrom jax import test_util as jtu\nfrom jax.interpreters.masking import ShapeError, shape_as_value, parse_spec\n-from jax import mask, vmap, jit, shapecheck\n+from jax import mask, vmap, jit, grad, shapecheck\nfrom jax import lax\nimport jax.numpy as np\n@@ -222,6 +222,87 @@ class MaskingTest(jtu.JaxTestCase):\nexpected = np.array([3, 5])\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_rnn(self):\n+ n = 3\n+\n+ @partial(mask, in_shapes=['(_, _)', '(t, _)'], out_shape='_')\n+ def rnn(W, xs):\n+ def step(h, x):\n+ new_h = np.dot(W, h) + np.dot(W, x)\n+ return new_h, ()\n+ predicted, _ = lax.scan(step, np.zeros(n), xs)\n+ return predicted\n+\n+ rng = onp.random.RandomState(0)\n+ W = onp.eye(n)\n+ xs = rng.randn(10, n)\n+ ans = rnn([W, xs], dict(t=4))\n+ expected = xs[:4].sum(0)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def test_rnn_grad(self):\n+ n = 3\n+\n+ @partial(mask, in_shapes=['(_, _)', '(t, _)', '_'], out_shape='')\n+ def rnn(W, xs, target):\n+ def step(h, x):\n+ new_h = np.tanh(np.dot(W, h) + np.dot(W, x))\n+ return new_h, ()\n+ predicted, _ = lax.scan(step, np.zeros(n), xs)\n+ return np.sum((predicted - target)**2)\n+\n+ rng = onp.random.RandomState(0)\n+ W = rng.randn(n, n)\n+ xs = rng.randn(10, n)\n+ y = rng.randn(n)\n+\n+ ans = grad(lambda W: rnn([W, xs, y], dict(t=4)))(W)\n+\n+ def rnn_reference(W, xs, target):\n+ h = np.zeros(n)\n+ for x in xs:\n+ h = np.tanh(np.dot(W, h) + np.dot(W, x))\n+ predicted = h\n+ return np.sum((predicted - target)**2)\n+\n+ expected = grad(lambda W: rnn_reference(W, xs[:4], y))(W)\n+\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def test_ragged_batched_rnn(self):\n+ n = 3\n+\n+ @partial(mask, in_shapes=('(_, _)', '(t, _)', '_'), out_shape='')\n+ def rnn(W, xs, target):\n+ def step(h, x):\n+ new_h = np.tanh(np.dot(W, h) + np.dot(W, x))\n+ return new_h, ()\n+ predicted, _ = lax.scan(step, np.zeros(n), xs)\n+ return np.sum((predicted - target)**2)\n+\n+ rng = onp.random.RandomState(0)\n+ W = rng.randn(n, n)\n+ seqs = rng.randn(3, 10, n)\n+ ts = np.array([2, 5, 4])\n+ ys = rng.randn(3, n)\n+\n+ ans = grad(lambda W: vmap(rnn, ((None, 0, 0), 0))((W, seqs, ys), dict(t=ts)).sum())(W)\n+\n+ def rnn_reference(W, seqs, targets):\n+ total_loss = 0\n+ for xs, target in zip(seqs, targets):\n+ h = np.zeros(n)\n+ for x in xs:\n+ h = np.tanh(np.dot(W, h) + np.dot(W, x))\n+ predicted = h\n+ total_loss = total_loss + np.sum((predicted - target)**2)\n+ return total_loss\n+\n+ seqs_ = [xs[:t] for xs, t in zip(seqs, ts)]\n+ expected = grad(lambda W: rnn_reference(W, seqs_, ys).sum())(W)\n+\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef test_nesting(self):\nraise SkipTest(\"not yet implemented\")\n@@ -229,12 +310,19 @@ class MaskingTest(jtu.JaxTestCase):\ndef padded_sum(x):\nreturn np.sum(x)\n- @partial(mask, in_shapes=['n'], out_shape='')\n- def padded_sum2(x):\n- return padded_sum([x], dict(n=2))\n+ batched_sum = vmap(padded_sum)\n- ans = padded_sum2([np.array([3, 1, 4, 1])], dict(n=1))\n- import ipdb; ipdb.set_trace()\n+ @partial(mask, in_shapes=['(m, _)', 'm'], out_shape='')\n+ def fun(x, ns):\n+ return batched_sum([x], dict(n=ns)).sum()\n+\n+ x = np.array([[3, 1, 4, 1],\n+ [5, 9, 2, 6],\n+ [5, 3, 5, 8]])\n+ ns = np.array([2, 3, 2])\n+ ans = fun([x, ns], dict(m=2))\n+ expected = 3+1 + 5+9+2\n+ self.assertAllClose(ans, expected, check_dtypes=False)\ndef test_arange(self):\nraise SkipTest(\"not yet implemented\")\n"
}
] | Python | Apache License 2.0 | google/jax | tweaks to simplify masked jaxprs, rnn test |
260,335 | 16.09.2019 16:30:42 | 25,200 | 99b9e48580d62da65f13bf533687c4d337e37902 | python2 fix for ShapeExpr slicing | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -57,12 +57,18 @@ def extend_shape_envs(logical_env, padded_env):\ndef shape_as_value(expr):\nif type(expr) is ShapeExpr:\nreturn eval_shape_expr(shape_envs.logical, expr)\n+ elif type(expr) is tuple and any(type(d) is Poly for d in expr):\n+ return tuple(eval_dim_expr(shape_envs.logical, d) if type(d) is Poly else d\n+ for d in expr)\nelse:\nreturn expr\ndef padded_shape_as_value(expr):\nif type(expr) is ShapeExpr:\nreturn eval_shape_expr(shape_envs.padded, expr)\n+ elif type(expr) is tuple and any(type(d) is Poly for d in expr):\n+ return tuple(eval_dim_expr(shape_envs.padded, d) if type(d) is Poly else d\n+ for d in expr)\nelse:\nreturn expr\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -82,7 +82,8 @@ def _canonicalize_shape(shape):\nA tuple of integers.\n\"\"\"\n# TODO(mattjj): this next check is a temporary workaround for masking\n- if type(shape) is ShapeExpr or any(type(d) is masking.Poly for d in shape):\n+ if (type(shape) is ShapeExpr\n+ or type(shape) is tuple and any(type(d) is masking.Poly for d in shape)):\nreturn shape\ntry:\nreturn tuple(map(operator.index, shape))\n"
}
] | Python | Apache License 2.0 | google/jax | python2 fix for ShapeExpr slicing |
260,677 | 17.09.2019 18:55:11 | -3,600 | dda0c806c18f057fc734a0e6ec800584c334c365 | Added test case for sloget gradient | [
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -117,6 +117,18 @@ class NumpyLinalgTest(jtu.JaxTestCase):\ncheck_dtypes=True, tol=1e-3)\nself._CompileAndCheck(np.linalg.slogdet, args_maker, check_dtypes=True)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n+ \"shape\": shape, \"dtype\": dtype, \"rng\": rng}\n+ for shape in [(1, 1), (4, 4), (5, 5), (50, 50), (2, 7, 7)]\n+ for dtype in float_types + complex_types\n+ for rng in [jtu.rand_default()]))\n+ def testSlogdetGrad(self, shape, dtype, rng):\n+ _skip_if_unsupported_type(dtype)\n+ a = rng(shape, dtype)\n+ jtu.check_grads(np.linalg.slogdet, (a,), 2)\n+\ndef testIssue1213(self):\nfor n in range(5):\nmat = np.array([onp.diag(onp.ones([5], dtype=onp.float32))*(-.01)] * 2)\n"
}
] | Python | Apache License 2.0 | google/jax | Added test case for sloget gradient |
260,677 | 17.09.2019 18:57:51 | -3,600 | 3c18245e64856eb8ffb7b859f8d29246c055a869 | Removed complex types from slogdet grad test | [
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -122,7 +122,7 @@ class NumpyLinalgTest(jtu.JaxTestCase):\n\"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n\"shape\": shape, \"dtype\": dtype, \"rng\": rng}\nfor shape in [(1, 1), (4, 4), (5, 5), (50, 50), (2, 7, 7)]\n- for dtype in float_types + complex_types\n+ for dtype in float_types\nfor rng in [jtu.rand_default()]))\ndef testSlogdetGrad(self, shape, dtype, rng):\n_skip_if_unsupported_type(dtype)\n"
}
] | Python | Apache License 2.0 | google/jax | Removed complex types from slogdet grad test |
260,677 | 17.09.2019 18:58:34 | -3,600 | 7a347dede9beba964c15144bc42da6cfe988d18b | Added TODO to fix slogdet grad for complex types | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/linalg.py",
"new_path": "jax/numpy/linalg.py",
"diff": "@@ -60,6 +60,7 @@ def svd(a, full_matrices=True, compute_uv=True):\nreturn lax_linalg.svd(a, full_matrices, compute_uv)\n+# TODO(pfau): make this work for complex types\ndef _jvp_slogdet(g, ans, x):\njvp_sign = np.zeros(x.shape[:-2])\njvp_logdet = np.trace(solve(x, g), axis1=-1, axis2=-2)\n"
}
] | Python | Apache License 2.0 | google/jax | Added TODO to fix slogdet grad for complex types |
260,677 | 17.09.2019 19:03:50 | -3,600 | 1e8746ab1f2fb0da55be53475571de09b2ddfb85 | Shrink largest test in slogdet grad | [
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -121,7 +121,7 @@ class NumpyLinalgTest(jtu.JaxTestCase):\n{\"testcase_name\":\n\"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n\"shape\": shape, \"dtype\": dtype, \"rng\": rng}\n- for shape in [(1, 1), (4, 4), (5, 5), (50, 50), (2, 7, 7)]\n+ for shape in [(1, 1), (4, 4), (5, 5), (25, 25), (2, 7, 7)]\nfor dtype in float_types\nfor rng in [jtu.rand_default()]))\ndef testSlogdetGrad(self, shape, dtype, rng):\n"
}
] | Python | Apache License 2.0 | google/jax | Shrink largest test in slogdet grad |
260,677 | 18.09.2019 11:05:17 | -3,600 | f25cfafef00663a2d2cd9d20f5fe1deef92662ab | Reduced tolerance for slogdet grad test | [
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -127,7 +127,7 @@ class NumpyLinalgTest(jtu.JaxTestCase):\ndef testSlogdetGrad(self, shape, dtype, rng):\n_skip_if_unsupported_type(dtype)\na = rng(shape, dtype)\n- jtu.check_grads(np.linalg.slogdet, (a,), 2)\n+ jtu.check_grads(np.linalg.slogdet, (a,), 2, atol=1e-3, rtol=1e-3)\ndef testIssue1213(self):\nfor n in range(5):\n"
}
] | Python | Apache License 2.0 | google/jax | Reduced tolerance for slogdet grad test |
260,677 | 18.09.2019 12:28:57 | -3,600 | fd4c3029d8e42fd1244ccdc075c9571428f4d464 | Further relaxed the tolerance of slogdet grad test | [
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -127,7 +127,7 @@ class NumpyLinalgTest(jtu.JaxTestCase):\ndef testSlogdetGrad(self, shape, dtype, rng):\n_skip_if_unsupported_type(dtype)\na = rng(shape, dtype)\n- jtu.check_grads(np.linalg.slogdet, (a,), 2, atol=1e-3, rtol=1e-3)\n+ jtu.check_grads(np.linalg.slogdet, (a,), 2, atol=1e-3, rtol=1e-1)\ndef testIssue1213(self):\nfor n in range(5):\n"
}
] | Python | Apache License 2.0 | google/jax | Further relaxed the tolerance of slogdet grad test |
260,677 | 18.09.2019 13:08:27 | -3,600 | daf5b1cbdedfcd408e86c37d8ac920ddb68534ce | Relaxed test tolerance even more | [
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -127,7 +127,7 @@ class NumpyLinalgTest(jtu.JaxTestCase):\ndef testSlogdetGrad(self, shape, dtype, rng):\n_skip_if_unsupported_type(dtype)\na = rng(shape, dtype)\n- jtu.check_grads(np.linalg.slogdet, (a,), 2, atol=1e-3, rtol=1e-1)\n+ jtu.check_grads(np.linalg.slogdet, (a,), 2, atol=1e-1, rtol=1e-1)\ndef testIssue1213(self):\nfor n in range(5):\n"
}
] | Python | Apache License 2.0 | google/jax | Relaxed test tolerance even more |
260,389 | 18.09.2019 23:55:31 | 25,200 | b39179c88723742b89ba05e6e789b53bf5737e0f | better abs jvp | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1636,9 +1636,14 @@ ad.primitive_jvps[conj_p] = partial(ad.linear_jvp, conj_p)\nad.primitive_transposes[conj_p] = _conj_transpose_rule\nabs_p = unop(_complex_basetype, _num, 'abs')\n-ad.defjvp2(abs_p,\n- lambda g, ans, x:\n- div(_maybe_real(mul(g, _maybe_conj(x))), _replace_zero(ans)))\n+\n+def _abs_jvp_rule(g, ans, x):\n+ if _iscomplex(x):\n+ return _maybe_real(mul(g, div(_maybe_conj(x),\n+ _replace_zero(convert_element_type(ans, _dtype(x))))))\n+ else:\n+ return select(ge(x, _zero(x)), g, neg(g))\n+ad.defjvp2(abs_p, _abs_jvp_rule)\n_maybe_conj = lambda x: conj(x) if _iscomplex(x) else x\n_maybe_real = lambda x: real(x) if _iscomplex(x) else x\n"
}
] | Python | Apache License 2.0 | google/jax | better abs jvp |
260,389 | 18.09.2019 23:55:40 | 25,200 | 942d4e721758b7bfe5ef339a57595ae2e0117497 | restore more stable softplus | [
{
"change_type": "MODIFY",
"old_path": "jax/nn/functions.py",
"new_path": "jax/nn/functions.py",
"diff": "@@ -28,7 +28,7 @@ from jax import jarrett\n# activations\ndef relu(x): return np.maximum(x, 0)\n-def softplus(x): return np.log1p(np.exp(x))\n+def softplus(x): return np.logaddexp(x, 0)\ndef soft_sign(x): return x / (np.abs(x) + 1)\ndef sigmoid(x): return expit(x)\ndef swish(x): return x * sigmoid(x)\n"
}
] | Python | Apache License 2.0 | google/jax | restore more stable softplus |
260,685 | 20.09.2019 10:25:16 | -3,600 | 6fd938d8a02f066680d9c354b868d76769589b9e | no more nested loops of dynamic_update_slice! | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1714,12 +1714,11 @@ def _repeat_scalar(a, repeats, axis=None):\ndef repeat(a, repeats, axis=None):\n'''\n:param repeats: int or array of ints\n- largely same logic as `PyArray_Repeat` in https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/item_selection.c\n'''\n- # use the faster `_repeat_scalar` when possible\n+ # use `_repeat_scalar` when possible\nif isscalar(repeats):\nreturn _repeat_scalar(a, repeats, axis)\n- repeats_raveled = ravel(repeats)\n+ repeats_raveled = ravel(array(repeats)) # make sure it's jax's array type\nif size(repeats_raveled) == 1:\nreturn _repeat_scalar(a, list(repeats_raveled)[0], axis)\n@@ -1735,34 +1734,29 @@ def repeat(a, repeats, axis=None):\nrepeats_raveled.shape, n\n))\n- # total elements after repeat along the axis\n+ # calculating the new shape\ntotal = sum(repeats_raveled)\nnew_shape = a_shape[:]\nnew_shape[axis] = total\n- ret = ravel(zeros(new_shape, a.dtype))\na_flattened = ravel(a)\n- # size of each chunk to copy\n- chunk = 1\n- for i in range(axis+1, ndim(a)):\n- chunk *= a_shape[i]\n-\n- # copy `chunk` until axis\n- n_outer = 1\n- for i in range(0, axis):\n- n_outer *= a_shape[i]\n- old_data_ptr = 0\n- new_data_ptr = 0\n- for i in range(0, n_outer):\n- for j in range(0, n):\n- tmp = repeats_raveled[j]\n- for k in range(0, tmp):\n- # copy `chunk` data\n- ret = lax.dynamic_update_slice(ret, lax.dynamic_slice(a_flattened, [old_data_ptr], [chunk]), [new_data_ptr])\n- new_data_ptr += chunk\n- old_data_ptr += chunk\n+ '''\n+ main algorithm:\n+ first break down raveled input array into list of chunks; each chunk is the unit of repeat\n+ then tile the repeats to have same length as the list of chunks\n+ finally repeat each unit x number of times according to the tiled repeat list\n+ '''\n+ chunks = product(a_shape[:axis+1]).item()\n+ a_splitted = split(a_flattened, chunks)\n+ repeats_tiled = tile(repeats_raveled, chunks // len(repeats_raveled))\n+\n+ ret = array([], dtype=a.dtype)\n+ for i, repeat in enumerate(repeats_tiled):\n+ if not isinstance(repeat, int):\n+ repeat = repeat.item()\n+ ret = concatenate((ret, tile(a_splitted[i], repeat)))\nreturn reshape(ret, new_shape)\n"
}
] | Python | Apache License 2.0 | google/jax | no more nested loops of dynamic_update_slice! |
260,335 | 20.09.2019 15:35:43 | 25,200 | 36b5af517e4dafcd1158152bb2829d74f4e4759c | don't over-instantiate literals, fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -36,18 +36,15 @@ def identity(x): return x\n# A partial value (pval) is modeled as a pair (pv, const), as per\n# type PVal = (PV, Const)\n-# data PV = NonePV | AbstractPV AbstractValue\n+# data PV = Known | Unknown AbstractValue\n# type Const = MaybeTraced JaxType\n-# where the NonePV arm indicates a known (constant) value, the AbstractPV arm\n-# indicates an unknown value.\n+# where the Known arm indicates a known (constant) value (represented by a None\n+# payload, and the Unknown arm indicates an unknown value.\n# Additionally, when the pv is an AbstractValue, then the const must be unit.\nclass JaxprTrace(Trace):\ndef pure(self, val):\n- if type(val) in core.literalable_types and onp.shape(val) == ():\n- return JaxprTracer(self, PartialVal((None, val)), Literal(val))\n- else:\nreturn self.new_const(val)\ndef lift(self, val):\n@@ -76,8 +73,8 @@ class JaxprTrace(Trace):\nif isinstance(pv, AbstractValue):\nreturn tracer\nelif pv is None:\n- if type(tracer.recipe) is Literal:\n- return self.new_instantiated_literal(tracer.recipe.val)\n+ if type(const) in core.literalable_types and onp.shape(const) == ():\n+ return self.new_instantiated_literal(const)\nelse:\nreturn self.new_instantiated_const(const)\nelse:\n@@ -392,8 +389,7 @@ def tracers_to_jaxpr(in_tracers, out_tracers):\nenv_vars, env_vals = unzip2(env.items())\nconst_vars, const_vals = unzip2(consts.items())\njaxpr = Jaxpr(const_vars, env_vars, invars, list(map(var, out_tracers)), eqns)\n- # core.skip_checks or core.check_jaxpr(jaxpr)\n- core.check_jaxpr(jaxpr)\n+ core.skip_checks or core.check_jaxpr(jaxpr)\nreturn jaxpr, const_vals, env_vals\n"
}
] | Python | Apache License 2.0 | google/jax | don't over-instantiate literals, fixes #1361
Co-authored-by: Dougal Maclaurin <dougalm@google.com> |
260,716 | 14.03.2019 14:47:41 | -14,400 | 12de81456bf8a41853033b53fbd3bafccc4d9425 | Simplify nanmean with logical not | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1228,6 +1228,26 @@ nanmax = _make_nan_reduction(onp.nanmax, max, -inf, nan_if_all_nan=True)\nnansum = _make_nan_reduction(onp.nansum, sum, 0, nan_if_all_nan=False)\nnanprod = _make_nan_reduction(onp.nanprod, prod, 1, nan_if_all_nan=False)\n+<<<<<<< HEAD\n+=======\n+@_wraps(onp.nanmean)\n+def nanmean(a, axis=None, dtype=None, out=None, keepdims=False):\n+ if out is not None:\n+ raise ValueError(\"nanmean does not support the `out` argument.\")\n+ # Check and Count all non-NaN values\n+ nan_mask = logical_not(isnan(a))\n+ normalizer = sum(nan_mask, axis=axis, dtype=int32, keepdims=keepdims)\n+ normalizer = lax.convert_element_type(normalizer, dtype)\n+ #Perform mean calculation\n+ if dtype is None:\n+ if (onp.issubdtype(lax._dtype(a), onp.bool_) or\n+ onp.issubdtype(lax._dtype(a), onp.integer)):\n+ dtype = xla_bridge.canonicalize_dtype(onp.float64)\n+ else:\n+ dtype = lax._dtype(a)\n+ td = true_divide(nansum(a, axis, dtype=dtype, keepdims=keepdims), normalizer)\n+ return lax.convert_element_type(td, dtype)\n+>>>>>>> 7c6f468... Simplify nanmean with logical not\ndef _make_cumulative_reduction(onp_reduction, window_reduce, init_val,\nsquash_nan=False):\n"
}
] | Python | Apache License 2.0 | google/jax | Simplify nanmean with logical not |
260,716 | 21.09.2019 01:24:48 | 25,200 | 949e1ddf43c9971d9e37ef8df038c56c50364d27 | Weird Cherry Pick Remnant | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1228,8 +1228,6 @@ nanmax = _make_nan_reduction(onp.nanmax, max, -inf, nan_if_all_nan=True)\nnansum = _make_nan_reduction(onp.nansum, sum, 0, nan_if_all_nan=False)\nnanprod = _make_nan_reduction(onp.nanprod, prod, 1, nan_if_all_nan=False)\n-<<<<<<< HEAD\n-=======\n@_wraps(onp.nanmean)\ndef nanmean(a, axis=None, dtype=None, out=None, keepdims=False):\nif out is not None:\n@@ -1247,7 +1245,6 @@ def nanmean(a, axis=None, dtype=None, out=None, keepdims=False):\ndtype = lax._dtype(a)\ntd = true_divide(nansum(a, axis, dtype=dtype, keepdims=keepdims), normalizer)\nreturn lax.convert_element_type(td, dtype)\n->>>>>>> 7c6f468... Simplify nanmean with logical not\ndef _make_cumulative_reduction(onp_reduction, window_reduce, init_val,\nsquash_nan=False):\n"
}
] | Python | Apache License 2.0 | google/jax | Weird Cherry Pick Remnant |
260,296 | 22.09.2019 15:32:12 | 25,200 | 58ed2e31d898c2c64e778c2378e576d97799cf76 | Make `assertAllClose` work with non-array types.
In our application this would make comparing trees with other entries like Nones and enums easier. I may be missing some other issues though, let me know if this change makes sense! | [
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -516,6 +516,8 @@ class JaxTestCase(parameterized.TestCase):\nx = onp.asarray(x)\ny = onp.asarray(y)\nself.assertArraysAllClose(x, y, check_dtypes, atol=atol, rtol=rtol)\n+ elif x == y:\n+ return\nelse:\nraise TypeError((type(x), type(y)))\n"
}
] | Python | Apache License 2.0 | google/jax | Make `assertAllClose` work with non-array types.
In our application this would make comparing trees with other entries like Nones and enums easier. I may be missing some other issues though, let me know if this change makes sense! |
260,716 | 22.09.2019 21:38:34 | 25,200 | c312729d62d0c4fd9177c231802e97b7842f49e0 | Refactor and Test based on comments from old PR | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1232,17 +1232,16 @@ nanprod = _make_nan_reduction(onp.nanprod, prod, 1, nan_if_all_nan=False)\ndef nanmean(a, axis=None, dtype=None, out=None, keepdims=False):\nif out is not None:\nraise ValueError(\"nanmean does not support the `out` argument.\")\n+ if (onp.issubdtype(lax._dtype(a), onp.bool_) or\n+ onp.issubdtype(lax._dtype(a), onp.integer)):\n+ return mean(a, axis, dtype, out, keepdims)\n# Check and Count all non-NaN values\nnan_mask = logical_not(isnan(a))\nnormalizer = sum(nan_mask, axis=axis, dtype=int32, keepdims=keepdims)\nnormalizer = lax.convert_element_type(normalizer, dtype)\n- #Perform mean calculation\nif dtype is None:\n- if (onp.issubdtype(lax._dtype(a), onp.bool_) or\n- onp.issubdtype(lax._dtype(a), onp.integer)):\n- dtype = xla_bridge.canonicalize_dtype(onp.float64)\n- else:\ndtype = lax._dtype(a)\n+ #Perform mean calculation\ntd = true_divide(nansum(a, axis, dtype=dtype, keepdims=keepdims), normalizer)\nreturn lax.convert_element_type(td, dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -373,6 +373,31 @@ def rand_some_inf():\nreturn rand\n+def rand_some_nan():\n+ \"\"\"Return a random sampler that produces nans in floating types.\"\"\"\n+ rng = npr.RandomState(1)\n+ base_rand = rand_default()\n+\n+ def rand(shape, dtype):\n+ \"\"\"The random sampler function.\"\"\"\n+ if not onp.issubdtype(dtype, onp.floating):\n+ # only float types have inf\n+ return base_rand(shape, dtype)\n+\n+ if onp.issubdtype(dtype, onp.complexfloating):\n+ base_dtype = onp.real(onp.array(0, dtype=dtype)).dtype\n+ return rand(shape, base_dtype) + 1j * rand(shape, base_dtype)\n+\n+ dims = _dims_of_shape(shape)\n+ nan_flips = rng.rand(*dims) < 0.1\n+\n+ vals = base_rand(shape, dtype)\n+ vals = onp.where(nan_flips, onp.nan, vals)\n+\n+ return _cast_to_shape(onp.asarray(vals, dtype=dtype), shape, dtype)\n+\n+ return rand\n+\ndef rand_some_inf_and_nan():\n\"\"\"Return a random sampler that produces infinities in floating types.\"\"\"\nrng = npr.RandomState(1)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -189,6 +189,9 @@ JAX_REDUCER_RECORDS = [\nop_record(\"sum\", 1, number_dtypes, all_shapes, jtu.rand_default(), []),\nop_record(\"var\", 1, number_dtypes, nonempty_shapes, jtu.rand_default(), []),\nop_record(\"std\", 1, inexact_dtypes, nonempty_shapes, jtu.rand_default(), []),\n+ op_record(\"nanmean\", 1, number_dtypes, nonempty_shapes, jtu.rand_some_nan(), []),\n+ op_record(\"nanprod\", 1, number_dtypes, all_shapes, jtu.rand_some_nan(), []),\n+ op_record(\"nansum\", 1, number_dtypes, all_shapes, jtu.rand_some_nan(), []),\n]\nJAX_REDUCER_NO_DTYPE_RECORDS = [\n"
}
] | Python | Apache License 2.0 | google/jax | Refactor and Test based on comments from old PR |
260,716 | 23.09.2019 08:53:49 | 25,200 | 3d21393d0ca87f7058c82ea1b8a77a4e4ac436e1 | PR Response Changes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1235,15 +1235,13 @@ def nanmean(a, axis=None, dtype=None, out=None, keepdims=False):\nif (onp.issubdtype(lax._dtype(a), onp.bool_) or\nonp.issubdtype(lax._dtype(a), onp.integer)):\nreturn mean(a, axis, dtype, out, keepdims)\n- # Check and Count all non-NaN values\n+ if dtype is None:\n+ dtype = lax._dtype(a)\nnan_mask = logical_not(isnan(a))\nnormalizer = sum(nan_mask, axis=axis, dtype=int32, keepdims=keepdims)\nnormalizer = lax.convert_element_type(normalizer, dtype)\n- if dtype is None:\n- dtype = lax._dtype(a)\n- #Perform mean calculation\n- td = true_divide(nansum(a, axis, dtype=dtype, keepdims=keepdims), normalizer)\n- return lax.convert_element_type(td, dtype)\n+ td = lax.divide(nansum(a, axis, dtype=dtype, keepdims=keepdims), normalizer)\n+ return td\ndef _make_cumulative_reduction(onp_reduction, window_reduce, init_val,\nsquash_nan=False):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -380,14 +380,14 @@ def rand_some_nan():\ndef rand(shape, dtype):\n\"\"\"The random sampler function.\"\"\"\n- if not onp.issubdtype(dtype, onp.floating):\n- # only float types have inf\n- return base_rand(shape, dtype)\n-\nif onp.issubdtype(dtype, onp.complexfloating):\nbase_dtype = onp.real(onp.array(0, dtype=dtype)).dtype\nreturn rand(shape, base_dtype) + 1j * rand(shape, base_dtype)\n+ if not onp.issubdtype(dtype, onp.floating):\n+ # only float types have inf\n+ return base_rand(shape, dtype)\n+\ndims = _dims_of_shape(shape)\nnan_flips = rng.rand(*dims) < 0.1\n@@ -405,14 +405,14 @@ def rand_some_inf_and_nan():\ndef rand(shape, dtype):\n\"\"\"The random sampler function.\"\"\"\n- if not onp.issubdtype(dtype, onp.floating):\n- # only float types have inf\n- return base_rand(shape, dtype)\n-\nif onp.issubdtype(dtype, onp.complexfloating):\nbase_dtype = onp.real(onp.array(0, dtype=dtype)).dtype\nreturn rand(shape, base_dtype) + 1j * rand(shape, base_dtype)\n+ if not onp.issubdtype(dtype, onp.floating):\n+ # only float types have inf\n+ return base_rand(shape, dtype)\n+\ndims = _dims_of_shape(shape)\nposinf_flips = rng.rand(*dims) < 0.1\nneginf_flips = rng.rand(*dims) < 0.1\n"
}
] | Python | Apache License 2.0 | google/jax | PR Response Changes |
260,716 | 23.09.2019 10:04:31 | 25,200 | 03fb88e49e7e0349a294dbb3fd20933fce3edc67 | TODOs and wrong name | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1240,7 +1240,7 @@ def nanmean(a, axis=None, dtype=None, out=None, keepdims=False):\nnan_mask = logical_not(isnan(a))\nnormalizer = sum(nan_mask, axis=axis, dtype=int32, keepdims=keepdims)\nnormalizer = lax.convert_element_type(normalizer, dtype)\n- td = lax.divide(nansum(a, axis, dtype=dtype, keepdims=keepdims), normalizer)\n+ td = lax.div(nansum(a, axis, dtype=dtype, keepdims=keepdims), normalizer)\nreturn td\ndef _make_cumulative_reduction(onp_reduction, window_reduce, init_val,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -351,6 +351,10 @@ def rand_some_inf():\nrng = npr.RandomState(1)\nbase_rand = rand_default()\n+ \"\"\"\n+ TODO: Complex numbers are not correctly tested\n+ If blocks should be switched in order, and relevant tests should be fixed\n+ \"\"\"\ndef rand(shape, dtype):\n\"\"\"The random sampler function.\"\"\"\nif not onp.issubdtype(dtype, onp.floating):\n@@ -403,16 +407,20 @@ def rand_some_inf_and_nan():\nrng = npr.RandomState(1)\nbase_rand = rand_default()\n+ \"\"\"\n+ TODO: Complex numbers are not correctly tested\n+ If blocks should be switched in order, and relevant tests should be fixed\n+ \"\"\"\ndef rand(shape, dtype):\n\"\"\"The random sampler function.\"\"\"\n- if onp.issubdtype(dtype, onp.complexfloating):\n- base_dtype = onp.real(onp.array(0, dtype=dtype)).dtype\n- return rand(shape, base_dtype) + 1j * rand(shape, base_dtype)\n-\nif not onp.issubdtype(dtype, onp.floating):\n# only float types have inf\nreturn base_rand(shape, dtype)\n+ if onp.issubdtype(dtype, onp.complexfloating):\n+ base_dtype = onp.real(onp.array(0, dtype=dtype)).dtype\n+ return rand(shape, base_dtype) + 1j * rand(shape, base_dtype)\n+\ndims = _dims_of_shape(shape)\nposinf_flips = rng.rand(*dims) < 0.1\nneginf_flips = rng.rand(*dims) < 0.1\n"
}
] | Python | Apache License 2.0 | google/jax | TODOs and wrong name |
260,299 | 24.09.2019 19:20:12 | -7,200 | f9b9146a92617b825d119ed14706fe182cd483a0 | Ensure lax.scatter cache hits in op-by-op mode | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -785,6 +785,9 @@ def scatter_max(operand, scatter_indices, updates, dimension_numbers):\nupdate_consts=consts, dimension_numbers=dimension_numbers,\nupdates_shape=updates.shape)\n+# Define this outside of scatter to ensure cache hits.\n+_scatter_reduction_computation = lambda x, y: y\n+\ndef scatter(operand, scatter_indices, updates, dimension_numbers):\n\"\"\"Scatter-update operator.\n@@ -809,7 +812,8 @@ def scatter(operand, scatter_indices, updates, dimension_numbers):\nReturns:\nAn array containing the sum of `operand` and the scattered updates.\n\"\"\"\n- jaxpr, consts = _reduction_jaxpr(lambda x, y: y, _abstractify(_const(operand, 0)))\n+ jaxpr, consts = _reduction_jaxpr(_scatter_reduction_computation,\n+ _abstractify(_const(operand, 0)))\nreturn scatter_p.bind(\noperand, scatter_indices, updates, update_jaxpr=jaxpr,\nupdate_consts=consts, dimension_numbers=dimension_numbers,\n"
}
] | Python | Apache License 2.0 | google/jax | Ensure lax.scatter cache hits in op-by-op mode |
260,299 | 25.09.2019 15:59:52 | -7,200 | 7c979e7c28a1a141dee66f0502caf7c15189710d | Always test for cache misses on second op-by-op call | [
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -35,6 +35,7 @@ from .config import flags\nfrom .util import partial\nfrom .tree_util import tree_multimap, tree_all, tree_map, tree_reduce\nfrom .lib import xla_bridge\n+from .interpreters import xla\nFLAGS = flags.FLAGS\n@@ -533,6 +534,13 @@ class JaxTestCase(parameterized.TestCase):\npython_should_be_executing = True\npython_ans = fun(*args)\n+ cache_misses = xla.xla_primitive_callable.cache_info().misses\n+ python_ans = fun(*args)\n+ self.assertEqual(\n+ cache_misses, xla.xla_primitive_callable.cache_info().misses,\n+ \"Compilation detected during second call of {} in op-by-op \"\n+ \"mode.\".format(fun))\n+\ncfun = api.jit(wrapped_fun)\npython_should_be_executing = True\nmonitored_ans = cfun(*args)\n"
}
] | Python | Apache License 2.0 | google/jax | Always test for cache misses on second op-by-op call |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.