author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
260,335
22.02.2019 20:42:07
28,800
1171626b99ab070befe52cc1d3d69f77177b0546
fix symbolic zero handling in sub transpose fixes
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -1363,7 +1363,7 @@ ad.primitive_transposes[add_p] = _add_transpose\ndef _sub_transpose(t, x, y):\nassert x is None and y is None # computation must be linear, not affine\n- return [t, neg(t)]\n+ return [t, neg(t) if t is not ad_util.zero else ad_util.zero]\nsub_p = standard_binop([_num, _num], 'sub')\nad.defjvp(sub_p,\n" } ]
Python
Apache License 2.0
google/jax
fix symbolic zero handling in sub transpose fixes #433
260,335
22.02.2019 21:34:41
28,800
eacf0650a59ec770d509bace35e9116da6c949d3
nested pjit split/join (internal tests pass)
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -73,8 +73,8 @@ def replica_groups(mesh_spec, mesh_axis):\nAxisEnv = namedtuple(\"AxisEnv\", [\"names\", \"sizes\"])\n-def extend_env(axis_env, name, size):\n- return AxisEnv(axis_env.names + [name], axis_env.sizes + [size])\n+def axis_read(axis_env, axis_name):\n+ return max(i for i, name in enumerate(axis_env.names) if name == axis_name)\ndef compile_replicated(jaxpr, axis_name, axis_size, consts, *abstract_args):\naxis_env = AxisEnv([axis_name], [axis_size])\n@@ -93,6 +93,9 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\nassert node is not None\nenv[v] = node\n+ def axis_env_extend(name, size):\n+ return AxisEnv(axis_env.names + [name], axis_env.sizes + [size])\n+\nenv = {}\nwrite(core.unitvar, c.Tuple())\nif const_vals:\n@@ -106,22 +109,25 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\nin_nodes = map(read, eqn.invars)\nif eqn.primitive in parallel_translation_rules:\nname = eqn.params['axis_name']\n- device_groups = replica_groups(axis_env.sizes, axis_env.names.index(name))\n+ device_groups = replica_groups(axis_env.sizes, axis_read(axis_env, name))\nparams = {k: eqn.params[k] for k in eqn.params if k != 'axis_name'}\nrule = parallel_translation_rules[eqn.primitive]\nans = rule(c, *in_nodes, device_groups=device_groups, **params)\nelif eqn.bound_subjaxprs:\nif eqn.primitive is xla_pcall_p:\n- in_nodes = map(partial(xla_split, c), in_nodes)\n+ name = eqn.params['axis_name']\n+ new_env = axis_env_extend(name, eqn.params['axis_size'])\n+ in_nodes = map(partial(xla_split, c, new_env.sizes), in_nodes)\nin_shapes = map(c.GetShape, in_nodes)\n(subjaxpr, const_bindings, freevar_bindings), = eqn.bound_subjaxprs\nsubc = replicated_comp(\n- subjaxpr,\n- extend_env(axis_env, eqn.params['axis_name'], eqn.params['axis_size']),\n- (), map(c.GetShape, map(read, const_bindings + freevar_bindings)),\n+ subjaxpr, new_env, (),\n+ map(c.GetShape, map(read, const_bindings + freevar_bindings)),\n*in_shapes)\nsubfun = (subc, tuple(map(read, const_bindings + freevar_bindings)))\n- ans = xla.xla_call_translation_rule(c, subfun, *in_nodes)\n+ sharded_result = xla.xla_call_translation_rule(c, subfun, *in_nodes)\n+ device_groups = replica_groups(new_env.sizes, axis_read(new_env, name))\n+ ans = xla_join(c, device_groups, sharded_result)\nelse:\nin_shapes = map(c.GetShape, in_nodes)\nsubcs = [\n@@ -141,12 +147,33 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\nmap(write, eqn.outvars, out_nodes)\nreturn c.Build(read(jaxpr.outvar))\n-def xla_split(c, x):\n- shape = list(c.GetShape(x).dimensions())\n- start_indices = c.Constant(onp.array([0] * len(shape)))\n- # start_indices = [c.ReplicaId()] + [c.Constant(0)] * len(shape) # TODO\n- return c.Reshape(c.DynamicSlice(x, start_indices, [1] + shape[1:]),\n- None, shape[1:])\n+def xla_split(c, axis_sizes, x):\n+ def _xla_split(shape, x):\n+ if shape.is_tuple():\n+ elts = map(_xla_split, shape.tuple_shapes(), _xla_destructure(c, x))\n+ return c.Tuple(*elts)\n+ else:\n+ size = onp.array(prod(axis_sizes), onp.uint32)\n+ idx = c.Rem(c.ReplicaId(), c.Constant(size))\n+ dims = list(shape.dimensions())\n+ zero = onp.zeros(len(dims) - 1, onp.uint32)\n+ start_indices = c.Concatenate([c.Reshape(idx, None, [1]),\n+ c.Constant(zero)], 0)\n+ return c.Reshape(c.DynamicSlice(x, start_indices, [1] + dims[1:]),\n+ None, dims[1:])\n+ return _xla_split(c.GetShape(x), x)\n+\n+# TODO(b/110096942): more efficient gather\n+def xla_join(c, device_groups, x):\n+ def _xla_join(shape, x):\n+ if shape.is_tuple():\n+ elts = map(_xla_join, shape.tuple_shapes(), _xla_destructure(c, x))\n+ return c.Tuple(*elts)\n+ else:\n+ group_size = len(device_groups[0])\n+ broadcasted = c.Broadcast(x, (group_size,))\n+ return c.AllToAll(broadcasted, 0, 0, device_groups)\n+ return _xla_join(c.GetShape(x), x)\ndef xla_pcall_impl(fun, *args, **params):\n@@ -197,7 +224,7 @@ xla_pcall = partial(core.call_bind, xla_pcall_p)\nxla_pcall_p.def_custom_bind(xla_pcall)\nxla_pcall_p.def_impl(xla_pcall_impl)\nad.primitive_transposes[xla_pcall_p] = partial(ad.call_transpose, xla_pcall_p)\n-# xla.translations[xla_pcall_p] = xla.xla_call_translation_rule # TODO\n+# xla.translations[xla_pcall_p] = xla.xla_call_translation_rule # TODO(mattjj)\npe.map_primitives.add(xla_pcall_p)\n" } ]
Python
Apache License 2.0
google/jax
nested pjit split/join (internal tests pass)
260,335
23.02.2019 08:09:36
28,800
8a2fd90b164b1eece5f6f01ad3a5e7718af2f935
fix typo in pxla
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -150,7 +150,7 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\ndef xla_split(c, axis_sizes, x):\ndef _xla_split(shape, x):\nif shape.is_tuple():\n- elts = map(_xla_split, shape.tuple_shapes(), _xla_destructure(c, x))\n+ elts = map(_xla_split, shape.tuple_shapes(), xla_destructure(c, x))\nreturn c.Tuple(*elts)\nelse:\nsize = onp.array(prod(axis_sizes), onp.uint32)\n@@ -167,7 +167,7 @@ def xla_split(c, axis_sizes, x):\ndef xla_join(c, device_groups, x):\ndef _xla_join(shape, x):\nif shape.is_tuple():\n- elts = map(_xla_join, shape.tuple_shapes(), _xla_destructure(c, x))\n+ elts = map(_xla_join, shape.tuple_shapes(), xla_destructure(c, x))\nreturn c.Tuple(*elts)\nelse:\ngroup_size = len(device_groups[0])\n" } ]
Python
Apache License 2.0
google/jax
fix typo in pxla
260,335
23.02.2019 12:33:56
28,800
12ed52eab5bb3c570d326a0bd6faa85f12e5d577
fix typo in a lax error message
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -1860,7 +1860,7 @@ def _broadcast_in_dim_shape_rule(operand, shape, broadcast_dimensions):\nbroadcast_dimensions)\nif operand.ndim != len(broadcast_dimensions):\nmsg = ('broadcast_in_dim broadcast_dimensions must have length equal to '\n- 'operand ndim, got broadcast_dimensions for operand ndim {}.')\n+ 'operand ndim, got broadcast_dimensions {} for operand ndim {}.')\nraise TypeError(msg.format(broadcast_dimensions, operand.ndim))\nif not set(broadcast_dimensions).issubset(set(range(len(shape)))):\nmsg = ('broadcast_in_dim broadcast_dimensions must be a subset of output '\n" } ]
Python
Apache License 2.0
google/jax
fix typo in a lax error message
260,335
23.02.2019 20:34:14
28,800
bdd54d660ef66410c83e2d24fec096710129dc8b
fix up transpose-of-pjit
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -16,13 +16,15 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n+import itertools as it\n+\nfrom . import partial_eval as pe\nfrom .. import core as core\nfrom ..core import JaxTuple, Trace, Tracer, new_master, get_aval, pack, call_p, Primitive\nfrom ..ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval,\nzeros_like_p, zero, Zero)\nfrom ..util import unzip2, unzip3, safe_map, safe_zip, partial\n-from ..tree_util import process_pytree, build_tree, register_pytree_node, prune\n+from ..tree_util import process_pytree, build_tree, register_pytree_node, prune, tree_map\nfrom ..linear_util import thunk, staged, transformation, transformation_with_aux, wrap_init\nfrom six.moves import builtins, reduce\n@@ -138,11 +140,10 @@ def backward_pass(jaxpr, consts, freevar_vals, args, cotangent_in):\nif cts_out is zero:\ncts_out = [zero for _ in eqn.invars]\n+ map(write_cotangent, eqn.invars, cts_out)\n- for var, ct in zip(eqn.invars, cts_out):\n- write_cotangent(var, ct)\n-\n- cotangents_out = map(read_cotangent, jaxpr.invars)\n+ cotangents_out = [read_cotangent(var) if argval is None else None\n+ for var, argval in zip(jaxpr.invars, args)]\nfreevar_cts = map(read_cotangent, jaxpr.freevars)\nreturn freevar_cts, cotangents_out\n@@ -392,12 +393,36 @@ def call_transpose(primitive, params, jaxpr, consts, freevar_vals, args, ct):\nans = primitive.bind(fun, all_args, **params)\nreturn build_tree(out_tree_def(), ans)\n+@transformation_with_aux\n+def transposed_mapped(jaxpr, in_tree_def, freevar_vals, args):\n+ args, consts, ct = args\n+ args, ct = build_tree(in_tree_def, (args, ct))\n+ freevar_cts, cotangents_out = yield jaxpr, consts, freevar_vals, args, ct\n+ out_jtuple, tree_def = tree_to_jaxtuples((cotangents_out, freevar_cts))\n+ yield out_jtuple, tree_def\n+\n+def map_transpose(primitive, params, jaxpr, consts, freevar_vals, args, ct):\n+ jaxpr, = jaxpr\n+ consts, = consts\n+ freevar_vals, = freevar_vals\n+ (args, ct), in_tree_def = tree_to_jaxtuples((args, ct))\n+ fun = wrap_init(backward_pass)\n+ fun, out_tree_def = transposed_mapped(fun, jaxpr, in_tree_def, tuple(freevar_vals))\n+ all_args = pack((pack(args), pack(consts), ct))\n+ ans = primitive.bind(fun, all_args, **params)\n+ cts_out, freevar_cts = build_tree(out_tree_def(), ans)\n+ freevar_cts = tree_map(_sum_leading_axis, freevar_cts)\n+ return cts_out, freevar_cts\n+\n+def _sum_leading_axis(x):\n+ try:\n+ return x.sum(0)\n+ except AttributeError:\n+ return onp.sum(x, 0)\n+\nprimitive_transposes[core.call_p] = partial(call_transpose, call_p)\nprimitive_transposes[pe.compiled_call_p] = partial(call_transpose, pe.compiled_call_p)\ntree_to_jaxtuples = partial(process_pytree, pack)\n-\n-\n-call_primitive_jvp_params = {}\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -143,36 +143,56 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\nelse:\nans = translation_rule(eqn.primitive)(c, *in_nodes, **eqn.params)\n+ try:\nout_nodes = xla_destructure(c, ans) if eqn.destructure else [ans]\n+ except:\n+ import ipdb; ipdb.set_trace()\nmap(write, eqn.outvars, out_nodes)\nreturn c.Build(read(jaxpr.outvar))\ndef xla_split(c, axis_sizes, x):\n- def _xla_split(shape, x):\n- if shape.is_tuple():\n- elts = map(_xla_split, shape.tuple_shapes(), xla_destructure(c, x))\n- return c.Tuple(*elts)\n+ def split_array(shape, x):\n+ if xb.get_replica_count() == 1:\n+ # TODO(mattjj): remove this special case, used for debugging on cpu\n+ dims = c.GetShape(x).dimensions()\n+ return c.Reshape(x, None, dims[1:])\nelse:\nsize = onp.array(prod(axis_sizes), onp.uint32)\nidx = c.Rem(c.ReplicaId(), c.Constant(size))\ndims = list(shape.dimensions())\nzero = onp.zeros(len(dims) - 1, onp.uint32)\n- start_indices = c.Concatenate([c.Reshape(idx, None, [1]),\n- c.Constant(zero)], 0)\n+ start_indices = c.Concatenate([c.Reshape(idx, None, [1]), c.Constant(zero)], 0)\nreturn c.Reshape(c.DynamicSlice(x, start_indices, [1] + dims[1:]),\nNone, dims[1:])\n+\n+ def _xla_split(shape, x):\n+ if shape.is_tuple():\n+ elts = map(_xla_split, shape.tuple_shapes(), xla_destructure(c, x))\n+ return c.Tuple(*elts)\n+ else:\n+ return split_array(shape, x)\n+\nreturn _xla_split(c.GetShape(x), x)\n# TODO(b/110096942): more efficient gather\ndef xla_join(c, device_groups, x):\n+ def join_arrays(x):\n+ # TODO(mattjj): remove this special case, used for debugging on cpu\n+ if xb.get_replica_count() == 1:\n+ dims = c.GetShape(x).dimensions()\n+ return c.Reshape(x, None, (1,) + tuple(dims))\n+ else:\n+ group_size = len(device_groups[0])\n+ broadcasted = c.Broadcast(x, (group_size,))\n+ return c.AllToAll(broadcasted, 0, 0, device_groups)\n+\ndef _xla_join(shape, x):\nif shape.is_tuple():\nelts = map(_xla_join, shape.tuple_shapes(), xla_destructure(c, x))\nreturn c.Tuple(*elts)\nelse:\n- group_size = len(device_groups[0])\n- broadcasted = c.Broadcast(x, (group_size,))\n- return c.AllToAll(broadcasted, 0, 0, device_groups)\n+ return join_arrays(x)\n+\nreturn _xla_join(c.GetShape(x), x)\n@@ -223,7 +243,7 @@ xla_pcall_p = core.Primitive('xla_pcall')\nxla_pcall = partial(core.call_bind, xla_pcall_p)\nxla_pcall_p.def_custom_bind(xla_pcall)\nxla_pcall_p.def_impl(xla_pcall_impl)\n-ad.primitive_transposes[xla_pcall_p] = partial(ad.call_transpose, xla_pcall_p)\n+ad.primitive_transposes[xla_pcall_p] = partial(ad.map_transpose, xla_pcall_p)\n# xla.translations[xla_pcall_p] = xla.xla_call_translation_rule # TODO(mattjj)\npe.map_primitives.add(xla_pcall_p)\n" }, { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -773,6 +773,10 @@ opaque_param_ids = itertools.count()\ndef tie_in(x, y):\nreturn tie_in_p.bind(x, y)\n+def shaped_identity(x):\n+ return shaped_identity_p.bind(x, shape=x.shape)\n+\n+\ndef full(shape, fill_value, dtype):\ntry:\nshape = tuple(map(int, shape))\n@@ -3311,6 +3315,15 @@ ad.deflinear(tie_in_p, _tie_in_transpose_rule)\nbatching.primitive_batchers[tie_in_p] = _tie_in_batch_rule\n+shaped_identity_p = Primitive('shape_id')\n+shaped_identity_p.def_impl(lambda x, shape: x)\n+shaped_identity_p.def_abstract_eval(lambda x, shape: x)\n+xla.translations[shaped_identity_p] = lambda c, x, shape: x\n+ad.deflinear(shaped_identity_p, lambda t, shape: [shaped_identity(t)])\n+batching.primitive_batchers[shaped_identity_p] = \\\n+ lambda a, d, shape: (shaped_identity(a[0]), d[0])\n+\n+\n### constants\n" }, { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "@@ -16,21 +16,53 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n+from functools import partial\n+\nimport numpy as onp\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax.numpy as np\nfrom jax import test_util as jtu\n-from jax.api import pjit, pmap, jvp, grad\n+from jax import lax\n+from jax.api import pjit, pmap, vmap, jvp, grad, make_jaxpr, linearize\nfrom jax.lax import psum\n+from jax.lib import xla_bridge\nfrom jax.config import config\nconfig.parse_flags_with_absl()\nclass PjitTest(jtu.JaxTestCase):\n- pass # TODO(mattjj)\n+\n+ @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ def testNestedWithClosure(self):\n+ assert xla_bridge.get_replica_count() == 1 # OSS CPU testing only\n+ x = onp.arange(3, dtype=onp.float32).reshape(1, 1, 3)\n+\n+ @partial(pjit, axis_name='i')\n+ def test_fun(x):\n+ y = np.sum(np.sin(x))\n+\n+ @partial(pjit, axis_name='j')\n+ def g(z):\n+ return 3. * np.exp(np.sin(x).sum() * np.cos(y) * np.tan(z))\n+\n+ return grad(lambda w: np.sum(g(w)))(x)\n+\n+ @vmap\n+ def baseline_fun(x):\n+ y = np.sum(np.sin(x))\n+\n+ @vmap\n+ def g(z):\n+ return 3. * np.exp(np.sin(x).sum() * np.cos(y) * np.tan(z))\n+\n+ return grad(lambda w: np.sum(g(w)))(x)\n+\n+ ans = grad(lambda x: np.sum(test_fun(x)))(x)\n+ expected = grad(lambda x: np.sum(baseline_fun(x)))(x)\n+ self.assertAllClose(ans, expected, check_dtypes=True)\nif __name__ == '__main__':\n" } ]
Python
Apache License 2.0
google/jax
fix up transpose-of-pjit
260,335
23.02.2019 20:38:35
28,800
dd75c564d35e8159cc985620d749e504a6b92d13
todo note cleanup
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -153,7 +153,8 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\ndef xla_split(c, axis_sizes, x):\ndef split_array(shape, x):\nif xb.get_replica_count() == 1:\n- # TODO(mattjj): remove this special case, used for debugging on cpu\n+ # TODO(mattjj): remove this special case, used for debugging on CPU\n+ # because CPU doesn't have some collectives implemented\ndims = c.GetShape(x).dimensions()\nreturn c.Reshape(x, None, dims[1:])\nelse:\n@@ -177,7 +178,8 @@ def xla_split(c, axis_sizes, x):\n# TODO(b/110096942): more efficient gather\ndef xla_join(c, device_groups, x):\ndef join_arrays(x):\n- # TODO(mattjj): remove this special case, used for debugging on cpu\n+ # TODO(mattjj): remove this special case, used for debugging on CPU\n+ # because CPU doesn't have some collectives implemented\nif xb.get_replica_count() == 1:\ndims = c.GetShape(x).dimensions()\nreturn c.Reshape(x, None, (1,) + tuple(dims))\n@@ -244,8 +246,9 @@ xla_pcall = partial(core.call_bind, xla_pcall_p)\nxla_pcall_p.def_custom_bind(xla_pcall)\nxla_pcall_p.def_impl(xla_pcall_impl)\nad.primitive_transposes[xla_pcall_p] = partial(ad.map_transpose, xla_pcall_p)\n-# xla.translations[xla_pcall_p] = xla.xla_call_translation_rule # TODO(mattjj)\npe.map_primitives.add(xla_pcall_p)\n+# TODO(mattjj): enable pjit inside jit\n+# xla.translations[xla_pcall_p] = xla.xla_call_translation_rule\nparallel_translation_rules = {}\n" } ]
Python
Apache License 2.0
google/jax
todo note cleanup
260,335
24.02.2019 09:00:21
28,800
6ee3c4a8fe5efab054acdc2ae8546712cd2dbbe6
simplify map_transpose summing
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -411,15 +411,9 @@ def map_transpose(primitive, params, jaxpr, consts, freevar_vals, args, ct):\nall_args = pack((pack(args), pack(consts), ct))\nans = primitive.bind(fun, all_args, **params)\ncts_out, freevar_cts = build_tree(out_tree_def(), ans)\n- freevar_cts = tree_map(_sum_leading_axis, freevar_cts)\n+ freevar_cts = tree_map(lambda x: x.sum(0), freevar_cts)\nreturn cts_out, freevar_cts\n-def _sum_leading_axis(x):\n- try:\n- return x.sum(0)\n- except AttributeError:\n- return onp.sum(x, 0)\n-\nprimitive_transposes[core.call_p] = partial(call_transpose, call_p)\nprimitive_transposes[pe.compiled_call_p] = partial(call_transpose, pe.compiled_call_p)\n" } ]
Python
Apache License 2.0
google/jax
simplify map_transpose summing
260,335
24.02.2019 10:58:38
28,800
b61b6e11200a67cab087e3b1bdb5c473ec46a644
replace global replica count with per-comp config
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -45,25 +45,28 @@ map = safe_map\n### util\n-def shard_arg(arg):\n+def shard_arg(nrep, arg):\nsz = arg.shape[0]\nshards = [arg[i] for i in range(sz)]\n- return [xb.device_put(shards[i], n) for n, i in enumerate(assign_shards(sz))]\n+ assignments = assign_shards(nrep, sz)\n+ return [xb.device_put(shards[i], n) for n, i in enumerate(assignments)]\n-def unshard_output(axis_size, out_shards):\n- _, ids = onp.unique(assign_shards(axis_size), return_index=True)\n+def unshard_output(nrep, axis_size, out_shards):\n+ _, ids = onp.unique(assign_shards(nrep, axis_size), return_index=True)\nreturn onp.stack([out_shards[i] for i in ids])\n-def assign_shards(size):\n- groupsize, ragged = divmod(xb.get_replica_count(), size)\n+def assign_shards(nrep, size):\n+ groupsize, ragged = divmod(nrep, size)\nassert not ragged\nindices = onp.tile(onp.arange(size)[:, None], (1, groupsize))\nreturn tuple(indices.ravel())\n-def replica_groups(mesh_spec, mesh_axis):\n- mesh_spec = mesh_spec + [xb.get_replica_count() // prod(mesh_spec)]\n- groups = onp.split(onp.arange(prod(mesh_spec)).reshape(mesh_spec),\n- mesh_spec[mesh_axis], axis=mesh_axis)\n+def replica_groups(nrep, mesh_spec, mesh_axis):\n+ trailing_size, ragged = divmod(nrep, prod(mesh_spec))\n+ assert not ragged\n+ full_spec = mesh_spec + [trailing_size]\n+ groups = onp.split(onp.arange(prod(full_spec)).reshape(full_spec),\n+ full_spec[mesh_axis], axis=mesh_axis)\ngroups = map(onp.ravel, groups)\nreturn tuple(tuple(group) for group in zip(*groups))\n@@ -71,19 +74,31 @@ def replica_groups(mesh_spec, mesh_axis):\n### xla_pcall\n-AxisEnv = namedtuple(\"AxisEnv\", [\"names\", \"sizes\"])\n+AxisEnv = namedtuple(\"AxisEnv\", [\"nreps\", \"names\", \"sizes\"])\ndef axis_read(axis_env, axis_name):\nreturn max(i for i, name in enumerate(axis_env.names) if name == axis_name)\n+def axis_groups(axis_env, name):\n+ mesh_axis = axis_read(axis_env, name)\n+ return replica_groups(axis_env.nreps, axis_env.sizes, mesh_axis)\n+\ndef compile_replicated(jaxpr, axis_name, axis_size, consts, *abstract_args):\n- axis_env = AxisEnv([axis_name], [axis_size])\n+ num_replicas = axis_size * jaxpr_replicas(jaxpr)\n+ assert num_replicas <= xb.get_replica_count()\n+ axis_env = AxisEnv(num_replicas, [axis_name], [axis_size])\narg_shapes = list(map(xla_shape, abstract_args))\nbuilt_c = replicated_comp(jaxpr, axis_env, consts, (), *arg_shapes)\nresult_shape = xla_shape_to_result_shape(built_c.GetReturnValueShape())\n- return built_c.Compile(arg_shapes, xb.get_compile_options()), result_shape\n+ compiled = built_c.Compile(arg_shapes, xb.get_compile_options(num_replicas))\n+ return compiled, num_replicas, result_shape\n+\n+def jaxpr_replicas(jaxpr):\n+ return _max(eqn.params['axis_size'] * jaxpr_replicas(eqn.bound_subjaxprs[0][0])\n+ for eqn in jaxpr.eqns if eqn.primitive is xla_pcall_p)\n+def _max(itr): return max(list(itr) or [1])\n-def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\n+def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nc = xb.make_computation_builder(\"replicated_computation\")\ndef read(v):\n@@ -94,7 +109,7 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\nenv[v] = node\ndef axis_env_extend(name, size):\n- return AxisEnv(axis_env.names + [name], axis_env.sizes + [size])\n+ return AxisEnv(ax_env.nreps, ax_env.names + [name], ax_env.sizes + [size])\nenv = {}\nwrite(core.unitvar, c.Tuple())\n@@ -109,10 +124,9 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\nin_nodes = map(read, eqn.invars)\nif eqn.primitive in parallel_translation_rules:\nname = eqn.params['axis_name']\n- device_groups = replica_groups(axis_env.sizes, axis_read(axis_env, name))\nparams = {k: eqn.params[k] for k in eqn.params if k != 'axis_name'}\nrule = parallel_translation_rules[eqn.primitive]\n- ans = rule(c, *in_nodes, device_groups=device_groups, **params)\n+ ans = rule(c, *in_nodes, device_groups=axis_groups(ax_env, name), **params)\nelif eqn.bound_subjaxprs:\nif eqn.primitive is xla_pcall_p:\nname = eqn.params['axis_name']\n@@ -126,8 +140,7 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\n*in_shapes)\nsubfun = (subc, tuple(map(read, const_bindings + freevar_bindings)))\nsharded_result = xla.xla_call_translation_rule(c, subfun, *in_nodes)\n- device_groups = replica_groups(new_env.sizes, axis_read(new_env, name))\n- ans = xla_join(c, device_groups, sharded_result)\n+ ans = xla_join(c, axis_groups(new_env, name), sharded_result)\nelse:\nin_shapes = map(c.GetShape, in_nodes)\nsubcs = [\n@@ -143,10 +156,7 @@ def replicated_comp(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\nelse:\nans = translation_rule(eqn.primitive)(c, *in_nodes, **eqn.params)\n- try:\nout_nodes = xla_destructure(c, ans) if eqn.destructure else [ans]\n- except:\n- import ipdb; ipdb.set_trace()\nmap(write, eqn.outvars, out_nodes)\nreturn c.Build(read(jaxpr.outvar))\n@@ -227,18 +237,18 @@ def parallel_callable(fun, axis_name, axis_size, *avals):\nwith core.new_master(JaxprTrace, True) as master:\njaxpr, (pval, consts, env) = trace_to_subjaxpr(fun, master).call_wrapped(pvals)\nassert not env\n- compiled, _ = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\n+ compiled, nrep, _ = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\ndel master, consts, jaxpr, env\n- return partial(execute_replicated, compiled, pval, axis_size)\n+ return partial(execute_replicated, compiled, pval, axis_size, nrep)\n-def execute_replicated(compiled, pval, axis_size, out_tree, *args):\n- input_bufs = zip(*map(shard_arg, args)) if args else [[]] * xb.get_replica_count()\n+def execute_replicated(compiled, pval, axis_size, nrep, out_tree, *args):\n+ input_bufs = zip(*map(partial(shard_arg, nrep), args)) if args else [[]] * nrep\nout_bufs = compiled.ExecutePerReplica(input_bufs)\nout_shards = [merge_pvals(buf.to_py(), pval) for buf in out_bufs]\nif out_tree is xla.leaf:\n- return unshard_output(axis_size, out_shards)\n+ return unshard_output(nrep, axis_size, out_shards)\nelse:\n- return map(partial(unshard_output, axis_size), zip(*out_shards))\n+ return map(partial(unshard_output, nrep, axis_size), zip(*out_shards))\nxla_pcall_p = core.Primitive('xla_pcall')\n" }, { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -77,7 +77,7 @@ def _hlo_path(path, name):\nreturn path\n-def get_compile_options():\n+def get_compile_options(num_replicas=None):\n\"\"\"Returns the compile options to use, as derived from flag values.\"\"\"\ncompile_options = None\nif FLAGS.jax_dump_hlo_graph is not None:\n@@ -98,6 +98,9 @@ def get_compile_options():\ncompile_options = compile_options or get_xla_client().CompileOptions()\npath = _hlo_path(FLAGS.jax_dump_hlo_per_pass, 'hlo_per_pass')\ncompile_options.dump_per_pass_hlo_proto_to = path\n+ if num_replicas is not None:\n+ compile_options = compile_options or get_xla_client().CompileOptions()\n+ compile_options.num_replicas = num_replicas\nreturn compile_options\n" } ]
Python
Apache License 2.0
google/jax
replace global replica count with per-comp config
260,335
24.02.2019 12:02:17
28,800
ffdee451606a00be2d5a0cde8dc95463a60d588e
tweak todo comment
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -257,7 +257,7 @@ xla_pcall_p.def_custom_bind(xla_pcall)\nxla_pcall_p.def_impl(xla_pcall_impl)\nad.primitive_transposes[xla_pcall_p] = partial(ad.map_transpose, xla_pcall_p)\npe.map_primitives.add(xla_pcall_p)\n-# TODO(mattjj): enable pjit inside jit\n+# TODO(mattjj): enable pjit inside jit, maybe by merging xla_pcall and xla_call\n# xla.translations[xla_pcall_p] = xla.xla_call_translation_rule\n" } ]
Python
Apache License 2.0
google/jax
tweak todo comment
260,335
24.02.2019 15:21:00
28,800
2361f08eb45ab1fcf12bc65cbf1b724fbe388c64
sketch basic sharded device persistence (no tests)
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -27,7 +27,7 @@ from .. import core\nfrom .. import ad_util\nfrom .. import tree_util\nfrom .. import linear_util as lu\n-from ..abstract_arrays import ShapedArray\n+from ..abstract_arrays import ConcreteArray, ShapedArray\nfrom ..util import partial, unzip2, concatenate, safe_map, prod\nfrom ..lib import xla_bridge as xb\nfrom .xla import (xla_shape, xla_destructure, translation_rule,\n@@ -46,14 +46,26 @@ map = safe_map\ndef shard_arg(nrep, arg):\n- sz = arg.shape[0]\n- shards = [arg[i] for i in range(sz)]\n- assignments = assign_shards(nrep, sz)\n+ if type(arg) is ShardedDeviceArray and arg.nrep == nrep:\n+ return arg.device_buffer\n+ else:\n+ arg = xla.canonicalize_ndarray_dtype(arg)\n+ shards = [arg[i] for i in range(arg.shape[0])]\n+ assignments = assign_shards(nrep, arg.shape[0])\nreturn [xb.device_put(shards[i], n) for n, i in enumerate(assignments)]\n-def unshard_output(nrep, axis_size, out_shards):\n+def unshard_output(axis_size, replica_results):\n+ nrep = len(replica_results)\n+ if all(type(res) is xla.DeviceArray for res in replica_results):\n+ r = replica_results[0]\n+ shape = (axis_size,) + r.shape\n+ ndim = 1 + r.ndim\n+ size = axis_size * r.size\n+ bufs = [res.device_buffer for res in replica_results]\n+ return ShardedDeviceArray(bufs, shape, r.dtype, ndim, size)\n+ else:\n_, ids = onp.unique(assign_shards(nrep, axis_size), return_index=True)\n- return onp.stack([out_shards[i] for i in ids])\n+ return onp.stack([replica_results[i] for i in ids])\ndef assign_shards(nrep, size):\ngroupsize, ragged = divmod(nrep, size)\n@@ -208,6 +220,26 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nreturn c.Build(read(jaxpr.outvar))\n+class ShardedDeviceArray(xla.DeviceArray):\n+ # we're reusing the 'device_buffer' slot to mean a list of device buffers\n+ @property\n+ def _value(self):\n+ if self._npy_value is None:\n+ npy_shards = [buf.to_py() for buf in self.device_buffer]\n+ self._npy_value = unshard_output(self.shape[0], npy_shards)\n+ return self._npy_value\n+\n+ @property\n+ def nrep(self):\n+ return len(self.device_buffer)\n+\n+core.pytype_aval_mappings[ShardedDeviceArray] = ConcreteArray\n+xla.pytype_aval_mappings[ShardedDeviceArray] = \\\n+ xla.pytype_aval_mappings[xla.DeviceArray]\n+xla.canonicalize_dtype_handlers[ShardedDeviceArray] = \\\n+ xla.canonicalize_dtype_handlers[xla.DeviceArray]\n+\n+\ndef xla_pcall_impl(fun, *args, **params):\naxis_name = params.pop('axis_name')\naxis_size = params.pop('axis_size')\n@@ -237,18 +269,20 @@ def parallel_callable(fun, axis_name, axis_size, *avals):\nwith core.new_master(JaxprTrace, True) as master:\njaxpr, (pval, consts, env) = trace_to_subjaxpr(fun, master).call_wrapped(pvals)\nassert not env\n- compiled, nrep, _ = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\n+ out = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\n+ compiled, nrep, result_shape = out\ndel master, consts, jaxpr, env\n- return partial(execute_replicated, compiled, pval, axis_size, nrep)\n+ handle_result = xla.result_handler(result_shape)\n+ return partial(execute_replicated, compiled, pval, axis_size, nrep, handle_result)\n-def execute_replicated(compiled, pval, axis_size, nrep, out_tree, *args):\n+def execute_replicated(compiled, pval, axis_size, nrep, handler, out_tree, *args):\ninput_bufs = zip(*map(partial(shard_arg, nrep), args)) if args else [[]] * nrep\nout_bufs = compiled.ExecutePerReplica(input_bufs)\n- out_shards = [merge_pvals(buf.to_py(), pval) for buf in out_bufs]\n+ replica_results = [merge_pvals(handler(buf), pval) for buf in out_bufs]\nif out_tree is xla.leaf:\n- return unshard_output(nrep, axis_size, out_shards)\n+ return unshard_output(axis_size, replica_results)\nelse:\n- return map(partial(unshard_output, nrep, axis_size), zip(*out_shards))\n+ return map(partial(unshard_output, axis_size), zip(*replica_results))\nxla_pcall_p = core.Primitive('xla_pcall')\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -81,14 +81,17 @@ def execute_compiled_primitive(compiled, result_handler, *args):\ninput_bufs = [device_put(x) for x in args]\nreturn result_handler(compiled.Execute(input_bufs, not core.skip_checks))\n-def device_put(x):\n+def device_put(x, replica_num=0):\nx = canonicalize_pyval_dtype(x)\nif type(x) is DeviceArray:\n+ if x.device_buffer.device() == replica_num:\nreturn x.device_buffer\n+ else:\n+ return device_put(x.device_buffer.to_py(), replica_num)\nelif isinstance(x, DeviceConstant):\n- return instantiate_device_constant(x)\n+ return instantiate_device_constant(x, replica_num=replica_num)\nelse:\n- return xb.device_put(x) # can round-trip elements of tuples here\n+ return xb.device_put(x, replica_num) # round-trips tuple elements\ndef result_handler(result_shape):\nif type(result_shape) is ResultArray and FLAGS.jax_device_values:\n@@ -353,17 +356,17 @@ class DeviceConstant(DeviceArray):\ndef constant_handler(c, constant_instance, canonicalize_types=True):\nassert False\n-def instantiate_device_constant(const, cutoff=1e6):\n+def instantiate_device_constant(const, cutoff=1e6, replica_num=0):\n# dispatch an XLA Computation to build the constant on the device if it's\n# large, or alternatively build it on the host and transfer it if it's small\nassert isinstance(const, DeviceConstant)\nif const.size > cutoff:\nc = xb.make_computation_builder(\"constant_instantiating_computation\")\nxla_const = const.constant_handler(c, const)\n- compiled = c.Build(xla_const).Compile((), xb.get_compile_options())\n+ compiled = c.Build(xla_const).Compile((), xb.get_compile_options(replica_num))\nreturn compiled.Execute(())\nelse:\n- return xb.device_put(onp.asarray(const))\n+ return xb.device_put(onp.asarray(const), replica_num)\ndef xla_shape(x):\n" } ]
Python
Apache License 2.0
google/jax
sketch basic sharded device persistence (no tests)
260,335
24.02.2019 15:25:10
28,800
7e93bff2b95e6f49be7e2cd310e8953bbbdcdc9d
fix batchnorm square vs sqrt error (fixes
[ { "change_type": "MODIFY", "old_path": "jax/experimental/stax.py", "new_path": "jax/experimental/stax.py", "diff": "@@ -137,7 +137,7 @@ def BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True,\ndef apply_fun(params, x, rng=None):\nbeta, gamma = params\nmean, var = np.mean(x, axis, keepdims=True), fastvar(x, axis, keepdims=True)\n- z = (x - mean) / (var + epsilon)**2\n+ z = (x - mean) / np.sqrt(var + epsilon)\nif center and scale: return gamma * z + beta\nif center: return z + beta\nif scale: return gamma * z\n" } ]
Python
Apache License 2.0
google/jax
fix batchnorm square vs sqrt error (fixes #442)
260,335
24.02.2019 15:36:20
28,800
caac8c82a7100ab9dec26a3077dab3b55a48fc1b
minor cleanup of sharded device-persistent values
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -47,22 +47,16 @@ map = safe_map\ndef shard_arg(nrep, arg):\nif type(arg) is ShardedDeviceArray and arg.nrep == nrep:\n- return arg.device_buffer\n+ return arg.device_buffers\nelse:\n- arg = xla.canonicalize_ndarray_dtype(arg)\nshards = [arg[i] for i in range(arg.shape[0])]\nassignments = assign_shards(nrep, arg.shape[0])\n- return [xb.device_put(shards[i], n) for n, i in enumerate(assignments)]\n+ return [xla.device_put(shards[i], n) for n, i in enumerate(assignments)]\ndef unshard_output(axis_size, replica_results):\nnrep = len(replica_results)\nif all(type(res) is xla.DeviceArray for res in replica_results):\n- r = replica_results[0]\n- shape = (axis_size,) + r.shape\n- ndim = 1 + r.ndim\n- size = axis_size * r.size\n- bufs = [res.device_buffer for res in replica_results]\n- return ShardedDeviceArray(bufs, shape, r.dtype, ndim, size)\n+ return ShardedDeviceArray(axis_size, replica_results)\nelse:\n_, ids = onp.unique(assign_shards(nrep, axis_size), return_index=True)\nreturn onp.stack([replica_results[i] for i in ids])\n@@ -221,18 +215,25 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nclass ShardedDeviceArray(xla.DeviceArray):\n- # we're reusing the 'device_buffer' slot to mean a list of device buffers\n+ __slots__ = [\"device_buffers\", \"nrep\"]\n+\n+ def __init__(self, axis_size, replica_results):\n+ self.device_buffers = [res.device_buffer for res in replica_results]\n+ self.nrep = len(replica_results)\n+ r = replica_results[0]\n+ self.shape = (axis_size,) + r.shape\n+ self.dtype = r.dtype\n+ self.ndim = 1 + r.ndim\n+ self.size = axis_size * r.size\n+ self._npy_value = None\n+\n@property\ndef _value(self):\nif self._npy_value is None:\n- npy_shards = [buf.to_py() for buf in self.device_buffer]\n+ npy_shards = [buf.to_py() for buf in self.device_buffers]\nself._npy_value = unshard_output(self.shape[0], npy_shards)\nreturn self._npy_value\n- @property\n- def nrep(self):\n- return len(self.device_buffer)\n-\ncore.pytype_aval_mappings[ShardedDeviceArray] = ConcreteArray\nxla.pytype_aval_mappings[ShardedDeviceArray] = \\\nxla.pytype_aval_mappings[xla.DeviceArray]\n" } ]
Python
Apache License 2.0
google/jax
minor cleanup of sharded device-persistent values
260,335
24.02.2019 18:33:59
28,800
b667ac19dc975a7ccefd0b11d5c7e3bc4fa8fae9
add constant handler for ShardedDeviceArray
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -240,6 +240,9 @@ xla.pytype_aval_mappings[ShardedDeviceArray] = \\\nxla.canonicalize_dtype_handlers[ShardedDeviceArray] = \\\nxla.canonicalize_dtype_handlers[xla.DeviceArray]\n+xb.register_constant_handler(ShardedDeviceArray,\n+ xla._device_array_constant_handler)\n+\ndef xla_pcall_impl(fun, *args, **params):\naxis_name = params.pop('axis_name')\n" } ]
Python
Apache License 2.0
google/jax
add constant handler for ShardedDeviceArray
260,335
24.02.2019 18:49:48
28,800
b90f5d80cdf9b2e820f08879d569e5dd832ea847
use 'device_num' not 'replica_num', leave a todo
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -44,7 +44,6 @@ map = safe_map\n### util\n-\ndef shard_arg(nrep, arg):\nif type(arg) is ShardedDeviceArray and arg.nrep == nrep:\nreturn arg.device_buffers\n@@ -61,6 +60,7 @@ def unshard_output(axis_size, replica_results):\n_, ids = onp.unique(assign_shards(nrep, axis_size), return_index=True)\nreturn onp.stack([replica_results[i] for i in ids])\n+# TODO(mattjj): this code needs to map from replica number to device number\ndef assign_shards(nrep, size):\ngroupsize, ragged = divmod(nrep, size)\nassert not ragged\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -81,17 +81,17 @@ def execute_compiled_primitive(compiled, result_handler, *args):\ninput_bufs = [device_put(x) for x in args]\nreturn result_handler(compiled.Execute(input_bufs, not core.skip_checks))\n-def device_put(x, replica_num=0):\n+def device_put(x, device_num=0):\nx = canonicalize_pyval_dtype(x)\nif type(x) is DeviceArray:\n- if x.device_buffer.device() == replica_num:\n+ if x.device_buffer.device() == device_num:\nreturn x.device_buffer\nelse:\n- return device_put(x.device_buffer.to_py(), replica_num)\n+ return device_put(x.device_buffer.to_py(), device_num)\nelif isinstance(x, DeviceConstant):\n- return instantiate_device_constant(x, replica_num=replica_num)\n+ return instantiate_device_constant(x, device_num=device_num)\nelse:\n- return xb.device_put(x, replica_num) # round-trips tuple elements\n+ return xb.device_put(x, device_num) # round-trips tuple elements\ndef result_handler(result_shape):\nif type(result_shape) is ResultArray and FLAGS.jax_device_values:\n@@ -356,17 +356,17 @@ class DeviceConstant(DeviceArray):\ndef constant_handler(c, constant_instance, canonicalize_types=True):\nassert False\n-def instantiate_device_constant(const, cutoff=1e6, replica_num=0):\n+def instantiate_device_constant(const, cutoff=1e6, device_num=0):\n# dispatch an XLA Computation to build the constant on the device if it's\n# large, or alternatively build it on the host and transfer it if it's small\nassert isinstance(const, DeviceConstant)\nif const.size > cutoff:\nc = xb.make_computation_builder(\"constant_instantiating_computation\")\nxla_const = const.constant_handler(c, const)\n- compiled = c.Build(xla_const).Compile((), xb.get_compile_options(replica_num))\n+ compiled = c.Build(xla_const).Compile((), xb.get_compile_options(device_num))\nreturn compiled.Execute(())\nelse:\n- return xb.device_put(onp.asarray(const), replica_num)\n+ return xb.device_put(onp.asarray(const), device_num)\ndef xla_shape(x):\n" } ]
Python
Apache License 2.0
google/jax
use 'device_num' not 'replica_num', leave a todo
260,477
25.02.2019 09:53:08
28,800
0b60efb6ce81fbfb0a38853c638a20686aa6d0d0
Add maml tutorial notebook.
[ { "change_type": "MODIFY", "old_path": "notebooks/maml.ipynb", "new_path": "notebooks/maml.ipynb", "diff": "\"- how to fit a sinusoid function with a neural network (and do auto-batching with vmap)\\n\",\n\"- how to implement MAML and check its numerics\\n\",\n\"- how to implement MAML for sinusoid task (single-task objective, batching task instances).\\n\",\n- \"- extending MAML to handle batching at the task-level\\n\",\n- \"\\n\",\n- \"## Installing Dependencies\\n\",\n- \"\\n\",\n- \"Download/clone the git repository and install dependencies.\\n\",\n- \"\\n\",\n- \"```\\n\",\n- \"git clone https://github.com/ericjang/maml-jax.git\\n\",\n- \"cd maml-jax\\n\",\n- \"pip install -r requirements.txt\\n\",\n- \"```\\n\",\n- \"\\n\",\n- \"You will also need to compile Jax/Jaxlib from source:\\n\",\n- \"\\n\",\n- \"```\\n\",\n- \"git clone https://github.com/google/jax\\n\",\n- \"cd jax\\n\",\n- \"python build/build.py # optionally add --enable_cuda \\n\",\n- \"pip install -e build # install jaxlib (includes XLA)\\n\",\n- \"pip install -e . # install jax\\n\",\n- \"```\"\n+ \"- extending MAML to handle batching at the task-level\\n\"\n]\n},\n{\n" } ]
Python
Apache License 2.0
google/jax
Add maml tutorial notebook.
260,335
25.02.2019 10:14:47
28,800
3dc3f4dc7df502b05fcec1c325a217bf48e75f8d
fix some ShardedDeviceArray logic
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -44,24 +44,64 @@ map = safe_map\n### util\n-def shard_arg(nrep, arg):\n+def shard_arg(device_ordinals, nrep, arg):\n+ \"\"\"Shard an argument data array arg along its leading axis.\n+\n+ Args:\n+ # TODO(mattjj)\n+\n+ Returns:\n+ A list of length nrep of DeviceValues indexed by replica number, where the\n+ nth element is the argument to be passed to the nth replica.\n+ \"\"\"\n+ assignments = assign_shards_to_replicas(nrep, arg.shape[0])\nif type(arg) is ShardedDeviceArray and arg.nrep == nrep:\n- return arg.device_buffers\n+ # TODO(mattjj,phawkins): could make this exchange more efficient\n+ def replace_shard(buf, device_num):\n+ if buf.device() == device_num:\n+ return buf\n+ else:\n+ msg = \"Warning: device data movement on dispatch: {} to {}.\"\n+ print(msg.format(buf.device(), device_num))\n+ return xla.device_put(buf.to_py(), device_num)\n+ return [replace_shard(buf, device_ordinals[n])\n+ for buf, n in zip(arg.device_buffers, assignments)]\nelse:\nshards = [arg[i] for i in range(arg.shape[0])]\n- assignments = assign_shards(nrep, arg.shape[0])\n- return [xla.device_put(shards[i], n) for n, i in enumerate(assignments)]\n+ return [xla.device_put(shards[i], device_ordinals[n])\n+ for n, i in enumerate(assignments)]\ndef unshard_output(axis_size, replica_results):\n+ \"\"\"Collect together replica results into a result value.\n+\n+ Args:\n+ axis_size: size of the sharded output data axis.\n+ replica_results: list of either ndarrays or DeviceArrays indexed by replica\n+ number.\n+\n+ Returns:\n+ Either an ndarray or a ShardedDeviceArray representing the result of the\n+ computation, stacking together the results from the replicas.\n+ \"\"\"\nnrep = len(replica_results)\nif all(type(res) is xla.DeviceArray for res in replica_results):\nreturn ShardedDeviceArray(axis_size, replica_results)\nelse:\n- _, ids = onp.unique(assign_shards(nrep, axis_size), return_index=True)\n+ assignments = assign_shards_to_replicas(nrep, axis_size)\n+ _, ids = onp.unique(assignments, return_index=True)\nreturn onp.stack([replica_results[i] for i in ids])\n-# TODO(mattjj): this code needs to map from replica number to device number\n-def assign_shards(nrep, size):\n+def assign_shards_to_replicas(nrep, size):\n+ \"\"\"Produce a mapping from replica id to shard index.\n+\n+ Args:\n+ nrep: int, number of relpicas (a computation-dependent value).\n+ size: int, size of the data array axis being sharded.\n+\n+ Returns:\n+ A tuple of integers of length nrep in which the elements take on values from\n+ 0 to size-1. Replica n is assgined shard data_array[assignments[n]].\n+ \"\"\"\ngroupsize, ragged = divmod(nrep, size)\nassert not ragged\nindices = onp.tile(onp.arange(size)[:, None], (1, groupsize))\n@@ -138,7 +178,6 @@ def axis_groups(axis_env, name):\ndef compile_replicated(jaxpr, axis_name, axis_size, consts, *abstract_args):\nnum_replicas = axis_size * jaxpr_replicas(jaxpr)\n- assert num_replicas <= xb.get_replica_count()\naxis_env = AxisEnv(num_replicas, [axis_name], [axis_size])\narg_shapes = list(map(xla_shape, abstract_args))\nbuilt_c = replicated_comp(jaxpr, axis_env, consts, (), *arg_shapes)\n@@ -276,13 +315,16 @@ def parallel_callable(fun, axis_name, axis_size, *avals):\nout = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\ncompiled, nrep, result_shape = out\ndel master, consts, jaxpr, env\n+ handle_arg = partial(shard_arg, compiled._device_ordinals, nrep)\nhandle_result = xla.result_handler(result_shape)\n- return partial(execute_replicated, compiled, pval, axis_size, nrep, handle_result)\n+ return partial(execute_replicated, compiled, pval, axis_size, nrep,\n+ handle_arg, handle_result)\n-def execute_replicated(compiled, pval, axis_size, nrep, handler, out_tree, *args):\n- input_bufs = zip(*map(partial(shard_arg, nrep), args)) if args else [[]] * nrep\n+def execute_replicated(compiled, pval, axis_size, nrep, handle_in, handle_out,\n+ out_tree, *args):\n+ input_bufs = zip(*map(handle_in, args)) if args else [[]] * nrep\nout_bufs = compiled.ExecutePerReplica(input_bufs)\n- replica_results = [merge_pvals(handler(buf), pval) for buf in out_bufs]\n+ replica_results = [merge_pvals(handle_out(buf), pval) for buf in out_bufs]\nif out_tree is xla.leaf:\nreturn unshard_output(axis_size, replica_results)\nelse:\n" }, { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -203,9 +203,9 @@ def _get_backend():\nreturn backend()\n-def device_put(pyval, replica=0):\n+def device_put(pyval, device_num=0):\nclient = get_xla_client()\n- return client.LocalBuffer.from_pyval(pyval, replica, backend=_get_backend())\n+ return client.LocalBuffer.from_pyval(pyval, device_num, backend=_get_backend())\nShape = xla_client.Shape # pylint: disable=invalid-name\n" } ]
Python
Apache License 2.0
google/jax
fix some ShardedDeviceArray logic
260,335
25.02.2019 13:40:17
28,800
8c5e41042b82b5dc6bc0506422d00720e7d7afa0
fix bug in instantiate_device_constant
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -359,11 +359,12 @@ class DeviceConstant(DeviceArray):\ndef instantiate_device_constant(const, cutoff=1e6, device_num=0):\n# dispatch an XLA Computation to build the constant on the device if it's\n# large, or alternatively build it on the host and transfer it if it's small\n+ # TODO(mattjj): need a way to instantiate on a specific device\nassert isinstance(const, DeviceConstant)\n- if const.size > cutoff:\n+ if const.size > cutoff and device_num == 0:\nc = xb.make_computation_builder(\"constant_instantiating_computation\")\nxla_const = const.constant_handler(c, const)\n- compiled = c.Build(xla_const).Compile((), xb.get_compile_options(device_num))\n+ compiled = c.Build(xla_const).Compile((), xb.get_compile_options())\nreturn compiled.Execute(())\nelse:\nreturn xb.device_put(onp.asarray(const), device_num)\n" } ]
Python
Apache License 2.0
google/jax
fix bug in instantiate_device_constant
260,335
25.02.2019 13:48:01
28,800
a37703552faa536152009bebaa4bc800d5318c92
add test for device constant compile options bug
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -337,6 +337,9 @@ class APITest(jtu.JaxTestCase):\nf(2)\nassert len(effects) == 3\n+ def test_large_device_constant(self):\n+ jit(lambda x: x)(np.zeros(int(2e6))) # doesn't crash\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
add test for device constant compile options bug
260,335
25.02.2019 13:49:40
28,800
7701feb66c68d0be6970f31495a652463f48be52
revise large device constant test
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -338,7 +338,8 @@ class APITest(jtu.JaxTestCase):\nassert len(effects) == 3\ndef test_large_device_constant(self):\n- jit(lambda x: x)(np.zeros(int(2e6))) # doesn't crash\n+ ans = jit(lambda x: 2 * x)(np.ones(int(2e6))) # doesn't crash\n+ self.assertAllClose(ans, 2., check_dtypes=False)\nif __name__ == '__main__':\n" } ]
Python
Apache License 2.0
google/jax
revise large device constant test
260,335
27.02.2019 07:42:26
28,800
02124e31bf00f650bb1cbf66114244a005acf881
fix bug in transpose with order='F' (fixes
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -597,19 +597,18 @@ def angle(x):\n@_wraps(onp.reshape)\ndef reshape(a, newshape, order=\"C\"): # pylint: disable=missing-docstring\n- if order == \"C\" or order is None:\n- dims = None\n+ dummy_val = onp.broadcast_to(0, shape(a)) # zero strides\n+ computed_newshape = onp.reshape(dummy_val, newshape).shape\n+\n+ if order == \"C\":\n+ return lax.reshape(a, computed_newshape, None)\nelif order == \"F\":\n- dims = onp.arange(ndim(a))[::-1]\n+ return lax.reshape(a, computed_newshape[::-1], None).T\nelif order == \"A\":\nraise NotImplementedError(\"np.reshape order=A is not implemented.\")\nelse:\nraise ValueError(\"Unexpected value for 'order' argument: {}.\".format(order))\n- dummy_val = onp.broadcast_to(0, shape(a)) # zero strides\n- computed_newshape = onp.reshape(dummy_val, newshape).shape\n- return lax.reshape(a, computed_newshape, dims)\n-\n@_wraps(onp.ravel)\ndef ravel(a, order=\"C\"):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1327,6 +1327,13 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nresult = api.grad(test_fail)(x)\nassert not onp.any(onp.isnan(result))\n+ def testIssue453(self):\n+ # https://github.com/google/jax/issues/453\n+ a = onp.arange(6) + 1\n+ ans = lnp.reshape(a, (3, 2), order='F')\n+ expected = onp.reshape(a, (3, 2), order='F')\n+ self.assertAllClose(ans, expected, check_dtypes=True)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
fix bug in transpose with order='F' (fixes #453)
260,335
27.02.2019 07:50:19
28,800
c8b9fe23d65555a9bd5329f7024b6bcccfc9879c
fix in full, more exhaustive tests
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -603,7 +603,8 @@ def reshape(a, newshape, order=\"C\"): # pylint: disable=missing-docstring\nif order == \"C\":\nreturn lax.reshape(a, computed_newshape, None)\nelif order == \"F\":\n- return lax.reshape(a, computed_newshape[::-1], None).T\n+ dims = onp.arange(ndim(a))[::-1]\n+ return lax.reshape(a, computed_newshape[::-1], dims).T\nelif order == \"A\":\nraise NotImplementedError(\"np.reshape order=A is not implemented.\")\nelse:\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -859,12 +859,14 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_inshape={}_outshape={}\".format(\n+ {\"testcase_name\": \"_inshape={}_outshape={}_order={}\".format(\njtu.format_shape_dtype_string(arg_shape, dtype),\n- jtu.format_shape_dtype_string(out_shape, dtype)),\n+ jtu.format_shape_dtype_string(out_shape, dtype),\n+ order),\n\"arg_shape\": arg_shape, \"out_shape\": out_shape, \"dtype\": dtype,\n- \"rng\": jtu.rand_default()}\n+ \"order\": order, \"rng\": jtu.rand_default()}\nfor dtype in default_dtypes\n+ for order in [\"C\", \"F\"]\nfor arg_shape, out_shape in [\n(jtu.NUMPY_SCALAR_SHAPE, (1, 1, 1)),\n((), (1, 1, 1)),\n@@ -875,9 +877,9 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n((2, 1, 4), (-1,)),\n((2, 2, 4), (2, 8))\n]))\n- def testReshape(self, arg_shape, out_shape, dtype, rng):\n- onp_fun = lambda x: onp.reshape(x, out_shape)\n- lnp_fun = lambda x: lnp.reshape(x, out_shape)\n+ def testReshape(self, arg_shape, out_shape, dtype, order, rng):\n+ onp_fun = lambda x: onp.reshape(x, out_shape, order=order)\n+ lnp_fun = lambda x: lnp.reshape(x, out_shape, order=order)\nargs_maker = lambda: [rng(arg_shape, dtype)]\nself._CheckAgainstNumpy(onp_fun, lnp_fun, args_maker, check_dtypes=True)\nself._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n" } ]
Python
Apache License 2.0
google/jax
fix #453 in full, more exhaustive tests
260,335
28.02.2019 20:25:09
28,800
0927b667744bccaa496e21ff893ae957f99c5ef1
update XLA and jaxlib
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -17,10 +17,10 @@ http_archive(\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"ba253da211d3d22255ca6afa204eedd8348cae4a1e3a726684eb76e18de90df6\",\n- strip_prefix = \"tensorflow-00afc7bb81d6d36a0f619c08c011abe08965a25b\",\n+ sha256 = \"439598337c4eb0b8c2ad31d53fbb1878567de2f69ddd9b059a4909a3eefc333c\",\n+ strip_prefix = \"tensorflow-ba48c8e6fb610b820526ad231269e5741df616ec\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/00afc7bb81d6d36a0f619c08c011abe08965a25b.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/ba48c8e6fb610b820526ad231269e5741df616ec.tar.gz\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "build/jaxlib/version.py", "new_path": "build/jaxlib/version.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-__version__ = \"0.1.10\"\n+__version__ = \"0.1.11\"\n" } ]
Python
Apache License 2.0
google/jax
update XLA and jaxlib
260,403
01.03.2019 13:12:47
28,800
c3cbf4a20aef44c63a0d76e9539481d266bfd4e1
allow apply_fns to take general kwargs, not just rng
[ { "change_type": "MODIFY", "old_path": "jax/experimental/stax.py", "new_path": "jax/experimental/stax.py", "diff": "@@ -91,7 +91,7 @@ def Dense(out_dim, W_init=glorot(), b_init=randn()):\noutput_shape = input_shape[:-1] + (out_dim,)\nW, b = W_init((input_shape[-1], out_dim)), b_init((out_dim,))\nreturn output_shape, (W, b)\n- def apply_fun(params, inputs, rng=None):\n+ def apply_fun(params, inputs, **kwargs):\nW, b = params\nreturn np.dot(inputs, W) + b\nreturn init_fun, apply_fun\n@@ -115,7 +115,7 @@ def GeneralConv(dimension_numbers, out_chan, filter_shape,\nbias_shape = tuple(itertools.dropwhile(lambda x: x == 1, bias_shape))\nW, b = W_init(kernel_shape), b_init(bias_shape)\nreturn output_shape, (W, b)\n- def apply_fun(params, inputs, rng=None):\n+ def apply_fun(params, inputs, **kwargs):\nW, b = params\nreturn lax.conv_general_dilated(inputs, W, strides, padding, one, one,\ndimension_numbers) + b\n@@ -134,7 +134,7 @@ def BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True,\nshape = tuple(itertools.dropwhile(lambda x: x == 1, shape))\nbeta, gamma = _beta_init(shape), _gamma_init(shape)\nreturn input_shape, (beta, gamma)\n- def apply_fun(params, x, rng=None):\n+ def apply_fun(params, x, **kwargs):\nbeta, gamma = params\nmean, var = np.mean(x, axis, keepdims=True), fastvar(x, axis, keepdims=True)\nz = (x - mean) / np.sqrt(var + epsilon)\n@@ -145,9 +145,9 @@ def BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True,\nreturn init_fun, apply_fun\n-def _elemwise_no_params(fun, **kwargs):\n+def _elemwise_no_params(fun, **fun_kwargs):\ninit_fun = lambda input_shape: (input_shape, ())\n- apply_fun = lambda params, inputs, rng=None: fun(inputs, **kwargs)\n+ apply_fun = lambda params, inputs, **kwargs: fun(inputs, **fun_kwargs)\nreturn init_fun, apply_fun\nTanh = _elemwise_no_params(np.tanh)\nRelu = _elemwise_no_params(relu)\n@@ -167,7 +167,7 @@ def _pooling_layer(reducer, init_val, rescaler=None):\ndef init_fun(input_shape):\nout_shape = lax.reduce_window_shape_tuple(input_shape, dims, strides, padding)\nreturn out_shape, ()\n- def apply_fun(params, inputs, rng=None):\n+ def apply_fun(params, inputs, **kwargs):\nout = lax.reduce_window(inputs, init_val, reducer, dims, strides, padding)\nreturn rescale(out, inputs) if rescale else out\nreturn init_fun, apply_fun\n@@ -190,7 +190,7 @@ def Flatten():\ndef init_fun(input_shape):\noutput_shape = input_shape[0], reduce(op.mul, input_shape[1:], 1)\nreturn output_shape, ()\n- def apply_fun(params, inputs, rng=None):\n+ def apply_fun(params, inputs, **kwargs):\nreturn np.reshape(inputs, (inputs.shape[0], -1))\nreturn init_fun, apply_fun\nFlatten = Flatten()\n@@ -199,7 +199,7 @@ Flatten = Flatten()\ndef Identity():\n\"\"\"Layer construction function for an identity layer.\"\"\"\ninit_fun = lambda input_shape: (input_shape, ())\n- apply_fun = lambda params, inputs, rng=None: inputs\n+ apply_fun = lambda params, inputs, **kwargs: inputs\nreturn init_fun, apply_fun\nIdentity = Identity()\n@@ -207,14 +207,14 @@ Identity = Identity()\ndef FanOut(num):\n\"\"\"Layer construction function for a fan-out layer.\"\"\"\ninit_fun = lambda input_shape: ([input_shape] * num, ())\n- apply_fun = lambda params, inputs, rng=None: [inputs] * num\n+ apply_fun = lambda params, inputs, **kwargs: [inputs] * num\nreturn init_fun, apply_fun\ndef FanInSum():\n\"\"\"Layer construction function for a fan-in sum layer.\"\"\"\ninit_fun = lambda input_shape: (input_shape[0], ())\n- apply_fun = lambda params, inputs, rng=None: sum(inputs)\n+ apply_fun = lambda params, inputs, **kwargs: sum(inputs)\nreturn init_fun, apply_fun\nFanInSum = FanInSum()\n@@ -226,7 +226,7 @@ def FanInConcat(axis=-1):\nconcat_size = sum(shape[ax] for shape in input_shape)\nout_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]\nreturn out_shape, ()\n- def apply_fun(params, inputs, rng=None):\n+ def apply_fun(params, inputs, **kwargs):\nreturn np.concatenate(inputs, axis)\nreturn init_fun, apply_fun\n@@ -235,7 +235,8 @@ def Dropout(rate, mode='train'):\n\"\"\"Layer construction function for a dropout layer with given rate.\"\"\"\ndef init_fun(input_shape):\nreturn input_shape, ()\n- def apply_fun(params, inputs, rng):\n+ def apply_fun(params, inputs, **kwargs):\n+ rng = kwargs.get('rng', None)\nif rng is None:\nmsg = (\"Dropout layer requires apply_fun to be called with a PRNG key \"\n\"argument. That is, instead of `apply_fun(params, inputs)`, call \"\n@@ -271,10 +272,11 @@ def serial(*layers):\ninput_shape, param = init_fun(input_shape)\nparams.append(param)\nreturn input_shape, params\n- def apply_fun(params, inputs, rng=None):\n+ def apply_fun(params, inputs, **kwargs):\n+ rng = kwargs.pop('rng', None)\nrngs = random.split(rng, nlayers) if rng is not None else (None,) * nlayers\nfor fun, param, rng in zip(apply_funs, params, rngs):\n- inputs = fun(param, inputs, rng)\n+ inputs = fun(param, inputs, rng=rng, **kwargs)\nreturn inputs\nreturn init_fun, apply_fun\n@@ -298,9 +300,10 @@ def parallel(*layers):\ninit_funs, apply_funs = zip(*layers)\ndef init_fun(input_shape):\nreturn zip(*[init(shape) for init, shape in zip(init_funs, input_shape)])\n- def apply_fun(params, inputs, rng=None):\n+ def apply_fun(params, inputs, **kwargs):\n+ rng = kwargs.pop('rng', None)\nrngs = random.split(rng, nlayers) if rng is not None else (None,) * nlayers\n- return [f(p, x, r) for f, p, x, r in zip(apply_funs, params, inputs, rngs)]\n+ return [f(p, x, rng=r, **kwargs) for f, p, x, r in zip(apply_funs, params, inputs, rngs)]\nreturn init_fun, apply_fun\n@@ -318,6 +321,6 @@ def shape_dependent(make_layer):\n\"\"\"\ndef init_fun(input_shape):\nreturn make_layer(input_shape)[0](input_shape)\n- def apply_fun(params, inputs, rng=None):\n- return make_layer(inputs.shape)[1](params, inputs, rng)\n+ def apply_fun(params, inputs, **kwargs):\n+ return make_layer(inputs.shape)[1](params, inputs, **kwargs)\nreturn init_fun, apply_fun\n" }, { "change_type": "MODIFY", "old_path": "tests/stax_test.py", "new_path": "tests/stax_test.py", "diff": "@@ -43,7 +43,7 @@ def _CheckShapeAgreement(test_case, init_fun, apply_fun, input_shape):\nresult_shape, params = init_fun(input_shape)\ninputs = random_inputs(onp.random.RandomState(0), input_shape)\nrng_key = random.PRNGKey(0)\n- result = apply_fun(params, inputs, rng_key)\n+ result = apply_fun(params, inputs, rng=rng_key)\ntest_case.assertEqual(result.shape, result_shape)\n" } ]
Python
Apache License 2.0
google/jax
allow apply_fns to take general kwargs, not just rng
260,314
02.03.2019 19:11:16
18,000
f05d0bcbd80f7e4468464bcf10d35c9be8e39621
fix bernoulli shape bug
[ { "change_type": "MODIFY", "old_path": "jax/random.py", "new_path": "jax/random.py", "diff": "@@ -379,5 +379,5 @@ def bernoulli(key, mean=onp.float32(0.5), shape=()):\nif not onp.issubdtype(lax._dtype(mean), onp.float32):\nmean = lax.convert_element_type(mean, onp.float32)\nif onp.shape(mean) != shape:\n- mean = lax.broadcast(mean, shape)\n+ mean = np.broadcast_to(mean, shape)\nreturn lax.lt(uniform(key, shape), mean)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -149,6 +149,11 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertFalse(onp.all(perm1 == x)) # seems unlikely!\nself.assertTrue(onp.all(onp.sort(perm1) == x))\n+ def testBernoulli(self):\n+ key = random.PRNGKey(0)\n+ x = random.bernoulli(key, onp.array([0.2, 0.3]), shape=(3, 2))\n+ assert x.shape == (3, 2)\n+\ndef testIssue222(self):\nx = random.randint(random.PRNGKey(10003), (), 0, 0)\nassert x == 0\n" } ]
Python
Apache License 2.0
google/jax
fix bernoulli shape bug
260,335
02.03.2019 17:52:28
28,800
234f48769f648e80007e415cc1a9bf664a606df3
get rid of lax's OpaqueParams class That class was once used for smuggling consts into primitives for lax.while_loop and lax.cond, but it's no longer needed because those bind rules take constants as positional arguments now (and hence handle closed-over tracers).
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -872,25 +872,16 @@ def while_loop(cond_fun, body_fun, init_val):\npval_flat = _abstractify(init_val_flat)\ncond_jaxpr, _, cond_consts = pe.trace_to_jaxpr(flat_cond_fun, (pval_flat,))\nbody_jaxpr, pvout, body_consts = pe.trace_to_jaxpr(flat_body_fun, (pval_flat,))\n- abs_out, _ = pvout\n+ aval_out, _ = pvout\nif out_tree() != in_tree:\nraise TypeError(\"body_fun input and output must have identical structure\")\n- params = _OpaqueParam((abs_out, cond_jaxpr, body_jaxpr))\n- out_flat = while_p.bind(init_val_flat, core.pack(cond_consts), core.pack(body_consts),\n- opaque_params=params)\n+ out_flat = while_p.bind(init_val_flat, core.pack(cond_consts),\n+ core.pack(body_consts), aval_out=aval_out,\n+ cond_jaxpr=cond_jaxpr, body_jaxpr=body_jaxpr)\nreturn build_tree(out_tree(), out_flat)\n-class _OpaqueParam(object):\n- __slots__ = [\"val\", \"id\"]\n- def __init__(self, val):\n- self.val = val\n- self.id = next(opaque_param_ids)\n- def __hash__(self):\n- return self.id\n-opaque_param_ids = itertools.count()\n-\ndef cond(pred, true_operand, true_fun, false_operand, false_fun):\ndef trace_jaxpr(fun, operand):\n@@ -3538,14 +3529,14 @@ ad.primitive_transposes[sort_key_val_p] = _sort_key_val_transpose_rule\nbatching.primitive_batchers[sort_key_val_p] = _sort_key_val_batch_rule\n-def _while_loop_abstract_eval(init_val, cond_consts, body_consts, opaque_params):\n- abs_out = opaque_params.val[0]\n- return maybe_tracer_tuple_to_abstract_tuple(abs_out)\n+def _while_loop_abstract_eval(init_val, cond_consts, body_consts, aval_out,\n+ cond_jaxpr, body_jaxpr):\n+ return maybe_tracer_tuple_to_abstract_tuple(aval_out)\n-def _while_loop_translation_rule(c, init_val, cond_consts, body_consts, opaque_params):\n+def _while_loop_translation_rule(c, init_val, cond_consts, body_consts,\n+ aval_out, cond_jaxpr, body_jaxpr):\nloop_carry = c.Tuple(init_val, cond_consts, body_consts)\nshape = c.GetShape(loop_carry)\n- _, cond_jaxpr, body_jaxpr = opaque_params.val\nloop_carry_var = pe.Var(0, \"loop_carry\")\noutvar = pe.Var(0, \"loop_carry_out\")\n" } ]
Python
Apache License 2.0
google/jax
get rid of lax's OpaqueParams class That class was once used for smuggling consts into primitives for lax.while_loop and lax.cond, but it's no longer needed because those bind rules take constants as positional arguments now (and hence handle closed-over tracers).
260,335
02.03.2019 18:08:34
28,800
65b6f19cf8a18e8cae43f60de14d5e5d8bb2caa4
add a better error message on cond pval join error
[ { "change_type": "MODIFY", "old_path": "jax/abstract_arrays.py", "new_path": "jax/abstract_arrays.py", "diff": "@@ -68,7 +68,10 @@ class UnshapedArray(core.AbstractValue):\nreturn self\ndef join(self, other):\n+ if self.dtype == other.dtype:\nreturn self\n+ else:\n+ raise TypeError(other)\ndef str_short(self):\nreturn onp.dtype(self.dtype).name\n" }, { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -899,7 +899,11 @@ def cond(pred, true_operand, true_fun, false_operand, false_fun):\nmsg = \"true_fun and false_fun outputs must have identical structure\"\nraise TypeError(msg)\n+ try:\njoined_pval = pe.join_pvals(true_pval, false_pval)\n+ except TypeError:\n+ msg = \"could not merge true_fun and false_fun output pvals: {} and {}.\"\n+ raise TypeError(msg.format(true_pval, false_pval))\nrevis = _revise_cond_jaxpr(joined_pval, true_pval, true_jaxpr, true_consts)\ntrue_jaxpr, true_consts = revis\nrevis = _revise_cond_jaxpr(joined_pval, false_pval, false_jaxpr, false_consts)\n" } ]
Python
Apache License 2.0
google/jax
add a better error message on cond pval join error
260,335
28.02.2019 12:07:33
28,800
b94c3fea0d1532484dc3407495f468bc95fb1b86
fix abstract_eval_fun kwarg handling
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -179,7 +179,7 @@ def partial_eval_wrapper(avals, *consts, **kwargs):\ndef abstract_eval_fun(fun, *avals, **params):\npvs_in = [PartialVal((a, unit)) for a in avals]\n- _, pvout, _ = trace_unwrapped_to_jaxpr(fun, pvs_in, **params)\n+ _, pvout, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvs_in)\naval_out, _ = pvout\nreturn aval_out\n" } ]
Python
Apache License 2.0
google/jax
fix abstract_eval_fun kwarg handling
260,335
01.03.2019 09:46:32
28,800
71d8bdc46c17bf49c993c1beecdf7ff3a2ed2852
wip w/ phawkins
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -958,9 +958,19 @@ def _revise_cond_jaxpr(new_pval, old_pval, jaxpr, consts):\ndef scan(f, a, bs):\n- return scan_p.bind(a, bs, f=f)\n+ assert type(bs) is tuple\n+ assert type(a) is tuple\n-def _scan_impl(a, bs, f=None):\n+ a = core.pack(a)\n+ bs = core.pack(bs)\n+ a_pv = _abstractify(a)\n+ b_pv = _abstractify(core.pack([b[0] for b in bs]))\n+ jaxpr, _, consts = pe.trace_to_jaxpr(lu.wrap_init(f), (a_pv, b_pv))\n+ assert not consts # TODO\n+\n+ return scan_p.bind(a, bs, jaxpr=jaxpr)\n+\n+def _scan_impl(a, bs, jaxpr):\n\"\"\"Scans over a list.\nArguments:\n@@ -968,8 +978,8 @@ def _scan_impl(a, bs, f=None):\na: `a` value.\nbs: `b` values.\n\"\"\"\n- a_flat, a_tree = tree_flatten(a)\n- bs_flat, bs_tree = tree_flatten(bs)\n+ a_flat = tuple(a)\n+ bs_flat = tuple(bs)\n# Verifies that the bs are all arrays of the same length\nif len(bs_flat) == 0:\n@@ -995,19 +1005,12 @@ def _scan_impl(a, bs, f=None):\ndef body_fun(i, vals):\na_flat, state_flat = vals\nassert len(a_flat) == len(state_flat)\n- a = tree_unflatten(a_tree, a_flat)\nb_flat = []\nfor b in bs_flat:\nb_flat.append(dynamic_index_in_dim(b, i, keepdims=False))\n- bs = tree_unflatten(bs_tree, b_flat)\n- a = f(a, bs)\n- a_out_flat, a_out_tree = tree_flatten(a)\n- if len(a_out_flat) != len(a_flat) or a_tree != a_out_tree:\n- raise ValueError(\n- \"The first input of f must have the same tree structure as the output: \"\n- \"{} vs {}.\".format(a_tree, a_out_tree))\n+ a_out_flat = core.eval_jaxpr(jaxpr, (), (), a_flat, core.pack(b_flat))\nstate_out_flat = []\nfor a, a_out, state in zip(a_flat, a_out_flat, state_flat):\n@@ -1018,10 +1021,10 @@ def _scan_impl(a, bs, f=None):\nstate_out = dynamic_update_index_in_dim(state, a_out[None, ...], i, axis=0)\nstate_out_flat.append(state_out)\n- return a_out_flat, state_out_flat\n+ return tuple(a_out_flat), state_out_flat\n_, out_flat = fori_loop(0, length, body_fun, (a_flat, out_flat))\n- return tree_unflatten(a_tree, out_flat)\n+ return core.pack(out_flat)\ndef _scan_jvp(primals, tangents, f=None):\n# (ap, bp), (adot, bdot)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scanplan.py", "diff": "+from functools import partial\n+import numpy as onp\n+\n+import jax.numpy as np\n+from jax import core\n+from jax import make_jaxpr, vjp\n+from jax import lax\n+\n+\n+def f(x, y):\n+ x_, = x\n+ y_, = y\n+ return core.pack((x_ * y_,))\n+\n+g = partial(lax.scan, f)\n+a = onp.array(7, onp.float32)\n+bs = onp.array([2, 4, -2, 6], onp.float32)\n+out = g((a,), (bs,))\n+\n+jaxpr = make_jaxpr(g)((a,), (bs,))\n+\n+\n+###\n+\n+# scan :: (a -> b -> a) -> a -> [b] -> [a]\n+\n+\n+# first scan\n+as_ = lax.scan(f, a, bs)\n+\n+# second scan\n+f_vjp = lambda args, ct: vjp(f, *args)[1](ct)\n+lax.scan(f_vjp, cts[-1], (as_, bs, cts)) # off by one stuff... draw boxes\n" } ]
Python
Apache License 2.0
google/jax
wip w/ phawkins
260,335
01.03.2019 13:16:44
28,800
a20e8982fa22c8e265fcff374c21ca9d8b2a3d53
completed scan (PAIR=hawkinsp@)
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -475,6 +475,8 @@ class AbstractTuple(AbstractValue, tuple):\ndef __repr__(self):\nreturn '({})'.format(','.join(map(repr, self)))\n+ # TODO(mattjj,phawkins): bool, maybe getitem\n+\nunit = JaxTuple(())\nunitvar = '*'\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -302,9 +302,16 @@ def xla_pcall_impl(fun, *args, **params):\nreturn xla.build_tree(iter(flat_ans), out_tree())\ndef abstractify(axis_size, x):\n- assert onp.shape(x)[0] == axis_size\n- aval = xla.abstractify(x)\n+ return _shard_aval(axis_size, xla.abstractify(x))\n+\n+def _shard_aval(axis_size, aval):\n+ if type(aval) is AbstractTuple:\n+ return AbstractTuple(map(partial(_shard_aval, axis_size), aval))\n+ elif type(aval) is ShapedArray:\n+ assert aval.shape[0] == axis_size\nreturn ShapedArray(aval.shape[1:], aval.dtype)\n+ else:\n+ raise TypeError(type(aval))\n@lu.memoize\ndef parallel_callable(fun, axis_name, axis_size, *avals):\n" }, { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -54,7 +54,7 @@ from .interpreters import ad\nfrom .interpreters import batching\nfrom .interpreters import parallel\nfrom .util import curry, memoize, safe_zip, unzip2, prod\n-from .tree_util import build_tree, tree_flatten, tree_unflatten\n+from .tree_util import build_tree, tree_unflatten\nfrom .lib import xla_bridge\nFLAGS = flags.FLAGS\n@@ -872,8 +872,8 @@ def while_loop(cond_fun, body_fun, init_val):\npval_flat = _abstractify(init_val_flat)\ncond_jaxpr, _, cond_consts = pe.trace_to_jaxpr(flat_cond_fun, (pval_flat,))\n- body_jaxpr, pvout, body_consts = pe.trace_to_jaxpr(flat_body_fun, (pval_flat,))\n- aval_out, _ = pvout\n+ body_jaxpr, pval_out, body_consts = pe.trace_to_jaxpr(flat_body_fun, (pval_flat,))\n+ aval_out, _ = pval_out\nif out_tree() != in_tree:\nraise TypeError(\"body_fun input and output must have identical structure\")\n@@ -958,19 +958,37 @@ def _revise_cond_jaxpr(new_pval, old_pval, jaxpr, consts):\ndef scan(f, a, bs):\n- assert type(bs) is tuple\n- assert type(a) is tuple\n-\n- a = core.pack(a)\n- bs = core.pack(bs)\n- a_pv = _abstractify(a)\n- b_pv = _abstractify(core.pack([b[0] for b in bs]))\n- jaxpr, _, consts = pe.trace_to_jaxpr(lu.wrap_init(f), (a_pv, b_pv))\n- assert not consts # TODO\n+ a, a_tree = pytree_to_flatjaxtuple(a)\n+ bs, b_tree = pytree_to_flatjaxtuple(bs) # b_tree is the same as bs_tree\n+ f, out_tree = pytree_fun_to_flatjaxtuple_fun(lu.wrap_init(f), (a_tree, b_tree))\n+\n+ if not len(bs):\n+ raise TypeError(\"bs argument to scan does not contain any arrays\")\n+ if any(b.ndim == 0 for b in bs):\n+ msg = \"bs argument arrays must be rank >=1, got shapes {}.\"\n+ raise TypeError(msg.format(\", \".format(str(b.shape) for b in bs)))\n+ if len({b.shape[0] for b in bs}) != 1:\n+ msg = \"arrays in bs must have equal most-major dimensions, got shapes {}.\"\n+ raise TypeError(msg.format(\", \".format(str(b.shape) for b in bs)))\n+\n+ a_pval = a_aval, _ = _abstractify(a)\n+ bs_aval, _ = _abstractify(bs)\n+ b_aval = core.AbstractTuple([ShapedArray(b.shape[1:], b.dtype) for b in bs_aval])\n+ b_pval = pe.PartialVal((b_aval, core.unit))\n+ jaxpr, pval_out, consts = pe.trace_to_jaxpr(f, (a_pval, b_pval))\n+ aval_out, _ = pval_out\n+\n+ if a_tree != out_tree():\n+ msg = \"scanned function input and output must have identical structure\"\n+ raise TypeError(msg)\n+ if a_aval != aval_out:\n+ msg = \"output shape mismatch for scanned function: {} vs {}\"\n+ raise TypeError(msg.format(a_aval, aval_out))\n- return scan_p.bind(a, bs, jaxpr=jaxpr)\n+ out = scan_p.bind(a, bs, core.pack(consts), aval_out=aval_out, jaxpr=jaxpr)\n+ return tree_unflatten(out_tree(), out)\n-def _scan_impl(a, bs, jaxpr):\n+def _scan_impl(a, bs, consts, aval_out, jaxpr):\n\"\"\"Scans over a list.\nArguments:\n@@ -978,53 +996,20 @@ def _scan_impl(a, bs, jaxpr):\na: `a` value.\nbs: `b` values.\n\"\"\"\n- a_flat = tuple(a)\n- bs_flat = tuple(bs)\n-\n- # Verifies that the bs are all arrays of the same length\n- if len(bs_flat) == 0:\n- raise ValueError(\"bs argument to scan does not contain any arrays\")\n-\n- if any(len(b.shape) == 0 for b in bs_flat):\n- msg = \"bs argument arrays must be rank >= 1, got shapes {}\"\n- raise ValueError(msg.format(\",\".join(str(b.shape) for b in bs_flat)))\n-\n- length = bs_flat[0].shape[0]\n- for b in bs_flat[1:]:\n- if b.shape[0] != length:\n- msg = (\"bs argument arrays must have equal most-major dimensions; got \"\n- \"shapes {}\")\n- raise ValueError(msg.format(\",\".join(str(b.shape) for b in bs_flat)))\n-\n- # Form the initial outputs as zeros like `a` with a new leading `length`\n- # dimension.\n- out_flat = []\n- for a in a_flat:\n- out_flat.append(full((length,) + tuple(a.shape), 0, _dtype(a)))\n+ length = tuple(bs)[0].shape[0]\n+ state = [full((length,) + elt.shape, 0, _dtype(elt)) for elt in a]\ndef body_fun(i, vals):\n- a_flat, state_flat = vals\n- assert len(a_flat) == len(state_flat)\n-\n- b_flat = []\n- for b in bs_flat:\n- b_flat.append(dynamic_index_in_dim(b, i, keepdims=False))\n-\n- a_out_flat = core.eval_jaxpr(jaxpr, (), (), a_flat, core.pack(b_flat))\n-\n- state_out_flat = []\n- for a, a_out, state in zip(a_flat, a_out_flat, state_flat):\n- if a.shape != a_out.shape:\n- raise ValueError(\n- \"Output shape mismatch for f: {} vs {}\".format(a.shape, a_out.shape))\n-\n- state_out = dynamic_update_index_in_dim(state, a_out[None, ...], i, axis=0)\n- state_out_flat.append(state_out)\n-\n- return tuple(a_out_flat), state_out_flat\n+ a, state = vals\n+ assert len(a) == len(state)\n+ b = [dynamic_index_in_dim(b, i, keepdims=False) for b in bs]\n+ a_out = core.eval_jaxpr(jaxpr, consts, (), a, core.pack(b))\n+ state_out = [dynamic_update_index_in_dim(s, a[None, ...], i, axis=0)\n+ for a, s in zip(a_out, state)]\n+ return a_out, state_out\n- _, out_flat = fori_loop(0, length, body_fun, (a_flat, out_flat))\n- return core.pack(out_flat)\n+ _, out = fori_loop(0, length, body_fun, (a, state))\n+ return core.pack(out)\ndef _scan_jvp(primals, tangents, f=None):\n# (ap, bp), (adot, bdot)\n@@ -1040,7 +1025,7 @@ def _scan_jvp(primals, tangents, f=None):\nscan_p = core.Primitive(\"scan\")\nscan_p.def_impl(_scan_impl)\n-scan_p.def_abstract_eval(partial(pe.abstract_eval_fun, _scan_impl))\n+scan_p.def_abstract_eval(partial(pe.abstract_eval_fun, _scan_impl)) # TODO\nxla.translations[scan_p] = partial(xla.lower_fun, _scan_impl)\nad.primitive_jvps[scan_p] = _scan_jvp\n" }, { "change_type": "MODIFY", "old_path": "jax/tree_util.py", "new_path": "jax/tree_util.py", "diff": "@@ -91,7 +91,6 @@ def build_tree(treedef, xs):\ntree_flatten = partial(walk_pytree, concatenate, lambda x: [x])\ndef tree_unflatten(treedef, xs):\n- # like build_tree, but handles empty containers in the tree\nreturn _tree_unflatten(iter(xs), treedef)\ndef _tree_unflatten(xs, treedef):\n" }, { "change_type": "MODIFY", "old_path": "scanplan.py", "new_path": "scanplan.py", "diff": "@@ -8,26 +8,23 @@ from jax import lax\ndef f(x, y):\n- x_, = x\n- y_, = y\n- return core.pack((x_ * y_,))\n+ return x * y\ng = partial(lax.scan, f)\na = onp.array(7, onp.float32)\nbs = onp.array([2, 4, -2, 6], onp.float32)\n-out = g((a,), (bs,))\n+out = g(a, bs)\n-jaxpr = make_jaxpr(g)((a,), (bs,))\n+jaxpr = make_jaxpr(g)(a, bs)\n###\n# scan :: (a -> b -> a) -> a -> [b] -> [a]\n+# # first scan\n+# as_ = lax.scan(f, a, bs)\n-# first scan\n-as_ = lax.scan(f, a, bs)\n-\n-# second scan\n-f_vjp = lambda args, ct: vjp(f, *args)[1](ct)\n-lax.scan(f_vjp, cts[-1], (as_, bs, cts)) # off by one stuff... draw boxes\n+# # second scan\n+# f_vjp = lambda args, ct: vjp(f, *args)[1](ct)\n+# lax.scan(f_vjp, cts[-1], (as_, bs, cts)) # off by one stuff... draw boxes\n" } ]
Python
Apache License 2.0
google/jax
completed scan (PAIR=hawkinsp@)
260,335
01.03.2019 13:37:49
28,800
abfb7e330a2c2e555fd4850c02669eddb8c73274
progress on scan jvp (pair w/
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -964,7 +964,7 @@ def scan(f, a, bs):\nif not len(bs):\nraise TypeError(\"bs argument to scan does not contain any arrays\")\n- if any(b.ndim == 0 for b in bs):\n+ if any([b.ndim == 0 for b in bs]):\nmsg = \"bs argument arrays must be rank >=1, got shapes {}.\"\nraise TypeError(msg.format(\", \".format(str(b.shape) for b in bs)))\nif len({b.shape[0] for b in bs}) != 1:\n@@ -1011,17 +1011,23 @@ def _scan_impl(a, bs, consts, aval_out, jaxpr):\n_, out = fori_loop(0, length, body_fun, (a, state))\nreturn core.pack(out)\n-def _scan_jvp(primals, tangents, f=None):\n- # (ap, bp), (adot, bdot)\n+def _scan_jvp(primals, tangents, aval_out, jaxpr):\n+ a, bs, consts_primals = primals\n+ a_dot, bs_dot, consts_tangents = tangents\n+ assert consts_tangents is ad_util.zero # TODO figure out\n+\n+ primal_out = scan_p.bind(a, bs, consts_primals,\n+ aval_out=aval_out, jaxpr=jaxpr)\n+\n+ # TODO jaxtuple packing issue\ndef f_jvp(a_pt, b_pt):\na, a_dot = a_pt\nb, b_dot = b_pt\n- return api.jvp(f, (a, b), (a_dot, b_dot))\n-\n- a, bs = primals\n- a_dot, bs_dot = tangents\n+ f = lambda a, b, c: core.eval_jaxpr(jaxpr, c, (), a, b)\n+ return api.jvp(f, (a, b, consts), (b, b_dot, consts_tangents))\n+ tangent_out = scan(f_jvp, (a, a_dot), (b, b_dot))\n- return scan(f_jvp, (a, a_dot), (bs, bs_dot))\n+ return primal_out, tangent_out\nscan_p = core.Primitive(\"scan\")\nscan_p.def_impl(_scan_impl)\n" }, { "change_type": "MODIFY", "old_path": "scanplan.py", "new_path": "scanplan.py", "diff": "@@ -3,7 +3,7 @@ import numpy as onp\nimport jax.numpy as np\nfrom jax import core\n-from jax import make_jaxpr, vjp\n+from jax import make_jaxpr, vjp, jvp\nfrom jax import lax\n@@ -18,6 +18,9 @@ out = g(a, bs)\njaxpr = make_jaxpr(g)(a, bs)\n+primal, tangent = jvp(g, (a, bs), (a, bs))\n+\n+\n###\n# scan :: (a -> b -> a) -> a -> [b] -> [a]\n" } ]
Python
Apache License 2.0
google/jax
progress on scan jvp (pair w/ @hawkinsp)
260,335
02.03.2019 21:24:23
28,800
ddd18dfebd53f3de1e153ef6287f49ca994ec5b1
update scan docstring, comment-out scan jvp
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -958,6 +958,19 @@ def _revise_cond_jaxpr(new_pval, old_pval, jaxpr, consts):\ndef scan(f, a, bs):\n+ \"\"\"Scans over the leading axis of an array.\n+\n+ Arguments:\n+ f: function with signature `a -> b -> a`\n+ a: `a` value, or a pytree of `a` values.\n+ bs: an array of `b` values, or a pytree of arrays of `b` values with the\n+ same leading axis size.\n+\n+ Returns:\n+ An array of `a` values, or a pytree of arrays of `a` values, representing\n+ the result of scanning the function `f` over the leading axis of `bs`, with\n+ each application producing an `a` for the next and collecting the results.\n+ \"\"\"\na, a_tree = pytree_to_flatjaxtuple(a)\nbs, b_tree = pytree_to_flatjaxtuple(bs) # b_tree is the same as bs_tree\nf, out_tree = pytree_fun_to_flatjaxtuple_fun(lu.wrap_init(f), (a_tree, b_tree))\n@@ -989,13 +1002,6 @@ def scan(f, a, bs):\nreturn tree_unflatten(out_tree(), out)\ndef _scan_impl(a, bs, consts, aval_out, jaxpr):\n- \"\"\"Scans over a list.\n-\n- Arguments:\n- f: function with signature `a -> b -> a`\n- a: `a` value.\n- bs: `b` values.\n- \"\"\"\nlength = tuple(bs)[0].shape[0]\nstate = [full((length,) + elt.shape, 0, _dtype(elt)) for elt in a]\n@@ -1011,15 +1017,15 @@ def _scan_impl(a, bs, consts, aval_out, jaxpr):\n_, out = fori_loop(0, length, body_fun, (a, state))\nreturn core.pack(out)\n+# TODO(mattjj, phawkins): figure out what to do with consts_tangents, and the\n+# jaxtuple packing issues\ndef _scan_jvp(primals, tangents, aval_out, jaxpr):\na, bs, consts_primals = primals\na_dot, bs_dot, consts_tangents = tangents\n- assert consts_tangents is ad_util.zero # TODO figure out\nprimal_out = scan_p.bind(a, bs, consts_primals,\naval_out=aval_out, jaxpr=jaxpr)\n- # TODO jaxtuple packing issue\ndef f_jvp(a_pt, b_pt):\na, a_dot = a_pt\nb, b_dot = b_pt\n@@ -1029,11 +1035,14 @@ def _scan_jvp(primals, tangents, aval_out, jaxpr):\nreturn primal_out, tangent_out\n+def _scan_abstract_eval(a, bs, consts, aval_out, jaxpr):\n+ return maybe_tracer_tuple_to_abstract_tuple(aval_out)\n+\nscan_p = core.Primitive(\"scan\")\nscan_p.def_impl(_scan_impl)\n-scan_p.def_abstract_eval(partial(pe.abstract_eval_fun, _scan_impl)) # TODO\n+scan_p.def_abstract_eval(_scan_abstract_eval)\nxla.translations[scan_p] = partial(xla.lower_fun, _scan_impl)\n-ad.primitive_jvps[scan_p] = _scan_jvp\n+# ad.primitive_jvps[scan_p] = _scan_jvp # TODO(mattjj, phawkins)\ndef tie_in(x, y):\n" } ]
Python
Apache License 2.0
google/jax
update scan docstring, comment-out scan jvp
260,335
02.03.2019 21:30:20
28,800
1a704f50b52d0757bf768ea7e43be508ae25777b
comment out scan jvp tests (wip)
[ { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -1432,7 +1432,7 @@ class LaxTest(jtu.JaxTestCase):\nself.assertAllClose(out, onp.array([9, 13, 11, 17], onp.float32),\ncheck_dtypes=True)\n- jtu.check_jvp(g, partial(api.jvp, g), (a, bs))\n+ # jtu.check_jvp(g, partial(api.jvp, g), (a, bs))\ndef testScanMul(self):\ndef f(x, y):\n@@ -1445,7 +1445,7 @@ class LaxTest(jtu.JaxTestCase):\nself.assertAllClose(out, onp.array([14, 56, -112, -672], onp.float32),\ncheck_dtypes=True)\n- jtu.check_jvp(g, partial(api.jvp, g), (a, bs))\n+ # jtu.check_jvp(g, partial(api.jvp, g), (a, bs))\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_lhs_shape={}_rhs_shape={}\"\n" } ]
Python
Apache License 2.0
google/jax
comment out scan jvp tests (wip)
260,335
02.03.2019 21:39:21
28,800
66624ef51f644b1a2ff80b0b2f3f03a1be01d52d
add a test for scan-of-jit
[ { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -1447,6 +1447,19 @@ class LaxTest(jtu.JaxTestCase):\n# jtu.check_jvp(g, partial(api.jvp, g), (a, bs))\n+ def testScanJit(self):\n+ @api.jit\n+ def f(x, yz):\n+ y, z = yz\n+ return 5. * lax.exp(lax.sin(x) * lax.cos(y)) + z\n+\n+ a = onp.array(7, onp.float32)\n+ bs = (onp.array([3., 1., -4., 1.], onp.float32),\n+ onp.array([5., 9., -2., 6.], onp.float32))\n+ ans = lax.scan(f, a, bs)\n+ expected = onp.array([7.609, 17.445, 7.52596, 14.3389172], onp.float32)\n+ self.assertAllClose(ans, expected, check_dtypes=True)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_lhs_shape={}_rhs_shape={}\"\n.format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n" } ]
Python
Apache License 2.0
google/jax
add a test for scan-of-jit
260,335
02.03.2019 21:43:40
28,800
acd9276f0dbf8a083a0b91b447577517ca8f5115
add __bool__ to jaxtuples / abstracttuples
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -475,7 +475,9 @@ class AbstractTuple(AbstractValue, tuple):\ndef __repr__(self):\nreturn '({})'.format(','.join(map(repr, self)))\n- # TODO(mattjj,phawkins): bool, maybe getitem\n+ def __bool__(self, ignored_tracer):\n+ return bool(self)\n+ __nonzero__ = __bool__\nunit = JaxTuple(())\n" }, { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -975,7 +975,7 @@ def scan(f, a, bs):\nbs, b_tree = pytree_to_flatjaxtuple(bs) # b_tree is the same as bs_tree\nf, out_tree = pytree_fun_to_flatjaxtuple_fun(lu.wrap_init(f), (a_tree, b_tree))\n- if not len(bs):\n+ if not bs:\nraise TypeError(\"bs argument to scan does not contain any arrays\")\nif any([b.ndim == 0 for b in bs]):\nmsg = \"bs argument arrays must be rank >=1, got shapes {}.\"\n" } ]
Python
Apache License 2.0
google/jax
add __bool__ to jaxtuples / abstracttuples
260,335
02.03.2019 21:44:35
28,800
1e0d04a3d7b23a64188b0a64d8de4dd5d6dd87cf
fix pxla.py typo
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -305,7 +305,7 @@ def abstractify(axis_size, x):\nreturn _shard_aval(axis_size, xla.abstractify(x))\ndef _shard_aval(axis_size, aval):\n- if type(aval) is AbstractTuple:\n+ if type(aval) is core.AbstractTuple:\nreturn AbstractTuple(map(partial(_shard_aval, axis_size), aval))\nelif type(aval) is ShapedArray:\nassert aval.shape[0] == axis_size\n" } ]
Python
Apache License 2.0
google/jax
fix pxla.py typo
260,335
02.03.2019 21:49:03
28,800
4acd793f7453ae19b0c1b7c5fcc535a762301b9b
remove temporary scanplan.py brainstorm file
[ { "change_type": "DELETE", "old_path": "scanplan.py", "new_path": null, "diff": "-from functools import partial\n-import numpy as onp\n-\n-import jax.numpy as np\n-from jax import core\n-from jax import make_jaxpr, vjp, jvp\n-from jax import lax\n-\n-\n-def f(x, y):\n- return x * y\n-\n-g = partial(lax.scan, f)\n-a = onp.array(7, onp.float32)\n-bs = onp.array([2, 4, -2, 6], onp.float32)\n-out = g(a, bs)\n-\n-jaxpr = make_jaxpr(g)(a, bs)\n-\n-\n-primal, tangent = jvp(g, (a, bs), (a, bs))\n-\n-\n-###\n-\n-# scan :: (a -> b -> a) -> a -> [b] -> [a]\n-\n-# # first scan\n-# as_ = lax.scan(f, a, bs)\n-\n-# # second scan\n-# f_vjp = lambda args, ct: vjp(f, *args)[1](ct)\n-# lax.scan(f_vjp, cts[-1], (as_, bs, cts)) # off by one stuff... draw boxes\n" } ]
Python
Apache License 2.0
google/jax
remove temporary scanplan.py brainstorm file
260,335
06.03.2019 23:19:41
28,800
28b718fe33a716364b585d89015246a97e931e25
add jax_debug_nans flag, time-travel debugging
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -42,6 +42,9 @@ FLAGS = flags.FLAGS\nflags.DEFINE_bool('jax_device_values',\nstrtobool(os.getenv('JAX_DEVICE_VALUES', \"True\")),\n'Enable device-persistent values.')\n+flags.DEFINE_bool('jax_debug_nans',\n+ strtobool(os.getenv('JAX_DEBUG_NANS', \"False\")),\n+ 'Add nan checks to every operation.')\nmap = safe_map\n@@ -95,6 +98,14 @@ def device_put(x, device_num=0):\ndef result_handler(result_shape):\nif type(result_shape) is ResultArray and FLAGS.jax_device_values:\n+ if FLAGS.jax_debug_nans and onp.issubdtype(result_shape[1], onp.floating):\n+ def handle_result(device_buffer):\n+ py_val = device_buffer.to_py()\n+ if onp.any(onp.isnan(py_val)):\n+ raise FloatingPointError(\"invalid value\")\n+ else:\n+ return DeviceArray(device_buffer, *result_shape)\n+ else:\ndef handle_result(device_buffer):\nreturn DeviceArray(device_buffer, *result_shape)\nelif type(result_shape) is ResultArray:\n@@ -434,13 +445,20 @@ def xla_call_impl(fun, *args):\nfun, out_tree = flatten_fun(fun, in_trees)\ncompiled_fun = xla_callable(fun, *map(abstractify, flat_args))\n+ try:\nflat_ans = compiled_fun(*flat_args)\n+ except FloatingPointError:\n+ msg = (\"Invalid value encountered in the output of a jit function. \"\n+ \"Calling the de-optimized version.\")\n+ print(msg)\n+ return fun.call_wrapped(*args) # probably won't return\nif out_tree() is leaf:\nreturn flat_ans\nelse:\nreturn build_tree(iter(flat_ans), out_tree())\n+\n@lu.memoize\ndef xla_callable(fun, *abstract_args):\npvals = [pe.PartialVal((aval, core.unit)) for aval in abstract_args]\n" } ]
Python
Apache License 2.0
google/jax
add jax_debug_nans flag, time-travel debugging
260,335
07.03.2019 14:08:02
28,800
e35d5f62b27e919ea0e85f2f4d022f6dfdf9e3d3
add support for returning aux data from grad fixes
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -169,7 +169,7 @@ def xla_computation(fun, static_argnums=()):\nreturn computation_maker\n-def grad(fun, argnums=0):\n+def grad(fun, argnums=0, has_aux=False):\n\"\"\"Creates a function which evaluates the gradient of `fun`.\nArgs:\n@@ -179,6 +179,9 @@ def grad(fun, argnums=0):\narrays with shape `(1,)` etc.)\nargnums: Optional, integer or tuple of integers. Specifies which positional\nargument(s) to differentiate with respect to (default 0).\n+ has_aux: Optional, bool. Indicates whether `fun` returns a pair where the\n+ first element is considered the output of the mathematical functoin to be\n+ differentiated and the second element is auxiliary data. Default False.\nReturns:\nA function with the same arguments as `fun`, that evaluates the gradient of\n@@ -194,7 +197,7 @@ def grad(fun, argnums=0):\narray(0.961043, dtype=float32)\n\"\"\"\n- value_and_grad_f = value_and_grad(fun, argnums)\n+ value_and_grad_f = value_and_grad(fun, argnums, has_aux=has_aux)\ndocstr = (\"Gradient of {fun} with respect to positional argument(s) \"\n\"{argnums}. Takes the same arguments as {fun} but returns the \"\n@@ -203,12 +206,16 @@ def grad(fun, argnums=0):\n@wraps(fun, docstr=docstr, argnums=argnums)\ndef grad_f(*args, **kwargs):\n- ans, g = value_and_grad_f(*args, **kwargs)\n+ if not has_aux:\n+ _, g = value_and_grad_f(*args, **kwargs)\nreturn g\n+ else:\n+ (_, aux), g = value_and_grad_f(*args, **kwargs)\n+ return g, aux\nreturn grad_f\n-def value_and_grad(fun, argnums=0):\n+def value_and_grad(fun, argnums=0, has_aux=False):\n\"\"\"Creates a function which evaluates both `fun` and the gradient of `fun`.\nArgs:\n@@ -218,6 +225,9 @@ def value_and_grad(fun, argnums=0):\narrays with shape `(1,)` etc.)\nargnums: Optional, integer or tuple of integers. Specifies which positional\nargument(s) to differentiate with respect to (default 0).\n+ has_aux: Optional, bool. Indicates whether `fun` returns a pair where the\n+ first element is considered the output of the mathematical functoin to be\n+ differentiated and the second element is auxiliary data. Default False.\nReturns:\nA function with the same arguments as `fun` that evaluates both `fun` and\n@@ -238,11 +248,17 @@ def value_and_grad(fun, argnums=0):\ndef value_and_grad_f(*args, **kwargs):\nf = lu.wrap_init(fun, kwargs)\nf_partial, dyn_args = _argnums_partial(f, argnums, args)\n+ if not has_aux:\nans, vjp_py = vjp(f_partial, *dyn_args)\n+ else:\n+ ans, vjp_py, aux = vjp(f_partial, *dyn_args, has_aux=True)\n_check_scalar(ans)\ng = vjp_py(onp.ones((), onp.result_type(ans)))\ng = g[0] if isinstance(argnums, int) else g\n- return (ans, g)\n+ if not has_aux:\n+ return ans, g\n+ else:\n+ return (ans, aux), g\nreturn value_and_grad_f\n@@ -529,7 +545,7 @@ def lift_linearized(jaxpr, consts, io_tree, out_pval, *py_args):\nreturn apply_jaxtree_fun(fun, io_tree, *py_args)\n-def vjp(fun, *primals):\n+def vjp(fun, *primals, **kwargs):\n\"\"\"Compute a (reverse-mode) vector-Jacobian product of `fun`.\n`grad` is implemented as a special case of `vjp`.\n@@ -542,6 +558,9 @@ def vjp(fun, *primals):\nshould be evaluated. The length of `primals` should be equal to the number\nof positional parameters to `fun`. Each primal value should be a tuple of\narrays, scalar, or standard Python containers thereof.\n+ has_aux: Optional, bool. Indicates whether `fun` returns a pair where the\n+ first element is considered the output of the mathematical functoin to be\n+ differentiated and the second element is auxiliary data. Default False.\nReturns:\nA `(primals_out, vjpfun)` pair, where `primals_out` is `fun(*primals)`.\n@@ -556,20 +575,30 @@ def vjp(fun, *primals):\n>>> g((-0.7, 0.3))\n(array(-0.61430776, dtype=float32), array(-0.2524413, dtype=float32))\n\"\"\"\n+ has_aux = kwargs.pop('has_aux', False)\n+ assert not kwargs\nif not isinstance(fun, lu.WrappedFun):\nfun = lu.wrap_init(fun)\nprimals_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, primals))\n_check_args(primals_flat)\njaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(fun, in_trees)\n+ if not has_aux:\nout_primal, out_vjp = ad.vjp(jaxtree_fun, primals_flat)\n+ else:\n+ out_primal, out_vjp, aux = ad.vjp(jaxtree_fun, primals_flat, has_aux=True)\nout_tree = out_tree()\n+ if has_aux:\n+ out_tree, aux_tree = out_tree.children\nout_primal_py = build_tree(out_tree, out_primal)\nct_in_trees = [out_tree]\nct_out_tree = PyTreeDef(node_types[tuple], None, in_trees)\ndef out_vjp_packed(cotangent_in):\nreturn out_vjp(cotangent_in)\nvjp_py = partial(apply_jaxtree_fun, out_vjp_packed, (ct_in_trees, ct_out_tree))\n+ if not has_aux:\nreturn out_primal_py, vjp_py\n+ else:\n+ return out_primal_py, vjp_py, build_tree(aux_tree, aux)\ndef trace_to_jaxpr(traceable, py_pvals, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -34,8 +34,12 @@ map = safe_map\ndef identity(x): return x\n-def jvp(fun):\n+def jvp(fun, has_aux=False):\n+ if not has_aux:\nreturn jvpfun(jvp_subtrace(fun))\n+ else:\n+ fun, aux = jvp_subtrace_aux(fun)\n+ return jvpfun(fun), aux\n@transformation\ndef jvpfun(primals, tangents):\n@@ -56,13 +60,31 @@ def jvp_subtrace(master, primals, tangents):\nout_primal, out_tangent = out_tracer.primal, out_tracer.tangent\nyield (out_primal, out_tangent)\n+@transformation_with_aux\n+def jvp_subtrace_aux(master, primals, tangents):\n+ trace = JVPTrace(master, core.cur_sublevel())\n+ for x in list(primals) + list(tangents):\n+ if isinstance(x, Tracer):\n+ assert x.trace.level < trace.level\n+ ans_and_aux = yield map(partial(JVPTracer, trace), primals, tangents)\n+ out_tracer, aux_tracer = trace.full_raise(ans_and_aux)\n+ out_primal, out_tangent = out_tracer.primal, out_tracer.tangent\n+ aux = aux_tracer.primal # ignore aux tangent\n+ yield (out_primal, out_tangent), aux\n+\n+\n@transformation\ndef pack_output(*args):\nans = yield args\nyield pack(ans)\n-def linearize(traceable, *primals):\n+def linearize(traceable, *primals, **kwargs):\n+ has_aux = kwargs.pop('has_aux', False)\n+ if not has_aux:\njvpfun = pack_output(jvp(traceable))\n+ else:\n+ jvpfun, aux = jvp(traceable, has_aux=True)\n+ jvpfun = pack_output(jvpfun)\ntangent_avals = [get_aval(p).at_least_vspace() for p in primals]\nin_pvals = (pe.PartialVal((None, pack(primals))),\npe.PartialVal((core.AbstractTuple(tangent_avals), core.unit)))\n@@ -70,10 +92,16 @@ def linearize(traceable, *primals):\npval_primal, pval_tangent = unpair_pval(out_pval)\naval_primal, const_primal = pval_primal\nassert aval_primal is None\n+ if not has_aux:\nreturn const_primal, pval_tangent, jaxpr, consts\n+ else:\n+ return const_primal, pval_tangent, jaxpr, consts, aux()\n-def vjp(traceable, primals):\n+def vjp(traceable, primals, has_aux=False):\n+ if not has_aux:\nout_primal, pval, jaxpr, consts = linearize(traceable, *primals)\n+ else:\n+ out_primal, pval, jaxpr, consts, aux = linearize(traceable, *primals, has_aux=True)\ndef vjp_(ct):\nct = ignore_consts(ct, pval)\ndummy_primal_and_ct = pack((core.unit, ct))\n@@ -81,7 +109,10 @@ def vjp(traceable, primals):\n_, arg_cts = backward_pass(jaxpr, consts, (), dummy_args, dummy_primal_and_ct)\nreturn instantiate_zeros(pack(primals), arg_cts[1])\n+ if not has_aux:\nreturn out_primal, vjp_\n+ else:\n+ return out_primal, vjp_, aux\ndef ignore_consts(ct, pval):\naval, const = pval\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -341,6 +341,32 @@ class APITest(jtu.JaxTestCase):\nans = jit(lambda x: 2 * x)(np.ones(int(2e6))) # doesn't crash\nself.assertAllClose(ans, 2., check_dtypes=False)\n+ def test_grad_and_aux_basic(self):\n+ g, aux = grad(lambda x: (x**3, [x**2]), has_aux=True)(3.)\n+ self.assertEqual(type(aux), list)\n+ self.assertEqual(aux, [9.])\n+\n+ def test_grad_and_aux_nested(self):\n+ def f(x):\n+ g, aux = grad(lambda x: (x**3, [x**3]), has_aux=True)(x)\n+ return aux[0]\n+\n+ f2 = lambda x: x**3\n+\n+ self.assertEqual(grad(f)(4.), grad(f2)(4.))\n+ self.assertEqual(jit(grad(f))(4.), grad(f2)(4.))\n+ self.assertEqual(jit(grad(jit(f)))(4.), grad(f2)(4.))\n+\n+ def f(x):\n+ g, aux = grad(lambda x: (x**3, [x**3]), has_aux=True)(x)\n+ return aux[0] * np.sin(x)\n+\n+ f2 = lambda x: x**3 * np.sin(x)\n+\n+ self.assertEqual(grad(f)(4.), grad(f2)(4.))\n+ self.assertEqual(jit(grad(f))(4.), grad(f2)(4.))\n+ self.assertEqual(jit(grad(jit(f)))(4.), grad(f2)(4.))\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
add support for returning aux data from grad fixes #366
260,335
07.03.2019 14:48:05
28,800
caa2ed1a40c1481173e72ee52140a48d097b33e9
fix grad-and-aux handling of constant aux data
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -66,8 +66,8 @@ def jvp_subtrace_aux(master, primals, tangents):\nfor x in list(primals) + list(tangents):\nif isinstance(x, Tracer):\nassert x.trace.level < trace.level\n- ans_and_aux = yield map(partial(JVPTracer, trace), primals, tangents)\n- out_tracer, aux_tracer = trace.full_raise(ans_and_aux)\n+ ans, aux = yield map(partial(JVPTracer, trace), primals, tangents)\n+ out_tracer, aux_tracer = map(trace.full_raise, (ans, aux))\nout_primal, out_tangent = out_tracer.primal, out_tracer.tangent\naux = aux_tracer.primal # ignore aux tangent\nyield (out_primal, out_tangent), aux\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -343,7 +343,7 @@ class APITest(jtu.JaxTestCase):\ndef test_grad_and_aux_basic(self):\ng, aux = grad(lambda x: (x**3, [x**2]), has_aux=True)(3.)\n- self.assertEqual(type(aux), list)\n+ self.assertEqual(g, grad(lambda x: x**3)(3.))\nself.assertEqual(aux, [9.])\ndef test_grad_and_aux_nested(self):\n@@ -367,6 +367,11 @@ class APITest(jtu.JaxTestCase):\nself.assertEqual(jit(grad(f))(4.), grad(f2)(4.))\nself.assertEqual(jit(grad(jit(f)))(4.), grad(f2)(4.))\n+ def test_grad_and_aux_constant(self):\n+ g, aux = grad(lambda x: (x**3, [4.]), has_aux=True)(4.)\n+ self.assertEqual(g, grad(lambda x: x**3)(4.))\n+ self.assertEqual(aux, [4.])\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
fix grad-and-aux handling of constant aux data
260,335
07.03.2019 14:49:29
28,800
04081a4faa4c1b10a86f4ca5669b8008c02bbefe
improve a test for grad-and-aux
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -372,6 +372,10 @@ class APITest(jtu.JaxTestCase):\nself.assertEqual(g, grad(lambda x: x**3)(4.))\nself.assertEqual(aux, [4.])\n+ g, aux = grad(lambda x: (x**3, [x**2, 4.]), has_aux=True)(4.)\n+ self.assertEqual(g, grad(lambda x: x**3)(4.))\n+ self.assertEqual(aux, [4.**2, 4.])\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
improve a test for grad-and-aux
260,335
07.03.2019 17:20:26
28,800
8980da1a5c1102b3385e3974e6fa40f13e35a22c
add batching rule for lax.while_loop (fixes
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -35,28 +35,27 @@ from ..util import unzip2, partial, safe_map\nmap = safe_map\n-def batch(fun, in_vals, in_dims, out_dim_target):\n+def batch(fun, in_vals, in_dims, out_dim_dst):\nsizes = reduce(set.union, map(dimsize, in_dims, in_vals))\nif not sizes:\nreturn fun.call_wrapped(*in_vals), None # no mapped dimensions\nelif len(sizes) == 1:\n- out_val, out_dim = batch_transform(fun).call_wrapped(in_vals, in_dims)\n- return moveaxis(sizes.pop(), out_dim_target, out_dim, out_val)\n+ sz = sizes.pop()\n+ return batch_transform(fun, sz, in_dims, out_dim_dst).call_wrapped(in_vals)\nelse:\nraise TypeError(\"got inconsistent map dimension sizes: {}\".format(sizes))\n-# TODO(mattjj,dougalm): could call batch_subtrace here (a bit redundant)\n@transformation\n-def batch_transform(vals, dims):\n+def batch_transform(size, in_dims, out_dim_dst, vals):\nwith new_master(BatchTrace) as master:\ntrace = BatchTrace(master, core.cur_sublevel())\n- in_tracers = map(partial(BatchTracer, trace), vals, dims)\n+ in_tracers = map(partial(BatchTracer, trace), vals, in_dims)\nout_tracer = yield in_tracers\nout_tracer = trace.full_raise(out_tracer)\nout_val, out_dim = out_tracer.val, out_tracer.batch_dim\ndel master\n- yield (out_val, out_dim)\n+ yield moveaxis(size, out_dim_dst, out_dim, out_val)\n@transformation_with_aux\n" }, { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -3665,10 +3665,47 @@ def _while_loop_translation_rule(c, init_val, cond_consts, body_consts,\nfull_ans = c.While(cond_computation, body_computation, loop_carry)\nreturn c.GetTupleElement(full_ans, 0)\n+def _while_loop_batching_rule(batched_args, batch_dims, aval_out, cond_jaxpr,\n+ body_jaxpr):\n+ init_val, cond_consts, body_consts = batched_args\n+ init_val_bd, cond_consts_bd, body_consts_bd = batch_dims\n+\n+ sizes = _reduce(set.union, map(batching.dimsize, batch_dims, batched_args))\n+ size = sizes.pop()\n+ assert not sizes\n+\n+ if init_val_bd is None:\n+ # TODO(mattjj): if cond_consts_bd is also None, we could keep cond_fun\n+ # unbatched and avoid the masking logic, but we ignore that optimiztaion\n+ init_val = batching.bdim_at_front(init_val, init_val_bd, size,\n+ force_broadcast=True)\n+ init_val_bd = 0\n+\n+ def batched_cond_fun(batched_loop_carry):\n+ @lu.wrap_init\n+ def lifted(loop_carry, cond_consts):\n+ return core.eval_jaxpr(cond_jaxpr, cond_consts, (), loop_carry)\n+ f = batching.batch_transform(lifted, size, (init_val_bd, cond_consts_bd), 0)\n+ preds = f.call_wrapped((batched_loop_carry, cond_consts))\n+ return reduce(preds, onp.array(False), bitwise_or, [0])\n+\n+ def batched_body_fun(batched_loop_carry):\n+ @lu.wrap_init\n+ def lifted(loop_carry, cond_consts, body_consts):\n+ pred = core.eval_jaxpr(cond_jaxpr, cond_consts, (), loop_carry)\n+ new_loop_carry = core.eval_jaxpr(body_jaxpr, body_consts, (), loop_carry)\n+ return select(pred, new_loop_carry, loop_carry)\n+ f = batching.batch_transform(\n+ lifted, size, (init_val_bd, cond_consts_bd, body_consts_bd), init_val_bd)\n+ return f.call_wrapped((batched_loop_carry, cond_consts, body_consts))\n+\n+ return while_loop(batched_cond_fun, batched_body_fun, init_val), init_val_bd\n+\nwhile_p = Primitive('while')\nwhile_p.def_impl(partial(xla.apply_primitive, while_p))\nwhile_p.def_abstract_eval(_while_loop_abstract_eval)\nxla.translations[while_p] = _while_loop_translation_rule\n+batching.primitive_batchers[while_p] = _while_loop_batching_rule\ndef _unpack_eqn(invar, outvars):\nreturn core.JaxprEqn([invar], outvars, core.identity_p, (), True, {})\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -833,6 +833,19 @@ class BatchingTest(jtu.JaxTestCase):\nH = hessian(f)(R) # don't crash on UnshapedArray\n+ def testWhileLoop(self):\n+ def fun(x):\n+ return lax.while_loop(lambda x: x < 3, lambda x: x + 2, x)\n+\n+ ans = vmap(fun)(onp.array([0, 1, 2, 3]))\n+ expected = onp.array([4, 3, 4, 3])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ fun = jit(fun)\n+ ans = vmap(fun)(onp.array([0, 1, 2, 3]))\n+ expected = onp.array([4, 3, 4, 3])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
add batching rule for lax.while_loop (fixes #441)
260,335
07.03.2019 17:32:16
28,800
b42d3177be4cbd58624081e71bedb83d7941e777
add comment to _while_loop_batching_rule
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -3667,6 +3667,15 @@ def _while_loop_translation_rule(c, init_val, cond_consts, body_consts,\ndef _while_loop_batching_rule(batched_args, batch_dims, aval_out, cond_jaxpr,\nbody_jaxpr):\n+ # See https://github.com/google/jax/issues/441 for a discussion.\n+ # To batch a while_loop, we need to do some masking, since the elements of the\n+ # batch may run for different numbers of iterations. We perform that masking\n+ # usnig lax.select, and keep the loop running so long as any of the batch\n+ # elements need by effectively using an np.any(...) in the cond_fun.\n+ # The basic strategy here is to lift `cond_jaxpr` and `body_jaxpr` back into\n+ # traceable Python functions using `core.eval_jaxpr`. Then we can batch them\n+ # using `batching.batch_transform` (the transform underlying `api.vmap`). This\n+ # code also avoids broadcasting `cond_consts` and `body_consts`.\ninit_val, cond_consts, body_consts = batched_args\ninit_val_bd, cond_consts_bd, body_consts_bd = batch_dims\n" } ]
Python
Apache License 2.0
google/jax
add comment to _while_loop_batching_rule
260,335
07.03.2019 18:29:59
28,800
f8d0fcf0f721300b3e7e42c4fa1acefeb8bef761
add better while_loop batching tests
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -307,8 +307,16 @@ def move_dim_to_front(x, dim):\ndef dimsize(dim, x):\naval = get_aval(x)\nif type(aval) is AbstractTuple:\n- return reduce(set.union, map(partial(dimsize, dim), x))\n+ if type(dim) is tuple:\n+ return reduce(set.union, map(dimsize, dim, x))\nelif type(dim) is int:\n+ return reduce(set.union, map(partial(dimsize, dim), x))\n+ elif dim is None:\n+ return set()\n+ else:\n+ raise TypeError(type(dim))\n+ else:\n+ if type(dim) is int:\nreturn {x.shape[dim]}\nelif dim is None:\nreturn set()\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -846,6 +846,22 @@ class BatchingTest(jtu.JaxTestCase):\nexpected = onp.array([4, 3, 4, 3])\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testWhileLoopCondConstsBatched(self):\n+ def fun(x, y):\n+ return lax.while_loop(lambda x: x < y, lambda x: x + 2, x)\n+\n+ ans = vmap(fun, in_axes=(None, 0))(0, onp.array([2, 3]))\n+ expected = onp.array([2, 4])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testWhileLoopBodyConstsBatched(self):\n+ def fun(x, y):\n+ return lax.while_loop(lambda x: x < 3, lambda x: x + y, x)\n+\n+ ans = vmap(fun, in_axes=(None, 0))(0, onp.array([2, 3]))\n+ expected = onp.array([4, 3])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
add better while_loop batching tests
260,335
03.03.2019 11:26:04
28,800
e2296423056a163d2ad64d2f55eabb74d563b85b
fix parallel device persistence re-placement pair w/
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -44,32 +44,32 @@ map = safe_map\n### util\n-def shard_arg(device_ordinals, nrep, arg):\n+def shard_arg(device_ordinals, arg):\n\"\"\"Shard an argument data array arg along its leading axis.\nArgs:\n- # TODO(mattjj)\n+ device_ordinals: list of integers of length num_replicas mapping a logical\n+ replica index to a physical device number.\n+ arg: an array type representing an argument value to be sharded along its\n+ leading axis and placed on the devices/replicas.\nReturns:\n- A list of length nrep of DeviceValues indexed by replica number, where the\n- nth element is the argument to be passed to the nth replica.\n+ A list of length num_replicas of device buffers indexed by replica number,\n+ where the nth element is the argument to be passed to the nth replica.\n\"\"\"\n+ nrep = len(device_ordinals)\nassignments = assign_shards_to_replicas(nrep, arg.shape[0])\n- if type(arg) is ShardedDeviceArray and arg.nrep == nrep:\n- # TODO(mattjj,phawkins): could make this exchange more efficient\n- def replace_shard(buf, device_num):\n- if buf.device() == device_num:\n- return buf\n- else:\n- msg = \"Warning: device data movement on dispatch: {} to {}.\"\n- print(msg.format(buf.device(), device_num))\n- return xla.device_put(buf.to_py(), device_num)\n- return [replace_shard(buf, device_ordinals[n])\n- for buf, n in zip(arg.device_buffers, assignments)]\n+ if type(arg) is ShardedDeviceArray and nrep == len(arg.device_buffers):\n+ # TODO(mattjj, phawkins): improve re-distribution not to copy to host\n+ _, ids = onp.unique(assignments, return_index=True)\n+ shards = [arg.device_buffers[i].to_py() for i in ids] # TODO(mattjj): lazy\n+ return [buf if buf.device() == device_ordinals[r]\n+ else xla.device_put(shards[i], device_ordinals[r])\n+ for r, (i, buf) in enumerate(zip(assignments, arg.device_buffers))]\nelse:\nshards = [arg[i] for i in range(arg.shape[0])]\n- return [xla.device_put(shards[i], device_ordinals[n])\n- for n, i in enumerate(assignments)]\n+ return [xla.device_put(shards[i], device_ordinals[r])\n+ for r, i in enumerate(assignments)]\ndef unshard_output(axis_size, replica_results):\n\"\"\"Collect together replica results into a result value.\n@@ -116,7 +116,7 @@ def replica_groups(nrep, mesh_spec, mesh_axis):\ngroups = map(onp.ravel, groups)\nreturn tuple(tuple(group) for group in zip(*groups))\n-def xla_shard(c, axis_sizes, x):\n+def xla_shard(c, sizes, x):\ndef _xla_shard(shape, x):\nif shape.is_tuple():\nelts = map(_xla_shard, shape.tuple_shapes(), xla_destructure(c, x))\n@@ -127,15 +127,15 @@ def xla_shard(c, axis_sizes, x):\ndef shard_array(shape, x):\nif xb.get_replica_count() == 1:\n# TODO(mattjj): remove this special case, used for debugging on CPU\n- # because CPU doesn't have some collectives implemented\ndims = c.GetShape(x).dimensions()\nreturn c.Reshape(x, None, dims[1:])\nelse:\n- size = onp.array(prod(axis_sizes), onp.uint32)\n- idx = c.Rem(c.ReplicaId(), c.Constant(size))\ndims = list(shape.dimensions())\n+ assert dims[0] == sizes[-1]\n+ idx = c.Rem(c.ReplicaId(), c.Constant(onp.array(prod(sizes), onp.uint32)))\nzero = onp.zeros(len(dims) - 1, onp.uint32)\n- start_indices = c.Concatenate([c.Reshape(idx, None, [1]), c.Constant(zero)], 0)\n+ start_indices = c.Concatenate([c.Reshape(idx, None, [1]),\n+ c.Constant(zero)], 0)\nreturn c.Reshape(c.DynamicSlice(x, start_indices, [1] + dims[1:]),\nNone, dims[1:])\n@@ -221,17 +221,17 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nans = rule(c, *in_nodes, device_groups=axis_groups(ax_env, name), **params)\nelif eqn.bound_subjaxprs:\nif eqn.primitive is xla_pcall_p:\n- name = eqn.params['axis_name']\n- new_env = axis_env_extend(name, eqn.params['axis_size'])\n- in_nodes = map(partial(xla_shard, c, new_env.sizes), in_nodes)\n- in_shapes = map(c.GetShape, in_nodes)\n+ name, size = eqn.params['axis_name'], eqn.params['axis_size']\n+ new_env = axis_env_extend(name, size)\n+ in_shards = map(partial(xla_shard, c, new_env.sizes), in_nodes)\n+ in_shapes = map(c.GetShape, in_shards)\n(subjaxpr, const_bindings, freevar_bindings), = eqn.bound_subjaxprs\nsubc = replicated_comp(\nsubjaxpr, new_env, (),\nmap(c.GetShape, map(read, const_bindings + freevar_bindings)),\n*in_shapes)\nsubfun = (subc, tuple(map(read, const_bindings + freevar_bindings)))\n- sharded_result = xla.xla_call_translation_rule(c, subfun, *in_nodes)\n+ sharded_result = xla.xla_call_translation_rule(c, subfun, *in_shards)\nans = xla_unshard(c, axis_groups(new_env, name), sharded_result)\nelse:\nin_shapes = map(c.GetShape, in_nodes)\n@@ -254,11 +254,10 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nclass ShardedDeviceArray(xla.DeviceArray):\n- __slots__ = [\"device_buffers\", \"nrep\"]\n+ __slots__ = [\"device_buffers\"]\ndef __init__(self, axis_size, replica_results):\nself.device_buffers = [res.device_buffer for res in replica_results]\n- self.nrep = len(replica_results)\nr = replica_results[0]\nself.shape = (axis_size,) + r.shape\nself.dtype = r.dtype\n" } ]
Python
Apache License 2.0
google/jax
fix parallel device persistence re-placement pair w/ @hawkinsp
260,335
03.03.2019 12:44:26
28,800
1ffdfb1b52294d1ee4ed716bab9bed382e3ab279
clean up compiled shard/unshard logic
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -44,6 +44,7 @@ map = safe_map\n### util\n+\ndef shard_arg(device_ordinals, arg):\n\"\"\"Shard an argument data array arg along its leading axis.\n@@ -125,17 +126,9 @@ def xla_shard(c, sizes, x):\nreturn shard_array(shape, x)\ndef shard_array(shape, x):\n- if xb.get_replica_count() == 1:\n- # TODO(mattjj): remove this special case, used for debugging on CPU\n- dims = c.GetShape(x).dimensions()\n- return c.Reshape(x, None, dims[1:])\n- else:\ndims = list(shape.dimensions())\nassert dims[0] == sizes[-1]\n- idx = c.Rem(c.ReplicaId(), c.Constant(onp.array(prod(sizes), onp.uint32)))\n- zero = onp.zeros(len(dims) - 1, onp.uint32)\n- start_indices = c.Concatenate([c.Reshape(idx, None, [1]),\n- c.Constant(zero)], 0)\n+ start_indices = xla_shard_start_indices(c, dims[0], len(dims))\nreturn c.Reshape(c.DynamicSlice(x, start_indices, [1] + dims[1:]),\nNone, dims[1:])\n@@ -148,21 +141,20 @@ def xla_unshard(c, device_groups, x):\nelts = map(_xla_unshard, shape.tuple_shapes(), xla_destructure(c, x))\nreturn c.Tuple(*elts)\nelse:\n- return unshard_array(x)\n-\n- def unshard_array(x):\n- # TODO(mattjj): remove this special case, used for debugging on CPU\n- # because CPU doesn't have some collectives implemented\n- if xb.get_replica_count() == 1:\n- dims = c.GetShape(x).dimensions()\n- return c.Reshape(x, None, (1,) + tuple(dims))\n- else:\n+ return unshard_array(shape, x)\n+\n+ def unshard_array(shape, x):\ngroup_size = len(device_groups[0])\nbroadcasted = c.Broadcast(x, (group_size,))\nreturn c.AllToAll(broadcasted, 0, 0, device_groups)\nreturn _xla_unshard(c.GetShape(x), x)\n+def xla_shard_start_indices(c, axis_size, ndim):\n+ idx = c.Rem(c.ReplicaId(), c.Constant(onp.array(axis_size, onp.uint32)))\n+ zero = onp.zeros(ndim - 1, onp.uint32)\n+ return c.Concatenate([c.Reshape(idx, None, [1]), c.Constant(zero)], 0)\n+\n### xla_pcall\n@@ -321,7 +313,7 @@ def parallel_callable(fun, axis_name, axis_size, *avals):\nout = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\ncompiled, nrep, result_shape = out\ndel master, consts, jaxpr, env\n- handle_arg = partial(shard_arg, compiled._device_ordinals, nrep)\n+ handle_arg = partial(shard_arg, compiled._device_ordinals)\nhandle_result = xla.result_handler(result_shape)\nreturn partial(execute_replicated, compiled, pval, axis_size, nrep,\nhandle_arg, handle_result)\n" }, { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -304,6 +304,13 @@ class _JaxComputationBuilderBase(object):\nelse:\nraise TypeError(\"No constant handler for type: {}\".format(py_type))\n+ def AllToAll(self, operand, split_dimension, concat_dimension, replica_groups):\n+ \"\"\"Workaround for AllToAll not being implemented on some backends.\"\"\"\n+ if split_dimension == concat_dimension and len(replica_groups[0]) == 1:\n+ return operand\n+ else:\n+ return self.AllToAll(operand, split_dimension, concat_dimension, replica_gruops)\n+\n@memoize_thunk\ndef get_jax_computation_builder_class():\n" } ]
Python
Apache License 2.0
google/jax
clean up compiled shard/unshard logic
260,335
06.03.2019 14:03:47
28,800
ca802586a547d4557b8dd90b8db0288ffd2213f8
make pjit axis name optional (for pure maps)
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -423,8 +423,10 @@ def vmap(fun, in_axes=0, out_axes=0):\nreturn batched_fun\n-def pjit(fun, axis_name):\n+def pjit(fun, axis_name=None):\n\"\"\"Set up SPMD function for JIT compilation and parallel execution with XLA.\"\"\"\n+ axis_name = _TempAxisName() if axis_name is None else axis_name\n+\n@wraps(fun)\ndef f_jitted(*args, **kwargs):\nleaves, _ = tree_flatten(args)\n@@ -445,6 +447,10 @@ def pjit(fun, axis_name):\nf_jitted.__name__ = \"pjit({})\".format(f_jitted.__name__)\nreturn f_jitted\n+class _TempAxisName(object):\n+ def __repr__(self):\n+ return '<temp axis {}>'.format(hex(id(self)))\n+\ndef pmap(fun, axis_name, in_axes=0, out_axes=0):\n\"\"\"Vectorizing pseudo-map for single-program multiple-data (SPMD) functions.\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
make pjit axis name optional (for pure maps)
260,335
06.03.2019 14:36:47
28,800
ae4dc078875950f1626c2f388dc51e9efa0040e4
rename pmap -> serial_pmap, pjit -> pmap
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -423,7 +423,7 @@ def vmap(fun, in_axes=0, out_axes=0):\nreturn batched_fun\n-def pjit(fun, axis_name=None):\n+def pmap(fun, axis_name=None):\n\"\"\"Set up SPMD function for JIT compilation and parallel execution with XLA.\"\"\"\naxis_name = _TempAxisName() if axis_name is None else axis_name\n@@ -432,7 +432,7 @@ def pjit(fun, axis_name=None):\nleaves, _ = tree_flatten(args)\naxis_sizes = set(onp.shape(leaf)[0] for leaf in leaves)\nif len(axis_sizes) != 1:\n- msg = \"pjit requires all leading axes to have equal length, got {}.\"\n+ msg = \"pmap requires all leading axes to have equal length, got {}.\"\nraise TypeError(msg.format(axis_sizes))\naxis_size = axis_sizes.pop()\n@@ -444,37 +444,27 @@ def pjit(fun, axis_name=None):\naxis_name=axis_name, axis_size=axis_size)\nreturn build_tree(out_tree(), jaxtupletree_out)\n- f_jitted.__name__ = \"pjit({})\".format(f_jitted.__name__)\n+ namestr = \"pmap({}, axis_name={})\".format\n+ f_jitted.__name__ = namestr(f_jitted.__name__, axis_name)\nreturn f_jitted\n-class _TempAxisName(object):\n- def __repr__(self):\n- return '<temp axis {}>'.format(hex(id(self)))\n-\n-\n-def pmap(fun, axis_name, in_axes=0, out_axes=0):\n+def serial_pmap(fun, axis_name=None, in_axes=0, out_axes=0):\n\"\"\"Vectorizing pseudo-map for single-program multiple-data (SPMD) functions.\"\"\"\n- def pmap_fun(*args, **kwargs):\n+ axis_name = _TempAxisName() if axis_name is None else axis_name\n+\n+ def map_fun(*args, **kwargs):\nf = lu.wrap_init(fun, kwargs)\nin_axes_ = in_axes if isinstance(in_axes, (list, tuple)) else (in_axes,) * len(args)\nin_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\njaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(f, in_trees)\n- out_flat = parallel.pmap(jaxtree_fun, axis_name, args, in_axes_, out_axes)\n+ out_flat = parallel.serial_pmap(jaxtree_fun, axis_name, args, in_axes_, out_axes)\nreturn build_tree(out_tree(), out_flat)\n- return pmap_fun\n-\n+ return map_fun\n-def axisvar_split(fun, name, new_names):\n- \"\"\"Split axis variable names into new names in an SPMD function.\"\"\"\n- def split_fun(*args, **kwargs):\n- f = lu.wrap_init(fun, kwargs)\n- in_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\n- jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(f, in_trees)\n- out_flat = parallel.axisvar_split(jaxtree_fun, name, new_names).call_wrapped(*args)\n- return build_tree(out_tree(), out_flat)\n-\n- return split_fun\n+class _TempAxisName(object):\n+ def __repr__(self):\n+ return '<temp axis {}>'.format(hex(id(self)))\ndef papply(fun, axis_size, in_axes=0, out_axes=0):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/parallel.py", "new_path": "jax/interpreters/parallel.py", "diff": "@@ -37,25 +37,25 @@ zip = safe_zip\ndef identity(x): return x\n-### pmap\n+### serial_pmap is like pmap but executes in a single-machine vectorized way\n-def pmap(fun, name, in_vals, in_axes, out_axis_target):\n+def serial_pmap(fun, name, in_vals, in_axes, out_axis_target):\nsizes = reduce(set.union, map(batching.dimsize, in_axes, in_vals))\nif not sizes:\nreturn fun.call_wrapped(*in_vals)\nelif len(sizes) == 1:\n- fun, out_axis = pmap_transform(fun, name, in_axes)\n+ fun, out_axis = serial_pmap_transform(fun, name, in_axes)\nout_val = fun.call_wrapped(*in_vals)\nreturn batching.moveaxis(sizes.pop(), out_axis_target, out_axis(), out_val)\nelse:\nraise TypeError(\"got inconsistent map dimension sizes: {}\".format(sizes))\n@lu.transformation_with_aux\n-def pmap_transform(name, axes, *vals):\n- with new_master(PmapTrace) as master:\n- trace = PmapTrace(master, core.cur_sublevel())\n- in_tracers = map(partial(PmapTracer, trace, name), vals, axes)\n+def serial_pmap_transform(name, axes, *vals):\n+ with new_master(SerialPmapTrace) as master:\n+ trace = SerialPmapTrace(master, core.cur_sublevel())\n+ in_tracers = map(partial(SerialPmapTracer, trace, name), vals, axes)\nans = yield in_tracers\nout_tracer = trace.full_raise(ans)\nout_val, out_axis = out_tracer.val, out_tracer.axis\n@@ -63,14 +63,14 @@ def pmap_transform(name, axes, *vals):\nyield out_val, out_axis\n@lu.transformation_with_aux\n-def pmap_subtrace(master, name, axes, *vals):\n- trace = PmapTrace(master, core.cur_sublevel())\n- ans = yield map(partial(PmapTracer, trace, name), vals, axes)\n+def serial_pmap_subtrace(master, name, axes, *vals):\n+ trace = SerialPmapTrace(master, core.cur_sublevel())\n+ ans = yield map(partial(SerialPmapTracer, trace, name), vals, axes)\nout_tracer = trace.full_raise(ans)\nout_val, out_axis = out_tracer.val, out_tracer.axis\nyield out_val, out_axis\n-class PmapTracer(Tracer):\n+class SerialPmapTracer(Tracer):\ndef __init__(self, trace, name, val, axis):\nself.trace = trace\nself.name = name\n@@ -92,7 +92,7 @@ class PmapTracer(Tracer):\nreturn tuple(self.val)\nelse:\nraise TypeError(t)\n- return map(partial(PmapTracer, self.trace, self.name), self.val, axes)\n+ return map(partial(SerialPmapTracer, self.trace, self.name), self.val, axes)\ndef full_lower(self):\nif self.axis is None:\n@@ -100,15 +100,15 @@ class PmapTracer(Tracer):\nelse:\nreturn self\n-class PmapTrace(Trace):\n+class SerialPmapTrace(Trace):\ndef pure(self, val):\n- return PmapTracer(self, None, val, None)\n+ return SerialPmapTracer(self, None, val, None)\ndef lift(self, val):\n- return PmapTracer(self, None, val, None)\n+ return SerialPmapTracer(self, None, val, None)\ndef sublift(self, val):\n- return PmapTracer(self, val.name, val.val, val.axis)\n+ return SerialPmapTracer(self, val.name, val.val, val.axis)\ndef process_primitive(self, primitive, tracers, params):\nnames_in, vals_in, axes_in = unzip3((t.name, t.val, t.axis) for t in tracers)\n@@ -116,25 +116,25 @@ class PmapTrace(Trace):\nreturn primitive.bind(*vals_in, **params)\nelse:\nname = next(name for name in names_in if name is not None) # all same\n- if primitive in pmap_primitive_rules:\n+ if primitive in serial_pmap_primitive_rules:\n# if it's a pmap collective primitive, do something special\nval_in, = vals_in\naxis_in, = axes_in\nif name == params['axis_name']:\n# if the name matches this tracer's name, apply the pmap rule\n- rule = pmap_primitive_rules[primitive]\n+ rule = serial_pmap_primitive_rules[primitive]\nparams = {k: params[k] for k in params if k != 'axis_name'}\nval_out, axis_out = rule(val_in, axis_in, **params)\n- return PmapTracer(self, name, val_out, axis_out)\n+ return SerialPmapTracer(self, name, val_out, axis_out)\nelse:\n# if not, bind the primitive so that any other pmap tracers can see it\nval_out = primitive.bind(val_in, **params)\n- return PmapTracer(self, name, val_out, axis_in)\n+ return SerialPmapTracer(self, name, val_out, axis_in)\nelse:\n# if it's not a pmap collective primitive, act just like vmap\nrule = batching.get_primitive_batcher(primitive)\nval_out, axis_out = rule(vals_in, axes_in, **params)\n- return PmapTracer(self, name, val_out, axis_out)\n+ return SerialPmapTracer(self, name, val_out, axis_out)\ndef process_call(self, call_primitive, f, tracers, params):\nnames, vals, axes = unzip3((t.name, t.val, t.axis) for t in tracers)\n@@ -142,16 +142,16 @@ class PmapTrace(Trace):\nreturn call_primitive.bind(f, *vals, **params)\nelse:\nname = next(name for name in names if name is not None) # all same\n- f, axis_out = pmap_subtrace(f, self.master, name, axes)\n+ f, axis_out = serial_pmap_subtrace(f, self.master, name, axes)\nval_out = call_primitive.bind(f, *vals, **params)\n- return PmapTracer(self, name, val_out, axis_out())\n+ return SerialPmapTracer(self, name, val_out, axis_out())\ndef post_process_call(self, _, out_tracer):\nname, val, axis = out_tracer.name, out_tracer.val, out_tracer.axis\nmaster = self.master\ndef todo(x):\n- trace = PmapTrace(master, core.cur_sublevel())\n- return PmapTracer(trace, name, x, axis)\n+ trace = SerialPmapTrace(master, core.cur_sublevel())\n+ return SerialPmapTracer(trace, name, x, axis)\nreturn val, todo\n@@ -159,10 +159,10 @@ class PmapTrace(Trace):\nvals = core.pack([t.val for t in tracers])\naxis = tuple(t.axis for t in tracers)\nname = next(t.name for t in tracers if t.name)\n- return PmapTracer(self, name, vals, axis)\n+ return SerialPmapTracer(self, name, vals, axis)\n-pmap_primitive_rules = {}\n+serial_pmap_primitive_rules = {}\n### papply\n" }, { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -2014,10 +2014,28 @@ def _dot_batch_rule(batched_args, batch_dims):\ndim_nums = [(lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch)]\nreturn dot_general(lhs, rhs, dim_nums), 0\n+def _dot_papply_rule(name, vals, dims):\n+ x, y = vals\n+ xdim, ydim = dims\n+ if xdim is None:\n+ return dot(x, y), ydim\n+ elif ydim is None:\n+ return dot(x, y), xdim\n+ elif ydim == 0:\n+ if xdim != x.ndim:\n+ x = psplit(x, name, x.ndim)\n+ x = x[..., None]\n+ y = y[..., None, :]\n+ return psum(x * y, name), None\n+ else:\n+ y = pcollect(y, name)\n+ return dot(x, y), xdim\n+\n_dot_dtype_rule = partial(binop_dtype_rule, _input_dtype, [_num, _num], 'dot')\ndot_p = standard_primitive(_dot_shape_rule, _dot_dtype_rule, 'dot')\nad.defbilinear(dot_p, _dot_transpose_lhs, _dot_transpose_rhs)\nbatching.primitive_batchers[dot_p] = _dot_batch_rule\n+parallel.papply_primitive_rules[dot_p] = _dot_papply_rule\ndef _dot_general_shape_rule(lhs, rhs, dimension_numbers):\n@@ -2411,11 +2429,31 @@ def _transpose_batch_rule(batched_args, batch_dims, permutation):\nperm = (bdim,) + tuple(i if i < bdim else i+1 for i in permutation)\nreturn transpose(operand, perm), 0\n+def _transpose_papply_rule(name, vals, dims, permutation):\n+ x, = vals\n+ xdim, = dims\n+ perm = list(permutation)\n+ if perm[xdim] == xdim:\n+ x = transpose(x, perm)\n+ out_dim = xdim\n+ else:\n+ in_dim, = [i for i in range(len(perm)) if perm[i] == xdim]\n+ out_dim = perm[xdim]\n+ perm[in_dim] = out_dim\n+ perm[out_dim] = in_dim\n+ perm = perm[:xdim] + perm[xdim + 1:]\n+ perm = [i - 1 if i > xdim else i for i in perm]\n+ x = transpose(x, perm)\n+ x = pswapaxes(x, name, in_dim)\n+ return x, xdim\n+\n+\ntranspose_p = standard_primitive(_transpose_shape_rule, _input_dtype,\n'transpose')\nad.deflinear(transpose_p,\nlambda t, permutation: [transpose(t, onp.argsort(permutation))])\nbatching.primitive_batchers[transpose_p] = _transpose_batch_rule\n+parallel.papply_primitive_rules[transpose_p] = _transpose_papply_rule\ndef _select_shape_rule(pred, on_true, on_false):\n@@ -3909,7 +3947,7 @@ ad.primitive_jvps[stop_gradient_p] = _stop_gradient_jvp_rule\nbatching.primitive_batchers[stop_gradient_p] = _stop_gradient_batch_rule\n-### parallel library\n+### parallel traceables\ndef psum(x, axis_name):\nreturn psum_p.bind(x, axis_name=axis_name)\n@@ -3939,29 +3977,22 @@ def pcollect(x, axis_name):\n# return xla_all_to_all(x, 0, dim(axis_name), **params)\nreturn pcollect_p.bind(x, axis_name=axis_name)\n-### parallel primitives\n-def PmapPrimitive(name):\n- prim = Primitive(name)\n- prim.def_impl(partial(_unbound_name_error, name))\n- prim.def_abstract_eval(lambda x, *args, **kwargs: x) # default\n- return prim\n+### parallel primitives\ndef _unbound_name_error(primitive_name, *args, **kwargs):\naxis_name = kwargs['axis_name']\nmsg = \"axis name '{}' is unbound for primitive {}.\"\nraise NameError(msg.format(axis_name, primitive_name))\n-psum_p = PmapPrimitive('psum')\n-pswapaxes_p = PmapPrimitive('pswapaxes')\n-psplit_p = PmapPrimitive('psplit')\n-pcollect_p = PmapPrimitive('pcollect')\n-scatter_like_p = Primitive('scatter_like')\n-\n+def PmapPrimitive(name):\n+ prim = Primitive(name)\n+ prim.def_impl(partial(_unbound_name_error, name))\n+ prim.def_abstract_eval(lambda x, *args, **kwargs: x)\n+ return prim\n-### parallel rules\n-def _psum_pmap_rule(val, axis):\n+def _psum_serial_pmap_rule(val, axis):\nreturn _reduce_sum(val, [axis]), None\ndef _psum_transpose_rule(t, axis_name):\n@@ -3973,17 +4004,16 @@ def _psum_parallel_translation_rule(c, val, device_groups):\nelse:\nreturn c.CrossReplicaSum(val)\n-parallel.pmap_primitive_rules[psum_p] = _psum_pmap_rule\n+psum_p = PmapPrimitive('psum')\n+psum_p.def_impl(partial(_unbound_name_error, 'psum'))\n+psum_p.def_abstract_eval(lambda x, *args, **kwargs: x)\n+parallel.serial_pmap_primitive_rules[psum_p] = _psum_serial_pmap_rule\npxla.parallel_translation_rules[psum_p] = _psum_parallel_translation_rule\nad.deflinear(psum_p, _psum_transpose_rule)\nparallel.defreducer(reduce_sum_p, psum_p)\n-def gather_pmap_rule(val, axis):\n- return val, None\n-\n-parallel.pmap_primitive_rules[gather_p] = gather_pmap_rule\n-def pswapaxes_pmap_rule(x, axis_in, axis):\n+def _pswapaxes_serial_pmap_rule(x, axis_in, axis):\nif x.shape[axis_in] != x.shape[axis]:\nraise ValueError(\"pswapaxes between non-square dimensions\")\nperm = list(range(x.ndim))\n@@ -3991,74 +4021,24 @@ def pswapaxes_pmap_rule(x, axis_in, axis):\nperm[axis] = axis_in\nreturn transpose(x, perm), axis_in\n-parallel.pmap_primitive_rules[pswapaxes_p] = pswapaxes_pmap_rule\n+pswapaxes_p = PmapPrimitive('pswapaxes')\n+parallel.serial_pmap_primitive_rules[pswapaxes_p] = _pswapaxes_serial_pmap_rule\n+\n-def psplit_pmap_rule(x, axis_in, axis):\n+def _psplit_serial_pmap_rule(x, axis_in, axis):\nif x.shape[axis_in] != x.shape[axis]:\nraise ValueError(\"psplit between non-square dimensions\")\nreturn x, axis\n-parallel.pmap_primitive_rules[psplit_p] = psplit_pmap_rule\n-\n-def pcollect_pmap_rule(x, axis_in):\n- return x, None\n-\n-parallel.pmap_primitive_rules[pcollect_p] = pcollect_pmap_rule\n-\n-def transpose_papply_rule(name, vals, dims, permutation):\n- x, = vals\n- xdim, = dims\n- perm = list(permutation)\n- if perm[xdim] == xdim:\n- x = transpose(x, perm)\n- out_dim = xdim\n- else:\n- in_dim, = [i for i in range(len(perm)) if perm[i] == xdim]\n- out_dim = perm[xdim]\n- perm[in_dim] = out_dim\n- perm[out_dim] = in_dim\n- perm = perm[:xdim] + perm[xdim + 1:]\n- perm = [i - 1 if i > xdim else i for i in perm]\n- x = transpose(x, perm)\n- x = pswapaxes(x, name, in_dim)\n- return x, xdim\n-\n-parallel.papply_primitive_rules[transpose_p] = transpose_papply_rule\n-\n-def _pdot(x, y, axis_name):\n- x = x[..., None]\n- y = y[..., None, :]\n- return psum(x * y, axis_name)\n-\n-def dot_papply_rule(name, vals, dims):\n- x, y = vals\n- xdim, ydim = dims\n- if xdim is None:\n- return dot(x, y), ydim\n- elif ydim is None:\n- return dot(x, y), xdim\n- elif ydim == 0:\n- if xdim != x.ndim:\n- x = psplit(x, name, x.ndim)\n- return _pdot(x, y, name), None\n- else:\n- y = pcollect(y, name)\n- return dot(x, y), xdim\n-\n-parallel.papply_primitive_rules[dot_p] = dot_papply_rule\n-\n-def scatter_like(source, target):\n- return scatter_like_p.bind(source, target)\n+psplit_p = PmapPrimitive('psplit')\n+parallel.serial_pmap_primitive_rules[psplit_p] = _psplit_serial_pmap_rule\n-def scatter_like_papply_rule(name, vals, axes):\n- source, target = vals\n- source_axis, target_axis = axes\n- assert source_axis is None\n- return _scatter(source, target, target_axis, name)\n-scatter_like_p.def_abstract_eval(lambda source, target: source)\n+def _pcollect_serial_pmap_rule(x, axis_in):\n+ return x, None\n-parallel.papply_primitive_rules[scatter_like_p] = scatter_like_papply_rule\n+pcollect_p = PmapPrimitive('pcollect')\n+parallel.serial_pmap_primitive_rules[pcollect_p] = _pcollect_serial_pmap_rule\n### util\n" }, { "change_type": "MODIFY", "old_path": "tests/parallel_test.py", "new_path": "tests/parallel_test.py", "diff": "@@ -25,39 +25,39 @@ from absl.testing import parameterized\nimport jax.numpy as np\nfrom jax import test_util as jtu\nfrom jax import lax\n-from jax.api import pmap, papply, jit, make_jaxpr, axisvar_split\n+from jax.api import serial_pmap, papply, jit, make_jaxpr\nfrom jax.linear_util import wrap_init\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n-class PmapTest(jtu.JaxTestCase):\n+class SerialPmapTest(jtu.JaxTestCase):\ndef testConstantFunction(self):\nf = lambda x: 3\n- ans = pmap(f, axis_name='i')(onp.ones(4))\n+ ans = serial_pmap(f, axis_name='i')(onp.ones(4))\nexpected = 3 * onp.ones(4)\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testReduceSum(self):\nf = lambda x: lax.psum(x, 'i')\n- ans = pmap(f, axis_name='i')(onp.ones(4))\n+ ans = serial_pmap(f, axis_name='i')(onp.ones(4))\nexpected = 4 * onp.ones(4)\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testLogSoftmax(self):\nf = lambda x: x - np.log(lax.psum(np.exp(x), 'i'))\nx = onp.log(onp.arange(1., 10., dtype=onp.float32))\n- ans = pmap(f, axis_name='i')(x)\n+ ans = serial_pmap(f, axis_name='i')(x)\nexpected = x - onp.log(onp.sum(onp.exp(x)))\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testNested(self):\nf = lambda x: lax.psum(lax.psum(x, 'i'), 'j')\nx = onp.ones((2, 2))\n- ans1 = pmap(pmap(f, 'i'), 'j')(x)\n- ans2 = pmap(pmap(f, 'j'), 'i')(x)\n+ ans1 = serial_pmap(serial_pmap(f, 'i'), 'j')(x)\n+ ans2 = serial_pmap(serial_pmap(f, 'j'), 'i')(x)\nexpected = 4 * onp.ones((2, 2))\nself.assertAllClose(ans1, expected, check_dtypes=False)\nself.assertAllClose(ans2, expected, check_dtypes=False)\n@@ -86,7 +86,7 @@ class PapplyTest(jtu.JaxTestCase):\nlambda x: lax.psum(x, axis_name))(onp.zeros(5))\nassert repr(jaxpr) == repr(expected_jaxpr)\n- ans = pmap(pfun, axis_name)(onp.arange(3.))\n+ ans = serial_pmap(pfun, axis_name)(onp.arange(3.))\nexpected = onp.sum(onp.arange(3.))\nself.assertAllClose(ans, expected, check_dtypes=False)\n@@ -103,7 +103,7 @@ class PapplyTest(jtu.JaxTestCase):\nlambda x: x - np.log(lax.psum(np.exp(x), axis_name)))(onp.zeros(5))\nassert repr(jaxpr) == repr(expected_jaxpr)\n- ans = pmap(pfun, axis_name)(onp.arange(1., 5.))\n+ ans = serial_pmap(pfun, axis_name)(onp.arange(1., 5.))\nexpected = fun(onp.arange(1., 5.))\nself.assertAllClose(ans, expected, check_dtypes=False)\n@@ -112,7 +112,7 @@ class PapplyTest(jtu.JaxTestCase):\nexpected = x + x\npfun, axis_name = papply(np.add, 2)\n- ans = pmap(pfun, axis_name)(x, x)\n+ ans = serial_pmap(pfun, axis_name)(x, x)\nself.assertAllClose(ans, expected, check_dtypes=True)\n@skip\n@@ -125,7 +125,7 @@ class PapplyTest(jtu.JaxTestCase):\nexpected = x + 3\npfun, axis_name = papply(fun, 2)\n- ans = pmap(pfun, axis_name)(x)\n+ ans = serial_pmap(pfun, axis_name)(x)\nself.assertAllClose(ans, expected, check_dtypes=True)\ndef testTranspose(self):\n@@ -140,7 +140,7 @@ class PapplyTest(jtu.JaxTestCase):\nfor x in xs:\nexpected = x.T\npfun, axis_name = papply(fun, x.shape[0])\n- ans = pmap(pfun, axis_name)(x)\n+ ans = serial_pmap(pfun, axis_name)(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testTransposeWithOddPermutation(self):\n@@ -155,7 +155,7 @@ class PapplyTest(jtu.JaxTestCase):\nfor x in xs:\nexpected = np.transpose(x, (2, 0, 1))\npfun, axis_name = papply(fun, x.shape[0])\n- ans = pmap(pfun, axis_name)(x)\n+ ans = serial_pmap(pfun, axis_name)(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testTransposeAndAddRank2(self):\n@@ -167,7 +167,7 @@ class PapplyTest(jtu.JaxTestCase):\nexpected = x + x.T\npfun, axis_name = papply(fun, 2)\n- ans = pmap(pfun, axis_name)(x)\n+ ans = serial_pmap(pfun, axis_name)(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n@skip\n@@ -180,7 +180,7 @@ class PapplyTest(jtu.JaxTestCase):\nexpected = x + x.T\npfun, axis_name = papply(fun, 2)\n- ans = pmap(pfun, axis_name)(x)\n+ ans = serial_pmap(pfun, axis_name)(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testDot(self):\n@@ -196,7 +196,7 @@ class PapplyTest(jtu.JaxTestCase):\nfor x in xs:\nexpected = fun(x, x)\npfun, axis_name = papply(fun, x.shape[0], in_axes=in_axes)\n- ans = pmap(pfun, axis_name)(x, x)\n+ ans = serial_pmap(pfun, axis_name)(x, x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n" }, { "change_type": "RENAME", "old_path": "tests/pjit_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -25,7 +25,7 @@ from absl.testing import parameterized\nimport jax.numpy as np\nfrom jax import test_util as jtu\nfrom jax import lax\n-from jax.api import pjit, pmap, vmap, jvp, grad, make_jaxpr, linearize\n+from jax.api import pmap, vmap, jvp, grad, make_jaxpr, linearize\nfrom jax.lax import psum\nfrom jax.lib import xla_bridge\n@@ -33,18 +33,18 @@ from jax.config import config\nconfig.parse_flags_with_absl()\n-class PjitTest(jtu.JaxTestCase):\n+class PmapTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"gpu\", \"tpu\")\ndef testNestedWithClosure(self):\nassert xla_bridge.get_replica_count() == 1 # OSS CPU testing only\nx = onp.arange(3, dtype=onp.float32).reshape(1, 1, 3)\n- @partial(pjit, axis_name='i')\n+ @partial(pmap, axis_name='i')\ndef test_fun(x):\ny = np.sum(np.sin(x))\n- @partial(pjit, axis_name='j')\n+ @partial(pmap, axis_name='j')\ndef g(z):\nreturn 3. * np.exp(np.sin(x).sum() * np.cos(y) * np.tan(z))\n" } ]
Python
Apache License 2.0
google/jax
rename pmap -> serial_pmap, pjit -> pmap
260,335
06.03.2019 15:20:43
28,800
ab0c0585daca96c1e6c869c4bf056fec3d9613d7
update build file to work with cuda nccl
[ { "change_type": "MODIFY", "old_path": "build/build.py", "new_path": "build/build.py", "diff": "@@ -176,6 +176,9 @@ build --define=no_gcp_support=true\nbuild --define=no_hdfs_support=true\nbuild --define=no_kafka_support=true\nbuild --define=no_ignite_support=true\n+\n+build:cuda --crosstool_top=@local_config_cuda//crosstool:toolchain\n+build:cuda --define=using_cuda=true --define=using_cuda_nvcc=true\n\"\"\"\n@@ -298,6 +301,8 @@ def main():\nconfig_args += [\"--config=opt\"]\nif args.enable_mkl_dnn:\nconfig_args += [\"--config=mkl_open_source_only\"]\n+ if args.enable_cuda:\n+ config_args += [\"--config=cuda\"]\nshell(\n[bazel_path, \"run\", \"--verbose_failures=true\"] +\nconfig_args +\n" } ]
Python
Apache License 2.0
google/jax
update build file to work with cuda nccl
260,335
06.03.2019 17:28:28
28,800
07d74c7c8416b28cea5986909ce278c8cddde746
add device_count() function to xla_bridge
[ { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -164,6 +164,10 @@ def _get_backend():\nreturn backend()\n+def device_count():\n+ return _get_backend().device_count()\n+\n+\ndef device_put(pyval, device_num=0):\nclient = get_xla_client()\nreturn client.LocalBuffer.from_pyval(pyval, device_num, backend=_get_backend())\n" } ]
Python
Apache License 2.0
google/jax
add device_count() function to xla_bridge
260,335
06.03.2019 17:49:16
28,800
895169d84d5eea85fbe6419f0f8e6aa9578960c1
add spmd toy
[ { "change_type": "ADD", "old_path": null, "new_path": "spmd_toy.py", "diff": "+from functools import partial\n+import operator as op\n+\n+import numpy as onp\n+\n+import jax.numpy as np\n+from jax import pmap, grad\n+from jax import lax\n+from jax.tree_util import tree_map\n+from jax.lib.xla_bridge import device_count\n+\n+\n+step_size = 0.01\n+rng = onp.random.RandomState(0)\n+\n+def predict(params, inputs):\n+ for W, b in params:\n+ outputs = np.dot(inputs, W) + b\n+ inputs = np.tanh(outputs)\n+ return outputs\n+\n+def loss(params, batch):\n+ inputs, targets = batch\n+ predictions = predict(params, inputs)\n+ return np.sum((predictions - targets)**2)\n+\n+def update(params, batch):\n+ grads = grad(loss)(params, batch)\n+ new_params = [(W - step_size * dW, b - step_size * db)\n+ for (W, b), (dW, db) in zip(params, grads)]\n+ return new_params\n+\n+# initialize parameters\n+layer_sizes = [2, 4, 3] # input size 2, output size 3\n+scale = 0.01\n+params = [(scale * rng.randn(m, n), scale * rng.randn(n))\n+ for m, n in zip(layer_sizes[:-1], layer_sizes[1:])]\n+\n+# set up fake data\n+inputs = rng.randn(10, 2) # batch size 10, feature size 2\n+targets = rng.randn(10, 3) # batch size 10, output size 3\n+batch = (inputs, targets)\n+\n+\n+# standard functions\n+print(loss(params, batch))\n+print(update(params, batch)[0][0])\n+\n+\n+# reshape / replicate data\n+num_devices = device_count()\n+spmd_params = pmap(lambda _: params)(onp.arange(num_devices))\n+spmd_inputs = inputs.reshape((num_devices, -1, 2))\n+spmd_targets = targets.reshape((num_devices, -1, 3))\n+spmd_batch = (spmd_inputs, spmd_targets)\n+\n+@partial(pmap, axis_name='i')\n+def spmd_loss(params, batch):\n+ inputs, targets = batch\n+ predictions = predict(params, inputs)\n+ batch_loss = np.sum((predictions - targets)**2)\n+ return lax.psum(batch_loss, 'i')\n+print(spmd_loss(spmd_params, spmd_batch))\n+\n+@partial(pmap, axis_name='i')\n+def spmd_update(params, batch):\n+ grads = grad(loss)(params, batch) # loss, not spmd_loss\n+ grads = tree_map(lambda x: lax.psum(x, 'i'), grads)\n+ new_params = [(W - step_size * dW, b - step_size * db)\n+ for (W, b), (dW, db) in zip(params, grads)]\n+ return new_params\n+print(spmd_update(spmd_params, spmd_batch)[0][0])\n" } ]
Python
Apache License 2.0
google/jax
add spmd toy
260,335
08.03.2019 09:59:03
28,800
15da530b033819b2bc2ef762f71a7cb6e56c7867
add spmd mnist example
[ { "change_type": "MODIFY", "old_path": "examples/mnist_classifier_fromscratch.py", "new_path": "examples/mnist_classifier_fromscratch.py", "diff": "@@ -59,7 +59,7 @@ def accuracy(params, batch):\nif __name__ == \"__main__\":\n- layer_sizes = [784, 1024, 1024, 10] # TODO(mattjj): revise to standard arch\n+ layer_sizes = [784, 1024, 1024, 10]\nparam_scale = 0.1\nstep_size = 0.001\nnum_epochs = 10\n" }, { "change_type": "ADD", "old_path": null, "new_path": "examples/spmd_mnist_classifier_fromscratch.py", "diff": "+# Copyright 2018 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+\"\"\"A basic MNIST example using Numpy and JAX.\n+\n+The primary aim here is simplicity and minimal dependencies.\n+\"\"\"\n+\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+from functools import partial\n+import time\n+\n+import numpy.random as npr\n+\n+from jax import jit, grad, pmap, replicate, unreplicate\n+from jax.config import config\n+from jax.scipy.special import logsumexp\n+from jax.lib import xla_bridge\n+from jax import lax\n+import jax.numpy as np\n+from examples import datasets\n+\n+\n+def init_random_params(scale, layer_sizes, rng=npr.RandomState(0)):\n+ return [(scale * rng.randn(m, n), scale * rng.randn(n))\n+ for m, n, in zip(layer_sizes[:-1], layer_sizes[1:])]\n+\n+def predict(params, inputs):\n+ activations = inputs\n+ for w, b in params[:-1]:\n+ outputs = np.dot(activations, w) + b\n+ activations = np.tanh(outputs)\n+\n+ final_w, final_b = params[-1]\n+ logits = np.dot(activations, final_w) + final_b\n+ return logits - logsumexp(logits, axis=1, keepdims=True)\n+\n+def loss(params, batch):\n+ inputs, targets = batch\n+ preds = predict(params, inputs)\n+ return -np.mean(preds * targets)\n+\n+@jit\n+def accuracy(params, batch):\n+ inputs, targets = batch\n+ target_class = np.argmax(targets, axis=1)\n+ predicted_class = np.argmax(predict(params, inputs), axis=1)\n+ return np.mean(predicted_class == target_class)\n+\n+\n+if __name__ == \"__main__\":\n+ layer_sizes = [784, 1024, 1024, 10]\n+ param_scale = 0.1\n+ step_size = 0.001\n+ num_epochs = 10\n+ batch_size = 128\n+\n+ train_images, train_labels, test_images, test_labels = datasets.mnist()\n+ num_train = train_images.shape[0]\n+ num_complete_batches, leftover = divmod(num_train, batch_size)\n+ num_batches = num_complete_batches + bool(leftover)\n+\n+\n+ # For this manual SPMD example, we get the number of devices (e.g. GPUs or\n+ # TPUs) that we're using, and use it to reshape data minibatches.\n+ num_devices = xla_bridge.device_count()\n+ def data_stream():\n+ rng = npr.RandomState(0)\n+ while True:\n+ perm = rng.permutation(num_train)\n+ for i in range(num_batches):\n+ batch_idx = perm[i * batch_size:(i + 1) * batch_size]\n+ images, labels = train_images[batch_idx], train_labels[batch_idx]\n+ # For this SPMD example, we reshape the data batch dimension into two\n+ # batch dimensions, one of which is mapped over parallel devices.\n+ batch_size_per_device, ragged = divmod(images.shape[0], num_devices)\n+ if ragged:\n+ msg = \"batch size must be divisible by device count, got {} and {}.\"\n+ raise ValueError(msg.format(batch_size, num_devices))\n+ shape_prefix = (num_devices, batch_size_per_device)\n+ images = images.reshape(shape_prefix + images.shape[1:])\n+ labels = labels.reshape(shape_prefix + labels.shape[1:])\n+ yield images, labels\n+ batches = data_stream()\n+\n+ @partial(pmap, axis_name='batch')\n+ def spmd_update(params, batch):\n+ grads = grad(loss)(params, batch)\n+ # We compute the total gradients, summing across the device-mapped axis,\n+ # using the `lax.psum` SPMD primitive, which does a fast all-reduce-sum.\n+ grads = [(lax.psum(dw, 'batch'), lax.psum(db, 'batch')) for dw, db in grads]\n+ return [(w - step_size * dw, b - step_size * db)\n+ for (w, b), (dw, db) in zip(params, grads)]\n+\n+ # We replicate parameters out across devices. (Check the implementation of\n+ # replicate; analogous to device_put, it's a simple wrapper around pmap.)\n+ params = replicate(init_random_params(param_scale, layer_sizes))\n+\n+ for epoch in range(num_epochs):\n+ start_time = time.time()\n+ for _ in range(num_batches):\n+ params = spmd_update(params, next(batches))\n+ epoch_time = time.time() - start_time\n+\n+ # We evaluate using the jitted `accuracy` function (not using pmap) by\n+ # grabbing just one of the replicated parameter values.\n+ train_acc = accuracy(unreplicate(params), (train_images, train_labels))\n+ test_acc = accuracy(unreplicate(params), (test_images, test_labels))\n+ print(\"Epoch {} in {:0.2f} sec\".format(epoch, epoch_time))\n+ print(\"Training set accuracy {}\".format(train_acc))\n+ print(\"Test set accuracy {}\".format(test_acc))\n" }, { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -43,7 +43,7 @@ from .tree_util import (process_pytree, node_types, build_tree, PyTreeDef,\ntree_transpose, leaf)\nfrom .util import (unzip2, unzip3, curry, partial, safe_map, safe_zip,\nWrapHashably, prod)\n-from .lib.xla_bridge import canonicalize_dtype\n+from .lib.xla_bridge import canonicalize_dtype, device_count\nfrom .abstract_arrays import ShapedArray\nfrom .interpreters import partial_eval as pe\nfrom .interpreters import xla\n@@ -678,6 +678,8 @@ tree_to_pval_tuples = partial(process_pytree, pe.pack_pvals)\ndevice_put = jit(lambda x: x)\ndevice_get_array = lambda x: x.copy() if type(x) is xla.DeviceArray else x\ndevice_get = partial(tree_map, device_get_array)\n+replicate = lambda x: pmap(lambda _: x)(onp.arange(device_count()))\n+unreplicate = lambda x: tree_map(op.itemgetter(0), x)\ndef _argnums_partial(f, dyn_argnums, args):\n" }, { "change_type": "DELETE", "old_path": "spmd_toy.py", "new_path": null, "diff": "-from functools import partial\n-import operator as op\n-\n-import numpy as onp\n-\n-import jax.numpy as np\n-from jax import pmap, serial_pmap, grad\n-from jax import lax\n-from jax.tree_util import tree_map\n-from jax.lib.xla_bridge import device_count\n-\n-\n-step_size = 0.01\n-rng = onp.random.RandomState(0)\n-\n-def predict(params, inputs):\n- for W, b in params:\n- outputs = np.dot(inputs, W) + b\n- inputs = np.tanh(outputs)\n- return outputs\n-\n-def loss(params, batch):\n- inputs, targets = batch\n- predictions = predict(params, inputs)\n- return np.sum((predictions - targets)**2)\n-\n-def update(params, batch):\n- grads = grad(loss)(params, batch)\n- new_params = [(W - step_size * dW, b - step_size * db)\n- for (W, b), (dW, db) in zip(params, grads)]\n- return new_params\n-\n-# initialize parameters\n-layer_sizes = [2, 4, 3] # input size 2, output size 3\n-scale = 0.01\n-params = [(scale * rng.randn(m, n), scale * rng.randn(n))\n- for m, n in zip(layer_sizes[:-1], layer_sizes[1:])]\n-\n-# set up fake data\n-inputs = rng.randn(10, 2) # batch size 10, feature size 2\n-targets = rng.randn(10, 3) # batch size 10, output size 3\n-batch = (inputs, targets)\n-\n-\n-# standard functions\n-print(loss(params, batch))\n-print(update(params, batch)[0][0])\n-\n-\n-# reshape / replicate data\n-num_devices = device_count()\n-spmd_params = tree_map(partial(lax.broadcast, sizes=(num_devices,)), params)\n-spmd_inputs = inputs.reshape((num_devices, -1, 2))\n-spmd_targets = targets.reshape((num_devices, -1, 3))\n-spmd_batch = (spmd_inputs, spmd_targets)\n-\n-@partial(pmap, axis_name='i')\n-def spmd_loss(params, batch):\n- inputs, targets = batch\n- predictions = predict(params, inputs)\n- batch_loss = np.sum((predictions - targets)**2)\n- return lax.psum(batch_loss, 'i')\n-print(spmd_loss(spmd_params, spmd_batch))\n-\n-@partial(pmap, axis_name='i')\n-def spmd_update(params, batch):\n- grads = grad(loss)(params, batch) # loss, not spmd_loss\n- grads = tree_map(partial(lax.psum, axis_name='i'), grads)\n- new_params = [(W - step_size * dW, b - step_size * db)\n- for (W, b), (dW, db) in zip(params, grads)]\n- return new_params\n-print(spmd_update(spmd_params, spmd_batch)[0][0])\n" } ]
Python
Apache License 2.0
google/jax
add spmd mnist example
260,335
08.03.2019 16:09:22
28,800
9361d617293bc9ce4a3674e3542331ef4038c5d0
generalize while_loop vmap rule to handle tuples
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -3703,13 +3703,22 @@ def _while_loop_batching_rule(batched_args, batch_dims, aval_out, cond_jaxpr,\ndef lifted(loop_carry, cond_consts, body_consts):\npred = core.eval_jaxpr(cond_jaxpr, cond_consts, (), loop_carry)\nnew_loop_carry = core.eval_jaxpr(body_jaxpr, body_consts, (), loop_carry)\n- return select(pred, new_loop_carry, loop_carry)\n+ return _jaxtupletree_select(pred, new_loop_carry, loop_carry)\nf = batching.batch_transform(\nlifted, size, (init_val_bd, cond_consts_bd, body_consts_bd), init_val_bd)\nreturn f.call_wrapped((batched_loop_carry, cond_consts, body_consts))\nreturn while_loop(batched_cond_fun, batched_body_fun, init_val), init_val_bd\n+def _jaxtupletree_select(pred, on_true, on_false):\n+ aval = core.get_aval(on_true)\n+ if type(aval) is core.AbstractTuple:\n+ return core.pack(map(partial(_jaxtupletree_select, pred), on_true, on_false))\n+ elif isinstance(aval, UnshapedArray):\n+ return select(pred, on_true, on_false)\n+ else:\n+ raise TypeError(aval)\n+\nwhile_p = Primitive('while')\nwhile_p.def_impl(partial(xla.apply_primitive, while_p))\nwhile_p.def_abstract_eval(_while_loop_abstract_eval)\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -862,6 +862,23 @@ class BatchingTest(jtu.JaxTestCase):\nexpected = onp.array([4, 3])\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testWhileLoopTuple(self):\n+ def cond_fun(loop_carry):\n+ x, y = loop_carry\n+ return x + y < 5\n+\n+ def body_fun(loop_carry):\n+ x, y = loop_carry\n+ x = x + 1\n+ return x, y\n+\n+ def fun(x, y):\n+ return lax.while_loop(cond_fun, body_fun, (x, y))\n+\n+ ans = vmap(fun)(onp.array([0, 0]), onp.array([1, 2]))\n+ expected = (onp.array([4, 3]), onp.array([1, 2]))\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
generalize while_loop vmap rule to handle tuples
260,335
08.03.2019 16:16:39
28,800
58659182949761b0bd7e3fcccc3fd651444be1f6
add fori_loop batching test
[ { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -879,6 +879,20 @@ class BatchingTest(jtu.JaxTestCase):\nexpected = (onp.array([4, 3]), onp.array([1, 2]))\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testForiLoop(self):\n+ def body_fun(i, loop_carry):\n+ x, y = loop_carry\n+ x = x + 1\n+ y = y + 2\n+ return x, y\n+\n+ def fun(x):\n+ return lax.fori_loop(0, 10, body_fun, (x, 0))\n+\n+ ans = vmap(fun)(onp.array([0, 1]))\n+ expected = (onp.array([10, 11]), onp.array([20, 20]))\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
add fori_loop batching test
260,403
09.03.2019 17:31:07
28,800
4e02a607e0a13a1ab244964c5cda38682dae3162
fix the broken gufuncs.ipynb notebook
[ { "change_type": "MODIFY", "old_path": "notebooks/gufuncs.ipynb", "new_path": "notebooks/gufuncs.ipynb", "diff": "\"\\n\",\n\"## What is a gufunc?\\n\",\n\"\\n\",\n- \"[Generalized universal functions](https://docs.scipy.org/doc/numpy-1.15.0/reference/c-api.generalized-ufuncs.html) (\\\"gufuncs\\\") are one of my favorite abstractions from NumPy. They generalize NumPy's\n- [broadcasting rules](https://docs.scipy.org/doc/numpy-1.15.0/user/basics.broadcasting.html) to handle non-scalar operations. When a gufuncs is applied to arrays, there are:\\n\",\n+ \"[Generalized universal functions](https://docs.scipy.org/doc/numpy-1.15.0/reference/c-api.generalized-ufuncs.html) (\\\"gufuncs\\\") are one of my favorite abstractions from NumPy. They generalize NumPy's [broadcasting rules](https://docs.scipy.org/doc/numpy-1.15.0/user/basics.broadcasting.html) to handle non-scalar operations. When a gufuncs is applied to arrays, there are:\\n\",\n\"- \\\"core dimensions\\\" over which an operation is defined.\\n\",\n\"- \\\"broadcast dimensions\\\" over which operations can be automatically vectorized.\\n\",\n\"\\n\",\n" } ]
Python
Apache License 2.0
google/jax
fix the broken gufuncs.ipynb notebook
260,403
09.03.2019 18:04:45
28,800
e07d557e173e86868990f1a22b57b2cf3370e873
fix notebooks that did not install jax/jaxlib for interactive colab use
[ { "change_type": "MODIFY", "old_path": "notebooks/maml.ipynb", "new_path": "notebooks/maml.ipynb", "diff": "\"- extending MAML to handle batching at the task-level\\n\"\n]\n},\n+ {\n+ \"metadata\": {\n+ \"colab_type\": \"code\",\n+ \"id\": \"PaW85yP_BrCF\",\n+ \"colab\": {}\n+ },\n+ \"cell_type\": \"code\",\n+ \"source\": [\n+ \"!pip install --upgrade -q https://storage.googleapis.com/jax-wheels/cuda$(echo $CUDA_VERSION | sed -e 's/\\\\.//' -e 's/\\\\..*//')/jaxlib-0.1.11-cp36-none-linux_x86_64.whl\\n\",\n+ \"!pip install --upgrade -q jax\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n{\n\"cell_type\": \"code\",\n\"execution_count\": 1,\n" }, { "change_type": "MODIFY", "old_path": "notebooks/vmapped log-probs.ipynb", "new_path": "notebooks/vmapped log-probs.ipynb", "diff": "\"Inspired by a notebook by @davmre.\"\n]\n},\n+ {\n+ \"metadata\": {\n+ \"colab_type\": \"code\",\n+ \"id\": \"PaW85yP_BrCF\",\n+ \"colab\": {}\n+ },\n+ \"cell_type\": \"code\",\n+ \"source\": [\n+ \"!pip install --upgrade -q https://storage.googleapis.com/jax-wheels/cuda$(echo $CUDA_VERSION | sed -e 's/\\\\.//' -e 's/\\\\..*//')/jaxlib-0.1.11-cp36-none-linux_x86_64.whl\\n\",\n+ \"!pip install --upgrade -q jax\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n{\n\"cell_type\": \"code\",\n\"execution_count\": 1,\n" } ]
Python
Apache License 2.0
google/jax
fix notebooks that did not install jax/jaxlib for interactive colab use
260,335
11.03.2019 15:59:09
25,200
6881252fb57b33b952768f3f220002c7e87593b4
fix dtype issue in new test
[ { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -917,7 +917,7 @@ class BatchingTest(jtu.JaxTestCase):\ndef f(key):\ndef body_fn(uk):\nkey = uk[1]\n- u = random.uniform(key, ())\n+ u = random.uniform(key, (), dtype=np.float64)\nkey, _ = random.split(key)\nreturn u, key\n" } ]
Python
Apache License 2.0
google/jax
fix dtype issue in new test
260,314
14.03.2019 10:08:09
14,400
82938b9b5a4557ed4443e02a51d0b58025708de2
fix logpdf shape of uniform dist
[ { "change_type": "MODIFY", "old_path": "jax/scipy/stats/uniform.py", "new_path": "jax/scipy/stats/uniform.py", "diff": "@@ -20,14 +20,14 @@ import numpy as onp\nimport scipy.stats as osp_stats\nfrom ... import lax\n-from ...numpy.lax_numpy import _promote_args_like, _wraps, where, inf, logical_or\n+from ...numpy.lax_numpy import _promote_args_like, _wraps, where, inf, logical_or, broadcast_to\n@_wraps(osp_stats.uniform.logpdf)\ndef logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.uniform.logpdf, x, loc, scale)\nfill_value = lax.neg(lax.log(scale))\n- log_probs = lax.broadcast(fill_value, onp.shape(x))\n+ log_probs = broadcast_to(fill_value, onp.shape(x))\nreturn where(logical_or(lax.ge(x, lax.add(loc, scale)),\nlax.le(x, loc)), -inf, log_probs)\n" } ]
Python
Apache License 2.0
google/jax
fix logpdf shape of uniform dist
260,314
14.03.2019 11:49:07
14,400
cf9564ca374b56223b21b3cf89cdb23fda0ef84c
add test for uniform shape
[ { "change_type": "MODIFY", "old_path": "jax/scipy/stats/uniform.py", "new_path": "jax/scipy/stats/uniform.py", "diff": "@@ -27,7 +27,8 @@ from ...numpy.lax_numpy import _promote_args_like, _wraps, where, inf, logical_o\ndef logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.uniform.logpdf, x, loc, scale)\nfill_value = lax.neg(lax.log(scale))\n- log_probs = broadcast_to(fill_value, onp.shape(x))\n+ log_probs_shape = lax.broadcast_shapes(*[onp.shape(x), onp.shape(loc), onp.shape(scale)])\n+ log_probs = broadcast_to(fill_value, log_probs_shape)\nreturn where(logical_or(lax.ge(x, lax.add(loc, scale)),\nlax.le(x, loc)), -inf, log_probs)\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_stats_test.py", "new_path": "tests/scipy_stats_test.py", "diff": "@@ -174,7 +174,12 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nx, loc, scale = map(rng, shapes, dtypes)\nreturn [x, loc, onp.abs(scale)]\n+ def args_maker2():\n+ _, loc, scale = map(rng, shapes, dtypes)\n+ return [0.5, loc, onp.abs(scale)]\n+\nself._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=True)\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker2, check_dtypes=True)\nself._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\nif __name__ == \"__main__\":\n" } ]
Python
Apache License 2.0
google/jax
add test for uniform shape
260,285
14.03.2019 16:35:23
0
2ca77821642a280e11e0ec5fb29d16dcd3db56c7
Allow negative padding in pad gradient
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -2356,20 +2356,16 @@ def _pad_shape_rule(operand, padding_value, padding_config):\ndef _pad_transpose(t, operand, padding_value, padding_config):\nlo, hi, interior = zip(*padding_config)\n- if onp.any(onp.less(lo, 0)) or onp.any(onp.less(hi, 0)):\n- msg = \"pad transpose not implemented for negative padding, got {}.\"\n- raise NotImplementedError(msg.format(padding_config))\ntotal = lambda x: _reduce_sum(x, list(range(t.ndim)))\n- t_op = lambda: slice(t, lo, onp.subtract(t.shape, hi), onp.add(interior, 1))\n- t_operand = t_op() if operand is None else None\n+ def t_op():\n+ unpad_config = zip(onp.negative(lo), onp.negative(hi), onp.zeros_like(interior))\n+ unpadded = pad(t, 0., unpad_config)\n+ return slice(unpadded, onp.zeros_like(lo), unpadded.shape, onp.add(interior, 1))\n- if padding_value is None:\n- t_operand = t_op() if t_operand is None else t_operand\n- t_padv = sub(total(t), total(t_operand))\n- else:\n- t_padv = None\n+ t_operand = t_op() if operand is None else None\n+ t_padv = sub(total(t), total(t_operand)) if padding_value is None else None\nreturn [t_operand, t_padv]\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -2007,7 +2007,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n\"shape\": shape, \"dtype\": dtype, \"pads\": pads, \"rng\": jtu.rand_small()}\nfor shape in [(2, 3)]\nfor dtype in float_dtypes\n- for pads in [[(1, 2, 1), (0, 1, 0)]]))\n+ for pads in [[(1, 2, 1), (0, 1, 0)], [(-1, 0, 0), (-1, 0, 2)]]))\ndef testPadGrad(self, shape, dtype, pads, rng):\ntol = 1e-2 if onp.finfo(dtype).bits == 32 else None\n" } ]
Python
Apache License 2.0
google/jax
Allow negative padding in pad gradient
260,314
14.03.2019 23:11:00
14,400
5e6d48852eea01c33c5b2df03a30382c15c3f032
use simpler fix
[ { "change_type": "MODIFY", "old_path": "jax/scipy/stats/uniform.py", "new_path": "jax/scipy/stats/uniform.py", "diff": "@@ -26,9 +26,7 @@ from ...numpy.lax_numpy import _promote_args_like, _wraps, where, inf, logical_o\n@_wraps(osp_stats.uniform.logpdf)\ndef logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.uniform.logpdf, x, loc, scale)\n- fill_value = lax.neg(lax.log(scale))\n- log_probs_shape = lax.broadcast_shapes(onp.shape(x), onp.shape(loc), onp.shape(scale))\n- log_probs = broadcast_to(fill_value, log_probs_shape)\n+ log_probs = lax.neg(lax.log(scale))\nreturn where(logical_or(lax.ge(x, lax.add(loc, scale)),\nlax.le(x, loc)), -inf, log_probs)\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_stats_test.py", "new_path": "tests/scipy_stats_test.py", "diff": "@@ -177,7 +177,6 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=True)\nself._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n- assert lax_fun(*args_maker()).shape == lax.broadcast_shapes(*shapes)\nif __name__ == \"__main__\":\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
use simpler fix
260,314
14.03.2019 23:12:07
14,400
ab2de951a013a24474778b5ab1e598c449a377ea
no need broadcast_to
[ { "change_type": "MODIFY", "old_path": "jax/scipy/stats/uniform.py", "new_path": "jax/scipy/stats/uniform.py", "diff": "@@ -20,7 +20,7 @@ import numpy as onp\nimport scipy.stats as osp_stats\nfrom ... import lax\n-from ...numpy.lax_numpy import _promote_args_like, _wraps, where, inf, logical_or, broadcast_to\n+from ...numpy.lax_numpy import _promote_args_like, _wraps, where, inf, logical_or\n@_wraps(osp_stats.uniform.logpdf)\n" } ]
Python
Apache License 2.0
google/jax
no need broadcast_to
260,314
14.03.2019 23:14:35
14,400
5bc452a698d74040385c4049ddd2b9db246c839d
revert lax import in scipy_stats_test
[ { "change_type": "MODIFY", "old_path": "tests/scipy_stats_test.py", "new_path": "tests/scipy_stats_test.py", "diff": "@@ -25,7 +25,6 @@ import numpy as onp\nimport scipy.stats as osp_stats\nfrom scipy.stats import random_correlation\n-from jax import lax\nfrom jax import test_util as jtu\nfrom jax.scipy import stats as lsp_stats\n" } ]
Python
Apache License 2.0
google/jax
revert lax import in scipy_stats_test
260,335
19.03.2019 08:32:45
25,200
518dba3e5af816bb38c2c3617432a3b6a3d695f7
fix typo in partial_eval.join_pvals (fixes
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -296,7 +296,7 @@ def join_pvals(pval1, pval2):\npvals1, pvals2 = zip(pv1, const1), zip(pv2, const2)\njoin_pvs, join_consts = unzip2(map(join_pvals, pvals1, pvals2))\nif all(isinstance(pv, AbstractValue) for pv in join_pvs):\n- return PartialVal(AbstractTuple(join_pvs), tuple(join_consts))\n+ return PartialVal((AbstractTuple(join_pvs), tuple(join_consts)))\nelse:\nreturn PartialVal((JaxprTracerTuple(join_pvs), tuple(join_consts)))\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -1421,6 +1421,12 @@ class LaxTest(jtu.JaxTestCase):\nself.assertEqual(fun(4), cfun(4))\nself.assertEqual(cfun(4), (4, 2., 4.))\n+ def testIssue514(self):\n+ # just check this doesn't crash\n+ lax.cond(True,\n+ (0, 0), lambda x: (x[0], 0),\n+ (1, 1), lambda x: x)\n+\ndef testScanAdd(self):\ndef f(x, y):\nreturn x + y\n" } ]
Python
Apache License 2.0
google/jax
fix typo in partial_eval.join_pvals (fixes #514)
260,335
19.03.2019 16:38:42
25,200
0e749f29efdfbeeb56914cc9e93b5b983dc54f7b
use unittest.SkipTest to skip tests properly
[ { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -19,6 +19,7 @@ from __future__ import print_function\nimport collections\nimport functools\nimport itertools\n+from unittest import SkipTest\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -117,7 +118,7 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\n# TODO(mattjj): unskip this test combination when real() on tpu is improved\nif (FLAGS.jax_test_dut and FLAGS.jax_test_dut.startswith(\"tpu\")\nand not shapes[0]):\n- return absltest.unittest.skip(\"real() on scalar not supported on tpu\")\n+ raise SkipTest(\"real() on scalar not supported on tpu\")\nargs_maker = self._GetArgsMaker(rng, shapes, dtypes)\nargs = args_maker()\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -20,7 +20,7 @@ import collections\nimport functools\nfrom functools import partial\nimport itertools\n-from unittest import skip\n+from unittest import skip, SkipTest\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -1759,7 +1759,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ndef testOpGrad(self, op, rng, shapes, dtype, order):\nif FLAGS.jax_test_dut and FLAGS.jax_test_dut.startswith(\"tpu\"):\nif op is lax.pow:\n- return absltest.unittest.skip(\"pow grad imprecise on tpu\")\n+ raise SkipTest(\"pow grad imprecise on tpu\")\ntol = 1e-1 if num_float_bits(dtype) == 32 else None\nargs = tuple(rng(shape, dtype) for shape in shapes)\ncheck_grads(op, args, order, tol, tol)\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -19,6 +19,7 @@ from __future__ import print_function\nfrom functools import partial\nimport itertools\n+from unittest import SkipTest\nimport numpy as onp\nimport scipy as osp\n@@ -237,7 +238,7 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nif (ord in ('nuc', 2, -2) and isinstance(axis, tuple) and len(axis) == 2 and\n(not FLAGS.jax_test_dut or not FLAGS.jax_test_dut.startswith(\"cpu\") or\nlen(shape) != 2)):\n- return absltest.unittest.skip(\"No adequate SVD implementation available\")\n+ raise SkipTest(\"No adequate SVD implementation available\")\nargs_maker = lambda: [rng(shape, dtype)]\nonp_fn = partial(onp.linalg.norm, ord=ord, axis=axis, keepdims=keepdims)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -16,6 +16,8 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n+from unittest import SkipTest\n+\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -54,7 +56,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor dtype in [onp.float32, onp.float64]))\ndef testNumpyAndXLAAgreeOnFloatEndianness(self, dtype):\nif not FLAGS.jax_enable_x64 and onp.issubdtype(dtype, onp.float64):\n- return absltest.unittest.skip(\"can't test float64 agreement\")\n+ raise SkipTest(\"can't test float64 agreement\")\nbits_dtype = onp.uint32 if onp.finfo(dtype).bits == 32 else onp.uint64\nnumpy_bits = onp.array(1., dtype).view(bits_dtype)\n" } ]
Python
Apache License 2.0
google/jax
use unittest.SkipTest to skip tests properly
260,335
19.03.2019 16:54:55
25,200
54abf1e77ae8198b1981ab8fd313e4be812a92fe
add back in pmap tests
[ { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -17,6 +17,7 @@ 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\n@@ -25,9 +26,11 @@ from absl.testing import parameterized\nimport jax.numpy as np\nfrom jax import test_util as jtu\nfrom jax import lax\n-from jax.api import pmap, vmap, jvp, grad, make_jaxpr, linearize\n+from jax.api import pmap, vmap, jvp, grad, make_jaxpr, linearize, device_put\nfrom jax.lax import psum\nfrom jax.lib import xla_bridge\n+from jax.util import prod\n+from jax.interpreters import pxla\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -35,10 +38,122 @@ config.parse_flags_with_absl()\nclass PmapTest(jtu.JaxTestCase):\n- @jtu.skip_on_devices(\"gpu\", \"tpu\")\n- def testNestedWithClosure(self):\n- assert xla_bridge.get_replica_count() == 1 # OSS CPU testing only\n- x = onp.arange(3, dtype=onp.float32).reshape(1, 1, 3)\n+ def testBasic(self):\n+ f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i')\n+\n+ shape = (xla_bridge.device_count(), 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+ expected = x - onp.sum(x, 0)\n+\n+ ans = f(x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testNestedBasic(self):\n+ f = lambda x: lax.psum(lax.psum(x, 'i'), 'j')\n+ f = pmap(pmap(f, 'i'), 'j')\n+\n+ shape = (xla_bridge.device_count(), 1, 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+ expected = onp.broadcast_to(onp.sum(x, (0, 1)), shape)\n+\n+ ans = f(x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"device_mesh_shape={}\".format(device_mesh_shape),\n+ \"device_mesh_shape\": device_mesh_shape}\n+ for device_mesh_shape in [(1, 1), (2, -1), (-1, 2)])\n+ def testNestedShardingAndStacking(self, device_mesh_shape):\n+ device_count = xla_bridge.device_count()\n+ try:\n+ mesh_shape = onp.arange(device_count).reshape(device_mesh_shape).shape\n+ except ValueError:\n+ raise SkipTest(\"incompatible device count for test: {}\")\n+\n+ f = lambda x: x\n+ f = pmap(pmap(f, 'i'), 'j')\n+\n+ shape = mesh_shape + (4,)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+ expected = x\n+ ans = f(x)\n+ self.assertEqual(ans.shape, expected.shape)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testJvpAndPartialEval(self):\n+ @partial(pmap, axis_name='i')\n+ def f(x):\n+ return np.sin(x)\n+\n+ def splitjvp(x):\n+ _, jvp = linearize(f, x)\n+ return jvp(np.ones_like(x))\n+\n+ shape = (xla_bridge.device_count(), 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+ expected = onp.cos(x)\n+\n+ ans = splitjvp(x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ make_jaxpr(splitjvp)(x) # doesn't crash\n+\n+ def testGradBasic(self):\n+ @partial(pmap, axis_name='i')\n+ def f(x):\n+ return np.sin(x)\n+\n+ shape = (xla_bridge.device_count(), 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+\n+ ans = grad(lambda x: np.sum(np.sin(x)))(x)\n+ expected = grad(lambda x: np.sum(f(x)))(x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testGradOfJvp(self):\n+ @partial(pmap, axis_name='i')\n+ def f(x):\n+ return np.sin(x)\n+\n+ def splitjvp(x):\n+ _, jvp = linearize(f, x)\n+ return jvp(np.ones_like(x))\n+\n+ fun = lambda x: np.sum(jvp(np.sin, (x,), (np.ones_like(x),))[1])\n+\n+ shape = (xla_bridge.device_count(), 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+\n+ ans = grad(lambda x: np.sum(splitjvp(x)))(x)\n+ expected = grad(fun)(x)\n+ self.assertAllClose(ans, expected, check_dtypes=True)\n+\n+ def testTwoArgsGrad(self):\n+ def f(x, y):\n+ return lax.psum(5. * np.cos(x) * np.sin(y), 'i')\n+ f = pmap(f, 'i')\n+\n+ def g(x, y):\n+ tot = np.sum(5. * np.cos(x) * np.sin(y))\n+ return tot * np.ones_like(x) # broadcast to map like pjit does\n+\n+ shape = (xla_bridge.device_count(), 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+ y = 4 + x\n+ ans = grad(lambda x, y: np.sum(g(x, y)))(x, y)\n+ expected = grad(lambda x, y: np.sum(g(x, y)))(x, y)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"device_mesh_shape={}\".format(device_mesh_shape),\n+ \"device_mesh_shape\": device_mesh_shape}\n+ for device_mesh_shape in [(1, 1), (2, -1), (-1, 2)])\n+ def testNestedWithClosure(self, device_mesh_shape):\n+ device_count = xla_bridge.device_count()\n+ try:\n+ mesh_shape = onp.arange(device_count).reshape(device_mesh_shape).shape\n+ except ValueError:\n+ raise SkipTest(\"incompatible device count for test: {}\")\n@partial(pmap, axis_name='i')\ndef test_fun(x):\n@@ -60,10 +175,42 @@ class PmapTest(jtu.JaxTestCase):\nreturn grad(lambda w: np.sum(g(w)))(x)\n+ shape = mesh_shape + (4,)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+\nans = grad(lambda x: np.sum(test_fun(x)))(x)\nexpected = grad(lambda x: np.sum(baseline_fun(x)))(x)\nself.assertAllClose(ans, expected, check_dtypes=True)\n+ def testShardedDeviceValues(self):\n+ f = lambda x: 2 * x\n+ f = pmap(f, axis_name='i')\n+\n+ shape = (xla_bridge.device_count(), 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+\n+ # test that we can pass in and out ShardedDeviceArrays\n+ y = f(x)\n+ assert type(y) is pxla.ShardedDeviceArray # pylint: disable=unidiomatic-typecheck\n+ self.assertAllClose(y, 2 * x, check_dtypes=False)\n+ z = f(y)\n+ assert type(z) is pxla.ShardedDeviceArray # pylint: disable=unidiomatic-typecheck\n+ self.assertAllClose(z, 2 * 2 * x, check_dtypes=False)\n+\n+ # test that we can pass in a regular DeviceArray\n+ y = f(device_put(x))\n+ assert type(y) is pxla.ShardedDeviceArray # pylint: disable=unidiomatic-typecheck\n+ self.assertAllClose(y, 2 * x, check_dtypes=False)\n+\n+ # test that we can pass a ShardedDeviceArray to a regular jit computation\n+ z = y + y\n+ self.assertAllClose(z, 2 * 2 * x, check_dtypes=False)\n+\n+ # test that we can handle device movement on dispatch\n+ y.device_buffers = y.device_buffers[::-1]\n+ z = f(y)\n+ self.assertAllClose(z, 2 * 2 * x[::-1], check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
add back in pmap tests
260,335
19.03.2019 17:13:44
25,200
5e52abed18ffd5ae38ff362afea76b0f2f35172e
fix typo (missing super())
[ { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -313,7 +313,8 @@ class _JaxComputationBuilderBase(object):\nif split_dimension == concat_dimension and len(replica_groups[0]) == 1:\nreturn operand\nelse:\n- return self.AllToAll(operand, split_dimension, concat_dimension, replica_groups)\n+ return super(_JaxComputationBuliderBase, self).AllToAll(\n+ operand, split_dimension, concat_dimension, replica_groups)\n@memoize_thunk\n" } ]
Python
Apache License 2.0
google/jax
fix typo (missing super())
260,335
19.03.2019 17:25:18
25,200
8cfe3a38b031a64b8b3972dcd7d09e77843393c3
remove old jax_replica_count option
[ { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -55,7 +55,6 @@ FLAGS = flags.FLAGS\nflags.DEFINE_bool('jax_enable_x64',\nstrtobool(os.getenv('JAX_ENABLE_X64', \"False\")),\n'Enable 64-bit types to be used.')\n-flags.DEFINE_integer('jax_replica_count', 1, 'Replica count for computations.')\nflags.DEFINE_string(\n'jax_xla_backend', 'xla',\n'Either \"xla\" for the XLA service directly, or \"xrt\" for an XRT backend.')\n@@ -97,25 +96,20 @@ def memoize_thunk(func):\n@memoize_thunk\ndef get_xla_client():\n- return _get_xla_client(FLAGS.jax_xla_backend,\n- FLAGS.jax_platform_name,\n- FLAGS.jax_replica_count)\n+ return _get_xla_client(FLAGS.jax_xla_backend, FLAGS.jax_platform_name)\n-def _get_xla_client(backend_name, platform_name, replica_count):\n+def _get_xla_client(backend_name, platform_name):\n\"\"\"Configures and returns a handle to the XLA client.\nArgs:\nbackend_name: backend name, 'xla' or 'xrt'\nplatform_name: platform name for XLA backend\n- replica_count: number of computation replicas with which to configure the\n- backend library.\nReturns:\nA client library module, or an object that behaves identically to one.\n\"\"\"\nglobal _platform_name\n- xla_client.initialize_replica_count(replica_count)\nif backend_name == 'xla':\nif platform_name:\nxla_client.initialize_platform_name(platform_name)\n@@ -131,10 +125,6 @@ def _get_xla_client(backend_name, platform_name, replica_count):\nreturn xla_client\n-def get_replica_count():\n- return get_xla_client().get_replica_count()\n-\n-\n_backends = {}\ndef register_backend(name, factory):\n" } ]
Python
Apache License 2.0
google/jax
remove old jax_replica_count option
260,335
20.03.2019 17:46:16
25,200
7129d2a01eb6cb567e89a6b4e72155745e0dae63
fix bug in nested pmap test code
[ { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -52,11 +52,14 @@ class PmapTest(jtu.JaxTestCase):\nf = lambda x: lax.psum(lax.psum(x, 'i'), 'j')\nf = pmap(pmap(f, 'i'), 'j')\n+ def sum_and_broadcast(x, axis):\n+ return onp.repeat(onp.sum(x, axis, keepdims=True), x.shape[axis], axis)\n+\nshape = (xla_bridge.device_count(), 1, 4)\nx = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n- expected = onp.broadcast_to(onp.sum(x, (0, 1)), shape)\nans = f(x)\n+ expected = sum_and_broadcast(sum_and_broadcast(x, 0), 1)\nself.assertAllClose(ans, expected, check_dtypes=False)\n@parameterized.named_parameters(\n@@ -75,8 +78,9 @@ class PmapTest(jtu.JaxTestCase):\nshape = mesh_shape + (4,)\nx = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n- expected = x\n+\nans = f(x)\n+ expected = x\nself.assertEqual(ans.shape, expected.shape)\nself.assertAllClose(ans, expected, check_dtypes=False)\n" } ]
Python
Apache License 2.0
google/jax
fix bug in nested pmap test code
260,335
20.03.2019 18:45:46
25,200
cb02507e2cac7961e7d2dc4ae014df7062728863
add some docstrings in pxla.py
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -109,6 +109,21 @@ def assign_shards_to_replicas(nrep, size):\nreturn tuple(indices.ravel())\ndef replica_groups(nrep, mesh_spec, mesh_axis):\n+ \"\"\"Compute XLA replica groups from a replica count and device mesh data.\n+\n+ ArgS:\n+ nrep: int, number of relpicas (a computation-dependent value).\n+ mesh_spec: tuple of integers, a specification of the logical device mesh,\n+ which depends on the lexical context of nested xla_pcalls. In particular,\n+ each xla_pcall effectively appends its mapped axis size to this tuple.\n+ mesh_axis: int, logical device mesh axis index indicating the axis along\n+ which collective operations are to be executed.\n+\n+ Returns:\n+ replica_groups, a list of lists of ints encoding a partition of the set\n+ {0, 1, ..., nrep} into equally-sized replica groups (within which\n+ collectives are executed). XLA consumes this replica group specification.\n+ \"\"\"\ntrailing_size, ragged = divmod(nrep, prod(mesh_spec))\nassert not ragged\nfull_spec = mesh_spec + [trailing_size]\n@@ -118,6 +133,7 @@ def replica_groups(nrep, mesh_spec, mesh_axis):\nreturn tuple(tuple(group) for group in zip(*groups))\ndef xla_shard(c, sizes, x):\n+ \"\"\"Analog of shard_arg that performs sharding within an XLA computation.\"\"\"\ndef _xla_shard(shape, x):\nif shape.is_tuple():\nelts = map(_xla_shard, shape.tuple_shapes(), xla_destructure(c, x))\n@@ -128,14 +144,20 @@ def xla_shard(c, sizes, x):\ndef shard_array(shape, x):\ndims = list(shape.dimensions())\nassert dims[0] == sizes[-1]\n- start_indices = xla_shard_start_indices(c, dims[0], len(dims))\n+ start_indices = _xla_shard_start_indices(c, dims[0], len(dims))\nreturn c.Reshape(c.DynamicSlice(x, start_indices, [1] + dims[1:]),\nNone, dims[1:])\nreturn _xla_shard(c.GetShape(x), x)\n+def _xla_shard_start_indices(c, axis_size, ndim):\n+ idx = c.Rem(c.ReplicaId(), c.Constant(onp.array(axis_size, onp.uint32)))\n+ zero = onp.zeros(ndim - 1, onp.uint32)\n+ return c.Concatenate([c.Reshape(idx, None, [1]), c.Constant(zero)], 0)\n+\n# TODO(b/110096942): more efficient gather\ndef xla_unshard(c, device_groups, x):\n+ \"\"\"Analog of unshard_output that un-shards within an XLA computation.\"\"\"\ndef _xla_unshard(shape, x):\nif shape.is_tuple():\nelts = map(_xla_unshard, shape.tuple_shapes(), xla_destructure(c, x))\n@@ -150,11 +172,6 @@ def xla_unshard(c, device_groups, x):\nreturn _xla_unshard(c.GetShape(x), x)\n-def xla_shard_start_indices(c, axis_size, ndim):\n- idx = c.Rem(c.ReplicaId(), c.Constant(onp.array(axis_size, onp.uint32)))\n- zero = onp.zeros(ndim - 1, onp.uint32)\n- return c.Concatenate([c.Reshape(idx, None, [1]), c.Constant(zero)], 0)\n-\n### xla_pcall\n" } ]
Python
Apache License 2.0
google/jax
add some docstrings in pxla.py
260,335
21.03.2019 07:27:08
25,200
b4e83ee7516d4d43ebd90041e3ac2ffbb745c5fb
avoid generating trivial lax.slice operations
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -556,6 +556,11 @@ def slice(operand, start_indices, limit_indices, strides=None):\n<https://www.tensorflow.org/xla/operation_semantics#slice>`_\noperator.\n\"\"\"\n+ if (onp.all(onp.equal(start_indices, 0))\n+ and onp.all(onp.equal(limit_indices, operand.shape))\n+ and strides is None):\n+ return operand\n+ else:\nreturn slice_p.bind(operand, start_indices=tuple(start_indices),\nlimit_indices=tuple(limit_indices),\nstrides=None if strides is None else tuple(strides),\n" } ]
Python
Apache License 2.0
google/jax
avoid generating trivial lax.slice operations
260,335
21.03.2019 07:37:43
25,200
e12a3cd58d8c19ed2581607fbf43666e1845c346
improve pmap device_num compatibility check
[ { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -38,6 +38,21 @@ config.parse_flags_with_absl()\nclass PmapTest(jtu.JaxTestCase):\n+ def _getMeshShape(self, device_mesh_shape):\n+ device_count = xla_bridge.device_count()\n+ if any(size == -1 for size in device_mesh_shape):\n+ try:\n+ return onp.arange(device_count).reshape(device_mesh_shape).shape\n+ except ValueError:\n+ msg = \"device mesh shape {} not compatible with device count {}\"\n+ raise SkipTest(msg.format(device_mesh_shape, device_count))\n+ else:\n+ if device_count % prod(device_mesh_shape):\n+ msg = \"device mesh size {} does not divide available device count {}\"\n+ raise SkipTest(msg.format(prod(device_mesh_shape), device_count))\n+ else:\n+ return device_mesh_shape\n+\ndef testBasic(self):\nf = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i')\n@@ -67,11 +82,7 @@ class PmapTest(jtu.JaxTestCase):\n\"device_mesh_shape\": device_mesh_shape}\nfor device_mesh_shape in [(1, 1), (2, -1), (-1, 2)])\ndef testNestedShardingAndStacking(self, device_mesh_shape):\n- device_count = xla_bridge.device_count()\n- try:\n- mesh_shape = onp.arange(device_count).reshape(device_mesh_shape).shape\n- except ValueError:\n- raise SkipTest(\"incompatible device count for test: {}\")\n+ mesh_shape = self._getMeshShape(device_mesh_shape)\nf = lambda x: x\nf = pmap(pmap(f, 'i'), 'j')\n@@ -153,11 +164,7 @@ class PmapTest(jtu.JaxTestCase):\n\"device_mesh_shape\": device_mesh_shape}\nfor device_mesh_shape in [(1, 1), (2, -1), (-1, 2)])\ndef testNestedWithClosure(self, device_mesh_shape):\n- device_count = xla_bridge.device_count()\n- try:\n- mesh_shape = onp.arange(device_count).reshape(device_mesh_shape).shape\n- except ValueError:\n- raise SkipTest(\"incompatible device count for test: {}\")\n+ mesh_shape = self._getMeshShape(device_mesh_shape)\n@partial(pmap, axis_name='i')\ndef test_fun(x):\n" } ]
Python
Apache License 2.0
google/jax
improve pmap device_num compatibility check
260,335
21.03.2019 09:29:33
25,200
540eb32ca8b24e88906558dc58c1a1853c474517
fix typos caught by review
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -96,7 +96,7 @@ def assign_shards_to_replicas(nrep, size):\n\"\"\"Produce a mapping from replica id to shard index.\nArgs:\n- nrep: int, number of relpicas (a computation-dependent value).\n+ nrep: int, number of replicas (a computation-dependent value).\nsize: int, size of the data array axis being sharded.\nReturns:\n@@ -111,8 +111,8 @@ def assign_shards_to_replicas(nrep, size):\ndef replica_groups(nrep, mesh_spec, mesh_axis):\n\"\"\"Compute XLA replica groups from a replica count and device mesh data.\n- ArgS:\n- nrep: int, number of relpicas (a computation-dependent value).\n+ Args:\n+ nrep: int, number of replicas (a computation-dependent value).\nmesh_spec: tuple of integers, a specification of the logical device mesh,\nwhich depends on the lexical context of nested xla_pcalls. In particular,\neach xla_pcall effectively appends its mapped axis size to this tuple.\n" } ]
Python
Apache License 2.0
google/jax
fix typos caught by review
260,335
21.03.2019 15:50:06
25,200
55a28b3a8aaaccbe1f725ab012a0ad459b0b3ddc
remove JaxTuples from optimizer states
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optimizers.py", "new_path": "jax/experimental/optimizers.py", "diff": "@@ -27,7 +27,8 @@ import functools\nimport jax.numpy as np\nfrom jax.core import pack\n-from jax.tree_util import tree_map, tree_multimap\n+from jax.util import partial\n+from jax.tree_util import tree_multimap, tree_flatten, tree_unflatten\ndef optimizer(opt_maker):\n@@ -38,19 +39,21 @@ def optimizer(opt_maker):\n@functools.wraps(init_fun)\ndef fmapped_init_fun(x0_tree):\n- return tree_map(lambda x0: pack(init_fun(x0)), x0_tree)\n+ x0_flat, treedef = tree_flatten(x0_tree)\n+ state_flat = zip(*map(init_fun, x0_flat))\n+ state_trees = map(partial(tree_unflatten, treedef), state_flat)\n+ return tuple(state_trees)\n@functools.wraps(update_fun)\n- def fmapped_update_fun(i, grad_tree, state_tree):\n- update = lambda g, state: pack(update_fun(i, g, *state))\n- return tree_multimap(update, grad_tree, state_tree)\n+ def fmapped_update_fun(i, grad_tree, state_trees):\n+ return tree_multimap(partial(update_fun, i), grad_tree, *state_trees)\nreturn fmapped_init_fun, fmapped_update_fun\nreturn tree_opt_maker\n-def iterate(state_tree):\n+def iterate(state_trees):\n\"\"\"Extract the current iterate from an optimizer state.\"\"\"\n- return tree_map(lambda state: tuple(state)[0], state_tree)\n+ return state_trees[0]\nget_params = iterate\n# optimizers\n" } ]
Python
Apache License 2.0
google/jax
remove JaxTuples from optimizer states
260,335
21.03.2019 16:37:04
25,200
ce9f8bacc9063de0ebd1dd3c6e18682b8ab4bfd2
optimizer update must zip* the updated result too
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optimizers.py", "new_path": "jax/experimental/optimizers.py", "diff": "@@ -27,9 +27,11 @@ import functools\nimport jax.numpy as np\nfrom jax.core import pack\n-from jax.util import partial\n+from jax.util import partial, safe_zip, safe_map, unzip2\nfrom jax.tree_util import tree_multimap, tree_flatten, tree_unflatten\n+map = safe_map\n+zip = safe_zip\ndef optimizer(opt_maker):\n\"\"\"Decorator to make an optimizer map over tuple/list/dict containers.\"\"\"\n@@ -42,11 +44,17 @@ def optimizer(opt_maker):\nx0_flat, treedef = tree_flatten(x0_tree)\nstate_flat = zip(*map(init_fun, x0_flat))\nstate_trees = map(partial(tree_unflatten, treedef), state_flat)\n+ assert all(treedef == tree_flatten(tree)[1] for tree in state_trees)\nreturn tuple(state_trees)\n@functools.wraps(update_fun)\ndef fmapped_update_fun(i, grad_tree, state_trees):\n- return tree_multimap(partial(update_fun, i), grad_tree, *state_trees)\n+ grad_flat, treedef = tree_flatten(grad_tree)\n+ state_flat, treedefs = unzip2(map(tree_flatten, state_trees))\n+ assert all(td == treedef for td in treedefs)\n+ state_flat = zip(*map(partial(update_fun, i), grad_flat, *state_flat))\n+ state_trees = map(partial(tree_unflatten, treedef), state_flat)\n+ return tuple(state_trees)\nreturn fmapped_init_fun, fmapped_update_fun\nreturn tree_opt_maker\n" } ]
Python
Apache License 2.0
google/jax
optimizer update must zip* the updated result too
260,335
21.03.2019 16:46:09
25,200
7be3649744afb582909d8fb4f31233ecd159baf5
make optimizer update_fun signatures consistent
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optimizers.py", "new_path": "jax/experimental/optimizers.py", "diff": "@@ -40,7 +40,7 @@ def optimizer(opt_maker):\ninit_fun, update_fun = opt_maker(*args, **kwargs)\n@functools.wraps(init_fun)\n- def fmapped_init_fun(x0_tree):\n+ def treemapped_init_fun(x0_tree):\nx0_flat, treedef = tree_flatten(x0_tree)\nstate_flat = zip(*map(init_fun, x0_flat))\nstate_trees = map(partial(tree_unflatten, treedef), state_flat)\n@@ -48,15 +48,15 @@ def optimizer(opt_maker):\nreturn tuple(state_trees)\n@functools.wraps(update_fun)\n- def fmapped_update_fun(i, grad_tree, state_trees):\n+ def treemapped_update_fun(i, grad_tree, state_trees):\ngrad_flat, treedef = tree_flatten(grad_tree)\nstate_flat, treedefs = unzip2(map(tree_flatten, state_trees))\nassert all(td == treedef for td in treedefs)\n- state_flat = zip(*map(partial(update_fun, i), grad_flat, *state_flat))\n+ state_flat = zip(*map(partial(update_fun, i), grad_flat, zip(*state_flat)))\nstate_trees = map(partial(tree_unflatten, treedef), state_flat)\nreturn tuple(state_trees)\n- return fmapped_init_fun, fmapped_update_fun\n+ return treemapped_init_fun, treemapped_update_fun\nreturn tree_opt_maker\ndef iterate(state_trees):\n@@ -80,7 +80,8 @@ def sgd(step_size):\nstep_size = make_schedule(step_size)\ndef init_fun(x0):\nreturn (x0,)\n- def update_fun(i, g, x):\n+ def update_fun(i, g, state):\n+ x, = state\nreturn (x - step_size(i) * g,)\nreturn init_fun, update_fun\n@@ -99,7 +100,8 @@ def momentum(step_size, mass):\ndef init_fun(x0):\nv0 = np.zeros_like(x0)\nreturn x0, v0\n- def update_fun(i, g, x, velocity):\n+ def update_fun(i, g, state):\n+ x, velocity = state\nvelocity = mass * velocity - (1. - mass) * g\nx = x + step_size(i) * velocity\nreturn x, velocity\n@@ -120,7 +122,8 @@ def rmsprop(step_size, gamma=0.9, eps=1e-8):\ndef init_fun(x0):\navg_sq_grad = np.ones_like(x0)\nreturn x0, avg_sq_grad\n- def update_fun(i, g, x, avg_sq_grad):\n+ def update_fun(i, g, state):\n+ x, avg_sq_grad = state\navg_sq_grad = avg_sq_grad * gamma + g**2 * (1. - gamma)\nx = x - step_size(i) * g / (np.sqrt(avg_sq_grad) + eps)\nreturn x, avg_sq_grad\n@@ -148,7 +151,8 @@ def adam(step_size, b1=0.9, b2=0.999, eps=1e-8):\nm0 = np.zeros_like(x0)\nv0 = np.zeros_like(x0)\nreturn x0, m0, v0\n- def update_fun(i, g, x, m, v):\n+ def update_fun(i, g, state):\n+ x, m, v = state\nm = (1 - b1) * g + b1 * m # First moment estimate.\nv = (1 - b2) * (g ** 2) + b2 * v # Second moment estimate.\nmhat = m / (1 - b1 ** (i + 1)) # Bias correction.\n" } ]
Python
Apache License 2.0
google/jax
make optimizer update_fun signatures consistent
260,335
21.03.2019 19:08:19
25,200
04cfa11ebe472ab8a4e1e5ef58cd2961c379e3dc
almost done with a prefix_multimap solution
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optimizers.py", "new_path": "jax/experimental/optimizers.py", "diff": "@@ -28,7 +28,7 @@ import functools\nimport jax.numpy as np\nfrom jax.core import pack\nfrom jax.util import partial, safe_zip, safe_map, unzip2\n-from jax.tree_util import tree_multimap, tree_flatten, tree_unflatten\n+from jax.tree_util import tree_map, prefix_multimap, tree_structure\nmap = safe_map\nzip = safe_zip\n@@ -41,27 +41,19 @@ def optimizer(opt_maker):\n@functools.wraps(init_fun)\ndef treemapped_init_fun(x0_tree):\n- x0_flat, treedef = tree_flatten(x0_tree)\n- state_flat = zip(*map(init_fun, x0_flat))\n- state_trees = map(partial(tree_unflatten, treedef), state_flat)\n- assert all(treedef == tree_flatten(tree)[1] for tree in state_trees)\n- return tuple(state_trees)\n+ return tree_map(init_fun, x0_tree)\n@functools.wraps(update_fun)\n- def treemapped_update_fun(i, grad_tree, state_trees):\n- grad_flat, treedef = tree_flatten(grad_tree)\n- state_flat, treedefs = unzip2(map(tree_flatten, state_trees))\n- assert all(td == treedef for td in treedefs)\n- state_flat = zip(*map(partial(update_fun, i), grad_flat, zip(*state_flat)))\n- state_trees = map(partial(tree_unflatten, treedef), state_flat)\n- return tuple(state_trees)\n+ def treemapped_update_fun(i, grad_tree, state_tree):\n+ tdf = tree_structure(grad_tree)\n+ return prefix_multimap(partial(update_fun, i), tdf, grad_tree, state_tree)\nreturn treemapped_init_fun, treemapped_update_fun\nreturn tree_opt_maker\ndef iterate(state_trees):\n\"\"\"Extract the current iterate from an optimizer state.\"\"\"\n- return state_trees[0]\n+ raise NotImplementedError # TODO don't have tree structure... assume flat?\nget_params = iterate\n# optimizers\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -24,7 +24,7 @@ from ..core import JaxTuple, Trace, Tracer, new_master, get_aval, pack, call_p,\nfrom ..ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval,\nzeros_like_p, zero, Zero)\nfrom ..util import unzip2, unzip3, safe_map, safe_zip, partial\n-from ..tree_util import process_pytree, build_tree, register_pytree_node, prune, tree_map\n+from ..tree_util import process_pytree, build_tree, register_pytree_node, tree_map\nfrom ..linear_util import thunk, staged, transformation, transformation_with_aux, wrap_init\nfrom six.moves import builtins, reduce\n" }, { "change_type": "MODIFY", "old_path": "jax/tree_util.py", "new_path": "jax/tree_util.py", "diff": "@@ -36,15 +36,17 @@ def tree_map(f, tree):\ndef tree_multimap(f, tree, *rest):\n- tree_type = type(tree)\n- node_type = node_types.get(tree_type)\n+ node_type = node_types.get(type(tree))\nif node_type:\nchildren, node_spec = node_type.to_iterable(tree)\nall_children = [children]\nfor other_tree in rest:\n- other_children, other_node_spec = node_type.to_iterable(other_tree)\n- if other_node_spec != node_spec:\n- raise TypeError('Mismatch: {} != {}'.format(other_node_spec, node_spec))\n+ other_node_type = node_types.get(type(other_tree))\n+ if node_type != other_node_type:\n+ raise TypeError('Mismatch: {} != {}'.format(other_node_type, node_type))\n+ other_children, other_node_data = node_type.to_iterable(other_tree)\n+ if other_node_data != node_spec:\n+ raise TypeError('Mismatch: {} != {}'.format(other_node_data, node_spec))\nall_children.append(other_children)\nnew_children = [tree_multimap(f, *xs) for xs in zip(*all_children)]\n@@ -53,6 +55,30 @@ def tree_multimap(f, tree, *rest):\nreturn f(tree, *rest)\n+def prefix_multimap(f, treedef, tree, *rest):\n+ \"\"\"Like tree_multimap but only maps down through a tree prefix.\"\"\"\n+ if treedef is leaf:\n+ return f(tree, *rest)\n+ else:\n+ node_type = node_types.get(type(tree))\n+ if node_type != treedef.node_type:\n+ raise TypeError('Mismatch: {} != {}'.format(treedef.node_type, node_type))\n+ children, node_data = node_type.to_iterable(tree)\n+ if node_data != treedef.node_data:\n+ raise TypeError('Mismatch: {} != {}'.format(treedef.node_data, node_data))\n+ all_children = [children]\n+ for other_tree in rest:\n+ other_children, other_node_data = node_type.to_iterable(other_tree)\n+ if other_node_data != node_data:\n+ raise TypeError('Mismatch: {} != {}'.format(other_node_data, node_data))\n+ all_children.append(other_children)\n+ all_children = zip(*all_children)\n+\n+ new_children = [tree_multimap_prefix(f, td, *xs)\n+ for td, xs in zip(treedef.children, all_children)]\n+ return node_type.from_iterable(node_data, new_children)\n+\n+\ndef tree_reduce(f, tree):\nflat, _ = tree_flatten(tree)\nreturn reduce(f, flat)\n@@ -132,15 +158,6 @@ def tree_structure(tree):\nreturn spec\n-def prune(treedef, tuple_tree):\n- if treedef is leaf:\n- return tuple_tree\n- elif treedef.children:\n- return tuple(map(prune, treedef.children, tuple_tree))\n- else:\n- return ()\n-\n-\nclass PyTreeDef(object):\ndef __init__(self, node_type, node_data, children):\nself.node_type = node_type\n" } ]
Python
Apache License 2.0
google/jax
almost done with a prefix_multimap solution
260,335
21.03.2019 19:23:00
25,200
6fdf64d7ee5480674ba4a8dd98e3169d3f0d9bad
add back an OptState that is a proper pytree
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optimizers.py", "new_path": "jax/experimental/optimizers.py", "diff": "@@ -22,13 +22,15 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n-import operator\n+import collections\nimport functools\n+import operator\nimport jax.numpy as np\nfrom jax.core import pack\nfrom jax.util import partial, safe_zip, safe_map, unzip2\n-from jax.tree_util import tree_map, prefix_multimap, tree_structure\n+from jax.tree_util import (tree_map, prefix_multimap, tree_structure,\n+ register_pytree_node)\nmap = safe_map\nzip = safe_zip\n@@ -40,22 +42,31 @@ def optimizer(opt_maker):\ninit_fun, update_fun = opt_maker(*args, **kwargs)\n@functools.wraps(init_fun)\n- def treemapped_init_fun(x0_tree):\n- return tree_map(init_fun, x0_tree)\n+ def tree_init_fun(x0_tree):\n+ prefix = tree_structure(x0_tree)\n+ return OptState(prefix, tree_map(init_fun, x0_tree))\n@functools.wraps(update_fun)\n- def treemapped_update_fun(i, grad_tree, state_tree):\n- tdf = tree_structure(grad_tree)\n- return prefix_multimap(partial(update_fun, i), tdf, grad_tree, state_tree)\n+ def tree_update_fun(i, grad_tree, state_tree):\n+ assert type(state_tree) is OptState\n+ prefix, tree = state_tree\n+ tree = prefix_multimap(partial(update_fun, i), prefix, grad_tree, tree)\n+ return OptState(prefix, tree)\n- return treemapped_init_fun, treemapped_update_fun\n+ return tree_init_fun, tree_update_fun\nreturn tree_opt_maker\n-def iterate(state_trees):\n+def iterate(state_tree):\n\"\"\"Extract the current iterate from an optimizer state.\"\"\"\n- raise NotImplementedError # TODO don't have tree structure... assume flat?\n+ assert type(state_tree) is OptState\n+ prefix, tree = state_tree\n+ return prefix_multimap(operator.itemgetter(0), prefix, tree)\nget_params = iterate\n+OptState = collections.namedtuple(\"OptState\", [\"prefix\", \"tree\"])\n+register_pytree_node(OptState, lambda xs: ([xs.tree], xs.prefix),\n+ lambda prefix, xs: OptState(prefix, xs[0]))\n+\n# optimizers\n@optimizer\n" }, { "change_type": "MODIFY", "old_path": "jax/tree_util.py", "new_path": "jax/tree_util.py", "diff": "@@ -74,7 +74,7 @@ def prefix_multimap(f, treedef, tree, *rest):\nall_children.append(other_children)\nall_children = zip(*all_children)\n- new_children = [tree_multimap_prefix(f, td, *xs)\n+ new_children = [prefix_multimap(f, td, *xs)\nfor td, xs in zip(treedef.children, all_children)]\nreturn node_type.from_iterable(node_data, new_children)\n" } ]
Python
Apache License 2.0
google/jax
add back an OptState that is a proper pytree
260,335
22.03.2019 07:12:25
25,200
f94c20633a58ec2f324c8d706b1ea9be10e21ac3
back to original tree_mimomap optimizers solution
[ { "change_type": "MODIFY", "old_path": "jax/experimental/optimizers.py", "new_path": "jax/experimental/optimizers.py", "diff": "@@ -29,7 +29,7 @@ import operator\nimport jax.numpy as np\nfrom jax.core import pack\nfrom jax.util import partial, safe_zip, safe_map, unzip2\n-from jax.tree_util import (tree_map, prefix_multimap, tree_structure,\n+from jax.tree_util import (tree_map, tree_mimomap, tree_structure,\nregister_pytree_node)\nmap = safe_map\n@@ -43,30 +43,20 @@ def optimizer(opt_maker):\n@functools.wraps(init_fun)\ndef tree_init_fun(x0_tree):\n- prefix = tree_structure(x0_tree)\n- return OptState(prefix, tree_map(init_fun, x0_tree))\n+ return tree_mimomap(init_fun, x0_tree)\n@functools.wraps(update_fun)\n- def tree_update_fun(i, grad_tree, state_tree):\n- assert type(state_tree) is OptState\n- prefix, tree = state_tree\n- tree = prefix_multimap(partial(update_fun, i), prefix, grad_tree, tree)\n- return OptState(prefix, tree)\n+ def tree_update_fun(i, grad_tree, state_trees):\n+ return tree_mimomap(partial(update_fun, i), grad_tree, *state_trees)\nreturn tree_init_fun, tree_update_fun\nreturn tree_opt_maker\n-def iterate(state_tree):\n+def iterate(state_trees):\n\"\"\"Extract the current iterate from an optimizer state.\"\"\"\n- assert type(state_tree) is OptState\n- prefix, tree = state_tree\n- return prefix_multimap(operator.itemgetter(0), prefix, tree)\n+ return state_trees[0]\nget_params = iterate\n-OptState = collections.namedtuple(\"OptState\", [\"prefix\", \"tree\"])\n-register_pytree_node(OptState, lambda xs: ([xs.tree], xs.prefix),\n- lambda prefix, xs: OptState(prefix, xs[0]))\n-\n# optimizers\n@optimizer\n@@ -83,8 +73,7 @@ def sgd(step_size):\nstep_size = make_schedule(step_size)\ndef init_fun(x0):\nreturn (x0,)\n- def update_fun(i, g, state):\n- x, = state\n+ def update_fun(i, g, x):\nreturn (x - step_size(i) * g,)\nreturn init_fun, update_fun\n@@ -103,8 +92,7 @@ def momentum(step_size, mass):\ndef init_fun(x0):\nv0 = np.zeros_like(x0)\nreturn x0, v0\n- def update_fun(i, g, state):\n- x, velocity = state\n+ def update_fun(i, g, x, velocity):\nvelocity = mass * velocity - (1. - mass) * g\nx = x + step_size(i) * velocity\nreturn x, velocity\n@@ -125,8 +113,7 @@ def rmsprop(step_size, gamma=0.9, eps=1e-8):\ndef init_fun(x0):\navg_sq_grad = np.ones_like(x0)\nreturn x0, avg_sq_grad\n- def update_fun(i, g, state):\n- x, avg_sq_grad = state\n+ def update_fun(i, g, x, avg_sq_grad):\navg_sq_grad = avg_sq_grad * gamma + g**2 * (1. - gamma)\nx = x - step_size(i) * g / (np.sqrt(avg_sq_grad) + eps)\nreturn x, avg_sq_grad\n@@ -154,8 +141,7 @@ def adam(step_size, b1=0.9, b2=0.999, eps=1e-8):\nm0 = np.zeros_like(x0)\nv0 = np.zeros_like(x0)\nreturn x0, m0, v0\n- def update_fun(i, g, state):\n- x, m, v = state\n+ def update_fun(i, g, x, m, v):\nm = (1 - b1) * g + b1 * m # First moment estimate.\nv = (1 - b2) * (g ** 2) + b2 * v # Second moment estimate.\nmhat = m / (1 - b1 ** (i + 1)) # Bias correction.\n" }, { "change_type": "MODIFY", "old_path": "jax/tree_util.py", "new_path": "jax/tree_util.py", "diff": "@@ -26,6 +26,17 @@ map = safe_map\ndef 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+ \"\"\"\nnode_type = node_types.get(type(tree))\nif node_type:\nchildren, node_spec = node_type.to_iterable(tree)\n@@ -34,8 +45,22 @@ def tree_map(f, tree):\nelse:\nreturn f(tree)\n-\ndef 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+ # equivalent to prefix_multimap(f, tree_structure(tree), tree, *rest)\nnode_type = node_types.get(type(tree))\nif node_type:\nchildren, node_spec = node_type.to_iterable(tree)\n@@ -54,7 +79,6 @@ def tree_multimap(f, tree, *rest):\nelse:\nreturn f(tree, *rest)\n-\ndef prefix_multimap(f, treedef, tree, *rest):\n\"\"\"Like tree_multimap but only maps down through a tree prefix.\"\"\"\nif treedef is leaf:\n@@ -78,6 +102,28 @@ def prefix_multimap(f, treedef, tree, *rest):\nfor td, xs in zip(treedef.children, all_children)]\nreturn node_type.from_iterable(node_data, new_children)\n+def tree_mimomap(f, tree, *rest):\n+ \"\"\"Map a multi-input tuple-output over pytree args to form a tuple of pytrees.\n+\n+ Args:\n+ f: function that takes `1 + len(rest)` arguments and returns a tuple, to be\n+ applied at the 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 tuple of pytrees with length given by the length of the output of `f` and\n+ with each pytree element having the same structure as `tree`.\n+ \"\"\"\n+ flat, treedef = tree_flatten(tree)\n+ rest_flat, treedefs = unzip2(map(tree_flatten, rest))\n+ if not all(td == treedef for td in treedefs):\n+ td = next(td for td in treedefs if td != treedef)\n+ raise TypeError('Mismatch: {} != {}'.format(treedef, td))\n+ out_flat = zip(*map(f, flat, *rest_flat))\n+ return tuple(map(partial(tree_unflatten, treedef), out_flat))\n+\ndef tree_reduce(f, tree):\nflat, _ = tree_flatten(tree)\n" } ]
Python
Apache License 2.0
google/jax
back to original tree_mimomap optimizers solution
260,335
22.03.2019 07:38:40
25,200
50f52070fc2d1acb49ee60cc2ac18115ed9bff3d
comment-out new pytree check with a TODO
[ { "change_type": "MODIFY", "old_path": "jax/tree_util.py", "new_path": "jax/tree_util.py", "diff": "@@ -67,8 +67,9 @@ def tree_multimap(f, tree, *rest):\nall_children = [children]\nfor other_tree in rest:\nother_node_type = node_types.get(type(other_tree))\n- if node_type != other_node_type:\n- raise TypeError('Mismatch: {} != {}'.format(other_node_type, node_type))\n+ # TODO(mattjj): enable this check\n+ # if node_type != other_node_type:\n+ # raise TypeError('Mismatch: {} != {}'.format(other_node_type, node_type))\nother_children, other_node_data = node_type.to_iterable(other_tree)\nif other_node_data != node_spec:\nraise TypeError('Mismatch: {} != {}'.format(other_node_data, node_spec))\n" } ]
Python
Apache License 2.0
google/jax
comment-out new pytree check with a TODO
260,335
22.03.2019 16:55:15
25,200
629c573fd3babd46e2f2eb19942d69eeab6bf7b6
handle numpy < 1.14 behavior of isclose
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -667,12 +667,25 @@ def isclose(a, b, rtol=1e-05, atol=1e-08):\ndtype = _result_dtype(real, a)\nrtol = lax.convert_element_type(rtol, dtype)\natol = lax.convert_element_type(atol, dtype)\n- return lax.le(\n+ out = lax.le(\nlax.abs(lax.sub(a, b)),\nlax.add(atol, lax.mul(rtol, lax.abs(b))))\n+ return _maybe_numpy_1_13_isclose_behavior(a, out)\nelse:\nreturn lax.eq(a, b)\n+numpy_version = tuple(map(int, onp.version.version.split('.')))\n+if numpy_version < (1, 14):\n+ # see discussion at https://github.com/numpy/numpy/pull/9720\n+ def _maybe_numpy_1_13_isclose_behavior(a, out):\n+ if size(out) == 1 and issubdtype(_dtype(a), complexfloating):\n+ return lax.reshape(out, (1,))\n+ else:\n+ return out\n+else:\n+ def _maybe_numpy_1_13_isclose_behavior(a, out):\n+ return out\n+\n@_wraps(onp.where)\ndef where(condition, x=None, y=None):\n" } ]
Python
Apache License 2.0
google/jax
handle numpy < 1.14 behavior of isclose
260,335
22.03.2019 17:09:35
25,200
a2778b245c51fe0858219d2b6d6974bc1f942163
reconcile _CheckAgainstNumpy arg order common use
[ { "change_type": "MODIFY", "old_path": "jax/test_util.py", "new_path": "jax/test_util.py", "diff": "@@ -488,7 +488,7 @@ class JaxTestCase(parameterized.TestCase):\nself.assertAllClose(python_ans, compiled_ans, check_dtypes, rtol, atol)\n- def _CheckAgainstNumpy(self, lax_op, numpy_reference_op, args_maker,\n+ def _CheckAgainstNumpy(self, numpy_reference_op, lax_op, args_maker,\ncheck_dtypes=False, tol=1e-5):\nargs = args_maker()\nnumpy_ans = numpy_reference_op(*args)\n" } ]
Python
Apache License 2.0
google/jax
reconcile _CheckAgainstNumpy arg order common use
260,335
23.03.2019 14:08:15
25,200
c9f9676147c585be3ce3e5688e646c838c8a3e22
implement manual jarrett jvps
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -353,6 +353,7 @@ def hessian(fun, argnums=0):\ndef _std_basis(pytree):\nleaves, _ = tree_flatten(pytree)\nndim = sum(map(onp.size, leaves))\n+ # TODO(mattjj): use a symbolic identity matrix here\nreturn _unravel_array_into_pytree(pytree, 1, onp.eye(ndim))\ndef _unravel_array_into_pytree(pytree, axis, arr):\n@@ -734,3 +735,26 @@ def _primitive(fun):\ntraceable.primitive = fun_p\nreturn traceable\n+\n+\n+def _elementwise_std_basis(pytree):\n+ leaves, _ = tree_flatten(pytree)\n+ arity = len(leaves)\n+ dims = map(onp.size, leaves)\n+ # TODO(mattjj): use symbolic constants\n+ basis_array = onp.stack(\n+ [onp.concatenate([onp.ones(dims[j]) if i == j else onp.zeros(dims[j])\n+ for j in range(arity)]) for i in range(arity)])\n+ return _unravel_array_into_pytree(pytree, 1, basis_array)\n+\n+def jarrett(fun):\n+ new_fun = _primitive(fun)\n+\n+ def elementwise_jvp(primals, tangents):\n+ pushfwd = partial(jvp, fun, primals)\n+ y, jacs = vmap(pushfwd, out_axes=(None, 0))(_elementwise_std_basis(tangents))\n+ out_tangent = sum([tangent * jac for tangent, jac in zip(tangents, jacs)])\n+ return y, out_tangent\n+\n+ ad.primitive_jvps[new_fun.primitive] = elementwise_jvp\n+ return new_fun\n" }, { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -1707,7 +1707,7 @@ xor_p = standard_binop([_any, _any], 'xor')\nad.defjvp_zero(xor_p)\ndef _add_transpose(t, x, y):\n- assert x is None and y is None # computation must be linear, not affine\n+ # assert x is None and y is None # computation must be linear, not affine\nreturn [t, t]\nadd_p = standard_binop([_num, _num], 'add')\n" } ]
Python
Apache License 2.0
google/jax
implement manual jarrett jvps
260,335
23.03.2019 14:58:00
25,200
122c2df261e8b84d77061711e6f044c33ca73759
handle pytrees in jarrett tangents
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -753,7 +753,8 @@ def jarrett(fun):\ndef elementwise_jvp(primals, tangents):\npushfwd = partial(jvp, fun, primals)\ny, jacs = vmap(pushfwd, out_axes=(None, 0))(_elementwise_std_basis(tangents))\n- out_tangent = sum([tangent * jac for tangent, jac in zip(tangents, jacs)])\n+ flat_tangents, _ = tree_flatten(tangents)\n+ out_tangent = sum([t * jac for t, jac in zip(flat_tangents, jacs)])\nreturn y, out_tangent\nad.primitive_jvps[new_fun.primitive] = elementwise_jvp\n" } ]
Python
Apache License 2.0
google/jax
handle pytrees in jarrett tangents
260,335
23.03.2019 15:11:21
25,200
87143d8e0a0cba8b237c311929aa43697ce64f20
add some simple tests for jarrett jvps
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -717,7 +717,7 @@ def _check_scalar(x):\nraise TypeError(msg(x))\n-def _primitive(fun):\n+def custom_transforms(fun):\nname = getattr(fun, '__name__', '<unnamed user primitive>')\nfun_p = core.Primitive(name)\nfun_p.def_impl(fun)\n@@ -748,7 +748,7 @@ def _elementwise_std_basis(pytree):\nreturn _unravel_array_into_pytree(pytree, 1, basis_array)\ndef jarrett(fun):\n- new_fun = _primitive(fun)\n+ new_fun = custom_transforms(fun)\ndef elementwise_jvp(primals, tangents):\npushfwd = partial(jvp, fun, primals)\n@@ -756,6 +756,6 @@ def jarrett(fun):\nflat_tangents, _ = tree_flatten(tangents)\nout_tangent = sum([t * jac for t, jac in zip(flat_tangents, jacs)])\nreturn y, out_tangent\n-\nad.primitive_jvps[new_fun.primitive] = elementwise_jvp\n+\nreturn new_fun\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -376,6 +376,37 @@ class APITest(jtu.JaxTestCase):\nself.assertEqual(g, grad(lambda x: x**3)(4.))\nself.assertEqual(aux, [4.**2, 4.])\n+ def test_jarrett_jvps(self):\n+ def f1(x):\n+ return np.sin(np.sin(np.sin(x)))\n+ f2 = api.jarrett(f1)\n+\n+ for x in [3., onp.array([2., 3., 4.])]:\n+ self.assertAllClose(f1(x), f2(x), check_dtypes=True)\n+\n+ _, f1_vjp = api.vjp(f1, x)\n+ _, f2_vjp = api.vjp(f2, x)\n+ self.assertAllClose(f1_vjp(x), f2_vjp(x), check_dtypes=True)\n+\n+ jaxpr2 = api.make_jaxpr(f2_vjp)(x)\n+ assert len(jaxpr2.constvars) == 1\n+\n+ def test_jarrett_jvps2(self):\n+ def f1(x, y):\n+ return np.sin(x) * np.cos(y) * np.sin(x) * np.cos(y)\n+ f2 = api.jarrett(f1)\n+\n+ # TODO(mattjj): doesn't work for (3., onp.array([4., 5.]))\n+ for x, y in [(3., 4.), (onp.array([5., 6.]), onp.array([7., 8.]))]:\n+ self.assertAllClose(f1(x, y), f2(x, y), check_dtypes=True)\n+\n+ _, f1_vjp = api.vjp(f1, x, y)\n+ _, f2_vjp = api.vjp(f2, x, y)\n+ self.assertAllClose(f1_vjp(y), f2_vjp(y), check_dtypes=True)\n+\n+ jaxpr2 = api.make_jaxpr(f2_vjp)(y)\n+ assert len(jaxpr2.constvars) == 2\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
add some simple tests for jarrett jvps
260,335
23.03.2019 17:10:01
25,200
b041435f29a205329118a31d830920c63402fb6d
fix scalar broadcast bug in safe_mul translation
[ { "change_type": "MODIFY", "old_path": "jax/lax.py", "new_path": "jax/lax.py", "diff": "@@ -1732,8 +1732,8 @@ ad.defbilinear_broadcasting(_brcast, mul_p, mul, mul) # TODO\ndef _safe_mul_translation_rule(c, x, y):\ndtype = c.GetShape(x).numpy_dtype()\nzero = c.Constant(onp.array(0, dtype=dtype))\n- out_shape = tuple(onp.maximum(c.GetShape(x).dimensions(),\n- c.GetShape(y).dimensions()))\n+ out_shape = broadcast_shapes(c.GetShape(x).dimensions(),\n+ c.GetShape(y).dimensions())\nreturn c.Select(c.Or(c.Eq(x, zero), c.Eq(y, zero)),\nc.Broadcast(zero, out_shape),\nc.Mul(x, y))\n" } ]
Python
Apache License 2.0
google/jax
fix scalar broadcast bug in safe_mul translation
260,335
24.03.2019 07:59:50
25,200
a848d0c0fecbeff685a03a256de52a70736cd24c
update readme, link gotchas notebook
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -33,7 +33,8 @@ are instances of such transformations. Another is [`vmap`](#auto-vectorization-w\nfor automatic vectorization, with more to come.\nThis is a research project, not an official Google product. Expect bugs and\n-sharp edges. Please help by trying it out, [reporting\n+[sharp edges](https://github.com/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb).\n+Please help by trying it out, [reporting\nbugs](https://github.com/google/jax/issues), and letting us know what you\nthink!\n@@ -78,13 +79,16 @@ open](https://github.com/google/jax) by a growing number of\n* [Current gotchas](#current-gotchas)\n## Quickstart: Colab in the Cloud\n-Jump right in using a notebook in your browser, connected to a Google Cloud GPU:\n+Jump right in using a notebook in your browser, connected to a Google Cloud GPU. Here are some starter notebooks:\n- [The basics: NumPy on accelerators, `grad` for differentiation, `jit` for compilation, and `vmap` for vectorization](https://colab.research.google.com/github/google/jax/blob/master/notebooks/quickstart.ipynb)\n- [Training a Simple Neural Network, with PyTorch Data Loading](https://colab.research.google.com/github/google/jax/blob/master/notebooks/neural_network_and_data_loading.ipynb)\n- [Training a Simple Neural Network, with TensorFlow Dataset Data Loading](https://colab.research.google.com/github/google/jax/blob/master/notebooks/neural_network_with_tfds_data.ipynb)\n-- [The Autodiff Cookbook: easy and powerful automatic differentiation in JAX](https://colab.research.google.com/github/google/jax/blob/master/notebooks/autodiff_cookbook.ipynb)\n-- [MAML Tutorial with JAX](https://colab.research.google.com/github/google/jax/blob/autodiff-cookbook/notebooks/maml.ipynb).\n+\n+And for a deeper dive into JAX:\n+- [Common gotchas and sharp edges](https://github.com/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb)\n+- [The Autodiff Cookbook, Part 1: easy and powerful automatic differentiation in JAX](https://colab.research.google.com/github/google/jax/blob/master/notebooks/autodiff_cookbook.ipynb)\n- [Directly using XLA in Python](https://colab.research.google.com/github/google/jax/blob/autodiff-cookbook/notebooks/XLA_in_Python.ipynb)\n+- [MAML Tutorial with JAX](https://colab.research.google.com/github/google/jax/blob/autodiff-cookbook/notebooks/maml.ipynb).\n## Installation\nJAX is written in pure Python, but it depends on XLA, which needs to be\n@@ -708,15 +712,17 @@ code to compile and end-to-end optimize much bigger functions.\n## Current gotchas\n-Some things we don't handle that might surprise NumPy users:\n-1. No in-place mutation syntax. JAX requires functional code. You can use\n- lax.dynamic\\_update\\_slice for slice updating that, under `@jit`, will be\n- optimized to in-place buffer updating.\n-2. PRNGs can be awkward, and linearity is not checked with a warning.\n+For a survey of current gotchas, with examples and explanations, we highly recommend reading the [Gotchas Notebook](https://github.com/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb).\n+\n+Two stand-out gotchas that might surprise NumPy users:\n+1. In-place mutation of arrays isn't supported. Generally JAX requires functional code.\n+2. PRNGs can be awkward, and non-reuse (linearity) is not checked.\n+\n+See [the notebook](https://github.com/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb) for much more information.\n## Contributors\n-So far, JAX includes lots of help and contributions from\n+So far, JAX includes lots of help and [contributions](https://github.com/google/jax/graphs/contributors). In addition to the code contributions reflected on GitHub, JAX has benefitted substantially from the advice of\n[Jamie Townsend](https://github.com/j-towns),\n[Peter Hawkins](https://github.com/hawkinsp),\n[Jonathan Ragan-Kelley](https://people.eecs.berkeley.edu/~jrk/),\n" } ]
Python
Apache License 2.0
google/jax
update readme, link gotchas notebook
260,335
24.03.2019 08:50:56
25,200
cefbea6a4220d0d1c074f1ed70b12808827fac3f
README should point to hosted colab for gotchas
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -33,7 +33,7 @@ are instances of such transformations. Another is [`vmap`](#auto-vectorization-w\nfor automatic vectorization, with more to come.\nThis is a research project, not an official Google product. Expect bugs and\n-[sharp edges](https://github.com/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb).\n+[sharp edges](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb).\nPlease help by trying it out, [reporting\nbugs](https://github.com/google/jax/issues), and letting us know what you\nthink!\n@@ -85,7 +85,7 @@ Jump right in using a notebook in your browser, connected to a Google Cloud GPU.\n- [Training a Simple Neural Network, with TensorFlow Dataset Data Loading](https://colab.research.google.com/github/google/jax/blob/master/notebooks/neural_network_with_tfds_data.ipynb)\nAnd for a deeper dive into JAX:\n-- [Common gotchas and sharp edges](https://github.com/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb)\n+- [Common gotchas and sharp edges](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb)\n- [The Autodiff Cookbook, Part 1: easy and powerful automatic differentiation in JAX](https://colab.research.google.com/github/google/jax/blob/master/notebooks/autodiff_cookbook.ipynb)\n- [Directly using XLA in Python](https://colab.research.google.com/github/google/jax/blob/autodiff-cookbook/notebooks/XLA_in_Python.ipynb)\n- [MAML Tutorial with JAX](https://colab.research.google.com/github/google/jax/blob/autodiff-cookbook/notebooks/maml.ipynb).\n@@ -712,13 +712,13 @@ code to compile and end-to-end optimize much bigger functions.\n## Current gotchas\n-For a survey of current gotchas, with examples and explanations, we highly recommend reading the [Gotchas Notebook](https://github.com/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb).\n+For a survey of current gotchas, with examples and explanations, we highly recommend reading the [Gotchas Notebook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb).\nTwo stand-out gotchas that might surprise NumPy users:\n1. In-place mutation of arrays isn't supported. Generally JAX requires functional code.\n2. PRNGs can be awkward, and non-reuse (linearity) is not checked.\n-See [the notebook](https://github.com/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb) for much more information.\n+See [the notebook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb) for much more information.\n## Contributors\n" } ]
Python
Apache License 2.0
google/jax
README should point to hosted colab for gotchas
260,335
25.03.2019 10:37:24
25,200
a169e534a81e90ac44b8e26d7721208ff22339b3
add docstring for `jax.linearize` (fixes
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -523,10 +523,50 @@ def jvp(fun, primals, tangents):\nout_primal, out_tangent = ad.jvp(jaxtree_fun).call_wrapped(ps_flat, ts_flat)\nreturn (build_tree(out_tree(), out_primal), build_tree(out_tree(), out_tangent))\n-def linearize(traceable, *primals):\n- fun = lu.wrap_init(traceable)\n+def linearize(fun, *primals):\n+ \"\"\"Produce a linear approximation to `fun` using `jvp` and partial evaluation.\n+\n+ Args:\n+ fun: Function to be differentiated. Its arguments should be arrays, scalars,\n+ or standard Python containers of arrays or scalars. It should return an\n+ array, scalar, or standard python container of arrays or scalars.\n+ primals: The primal values at which the Jacobian of `fun` should be\n+ evaluated. Should be a tuple of arrays, scalar, or standard Python\n+ container thereof. The length of the tuple is equal to the number of\n+ positional parameters of `fun`.\n+\n+ Returns:\n+ A pair where the first element is the value of `f(*primals)` and the second\n+ element is a function that evaluates the (forward-mode) Jacobian-vector\n+ product of `fun` evaluated at `primals` without re-doing the linearization\n+ work.\n+\n+ In terms of values computed, `linearize` behaves much like a curried `jvp`::\n+ y, out_tangent = jax.jvp(f, (x,), (in_tangent,))\n+\n+ y, f_jvp = jax.linearize(f, x)\n+ out_tangent = f_jvp(in_tangent)\n+\n+ However, the difference is that `linearize` uses partial evaluation so that\n+ the function `f` is not re-linearized on calls to `f_jvp`. In general that\n+ means the memory usage scales with the size of the computation, much like in\n+ reverse-mode. (Indeed, `linearize` has a similar signature to `vjp`!)\n+\n+ Here's a more complete example:\n+\n+ >>> def f(x): return 3. * np.sin(x) + np.cos(x / 2.)\n+ ...\n+ >>> jax.jvp(f, (2.,), (3.,))\n+ (array(3.2681944, dtype=float32), array(-5.007528, dtype=float32))\n+ >>> y, f_jvp = jax.linearize(f, 2.)\n+ >>> y\n+ array(3.2681944, dtype=float32)\n+ >>> f_jvp(3.)\n+ array(-5.007528, dtype=float32)\n+ \"\"\"\n+ f = lu.wrap_init(fun)\nprimals_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, primals))\n- jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(fun, in_trees)\n+ jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(f, in_trees)\nout_primal, out_pval, jaxpr, consts = ad.linearize(jaxtree_fun, *primals_flat)\nout_tree = out_tree()\nout_primal_py = build_tree(out_tree, out_primal)\n" } ]
Python
Apache License 2.0
google/jax
add docstring for `jax.linearize` (fixes #526)
260,335
25.03.2019 11:03:03
25,200
54ac87957c86d0fb4800c4236ee569a2e4e5c885
add clarification about linearize vs jvp+vmap
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -552,7 +552,17 @@ def linearize(fun, *primals):\nmeans the memory usage scales with the size of the computation, much like in\nreverse-mode. (Indeed, `linearize` has a similar signature to `vjp`!)\n- Here's a more complete example:\n+ This function is mainly useful if you want to apply `f_jvp` multiple times,\n+ i.e. to evaluate a pushforward for many different input tangent vectors at the\n+ same linearization point. Moreover if all the input tangent vectors are known\n+ at once, it can be more efficient to vectorize using `vmap`, as in::\n+ pushfwd = partial(jvp, f, (x,))\n+ y, out_tangents = vmap(pushfwd, out_axes=(None, 0))((in_tangents,))\n+ By using `vmap` and `jvp` together like this we avoid the stored-linearization\n+ memory cost that scales with the depth of the computation, which is incurred\n+ by both `linearize` and `vjp`.\n+\n+ Here's a more complete example of using `linearize`:\n>>> def f(x): return 3. * np.sin(x) + np.cos(x / 2.)\n...\n@@ -563,6 +573,8 @@ def linearize(fun, *primals):\narray(3.2681944, dtype=float32)\n>>> f_jvp(3.)\narray(-5.007528, dtype=float32)\n+ >>> f_jvp(4.)\n+ array(-5.007528, dtype=float32)\n\"\"\"\nf = lu.wrap_init(fun)\nprimals_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, primals))\n" } ]
Python
Apache License 2.0
google/jax
add clarification about linearize vs jvp+vmap
260,335
25.03.2019 11:27:29
25,200
f5b4391f38edec765551aa0f67a670dae95fc5d3
add jax.linearize to jax.readthedocs.io
[ { "change_type": "MODIFY", "old_path": "docs/jax.rst", "new_path": "docs/jax.rst", "diff": "@@ -18,6 +18,6 @@ Module contents\n---------------\n.. automodule:: jax\n- :members: jit, disable_jit, grad, value_and_grad, vmap, jacfwd, jacrev, hessian, jvp, vjp, make_jaxpr\n+ :members: jit, disable_jit, grad, value_and_grad, vmap, jacfwd, jacrev, hessian, jvp, linearize, vjp, make_jaxpr\n:undoc-members:\n:show-inheritance:\n" } ]
Python
Apache License 2.0
google/jax
add jax.linearize to jax.readthedocs.io
260,335
25.03.2019 11:29:44
25,200
5704624cf9647091cf431408e0b7a60270c3a3b7
attempt to fix readtheddocs.io formatting
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -541,7 +541,8 @@ def linearize(fun, *primals):\nproduct of `fun` evaluated at `primals` without re-doing the linearization\nwork.\n- In terms of values computed, `linearize` behaves much like a curried `jvp`::\n+ In terms of values computed, `linearize` behaves much like a curried `jvp`,\n+ where these two code blocks compute the same values::\ny, out_tangent = jax.jvp(f, (x,), (in_tangent,))\ny, f_jvp = jax.linearize(f, x)\n" } ]
Python
Apache License 2.0
google/jax
attempt to fix readtheddocs.io formatting
260,335
25.03.2019 11:31:44
25,200
850e8a756a78388605745d241a7f25daa371a23b
fix typo in linearize docstring
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -575,7 +575,7 @@ def linearize(fun, *primals):\n>>> f_jvp(3.)\narray(-5.007528, dtype=float32)\n>>> f_jvp(4.)\n- array(-5.007528, dtype=float32)\n+ array(-6.676704, dtype=float32)\n\"\"\"\nf = lu.wrap_init(fun)\nprimals_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, primals))\n" } ]
Python
Apache License 2.0
google/jax
fix typo in linearize docstring
260,609
25.03.2019 17:42:08
18,000
48934dc9d1ebd884781a13cb783d7db97acfa37e
Implement cross product and test cases
[ { "change_type": "MODIFY", "old_path": "docs/jax.numpy.rst", "new_path": "docs/jax.numpy.rst", "diff": "@@ -56,6 +56,7 @@ jax.numpy package\ncos\ncosh\ncount_nonzero\n+ cross\ncumsum\ncumprod\ncumproduct\n" }, { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -1687,6 +1687,48 @@ def outer(a, b, out=None):\nraise NotImplementedError(\"The 'out' argument to outer is not supported.\")\nreturn ravel(a)[:, None] * ravel(b)\n+@_wraps(onp.cross)\n+def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):\n+ if axis is not None:\n+ axisa = axis\n+ axisb = axis\n+ axisc = axis\n+\n+ a_ndims = len(shape(a))\n+ b_ndims = len(shape(b))\n+ axisa = _canonicalize_axis(axisa, a_ndims)\n+ axisb = _canonicalize_axis(axisb, b_ndims)\n+ a = moveaxis(a, axisa, -1)\n+ b = moveaxis(b, axisb, -1)\n+ a_shape = shape(a)\n+ b_shape = shape(b)\n+\n+ if a_shape[-1] not in (2, 3) or b_shape[-1] not in (2, 3):\n+ raise ValueError(\"Dimension must be either 2 or 3 for cross product\")\n+\n+ if a_shape[-1] == 2 and b_shape[-1] == 2:\n+ return a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]\n+\n+ if a_shape[-1] == 2:\n+ a = concatenate((a, zeros(a_shape[:-1])[..., None]), axis=-1)\n+ elif b_shape[-1] == 2:\n+ b = concatenate((b, zeros(b_shape[:-1])[..., None]), axis=-1)\n+\n+ a0 = a[..., 0]\n+ a1 = a[..., 1]\n+ a2 = a[..., 2]\n+ b0 = b[..., 0]\n+ b1 = b[..., 1]\n+ b2 = b[..., 2]\n+\n+ c = array([a1 * b2 - a2 * b1,\n+ a2 * b0 - a0 * b2,\n+ a0 * b1 - a1 * b0])\n+\n+ c_ndims = len(shape(c))\n+ axisc = _canonicalize_axis(axisc, c_ndims)\n+\n+ return moveaxis(c, 0, axisc)\n@_wraps(onp.kron)\ndef kron(a, b):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -404,6 +404,36 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(onp_fun, lnp_fun, args_maker, check_dtypes=True)\nself._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_{}_{}\".format(\n+ jtu.format_shape_dtype_string(lhs_shape, lhs_dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, rhs_dtype),\n+ axes),\n+ \"lhs_shape\": lhs_shape, \"lhs_dtype\": lhs_dtype,\n+ \"rhs_shape\": rhs_shape, \"rhs_dtype\": rhs_dtype,\n+ \"axes\": axes, \"rng\": rng}\n+ for rng in [jtu.rand_default()]\n+ for lhs_shape, rhs_shape, axes in [\n+ [(2,), (2,), (-1, -1, -1, None)], # scalar output\n+ [(2, 4), (2, 4), (-1, -1, -1, 0)], # 2D vectors\n+ [(3, 4), (3, 4), (-1, -1, -1, 0)], # 3D vectors\n+ [(3, 4), (3, 6, 5, 4), (-1, -1, -1, 0)], # broadcasting\n+ [(4, 3), (3, 6, 5, 4), (1, 0, -1, None)], # different axes\n+ [(6, 1, 3), (5, 3), (-1, -1, -1, None)], # more broadcasting\n+ [(6, 1, 2), (5, 3), (-1, -1, -1, None)], # mixed 2D and 3D vectors\n+ [(10, 5, 2, 8), (1, 5, 1, 3), (-2, -1, -3, None)], # axes/broadcasting\n+ [(4, 5, 2), (4, 5, 2), (-1, -1, 0, None)], # axisc should do nothing\n+ [(4, 5, 2), (4, 5, 2), (-1, -1, -1, None)] # same as before\n+ ]\n+ for lhs_dtype, rhs_dtype in CombosWithReplacement(number_dtypes, 2)))\n+ def testCross(self, lhs_shape, lhs_dtype, rhs_shape, rhs_dtype, axes, rng):\n+ args_maker = lambda: [rng(lhs_shape, lhs_dtype), rng(rhs_shape, rhs_dtype)]\n+ axisa, axisb, axisc, axis = axes\n+ lnp_fun = lambda a, b: lnp.cross(a, b, axisa, axisb, axisc, axis)\n+ onp_fun = lambda a, b: onp.cross(a, b, axisa, axisb, axisc, axis)\n+ self._CheckAgainstNumpy(onp_fun, lnp_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_{}_{}\".format(\nname,\n" } ]
Python
Apache License 2.0
google/jax
Implement cross product and test cases
260,609
25.03.2019 19:29:49
18,000
0a5a633d2027d86e09f6e6b29bbe4890cc425a02
Fix dtypes in cross product
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -1710,9 +1710,9 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):\nreturn a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]\nif a_shape[-1] == 2:\n- a = concatenate((a, zeros(a_shape[:-1])[..., None]), axis=-1)\n+ a = concatenate((a, zeros(a_shape[:-1] + (1,), dtype=a.dtype)), axis=-1)\nelif b_shape[-1] == 2:\n- b = concatenate((b, zeros(b_shape[:-1])[..., None]), axis=-1)\n+ b = concatenate((b, zeros(b_shape[:-1] + (1,), dtype=b.dtype)), axis=-1)\na0 = a[..., 0]\na1 = a[..., 1]\n" } ]
Python
Apache License 2.0
google/jax
Fix dtypes in cross product
260,609
25.03.2019 20:28:21
18,000
2b7d2df79824074af2ea42dd211aae9b385b4cfe
Comment out test case (need to change tolerance)
[ { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -68,7 +68,8 @@ JAX_SPECIAL_FUNCTION_RECORDS = [\nop_record(\"gammaln\", 1, float_dtypes, jtu.rand_positive(), False),\n# TODO: NaNs in gradient for logit.\nop_record(\"logit\", 1, float_dtypes, jtu.rand_small_positive(), False),\n- op_record(\"log_ndtr\", 1, float_dtypes, jtu.rand_default(), True),\n+ # TODO(mattjj): loosen tolerance on this test\n+ #op_record(\"log_ndtr\", 1, float_dtypes, jtu.rand_default(), True),\nop_record(\"ndtri\", 1, float_dtypes, jtu.rand_uniform(0., 1.), True),\nop_record(\"ndtr\", 1, float_dtypes, jtu.rand_default(), True),\n]\n" } ]
Python
Apache License 2.0
google/jax
Comment out test case (need to change tolerance)
260,335
26.03.2019 08:35:34
25,200
25479c3518a5bf3a2f02f02c85ca2c05ddee383b
fix pmap performance bug, dont always copy to host
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -28,7 +28,7 @@ from .. import ad_util\nfrom .. import tree_util\nfrom .. import linear_util as lu\nfrom ..abstract_arrays import ConcreteArray, ShapedArray\n-from ..util import partial, unzip2, concatenate, safe_map, prod\n+from ..util import partial, unzip2, concatenate, safe_map, prod, memoize_unary\nfrom ..lib import xla_bridge as xb\nfrom .xla import (xla_shape, xla_destructure, translation_rule,\nxla_shape_to_result_shape, jaxpr_computation)\n@@ -63,9 +63,9 @@ def shard_arg(device_ordinals, arg):\nif type(arg) is ShardedDeviceArray and nrep == len(arg.device_buffers):\n# TODO(mattjj, phawkins): improve re-distribution not to copy to host\n_, ids = onp.unique(assignments, return_index=True)\n- shards = [arg.device_buffers[i].to_py() for i in ids] # TODO(mattjj): lazy\n+ get_shard = memoize_unary(lambda i: arg.device_buffers[i].to_py())\nreturn [buf if buf.device() == device_ordinals[r]\n- else xla.device_put(shards[i], device_ordinals[r])\n+ else xla.device_put(get_shard(i), device_ordinals[r])\nfor r, (i, buf) in enumerate(zip(assignments, arg.device_buffers))]\nelse:\nshards = [arg[i] for i in range(arg.shape[0])]\n" }, { "change_type": "MODIFY", "old_path": "jax/util.py", "new_path": "jax/util.py", "diff": "@@ -176,6 +176,14 @@ def memoize(fun, max_size=4096):\nreturn memoized_fun\n+def memoize_unary(func):\n+ class memodict(dict):\n+ def __missing__(self, key):\n+ val = self[key] = func(key)\n+ return val\n+ return memodict().__getitem__\n+\n+\ndef prod(xs):\nreturn functools.reduce(mul, xs, 1)\n" } ]
Python
Apache License 2.0
google/jax
fix pmap performance bug, dont always copy to host
260,335
26.03.2019 08:43:02
25,200
482c1ce8b8198a8c1bc315ec7f083e1fd49a874f
change scipy.special.log_ndtr test rng for numerics
[ { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -68,8 +68,7 @@ JAX_SPECIAL_FUNCTION_RECORDS = [\nop_record(\"gammaln\", 1, float_dtypes, jtu.rand_positive(), False),\n# TODO: NaNs in gradient for logit.\nop_record(\"logit\", 1, float_dtypes, jtu.rand_small_positive(), False),\n- # TODO(mattjj): loosen tolerance on this test\n- #op_record(\"log_ndtr\", 1, float_dtypes, jtu.rand_default(), True),\n+ op_record(\"log_ndtr\", 1, float_dtypes, jtu.rand_small(), True),\nop_record(\"ndtri\", 1, float_dtypes, jtu.rand_uniform(0., 1.), True),\nop_record(\"ndtr\", 1, float_dtypes, jtu.rand_default(), True),\n]\n" } ]
Python
Apache License 2.0
google/jax
change scipy.special.log_ndtr test rng for numerics
260,474
26.03.2019 15:35:31
14,400
273a9a858a1b05075ad47409aee072675e924c77
Scan impl and broken jvp
[ { "change_type": "ADD", "old_path": null, "new_path": "jax/scan.py", "diff": "+# Copyright 2018 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+from functools import partial\n+\n+import jax.core as core\n+import jax.linear_util as lu\n+import jax.numpy as np\n+import jax.lax as lax\n+\n+from jax.lax import _abstractify\n+from jax.abstract_arrays import ShapedArray\n+from jax.interpreters import partial_eval as pe\n+from jax.interpreters import ad\n+\n+import jax.util as ju\n+\n+map = ju.safe_map\n+\n+# scan :: (a -> c -> c) -> c -> [a] -> [c]\n+# scan_cc :: (d ->a -> c -> c) -> d-> c -> [a] -> [c]\n+# pro: fewer types\n+# pro: all types are passed as args\n+\n+# scan :: (a -> c -> (b,c)) -> c -> [a] -> ([b],c)\n+# scan_cc :: (d -> a -> c -> (b,c)) -> d -> c -> [a] -> ([b],c)\n+# pro: fold and for_i are special cases without needing DCE\n+# pro: feels cleaner for transposition\n+# pro: accumulation without saving intermediates\n+\n+def scan_reference(f, init, xs):\n+ carry = init\n+ ys = []\n+ for x in xs:\n+ (y, carry) = f(x, carry)\n+ ys.append(y)\n+\n+ return ys, carry\n+\n+def demote_aval_rank(xs):\n+ if isinstance(xs, core.AbstractTuple):\n+ return core.AbstractTuple(map(demote_aval_rank, xs))\n+ else:\n+ return ShapedArray(xs.shape[1:], xs.dtype)\n+\n+def promote_aval_rank(n, xs):\n+ if isinstance(xs, core.AbstractTuple):\n+ return core.AbstractTuple(map(partial(promote_aval_rank, n), xs))\n+ else:\n+ return ShapedArray((n,) + xs.shape, xs.dtype)\n+\n+def leading_dim_size(xs):\n+ if isinstance(xs, core.AbstractTuple):\n+ return leading_dim_size(xs[0])\n+ else:\n+ return xs.shape[0]\n+\n+def empty_arrays(aval):\n+ if isinstance(aval, core.AbstractTuple):\n+ return core.pack(map(empty_arrays, aval))\n+ else:\n+ return lax.full(aval.shape, 0, aval.dtype)\n+\n+def index_arrays(i, aval, xs):\n+ if isinstance(aval, core.AbstractTuple):\n+ return core.pack(map(partial(index_arrays, i), aval, xs))\n+ else:\n+ return lax.dynamic_index_in_dim(xs, i, keepdims=False)\n+\n+def update_arrays(i, aval, xs, x):\n+ if isinstance(aval, core.AbstractTuple):\n+ return core.pack(map(partial(update_arrays, i), aval, xs, x))\n+ else:\n+ return lax.dynamic_update_index_in_dim(xs, x[None, ...], i, axis=0)\n+\n+# scan :: (a -> c -> (b,c)) -> c -> [a] -> ([b],c)\n+def scan(f, init, xs):\n+ consts, avals, jaxpr = trace_scan_fun(f, init, xs)\n+ return scan_p.bind(core.pack(consts), init, xs, avals=avals, jaxpr=jaxpr)\n+\n+def trace_scan_fun(f, init, xs):\n+ f = lu.wrap_init(f)\n+ carry_pval = carry_aval, _ = _abstractify(init)\n+ xs_aval, _ = _abstractify(xs)\n+ x_aval = demote_aval_rank(xs_aval)\n+ x_pval = pe.PartialVal((x_aval, core.unit))\n+ jaxpr, pval_out, consts = pe.trace_to_jaxpr(f, (x_pval, carry_pval))\n+ (y_aval, carry_aval_out), _ = pval_out\n+ assert carry_aval == carry_aval_out\n+ avals = (x_aval, y_aval, carry_aval)\n+ return consts, avals, jaxpr\n+\n+def _scan_impl(consts, init, xs, avals, jaxpr):\n+ length = leading_dim_size(xs)\n+ (x_aval, y_aval, carry_aval) = avals\n+ ys_aval = promote_aval_rank(length, y_aval)\n+\n+ def body_fun(i, vals):\n+ carry, ys = vals\n+ x = index_arrays(i, x_aval, xs)\n+ (y, carry_out) = core.eval_jaxpr(jaxpr, consts, (), x, carry)\n+ ys_out = update_arrays(i, y_aval, ys, y)\n+ return (carry_out, ys_out)\n+\n+ ys_init = empty_arrays(ys_aval)\n+ carry, out = lax.fori_loop(0, length, body_fun, (init, ys_init))\n+ return core.pack((out, carry))\n+\n+# scan :: (a -> c -> (b,c)) -> c -> [a] -> ([b],c)\n+def _scan_jvp(primals, tangents, avals, jaxpr):\n+ consts, init, xs = primals\n+ consts_dot, init_dot, xs_dot = tangents\n+ f = partial(core.eval_jaxpr, jaxpr)\n+\n+ consts_dot = ad.instantiate_zeros(consts, consts_dot)\n+ init_dot = ad.instantiate_zeros(init , init_dot)\n+ xs_dot = ad.instantiate_zeros(xs , xs_dot)\n+\n+ # consts_dual = core.pack((consts, consts_dot))\n+ init_dual = core.pack((init , init_dot))\n+ xs_dual = core.pack((xs , xs_dot))\n+\n+ # f_jvp :: (consts, init, xs) -> (consts_t, init_t, xs_t) -> ...\n+ f_jvp = ad.jvp(lu.wrap_init(f)).call_wrapped\n+\n+ def f_jvp_c(carry_dual, x_dual):\n+ init, init_dot = carry_dual\n+ x, x_dot = x_dual\n+ ans = f_jvp(core.pack((consts, init, x)),\n+ core.pack((consts_dot, init_dot, x_dot)))\n+ (y, carry_out), (y_dot, carry_out_dot) = ans\n+ return (core.pack((y, y_dot)),\n+ core.pack((carry_out, carry_out_dot)))\n+\n+\n+ consts, avals, jaxpr = trace_scan_fun(f_jvp_c, init_dual, xs_dual)\n+\n+\n+ # TODO: plumb symbolic zeros in and out of jvp transformation so we can test\n+ # that they're the same as the inputs and re-run if not\n+ return scan_p.bind(init, xs, core.pack(consts), avals=avals, jaxpr=jaxpr_jvp)\n+\n+\n+scan_p = core.Primitive(\"scan\")\n+scan_p.def_impl(_scan_impl)\n+ad.primitive_jvps[scan_p] = _scan_jvp\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/scan_test.py", "diff": "+from jax.scan import scan\n+from jax.core import pack\n+import jax.core as core\n+import jax.numpy as np\n+from jax import jvp\n+\n+# scan :: (a -> c -> (b,c)) -> c -> [a] -> ([b],c)\n+\n+def f(x, carry):\n+ carry = carry + np.sin(x)\n+ y = pack((carry**2, -carry))\n+ return pack((y, carry))\n+\n+x = np.array(np.arange(4), dtype=np.float64)\n+\n+[0, 1, 9, 36]\n+\n+ans = scan(f, 0.0, np.arange(4))\n+\n+def cumsum(xs):\n+ def f(x, carry):\n+ carry = carry + np.sin(x)\n+ return pack((carry, carry))\n+\n+ ys, _ = scan(f, 0.0, xs)\n+ return ys\n+\n+x = np.linspace(0, 3, 4)\n+\n+print x\n+print np.cumsum(x)\n+print cumsum(x)\n+\n+\n+print jvp(np.cumsum, (x,), (x*0.1,))\n+print jvp(cumsum, (x,), (x*0.1,))\n" } ]
Python
Apache License 2.0
google/jax
Scan impl and broken jvp
260,335
26.03.2019 13:50:27
25,200
8ad4f8c87234b794f87a267a6030a0feb8d56e80
plumbing fixes (or maybe more breaking!)
[ { "change_type": "MODIFY", "old_path": "jax/scan.py", "new_path": "jax/scan.py", "diff": "@@ -65,7 +65,7 @@ def promote_aval_rank(n, xs):\nreturn ShapedArray((n,) + xs.shape, xs.dtype)\ndef leading_dim_size(xs):\n- if isinstance(xs, core.AbstractTuple):\n+ if isinstance(xs, core.JaxTuple):\nreturn leading_dim_size(xs[0])\nelse:\nreturn xs.shape[0]\n@@ -131,29 +131,26 @@ def _scan_jvp(primals, tangents, avals, jaxpr):\ninit_dot = ad.instantiate_zeros(init , init_dot)\nxs_dot = ad.instantiate_zeros(xs , xs_dot)\n- # consts_dual = core.pack((consts, consts_dot))\n- init_dual = core.pack((init , init_dot))\n- xs_dual = core.pack((xs , xs_dot))\n-\n- # f_jvp :: (consts, init, xs) -> (consts_t, init_t, xs_t) -> ...\nf_jvp = ad.jvp(lu.wrap_init(f)).call_wrapped\ndef f_jvp_c(carry_dual, x_dual):\ninit, init_dot = carry_dual\nx, x_dot = x_dual\n- ans = f_jvp(core.pack((consts, init, x)),\n- core.pack((consts_dot, init_dot, x_dot)))\n+ ans = f_jvp(core.pack((consts, core.unit, init, x)),\n+ core.pack((consts_dot, core.unit, init_dot, x_dot)))\n(y, carry_out), (y_dot, carry_out_dot) = ans\n- return (core.pack((y, y_dot)),\n- core.pack((carry_out, carry_out_dot)))\n-\n-\n- consts, avals, jaxpr = trace_scan_fun(f_jvp_c, init_dual, xs_dual)\n+ return core.pack((core.pack((y, y_dot)),\n+ core.pack((carry_out, carry_out_dot))))\n+ consts_dual = core.pack((consts, consts_dot))\n+ init_dual = core.pack((init , init_dot))\n+ xs_dual = core.pack((xs , xs_dot))\n+ consts, avals, jvp_jaxpr = trace_scan_fun(f_jvp_c, init_dual, xs_dual)\n# TODO: plumb symbolic zeros in and out of jvp transformation so we can test\n# that they're the same as the inputs and re-run if not\n- return scan_p.bind(init, xs, core.pack(consts), avals=avals, jaxpr=jaxpr_jvp)\n+ return scan_p.bind(core.pack(consts), init_dual, xs_dual,\n+ avals=avals, jaxpr=jvp_jaxpr)\nscan_p = core.Primitive(\"scan\")\n" }, { "change_type": "MODIFY", "old_path": "tests/scan_test.py", "new_path": "tests/scan_test.py", "diff": "@@ -7,7 +7,7 @@ from jax import jvp\n# scan :: (a -> c -> (b,c)) -> c -> [a] -> ([b],c)\ndef f(x, carry):\n- carry = carry + np.sin(x)\n+ carry = carry + x\ny = pack((carry**2, -carry))\nreturn pack((y, carry))\n@@ -19,7 +19,7 @@ ans = scan(f, 0.0, np.arange(4))\ndef cumsum(xs):\ndef f(x, carry):\n- carry = carry + np.sin(x)\n+ carry = carry + x\nreturn pack((carry, carry))\nys, _ = scan(f, 0.0, xs)\n" } ]
Python
Apache License 2.0
google/jax
plumbing fixes (or maybe more breaking!)
260,403
27.03.2019 13:12:07
25,200
dad8157d7ce276ca97de4547e8493709e77977de
gotchas updates and README.md colab link fixes
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -87,8 +87,8 @@ Jump right in using a notebook in your browser, connected to a Google Cloud GPU.\nAnd for a deeper dive into JAX:\n- [Common gotchas and sharp edges](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb)\n- [The Autodiff Cookbook, Part 1: easy and powerful automatic differentiation in JAX](https://colab.research.google.com/github/google/jax/blob/master/notebooks/autodiff_cookbook.ipynb)\n-- [Directly using XLA in Python](https://colab.research.google.com/github/google/jax/blob/autodiff-cookbook/notebooks/XLA_in_Python.ipynb)\n-- [MAML Tutorial with JAX](https://colab.research.google.com/github/google/jax/blob/autodiff-cookbook/notebooks/maml.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## Installation\nJAX is written in pure Python, but it depends on XLA, which needs to be\n" } ]
Python
Apache License 2.0
google/jax
gotchas updates and README.md colab link fixes