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 | 20.05.2019 17:19:20 | 25,200 | dcb8584b07c953200c98f8a40584ec55b0b54fd1 | handle tensordot with zero contracting dims
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1585,6 +1585,11 @@ def tensordot(a, b, axes=2):\nraise TypeError(msg.format(ndim(a), ndim(b)))\nif type(axes) is int:\n+ if axes == 0:\n+ a, b = _promote_dtypes(a, b)\n+ return lax.mul(lax.reshape(a, shape(a) + (1,) * ndim(b)),\n+ lax.reshape(b, (1,) * ndim(a) + shape(b)))\n+ else:\na, b = _promote_dtypes(a, b)\na_reshape = lax.reshape(a, (_prod(a.shape[:-axes]), _prod(a.shape[-axes:])))\nb_reshape = lax.reshape(b, (_prod(b.shape[:axes]), _prod(b.shape[axes:])))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -539,6 +539,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n\"axes\": axes, \"rng\": rng}\nfor rng in [jtu.rand_default()]\nfor lhs_shape, rhs_shape, axes in [\n+ [(2, 3, 4), (5, 6, 7), 0], # from issue #740\n[(2, 3, 4), (3, 4, 5, 6), 2],\n[(2, 3, 4), (5, 4, 3, 6), [1, 2]],\n[(2, 3, 4), (5, 4, 3, 6), [[1, 2], [2, 1]]],\n"
}
] | Python | Apache License 2.0 | google/jax | handle tensordot with zero contracting dims
fixes #740 |
260,335 | 21.05.2019 07:08:13 | 25,200 | f3c1a5cafd1865df5de549b7a65ff54c788cb874 | improve scan error messages, add test (fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -464,9 +464,21 @@ def _promote_aval_rank(n, xs):\ndef _leading_dim_size(xs):\nif isinstance(xs, core.JaxTuple):\n- return _leading_dim_size(xs[0])\n+ sizes = set(map(_leading_dim_size, xs))\n+ if len(sizes) == 1:\n+ return sizes.pop()\n+ elif len(sizes) > 1:\n+ msg = \"scan got inconsistent leading axis sizes: {}\"\n+ raise ValueError(msg.format(sizes))\nelse:\n- return xs.shape[0]\n+ raise ValueError(\"scan found no leading axis to scan over\")\n+ else:\n+ shape = onp.shape(xs)\n+ if shape:\n+ return shape[0]\n+ else:\n+ msg = \"scan got value with no leading axis to scan over: {}\"\n+ raise ValueError(msg.format(xs))\ndef _empty_arrays(aval):\nassert isinstance(aval, core.AbstractValue)\n@@ -556,7 +568,7 @@ def scan(f, init, xs):\ncarry_aval_out, y_aval = pv_out\nif carry_aval != carry_aval_out:\nmsg = (\"scanned function carry output does not match carry input: \"\n- \"input carry is {} and output carry is {}\")\n+ \"input carry is {} and output carry is {}.\")\nraise TypeError(msg.format(carry_aval, carry_aval_out))\nlifted_jaxpr = pe._closure_convert_jaxpr(jaxpr)\nconsts_aval, _ = _abstractify(core.pack(consts))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -16,6 +16,7 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n+import collections\nfrom functools import partial\nfrom absl.testing import absltest\n@@ -623,6 +624,18 @@ class LaxControlFlowTest(jtu.JaxTestCase):\napi.grad(loss)(0.25) # doesn't crash\n+ def testIssue744(self):\n+ Point = collections.namedtuple('Point', ['x', 'y'])\n+ p0 = Point(x=np.array(1), y=np.array(2))\n+\n+ def plus_one(p, iter_idx):\n+ return Point(p.x+1, p.y+1), iter_idx\n+\n+ self.assertRaisesRegexp(\n+ ValueError,\n+ '.*no leading.*',\n+ lambda: lax.scan(plus_one, p0, list(range(5))))\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | improve scan error messages, add test (fixes #744) |
260,335 | 21.05.2019 11:18:44 | 25,200 | d01e6a96e2972752ad626a83dd5552744fcd43ea | improve scan error message test | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -633,7 +633,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertRaisesRegexp(\nValueError,\n- '.*no leading.*',\n+ 'scan got value with no leading axis to scan over.*',\nlambda: lax.scan(plus_one, p0, list(range(5))))\n"
}
] | Python | Apache License 2.0 | google/jax | improve scan error message test |
260,335 | 21.05.2019 13:54:37 | 25,200 | cf996730cedf3782443ad49f41e1eca5d20bcc0e | add test showing bug in scan higher-order autodiff | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -636,6 +636,17 @@ class LaxControlFlowTest(jtu.JaxTestCase):\n'scan got value with no leading axis to scan over.*',\nlambda: lax.scan(plus_one, p0, list(range(5))))\n+ def testScanHigherOrderDifferentiation(self):\n+ def f(c, a):\n+ b = np.sin(c * a)\n+ c = 0.9 * c\n+ return c, b\n+\n+ as_ = np.arange(3.).reshape((3, 1))\n+ c = 1.\n+\n+ jtu.check_grads(lambda c, as_: lax.scan(f, c, as_), (c, as_), order=2)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add test showing bug in scan higher-order autodiff |
260,335 | 21.05.2019 15:14:28 | 25,200 | 8c00df1d61d2fec72d7261c924432f5d131d076e | finer-grained passing and failing tests | [
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -152,20 +152,32 @@ def check_vjp(f, f_vjp, args, atol=ATOL, rtol=RTOL, eps=EPS):\ncheck_close(ip, ip_expected, atol=atol, rtol=rtol)\n-def check_grads(f, args, order, atol=None, rtol=None, eps=None):\n+def check_grads(f, args, order, modes=[\"fwd\", \"rev\"],\n+ atol=None, rtol=None, eps=None):\nargs = tuple(args)\nif order > 1:\n+ # TODO check this order before recursing\n+\n+ if \"fwd\" in modes:\n+ def f_jvp(*args):\n+ return api.jvp(f, args, args)\n+ check_grads(f_jvp, args, order - 1,\n+ modes=modes, atol=atol, rtol=rtol, eps=eps)\n+\n+ if \"rev\" in modes:\ndef f_vjp(*args):\nout_primal_py, vjp_py = api.vjp(f, *args)\nreturn vjp_py(out_primal_py)\n-\n- check_grads(f_vjp, args, order - 1, atol=atol, rtol=rtol, eps=eps)\n+ check_grads(f_vjp, args, order - 1,\n+ modes=modes, atol=atol, rtol=rtol, eps=eps)\nelse:\ndefault_tol = 1e-6 if FLAGS.jax_enable_x64 else 1e-2\natol = atol or default_tol\nrtol = rtol or default_tol\neps = eps or EPS\n+ if \"fwd\" in modes:\ncheck_jvp(f, partial(api.jvp, f), args, atol, rtol, eps)\n+ if \"rev\" in modes:\ncheck_vjp(f, partial(api.vjp, f), args, atol, rtol, eps)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -645,7 +645,13 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nas_ = np.arange(3.).reshape((3, 1))\nc = 1.\n- jtu.check_grads(lambda c, as_: lax.scan(f, c, as_), (c, as_), order=2)\n+ jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\"], order=2) # passes\n+ jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"rev\"], order=2) # passes\n+ jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\"], order=2) # passes\n+ jtu.check_grads(lambda c: lax.scan(f, c, as_)[0], (c,), modes=[\"rev\"], order=2) # passes\n+ # jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\", \"rev\"], order=2) # fails\n+ # jtu.check_grads(lambda c: lax.scan(f, c, as_)[1], (c,), modes=[\"rev\"], order=2) # fails\n+ # jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\", \"rev\"], order=2) # fails\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | finer-grained passing and failing tests |
260,335 | 21.05.2019 17:22:33 | 25,200 | 1ecf75770b770c02d560ae49e3bde4baa37c55cb | make check_grads check all orders <= given order | [
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -152,33 +152,32 @@ def check_vjp(f, f_vjp, args, atol=ATOL, rtol=RTOL, eps=EPS):\ncheck_close(ip, ip_expected, atol=atol, rtol=rtol)\n-def check_grads(f, args, order, modes=[\"fwd\", \"rev\"],\n- atol=None, rtol=None, eps=None):\n+def check_grads(f, args, order,\n+ modes=[\"fwd\", \"rev\"], atol=None, rtol=None, eps=None):\nargs = tuple(args)\n- if order > 1:\n- # TODO check this order before recursing\n+ default_tol = 1e-6 if FLAGS.jax_enable_x64 else 1e-2\n+ atol = atol or default_tol\n+ rtol = rtol or default_tol\n+ eps = eps or EPS\n+\n+ _check_jvp = partial(check_jvp, atol=atol, rtol=rtol, eps=eps)\n+ _check_vjp = partial(check_vjp, atol=atol, rtol=rtol, eps=eps)\n+ def _check_grads(f, args, order):\nif \"fwd\" in modes:\n- def f_jvp(*args):\n- return api.jvp(f, args, args)\n- check_grads(f_jvp, args, order - 1,\n- modes=modes, atol=atol, rtol=rtol, eps=eps)\n+ _check_jvp(f, partial(api.jvp, f), args)\n+ if order > 1:\n+ _check_grads(partial(api.jvp, f), (args, args), order - 1)\nif \"rev\" in modes:\n+ _check_vjp(f, partial(api.vjp, f), args)\n+ if order > 1:\ndef f_vjp(*args):\nout_primal_py, vjp_py = api.vjp(f, *args)\nreturn vjp_py(out_primal_py)\n- check_grads(f_vjp, args, order - 1,\n- modes=modes, atol=atol, rtol=rtol, eps=eps)\n- else:\n- default_tol = 1e-6 if FLAGS.jax_enable_x64 else 1e-2\n- atol = atol or default_tol\n- rtol = rtol or default_tol\n- eps = eps or EPS\n- if \"fwd\" in modes:\n- check_jvp(f, partial(api.jvp, f), args, atol, rtol, eps)\n- if \"rev\" in modes:\n- check_vjp(f, partial(api.vjp, f), args, atol, rtol, eps)\n+ _check_grads(f_vjp, args, order - 1)\n+\n+ _check_grads(f, args, order)\ndef skip_on_devices(*disabled_devices):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -645,13 +645,19 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nas_ = np.arange(3.).reshape((3, 1))\nc = 1.\n- jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\"], order=2) # passes\n- jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"rev\"], order=2) # passes\n- jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\"], order=2) # passes\n- jtu.check_grads(lambda c: lax.scan(f, c, as_)[0], (c,), modes=[\"rev\"], order=2) # passes\n- # jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\", \"rev\"], order=2) # fails\n- # jtu.check_grads(lambda c: lax.scan(f, c, as_)[1], (c,), modes=[\"rev\"], order=2) # fails\n- # jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\", \"rev\"], order=2) # fails\n+ # pass\n+ jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\"], order=2)\n+ jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\"], order=2)\n+ jtu.check_grads(lambda c: lax.scan(f, c, as_)[0], (c,), modes=[\"rev\"], order=2)\n+\n+ # fail w/ zero\n+ # jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"rev\"], order=2)\n+ # jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\", \"rev\"], order=1)\n+ # jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\", \"rev\"], order=2)\n+ # jtu.check_grads(lambda c: lax.scan(f, c, as_)[1], (c,), modes=[\"rev\"], order=2)\n+\n+ # fail w/ nonzero\n+ # jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\", \"rev\"], order=2)\nif __name__ == '__main__':\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1404,84 +1404,94 @@ class DeviceConstantTest(jtu.JaxTestCase):\nGradTestSpec = collections.namedtuple(\n- \"GradTestSpec\", [\"op\", \"nargs\", \"order\", \"rng\", \"dtypes\"])\n+ \"GradTestSpec\", [\"op\", \"nargs\", \"order\", \"rng\", \"dtypes\", \"name\"])\n+def grad_test_spec(op, nargs, order, rng, dtypes, name=None):\n+ return GradTestSpec(op, nargs, order, rng, dtypes, name or op.__name__)\nLAX_GRAD_OPS = [\n- GradTestSpec(lax.neg, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.neg, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.floor, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.floor, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64]),\n- GradTestSpec(lax.ceil, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.ceil, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64]),\n- GradTestSpec(lax.round, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.round, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64]),\n- # GradTestSpec(lax.rem, nargs=2, order=2, rng=jtu.rand_default(),\n+ # grad_test_spec(lax.rem, nargs=2, order=2, rng=jtu.rand_default(),\n# dtypes=[onp.float64]), # TODO(mattjj): enable\n- GradTestSpec(lax.exp, nargs=1, order=2, rng=jtu.rand_small(),\n+ grad_test_spec(lax.exp, nargs=1, order=2, rng=jtu.rand_small(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.expm1, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.expm1, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.log, nargs=1, order=2, rng=jtu.rand_positive(),\n+ grad_test_spec(lax.log, nargs=1, order=2, rng=jtu.rand_positive(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.log1p, nargs=1, order=2, rng=jtu.rand_positive(),\n+ grad_test_spec(lax.log1p, nargs=1, order=2, rng=jtu.rand_positive(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.tanh, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.tanh, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.sin, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.sin, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.cos, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.cos, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n# TODO(proteneer): atan2 input is already a representation of a\n# complex number. Need to think harder about what this even means\n# if each input itself is a complex number.\n- GradTestSpec(lax.atan2, nargs=2, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.atan2, nargs=2, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64]),\n- GradTestSpec(lax.erf, nargs=1, order=2, rng=jtu.rand_small(),\n+ grad_test_spec(lax.erf, nargs=1, order=2, rng=jtu.rand_small(),\ndtypes=[onp.float64]),\n- GradTestSpec(lax.erfc, nargs=1, order=2, rng=jtu.rand_small(),\n+ grad_test_spec(lax.erfc, nargs=1, order=2, rng=jtu.rand_small(),\ndtypes=[onp.float64]),\n- GradTestSpec(lax.erf_inv, nargs=1, order=2, rng=jtu.rand_small(),\n+ grad_test_spec(lax.erf_inv, nargs=1, order=2, rng=jtu.rand_small(),\ndtypes=[onp.float64]),\n- # GradTestSpec(lax.lgamma, nargs=1, order=2, rng=jtu.rand_small(),\n+ # grad_test_spec(lax.lgamma, nargs=1, order=2, rng=jtu.rand_small(),\n# dtypes=[onp.float64]), # TODO(mattjj): enable\n- GradTestSpec(lax.real, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.real, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.complex64]),\n- GradTestSpec(lax.imag, nargs=1, order=2, rng=jtu.rand_default(),\n- dtypes=[onp.complex64]),\n- # GradTestSpec(lax.complex, nargs=2, order=2, rng=jtu.rand_default(),\n+ # grad_test_spec(lax.imag, nargs=1, order=2, rng=jtu.rand_default(),\n+ # dtypes=[onp.complex64]), # TODO(mattjj): enable\n+ # grad_test_spec(lax.complex, nargs=2, order=2, rng=jtu.rand_default(),\n# dtypes=[onp.float32]), # TODO(mattjj): enable\n- GradTestSpec(lax.conj, nargs=1, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.conj, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float32, onp.complex64]),\n- GradTestSpec(lax.abs, nargs=1, order=2, rng=jtu.rand_positive(),\n+ grad_test_spec(lax.abs, nargs=1, order=2, rng=jtu.rand_positive(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.pow, nargs=2, order=2, rng=jtu.rand_positive(),\n+ grad_test_spec(lax.pow, nargs=2, order=2, rng=jtu.rand_positive(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.add, nargs=2, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.add, nargs=2, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.sub, nargs=2, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.sub, nargs=2, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.mul, nargs=2, order=2, rng=jtu.rand_default(),\n+ grad_test_spec(lax.mul, nargs=2, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.div, nargs=2, order=1, rng=jtu.rand_not_small(),\n+ grad_test_spec(lax.div, nargs=2, order=1, rng=jtu.rand_not_small(),\ndtypes=[onp.float64, onp.complex64]),\n- GradTestSpec(lax.max, nargs=2, order=2, rng=jtu.rand_some_equal(),\n+ grad_test_spec(lax.max, nargs=2, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64]),\n- GradTestSpec(lax.min, nargs=2, order=2, rng=jtu.rand_some_equal(),\n+ grad_test_spec(lax.min, nargs=2, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64]),\n+ # TODO(mattjj): make some-equal checks more robust, enable second-order\n+ # grad_test_spec(lax.max, nargs=2, order=1, rng=jtu.rand_some_equal(),\n+ # dtypes=[onp.float64], name=\"MaxSomeEqual\"),\n+ # grad_test_spec(lax.min, nargs=2, order=1, rng=jtu.rand_some_equal(),\n+ # dtypes=[onp.float64], name=\"MinSomeEqual\"),\n]\n-def check_grads_bilinear(f, args, order, atol=None, rtol=None):\n+def check_grads_bilinear(f, args, order,\n+ modes=[\"fwd\", \"rev\"], atol=None, rtol=None):\n# Can use large eps to make up for numerical inaccuracies since the op is\n# bilinear (relying on the fact that we only check one arg at a time)\nlhs, rhs = args\n- check_grads(lambda lhs: f(lhs, rhs), (lhs,), order, atol, rtol, eps=1.)\n- check_grads(lambda rhs: f(lhs, rhs), (rhs,), order, atol, rtol, eps=1.)\n+ check_grads(lambda lhs: f(lhs, rhs), (lhs,), order,\n+ modes=modes, atol=atol, rtol=rtol, eps=1.)\n+ check_grads(lambda rhs: f(lhs, rhs), (rhs,), order,\n+ modes=modes, atol=atol, rtol=rtol, eps=1.)\nclass LaxAutodiffTest(jtu.JaxTestCase):\n@@ -1489,7 +1499,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n@parameterized.named_parameters(itertools.chain.from_iterable(\njtu.cases_from_list(\n{\"testcase_name\": jtu.format_test_name_suffix(\n- rec.op.__name__, shapes, itertools.repeat(dtype)),\n+ rec.name, shapes, itertools.repeat(dtype)),\n\"op\": rec.op, \"rng\": rec.rng, \"shapes\": shapes, \"dtype\": dtype,\n\"order\": rec.order}\nfor shape_group in compatible_shapes\n@@ -1502,7 +1512,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nraise 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)\n- check_grads(op, args, order, tol, tol)\n+ check_grads(op, args, order, [\"fwd\", \"rev\"], tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_from_dtype={}_to_dtype={}\".format(\n@@ -1514,8 +1524,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ndef testConvertElementTypeGrad(self, from_dtype, to_dtype, rng):\nargs = (rng((2, 3), from_dtype),)\nconvert_element_type = lambda x: lax.convert_element_type(x, to_dtype)\n- check_grads(convert_element_type, args, 1, 1e-3, 1e-3, 1e-3)\n- check_grads(convert_element_type, args, 2, 1e-3, 1e-3, 1e-3)\n+ check_grads(convert_element_type, args, 2, [\"fwd\", \"rev\"], 1e-3, 1e-3, 1e-3)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_min_shape={}_operand_shape={}_max_shape={}\".format(\n@@ -1536,7 +1545,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nshapes = [min_shape, operand_shape, max_shape]\nmin, operand, max = (rng(shape, dtype) for shape in shapes)\nmin, max = onp.minimum(min, max), onp.maximum(min, max) # broadcast\n- check_grads(lax.clamp, (min, operand, max), 2, tol, tol, tol)\n+ check_grads(lax.clamp, (min, operand, max), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_dim={}_baseshape=[{}]_dtype={}_narrs={}\".format(\n@@ -1555,7 +1564,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nfor size, _ in zip(itertools.cycle([3, 1, 4]), range(num_arrs))]\noperands = tuple(rng(shape, dtype) for shape in shapes)\nconcatenate = lambda *args: lax.concatenate(args, dim)\n- check_grads(concatenate, operands, 2, tol, tol, tol)\n+ check_grads(concatenate, operands, 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -1578,7 +1587,8 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nlhs = rng(lhs_shape, dtype)\nrhs = rng(rhs_shape, dtype)\nconv = partial(lax.conv, window_strides=strides, padding=padding)\n- check_grads_bilinear(conv, (lhs, rhs), order=2, atol=1e-2, rtol=1e-2)\n+ check_grads_bilinear(conv, (lhs, rhs), order=2, modes=[\"fwd\", \"rev\"],\n+ atol=1e-2, rtol=1e-2)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -1611,7 +1621,8 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nrhs = rng(rhs_shape, dtype)\nconv = partial(lax.conv_with_general_padding, window_strides=strides,\npadding=padding, lhs_dilation=lhs_dil, rhs_dilation=rhs_dil)\n- check_grads_bilinear(conv, (lhs, rhs), order=2, atol=1e-2, rtol=1e-2)\n+ check_grads_bilinear(conv, (lhs, rhs), order=2, modes=[\"fwd\", \"rev\"],\n+ atol=1e-2, rtol=1e-2)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -1654,7 +1665,8 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nconv = partial(lax.conv_general_dilated, window_strides=strides,\npadding=padding, lhs_dilation=lhs_dil, rhs_dilation=rhs_dil,\ndimension_numbers=dimension_numbers)\n- check_grads_bilinear(conv, (lhs, rhs), order=2, atol=tol, rtol=tol)\n+ check_grads_bilinear(conv, (lhs, rhs), order=2, modes=[\"fwd\", \"rev\"],\n+ atol=tol, rtol=tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_lhs_shape={}_rhs_shape={}\".format(\n@@ -1670,7 +1682,8 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ntol = 1e-1 if num_float_bits(dtype) == 32 else 1e-3\nlhs = rng(lhs_shape, dtype)\nrhs = rng(rhs_shape, dtype)\n- check_grads_bilinear(lax.dot, (lhs, rhs), order=2, atol=tol, rtol=tol)\n+ check_grads_bilinear(lax.dot, (lhs, rhs), order=2, modes=[\"fwd\", \"rev\"],\n+ atol=tol, rtol=tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -1694,7 +1707,8 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nlhs = rng(lhs_shape, dtype)\nrhs = rng(rhs_shape, dtype)\ndot_general = partial(lax.dot_general, dimension_numbers=dimension_numbers)\n- check_grads_bilinear(dot_general, (lhs, rhs), order=2, atol=tol, rtol=tol)\n+ check_grads_bilinear(dot_general, (lhs, rhs), order=2, modes=[\"fwd\", \"rev\"],\n+ atol=tol, rtol=tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_dtype={}_broadcast_sizes={}\".format(\n@@ -1709,7 +1723,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ntol = 1e-2 if onp.finfo(dtype).bits == 32 else None\nargs = (rng(shape, dtype),)\nbroadcast = lambda x: lax.broadcast(x, broadcast_sizes)\n- check_grads(broadcast, args, 2, tol, tol, tol)\n+ check_grads(broadcast, args, 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_inshape={}_outshape={}_bcdims={}\".format(\n@@ -1729,7 +1743,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ntol = 1e-2 if onp.finfo(dtype).bits == 32 else None\noperand = rng(inshape, dtype)\nbroadcast_in_dim = lambda x: lax.broadcast_in_dim(x, outshape, dimensions)\n- check_grads(broadcast_in_dim, (operand,), 2, tol, tol, tol)\n+ check_grads(broadcast_in_dim, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_inshape={}_outshape={}\".format(\n@@ -1746,7 +1760,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ntol = 1e-2 if onp.finfo(dtype).bits == 32 else None\noperand = rng(arg_shape, dtype)\nreshape = lambda x: lax.reshape(x, out_shape)\n- check_grads(reshape, (operand,), 2, tol, tol, tol)\n+ check_grads(reshape, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_inshape={}_pads={}\"\n@@ -1760,12 +1774,12 @@ class LaxAutodiffTest(jtu.JaxTestCase):\noperand = rng(shape, dtype)\npad = lambda operand: lax.pad(operand, onp.array(0, dtype), pads)\n- check_grads(pad, (operand,), 2, tol, tol, tol)\n+ check_grads(pad, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\noperand = rng(shape, dtype)\npadding_value = onp.array(0., dtype)\npad = lambda operand, padding_value: lax.pad(operand, padding_value, pads)\n- check_grads(pad, (operand, padding_value), 2, tol, tol, tol)\n+ check_grads(pad, (operand, padding_value), 2, [\"fwd\", \"rev\"], tol, tol, tol)\ndef testReverseGrad(self):\nrev = lambda operand: lax.rev(operand, dimensions)\n@@ -1792,7 +1806,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\non_true = rng(arg_shape, dtype)\non_false = rng(arg_shape, dtype)\nselect = lambda on_true, on_false: lax.select(pred, on_true, on_false)\n- check_grads(select, (on_true, on_false), 2, tol, tol, tol)\n+ check_grads(select, (on_true, on_false), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n@@ -1818,7 +1832,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ntol = 1e-2 if onp.finfo(dtype).bits == 32 else None\noperand = rng(shape, dtype)\nslice = lambda x: lax.slice(x, starts, limits, strides)\n- check_grads(slice, (operand,), 2, tol, tol, tol)\n+ check_grads(slice, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_start_indices={}_size_indices={}\".format(\n@@ -1838,7 +1852,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ntol = 1e-2 if onp.finfo(dtype).bits == 32 else None\noperand = rng(shape, dtype)\ndynamic_slice = lambda x: lax.dynamic_slice(x, start_indices, size_indices)\n- check_grads(dynamic_slice, (operand,), 2, tol, tol, tol)\n+ check_grads(dynamic_slice, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_start_indices={}_update_shape={}\".format(\n@@ -1861,13 +1875,13 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nstart_indices = onp.array(start_indices)\ndus = lambda x, y: lax.dynamic_update_slice(x, y, start_indices)\n- check_grads(dus, (operand, update), 2, tol, tol, tol)\n+ check_grads(dus, (operand, update), 2, [\"fwd\", \"rev\"], tol, tol, tol)\ndus = lambda x: lax.dynamic_update_slice(x, update, start_indices)\n- check_grads(dus, (operand,), 2, tol, tol, tol)\n+ check_grads(dus, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\ndus = lambda y: lax.dynamic_update_slice(operand, y, start_indices)\n- check_grads(dus, (update,), 2, tol, tol, tol)\n+ check_grads(dus, (update,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_perm={}\".format(\n@@ -1885,7 +1899,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ntol = 1e-2 if onp.finfo(dtype).bits == 32 else None\noperand = rng(shape, dtype)\ntranspose = lambda x: lax.transpose(x, perm)\n- check_grads(transpose, (operand,), 2, tol, tol, tol)\n+ check_grads(transpose, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_op={}_inshape={}_reducedims={}\"\n@@ -1914,7 +1928,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\noperand = rng(shape, dtype)\ninit_val = onp.asarray(init_val, dtype=dtype)\nreduce = lambda operand: lax.reduce(operand, init_val, op, dims)\n- check_grads(reduce, (operand,), 1, tol, tol)\n+ check_grads(reduce, (operand,), 1, [\"fwd\", \"rev\"], tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_op={}_dtype={}_padding={}\"\n@@ -1965,7 +1979,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nmsg=\"test requires operand elements to be unique.\")\njtu.check_vjp(fun, partial(api.vjp, fun), (operand,), 1e-2, 1e-2, 1e-2)\nif test_gradients:\n- check_grads(fun, (operand,), 3, 1e-2, 1e-2, 1e-2)\n+ check_grads(fun, (operand,), 3, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1e-2)\n# pylint: enable=cell-var-from-loop\n# TODO(b/205052657): enable more tests when supported\n@@ -1981,7 +1995,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ntol = 1e-2 if onp.finfo(dtype).bits == 32 else None\noperand = rng(shape, dtype)\nsort = lambda x: lax.sort(x, axis)\n- check_grads(sort, (operand,), 2, tol, tol, tol)\n+ check_grads(sort, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n# TODO(b/205052657): enable more tests when supported\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -2009,7 +2023,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nkeys, values = args_maker()\nfun = lambda keys, values: lax.sort_key_val(keys, values, axis)\n- check_grads(fun, (keys, values), 2, 1e-2, 1e-2, 1e-2)\n+ check_grads(fun, (keys, values), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1e-2)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_idxs={}_axes={}\".format(\n@@ -2027,7 +2041,9 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nidxs = tuple(rng(e.shape, e.dtype) for e in idxs)\nsrc = rng(shape, dtype)\nindex_take = lambda src: lax.index_take(src, idxs, axes)\n- check_grads(index_take, (src,), 2, 1e-2, 1e-2, 1)\n+ check_grads(index_take, (src,), 2, [\"fwd\"], 1e-2, 1e-2, 1)\n+ # TODO(mattjj): fix rev mode failures here!\n+ # check_grads(index_take, (src,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_idxs={}_dnums={}_slice_sizes={}\".format(\n@@ -2054,7 +2070,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ngather = lambda x: lax.gather(x, idxs, dimension_numbers=dnums,\nslice_sizes=slice_sizes)\nx = rng(shape, dtype)\n- check_grads(gather, (x,), 2, 1e-2, 1e-2, 1.)\n+ check_grads(gather, (x,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1.)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_idxs={}_update={}_dnums={}\".format(\n@@ -2084,7 +2100,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ndimension_numbers=dnums)\nx = rng(arg_shape, dtype)\ny = rng(update_shape, dtype)\n- check_grads(scatter_add, (x, y), 2, 1e-2, 1e-2, 1.)\n+ check_grads(scatter_add, (x, y), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1.)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_idxs={}_update={}_dnums={}\".format(\n@@ -2113,7 +2129,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nscatter = lambda x, y: lax.scatter(x, idxs, y, dimension_numbers=dnums)\nx = rng(arg_shape, dtype)\ny = rng(update_shape, dtype)\n- check_grads(scatter, (x, y), 2, 1e-2, 1e-2, 1.)\n+ check_grads(scatter, (x, y), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1.)\ndef testStopGradient(self):\ndef f(x):\n"
}
] | Python | Apache License 2.0 | google/jax | make check_grads check all orders <= given order |
260,335 | 21.05.2019 18:07:22 | 25,200 | 096dfb9b203c13b151cc5a121033812d0a1b5615 | fixed scan differentiation! | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -187,7 +187,11 @@ def backward_pass(jaxpr, consts, freevar_vals, args, cotangent_in):\nif cts_out is zero:\ncts_out = [zero for _ in eqn.invars]\n+ if not eqn.restructure:\nmap(write_cotangent, eqn.invars, cts_out)\n+ else:\n+ [map(write_cotangent, v, ct) if type(v) is tuple\n+ else write_cotangent(v, ct) for v, ct in zip(eqn.invars, cts_out)]\nfreevar_cts = core.pat_fmap(read_cotangent, jaxpr.freevars)\ncotangents_out = core.pat_fmap(lambda v, _: read_cotangent(v), jaxpr.invars, None)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -637,27 +637,16 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nlambda: lax.scan(plus_one, p0, list(range(5))))\ndef testScanHigherOrderDifferentiation(self):\n+ d = 0.75\ndef f(c, a):\n- b = np.sin(c * a)\n- c = 0.9 * c\n+ b = np.sin(c * np.sum(np.cos(d * a)))\n+ c = 0.9 * np.cos(d * np.sum(np.sin(c * a)))\nreturn c, b\n- as_ = np.arange(3.).reshape((3, 1))\n+ as_ = np.arange(6.).reshape((3, 2))\nc = 1.\n- # pass\n- jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\"], order=2)\n- jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\"], order=2)\n- jtu.check_grads(lambda c: lax.scan(f, c, as_)[0], (c,), modes=[\"rev\"], order=2)\n-\n- # fail w/ zero\n- # jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"rev\"], order=2)\n- # jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\", \"rev\"], order=1)\n- # jtu.check_grads(lambda as_: lax.scan(f, c, as_), (as_,), modes=[\"fwd\", \"rev\"], order=2)\n- # jtu.check_grads(lambda c: lax.scan(f, c, as_)[1], (c,), modes=[\"rev\"], order=2)\n-\n- # fail w/ nonzero\n- # jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\", \"rev\"], order=2)\n+ jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\", \"rev\"], order=2)\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | fixed scan differentiation! |
260,335 | 21.05.2019 18:19:42 | 25,200 | 6c47c9f2a1ba1ceb501bdeb6cc867736d2badede | loosen tolerance on testLuGrad | [
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -499,8 +499,7 @@ class ScipyLinalgTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"gpu\", \"tpu\")\ndef testLuGrad(self, shape, dtype, rng):\na = rng(shape, dtype)\n-\n- jtu.check_grads(jsp.linalg.lu, (a,), 2, rtol=1e-1)\n+ jtu.check_grads(jsp.linalg.lu, (a,), 2, atol=5e-2, rtol=1e-1)\n@jtu.skip_on_devices(\"gpu\", \"tpu\")\ndef testLuBatching(self):\n"
}
] | Python | Apache License 2.0 | google/jax | loosen tolerance on testLuGrad |
260,506 | 21.05.2019 21:34:42 | 14,400 | 8ea5eff3b1eaf59e45c8a003994f5c03a6f76591 | Fix vmap() when there are empty tuples in the input | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -291,9 +291,9 @@ def dimsize(dim, x):\ndef _dimsize(dim, aval, x):\nif type(aval) is AbstractTuple:\nif type(dim) is tuple:\n- return reduce(set.union, map(_dimsize, dim, aval, x))\n+ return reduce(set.union, map(_dimsize, dim, aval, x), set())\nelif type(dim) is int:\n- return reduce(set.union, map(partial(_dimsize, dim), aval, x))\n+ return reduce(set.union, map(partial(_dimsize, dim), aval, x), set())\nelif dim is None:\nreturn set()\nelse:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -962,6 +962,15 @@ class BatchingTest(jtu.JaxTestCase):\nprint(vmap(f)(random.split(random.PRNGKey(0), 2))) # no crash\n+ def testEmptyTuples(self):\n+ # Ensure there is no crash when a vectorized input contains empty tuples.\n+ result = vmap(lambda x, _: x + 1)(onp.array([0, 1]), ())\n+ self.assertAllClose(result, onp.array([1, 2]), check_dtypes=False)\n+ # Ensure there is no crash when a vectorized output contains empty tuples.\n+ result, empty_tuple = vmap(lambda x: (x + 1, ()))(onp.array([0, 1]))\n+ self.assertAllClose(result, onp.array([1, 2]), check_dtypes=False)\n+ self.assertEqual((), empty_tuple)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | Fix vmap() when there are empty tuples in the input |
260,335 | 21.05.2019 18:51:32 | 25,200 | e04f344ca524c3b3c0b4feaa93ea7f9d57d5df04 | fix typo in lax.scan autodiff test (cf. | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -646,7 +646,8 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nas_ = np.arange(6.).reshape((3, 2))\nc = 1.\n- jtu.check_grads(lambda c: lax.scan(f, c, as_), (c,), modes=[\"fwd\", \"rev\"], order=2)\n+ jtu.check_grads(lambda c, as_: lax.scan(f, c, as_), (c, as_),\n+ modes=[\"fwd\", \"rev\"], order=2)\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | fix typo in lax.scan autodiff test (cf. #749) |
260,335 | 21.05.2019 19:18:29 | 25,200 | ec6e39b9b253b708a4b893455523cfa6dd494527 | fix negative index handling in index_take
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -662,6 +662,7 @@ def scatter(operand, scatter_indices, updates, dimension_numbers):\ndef index_take(src, idxs, axes):\nindices = concatenate([reshape(i, [i.shape[0], 1]) for i in idxs], 1)\n+ indices = indices % onp.array([src.shape[ax] for ax in axes])\nslice_sizes = list(src.shape)\nfor ax in axes:\nslice_sizes[ax] = 1\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -2038,12 +2038,9 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n]\nfor rng in [jtu.rand_default()]))\ndef testIndexTakeGrad(self, shape, dtype, idxs, axes, rng):\n- idxs = tuple(rng(e.shape, e.dtype) for e in idxs)\nsrc = rng(shape, dtype)\nindex_take = lambda src: lax.index_take(src, idxs, axes)\n- check_grads(index_take, (src,), 2, [\"fwd\"], 1e-2, 1e-2, 1)\n- # TODO(mattjj): fix rev mode failures here!\n- # check_grads(index_take, (src,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1)\n+ check_grads(index_take, (src,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_idxs={}_dnums={}_slice_sizes={}\".format(\n"
}
] | Python | Apache License 2.0 | google/jax | fix negative index handling in index_take
fixes #751 |
260,335 | 21.05.2019 21:37:52 | 25,200 | 14d16b2d660d648f944ca3695369a43da8c53ce1 | support both .reshape(*shape) and .reshape(shape)
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -649,6 +649,20 @@ def _reshape(a, newshape, order=\"C\"):\nelse:\nraise ValueError(\"Unexpected value for 'order' argument: {}.\".format(order))\n+def _reshape_method(a, *newshape, **kwargs):\n+ order = kwargs.pop(\"order\", \"C\")\n+ if len(kwargs) == 1:\n+ invalid_kwarg, = kwargs\n+ msg = \"'{}' is an invalid keyword argument for this function\"\n+ raise TypeError(msg.format(invalid_kwarg)) # same as NumPy error\n+ elif kwargs:\n+ invalid_kwargs = \"'{}'\".format(\"'\".join(kwargs))\n+ msg = \"{} are invalid keyword arguments for this function\"\n+ raise TypeError(msg.format(invalid_kwargs)) # different from NumPy error\n+ if len(newshape) == 1 and not isinstance(newshape[0], int):\n+ newshape = newshape[0]\n+ return _reshape(a, newshape, order=order)\n+\n@_wraps(onp.ravel)\ndef ravel(a, order=\"C\"):\n@@ -2353,7 +2367,7 @@ for operator_name, function in _operators.items():\n# Forward methods and properties using core.aval_method and core.aval_property:\nfor method_name in _nondiff_methods + _diff_methods:\nsetattr(ShapedArray, method_name, core.aval_method(globals()[method_name]))\n-setattr(ShapedArray, \"reshape\", core.aval_method(_reshape))\n+setattr(ShapedArray, \"reshape\", core.aval_method(_reshape_method))\nsetattr(ShapedArray, \"flatten\", core.aval_method(ravel))\nsetattr(ShapedArray, \"T\", core.aval_property(transpose))\nsetattr(ShapedArray, \"real\", core.aval_property(real))\n@@ -2367,7 +2381,7 @@ for operator_name, function in _operators.items():\nsetattr(DeviceArray, \"__{}__\".format(operator_name), function)\nfor method_name in _nondiff_methods + _diff_methods:\nsetattr(DeviceArray, method_name, globals()[method_name])\n-setattr(DeviceArray, \"reshape\", _reshape)\n+setattr(DeviceArray, \"reshape\", _reshape_method)\nsetattr(DeviceArray, \"flatten\", ravel)\nsetattr(DeviceArray, \"T\", property(transpose))\nsetattr(DeviceArray, \"real\", property(real))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -975,6 +975,25 @@ 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\": \"_inshape={}_outshape={}\".format(\n+ jtu.format_shape_dtype_string(arg_shape, dtype),\n+ jtu.format_shape_dtype_string(out_shape, dtype)),\n+ \"arg_shape\": arg_shape, \"out_shape\": out_shape, \"dtype\": dtype,\n+ \"rng\": jtu.rand_default()}\n+ for dtype in default_dtypes\n+ for arg_shape, out_shape in [\n+ ((7, 0), (0, 42, 101)),\n+ ((2, 1, 4), (-1,)),\n+ ((2, 2, 4), (2, 8))\n+ ]))\n+ def testReshapeMethod(self, arg_shape, out_shape, dtype, rng):\n+ onp_fun = lambda x: onp.reshape(x, out_shape)\n+ lnp_fun = lambda x: x.reshape(*out_shape)\n+ args_maker = lambda: [rng(arg_shape, dtype)]\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\": \"_inshape={}_expanddim={}\".format(\njtu.format_shape_dtype_string(arg_shape, dtype), dim),\n@@ -1522,6 +1541,9 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nassert lnp.allclose(lnp.eye(5000), onp.eye(5000))\nself.assertEqual(0, onp.sum(lnp.eye(1050) - onp.eye(1050)))\n+ def testIssue746(self):\n+ lnp.arange(12).reshape(3, 4) # doesn't crash\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | support both .reshape(*shape) and .reshape(shape)
fixes #746 |
260,335 | 15.05.2019 07:25:03 | 25,200 | 140699ed7de017918f7049b35bae3e3f0ef4d080 | scan of vmap sketched out! cf. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -557,9 +557,6 @@ def map_transpose(primitive, params, jaxpr, consts, freevar_vals, args, ct):\nfreevar_cts = tree_map(lambda x: x.sum(0), freevar_cts)\nreturn cts_out, freevar_cts\n-def jaxpr_as_fun(jaxpr, consts, *args):\n- return core.eval_jaxpr(jaxpr, consts, (), *args)\n-\ndef get_nonzeros(tangent):\nif tangent is zero:\nreturn False\n@@ -599,7 +596,7 @@ def jvp_jaxpr(jaxpr, nonzeros, instantiate):\n# jaxpr :: d -> a -> b -> (c1, c2)\n# avals = (d, a, b)\n# f :: d -> a -> b -> (c1, c2)\n- f = wrap_init(partial(jaxpr_as_fun, jaxpr.jaxpr, jaxpr.literals))\n+ f = wrap_init(core.jaxpr_as_fun(jaxpr))\nf_jvp, out_nonzeros = f_jvp_traceable(jvp(f, instantiate=instantiate), nonzeros)\n# f_jvp :: (d, d') -> (a, a') -> (b, b') -> ((c1, c1'), (c2, c2'))\ntangent_avals = map(partial(strip_zeros, core.AbstractTuple(()), core.AbstractTuple),\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -29,9 +29,9 @@ from ..core import Trace, Tracer, new_master, pack, AbstractTuple, JaxTuple\nfrom ..abstract_arrays import ShapedArray, make_shaped_array, array_types, raise_to_shaped\nfrom ..ad_util import add_jaxvals_p, zeros_like_p, zeros_like_jaxval\nfrom ..linear_util import transformation, transformation_with_aux, wrap_init\n-from ..tree_util import register_pytree_node\nfrom ..util import unzip2, partial, safe_map\nfrom . import xla\n+from . import partial_eval as pe\nmap = safe_map\n@@ -52,10 +52,10 @@ def batch_transform(size, in_dims, out_dim_dst, vals):\nwith new_master(BatchTrace) as master:\ntrace = BatchTrace(master, core.cur_sublevel())\nin_tracers = map(partial(BatchTracer, trace), vals, in_dims)\n- out_tracer = yield in_tracers, {}\n- out_tracer = trace.full_raise(out_tracer)\n+ ans = yield in_tracers, {}\n+ out_tracer = trace.full_raise(ans)\nout_val, out_dim = out_tracer.val, out_tracer.batch_dim\n- del master\n+ del master, out_tracer\nyield moveaxis(size, out_dim_dst, out_dim, out_val)\n@@ -75,6 +75,7 @@ class BatchTracer(Tracer):\n__slots__ = ['val', 'batch_dim']\ndef __init__(self, trace, val, batch_dim):\n+ assert core.skip_checks or type(batch_dim) in (int, tuple)\nself.trace = trace\nself.val = val\nself.batch_dim = batch_dim\n@@ -365,3 +366,148 @@ def handle_scalar_broadcasting(nd, x, bdim):\nreturn x\nelse:\nreturn x.reshape(x.shape + (1,) * (nd - x.ndim))\n+\n+\n+def where_batched(bdim):\n+ t = type(bdim)\n+ if t is tuple:\n+ return tuple(map(where_batched, bdim))\n+ elif t in (int, type(None)):\n+ return bdim is not None\n+ else:\n+ raise TypeError(t)\n+\n+def bools_to_bdims(bdim, batched_indicator_tree):\n+ t = type(batched_indicator_tree)\n+ if t is tuple:\n+ return tuple(map(partial(bools_to_bdims, bdim), batched_indicator_tree))\n+ elif t is bool:\n+ return bdim if batched_indicator_tree else None\n+ else:\n+ raise TypeError(t)\n+\n+def instantiate_bdim(size, axis, instantiate, bdim, x):\n+ \"\"\"Instantiate or move a batch dimension to position `axis`.\n+\n+ Ensures that `x` is at least as high on the batched lattice as `instantiate`.\n+\n+ Args:\n+ size: int, size of the axis to instantiate.\n+ axis: int, where to instantiate or move the batch dimension.\n+ instantiate: tuple-tree of booleans, where the tree structure is a prefix of\n+ the tree structure in x, indicating whether to instantiate the batch\n+ dimension at the corresponding subtree in x.\n+ bdim: tuple-tree of ints or NoneTypes, with identical tree structure to\n+ `instantaite`, indicating where the batch dimension exists in the\n+ corresponding subtree of x.\n+ x: JaxType value on which to instantiate or move batch dimensions.\n+\n+ Returns:\n+ A new version of `x` with instantiated batch dimensions.\n+ \"\"\"\n+ def _inst(instantiate, bdim, x):\n+ if type(instantiate) is tuple:\n+ assert type(bdim) is tuple # instantiate at same granularity as bdim\n+ return core.pack(map(_inst, instantiate, bdim, x))\n+ elif type(instantiate) is bool:\n+ if not instantiate:\n+ if bdim is None:\n+ return x\n+ elif type(bdim) is int:\n+ return moveaxis2(bdim, axis, x)\n+ else:\n+ raise TypeError(type(bdim))\n+ else:\n+ if bdim is None:\n+ return broadcast2(size, axis, x)\n+ elif type(bdim) is int:\n+ return moveaxis2(bdim, axis, x)\n+ else:\n+ raise TypeError(type(bdim))\n+ else:\n+ raise TypeError(type(instantiate))\n+\n+ return _inst(instantiate, bdim, x)\n+\n+def moveaxis2(src, dst, x):\n+ if src == dst:\n+ return x\n+ else:\n+ return _moveaxis2(src, dst, x, get_aval(x))\n+\n+def _moveaxis2(src, dst, x, aval):\n+ if type(aval) is JaxTuple:\n+ return core.pack(map(partial(_moveaxis2, src, dst), x, aval))\n+ else:\n+ perm = [i for i in range(onp.ndim(x)) if i != src]\n+ perm.insert(dst, src)\n+ return x.transpose(perm)\n+\n+def broadcast2(size, axis, x):\n+ return _broadcast2(size, axis, x, get_aval(x))\n+\n+def _broadcast2(size, axis, x, aval):\n+ if type(aval) is JaxTuple:\n+ return core.pack(map(partial(_broadcast2, size, axis), x, aval))\n+ else:\n+ # see comment at the top of this section\n+ if isinstance(x, onp.ndarray) or onp.isscalar(x):\n+ return onp.broadcast_to(x, (sz,) + onp.shape(x))\n+ else:\n+ return x.broadcast((sz,)) # should be a JAX arraylike\n+\n+def _promote_aval_rank(n, batched, aval):\n+ assert isinstance(aval, core.AbstractValue)\n+ if isinstance(aval, core.AbstractTuple):\n+ t = type(batched)\n+ if t is tuple:\n+ return core.AbstractTuple(map(partial(_promote_aval_rank, n), batched, aval))\n+ elif t is bool:\n+ if batched:\n+ return core.AbstractTuple(map(partial(_promote_aval_rank, n, batched), aval))\n+ else:\n+ return aval\n+ else:\n+ raise TypeError(t)\n+ else:\n+ if batched:\n+ return ShapedArray((n,) + aval.shape, aval.dtype)\n+ else:\n+ return aval\n+\n+def batch_jaxpr(jaxpr, size, is_batched, instantiate):\n+ f = wrap_init(core.jaxpr_as_fun(jaxpr))\n+ f_batched, where_out_batched = batched_traceable(f, size, is_batched, instantiate)\n+ in_avals = map(partial(_promote_aval_rank, size), is_batched, jaxpr.in_avals)\n+ in_pvals = [pe.PartialVal((aval, core.unit)) for aval in in_avals]\n+ jaxpr_out, pval_out, literals_out = pe.trace_to_jaxpr(f_batched, in_pvals,\n+ instantiate=True)\n+ out_aval, _ = pval_out\n+ jaxpr_out = core.TypedJaxpr(jaxpr_out, literals_out, in_avals, out_aval)\n+ return jaxpr_out, where_out_batched()\n+\n+@transformation_with_aux\n+def batched_traceable(size, is_batched, instantiate, *vals):\n+ in_dims = bools_to_bdims(0, is_batched)\n+ with new_master(BatchTrace) as master:\n+ trace = BatchTrace(master, core.cur_sublevel())\n+ in_tracers = map(partial(BatchTracer, trace), vals, in_dims)\n+ ans = yield in_tracers, {}\n+ out_tracer = trace.full_raise(ans)\n+ out_val, out_dim = out_tracer.val, out_tracer.batch_dim\n+ del master, out_tracer\n+ out_val = instantiate_bdim(size, 0, instantiate, out_dim, out_val)\n+ yield out_val, _binary_lattice_join(where_batched(out_dim), instantiate)\n+\n+def _binary_lattice_join(a, b):\n+ t = (type(a), type(b))\n+ if t == (tuple, tuple):\n+ return tuple(map(_binary_lattice_join, a, b))\n+ elif t == (tuple, bool):\n+ return tuple(map(_binary_lattice_join, a, (b,) * len(a)))\n+ elif t == (bool, tuple):\n+ return tuple(map(_binary_lattice_join, (a,) * len(b), b))\n+ elif t == (bool, bool):\n+ return a or b\n+ else:\n+ raise TypeError((type(a), type(b)))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -35,7 +35,7 @@ from jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\nfrom jax.interpreters import ad\nfrom jax.util import partial, unzip2, safe_map, safe_zip\n-from jax.tree_util import build_tree, tree_unflatten\n+from jax.tree_util import build_tree, tree_unflatten, tree_map\nfrom jax import ad_util\nmap = safe_map\n@@ -236,6 +236,8 @@ def _while_loop_batching_rule(batched_args, batch_dims, cond_consts,\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_tracer_consts` and `body_tracer_consts`.\n+ # TODO(mattjj): Revise this using scan machinery (and fixed-point the loop\n+ # carry instead of lifting it all the way!)\ninit_val, cond_tracer_consts, body_tracer_consts = batched_args\ninit_val_bd, cond_tracer_consts_bd, body_tracer_consts_bd = batch_dims\n@@ -501,6 +503,8 @@ def _update_arrays(i, aval, xs, x):\nelse:\nreturn lax.dynamic_update_index_in_dim(xs, x[None, ...], i, axis=0)\n+class FixedPointError(Exception): pass\n+\ndef scan(f, init, xs):\n\"\"\"Scan a function over leading array axes while carrying along state.\n@@ -814,7 +818,6 @@ def _move_stuff_and_add_add(typed_jaxpr):\ndef _add_any_eqn(tot, a, b):\nreturn core.JaxprEqn([a, b], [tot], ad_util.add_jaxvals_p, (), False, False, {})\n-\n# transpose_jaxpr :: (res -> a -> b) -> (res -> CT b -> CT a)\ndef _transpose_jaxpr(jaxpr):\nassert len(jaxpr.in_avals) == 2\n@@ -837,7 +840,42 @@ def _make_typed_jaxpr(traceable, in_avals):\nreturn core.TypedJaxpr(jaxpr, consts, in_avals, out_aval)\n-class FixedPointError(Exception): pass\n+def _scan_batching_rule(batched_args, batch_dims, forward, length, jaxpr):\n+ consts, init, xs = batched_args\n+ consts_bdim, init_bdim, xs_bdim = batch_dims\n+\n+ sizes = lax._reduce(set.union, map(batching.dimsize, batch_dims, batched_args))\n+ size = sizes.pop()\n+ assert not sizes\n+\n+ consts_batched = batching.where_batched(consts_bdim)\n+ init_batched = batching.where_batched(init_bdim)\n+ xs_batched = batching.where_batched(xs_bdim)\n+\n+ carry_batched = init_batched\n+ for _ in range(1000):\n+ which_batched = (consts_batched, carry_batched, xs_batched)\n+ jaxpr_batched, batched_out = batching.batch_jaxpr(jaxpr, size, which_batched,\n+ instantiate=(carry_batched, False))\n+ carry_batched_out, ys_batched = batched_out\n+ if carry_batched_out == carry_batched:\n+ break\n+ else:\n+ carry_batched = _binary_lattice_join(carry_batched_out, carry_batched)\n+ else:\n+ raise FixedPointError\n+\n+ consts_batched = batching.instantiate_bdim(size, 0, consts_batched, consts_bdim, consts)\n+ init_batched = batching.instantiate_bdim(size, 0, carry_batched, init_bdim, init)\n+ xs_batched = batching.instantiate_bdim(size, 1, xs_batched, xs_bdim, xs)\n+\n+ carry_out, ys = scan_p.bind(\n+ consts_batched, init_batched, xs_batched,\n+ forward=forward, length=length, jaxpr=jaxpr_batched)\n+\n+ carry_out_bdim = batching.bools_to_bdims(0, carry_batched)\n+ ys_bdim = batching.bools_to_bdims(1, ys_batched)\n+ return core.pack((carry_out, ys)), (carry_out_bdim, ys_bdim)\n# We use a custom bind for scan just to add some error checks\n@@ -858,3 +896,4 @@ ad.primitive_jvps[scan_p] = _scan_jvp\nad.primitive_transposes[scan_p] = _scan_transpose\npe.custom_partial_eval_rules[scan_p] = _scan_partial_eval\nxla.translations[scan_p] = partial(xla.lower_fun, _scan_impl)\n+batching.primitive_batchers[scan_p] = _scan_batching_rule\n"
}
] | Python | Apache License 2.0 | google/jax | scan of vmap sketched out! cf. #716 |
260,335 | 16.05.2019 07:40:31 | 25,200 | 7065cb6374b06ca54969826c1e68b73f937faba5 | move control flow batching tests | [
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -889,66 +889,6 @@ 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-\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-\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-\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-\ndef testIssue489(self):\ndef f(key):\ndef body_fn(uk):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -234,6 +234,66 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(cfun(x, num), onp.sum(x[:num]), check_dtypes=False)\nself.assertAllClose(cfun(x, num), onp.sum(x[:num]), check_dtypes=False)\n+ def testWhileLoopBatched(self):\n+ def fun(x):\n+ return lax.while_loop(lambda x: x < 3, lambda x: x + 2, x)\n+\n+ ans = api.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 = api.jit(fun)\n+ ans = api.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+ 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 = api.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 = api.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+\n+ def testWhileLoopTupleBatched(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 = api.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+\n+ def testForiLoopBatched(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 = api.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+\ndef testForiLoopBasic(self):\ndef count(num):\ndef body_fun(i, tot):\n"
}
] | Python | Apache License 2.0 | google/jax | move control flow batching tests |
260,335 | 16.05.2019 10:18:53 | 25,200 | 4fe2bcfe4131e0c7e0d756f0ca051a58a1f82db2 | add vmap-of-scan tests, fix minor bugs | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -368,6 +368,8 @@ def handle_scalar_broadcasting(nd, x, bdim):\nreturn x.reshape(x.shape + (1,) * (nd - x.ndim))\n+# TODO(mattjj): try to de-duplicate utility functions with above\n+\ndef where_batched(bdim):\nt = type(bdim)\nif t is tuple:\n@@ -452,9 +454,9 @@ def _broadcast2(size, axis, x, aval):\nelse:\n# see comment at the top of this section\nif isinstance(x, onp.ndarray) or onp.isscalar(x):\n- return onp.broadcast_to(x, (sz,) + onp.shape(x))\n+ return onp.broadcast_to(x, (size,) + onp.shape(x))\nelse:\n- return x.broadcast((sz,)) # should be a JAX arraylike\n+ return x.broadcast((size,)) # should be a JAX arraylike\ndef _promote_aval_rank(n, batched, aval):\nassert isinstance(aval, core.AbstractValue)\n@@ -480,8 +482,8 @@ def batch_jaxpr(jaxpr, size, is_batched, instantiate):\nf_batched, where_out_batched = batched_traceable(f, size, is_batched, instantiate)\nin_avals = map(partial(_promote_aval_rank, size), is_batched, jaxpr.in_avals)\nin_pvals = [pe.PartialVal((aval, core.unit)) for aval in in_avals]\n- jaxpr_out, pval_out, literals_out = pe.trace_to_jaxpr(f_batched, in_pvals,\n- instantiate=True)\n+ jaxpr_out, pval_out, literals_out = pe.trace_to_jaxpr(\n+ f_batched, in_pvals, instantiate=True)\nout_aval, _ = pval_out\njaxpr_out = core.TypedJaxpr(jaxpr_out, literals_out, in_avals, out_aval)\nreturn jaxpr_out, where_out_batched()\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -18,6 +18,7 @@ from __future__ import print_function\nimport collections\nfrom functools import partial\n+import itertools\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -29,6 +30,7 @@ from jax import api\nfrom jax import core\nfrom jax import lax\nfrom jax import test_util as jtu\n+from jax.util import unzip2\nimport jax.numpy as np # scan tests use numpy\ndef scan_reference(f, init, xs):\n@@ -492,12 +494,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertEqual(out, (7, 10))\n@parameterized.named_parameters(\n- {\"testcase_name\": \"jit_scan={}_jit_f={}\".format(jit_scan, jit_f),\n+ {\"testcase_name\": \"_jit_scan={}_jit_f={}\".format(jit_scan, jit_f),\n\"jit_scan\": jit_scan, \"jit_f\": jit_f}\nfor jit_scan in [False, True]\nfor jit_f in [False, True])\ndef testScanImpl(self, jit_scan, jit_f):\n- d = np.zeros(2)\n+ d = np.array([1., 2.])\ndef f(c, a):\nassert a.shape == (3,)\nassert c.shape == (4,)\n@@ -521,12 +523,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\n@parameterized.named_parameters(\n- {\"testcase_name\": \"jit_scan={}_jit_f={}\".format(jit_scan, jit_f),\n+ {\"testcase_name\": \"_jit_scan={}_jit_f={}\".format(jit_scan, jit_f),\n\"jit_scan\": jit_scan, \"jit_f\": jit_f}\nfor jit_scan in [False, True]\nfor jit_f in [False, True])\ndef testScanJVP(self, jit_scan, jit_f):\n- d = np.zeros(2)\n+ d = np.array([1., 2.])\ndef f(c, a):\nassert a.shape == (3,)\nassert c.shape == (4,)\n@@ -550,12 +552,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\n@parameterized.named_parameters(\n- {\"testcase_name\": \"jit_scan={}_jit_f={}\".format(jit_scan, jit_f),\n+ {\"testcase_name\": \"_jit_scan={}_jit_f={}\".format(jit_scan, jit_f),\n\"jit_scan\": jit_scan, \"jit_f\": jit_f}\nfor jit_scan in [False, True]\nfor jit_f in [False, True])\ndef testScanLinearize(self, jit_scan, jit_f):\n- d = np.zeros(2)\n+ d = np.array([1., 2.])\ndef f(c, a):\nassert a.shape == (3,)\nassert c.shape == (4,)\n@@ -579,12 +581,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\n@parameterized.named_parameters(\n- {\"testcase_name\": \"jit_scan={}_jit_f={}\".format(jit_scan, jit_f),\n+ {\"testcase_name\": \"_jit_scan={}_jit_f={}\".format(jit_scan, jit_f),\n\"jit_scan\": jit_scan, \"jit_f\": jit_f}\nfor jit_scan in [False, True]\nfor jit_f in [False, True])\ndef testScanGrad(self, jit_scan, jit_f):\n- d = np.zeros(2)\n+ d = np.ones(2)\ndef f(c, a):\nassert a.shape == (3,)\nassert c.shape == (4,)\n@@ -611,9 +613,9 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nr = npr.RandomState(0)\nn_in = 4\n- n_hid = 3\n- n_out = 2\n- length = 5\n+ n_hid = 2\n+ n_out = 1\n+ length = 3\nW_trans = r.randn(n_hid, n_hid + n_in)\nW_out = r.randn(n_out, n_hid + n_in)\n@@ -647,11 +649,18 @@ class LaxControlFlowTest(jtu.JaxTestCase):\n# gradient evaluation doesn't crash\napi.grad(loss)(params, inputs, targets)\n- # gradient is zero in the right place\n- predictions = rnn(params, inputs)\n- ans = api.grad(loss)(params, inputs, predictions)\n- expected = (onp.zeros_like(W_trans), onp.zeros_like(W_out))\n- self.assertAllClose(ans, expected, check_dtypes=False)\n+ # gradient check passes\n+ jtu.check_grads(loss, (params, inputs, targets), order=1)\n+\n+ # we can vmap to batch things\n+ batch_size = 7\n+ batched_inputs = r.randn(batch_size, length, n_in)\n+ batched_targets = r.randn(batch_size, length, n_out)\n+ batched_loss = api.vmap(lambda x, y: loss(params, x, y))\n+ losses = batched_loss(batched_inputs, batched_targets)\n+ expected = onp.stack(list(map(lambda x, y: loss(params, x, y),\n+ batched_inputs, batched_targets)))\n+ self.assertAllClose(losses, expected, check_dtypes=False)\ndef testIssue711(self):\n# Tests reverse-mode differentiation through a scan for which the scanned\n@@ -709,6 +718,75 @@ class LaxControlFlowTest(jtu.JaxTestCase):\njtu.check_grads(lambda c, as_: lax.scan(f, c, as_), (c, as_),\nmodes=[\"fwd\", \"rev\"], order=2)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_jit_scan={}_jit_f={}_in_axes={}\".format(\n+ jit_scan, jit_f, in_axes),\n+ \"jit_scan\": jit_scan, \"jit_f\": jit_f, \"in_axes\": in_axes}\n+ for jit_scan in [False, True]\n+ for jit_f in [False, True]\n+ for in_axes in itertools.product([None, 0, 1], [None, 0, 1, 2])\n+ if in_axes != (None, None))\n+ def testScanVmap(self, jit_scan, jit_f, in_axes):\n+ d = np.array([1., 2.])\n+ def f(c, a):\n+ assert a.shape == (3,)\n+ assert c.shape == (4,)\n+ b = np.sum(np.sin(a)) + np.sum(np.sin(c)) + np.sum(np.sin(d))\n+ c = np.sin(c * b)\n+ assert b.shape == ()\n+ return c, b\n+\n+ if jit_f:\n+ f = api.jit(f)\n+ if jit_scan:\n+ scan = api.jit(lax.scan, (0,))\n+ else:\n+ scan = lax.scan\n+\n+ as_shape = [5, 3]\n+ c_shape = [4]\n+\n+ c_bdim, as_bdim = in_axes\n+ if c_bdim is not None:\n+ c_shape.insert(c_bdim, 7)\n+ if as_bdim is not None:\n+ as_shape.insert(as_bdim, 7)\n+\n+ r = onp.random.RandomState(0)\n+ as_ = r.randn(*as_shape)\n+ c = r.randn(*c_shape)\n+\n+ ans = api.vmap(lambda c, as_: scan(f, c, as_), in_axes)(c, as_)\n+ expected = api.vmap(lambda c, as_: scan_reference(f, c, as_), in_axes)(c, as_)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testScanVmapTuples(self):\n+ def f(c, a):\n+ a1, a2 = a\n+ c1, c2 = c\n+ b = np.sum(np.cos(a1)) * np.sum(np.tan(c2 * a2))\n+ c = c1 * np.sin(np.sum(a1 * a2)), c2 * np.cos(np.sum(a1))\n+ return c, b\n+\n+ in_axes = (0, (1, 2))\n+\n+ r = onp.random.RandomState(0)\n+ as_ = (r.randn(3, 7), r.randn(3, 4, 7))\n+ c = (r.randn(7, 2), r.randn(7))\n+\n+ expected_c_out, expected_bs = [], []\n+ for i in range(7):\n+ c_out, bs = lax.scan(f, (c[0][i], c[1][i]), (as_[0][:,i], as_[1][:,:,i]))\n+ expected_c_out.append(c_out)\n+ expected_bs.append(bs)\n+ expected_c_out_0, expected_c_out_1 = unzip2(expected_c_out)\n+ expected_c_out = (np.stack(expected_c_out_0), np.stack(expected_c_out_1))\n+ expected_bs = np.stack(expected_bs)\n+ expected = expected_c_out, expected_bs\n+\n+ ans = api.vmap(lambda c, as_: lax.scan(f, c, as_), in_axes)(c, as_)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add vmap-of-scan tests, fix minor bugs |
260,335 | 22.05.2019 13:33:51 | 25,200 | 0307ce5825cee480356f3333f283e6d9c34b2238 | compare binary lattice prefixes in scan
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -19,6 +19,8 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n+import operator\n+\nimport numpy as onp\nfrom jax import api\n@@ -619,7 +621,7 @@ def _scan_jvp(primals, tangents, forward, length, jaxpr):\njaxpr_jvp, nonzeros_out = ad.jvp_jaxpr(jaxpr, nonzeros,\ninstantiate=(carry_nonzeros, False))\ncarry_nonzeros_out, ys_nonzeros = nonzeros_out\n- if carry_nonzeros_out == carry_nonzeros:\n+ if _binary_lattice_eq(carry_nonzeros_out, carry_nonzeros):\nbreak\nelse:\ncarry_nonzeros = _binary_lattice_join(carry_nonzeros_out, carry_nonzeros)\n@@ -647,19 +649,23 @@ def _scan_jvp(primals, tangents, forward, length, jaxpr):\ncarry_out_dot = ad.put_zeros(ad.TangentTuple, carry_nonzeros_out, carry_out_dot)\nreturn core.pack((carry_out, ys)), ad.TangentTuple((carry_out_dot, ys_dot))\n-def _binary_lattice_join(a, b):\n+def _binary_lattice_fold(f, pack, a, b):\n+ recur = partial(_binary_lattice_fold, f, pack)\nt = (type(a), type(b))\nif t == (tuple, tuple):\n- return tuple(map(_binary_lattice_join, a, b))\n+ return pack(map(recur, a, b))\nelif t == (tuple, bool):\n- return tuple(map(_binary_lattice_join, a, (b,) * len(a)))\n+ return pack(map(recur, a, (b,) * len(a)))\nelif t == (bool, tuple):\n- return tuple(map(_binary_lattice_join, (a,) * len(b), b))\n+ return pack(map(recur, (a,) * len(b), b))\nelif t == (bool, bool):\n- return a or b\n+ return f(a, b)\nelse:\nraise TypeError((type(a), type(b)))\n+_binary_lattice_join = partial(_binary_lattice_fold, operator.or_, tuple)\n+_binary_lattice_eq = partial(_binary_lattice_fold, operator.eq, all)\n+\ndef _scan_partial_eval(trace, *tracers, **kwargs):\njaxpr = kwargs.pop('jaxpr')\n@@ -675,7 +681,7 @@ def _scan_partial_eval(trace, *tracers, **kwargs):\njaxpr_1, jaxpr_2, sc_out = pe.partial_eval_jaxpr(jaxpr, second_components,\ninstantiate=(sc_carry, False))\nsc_carry_out, sc_ys = sc_out\n- if sc_carry_out == sc_carry:\n+ if _binary_lattice_eq(sc_carry_out, sc_carry):\nbreak\nelse:\nsc_carry = _binary_lattice_join(sc_carry, sc_carry_out)\n@@ -858,7 +864,7 @@ def _scan_batching_rule(batched_args, batch_dims, forward, length, jaxpr):\njaxpr_batched, batched_out = batching.batch_jaxpr(jaxpr, size, which_batched,\ninstantiate=(carry_batched, False))\ncarry_batched_out, ys_batched = batched_out\n- if carry_batched_out == carry_batched:\n+ if _binary_lattice_eq(carry_batched_out, carry_batched):\nbreak\nelse:\ncarry_batched = _binary_lattice_join(carry_batched_out, carry_batched)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -787,6 +787,26 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nans = api.vmap(lambda c, as_: lax.scan(f, c, as_), in_axes)(c, as_)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testIssue757(self):\n+ # code from https://github.com/google/jax/issues/757\n+ def fn(a):\n+ return np.cos(a)\n+\n+ def loop(val):\n+ iterations = 10\n+ def apply_carry(x, i):\n+ return api.grad(fn, argnums=(0,))(x)[0], i\n+\n+ final_val, _ = lax.scan(\n+ apply_carry,\n+ val,\n+ np.arange(iterations)\n+ )\n+ return final_val\n+\n+ arg = 0.5\n+ print(api.jit(api.jacfwd(loop, argnums=(0,)))(arg))\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | compare binary lattice prefixes in scan
fixes #757 |
260,335 | 22.05.2019 14:38:49 | 25,200 | a193b3592bba6cc62a7ad4076f37f2f18507a8d6 | when xla_computation sees no kwargs, don't make () | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -175,8 +175,14 @@ def xla_computation(fun, static_argnums=()):\n@wraps(fun)\ndef computation_maker(*args, **kwargs):\nwrapped = lu.wrap_init(fun)\n- jax_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\njax_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\n+ if not kwargs:\n+ jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(wrapped, in_trees)\n+ pvals = map(pv_like, jax_args)\n+ jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals)\n+ return xla.build_jaxpr(jaxpr, consts, *map(xla.abstractify, jax_args))\n+ else:\n+ jax_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\njaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun2(wrapped, kwargs_tree, in_trees)\npvals = map(pv_like, (jax_kwargs,) + tuple(jax_args))\njaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals)\n"
}
] | Python | Apache License 2.0 | google/jax | when xla_computation sees no kwargs, don't make () |
260,335 | 22.05.2019 15:59:30 | 25,200 | 09b229969f16beb507e6437c7db6cbc8411ee5de | patch utility functions in batching.py
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -252,14 +252,16 @@ def reducer_batcher(prim, batched_args, batch_dims, axes, **params):\ndef add_batched(batched_args, batch_dims):\nbdx, bdy = batch_dims\n- xs, ys = batched_args\n- if bdx == bdy:\n- return add_jaxvals_p.bind(xs, ys), bdx\n+ x, y = batched_args\n+ x_aval, y_aval = map(get_aval, batched_args)\n+ assert core.skip_checks or x_aval == y_aval\n+ if bdx == bdy or x_aval == AbstractTuple(()):\n+ return add_jaxvals_p.bind(x, y), bdx\nelse:\n- sz = (dimsize(bdx, xs) | dimsize(bdy, ys)).pop()\n+ sz = (dimsize(bdx, x) | dimsize(bdy, y)).pop()\nmove_bdim = partial(bdim_at_front, broadcast_size=sz, force_broadcast=True)\n- xs, ys = map(move_bdim, batched_args, batch_dims)\n- return add_jaxvals_p.bind(xs, ys), 0\n+ x, y = map(move_bdim, batched_args, batch_dims)\n+ return add_jaxvals_p.bind(x, y), 0\nprimitive_batchers[add_jaxvals_p] = add_batched\ndef zeros_like_batched(batched_args, batch_dims):\n@@ -409,21 +411,18 @@ def instantiate_bdim(size, axis, instantiate, bdim, x):\n\"\"\"\ndef _inst(instantiate, bdim, x):\nif type(instantiate) is tuple:\n- assert type(bdim) is tuple # instantiate at same granularity as bdim\n+ if type(bdim) is tuple:\nreturn core.pack(map(_inst, instantiate, bdim, x))\n- elif type(instantiate) is bool:\n- if not instantiate:\n- if bdim is None:\n- return x\n- elif type(bdim) is int:\n- return moveaxis2(bdim, axis, x)\n- else:\n- raise TypeError(type(bdim))\nelse:\n+ bdims = (bdim,) * len(instantiate)\n+ return core.pack(map(_inst, instantiate, bdims, x))\n+ elif type(instantiate) is bool:\nif bdim is None:\n- return broadcast2(size, axis, x)\n+ return broadcast2(size, axis, x) if instantiate else x\nelif type(bdim) is int:\nreturn moveaxis2(bdim, axis, x)\n+ elif type(bdim) is tuple:\n+ return pack(map(partial(_inst, instantiate), bdim, x))\nelse:\nraise TypeError(type(bdim))\nelse:\n@@ -449,7 +448,7 @@ def broadcast2(size, axis, x):\nreturn _broadcast2(size, axis, x, get_aval(x))\ndef _broadcast2(size, axis, x, aval):\n- if type(aval) is JaxTuple:\n+ if type(aval) is AbstractTuple:\nreturn core.pack(map(partial(_broadcast2, size, axis), x, aval))\nelse:\n# see comment at the top of this section\n@@ -460,13 +459,13 @@ def _broadcast2(size, axis, x, aval):\ndef _promote_aval_rank(n, batched, aval):\nassert isinstance(aval, core.AbstractValue)\n- if isinstance(aval, core.AbstractTuple):\n+ if isinstance(aval, AbstractTuple):\nt = type(batched)\nif t is tuple:\n- return core.AbstractTuple(map(partial(_promote_aval_rank, n), batched, aval))\n+ return AbstractTuple(map(partial(_promote_aval_rank, n), batched, aval))\nelif t is bool:\nif batched:\n- return core.AbstractTuple(map(partial(_promote_aval_rank, n, batched), aval))\n+ return AbstractTuple(map(partial(_promote_aval_rank, n, batched), aval))\nelse:\nreturn aval\nelse:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/optimizers_test.py",
"new_path": "tests/optimizers_test.py",
"diff": "@@ -24,8 +24,9 @@ import numpy as onp\nimport jax.numpy as np\nimport jax.test_util as jtu\n-from jax import jit, grad\n+from jax import jit, grad, jacfwd, jacrev\nfrom jax import core, tree_util\n+from jax import lax\nfrom jax.experimental import optimizers\nfrom jax.interpreters import xla\n@@ -244,7 +245,48 @@ class OptimizerTests(jtu.JaxTestCase):\nexpected = 0.9 * norm\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testIssue758(self):\n+ # code from https://github.com/google/jax/issues/758\n+ # this is more of a scan + jacfwd/jacrev test, but it lives here to use the\n+ # optimizers.py code\n+ def harmonic_bond(conf, params):\n+ return np.sum(conf * params)\n+\n+ opt_init, opt_update, get_params = optimizers.sgd(5e-2)\n+\n+ x0 = onp.array([0.5], dtype=onp.float64)\n+ params = onp.array([0.3], dtype=onp.float64)\n+\n+ def minimize_structure(test_params):\n+ energy_fn = functools.partial(harmonic_bond, params=test_params)\n+ grad_fn = grad(energy_fn, argnums=(0,))\n+ opt_state = opt_init(x0)\n+\n+ def apply_carry(carry, _):\n+ i, x = carry\n+ g = grad_fn(get_params(x))[0]\n+ new_state = opt_update(i, g, x)\n+ new_carry = (i+1, new_state)\n+ return new_carry, _\n+\n+ carry_final, _ = lax.scan(apply_carry, (0, opt_state), np.zeros((75, 0)))\n+ trip, opt_final = carry_final\n+ assert trip == 75\n+ return opt_final\n+\n+ initial_params = 0.5\n+ minimize_structure(initial_params)\n+\n+ def loss(test_params):\n+ opt_final = minimize_structure(test_params)\n+ return 1.0 - get_params(opt_final)[0]\n+\n+ loss_opt_init, loss_opt_update, loss_get_params = optimizers.sgd(5e-2)\n+\n+ J1 = jacrev(loss, argnums=(0,))(initial_params)\n+ J2 = jacfwd(loss, argnums=(0,))(initial_params)\n+ self.assertAllClose(J1, J2, check_dtypes=True)\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | patch utility functions in batching.py
fixes #758 |
260,335 | 22.05.2019 16:04:16 | 25,200 | 86ad8e0456351dd9ae1ddaf8060d8e5f407703fe | make a batching.py utility function more defensive | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -413,9 +413,11 @@ def instantiate_bdim(size, axis, instantiate, bdim, x):\nif type(instantiate) is tuple:\nif type(bdim) is tuple:\nreturn core.pack(map(_inst, instantiate, bdim, x))\n- else:\n+ elif type(bdim) is int or bdim is None:\nbdims = (bdim,) * len(instantiate)\nreturn core.pack(map(_inst, instantiate, bdims, x))\n+ else:\n+ raise TypeError(type(bdim))\nelif type(instantiate) is bool:\nif bdim is None:\nreturn broadcast2(size, axis, x) if instantiate else x\n"
}
] | Python | Apache License 2.0 | google/jax | make a batching.py utility function more defensive |
260,335 | 22.05.2019 16:22:12 | 25,200 | 93e201f85ba2721ef51ac7f06d0e30c794290f37 | make jax.random default dtypes 64-bit
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -226,19 +226,21 @@ def _check_shape(name, shape):\nraise ValueError(msg.format(name, shape))\n-def uniform(key, shape, dtype=onp.float32, minval=0., maxval=1.):\n+def uniform(key, shape, dtype=onp.float64, minval=0., maxval=1.):\n\"\"\"Sample uniform random values in [minval, maxval) with given shape/dtype.\nArgs:\nkey: a PRNGKey used as the random key.\nshape: a tuple of nonnegative integers representing the shape.\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nminval: optional, a minimum (inclusive) value for the range (default 0).\nmaxval: optional, a maximum (exclusive) value for the range (default 1).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _uniform(key, shape, dtype, minval, maxval)\n@partial(jit, static_argnums=(1, 2))\n@@ -247,7 +249,6 @@ def _uniform(key, shape, dtype, minval, maxval):\nif not onp.issubdtype(dtype, onp.floating):\nraise TypeError(\"uniform only accepts floating point dtypes.\")\n- dtype = xla_bridge.canonicalize_dtype(dtype)\nminval = lax.convert_element_type(minval, dtype)\nmaxval = lax.convert_element_type(maxval, dtype)\nfinfo = onp.finfo(dtype)\n@@ -271,7 +272,7 @@ def _uniform(key, shape, dtype, minval, maxval):\nlax.reshape(floats * (maxval - minval) + minval, shape))\n-def randint(key, shape, minval, maxval, dtype=onp.int32):\n+def randint(key, shape, minval, maxval, dtype=onp.int64):\n\"\"\"Sample uniform random values in [minval, maxval) with given shape/dtype.\nArgs:\n@@ -281,20 +282,21 @@ def randint(key, shape, minval, maxval, dtype=onp.int32):\n(inclusive) value for the range.\nmaxval: int or array of ints broadcast-compatible with ``shape``, a maximum\n(exclusive) value for the range.\n- dtype: optional, an int dtype for the returned values (default int32).\n+ dtype: optional, an int dtype for the returned values (default int64 if\n+ jax_enable_x64 is true, otherwise int32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _randint(key, shape, minval, maxval, dtype)\n@partial(jit, static_argnums=(1, 4))\n-def _randint(key, shape, minval, maxval, dtype=onp.int32):\n+def _randint(key, shape, minval, maxval, dtype):\n_check_shape(\"randint\", shape)\nif not onp.issubdtype(dtype, onp.integer):\nraise TypeError(\"randint only accepts integer dtypes.\")\n- dtype = xla_bridge.canonicalize_dtype(dtype)\nminval = lax.convert_element_type(minval, dtype)\nmaxval = lax.convert_element_type(maxval, dtype)\nnbits = onp.iinfo(dtype).bits\n@@ -371,17 +373,19 @@ def _shuffle(key, x, axis):\nreturn x\n-def normal(key, shape, dtype=onp.float32):\n+def normal(key, shape, dtype=onp.float64):\n\"\"\"Sample standard normal random values with given shape and float dtype.\nArgs:\nkey: a PRNGKey used as the random key.\nshape: a tuple of nonnegative integers representing the shape.\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _normal(key, shape, dtype)\n@partial(jit, static_argnums=(1, 2))\n@@ -412,14 +416,14 @@ def bernoulli(key, p=onp.float32(0.5), shape=()):\ndef _bernoulli(key, p, shape):\n_check_shape(\"bernoulli\", shape)\nshape = shape or onp.shape(p)\n- if not onp.issubdtype(onp.float32, lax.dtype(p)):\n- p = lax.convert_element_type(p, onp.float32)\n+ if not onp.issubdtype(onp.float64, lax.dtype(p)):\n+ p = lax.convert_element_type(p, onp.float64)\nif onp.shape(p) != shape:\np = np.broadcast_to(p, shape)\nreturn lax.lt(uniform(key, shape, lax.dtype(p)), p)\n-def beta(key, a, b, shape=(), dtype=onp.float32):\n+def beta(key, a, b, shape=(), dtype=onp.float64):\n\"\"\"Sample Bernoulli random values with given shape and mean.\nArgs:\n@@ -430,11 +434,13 @@ def beta(key, a, b, shape=(), dtype=onp.float32):\nbeta of the random variables.\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _beta(key, a, b, shape, dtype)\n@partial(jit, static_argnums=(3, 4))\n@@ -449,18 +455,20 @@ def _beta(key, a, b, shape, dtype):\nreturn gamma_a / (gamma_a + gamma_b)\n-def cauchy(key, shape=(), dtype=onp.float32):\n+def cauchy(key, shape=(), dtype=onp.float64):\n\"\"\"Sample Cauchy random values with given shape and float dtype.\nArgs:\nkey: a PRNGKey used as the random key.\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _cauchy(key, shape, dtype)\n@partial(jit, static_argnums=(1, 2))\n@@ -471,7 +479,7 @@ def _cauchy(key, shape, dtype):\nreturn lax.tan(lax.mul(pi, lax.sub(u, _constant_like(u, 0.5))))\n-def dirichlet(key, alpha, shape=(), dtype=onp.float32):\n+def dirichlet(key, alpha, shape=(), dtype=onp.float64):\n\"\"\"Sample Cauchy random values with given shape and float dtype.\nArgs:\n@@ -480,11 +488,13 @@ def dirichlet(key, alpha, shape=(), dtype=onp.float32):\nused as the concentration parameter of the random variables.\nshape: optional, a tuple of nonnegative integers representing the batch\nshape (defaults to `alpha.shape[:-1]`).\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _dirichlet(key, alpha, shape, dtype)\n@partial(jit, static_argnums=(2, 3))\n@@ -496,18 +506,20 @@ def _dirichlet(key, alpha, shape, dtype):\nreturn gamma_samples / np.sum(gamma_samples, axis=-1, keepdims=True)\n-def exponential(key, shape=(), dtype=onp.float32):\n+def exponential(key, shape=(), dtype=onp.float64):\n\"\"\"Sample Exponential random values with given shape and float dtype.\nArgs:\nkey: a PRNGKey used as the random key.\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _exponential(key, shape, dtype)\n@partial(jit, static_argnums=(1, 2))\n@@ -568,7 +580,7 @@ def _gamma_one(key, alpha):\nreturn lax.select(lax.eq(z, zero), onp.finfo(z.dtype).tiny, z)\n-def gamma(key, a, shape=(), dtype=onp.float32):\n+def gamma(key, a, shape=(), dtype=onp.float64):\n\"\"\"Sample Gamma random values with given shape and float dtype.\nArgs:\n@@ -577,15 +589,17 @@ def gamma(key, a, shape=(), dtype=onp.float32):\nof the random variables.\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _gamma(key, a, shape, dtype)\n@partial(jit, static_argnums=(2, 3))\n-def _gamma(key, a, shape=(), dtype=onp.float32):\n+def _gamma(key, a, shape, dtype):\n_check_shape(\"gamma\", shape)\na = lax.convert_element_type(a, dtype)\nshape = shape or onp.shape(a)\n@@ -597,18 +611,20 @@ def _gamma(key, a, shape=(), dtype=onp.float32):\nreturn np.reshape(samples, shape)\n-def gumbel(key, shape=(), dtype=onp.float32):\n+def gumbel(key, shape=(), dtype=onp.float64):\n\"\"\"Sample Gumbel random values with given shape and float dtype.\nArgs:\nkey: a PRNGKey used as the random key.\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _gumbel(key, shape, dtype)\n@partial(jit, static_argnums=(1, 2))\n@@ -617,18 +633,20 @@ def _gumbel(key, shape, dtype):\nreturn -np.log(-np.log(uniform(key, shape, dtype)))\n-def laplace(key, shape=(), dtype=onp.float32):\n+def laplace(key, shape=(), dtype=onp.float64):\n\"\"\"Sample Laplace random values with given shape and float dtype.\nArgs:\nkey: a PRNGKey used as the random key.\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _laplace(key, shape, dtype)\n@partial(jit, static_argnums=(1, 2))\n@@ -638,7 +656,7 @@ def _laplace(key, shape, dtype):\nreturn lax.mul(lax.sign(u), lax.log1p(lax.neg(lax.abs(u))))\n-def pareto(key, b, shape=(), dtype=onp.float32):\n+def pareto(key, b, shape=(), dtype=onp.float64):\n\"\"\"Sample Pareto random values with given shape and float dtype.\nArgs:\n@@ -647,11 +665,13 @@ def pareto(key, b, shape=(), dtype=onp.float32):\nof the random variables.\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _pareto(key, b, shape, dtype)\n@partial(jit, static_argnums=(2, 3))\n@@ -665,7 +685,7 @@ def _pareto(key, b, shape, dtype):\nreturn lax.exp(lax.div(e, b))\n-def t(key, df, shape=(), dtype=onp.float32):\n+def t(key, df, shape=(), dtype=onp.float64):\n\"\"\"Sample Student's t random values with given shape and float dtype.\nArgs:\n@@ -674,11 +694,13 @@ def t(key, df, shape=(), dtype=onp.float32):\nof the random variables.\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\n- dtype: optional, a float dtype for the returned values (default float32).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\nreturn _t(key, df, shape, dtype)\n@partial(jit, static_argnums=(2, 3))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -358,6 +358,14 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertRaisesRegex(ValueError, re.compile(r'.*requires a concrete.*'),\nlambda: feature_map(5, 3))\n+ def testIssue756(self):\n+ key = random.PRNGKey(0)\n+ w = random.normal(key, ())\n+ if FLAGS.jax_enable_x64:\n+ self.assertEqual(onp.result_type(w), onp.float64)\n+ else:\n+ self.assertEqual(onp.result_type(w), onp.float32)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | make jax.random default dtypes 64-bit
fixes #756 |
260,335 | 23.05.2019 06:51:16 | 25,200 | c30667941a6226572b79ff12097d324e25112a56 | improve scan error message when output is not pair | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -570,7 +570,11 @@ def scan(f, init, xs):\njaxpr, pval_out, consts = pe.trace_to_jaxpr(\nf, (carry_pval, x_pval), instantiate=True)\npv_out, const_out = pval_out\n- assert isinstance(pv_out, core.AbstractTuple) and const_out == core.unit\n+ assert isinstance(pv_out, core.AbstractValue) and const_out == core.unit\n+ if not isinstance(pv_out, core.AbstractTuple) or len(pv_out) != 2:\n+ msg = (\"scanned function must have signature `c -> a -> (c, b)`, but the \"\n+ \"output was not a pair: got type {}.\")\n+ raise TypeError(msg.format(pv_out))\ncarry_aval_out, y_aval = pv_out\nif carry_aval != carry_aval_out:\nmsg = (\"scanned function carry output does not match carry input: \"\n"
}
] | Python | Apache License 2.0 | google/jax | improve scan error message when output is not pair |
260,335 | 23.05.2019 09:07:44 | 25,200 | 92e5f93a290ec8146ab6a667abe54adbf39d61ff | tweak docstrings in mnist examples | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "examples/fluidsim.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+def project(vx, vy):\n+ h = 1. / vx.shape[0]\n+ div = -0.5 * h * (np.roll(vx, -1, axis=0) - np.roll(vx, 1, axis=0) +\n+ np.roll(vy, -1, axis=1) - np.roll(vy, 1, axis=1))\n+\n+ p = np.zeros(vx.shape)\n+ for k in range(10):\n+ p = (div + np.roll(p, 1, axis=0) + np.roll(p, -1, axis=0)\n+ + np.roll(p, 1, axis=1) + np.roll(p, -1, axis=1)) / 4.\n+\n+ vx = vx - 0.5 * (np.roll(p, -1, axis=0) - np.roll(p, 1, axis=0)) / h\n+ vy = vy - 0.5 * (np.roll(p, -1, axis=1) - np.roll(p, 1, axis=1)) / h\n+ return vx, vy\n+\n+def advect(f, vx, vy):\n+ rows, cols = f.shape\n+ cell_ys, cell_xs = np.meshgrid(np.arange(rows), np.arange(cols))\n+ return linear_interpolate(f, cell_xs - vx, cell_ys - vy)\n+\n+def linear_interpolate(\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "examples/mnist_bench.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 JAX together with the mini-libraries stax, for\n+neural network building, and optimizers, for first-order stochastic optimization.\n+\"\"\"\n+\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+import time\n+import itertools\n+\n+import numpy.random as npr\n+\n+import jax.numpy as np\n+from jax.config import config\n+from jax import jit, grad, random\n+from jax.experimental import optimizers\n+from jax.experimental import stax\n+from jax.experimental.stax import Dense, Relu, LogSoftmax\n+from examples import datasets\n+\n+\n+def loss(params, batch):\n+ inputs, targets = batch\n+ preds = predict(params, inputs)\n+ return -np.mean(preds * targets)\n+\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+init_random_params, predict = stax.serial(\n+ Dense(1024), Relu,\n+ Dense(1024), Relu,\n+ Dense(10), LogSoftmax)\n+\n+if __name__ == \"__main__\":\n+ rng = random.PRNGKey(0)\n+\n+ step_size = 0.001\n+ num_epochs = 3\n+ batch_size = 128\n+ momentum_mass = 0.9\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+ 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+ yield train_images[batch_idx], train_labels[batch_idx]\n+ batches = data_stream()\n+\n+ opt_init, opt_update = optimizers.momentum(step_size, mass=momentum_mass)\n+\n+ @jit\n+ def update(i, opt_state, batch):\n+ params = optimizers.get_params(opt_state)\n+ return opt_update(i, grad(loss)(params, batch), opt_state)\n+\n+ _, init_params = init_random_params(rng, (-1, 28 * 28))\n+ opt_state = opt_init(init_params)\n+ itercount = itertools.count()\n+\n+ print(\"\\nStarting training...\")\n+ for epoch in range(num_epochs):\n+ start_time = time.time()\n+ for _ in range(num_batches):\n+ opt_state = update(next(itercount), opt_state, next(batches))\n+ epoch_time = time.time() - start_time\n+\n+ params = optimizers.get_params(opt_state)\n+ train_acc = accuracy(params, (train_images, train_labels))\n+ test_acc = accuracy(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": "examples/mnist_classifier.py",
"new_path": "examples/mnist_classifier.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-\"\"\"A basic MNIST example using JAX together with the mini-libraries stax, for\n-neural network building, and optimizers, for first-order stochastic optimization.\n+\"\"\"A basic MNIST example using JAX with the mini-libraries stax and optimizers.\n+\n+The mini-library jax.experimental.stax is for neural network building, and\n+the mini-library jax.experimentaloptimizers is for first-order stochastic\n+optimization.\n\"\"\"\nfrom __future__ import absolute_import\n"
},
{
"change_type": "MODIFY",
"old_path": "examples/spmd_mnist_classifier_fromscratch.py",
"new_path": "examples/spmd_mnist_classifier_fromscratch.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-\"\"\"A basic MNIST example using Numpy and JAX.\n+\"\"\"An MNIST example with single-program multiple-data (SPMD) data parallelism.\n-The primary aim here is simplicity and minimal dependencies.\n+The aim here is to illustrate how to use JAX's `pmap` to express and execute\n+SPMD programs for data parallelism along a batch dimension, while also\n+minimizing dependencies by avoiding the use of higher-level layers and\n+optimizers libraries.\n\"\"\"\nfrom __future__ import absolute_import\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "examples/spmd_spatially_sharded_conv_net.py",
"diff": "+# Copyright 2019 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+\n+\"\"\"An MNIST example for single-program multiple-data (SPMD) spatial parallelism.\n+\n+The aim here is to illustrate how to use JAX's `pmap` to express and execute\n+SPMD programs for data parallelism along a spatial dimension (rather than a\n+batch dimension).\n+\"\"\"\n+\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+import time\n+import itertools\n+\n+import numpy.random as npr\n+\n+import jax.numpy as np\n+from jax.config import config\n+from jax import jit, grad, random\n+from jax.experimental import optimizers\n+from jax.experimental import stax\n+from jax.experimental.stax import Relu, LogSoftmax\n+from examples import datasets\n+\n+\n+def loss(params, batch):\n+ inputs, targets = batch\n+ preds = predict(params, inputs)\n+ return -np.mean(preds * targets)\n+\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+init_random_params, predict = stax.serial(\n+ SpmdConv(3, (2, 2), axis_name=\"x\"), Relu,\n+ SpmdConv(3, (2, 2), axis_name=\"x\"), Relu,\n+ SpmdDense(10), LogSoftmax)\n"
}
] | Python | Apache License 2.0 | google/jax | tweak docstrings in mnist examples |
260,335 | 23.05.2019 11:28:15 | 25,200 | 8ffb9417e7a49201195704ede4b8731fd4975c3d | fix stax initialization rng bug, remove temp file | [
{
"change_type": "DELETE",
"old_path": "examples/spmd_spatially_sharded_conv_net.py",
"new_path": null,
"diff": "-# Copyright 2019 Google LLC\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-\n-\"\"\"An MNIST example for single-program multiple-data (SPMD) spatial parallelism.\n-\n-The aim here is to illustrate how to use JAX's `pmap` to express and execute\n-SPMD programs for data parallelism along a spatial dimension (rather than a\n-batch dimension).\n-\"\"\"\n-\n-from __future__ import absolute_import\n-from __future__ import division\n-from __future__ import print_function\n-\n-import time\n-import itertools\n-\n-import numpy.random as npr\n-\n-import jax.numpy as np\n-from jax.config import config\n-from jax import jit, grad, random\n-from jax.experimental import optimizers\n-from jax.experimental import stax\n-from jax.experimental.stax import Relu, LogSoftmax\n-from examples import datasets\n-\n-\n-def loss(params, batch):\n- inputs, targets = batch\n- preds = predict(params, inputs)\n- return -np.mean(preds * targets)\n-\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-init_random_params, predict = stax.serial(\n- SpmdConv(3, (2, 2), axis_name=\"x\"), Relu,\n- SpmdConv(3, (2, 2), axis_name=\"x\"), Relu,\n- SpmdDense(10), LogSoftmax)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -64,13 +64,13 @@ def randn(stddev=1e-2):\nreturn (stddev * random.normal(rng, shape)).astype('float32')\nreturn init\n-def glorot(out_dim=0, in_dim=1, scale=onp.sqrt(2)):\n+def glorot(out_axis=0, in_axis=1, scale=onp.sqrt(2)):\n\"\"\"An initializer function for random Glorot-scaled coefficients.\"\"\"\ndef init(rng, shape):\n- fan_in, fan_out = shape[in_dim], shape[out_dim]\n- size = onp.prod(onp.delete(shape, [in_dim, out_dim]))\n+ fan_in, fan_out = shape[in_axis], shape[out_axis]\n+ size = onp.prod(onp.delete(shape, [in_axis, out_axis]))\nstd = scale / np.sqrt((fan_in + fan_out) / 2. * size)\n- return (std * random.normal(rng, shape)).astype('float32')\n+ return std * random.normal(rng, shape, dtype=np.float32)\nreturn init\nzeros = lambda rng, shape: np.zeros(shape, dtype='float32')\n@@ -89,7 +89,8 @@ def Dense(out_dim, W_init=glorot(), b_init=randn()):\n\"\"\"Layer constructor function for a dense (fully-connected) layer.\"\"\"\ndef init_fun(rng, input_shape):\noutput_shape = input_shape[:-1] + (out_dim,)\n- W, b = W_init(rng, (input_shape[-1], out_dim)), b_init(rng, (out_dim,))\n+ k1, k2 = random.split(rng)\n+ W, b = W_init(k1, (input_shape[-1], out_dim)), b_init(k2, (out_dim,))\nreturn output_shape, (W, b)\ndef apply_fun(params, inputs, **kwargs):\nW, b = params\n@@ -113,7 +114,8 @@ def GeneralConv(dimension_numbers, out_chan, filter_shape,\ninput_shape, kernel_shape, strides, padding, dimension_numbers)\nbias_shape = [out_chan if c == 'C' else 1 for c in out_spec]\nbias_shape = tuple(itertools.dropwhile(lambda x: x == 1, bias_shape))\n- W, b = W_init(rng, kernel_shape), b_init(rng, bias_shape)\n+ k1, k2 = random.split(rng)\n+ W, b = W_init(k1, kernel_shape), b_init(k2, bias_shape)\nreturn output_shape, (W, b)\ndef apply_fun(params, inputs, **kwargs):\nW, b = params\n@@ -140,7 +142,8 @@ def GeneralConvTranspose(dimension_numbers, out_chan, filter_shape,\ninput_shape, kernel_shape, strides, padding, dimension_numbers)\nbias_shape = [out_chan if c == 'C' else 1 for c in out_spec]\nbias_shape = tuple(itertools.dropwhile(lambda x: x == 1, bias_shape))\n- W, b = W_init(rng, kernel_shape), b_init(rng, bias_shape)\n+ k1, k2 = random.split(rng)\n+ W, b = W_init(k1, kernel_shape), b_init(k2, bias_shape)\nreturn output_shape, (W, b)\ndef apply_fun(params, inputs, **kwargs):\nW, b = params\n@@ -160,7 +163,8 @@ def BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True,\naxis = (axis,) if np.isscalar(axis) else axis\ndef init_fun(rng, input_shape):\nshape = tuple(d for i, d in enumerate(input_shape) if i not in axis)\n- beta, gamma = _beta_init(rng, shape), _gamma_init(rng, shape)\n+ k1, k2 = random.split(rng)\n+ beta, gamma = _beta_init(k1, shape), _gamma_init(k2, shape)\nreturn input_shape, (beta, gamma)\ndef apply_fun(params, x, **kwargs):\nbeta, gamma = params\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -424,15 +424,30 @@ class ShardedDeviceArray(xla.DeviceArray):\nself.ndim, self.size = len(aval.shape), prod(aval.shape)\nself._npy_value = None\n+ def _ids(self):\n+ num_bufs = len(self.device_buffers)\n+ assignments = assign_shards_to_replicas(num_bufs, self.shape[0])\n+ _, ids = onp.unique(assignments, return_index=True)\n+ return ids\n+\n@property\ndef _value(self):\nif self._npy_value is None:\n+ ids = self._ids()\nnpy_shards = [buf.to_py() for buf in self.device_buffers]\n- assignments = assign_shards_to_replicas(len(npy_shards), self.shape[0])\n- _, ids = onp.unique(assignments, return_index=True)\nself._npy_value = onp.stack([npy_shards[i] for i in ids])\nreturn self._npy_value\n+ def __getitem__(self, idx):\n+ if self._npy_value is None and type(idx) is int:\n+ # When we don't have a copy of the data on the host, and we're just trying\n+ # to extract a simple integer-indexed slice of the logical array, we can\n+ # avoid transferring from all the devices and just communicate with one.\n+ ids = self._ids()\n+ return self.device_buffers[ids[idx]].to_py()\n+ else:\n+ return super(ShardedDeviceArray, self).__getitem__(idx)\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 | fix stax initialization rng bug, remove temp file |
260,335 | 23.05.2019 12:57:58 | 25,200 | 913bc6b508daf0121ef4307fa607dede5b2ccfd8 | fix stax dtype breakage | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -60,8 +60,9 @@ def fastvar(x, axis, keepdims):\ndef randn(stddev=1e-2):\n\"\"\"An initializer function for random normal coefficients.\"\"\"\n+ stddev = lax.convert_element_type(stddev, np.float32)\ndef init(rng, shape):\n- return (stddev * random.normal(rng, shape)).astype('float32')\n+ return stddev * random.normal(rng, shape, dtype=np.float32)\nreturn init\ndef glorot(out_axis=0, in_axis=1, scale=onp.sqrt(2)):\n@@ -70,6 +71,7 @@ def glorot(out_axis=0, in_axis=1, scale=onp.sqrt(2)):\nfan_in, fan_out = shape[in_axis], shape[out_axis]\nsize = onp.prod(onp.delete(shape, [in_axis, out_axis]))\nstd = scale / np.sqrt((fan_in + fan_out) / 2. * size)\n+ std = lax.convert_element_type(std, np.float32)\nreturn std * random.normal(rng, shape, dtype=np.float32)\nreturn init\n"
}
] | Python | Apache License 2.0 | google/jax | fix stax dtype breakage |
260,335 | 24.05.2019 10:44:33 | 25,200 | 2802c8f51434403fad17a8407848597d799a433d | try pinning travis to jaxlib==0.1.15
Currently Travis CI builds are failing in a way we can't reproduce
locally. | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -21,7 +21,7 @@ before_install:\n- conda config --add channels conda-forge\ninstall:\n- conda install --yes python=$TRAVIS_PYTHON_VERSION pip six protobuf>=3.6.0 absl-py opt_einsum numpy scipy pytest-xdist\n- - pip install jaxlib\n+ - pip install jaxlib==0.1.15\n- pip install -v .\nscript:\n- pytest -n 2 tests examples -W ignore\n"
}
] | Python | Apache License 2.0 | google/jax | try pinning travis to jaxlib==0.1.15
Currently Travis CI builds are failing in a way we can't reproduce
locally. |
260,335 | 24.05.2019 19:02:40 | 25,200 | 6fe6cb0dbe3c55ebffe260f596896bafa3b24367 | try fixing travis by using only one pytest job | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -21,7 +21,7 @@ before_install:\n- conda config --add channels conda-forge\ninstall:\n- conda install --yes python=$TRAVIS_PYTHON_VERSION pip six protobuf>=3.6.0 absl-py opt_einsum numpy scipy pytest-xdist\n- - pip install jaxlib==0.1.15\n+ - pip install jaxlib\n- pip install -v .\nscript:\n- - pytest -n 2 tests examples -W ignore\n+ - pytest -n 1 tests examples -W ignore\n"
}
] | Python | Apache License 2.0 | google/jax | try fixing travis by using only one pytest job |
260,314 | 25.05.2019 16:56:22 | 14,400 | e9ec30c096af45c420bd52d98a7908e2df753ba3 | promote args for special functions | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -27,12 +27,34 @@ from ..numpy.lax_numpy import (_wraps, asarray, _reduction_dims, _constant_like,\n_promote_args_like)\n-# need to create new functions because _wraps sets the __name__ attribute\n-gammaln = _wraps(osp_special.gammaln)(lambda x: lax.lgamma(x))\n-digamma = _wraps(osp_special.digamma)(lambda x: lax.digamma(x))\n-erf = _wraps(osp_special.erf)(lambda x: lax.erf(x))\n-erfc = _wraps(osp_special.erfc)(lambda x: lax.erfc(x))\n-erfinv = _wraps(osp_special.erfinv)(lambda x: lax.erf_inv(x))\n+@_wraps(osp_special.gammaln)\n+def gammaln(x):\n+ x = _promote_args_like(osp_special.gammaln, x)\n+ return lax.lgamma(x)\n+\n+\n+@_wraps(osp_special.digamma)\n+def digamma(x):\n+ x = _promote_args_like(osp_special.digamma, x)\n+ return lax.digamma(x)\n+\n+\n+@_wraps(osp_special.erf)\n+def erf(x):\n+ x = _promote_args_like(osp_special.erf, x)\n+ return lax.erf(x)\n+\n+\n+@_wraps(osp_special.erfc)\n+def erfc(x):\n+ x = _promote_args_like(osp_special.erfc, x)\n+ return lax.erfc(x)\n+\n+\n+@_wraps(osp_special.erfinv)\n+def erfinv(x):\n+ x = _promote_args_like(osp_special.erf_inv, x)\n+ return lax.erf_inv(x)\n@_wraps(osp_special.logit)\n"
}
] | Python | Apache License 2.0 | google/jax | promote args for special functions |
260,314 | 25.05.2019 22:45:01 | 14,400 | 57aac741ac7c5f1066168f08a8f2353d16ba569b | fix typos when getting output of promote_args | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -29,31 +29,31 @@ from ..numpy.lax_numpy import (_wraps, asarray, _reduction_dims, _constant_like,\n@_wraps(osp_special.gammaln)\ndef gammaln(x):\n- x = _promote_args_like(osp_special.gammaln, x)\n+ x, = _promote_args_like(osp_special.gammaln, x)\nreturn lax.lgamma(x)\n@_wraps(osp_special.digamma)\ndef digamma(x):\n- x = _promote_args_like(osp_special.digamma, x)\n+ x, = _promote_args_like(osp_special.digamma, x)\nreturn lax.digamma(x)\n@_wraps(osp_special.erf)\ndef erf(x):\n- x = _promote_args_like(osp_special.erf, x)\n+ x, = _promote_args_like(osp_special.erf, x)\nreturn lax.erf(x)\n@_wraps(osp_special.erfc)\ndef erfc(x):\n- x = _promote_args_like(osp_special.erfc, x)\n+ x, = _promote_args_like(osp_special.erfc, x)\nreturn lax.erfc(x)\n@_wraps(osp_special.erfinv)\ndef erfinv(x):\n- x = _promote_args_like(osp_special.erf_inv, x)\n+ x, = _promote_args_like(osp_special.erf_inv, x)\nreturn lax.erf_inv(x)\n"
}
] | Python | Apache License 2.0 | google/jax | fix typos when getting output of promote_args |
260,335 | 28.05.2019 20:25:38 | 25,200 | 743727325f4da4c2344fd3b9a9a0784eabeb76c4 | improve error message for grad of non-scalar funs | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -303,7 +303,7 @@ def _check_scalar(x):\nraise TypeError(msg(x))\nelse:\nif not (isinstance(aval, ShapedArray) and aval.shape == ()):\n- raise TypeError(msg(x))\n+ raise TypeError(msg(aval))\ndef jacfwd(fun, argnums=0, holomorphic=False):\n"
}
] | Python | Apache License 2.0 | google/jax | improve error message for grad of non-scalar funs |
260,335 | 28.05.2019 21:07:13 | 25,200 | 2bf9d5aae919098e2c8afd3b64c402c48a821387 | loosen tolerance on tanh grad test | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -82,7 +82,8 @@ LAX_OPS = [\nop_record(lax.expm1, 1, float_dtypes + complex_dtypes, jtu.rand_small()),\nop_record(lax.log, 1, float_dtypes + complex_dtypes, jtu.rand_positive()),\nop_record(lax.log1p, 1, float_dtypes + complex_dtypes, jtu.rand_positive()),\n- op_record(lax.tanh, 1, float_dtypes + complex_dtypes, jtu.rand_small()),\n+ op_record(lax.tanh, 1, float_dtypes + complex_dtypes, jtu.rand_small(),\n+ tol=1e-3),\nop_record(lax.sin, 1, float_dtypes + complex_dtypes, jtu.rand_default()),\nop_record(lax.cos, 1, float_dtypes + complex_dtypes, jtu.rand_default()),\nop_record(lax.atan2, 2, float_dtypes, jtu.rand_default()),\n"
}
] | Python | Apache License 2.0 | google/jax | loosen tolerance on tanh grad test |
260,335 | 28.05.2019 21:10:09 | 25,200 | 5a049feea9cdf88948b5a4b5f05222ac869153de | further improve grad-of-nonscalar error message | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -296,14 +296,17 @@ def value_and_grad(fun, argnums=0, has_aux=False, holomorphic=False):\nreturn value_and_grad_f\ndef _check_scalar(x):\n- msg = \"Gradient only defined for scalar-output functions. Output was: {}\".format\n+ msg = \"Gradient only defined for scalar-output functions. Output {}.\".format\ntry:\naval = core.get_aval(x)\nexcept TypeError:\n- raise TypeError(msg(x))\n+ raise TypeError(msg(\"was {}\".format(x)))\nelse:\n- if not (isinstance(aval, ShapedArray) and aval.shape == ()):\n- raise TypeError(msg(aval))\n+ if isinstance(aval, ShapedArray):\n+ if aval.shape != ():\n+ raise TypeError(msg(\"had shape: {}\".format(aval.shape)))\n+ else:\n+ raise TypeError(msg(\"had abstract value {}\".format(aval)))\ndef jacfwd(fun, argnums=0, holomorphic=False):\n"
}
] | Python | Apache License 2.0 | google/jax | further improve grad-of-nonscalar error message |
260,335 | 28.05.2019 21:36:34 | 25,200 | 3b290457c483f60bb224131dc0176f48baac6acc | move stax randn init convert_element_type later | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -60,8 +60,8 @@ def fastvar(x, axis, keepdims):\ndef randn(stddev=1e-2):\n\"\"\"An initializer function for random normal coefficients.\"\"\"\n- stddev = lax.convert_element_type(stddev, np.float32)\ndef init(rng, shape):\n+ stddev = lax.convert_element_type(stddev, np.float32)\nreturn stddev * random.normal(rng, shape, dtype=np.float32)\nreturn init\n"
}
] | Python | Apache License 2.0 | google/jax | move stax randn init convert_element_type later |
260,335 | 28.05.2019 21:48:15 | 25,200 | 9fab325a675b84da13d4788ccae88b9e820cef84 | loosen tanh grad test tolerance (2bf9d5a fix) | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -82,8 +82,7 @@ LAX_OPS = [\nop_record(lax.expm1, 1, float_dtypes + complex_dtypes, jtu.rand_small()),\nop_record(lax.log, 1, float_dtypes + complex_dtypes, jtu.rand_positive()),\nop_record(lax.log1p, 1, float_dtypes + complex_dtypes, jtu.rand_positive()),\n- op_record(lax.tanh, 1, float_dtypes + complex_dtypes, jtu.rand_small(),\n- tol=1e-3),\n+ op_record(lax.tanh, 1, float_dtypes + complex_dtypes, jtu.rand_small()),\nop_record(lax.sin, 1, float_dtypes + complex_dtypes, jtu.rand_default()),\nop_record(lax.cos, 1, float_dtypes + complex_dtypes, jtu.rand_default()),\nop_record(lax.atan2, 2, float_dtypes, jtu.rand_default()),\n@@ -1405,9 +1404,9 @@ class DeviceConstantTest(jtu.JaxTestCase):\nGradTestSpec = collections.namedtuple(\n- \"GradTestSpec\", [\"op\", \"nargs\", \"order\", \"rng\", \"dtypes\", \"name\"])\n-def grad_test_spec(op, nargs, order, rng, dtypes, name=None):\n- return GradTestSpec(op, nargs, order, rng, dtypes, name or op.__name__)\n+ \"GradTestSpec\", [\"op\", \"nargs\", \"order\", \"rng\", \"dtypes\", \"name\", \"tol\"])\n+def grad_test_spec(op, nargs, order, rng, dtypes, name=None, tol=None):\n+ return GradTestSpec(op, nargs, order, rng, dtypes, name or op.__name__, tol)\nLAX_GRAD_OPS = [\ngrad_test_spec(lax.neg, nargs=1, order=2, rng=jtu.rand_default(),\n@@ -1430,7 +1429,7 @@ LAX_GRAD_OPS = [\ngrad_test_spec(lax.log1p, nargs=1, order=2, rng=jtu.rand_positive(),\ndtypes=[onp.float64, onp.complex64]),\ngrad_test_spec(lax.tanh, nargs=1, order=2, rng=jtu.rand_default(),\n- dtypes=[onp.float64, onp.complex64]),\n+ dtypes=[onp.float64, onp.complex64], tol=1e-5),\ngrad_test_spec(lax.sin, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\ngrad_test_spec(lax.cos, nargs=1, order=2, rng=jtu.rand_default(),\n@@ -1502,16 +1501,16 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n{\"testcase_name\": jtu.format_test_name_suffix(\nrec.name, shapes, itertools.repeat(dtype)),\n\"op\": rec.op, \"rng\": rec.rng, \"shapes\": shapes, \"dtype\": dtype,\n- \"order\": rec.order}\n+ \"order\": rec.order, \"tol\": rec.tol}\nfor shape_group in compatible_shapes\nfor shapes in CombosWithReplacement(shape_group, rec.nargs)\nfor dtype in rec.dtypes)\nfor rec in LAX_GRAD_OPS))\n- def testOpGrad(self, op, rng, shapes, dtype, order):\n+ def testOpGrad(self, op, rng, shapes, dtype, order, tol):\nif FLAGS.jax_test_dut and FLAGS.jax_test_dut.startswith(\"tpu\"):\nif op is lax.pow:\nraise SkipTest(\"pow grad imprecise on tpu\")\n- tol = 1e-1 if num_float_bits(dtype) == 32 else None\n+ tol = 1e-1 if num_float_bits(dtype) == 32 else tol\nargs = tuple(rng(shape, dtype) for shape in shapes)\ncheck_grads(op, args, order, [\"fwd\", \"rev\"], tol, tol)\n"
}
] | Python | Apache License 2.0 | google/jax | loosen tanh grad test tolerance (2bf9d5a fix) |
260,335 | 28.05.2019 22:38:06 | 25,200 | 9c931ddebe4ae52877f0404c55e9d6f4a97a274e | allow more types to be jaxpr literals, fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/abstract_arrays.py",
"new_path": "jax/abstract_arrays.py",
"diff": "@@ -199,3 +199,7 @@ def raise_to_shaped(aval):\nreturn ShapedArray(aval.shape, aval.dtype)\nelse:\nraise TypeError(type(aval))\n+\n+def is_scalar(x):\n+ return isinstance(x, tuple(scalar_types)) and onp.shape(x) == ()\n+scalar_types = set(array_types)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -24,7 +24,7 @@ import six\nimport types\nfrom . import linear_util as lu\n-from .util import unzip2, safe_zip, safe_map, partial, curry\n+from .util import unzip2, safe_zip, safe_map, partial, curry, WrapHashably\nfrom .pprint_util import pp, vcat, hcat, pp_kv_pairs\n# TODO(dougalm): the trace cache breaks the leak detector. Consisder solving.\n@@ -100,7 +100,7 @@ def jaxpr_as_fun(typed_jaxpr, *args):\nJaxprEqn = namedtuple('JaxprEqn', ['invars', 'outvars', 'primitive',\n'bound_subjaxprs', 'restructure',\n'destructure', 'params'])\n-Literal = namedtuple('Literal', ['val'])\n+class Literal(WrapHashably): pass\nclass Primitive(object):\ndef __init__(self, name):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -19,9 +19,11 @@ from __future__ import print_function\nimport itertools as it\nfrom collections import namedtuple, Counter, defaultdict\n+import numpy as onp\n+\nfrom .. import core\nfrom .. import linear_util as lu\n-from ..abstract_arrays import ShapedArray, ConcreteArray\n+from ..abstract_arrays import ShapedArray, ConcreteArray, is_scalar\nfrom ..linear_util import thunk, transformation, transformation_with_aux\nfrom ..util import unzip2, safe_zip, safe_map, toposort, partial\nfrom ..core import (Trace, Tracer, new_master, Jaxpr, JaxprEqn, Literal,\n@@ -47,7 +49,7 @@ def identity(x): return x\nclass JaxprTrace(Trace):\ndef pure(self, val):\n- if type(val) in (int, float):\n+ if is_scalar(val):\nreturn JaxprTracer(self, PartialVal((None, val)), Literal(val))\nelse:\nreturn self.new_const(val)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -31,7 +31,8 @@ from .. import core\nfrom .. import ad_util\nfrom .. import tree_util\nfrom .. import linear_util as lu\n-from ..abstract_arrays import ConcreteArray, ShapedArray, make_shaped_array, array_types\n+from ..abstract_arrays import (ConcreteArray, ShapedArray, make_shaped_array,\n+ array_types, scalar_types)\nfrom ..core import AbstractTuple, JaxTuple, pack, valid_jaxtype, Literal\nfrom ..util import partial, partialmethod, memoize, unzip2, concatenate, safe_map, prod\nfrom ..lib import xla_bridge as xb\n@@ -541,6 +542,8 @@ class DeviceArray(DeviceValue):\n# fine.\nreturn id(self)\n+scalar_types.add(DeviceArray)\n+\n# DeviceValues don't need to be canonicalized because we assume values on the\n# device have already been canonicalized.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -409,8 +409,9 @@ class APITest(jtu.JaxTestCase):\n_, f2_vjp = api.vjp(f2, x)\nself.assertAllClose(f1_vjp(x), f2_vjp(x), check_dtypes=True)\n- jaxpr2 = api.make_jaxpr(f2_vjp)(x)\n- assert len(jaxpr2.constvars) == 1\n+ # TODO(mattjj): test that constants/literals are set up properly\n+ # jaxpr2 = api.make_jaxpr(f2_vjp)(x)\n+ # assert len(jaxpr2.constvars) == 1\ndef test_jarrett_jvps2(self):\ndef f1(x, y):\n@@ -425,8 +426,9 @@ class APITest(jtu.JaxTestCase):\n_, f2_vjp = api.vjp(f2, x, y)\nself.assertAllClose(f1_vjp(y), f2_vjp(y), check_dtypes=True)\n- jaxpr2 = api.make_jaxpr(f2_vjp)(y)\n- assert len(jaxpr2.constvars) == 2\n+ # TODO(mattjj): test that constants/literals are set up properly\n+ # jaxpr2 = api.make_jaxpr(f2_vjp)(y)\n+ # assert len(jaxpr2.constvars) == 2\ndef test_complex_grad_raises_error(self):\nself.assertRaises(TypeError, lambda: grad(lambda x: np.sin(x))(1 + 2j))\n"
}
] | Python | Apache License 2.0 | google/jax | allow more types to be jaxpr literals, fixes #772 |
260,335 | 28.05.2019 22:50:52 | 25,200 | 310103f578e078f55e70618e03fb782f76c9be2e | try a tweak on Literal for more cache hits | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -100,7 +100,23 @@ def jaxpr_as_fun(typed_jaxpr, *args):\nJaxprEqn = namedtuple('JaxprEqn', ['invars', 'outvars', 'primitive',\n'bound_subjaxprs', 'restructure',\n'destructure', 'params'])\n-class Literal(WrapHashably): pass\n+class Literal(object):\n+ __slots__ = [\"val\", \"hashable\"]\n+\n+ def __init__(self, val):\n+ self.val = val\n+ try:\n+ hash(val)\n+ except TypeError:\n+ self.hashable = False\n+ else:\n+ self.hashable = True\n+\n+ def __hash__(self):\n+ return hash(self.val) if self.hashable else id(self.val)\n+\n+ def __eq__(self, other):\n+ return self.val == other.val if self.hashable else self.val is other.val\nclass Primitive(object):\ndef __init__(self, name):\n"
}
] | Python | Apache License 2.0 | google/jax | try a tweak on Literal for more cache hits |
260,335 | 29.05.2019 08:12:05 | 25,200 | 778435a90b01762b6f207f352e8f8e5c013318b3 | undo in favor of new literal staging method | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -118,6 +118,9 @@ class Literal(object):\ndef __eq__(self, other):\nreturn self.val == other.val if self.hashable else self.val is other.val\n+ def __repr__(self):\n+ return 'Literal(val={}, hashable={})'.format(self.val, self.hashable)\n+\nclass Primitive(object):\ndef __init__(self, name):\nself.name = name\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -75,7 +75,7 @@ class BatchTracer(Tracer):\n__slots__ = ['val', 'batch_dim']\ndef __init__(self, trace, val, batch_dim):\n- assert core.skip_checks or type(batch_dim) in (int, tuple)\n+ assert core.skip_checks or type(batch_dim) in (int, tuple, type(None))\nself.trace = trace\nself.val = val\nself.batch_dim = batch_dim\n@@ -481,7 +481,7 @@ def _promote_aval_rank(n, batched, aval):\ndef batch_jaxpr(jaxpr, size, is_batched, instantiate):\nf = wrap_init(core.jaxpr_as_fun(jaxpr))\nf_batched, where_out_batched = batched_traceable(f, size, is_batched, instantiate)\n- in_avals = map(partial(_promote_aval_rank, size), is_batched, jaxpr.in_avals)\n+ in_avals = tuple(map(partial(_promote_aval_rank, size), is_batched, jaxpr.in_avals))\nin_pvals = [pe.PartialVal((aval, core.unit)) for aval in in_avals]\njaxpr_out, pval_out, literals_out = pe.trace_to_jaxpr(\nf_batched, in_pvals, instantiate=True)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -842,16 +842,6 @@ def sort_key_val(keys, values, dimension=-1):\nreturn sorted_keys, sorted_values\n-class _OpaqueParam(object):\n- \"\"\"Wrapper that hashes on its identity, instead of its contents.\n-\n- Used to pass unhashable parameters as primitive attributes.\"\"\"\n- __slots__ = [\"val\"]\n-\n- def __init__(self, val):\n- self.val = val\n-\n-\ndef tie_in(x, y):\nreturn tie_in_p.bind(x, y)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -148,49 +148,21 @@ def while_loop(cond_fun, body_fun, init_val):\nmsg = \"while_loop cond_fun must return a scalar boolean, got {}.\"\nraise TypeError(msg.format(cond_pv))\n- # We don't want to promote literal constants as loop arguments; there are\n- # sometimes many of them. We pass tracers as loop arguments, but leave\n- # nontracers as constants. We also sort the constants so the nontracers are\n- # first.\n- def split_tracers_and_nontracers(jaxpr, consts):\n- tracer = []\n- nontracer = []\n- for x in zip(jaxpr.constvars, consts):\n- # TODO(phawkins): We avoid treating DeviceArrays as constant literals so\n- # we don't copy large arrays back to the host. We probably should relax\n- # this and either always copy small constants, or opportunistically use\n- # DeviceArray values for which we already know npy_value.\n- not_literal_const = isinstance(x[1], (core.Tracer, xla.DeviceArray))\n- (tracer if not_literal_const else nontracer).append(x)\n- tracer_vars, tracer_consts = unzip2(tracer)\n- nontracer_vars, nontracer_consts = unzip2(nontracer)\n- return nontracer_vars + tracer_vars, nontracer_consts, tracer_consts\n-\n- cond_split = split_tracers_and_nontracers(cond_jaxpr, cond_consts)\n- cond_jaxpr.constvars, cond_nontracer_consts, cond_tracer_consts = cond_split\n- body_split = split_tracers_and_nontracers(body_jaxpr, body_consts)\n- body_jaxpr.constvars, body_nontracer_consts, body_tracer_consts = body_split\n-\nif out_tree() != in_tree:\nraise TypeError(\"body_fun input and output must have identical structure\")\nout_flat = while_p.bind(\n- init_val_flat,\n- core.pack(cond_tracer_consts), core.pack(body_tracer_consts),\n- cond_consts=lax._OpaqueParam(cond_nontracer_consts),\n- body_consts=lax._OpaqueParam(body_nontracer_consts),\n+ init_val_flat, core.pack(cond_consts), core.pack(body_consts),\naval_out=carry_aval_out, cond_jaxpr=cond_jaxpr, body_jaxpr=body_jaxpr)\nreturn build_tree(out_tree(), out_flat)\n-def _while_loop_abstract_eval(init_val, cond_tracer_consts, body_tracer_consts,\n- cond_consts, body_consts, aval_out,\n+def _while_loop_abstract_eval(init_val, cond_consts, body_consts, aval_out,\ncond_jaxpr, body_jaxpr):\nreturn _maybe_tracer_tuple_to_abstract_tuple(aval_out)\n-def _while_loop_translation_rule(c, init_val, cond_tracer_consts,\n- body_tracer_consts, cond_consts, body_consts,\n+def _while_loop_translation_rule(c, init_val, cond_consts, body_consts,\naval_out, cond_jaxpr, body_jaxpr):\n- loop_carry = c.Tuple(init_val, cond_tracer_consts, body_tracer_consts)\n+ loop_carry = c.Tuple(init_val, cond_consts, body_consts)\nshape = c.GetShape(loop_carry)\nloop_carry_var = pe.Var(0, \"loop_carry\")\n@@ -198,37 +170,33 @@ def _while_loop_translation_rule(c, init_val, cond_tracer_consts,\ncond_var = pe.Var(0, \"cond_consts\")\nbody_var = pe.Var(0, \"body_consts\")\n- num_cond_consts = len(cond_consts.val)\nassert len(cond_jaxpr.invars) == 1\ncond_jaxpr_converted = cond_jaxpr.copy()\n- cond_jaxpr_converted.constvars = cond_jaxpr.constvars[:num_cond_consts]\n+ cond_jaxpr_converted.constvars = []\ncond_jaxpr_converted.invars = [loop_carry_var]\ncond_jaxpr_converted.eqns = (\n[_unpack_eqn(loop_carry_var, [cond_jaxpr.invars[0], cond_var, body_var]),\n- _unpack_eqn(cond_var, cond_jaxpr.constvars[num_cond_consts:])]\n+ _unpack_eqn(cond_var, cond_jaxpr.constvars)]\n+ list(cond_jaxpr.eqns))\n- num_body_consts = len(body_consts.val)\nassert len(body_jaxpr.invars) == 1\nbody_jaxpr_converted = body_jaxpr.copy()\n- body_jaxpr_converted.constvars = body_jaxpr.constvars[:num_body_consts]\n+ body_jaxpr_converted.constvars = []\nbody_jaxpr_converted.invars = [loop_carry_var]\nbody_jaxpr_converted.outvar = outvar\nbody_jaxpr_converted.eqns = (\n[_unpack_eqn(loop_carry_var, [body_jaxpr.invars[0], cond_var, body_var]),\n- _unpack_eqn(body_var, body_jaxpr.constvars[num_body_consts:])]\n+ _unpack_eqn(body_var, body_jaxpr.constvars)]\n+ list(body_jaxpr.eqns) +\n[_pack_eqn([body_jaxpr.outvar, cond_var, body_var], outvar)])\n- cond_computation = xla.jaxpr_computation(\n- cond_jaxpr_converted, cond_consts.val, (), shape)\n- body_computation = xla.jaxpr_computation(\n- body_jaxpr_converted, body_consts.val, (), shape)\n+ cond_computation = xla.jaxpr_computation(cond_jaxpr_converted, (), (), shape)\n+ body_computation = xla.jaxpr_computation(body_jaxpr_converted, (), (), shape)\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, cond_consts,\n- body_consts, aval_out, cond_jaxpr, body_jaxpr):\n+def _while_loop_batching_rule(batched_args, batch_dims,\n+ aval_out, cond_jaxpr, body_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@@ -236,18 +204,17 @@ def _while_loop_batching_rule(batched_args, batch_dims, cond_consts,\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_tracer_consts` and `body_tracer_consts`.\n+ # using `batching.batch_transform` (the transform underlying `api.vmap`).\n# TODO(mattjj): Revise this using scan machinery (and fixed-point the loop\n# carry instead of lifting it all the way!)\n- init_val, cond_tracer_consts, body_tracer_consts = batched_args\n- init_val_bd, cond_tracer_consts_bd, body_tracer_consts_bd = batch_dims\n+ init_val, cond_consts, body_consts = batched_args\n+ init_val_bd, cond_consts_bd, body_consts_bd = batch_dims\nsizes = lax._reduce(set.union, map(batching.dimsize, batch_dims, batched_args))\nsize = sizes.pop()\nassert not sizes\n- # TODO(mattjj): if cond_tracer_consts_bd is also None, we could keep cond_fun\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 optimization\ninit_val = batching.bdim_at_front(init_val, init_val_bd, size,\nforce_broadcast=True)\n@@ -255,28 +222,21 @@ def _while_loop_batching_rule(batched_args, batch_dims, cond_consts,\ndef batched_cond_fun(batched_loop_carry):\n@lu.wrap_init\n- def lifted(loop_carry, cond_tracer_consts):\n- cond_tracer_consts = tuple(x for x in cond_tracer_consts)\n- return core.eval_jaxpr(\n- cond_jaxpr, cond_consts.val + cond_tracer_consts, (), loop_carry)\n- f = batching.batch_transform(lifted, size, (init_val_bd, cond_tracer_consts_bd), 0)\n- preds = f.call_wrapped((batched_loop_carry, cond_tracer_consts))\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))\nreturn lax.reduce(preds, onp.array(False), lax.bitwise_or, [0])\ndef batched_body_fun(batched_loop_carry):\n@lu.wrap_init\n- def lifted(loop_carry, cond_tracer_consts, body_tracer_consts):\n- cond_tracer_consts = tuple(x for x in cond_tracer_consts)\n- body_tracer_consts = tuple(x for x in body_tracer_consts)\n- pred = core.eval_jaxpr(\n- cond_jaxpr, cond_consts.val + cond_tracer_consts, (), loop_carry)\n- new_loop_carry = core.eval_jaxpr(\n- body_jaxpr, body_consts.val + body_tracer_consts, (), loop_carry)\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)\nreturn _jaxtupletree_select(pred, new_loop_carry, loop_carry)\nf = batching.batch_transform(\n- lifted, size, (init_val_bd, cond_tracer_consts_bd, body_tracer_consts_bd),\n- init_val_bd)\n- return f.call_wrapped((batched_loop_carry, cond_tracer_consts, body_tracer_consts))\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))\nreturn while_loop(batched_cond_fun, batched_body_fun, init_val), init_val_bd\n@@ -895,7 +855,7 @@ def scan_bind(consts, init, xs, forward, length, jaxpr):\nconsts_aval, init_aval, xs_aval = jaxpr.in_avals\nassert type(jaxpr.out_aval) is core.AbstractTuple\ncarry_aval, y_aval = jaxpr.out_aval\n- assert init_aval == carry_aval\n+ # assert init_aval == carry_aval # TODO(mattjj): handle unit tree prefixes\nreturn core.Primitive.bind(scan_p, consts, init, xs,\nforward=forward, length=length, jaxpr=jaxpr)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -787,6 +787,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nans = api.vmap(lambda c, as_: lax.scan(f, c, as_), in_axes)(c, as_)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ # TODO(mattjj, dougalm): fix this test when skip_checks is False\ndef testIssue757(self):\n# code from https://github.com/google/jax/issues/757\ndef fn(a):\n"
}
] | Python | Apache License 2.0 | google/jax | undo #503 in favor of new literal staging method |
260,389 | 29.05.2019 11:25:42 | 25,200 | c9b2e79bd131f65dd659c6affc76a2d37c26f68b | Drop dead compiled_call code | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -614,7 +614,5 @@ def jvp_jaxpr(jaxpr, nonzeros, instantiate):\nprimitive_transposes[core.call_p] = partial(call_transpose, call_p)\n-primitive_transposes[pe.compiled_call_p] = partial(call_transpose, pe.compiled_call_p)\n-\ntree_to_jaxtuples = partial(process_pytree, pack)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -517,21 +517,6 @@ def eqn_parents(eqn):\nreturn list(it.chain(invars, *subjaxpr_tracers))\n-def compiled_call_impl(fun, *args):\n- with new_master(JaxprTrace, True) as master:\n- pvals = map(abstractify, args)\n- jaxpr, (pval, consts, env) = trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)\n- jaxpr_ans = eval_jaxpr_raw(jaxpr, consts, env, *args)\n- ans = merge_pvals(jaxpr_ans, pval)\n- del master, pvals, pval, consts, env, jaxpr_ans, jaxpr\n- return ans\n-\n-compiled_call_p = Primitive('compiled_call')\n-compiled_call = partial(core.call_bind, compiled_call_p)\n-compiled_call_p.def_custom_bind(compiled_call)\n-compiled_call_p.def_impl(compiled_call_impl)\n-\n-\ndef unzip_tracer_tuple(pvals):\npvs, consts = unzip2(pvals)\nreturn PartialVal((JaxprTracerTuple(pvs), pack(consts)))\n"
}
] | Python | Apache License 2.0 | google/jax | Drop dead compiled_call code |
260,409 | 29.05.2019 16:35:39 | 14,400 | 58c02215052e68dc9fd60e93cccf1fc0f584ad85 | Updating GP regression example | [
{
"change_type": "MODIFY",
"old_path": "examples/gaussian_process_regression.py",
"new_path": "examples/gaussian_process_regression.py",
"diff": "@@ -20,77 +20,98 @@ from __future__ import division\nfrom __future__ import print_function\nfrom absl import app\nfrom absl import flags\n+from functools import partial\nfrom jax import grad\nfrom jax import jit\n+from jax import vmap\nfrom jax.config import config\nimport jax.numpy as np\nimport jax.random as random\nimport jax.scipy as scipy\nimport matplotlib.pyplot as plt\n-\nFLAGS = flags.FLAGS\n-def main(unused_argv):\n+def main():\n- numpts = 25\n+ numpts = 7\nkey = random.PRNGKey(0)\neye = np.eye(numpts)\n- def sqdist(x1, x2):\n- return (-2. * np.dot(x1, x2.T) + np.sum(x2**2, axis=1) +\n- np.sum(x1**2, axis=1)[:, None])\n-\n- def cov(params, x1, x2):\n- x1 = x1/np.exp(params[2])\n- x2 = x2/np.exp(params[2])\n- return np.exp(params[0]) * np.exp(-sqdist(x1, x2)/(2. * np.exp(params[1])))\n+ def cov_map(cov_func, xs, xs2=None):\n+ \"\"\"Compute a covariance matrix from a covariance function and data points.\n- def marginal_likelihood(params, x, y):\n- train_cov = cov(params, x, x) + eye * 1e-6\n- chol = np.linalg.cholesky(train_cov + eye * 1e-4).T\n- inv_chol = scipy.linalg.solve_triangular(chol, eye, lower=True)\n- inv_train_cov = np.dot(inv_chol.T, inv_chol)\n+ Args:\n+ cov_func: callable function, maps pairs of data points to scalars.\n+ xs: array of data points, stacked along the leading dimension.\n+ Returns:\n+ A 2d array `a` such that `a[i, j] = cov_func(xs[i], xs[j])`.\n+ \"\"\"\n+ if xs2 is None:\n+ return vmap(lambda x: vmap(lambda y: cov_func(x, y))(xs))(xs)\n+ else:\n+ return vmap(lambda x: vmap(lambda y: cov_func(x, y))(xs))(xs2).T\n+\n+ def softplus(x):\n+ return np.logaddexp(x, 0.)\n+\n+ def exp_quadratic(x1, x2):\n+ return np.exp(-np.sum((x1 - x2)**2))\n+\n+ def gp(params, x, y, xtest=None, compute_marginal_likelihood=False):\n+ noise = softplus(params['noise'])\n+ amp = softplus(params['amplitude'])\n+ ls = softplus(params['lengthscale'])\n+ ymean = np.mean(y)\n+ y = y - ymean\n+ x = x / ls\n+ train_cov = amp*cov_map(exp_quadratic, x) + eye * (noise + 1e-6)\n+ chol = scipy.linalg.cholesky(train_cov, lower=True)\n+ kinvy = scipy.linalg.solve_triangular(\n+ chol.T, scipy.linalg.solve_triangular(chol, y, lower=True))\n+ if compute_marginal_likelihood:\n+ log2pi = np.log(2. * 3.1415)\nml = np.sum(\n- -0.5 * np.dot(y.T, np.dot(inv_train_cov, y)) -\n- 0.5 * np.sum(2.0 * np.log(np.dot(inv_chol * eye, np.ones(\n- (numpts, 1))))) - (numpts / 2.) * np.log(2. * 3.1415))\n- return ml\n- grad_fun = jit(grad(marginal_likelihood))\n-\n- def predict(params, x, y, xtest):\n- train_cov = cov(params, x, x) + eye * 1e-6\n- chol = np.linalg.cholesky(train_cov + eye * 1e-4)\n- inv_chol = scipy.linalg.solve_triangular(chol, eye, lower=True)\n- inv_train_cov = np.dot(inv_chol.T, inv_chol)\n- cross_cov = cov(params, x, xtest)\n- mu = np.dot(cross_cov.T, np.dot(inv_train_cov, y))\n- var = (cov(params, xtest, xtest) -\n- np.dot(cross_cov.T, np.dot(inv_train_cov, cross_cov)))\n+ -0.5 * np.dot(y.T, kinvy) -\n+ np.sum(np.log(np.diag(chol))) -\n+ (numpts / 2.) * log2pi)\n+ ml -= np.sum(-0.5 * np.log(2 * 3.1415) - np.log(amp)**2) # lognormal prior\n+ return -ml\n+\n+ if xtest is not None:\n+ xtest = xtest / ls\n+ cross_cov = amp*cov_map(exp_quadratic, x, xtest)\n+ mu = np.dot(cross_cov.T, kinvy) + ymean\n+ v = scipy.linalg.solve_triangular(chol, cross_cov, lower=True)\n+ var = (amp * cov_map(exp_quadratic, xtest) - np.dot(v.T, v))\nreturn mu, var\n+ marginal_likelihood = partial(gp, compute_marginal_likelihood=True)\n+ predict = partial(gp, compute_marginal_likelihood=False)\n+ grad_fun = jit(grad(marginal_likelihood))\n+\n# Covariance hyperparameters to be learned\n- params = [np.zeros((1, 1)), # Amplitude\n- np.zeros((1, 1)), # Bandwidth\n- np.zeros((1, 1))] # Length-scale\n- momentums = [p * 0. for p in params]\n- scales = [p * 0. + 1. for p in params]\n+ params = {\"amplitude\": np.zeros((1, 1)),\n+ \"noise\": np.zeros((1, 1)) - 5.,\n+ \"lengthscale\": np.zeros((1, 1))}\n+ momentums = dict([(k, p * 0.) for k, p in params.items()])\n+ scales = dict([(k, p * 0. + 1.) for k, p in params.items()])\nlr = 0.01 # Learning rate\ndef train_step(params, momentums, scales, x, y):\ngrads = grad_fun(params, x, y)\n- for i in range(len(params)):\n- momentums[i] = 0.9 * momentums[i] + 0.1 * grads[i][0]\n- scales[i] = 0.9 * scales[i] + 0.1 * grads[i][0]**2\n- params[i] -= lr * momentums[i]/np.sqrt(scales[i] + 1e-5)\n+ for k in (params):\n+ momentums[k] = 0.9 * momentums[k] + 0.1 * grads[k][0]\n+ scales[k] = 0.9 * scales[k] + 0.1 * grads[k][0]**2\n+ params[k] -= lr * momentums[k]/np.sqrt(scales[k] + 1e-5)\nreturn params, momentums, scales\n# Create a really simple toy 1D function\n- y_fun = lambda x: np.sin(x) + 0.01 * random.normal(key, shape=(x.shape[0], 1))\n- x = np.linspace(1., 4., numpts)[:, None]\n+ y_fun = lambda x: np.sin(x) + 0.1 * random.normal(key, shape=(x.shape[0], 1))\n+ x = (random.uniform(key, shape=(numpts, 1)) * 4.) + 1\ny = y_fun(x)\n- xtest = np.linspace(0, 5., 200)[:, None]\n+ xtest = np.linspace(0, 6., 200)[:, None]\nytest = y_fun(xtest)\nfor i in range(1000):\n@@ -99,7 +120,7 @@ def main(unused_argv):\nml = marginal_likelihood(params, x, y)\nprint(\"Step: %d, neg marginal likelihood: %f\" % (i, ml))\n- print([i.copy() for i in params])\n+ print(params)\nmu, var = predict(params, x, y, xtest)\nstd = np.sqrt(np.diag(var))\nplt.plot(x, y, \"k.\")\n@@ -107,7 +128,6 @@ def main(unused_argv):\nplt.fill_between(xtest.flatten(),\nmu.flatten() - std * 2, mu.flatten() + std * 2)\n-\nif __name__ == \"__main__\":\nconfig.config_with_absl()\napp.run(main)\n"
}
] | Python | Apache License 2.0 | google/jax | Updating GP regression example |
260,409 | 30.05.2019 12:13:10 | 14,400 | 06d41fbad1d8a5df938babd734b44d1a41c68fc5 | Added a note about squared distances | [
{
"change_type": "MODIFY",
"old_path": "examples/gaussian_process_regression.py",
"new_path": "examples/gaussian_process_regression.py",
"diff": "@@ -56,6 +56,9 @@ def main(unused_argv):\ndef softplus(x):\nreturn np.logaddexp(x, 0.)\n+ # Note, writing out the vectorized form of the identity\n+ # ||x-y||^2 = <x-y,x-y> = ||x||^2 + ||y||^2 - 2<x,y>\n+ # for computing squared distances would be more efficient (but less succinct).\ndef exp_quadratic(x1, x2):\nreturn np.exp(-np.sum((x1 - x2)**2))\n"
}
] | Python | Apache License 2.0 | google/jax | Added a note about squared distances |
260,335 | 31.05.2019 09:20:45 | 25,200 | 0a8810d9bc9cfe62307d47f7d71d62dc0a6d8a94 | abstract_eval_fun should instantiate output pval | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -212,8 +212,9 @@ def partial_eval_wrapper(avals, *consts):\ndef abstract_eval_fun(fun, *avals, **params):\npvs_in = [PartialVal((a, unit)) for a in avals]\n- _, pvout, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvs_in)\n+ _, pvout, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvs_in, instantiate=True)\naval_out, _ = pvout\n+ assert isinstance(aval_out, AbstractValue) # instantiate=True\nreturn aval_out\n"
}
] | Python | Apache License 2.0 | google/jax | abstract_eval_fun should instantiate output pval |
260,335 | 31.05.2019 14:04:04 | 25,200 | 8377224b905b1fa3cbd2eaa9be52f749058581bc | ppermute (aka collective_permute) jvp + transpose | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -214,12 +214,12 @@ def _ppermute_translation_rule(c, x, replica_groups, perm):\nreturn c.CollectivePermute(x, full_perm)\ndef _ppermute_transpose_rule(t, perm, axis_name):\n- sources, dests = unzip2(perm)\n- inverse_perm = zip(dests, srcs)\n- return ppermute(t, axis_name=axis_name, perm=inverse_perm)\n+ srcs, dsts = unzip2(perm)\n+ inverse_perm = list(zip(dsts, srcs))\n+ return [ppermute(t, axis_name=axis_name, perm=inverse_perm)]\nppermute_p = standard_pmap_primitive('ppermute')\n-# ad.deflinear(ppermute_p, _ppermute_transpose_rule) # TODO(mattjj): test this\n+ad.deflinear(ppermute_p, _ppermute_transpose_rule)\npxla.parallel_translation_rules[ppermute_p] = _ppermute_translation_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -292,6 +292,20 @@ class PmapTest(jtu.JaxTestCase):\nexpected = onp.roll(x, shift=1, axis=0)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @jtu.skip_on_devices(\"cpu\", \"gpu\")\n+ def testCollectivePermuteGrad(self):\n+ device_count = xla_bridge.device_count()\n+ shift_right = [(i, (i + 1)) for i in range(device_count - 1)]\n+ f = lambda x: lax.ppermute(x, perm=shift_right, axis_name='i')\n+ y = onp.pi + onp.arange(device_count, dtype=onp.float32)\n+ g = lambda x: np.sum(y * pmap(f, 'i')(x))\n+\n+ x = onp.arange(device_count, dtype=onp.float32)\n+ ans = grad(g)(x)\n+ expected = onp.concatenate([onp.pi + onp.arange(1, device_count), [0]])\n+ print(ans)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n@jtu.skip_on_devices(\"cpu\", \"gpu\")\ndef testRule30(self):\n# This is a test of collective_permute implementing a simple halo exchange\n"
}
] | Python | Apache License 2.0 | google/jax | ppermute (aka collective_permute) jvp + transpose |
260,335 | 31.05.2019 14:11:38 | 25,200 | dffe49153700055e1d0c344dad2bb3d0edf07525 | add another ppermute test, remove extra print call | [
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -303,7 +303,19 @@ class PmapTest(jtu.JaxTestCase):\nx = onp.arange(device_count, dtype=onp.float32)\nans = grad(g)(x)\nexpected = onp.concatenate([onp.pi + onp.arange(1, device_count), [0]])\n- print(ans)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ @jtu.skip_on_devices(\"cpu\", \"gpu\")\n+ def testCollectivePermuteCyclicGrad(self):\n+ device_count = xla_bridge.device_count()\n+ shift_right = [(i, (i + 1) % device_count) for i in range(device_count)]\n+ f = lambda x: lax.ppermute(x, perm=shift_right, axis_name='i')\n+ y = onp.pi + onp.arange(device_count, dtype=onp.float32)\n+ g = lambda x: np.sum(y * pmap(f, 'i')(x))\n+\n+ x = onp.arange(device_count, dtype=onp.float32)\n+ ans = grad(g)(x)\n+ expected = onp.roll(onp.pi + onp.arange(device_count), 1)\nself.assertAllClose(ans, expected, check_dtypes=False)\n@jtu.skip_on_devices(\"cpu\", \"gpu\")\n"
}
] | Python | Apache License 2.0 | google/jax | add another ppermute test, remove extra print call |
260,335 | 01.06.2019 08:30:25 | 25,200 | 93e114337334fd0e42ac5bf0d5caecdab5344383 | improve disable_jit docstring | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -128,16 +128,17 @@ def _jit(fun, static_argnums, device_values=True):\n@contextmanager\ndef disable_jit():\n- \"\"\"Context manager that disables `jit`.\n+ \"\"\"Context manager that disables `jit` behavior under its dynamic context.\nFor debugging purposes, it is useful to have a mechanism that disables `jit`\n- everywhere in a block of code, namely the `disable_jit` decorator.\n+ everywhere in a dynamic context.\n- Inside a `jit`-ted function the values flowing through\n- traced code can be abstract (i.e., shaped arrays with an unknown values),\n- instead of concrete (i.e., specific arrays with known values).\n-\n- For example:\n+ Values that have a data dependence on the arguments to a jitted function are\n+ traced and abstracted. For example, an abstract value may be a ShapedArray\n+ instance, representing the set of all possible arrays with a given shape and\n+ dtype, but not representing one concrete array with specific values. You might\n+ notice those if you use a benign side-effecting operation in a jitted\n+ function, like a print:\n>>> @jax.jit\n>>> def f(x):\n@@ -150,9 +151,9 @@ def disable_jit():\n[5 7 9]\nHere `y` has been abstracted by `jit` to a `ShapedArray`, which represents an\n- array with a fixed shape and type but an arbitrary value. If we want to see a\n- concrete values while debugging, we can use the `disable_jit` decorator, at\n- the cost of slower code:\n+ array with a fixed shape and type but an arbitrary value. It's also traced. If\n+ we want to see a concrete value while debugging, and avoid the tracer too, we\n+ can use the `disable_jit` context manager:\n>>> with jax.disable_jit():\n>>> print(f(np.array([1, 2, 3])))\n"
}
] | Python | Apache License 2.0 | google/jax | improve disable_jit docstring |
260,335 | 01.06.2019 09:34:33 | 25,200 | 11c512a194add25ade20dbfacf635d6e0834eba3 | add jax.eval_shape, fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1062,3 +1062,54 @@ def _make_graphviz(fun):\ngraphviz_maker.__name__ = \"make_graphviz({})\".format(graphviz_maker.__name__)\nreturn graphviz_maker\n+\n+\n+def eval_shape(fun, *args, **kwargs):\n+ \"\"\"Compute the shape of ``fun(*args, **kwargs)`` without incurring any FLOPs.\n+\n+ This utility function is useful for performing shape inference. Its\n+ input/output behavior is defined by:\n+\n+ def eval_shape(fun, *args, **kwargs):\n+ out = fun(*args, **kwargs)\n+ return jax.tree_util.tree_map(np.shape, out)\n+\n+ But instead of applying ``fun`` directly, which might be expensive, it uses\n+ JAX's abstract interpretation machinery to evaluate the shapes without doing\n+ any FLOPs.\n+\n+ Using ``eval_shape`` can also catch shape errors, and will raise same shape\n+ errors as evaluating ``fun(*args, **kwargs)``.\n+\n+ Args:\n+ *args: a positional argument tuple of arrays, scalars, or (nested) standard\n+ Python containers (pytrees) of those types. Since only the ``shape`` and\n+ ``dtype`` attributes are accessed, only values that duck-type arrays are\n+ required, rather than real ndarrays.\n+ **kwargs: a keyword argument dict of arrays, scalars, or (nested) standard\n+ Python containers (pytrees) of those types. As in ``args``, array values\n+ need only be duck-typed to have ``shape`` and ``dtype`` attributes.\n+\n+ For example:\n+\n+ >>> f = lambda A, b, x: np.tanh(np.dot(A, x) + b)\n+ >>> MyArgArray = collections.namedtuple(\"MyArgArray\", [\"shape\", \"dtype\"])\n+ >>> A = MyArgArray((2000, 3000), np.float32)\n+ >>> b = MyArgArray((2000,), np.float32)\n+ >>> x = MyArgArray((3000, 1000), np.float32)\n+ >>> out_shape = jax.eval_shape(f, A, b, x) # no FLOPs performed\n+ >>> print(out_shape)\n+ (2000, 1000)\n+ \"\"\"\n+ def abstractify(x):\n+ if type(x) is core.JaxTuple:\n+ return core.AbstractTuple(map(abstractify, x))\n+ else:\n+ return ShapedArray(onp.shape(x), onp.result_type(x))\n+\n+ jax_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\n+ jax_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\n+ f, out_tree = pytree_fun_to_jaxtupletree_fun2(lu.wrap_init(fun), kwargs_tree, in_trees)\n+ abstract_args = map(abstractify, (jax_kwargs,) + tuple(jax_args))\n+ out = pe.abstract_eval_fun(f.call_wrapped, *abstract_args)\n+ return tree_map(onp.shape, build_tree(out_tree(), out))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -593,5 +593,66 @@ class APITest(jtu.JaxTestCase):\nf_jit = api.jit(f)\nself.assertAllClose(f(pt), f_jit(pt), check_dtypes=False)\n+ def test_eval_shape(self):\n+ def fun(x, y):\n+ return np.tanh(np.dot(x, y) + 3.)\n+\n+ x = np.ones((2, 3))\n+ y = np.ones((3, 4))\n+ out_shape = api.eval_shape(fun, x, y)\n+\n+ self.assertEqual(out_shape, (2, 4))\n+\n+ def test_eval_shape_constants(self):\n+ def fun():\n+ x = np.ones((2, 3))\n+ y = np.ones((3, 4))\n+ return np.tanh(np.dot(x, y) + 3.)\n+\n+ out_shape = api.eval_shape(fun)\n+\n+ self.assertEqual(out_shape, (2, 4))\n+\n+ def test_eval_shape_tuple_unpacking(self):\n+ def fun(x, y):\n+ a, b = x\n+ return a + b + y\n+\n+ x = (np.ones(2), np.ones(2))\n+ y = 3.\n+ out_shape = api.eval_shape(fun, x, y)\n+\n+ self.assertEqual(out_shape, (2,))\n+\n+ def test_eval_shape_tuple_itemgetting(self):\n+ def fun(x, y):\n+ return x[0] + x[1] + y\n+\n+ x = (np.ones(2), np.ones(2))\n+ y = 3.\n+ out_shape = api.eval_shape(fun, x, y)\n+\n+ self.assertEqual(out_shape, (2,))\n+\n+ def test_eval_shape_output_dict(self):\n+ def fun4(x, y):\n+ return {'hi': x[0] + x[1] + y}\n+\n+ x = (np.ones(2), np.ones(2))\n+ y = 3.\n+ out_shape = api.eval_shape(fun4, x, y)\n+\n+ self.assertEqual(out_shape, {'hi': (2,)})\n+\n+ def test_eval_shape_shape_error(self):\n+ def fun(x, y):\n+ return np.tanh(np.dot(x, y) + 3.)\n+\n+ x = np.ones((3, 3))\n+ y = np.ones((4, 4))\n+\n+ self.assertRaises(TypeError, lambda: api.eval_shape(fun, x, y))\n+\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add jax.eval_shape, fixes #798 |
260,335 | 01.06.2019 09:48:28 | 25,200 | dda95df519f3f421241e3fcda050e690524c012f | fix duck typing in jax.eval_shape (cf. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1083,21 +1083,26 @@ def eval_shape(fun, *args, **kwargs):\nArgs:\n*args: a positional argument tuple of arrays, scalars, or (nested) standard\n- Python containers (pytrees) of those types. Since only the ``shape`` and\n- ``dtype`` attributes are accessed, only values that duck-type arrays are\n- required, rather than real ndarrays.\n+ Python containers (tuples, lists, dicts, namedtuples, i.e. pytrees) of\n+ those types. Since only the ``shape`` and ``dtype`` attributes are\n+ accessed, only values that duck-type arrays are required, rather than real\n+ ndarrays. The duck-typed objects cannot be namedtuples because those are\n+ treated as standard Python containers. See the example below.\n**kwargs: a keyword argument dict of arrays, scalars, or (nested) standard\nPython containers (pytrees) of those types. As in ``args``, array values\nneed only be duck-typed to have ``shape`` and ``dtype`` attributes.\nFor example:\n- >>> f = lambda A, b, x: np.tanh(np.dot(A, x) + b)\n- >>> MyArgArray = collections.namedtuple(\"MyArgArray\", [\"shape\", \"dtype\"])\n+ >>> f = lambda A, x: np.tanh(np.dot(A, x))\n+ >>> class MyArgArray(object):\n+ ... def __init__(self, shape, dtype):\n+ ... self.shape = shape\n+ ... self.dtype = dtype\n+ ...\n>>> A = MyArgArray((2000, 3000), np.float32)\n- >>> b = MyArgArray((2000,), np.float32)\n>>> x = MyArgArray((3000, 1000), np.float32)\n- >>> out_shape = jax.eval_shape(f, A, b, x) # no FLOPs performed\n+ >>> out_shape = jax.eval_shape(f, A, x) # no FLOPs performed\n>>> print(out_shape)\n(2000, 1000)\n\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -635,12 +635,12 @@ class APITest(jtu.JaxTestCase):\nself.assertEqual(out_shape, (2,))\ndef test_eval_shape_output_dict(self):\n- def fun4(x, y):\n+ def fun(x, y):\nreturn {'hi': x[0] + x[1] + y}\nx = (np.ones(2), np.ones(2))\ny = 3.\n- out_shape = api.eval_shape(fun4, x, y)\n+ out_shape = api.eval_shape(fun, x, y)\nself.assertEqual(out_shape, {'hi': (2,)})\n@@ -653,6 +653,22 @@ class APITest(jtu.JaxTestCase):\nself.assertRaises(TypeError, lambda: api.eval_shape(fun, x, y))\n+ def test_eval_shape_duck_typing(self):\n+ def fun(A, b, x):\n+ return np.dot(A, x) + b\n+\n+ class MyArgArray(object):\n+ def __init__(self, shape, dtype):\n+ self.shape = shape\n+ self.dtype = dtype\n+\n+ A = MyArgArray((3, 4), np.float32)\n+ b = MyArgArray((5,), np.float32)\n+ x = MyArgArray((4, 5), np.float32)\n+ out_shape = api.eval_shape(fun, A, b, x)\n+\n+ self.assertEqual(out_shape, (3, 5))\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix duck typing in jax.eval_shape (cf. #798) |
260,335 | 01.06.2019 09:53:32 | 25,200 | ffec059f0ef4ebb27973868167bd13011ed321ab | add jax.eval_shape to reference docs via jax.rst | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.rst",
"new_path": "docs/jax.rst",
"diff": "@@ -19,6 +19,6 @@ Module contents\n---------------\n.. automodule:: jax\n- :members: jit, disable_jit, grad, value_and_grad, vmap, pmap, jacfwd, jacrev, hessian, jvp, linearize, vjp, make_jaxpr\n+ :members: jit, disable_jit, grad, value_and_grad, vmap, pmap, jacfwd, jacrev, hessian, jvp, linearize, vjp, make_jaxpr, eval_shape\n:undoc-members:\n:show-inheritance:\n"
}
] | Python | Apache License 2.0 | google/jax | add jax.eval_shape to reference docs via jax.rst |
260,335 | 03.06.2019 07:22:32 | 25,200 | fadd18b36c32ed3a2903dee745e68513d250f013 | namedtuple subclass transparency (fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/tree_util.py",
"new_path": "jax/tree_util.py",
"diff": "@@ -247,7 +247,7 @@ def _get_node_type(maybe_tree):\nreturn node_types.get(t) or _namedtuple_node(t)\ndef _namedtuple_node(t):\n- if t.__bases__ == (tuple,) and hasattr(t, '_fields'):\n+ if issubclass(t, tuple) and hasattr(t, '_fields'):\nreturn NamedtupleNode\nNamedtupleNode = NodeType('namedtuple',\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -593,6 +593,23 @@ class APITest(jtu.JaxTestCase):\nf_jit = api.jit(f)\nself.assertAllClose(f(pt), f_jit(pt), check_dtypes=False)\n+ def test_namedtuple_subclass_transparency(self):\n+ # See https://github.com/google/jax/issues/806\n+ Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n+\n+ class ZeroPoint(Point):\n+ def is_zero(self):\n+ return (self.x == 0) and (self.y == 0)\n+\n+ pt = ZeroPoint(0., 0.)\n+\n+ def f(pt):\n+ return 0. if pt.is_zero() else np.sqrt(pt.x ** 2 + pt.y ** 2)\n+\n+ f(pt) # doesn't crash\n+ g = api.grad(f)(pt)\n+ self.assertIsInstance(pt, ZeroPoint)\n+\ndef test_eval_shape(self):\ndef fun(x, y):\nreturn np.tanh(np.dot(x, y) + 3.)\n"
}
] | Python | Apache License 2.0 | google/jax | namedtuple subclass transparency (fixes #806) |
260,335 | 04.06.2019 13:17:41 | 25,200 | a12ca881a363354b07affadda86f92227be3a6ef | add future to macos wheel build script | [
{
"change_type": "MODIFY",
"old_path": "build/build_jaxlib_wheels_macos.sh",
"new_path": "build/build_jaxlib_wheels_macos.sh",
"diff": "@@ -27,7 +27,7 @@ build_jax () {\npyenv activate \"${VENV}\"\n# We pin the Numpy wheel to a version < 1.16.0, because Numpy extensions built\n# at 1.16.0 are not backward compatible to earlier Numpy versions.\n- pip install numpy==1.15.4 scipy==1.2.0 wheel\n+ pip install numpy==1.15.4 scipy==1.2.0 wheel future\nrm -fr build/build\npython build/build.py\ncd build\n"
}
] | Python | Apache License 2.0 | google/jax | add future to macos wheel build script |
260,335 | 04.06.2019 18:33:52 | 25,200 | e1f32d0d1e98b2b55d8b0ceefdfe14f7182f84e6 | add process_map to vmap tracer, i.e. vmap-of-pmap | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -124,6 +124,8 @@ class BatchTrace(Trace):\nreturn BatchTracer(self, val_out, dim_out)\ndef process_call(self, call_primitive, f, tracers, params):\n+ if call_primitive in pe.map_primitives:\n+ return self.process_map(call_primitive, f, tracers, params)\nvals, dims = unzip2((t.val, t.batch_dim) for t in tracers)\nif all(bdim is None for bdim in dims):\nreturn call_primitive.bind(f, *vals, **params)\n@@ -132,6 +134,19 @@ class BatchTrace(Trace):\nval_out = call_primitive.bind(f, *vals, **params)\nreturn BatchTracer(self, val_out, dim_out())\n+ def process_map(self, map_primitive, f, tracers, params):\n+ vals, dims = unzip2((t.val, t.batch_dim) for t in tracers)\n+ if all(dim is None for dim in dims):\n+ return map_primitive.bind(f, *vals, **params)\n+ else:\n+ size = reduce(set.union, map(dimsize, dims, vals)).pop()\n+ is_batched = tuple(map(where_batched, dims))\n+ vals = map(partial(instantiate_bdim, size, 1), is_batched, dims, vals)\n+ dims = tuple(map(partial(bools_to_bdims, 0), is_batched))\n+ f, dim_out = batch_subtrace(f, self.master, dims)\n+ val_out = map_primitive.bind(f, *vals, **params)\n+ return BatchTracer(self, val_out, increment_bdim(dim_out()))\n+\ndef post_process_call(self, call_primitive, out_tracer, params):\nval, dim = out_tracer.val, out_tracer.batch_dim\nmaster = self.master\n@@ -310,27 +325,28 @@ def _dimsize(dim, aval, x):\nraise TypeError(type(dim))\ndef moveaxis(sz, dst, src, x, force_broadcast=True):\n- return _moveaxis(sz, dst, src, get_aval(x), x, force_broadcast)\n+ return _moveaxis(force_broadcast, sz, dst, src, get_aval(x), x)\n-# TODO(mattjj): not passing force_broadcast recursively... intentional?\n-def _moveaxis(sz, dst, src, aval, x, force_broadcast=True):\n+def _moveaxis(force_bcast, sz, dst, src, aval, x):\nif type(aval) is AbstractTuple:\nif type(src) is tuple and type(dst) is tuple:\n- return pack(map(partial(_moveaxis, sz), dst, src, aval, x))\n+ return pack(map(partial(_moveaxis, force_bcast, sz), dst, src, aval, x))\nelif type(src) is tuple:\n- return pack(map(partial(_moveaxis, sz, dst), src, aval, x))\n+ return pack(map(partial(_moveaxis, force_bcast, sz, dst), src, aval, x))\nelif type(dst) is tuple:\nsrcs = (src,) * len(dst)\n- return pack(map(partial(_moveaxis, sz), dst, srcs, aval, x))\n+ return pack(map(partial(_moveaxis, force_bcast, sz), dst, srcs, aval, x))\n+ elif type(src) in (int, type(None)):\n+ return pack(map(partial(_moveaxis, force_bcast, sz, dst, src), aval, x))\nelse:\n- return pack(map(partial(_moveaxis, sz, dst, src), aval, x))\n+ raise TypeError(type(src))\nelif isinstance(aval, ShapedArray):\ndst_ = (dst % aval.ndim) if dst is not None and aval.ndim else dst\nif src == dst_:\nreturn x\nelse:\nif src is None:\n- x = broadcast(x, sz, force_broadcast=force_broadcast)\n+ x = broadcast(x, sz, force_broadcast=force_bcast)\nsrc = 0\ndst_ = dst % (aval.ndim + 1)\nif src == dst_:\n@@ -343,15 +359,14 @@ def _moveaxis(sz, dst, src, aval, x, force_broadcast=True):\nraise TypeError(type(aval))\ndef broadcast(x, sz, force_broadcast=False):\n- return _broadcast(sz, get_aval(x), x, force_broadcast)\n+ return _broadcast(force_broadcast, sz, get_aval(x), x)\n-# TODO(mattjj): not passing force_broadcast recursively... intentional?\n-def _broadcast(sz, aval, x, force_broadcast=False):\n+def _broadcast(force_bcast, sz, aval, x):\nif type(aval) is AbstractTuple:\nreturn pack(map(partial(_broadcast, sz), aval, x))\nelif isinstance(aval, ShapedArray):\n# for scalars, maybe don't actually broadcast\n- if not onp.ndim(x) and not force_broadcast:\n+ if not onp.ndim(x) and not force_bcast:\nreturn x\n# see comment at the top of this section\n@@ -372,14 +387,16 @@ def handle_scalar_broadcasting(nd, x, bdim):\n# TODO(mattjj): try to de-duplicate utility functions with above\n-def where_batched(bdim):\n+def _bdim_map(f, bdim):\nt = type(bdim)\nif t is tuple:\n- return tuple(map(where_batched, bdim))\n+ return tuple(map(partial(_bdim_map, f), bdim))\nelif t in (int, type(None)):\n- return bdim is not None\n+ return f(bdim)\nelse:\nraise TypeError(t)\n+where_batched = partial(_bdim_map, lambda x: x is not None)\n+increment_bdim = partial(_bdim_map, lambda x: None if x is None else x + 1)\ndef bools_to_bdims(bdim, batched_indicator_tree):\nt = type(batched_indicator_tree)\n@@ -402,7 +419,7 @@ def instantiate_bdim(size, axis, instantiate, bdim, x):\nthe tree structure in x, indicating whether to instantiate the batch\ndimension at the corresponding subtree in x.\nbdim: tuple-tree of ints or NoneTypes, with identical tree structure to\n- `instantaite`, indicating where the batch dimension exists in the\n+ `instantiate`, indicating where the batch dimension exists in the\ncorresponding subtree of x.\nx: JaxType value on which to instantiate or move batch dimensions.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -119,11 +119,11 @@ class JaxprTrace(Trace):\nFalse, False, params)\nreturn JaxprTracer(self, PartialVal((out_pv, out_pv_const)), eqn)\n- def process_map(self, call_primitive, f, tracers, params):\n+ def process_map(self, map_primitive, f, tracers, params):\nin_pvs, in_consts = unzip2([t.pval for t in tracers])\nreduced_pvs = map(remove_axis_from_pv, in_pvs)\nfun, aux = partial_eval(f, self, reduced_pvs)\n- out_const, consts = call_primitive.bind(fun, *in_consts, **params)\n+ out_const, consts = map_primitive.bind(fun, *in_consts, **params)\nout_pv_reduced, jaxpr, env = aux()\nout_pv = add_axis_to_pv(params['axis_size'], out_pv_reduced)\nconst_tracers = map(self.new_instantiated_const, consts)\n@@ -133,7 +133,7 @@ class JaxprTrace(Trace):\njaxpr_converted.invars = list(it.chain(jaxpr.constvars, jaxpr.invars))\ninvars = tuple(it.chain(const_tracers, tracers))\nbound_subjaxpr = (jaxpr_converted, (), env)\n- eqn = JaxprEqn(invars, None, call_primitive, (bound_subjaxpr,),\n+ eqn = JaxprEqn(invars, None, map_primitive, (bound_subjaxpr,),\nFalse, False, params)\nreturn JaxprTracer(self, PartialVal((out_pv, out_const)), eqn)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -459,6 +459,7 @@ def tuple_element_handler(axis_size, aval):\ncore.pytype_aval_mappings[ShardedDeviceTuple] = core.pytype_aval_mappings[core.JaxTuple]\nxla.pytype_aval_mappings[ShardedDeviceTuple] = op.attrgetter('aval')\n+batching.pytype_aval_mappings[ShardedDeviceTuple] = op.attrgetter('aval')\nxla.canonicalize_dtype_handlers[ShardedDeviceTuple] = \\\nxla.canonicalize_dtype_handlers[xla.DeviceTuple]\n@@ -524,6 +525,8 @@ class ShardedDeviceArray(xla.DeviceArray):\ncore.pytype_aval_mappings[ShardedDeviceArray] = ConcreteArray\nxla.pytype_aval_mappings[ShardedDeviceArray] = \\\nxla.pytype_aval_mappings[xla.DeviceArray]\n+batching.pytype_aval_mappings[ShardedDeviceArray] = \\\n+ batching.pytype_aval_mappings[xla.DeviceArray]\nxla.canonicalize_dtype_handlers[ShardedDeviceArray] = \\\nxla.canonicalize_dtype_handlers[xla.DeviceArray]\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -483,6 +483,42 @@ class PmapTest(jtu.JaxTestCase):\nexpected = 1 + onp.arange(device_count)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testVmapOfPmap(self):\n+ device_count = xla_bridge.device_count()\n+ f0 = lambda x: x\n+ f1 = pmap(f0, axis_name='i')\n+ ax = onp.random.randn(2, device_count, 50, 60)\n+ bx = vmap(f1)(ax)\n+ self.assertAllClose(ax, bx, check_dtypes=False)\n+\n+ def testVmapOfPmapNonLeadingAxis(self):\n+ device_count = xla_bridge.device_count()\n+ f0 = lambda x: x\n+ f1 = pmap(f0, axis_name='i')\n+ ax = onp.random.randn(device_count, 2, 50, 60)\n+ bx = vmap(f1, in_axes=2, out_axes=2)(ax)\n+ self.assertAllClose(ax, bx, check_dtypes=False)\n+\n+ def testVmapOfPmapTuple(self):\n+ device_count = xla_bridge.device_count()\n+ f0 = lambda *x: x\n+ f1 = pmap(f0, axis_name='i')\n+\n+ ax = onp.random.randn(device_count, 2, 50, 60)\n+ ay = onp.random.randn(device_count, 30, 2)\n+ az1 = onp.random.randn(device_count, 20)\n+ az2 = onp.random.randn(2, device_count, 20)\n+\n+ bx, by, bz = vmap(f1, in_axes=(1, 2, (None, 0)), out_axes=(1, 2, 0))(ax, ay, (az1, az2))\n+\n+ self.assertAllClose(ax, bx, check_dtypes=False)\n+ self.assertAllClose(ay, by, check_dtypes=False)\n+\n+ bz1, bz2 = bz\n+ expected_bz1 = onp.broadcast_to(az1, (2,) + az1.shape)\n+ self.assertAllClose(expected_bz1, bz1, check_dtypes=False)\n+ self.assertAllClose(bz2, bz2, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add process_map to vmap tracer, i.e. vmap-of-pmap |
260,335 | 03.06.2019 07:17:37 | 25,200 | 35e5e64416a0c1ab9376eccc7b1ce1f9278235a9 | make custom_transforms handle pytrees, add api.defvjp
With advice from | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -26,6 +26,7 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n+import collections\nimport itertools\nimport operator as op\nimport os\n@@ -38,6 +39,7 @@ from six.moves import reduce\nfrom . import core\nfrom . import linear_util as lu\n+from . import ad_util\nfrom .core import pack, eval_jaxpr\nfrom .api_util import (pytree_fun_to_jaxtupletree_fun, pytree_to_jaxtupletree,\npytree_fun_to_flatjaxtuple_fun, apply_jaxtree_fun, wraps,\n@@ -952,25 +954,165 @@ def _valid_jaxtype(arg):\nreturn True\n+class CustomTransformsFunction(object):\n+ def __init__(self, fun, prim):\n+ self.fun = fun\n+ self.prim = prim\n+ wraps(fun)(self)\n+\n+ def __repr__(self):\n+ return '<jax.custom_transforms function {fun}>'.format(fun=self.__name__)\n+\n+ def __call__(self, *args, **kwargs):\n+ jax_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\n+ jax_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\n+ out_tree = lu.Store()\n+ ans = self.prim.bind(jax_kwargs, *jax_args, kwargs_tree=kwargs_tree,\n+ in_trees=in_trees, out_tree=out_tree)\n+ return build_tree(out_tree.val, ans)\n+\ndef custom_transforms(fun):\n- name = getattr(fun, '__name__', '<unnamed user primitive>')\n+ name = getattr(fun, '__name__', '<unnamed custom_transforms primitive>')\nfun_p = core.Primitive(name)\n- fun_p.def_impl(fun)\n- # generic transformation implementations that rely on traceability of `fun`\n- fun_p.def_abstract_eval(partial(pe.abstract_eval_fun, fun))\n- xla.translations[fun_p] = partial(xla.lower_fun, fun)\n- ad.primitive_jvps[fun_p] = partial(jvp, fun)\n- # TODO(mattjj): batching\n+ def fun_impl(jax_kwargs, *jax_args, **params):\n+ args = map(build_tree, params.pop('in_trees'), jax_args)\n+ kwargs = build_tree(params.pop('kwargs_tree'), jax_kwargs)\n+ pytree_out = fun(*args, **kwargs)\n+ out, out_tree = pytree_to_jaxtupletree(pytree_out)\n+ params.pop('out_tree').store(out_tree) # linear_util style side effect\n+ assert not params\n+ return out\n+ fun_p.def_impl(fun_impl)\n+\n+ def fun_jvp(primals, tangents, **params):\n+ return ad.jvp(lu.wrap_init(fun_impl, params)).call_wrapped(primals, tangents)\n+ ad.primitive_jvps[fun_p] = fun_jvp\n+\n+ def fun_batch(batched_args, batch_dims, **params):\n+ out = batching.batch(lu.wrap_init(fun_impl, params), batched_args, batch_dims, 0)\n+ return out, 0\n+ batching.primitive_batchers[fun_p] = fun_batch\n+\n+ staged_fun_p = core.Primitive('staged_' + name)\n+ def fun_partial_eval(trace, *tracers, **params):\n+ tracers = tuple(map(trace.instantiate_const, tracers))\n+ avals = [t.aval for t in tracers]\n+ pvals_in = [pe.PartialVal((a, core.unit)) for a in avals]\n+ jaxpr, pval_out, consts = pe.trace_to_jaxpr(lu.wrap_init(fun_impl, params),\n+ pvals_in, instantiate=True)\n+ consts = trace.new_instantiated_const(core.pack(consts))\n+ eqn = pe.JaxprEqn((consts,) + tracers, None, staged_fun_p, (), False, False,\n+ dict(params, jaxpr=jaxpr))\n+ return pe.JaxprTracer(trace, pval_out, eqn)\n+ pe.custom_partial_eval_rules[fun_p] = fun_partial_eval\n+\n+ def staged_fun_translation(c, xla_consts, *xla_args, **params):\n+ consts_shapes = tuple(c.GetShape(xla_consts).tuple_shapes())\n+ xla_consts = tuple(xla.xla_destructure(c, xla_consts))\n+ arg_shapes = map(c.GetShape, xla_args)\n+ built_c = xla.jaxpr_computation(params['jaxpr'], (), consts_shapes, *arg_shapes)\n+ return c.Call(built_c, xla_consts + xla_args)\n+ xla.translations[staged_fun_p] = staged_fun_translation\n+\n+ return CustomTransformsFunction(fun, fun_p)\n+\n+def _check_custom_transforms_type(name, fun):\n+ if type(fun) is not CustomTransformsFunction:\n+ msg = (\"{} requires a custom_transforms function as its first argument, \"\n+ \"but got type {}.\")\n+ raise TypeError(msg.format(name, type(fun)))\n+\n+def defjvp_all(fun, custom_jvp):\n+ _check_custom_transforms_type(\"defjvp_all\", fun)\n+ def custom_transforms_jvp(primals, tangents, **params):\n+ jax_kwargs, jax_args = primals[0], primals[1:]\n+ _, jax_args_dot = tangents[0], tangents[1:]\n+ if jax_kwargs:\n+ msg = (\"defjvp_all requires the corresponding custom_transforms function \"\n+ \"not to be called with keyword arguments.\")\n+ raise ValueError(msg)\n+ in_trees = params['in_trees']\n+ args = tuple(map(build_tree, in_trees, jax_args))\n+ args_dot = tuple(map(build_tree, in_trees, jax_args_dot))\n+ pytree_out, pytree_out_dot = custom_jvp(args, args_dot)\n+ out, out_tree = pytree_to_jaxtupletree(pytree_out)\n+ out_dot, out_tree2 = pytree_to_jaxtupletree(pytree_out_dot)\n+ if out_tree != out_tree2:\n+ msg = (\"custom jvp rule returned different tree structures for primals \"\n+ \"and tangents, but they must be equal: {} vs {}.\")\n+ raise TypeError(msg.format(out_tree, out_tree2))\n+ params['out_tree'].store(out_tree) # linear_util style side effect\n+ return out, out_dot\n+ ad.primitive_jvps[fun.prim] = custom_transforms_jvp\n+\n+def defjvp(fun, *jvprules):\n+ _check_custom_transforms_type(\"defjvp\", fun)\n+ def custom_jvp(primals, tangents):\n+ ans = fun(*primals)\n+ tangents_out = [rule(t, *primals) for rule, t in zip(jvprules, tangents)\n+ if rule is not None and t is not ad_util.zero]\n+ return ans, reduce(ad.add_tangents, tangents_out, ad_util.zero)\n+ defjvp_all(fun, custom_jvp)\n+\n+def defjvp2(fun, *jvprules):\n+ _check_custom_transforms_type(\"defjvp2\", fun)\n+ def custom_jvp(primals, tangents):\n+ ans = fun(*primals)\n+ tangents_out = [rule(t, ans, *primals) for rule, t in zip(jvprules, tangents)\n+ if rule is not None and t is not ad_util.zero]\n+ return ans, reduce(ad.add_tangents, tangents_out, ad_util.zero)\n+ defjvp_all(fun, custom_jvp)\n+\n+def defvjp_all(fun, custom_vjp):\n+ _check_custom_transforms_type(\"defvjp_all\", fun)\n+ def custom_transforms_vjp(jax_kwargs, *jax_args, **params):\n+ if jax_kwargs:\n+ msg = (\"defvjp_all requires the corresponding custom_transforms function \"\n+ \"not to be called with keyword arguments.\")\n+ raise ValueError(msg)\n+ args = map(build_tree, params['in_trees'], jax_args)\n+ pytree_out, vjp_pytree = custom_vjp(*args)\n+ out, out_tree = pytree_to_jaxtupletree(pytree_out)\n+ params['out_tree'].store(out_tree) # linear_util style side effect\n+ vjp_pytree_ = lambda ct: ({},) + tuple(vjp_pytree(ct))\n+ vjp, _ = pytree_fun_to_jaxtupletree_fun(lu.wrap_init(vjp_pytree_), (out_tree,))\n+ return out, vjp.call_wrapped\n+ ad.defvjp_all(fun.prim, custom_transforms_vjp)\n+\n+def defvjp(fun, *vjprules):\n+ _check_custom_transforms_type(\"defvjp\", fun)\n+ def custom_vjp(*primals):\n+ ans = fun(*primals)\n+ # TODO(mattjj): avoid instantiating zeros?\n+ vjpfun = lambda ct: [vjp(ct, *primals) if vjp else ad_util.zeros_like_jaxval(x)\n+ for x, vjp in zip(primals, vjprules)]\n+ return ans, vjpfun\n+ defvjp_all(fun, custom_vjp)\n+\n+def defvjp2(fun, *vjprules):\n+ _check_custom_transforms_type(\"defvjp2\", fun)\n+ def custom_vjp(*primals):\n+ ans = fun(*primals)\n+ # TODO(mattjj): avoid instantiating zeros?\n+ vjpfun = lambda ct: [vjp(ct, ans, *primals) if vjp else ad_util.zeros_like_jaxval(x)\n+ for x, vjp in zip(primals, vjprules)]\n+ return ans, vjpfun\n+ defvjp_all(fun, custom_vjp)\n- @wraps(fun)\n- def traceable(*args, **kwargs):\n- # TODO(mattjj): pytrees to jaxtupletrees\n- return fun_p.bind(*args, **kwargs)\n- traceable.primitive = fun_p\n- return traceable\n+def jarrett(fun):\n+ new_fun = custom_transforms(fun)\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+ flat_tangents, _ = tree_flatten(tangents)\n+ out_tangent = sum([t * jac for t, jac in zip(flat_tangents, jacs)])\n+ return y, out_tangent\n+ defjvp_all(new_fun, elementwise_jvp)\n+\n+ return new_fun\ndef _elementwise_std_basis(pytree):\nleaves, _ = tree_flatten(pytree)\n@@ -987,19 +1129,6 @@ def _elementwise_std_basis(pytree):\nfor j in range(arity)]) for i in range(arity)])\nreturn _unravel_array_into_pytree(pytree, 1, basis_array)\n-def jarrett(fun):\n- new_fun = custom_transforms(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- flat_tangents, _ = tree_flatten(tangents)\n- out_tangent = sum([t * jac for t, jac in zip(flat_tangents, jacs)])\n- return y, out_tangent\n- ad.primitive_jvps[new_fun.primitive] = elementwise_jvp\n-\n- return new_fun\n-\n# This function mostly exists for making slides about JAX.\ndef _make_graphviz(fun):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -397,18 +397,19 @@ def add_tangents(x, y):\ndef defvjp_all(prim, custom_vjp):\n+ # see https://github.com/google/jax/pull/636\nname = prim.name\n- def fun_jvp(xs, ts):\n+ def fun_jvp(xs, ts, **params):\nts = map(instantiate_zeros, xs, ts) # TODO(mattjj): avoid instantiation?\n- primal_out, tangent_out = fun_jvp_p.bind(pack(xs), pack(ts))\n+ primal_out, tangent_out = fun_jvp_p.bind(pack(xs), pack(ts), **params)\nreturn primal_out, tangent_out\nprimitive_jvps[prim] = fun_jvp\nfun_jvp_p = core.Primitive('{name}_jvp'.format(name=name))\n- def fun_jvp_partial_eval(trace, *tracers):\n+ def fun_jvp_partial_eval(trace, *tracers, **params):\nprimals_tracer, tangents_tracer = tracers\n- primal_out, vjp_py = custom_vjp(*primals_tracer)\n+ primal_out, vjp_py = custom_vjp(*primals_tracer, **params)\nin_aval = raise_to_shaped(get_aval(primal_out))\nct_pval = pe.PartialVal((in_aval, core.unit))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -211,9 +211,10 @@ def partial_eval_wrapper(avals, *consts):\ndef abstract_eval_fun(fun, *avals, **params):\n- pvs_in = [PartialVal((a, unit)) for a in avals]\n- _, pvout, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvs_in, instantiate=True)\n- aval_out, _ = pvout\n+ pvals_in = [PartialVal((a, unit)) for a in avals]\n+ _, pval_out, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvals_in,\n+ instantiate=True)\n+ aval_out, _ = pval_out\nassert isinstance(aval_out, AbstractValue) # instantiate=True\nreturn aval_out\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -20,8 +20,7 @@ import numpy as onp\nimport scipy.special as osp_special\nfrom .. import lax\n-from ..api import custom_transforms\n-from ..interpreters import ad, batching\n+from ..api import custom_transforms, defjvp2\nfrom ..numpy import lax_numpy as np\nfrom ..numpy.lax_numpy import (_wraps, asarray, _reduction_dims, _constant_like,\n_promote_args_like)\n@@ -62,8 +61,7 @@ def erfinv(x):\ndef logit(x):\nx = asarray(x)\nreturn lax.log(lax.div(x, lax.sub(lax._const(x, 1), x)))\n-ad.defjvp2(logit.primitive, lambda g, ans, x: g / (x * (1 - x)))\n-batching.defvectorized(logit.primitive)\n+defjvp2(logit, lambda g, ans, x: g / (x * (1 - x)))\n@_wraps(osp_special.expit)\n@@ -72,8 +70,7 @@ def expit(x):\nx = asarray(x)\none = lax._const(x, 1)\nreturn lax.div(one, lax.add(one, lax.exp(lax.neg(x))))\n-ad.defjvp2(expit.primitive, lambda g, ans, x: g * ans * (lax._const(ans, 1) - ans))\n-batching.defvectorized(expit.primitive)\n+defjvp2(expit, lambda g, ans, x: g * ans * (lax._const(ans, 1) - ans))\n@_wraps(osp_special.logsumexp)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -26,7 +26,7 @@ import jax.numpy as np\nfrom jax import jit, grad, device_get, device_put, jacfwd, jacrev, hessian\nfrom jax import api\nfrom jax.core import Primitive, pack, JaxTuple\n-from jax.interpreters.ad import defjvp, defvjp, defvjp2, defvjp_all\n+from jax.interpreters import ad\nfrom jax.interpreters.xla import DeviceArray, DeviceTuple\nfrom jax.abstract_arrays import concretization_err_msg\nfrom jax import test_util as jtu\n@@ -242,7 +242,7 @@ class APITest(jtu.JaxTestCase):\n\"XLA translation rule for 'foo' not implemented\")\nfoo_p.def_impl(lambda x: x)\n- defjvp(foo_p, lambda g, x: foo(g))\n+ ad.defjvp(foo_p, lambda g, x: foo(g))\njtu.check_raises(lambda: grad(foo)(1.0), NotImplementedError,\n\"Reverse-mode differentiation rule for 'foo' not implemented\")\n@@ -473,7 +473,7 @@ class APITest(jtu.JaxTestCase):\nfoo_p = Primitive('foo')\ndef foo(x): return 2. * foo_p.bind(x)\n- defvjp_all(foo_p, lambda x: (x**2, lambda g: (4 * g * np.sin(x),)))\n+ ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (4 * g * np.sin(x),)))\nval_ans, grad_ans = api.value_and_grad(foo)(3.)\nself.assertAllClose(val_ans, 2 * 3.**2, check_dtypes=False)\nself.assertAllClose(grad_ans, 4 * 2 * onp.sin(3.), check_dtypes=False)\n@@ -482,7 +482,7 @@ class APITest(jtu.JaxTestCase):\nfoo_p = Primitive('foo')\ndef foo(x): return foo_p.bind(x)\n- defvjp_all(foo_p, lambda x: (x**2, lambda g: (12.,)))\n+ ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (12.,)))\nval_ans, grad_ans = api.value_and_grad(foo)(3.)\nself.assertAllClose(val_ans, 9., check_dtypes=False)\nself.assertAllClose(grad_ans, 12., check_dtypes=True)\n@@ -491,7 +491,7 @@ class APITest(jtu.JaxTestCase):\nfoo_p = Primitive('foo')\ndef foo(x): return 2. * foo_p.bind(x)\n- defvjp_all(foo_p, lambda x: (x**2, lambda g: (g * x ** 2,)))\n+ ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (g * x ** 2,)))\nans = api.grad(api.grad(foo))(3.)\nself.assertAllClose(ans, 2 * 2 * 3., check_dtypes=False)\n@@ -507,7 +507,7 @@ class APITest(jtu.JaxTestCase):\nvjp = lambda g: (g + x + y, g * x * 9.)\nreturn out, vjp\n- defvjp_all(foo_p, vjpfun)\n+ ad.defvjp_all(foo_p, vjpfun)\nval_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\nself.assertAllClose(val_ans, 3.**2 + 4.**3, check_dtypes=False)\nself.assertAllClose(grad_ans, 1. + 3. + 4., check_dtypes=False)\n@@ -515,12 +515,22 @@ class APITest(jtu.JaxTestCase):\nans = api.grad(foo, (0, 1))(3., 4.)\nself.assertAllClose(ans, (1. + 3. + 4., 1. * 3. * 9.), check_dtypes=False)\n+ def test_defvjp_all(self):\n+ @api.custom_transforms\n+ def foo(x):\n+ return np.sin(x)\n+\n+ api.defvjp_all(foo, lambda x: (np.sin(x), lambda g: (g * x,)))\n+ val_ans, grad_ans = api.value_and_grad(foo)(3.)\n+ self.assertAllClose(val_ans, onp.sin(3.), check_dtypes=False)\n+ self.assertAllClose(grad_ans, 3., check_dtypes=False)\n+\ndef test_defvjp(self):\n@api.custom_transforms\ndef foo(x, y):\nreturn np.sin(x * y)\n- defvjp(foo.primitive, None, lambda g, x, y: g * x * y)\n+ api.defvjp(foo, None, lambda g, x, y: g * x * y)\nval_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\nself.assertAllClose(val_ans, onp.sin(3. * 4.), check_dtypes=False)\nself.assertAllClose(grad_ans, 0., check_dtypes=False)\n@@ -529,17 +539,79 @@ class APITest(jtu.JaxTestCase):\nself.assertAllClose(ans_0, 0., check_dtypes=False)\nself.assertAllClose(ans_1, 3. * 4., check_dtypes=False)\n+ def test_defvjp_higher_order(self):\n+ @api.custom_transforms\n+ def foo(x):\n+ return np.sin(2. * x)\n+\n+ api.defvjp(foo, lambda g, x: g * np.cos(x))\n+ ans = api.grad(api.grad(foo))(2.)\n+ expected = api.grad(api.grad(np.sin))(2.)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef test_defvjp2(self):\n@api.custom_transforms\ndef foo(x, y):\nreturn np.sin(x * y)\n- defvjp2(foo.primitive, None, lambda g, ans, x, y: g * x * y + np.cos(ans))\n+ api.defvjp2(foo, None, lambda g, ans, x, y: g * x * y + np.cos(ans))\nval_ans, grad_ans = api.value_and_grad(foo, 1)(3., 4.)\nself.assertAllClose(val_ans, onp.sin(3. * 4.), check_dtypes=False)\nself.assertAllClose(grad_ans, 3. * 4. + onp.cos(onp.sin(3. * 4)),\ncheck_dtypes=False)\n+ def test_custom_transforms_eval_with_pytrees(self):\n+ @api.custom_transforms\n+ def f(x):\n+ a, b = x[0], x[1]\n+ return {'hi': 2 * a, 'bye': 2 * b}\n+\n+ ans = f((1, 2))\n+ self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n+\n+ def test_custom_transforms_jit_with_pytrees(self):\n+ @api.custom_transforms\n+ def f(x):\n+ a, b = x[0], x[1]\n+ return {'hi': 2 * a, 'bye': 2 * b}\n+\n+ ans = jit(f)((1, 2))\n+ self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n+\n+ def test_custom_transforms_jit_with_pytrees_consts(self):\n+ # The purpose of this test is to exercise the custom_transforms default\n+ # translation rule in how it deals with constants that are too large to be\n+ # treated as literals (at the time of writing).\n+ z = onp.arange(10.)\n+\n+ @api.custom_transforms\n+ def f(x):\n+ a, b = x[0], x[1]\n+ return {'hi': 2 * a, 'bye': z * b}\n+\n+ ans = jit(f)((1, 2))\n+ self.assertAllClose(ans, {'hi': 2 * 1, 'bye': z * 2}, check_dtypes=False)\n+\n+ def test_custom_transforms_jvp_with_pytrees(self):\n+ @api.custom_transforms\n+ def f(x):\n+ a, b = x[0], x[1]\n+ return {'hi': 2 * a, 'bye': 2 * b}\n+\n+ ans, out_tangent = api.jvp(f, ((1, 2),), ((3, 4),))\n+ self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n+ self.assertEqual(out_tangent, {'hi': 2 * 3, 'bye': 2 * 4})\n+\n+ def test_custom_transforms_vmap_with_pytrees(self):\n+ @api.custom_transforms\n+ def f(x):\n+ a, b = x[0], x[1]\n+ return {'hi': 2 * a, 'bye': 2 * b}\n+\n+ ans = api.vmap(f)((onp.arange(3), onp.ones((3, 2))))\n+ expected = {'hi': 2 * onp.arange(3), 'bye': 2 * onp.ones((3, 2))}\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef test_devicetuple_iteration(self):\ntup = device_put(pack((1, 2)))\nself.assertIsInstance(tup, DeviceTuple)\n"
}
] | Python | Apache License 2.0 | google/jax | make custom_transforms handle pytrees, add api.defvjp
With advice from @dougalm! |
260,335 | 05.06.2019 13:20:44 | 25,200 | 372d60bb08232e171a9480c6b1e66827b72c439e | add docstring to custom_transforms | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -73,8 +73,8 @@ def jit(fun, static_argnums=()):\nArgs:\nfun: Function to be jitted. Should be a pure function, as side-effects may\n- only be executed once. Its positional arguments and return value should be\n- arrays, scalars, or standard Python containers (tuple/list/dict) thereof.\n+ only be executed once. Its arguments and return value should be arrays,\n+ scalars, or (nested) standard Python containers (tuple/list/dict) thereof.\nPositional arguments indicated by `static_argnums` can be anything at all,\nprovided they are hashable and have an equality operation defined. Static\n@@ -972,6 +972,58 @@ class CustomTransformsFunction(object):\nreturn build_tree(out_tree.val, ans)\ndef custom_transforms(fun):\n+ \"\"\"Wraps a function so that its transformation behavior can be overridden.\n+\n+ A primary use case of ``custom_transforms`` is defining custom VJP rules (aka\n+ custom gradients) for a Python function, while still supporting other\n+ transformations like ``jax.jit`` and ``jax.vmap``. Custom differentiation\n+ rules can be supplied using the ``jax.defjvp`` and ``jax.defvjp`` functions.\n+\n+ JAX transforms Python functions by tracing which primitive operations (like\n+ black-box numerical kernels) are applied to the function's input arguments to\n+ produce its output, then transforming that recorded composition of primitives\n+ using a table of transformation rules for each primitive. That is, for each\n+ transformation (e.g. ``jax.jvp`` or ``jax.vmap``) there is a table of rules\n+ that specifies how each primitive is transformed. When a new primitive is\n+ added to the system, it also needs a rule for each transformation we might\n+ want to apply to it.\n+\n+ But in some cases instead of introducing a new primitive and specifying every\n+ transformation rule, we might start with a traceable/transformable Python\n+ function and want to override just its VJP (i.e. give it a custom gradient).\n+ More concretely, we might start with a Python function to which we can already\n+ apply ``jax.jit``, but we want to change how ``jax.grad`` behaves on it. These\n+ are the cases that ``custom_transforms`` handles.\n+\n+ The ``custom_transforms`` decorator wraps ``fun`` so that its transformation\n+ behavior can be overridden, but not all transformation rules need to be\n+ specified manually. For rules that aren't overridden, a default rule is used\n+ for each transformation that relies on tracing ``fun``.\n+\n+ Args:\n+ fun: a Python function. Must be functionally pure. Its arguments and return\n+ value should be arrays, scalars, or (nested) standard Python containers\n+ (tuple/list/dict) thereof.\n+\n+ Returns:\n+ A Python callable with the same input/output and transformation behavior as\n+ ``fun``, but for which custom transformation rules can be supplied, e.g.\n+ using ``jax.defvjp``.\n+\n+ For example:\n+\n+ >>> @jax.custom_transforms\n+ ... def f(x):\n+ ... return np.sin(x ** 2)\n+ ...\n+ >>> print(f(3.))\n+ 0.4121185\n+ >>> print(jax.grad(f)(3.))\n+ -5.4667816\n+ >>> jax.defvjp(f, lambda g, x: g * x)\n+ >>> print(jax.grad(f)(3.))\n+ 3.0\n+ \"\"\"\nname = getattr(fun, '__name__', '<unnamed custom_transforms primitive>')\nfun_p = core.Primitive(name)\n"
}
] | Python | Apache License 2.0 | google/jax | add docstring to custom_transforms |
260,335 | 05.06.2019 13:48:04 | 25,200 | 720dec4072ed9c0ead049ce90321d600110192f1 | add custom_gradient | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.rst",
"new_path": "docs/jax.rst",
"diff": "@@ -19,6 +19,6 @@ Module contents\n---------------\n.. automodule:: jax\n- :members: jit, disable_jit, grad, value_and_grad, vmap, pmap, jacfwd, jacrev, hessian, jvp, linearize, vjp, make_jaxpr, eval_shape\n+ :members: jit, disable_jit, grad, value_and_grad, vmap, pmap, jacfwd, jacrev, hessian, jvp, linearize, vjp, make_jaxpr, eval_shape, custom_transforms\n:undoc-members:\n:show-inheritance:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -972,7 +972,7 @@ class CustomTransformsFunction(object):\nreturn build_tree(out_tree.val, ans)\ndef custom_transforms(fun):\n- \"\"\"Wraps a function so that its transformation behavior can be overridden.\n+ \"\"\"Wraps a function so that its transformation behavior can be controlled.\nA primary use case of ``custom_transforms`` is defining custom VJP rules (aka\ncustom gradients) for a Python function, while still supporting other\n@@ -1001,7 +1001,7 @@ def custom_transforms(fun):\nfor each transformation that relies on tracing ``fun``.\nArgs:\n- fun: a Python function. Must be functionally pure. Its arguments and return\n+ fun: a Python callable. Must be functionally pure. Its arguments and return\nvalue should be arrays, scalars, or (nested) standard Python containers\n(tuple/list/dict) thereof.\n@@ -1076,6 +1076,7 @@ def _check_custom_transforms_type(name, fun):\nraise TypeError(msg.format(name, type(fun)))\ndef defjvp_all(fun, custom_jvp):\n+ \"\"\"Define a custom JVP rule for a custom_transforms function.\"\"\"\n_check_custom_transforms_type(\"defjvp_all\", fun)\ndef custom_transforms_jvp(primals, tangents, **params):\njax_kwargs, jax_args = primals[0], primals[1:]\n@@ -1152,6 +1153,50 @@ def defvjp2(fun, *vjprules):\nreturn ans, vjpfun\ndefvjp_all(fun, custom_vjp)\n+def custom_gradient(fun):\n+ \"\"\"Convenience function for defining custom VJP rules (aka custom gradients).\n+\n+ While the canonical way to define custom VJP rules is via ``jax.defvjp_all``\n+ and its convenience wrappers, the ``custom_gradient`` convenience wrapper\n+ follows TensorFlow's tf.custom_gradient API.\n+\n+ See https://www.tensorflow.org/api_docs/python/tf/custom_gradient.\n+\n+ If the function to be differentiated has type signature ``a -> b``, then the\n+ Python callable ``fun`` should have signature ``a -> (b, CT b -> CT a)`` where\n+ we use ``CT x`` to denote a cotangent type for ``x``. See the example below.\n+\n+ Args:\n+ fun: a Python callable specifying both the function to be differentiated and\n+ its reverse-mode differentiation rule. It should return a pair consisting\n+ of an output value and a Python callable that represents the custom\n+ gradient function.\n+\n+ Returns:\n+ A Python callable with signature ``a -> b``, i.e. that returns the output\n+ value specified by the first element of ``fun``'s output pair. A side effect\n+ is that under-the-hood ``jax.defvjp_all`` was called to set up the returned\n+ Python callable to have the custom VJP rule specified by the second element\n+ of ``fun``'s output pair.\n+\n+ For example:\n+\n+ >>> @jax.custom_gradient\n+ ... def f(x):\n+ ... return x ** 2, lambda g: (g * x,)\n+ ...\n+ >>> print(f(3.))\n+ 9.0\n+ >>> print(jax.grad(f)(3.))\n+ 3.0\n+ \"\"\"\n+ def primal_fun(*args, **kwargs):\n+ ans, _ = fun(*args, **kwargs)\n+ return ans\n+ primal_fun = custom_transforms(primal_fun)\n+ defvjp_all(primal_fun, fun)\n+ return primal_fun\n+\ndef jarrett(fun):\nnew_fun = custom_transforms(fun)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -612,6 +612,14 @@ class APITest(jtu.JaxTestCase):\nexpected = {'hi': 2 * onp.arange(3), 'bye': 2 * onp.ones((3, 2))}\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_custom_gradient(self):\n+ @api.custom_gradient\n+ def f(x):\n+ return x ** 2, lambda g: (g * x,)\n+\n+ self.assertEqual(f(3.), 9.)\n+ self.assertEqual(api.grad(f)(3.), 3.)\n+\ndef test_devicetuple_iteration(self):\ntup = device_put(pack((1, 2)))\nself.assertIsInstance(tup, DeviceTuple)\n"
}
] | Python | Apache License 2.0 | google/jax | add custom_gradient |
260,335 | 05.06.2019 17:04:33 | 25,200 | 9e49500c54b7a51eb379b4625275e30ec9b0921c | simplify gather shape rule | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2631,22 +2631,11 @@ def _gather_shape_rule(operand, start_indices, dimension_numbers, slice_sizes,\nmsg = (\"slice_sizes must have rank equal to the gather operand; \"\n\"operand.shape={}, slice_sizes={}\".format(operand_shape, slice_sizes))\nraise ValueError(msg)\n- expanded_start_indices_shape = list(start_indices.shape)\n- result_rank = len(dimension_numbers.offset_dims)\n- result_rank += len(expanded_start_indices_shape) - 1\n- output_shape = []\n- offset_dims_seen = 0\n- gather_dims_seen = 0\n- for i in xrange(result_rank):\n- if i in dimension_numbers.offset_dims:\n- while offset_dims_seen in dimension_numbers.collapsed_slice_dims:\n- offset_dims_seen += 1\n- output_shape.append(slice_sizes[offset_dims_seen])\n- offset_dims_seen += 1\n- else:\n- output_shape.append(expanded_start_indices_shape[gather_dims_seen])\n- gather_dims_seen += 1\n- return tuple(output_shape)\n+ result_rank = len(dimension_numbers.offset_dims) + start_indices.ndim - 1\n+ start_indices_shape = iter(start_indices.shape[:-1])\n+ slice_sizes = iter(onp.delete(slice_sizes, dimension_numbers.collapsed_slice_dims))\n+ return tuple(next(slice_sizes) if i in dimension_numbers.offset_dims\n+ else next(start_indices_shape) for i in range(result_rank))\ndef _gather_translation_rule(c, operand, start_indices, dimension_numbers,\nslice_sizes, operand_shape):\n"
}
] | Python | Apache License 2.0 | google/jax | simplify gather shape rule
Co-authored-by: Roy Frostig <frostig@google.com> |
260,335 | 05.06.2019 16:56:43 | 25,200 | ab20f0292ca22ee68c7c7debe12467ff932d8ce3 | add docstring for defjvp_all | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.rst",
"new_path": "docs/jax.rst",
"diff": "@@ -19,6 +19,6 @@ Module contents\n---------------\n.. automodule:: jax\n- :members: jit, disable_jit, grad, value_and_grad, vmap, pmap, jacfwd, jacrev, hessian, jvp, linearize, vjp, make_jaxpr, eval_shape, custom_transforms\n+ :members: jit, disable_jit, grad, value_and_grad, vmap, pmap, jacfwd, jacrev, hessian, jvp, linearize, vjp, make_jaxpr, eval_shape, custom_transforms, defjvp, defjvp2, defjvp_all, defvjp, defvjp2, defvjp_all, custom_gradient\n:undoc-members:\n:show-inheritance:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1076,7 +1076,47 @@ def _check_custom_transforms_type(name, fun):\nraise TypeError(msg.format(name, type(fun)))\ndef defjvp_all(fun, custom_jvp):\n- \"\"\"Define a custom JVP rule for a custom_transforms function.\"\"\"\n+ \"\"\"Define a custom JVP rule for a custom_transforms function.\n+\n+ If ``fun`` represents a function with signature ``a -> b``, then\n+ ``custom_jvp`` represents a function with signature ``a -> T a -> (b, Tb)``,\n+ where we use ``T x`` to represent a tangent type for the type ``x``.\n+\n+ Defining a custom JVP rule will also affect the dfeault VJP rule, which is\n+ derived from the JVP rule automatically via transposition.\n+\n+ Args:\n+ fun: a custom_transforms function.\n+ custom_jvp: a Python callable specifying the JVP rule, taking two tuples as\n+ arguments specifying the input primal values and tangent values,\n+ respectively. The tuple elements can be arrays, scalars, or (nested)\n+ standard Python containers (tuple/list/dict) thereof. Must be functionally\n+ pure.\n+\n+ Returns:\n+ None. A side-effect is that ``fun`` is associated with the JVP rule\n+ specified by ``custom_jvp``.\n+\n+ For example:\n+\n+ >>> @jax.custom_transforms\n+ ... def f(x):\n+ ... return np.sin(x ** 2)\n+ ...\n+ >>> print(f(3.))\n+ 0.4121185\n+ >>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))\n+ >>> print(out_primal)\n+ 0.4121185\n+ >>> print(out_tangent)\n+ -10.933563\n+ >>> jax.defjvp_all(f, lambda ps, ts: (np.sin(ps[0] ** 2), 8. * ts[0]))\n+ >>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))\n+ >>> print(out_primal)\n+ 0.4121185\n+ >>> print(out_tangent)\n+ 16.0\n+ \"\"\"\n_check_custom_transforms_type(\"defjvp_all\", fun)\ndef custom_transforms_jvp(primals, tangents, **params):\njax_kwargs, jax_args = primals[0], primals[1:]\n"
}
] | Python | Apache License 2.0 | google/jax | add docstring for defjvp_all |
260,335 | 05.06.2019 17:56:18 | 25,200 | 948ec8fbe8ef887935cbf53ec0d83265cafcaa8a | add docstrings for defjvp and defjvp2 | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1082,8 +1082,15 @@ def defjvp_all(fun, custom_jvp):\n``custom_jvp`` represents a function with signature ``a -> T a -> (b, Tb)``,\nwhere we use ``T x`` to represent a tangent type for the type ``x``.\n- Defining a custom JVP rule will also affect the dfeault VJP rule, which is\n- derived from the JVP rule automatically via transposition.\n+ In more detail, ``custom_jvp`` must two arguments, both tuples of length equal\n+ to the number of positional arguments to ``fun``. The first argument to\n+ ``custom_jvp`` represents the input primal values, and the second represents\n+ the input tangent values. ``custom_jvp`` must return a pair where the first\n+ element represents the output primal value and the second element represents\n+ the output tangent value.\n+\n+ Defining a custom JVP rule also affects the default VJP rule, which is derived\n+ from the JVP rule automatically via transposition.\nArgs:\nfun: a custom_transforms function.\n@@ -1140,6 +1147,73 @@ def defjvp_all(fun, custom_jvp):\nad.primitive_jvps[fun.prim] = custom_transforms_jvp\ndef defjvp(fun, *jvprules):\n+ \"\"\"Definine JVP rules for each argument separately.\n+\n+ This function is a convenience wrapper around ``jax.defjvp_all`` for separately\n+ defining JVP rules for each of the function's arguments. This convenience\n+ wrapper does not provide a mechanism for depending on anything other than the\n+ function arguments, so JVP rules defined in this way can't share work with the\n+ primal computation or with each other, though those things are possible using\n+ ``jax.defjvp_all``. See ``jax.defjvp2`` for a variant that allows for defining\n+ rules that depend on the output primal value. See also the ``jax.defjvp_all``\n+ docstring for more detail.\n+\n+ The signature of each component JVP rule is ``lambda g, *primals: ...`` where\n+ ``g`` represents the tangent of the corresponding positional argument and\n+ ``*primals`` represents all the primal positional arguments.\n+\n+ Defining a custom JVP rule also affects the default VJP rule, which is derived\n+ from the JVP rule automatically via transposition.\n+\n+ Args:\n+ fun: a custom_transforms function.\n+ *jvprules: a sequence of functions or Nones specifying the JVP rule for each\n+ corresponding positional argument. When an element is None, it indicates\n+ that the Jacobian from the corresponding input to the output is zero.\n+\n+ Returns:\n+ None. A side-effect is that ``fun`` is associated with the JVP rule\n+ specified by ``*jvprules``.\n+\n+ For example:\n+\n+ >>> @jax.custom_transforms\n+ ... def f(x):\n+ ... return np.sin(x ** 2)\n+ ...\n+ >>> print(f(3.))\n+ 0.4121185\n+ >>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))\n+ >>> print(out_primal)\n+ 0.4121185\n+ >>> print(out_tangent)\n+ -10.933563\n+ >>> jax.defjvp(f, lambda g, x: 8. * g)\n+ >>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))\n+ >>> print(out_primal)\n+ 0.4121185\n+ >>> print(out_tangent)\n+ 16.0\n+\n+ An example with a function on two arguments:\n+ >>> @jax.custom_transforms\n+ ... def f(x, y):\n+ ... return np.sin(x ** 2 + y)\n+ ...\n+ >>> print(f(3., 4.))\n+ 0.42016703\n+ >>> out_primal, out_tangent = jax.jvp(f, (3., 4.), (1., 2.))\n+ >>> print(out_primal)\n+ 0.42016703\n+ >>> print(out_tangent)\n+ 7.2595744\n+ >>> jax.defjvp(f, None, lambda g, x, y: 8. * g + y)\n+ >>> out_primal, out_tangent = jax.jvp(f, (3., 4.), (1., 2.))\n+ >>> print(out_primal)\n+ 0.42016703\n+ >>> print(out_tangent)\n+ 20.0\n+ \"\"\"\n_check_custom_transforms_type(\"defjvp\", fun)\ndef custom_jvp(primals, tangents):\nans = fun(*primals)\n@@ -1149,6 +1223,53 @@ def defjvp(fun, *jvprules):\ndefjvp_all(fun, custom_jvp)\ndef defjvp2(fun, *jvprules):\n+ \"\"\"Definine JVP rules for each argument separately.\n+\n+ This function is a convenience wrapper around ``jax.defjvp_all`` for separately\n+ defining JVP rules for each of the function's arguments. This convenience\n+ wrapper does not provide a mechanism for depending on anything other than the\n+ function arguments, so JVP rules defined in this way can't share work with the\n+ primal computation or with each other, though those things are possible using\n+ ``jax.defjvp_all``. See the ``jax.defjvp_all`` docstring for more detail.\n+\n+ The signature of each component JVP rule is ``lambda g, ans, *primals: ...``\n+ where ``g`` represents the tangent of the corresponding positional argument,\n+ ``ans`` represents the output primal, and ``*primals`` represents all the\n+ primal positional arguments.\n+\n+ Defining a custom JVP rule also affects the default VJP rule, which is derived\n+ from the JVP rule automatically via transposition.\n+\n+ Args:\n+ fun: a custom_transforms function.\n+ *jvprules: a sequence of functions or Nones specifying the JVP rule for each\n+ corresponding positional argument. When an element is None, it indicates\n+ that the Jacobian from the corresponding input to the output is zero.\n+\n+ Returns:\n+ None. A side-effect is that ``fun`` is associated with the JVP rule\n+ specified by ``*jvprules``.\n+\n+ For example:\n+\n+ >>> @jax.custom_transforms\n+ ... def f(x):\n+ ... return np.sin(x ** 2)\n+ ...\n+ >>> print(f(3.))\n+ 0.4121185\n+ >>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))\n+ >>> print(out_primal)\n+ 0.4121185\n+ >>> print(out_tangent)\n+ -10.933563\n+ >>> jax.defjvp2(f, lambda g, ans, x: 8. * g + ans)\n+ >>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))\n+ >>> print(out_primal)\n+ 0.4121185\n+ >>> print(out_tangent)\n+ 16.412119\n+ \"\"\"\n_check_custom_transforms_type(\"defjvp2\", fun)\ndef custom_jvp(primals, tangents):\nans = fun(*primals)\n"
}
] | Python | Apache License 2.0 | google/jax | add docstrings for defjvp and defjvp2 |
260,335 | 05.06.2019 18:02:15 | 25,200 | cfaa49f8843f2c1bfa18dc4d42f291ad72be362f | improve custom_gradient docstring | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1326,6 +1326,14 @@ def custom_gradient(fun):\nIf the function to be differentiated has type signature ``a -> b``, then the\nPython callable ``fun`` should have signature ``a -> (b, CT b -> CT a)`` where\nwe use ``CT x`` to denote a cotangent type for ``x``. See the example below.\n+ That is, ``fun`` should return a pair where the first element represents the\n+ value of the function to be differentiated and the second element is a\n+ function that represents the custom VJP rule.\n+\n+ The custom VJP function returned as the second element of the output of ``fun``\n+ can close over intermediate values computed when evaluating the function to be\n+ differentiated. That is, use lexical closure to share work between the forward\n+ pass and the backward pass of reverse-mode automatic differentiation.\nArgs:\nfun: a Python callable specifying both the function to be differentiated and\n"
}
] | Python | Apache License 2.0 | google/jax | improve custom_gradient docstring |
260,335 | 05.06.2019 19:13:33 | 25,200 | a6c41a323c1c9a4bd737fae31de889d7828b401d | finish drafting defvjp/defjvp docstrings | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1076,7 +1076,7 @@ def _check_custom_transforms_type(name, fun):\nraise TypeError(msg.format(name, type(fun)))\ndef defjvp_all(fun, custom_jvp):\n- \"\"\"Define a custom JVP rule for a custom_transforms function.\n+ \"\"\"Define a custom JVP rule for a ``custom_transforms`` function.\nIf ``fun`` represents a function with signature ``a -> b``, then\n``custom_jvp`` represents a function with signature ``a -> T a -> (b, Tb)``,\n@@ -1149,14 +1149,14 @@ def defjvp_all(fun, custom_jvp):\ndef defjvp(fun, *jvprules):\n\"\"\"Definine JVP rules for each argument separately.\n- This function is a convenience wrapper around ``jax.defjvp_all`` for separately\n- defining JVP rules for each of the function's arguments. This convenience\n- wrapper does not provide a mechanism for depending on anything other than the\n- function arguments, so JVP rules defined in this way can't share work with the\n- primal computation or with each other, though those things are possible using\n- ``jax.defjvp_all``. See ``jax.defjvp2`` for a variant that allows for defining\n- rules that depend on the output primal value. See also the ``jax.defjvp_all``\n- docstring for more detail.\n+ This function is a convenience wrapper around ``jax.defjvp_all`` for\n+ separately defining JVP rules for each of the function's arguments. This\n+ convenience wrapper does not provide a mechanism for depending on anything\n+ other than the function arguments, so JVP rules defined in this way can't\n+ share work with the primal computation or with each other, though those things\n+ are possible using ``jax.defjvp_all``. See ``jax.defjvp2`` for a variant that\n+ allows for defining rules that depend on the output primal value. See also the\n+ ``jax.defjvp_all`` docstring for more detail.\nThe signature of each component JVP rule is ``lambda g, *primals: ...`` where\n``g`` represents the tangent of the corresponding positional argument and\n@@ -1196,6 +1196,7 @@ def defjvp(fun, *jvprules):\n16.0\nAn example with a function on two arguments:\n+\n>>> @jax.custom_transforms\n... def f(x, y):\n... return np.sin(x ** 2 + y)\n@@ -1228,9 +1229,7 @@ def defjvp2(fun, *jvprules):\nThis function is a convenience wrapper around ``jax.defjvp_all`` for separately\ndefining JVP rules for each of the function's arguments. This convenience\nwrapper does not provide a mechanism for depending on anything other than the\n- function arguments, so JVP rules defined in this way can't share work with the\n- primal computation or with each other, though those things are possible using\n- ``jax.defjvp_all``. See the ``jax.defjvp_all`` docstring for more detail.\n+ function arguments and its primal output value.\nThe signature of each component JVP rule is ``lambda g, ans, *primals: ...``\nwhere ``g`` represents the tangent of the corresponding positional argument,\n@@ -1279,6 +1278,70 @@ def defjvp2(fun, *jvprules):\ndefjvp_all(fun, custom_jvp)\ndef defvjp_all(fun, custom_vjp):\n+ \"\"\"Define a custom VJP rule for a ``custom_transforms`` function.\n+\n+ If ``fun`` represents a function with signature ``a -> b``, then\n+ ``custom_vjp`` represents a function with signature ``a -> (b, CT b -> CT a)``\n+ where we use ``CT x`` to represent a cotangent type for the type ``x``. That\n+ is, ``custom_vjp`` should take the same arguments as ``fun`` and return a pair\n+ where the first element represents the primal value of ``fun`` applied to the\n+ arguments, and the second element is a VJP function that maps from output\n+ cotangents to input cotangents, returning a tuple with length equal to the\n+ number of positional arguments supplied to ``fun``.\n+\n+ The VJP function returned as the second element of the output of\n+ ``custom_vjp`` can close over intermediate values computed when evaluating the\n+ primal value of ``fun``. That is, use lexical closure to share work between\n+ the forward pass and the backward pass of reverse-mode automatic\n+ differentiation.\n+\n+ See also ``jax.custom_gradient``.\n+\n+ Args:\n+ fun: a custom_transforms function.\n+ custom_vjp: a Python callable specifying the VJP rule, taking the same\n+ arguments as ``fun`` and returning a pair where the first elment is the\n+ value of ``fun`` applied to the arguments and the second element is a\n+ Python callable representing the VJP map from output cotangents to input\n+ cotangents. The returned VJP function must accept a value with the same\n+ shape as the value of ``fun`` applied to the arguments and must return a\n+ tuple with length equal to the number of positional arguments to ``fun``.\n+ Arguments can be arrays, scalars, or (nested) standard Python containers\n+ (tuple/list/dict) thereof. Must be functionally pure.\n+\n+ Returns:\n+ None. A side-effect is that ``fun`` is associated with the VJP rule\n+ specified by ``custom_vjp``.\n+\n+ For example:\n+\n+ >>> @jax.custom_transforms\n+ ... def f(x):\n+ ... return np.sin(x ** 2)\n+ ...\n+ >>> print(f(3.))\n+ 0.4121185\n+ >>> print(jax.grad(f)(3.))\n+ -5.4667816\n+ >>> jax.defvjp_all(f, lambda x: (np.sin(x ** 2), lambda g: (g * x,)))\n+ >>> print(f(3.))\n+ 0.4121185\n+ >>> print(jax.grad(f)(3.))\n+ 3.0\n+\n+ An example with a function on two arguments, so that the VJP function must\n+ return a tuple of length two:\n+\n+ >>> @jax.custom_transforms\n+ ... def f(x, y):\n+ ... return x * y\n+ ...\n+ >>> jax.defvjp_all(f, lambda x, y: (x * y, lambda g: (y, x)))\n+ >>> print(f(3., 4.))\n+ 12.0\n+ >>> print(jax.grad(f, argnums=(0, 1))(3., 4.))\n+ (4.0, 3.0)\n+ \"\"\"\n_check_custom_transforms_type(\"defvjp_all\", fun)\ndef custom_transforms_vjp(jax_kwargs, *jax_args, **params):\nif jax_kwargs:\n@@ -1289,12 +1352,75 @@ def defvjp_all(fun, custom_vjp):\npytree_out, vjp_pytree = custom_vjp(*args)\nout, out_tree = pytree_to_jaxtupletree(pytree_out)\nparams['out_tree'].store(out_tree) # linear_util style side effect\n- vjp_pytree_ = lambda ct: ({},) + tuple(vjp_pytree(ct))\n+ def vjp_pytree_(ct):\n+ args_cts = tuple(vjp_pytree(ct))\n+ if len(args_cts) != len(params['in_trees']):\n+ msg = (\"custom VJP function must return a tuple of length equal to the \"\n+ \"number of positional arguments to the function being \"\n+ \"differentiated: expected {}, got {}\")\n+ raise TypeError(msg.format(len(params['in_trees']), len(args_cts)))\n+ return ({},) + args_cts\nvjp, _ = pytree_fun_to_jaxtupletree_fun(lu.wrap_init(vjp_pytree_), (out_tree,))\nreturn out, vjp.call_wrapped\nad.defvjp_all(fun.prim, custom_transforms_vjp)\ndef defvjp(fun, *vjprules):\n+ \"\"\"Define VJP rules for each argument separately.\n+\n+ This function is a convenience wrapper around ``jax.defvjp_all`` for\n+ separately defining VJP rules for each of the function's arguments. This\n+ convenience wrapper does not provide a mechanism for depending on anything\n+ other than the function arguments, so VJP rules defined in this way can't\n+ share work with the primal computation or with each other, though those things\n+ are possible using ``jax.defvjp_all`` or ``jax.custom_gradient``. See\n+ ``jax.defvjp2`` for a variant that allows for defining rules that depend on\n+ the output primal value. See also the ``jax.defvjp_all`` docstring.\n+\n+ The signature of each component VJP rule is ``lambda g, *primals: ...`` where\n+ ``g`` represents the output cotangent and ``*primals`` represents all the\n+ primal positional arguments.\n+\n+ Args:\n+ fun: a custom_transforms function.\n+ *vjprules: a sequence of functions or Nones specifying the VJP rule for each\n+ corresponding positional argument. When an element is None, it indicates\n+ that the Jacobian from the corresponding input to the output is zero.\n+\n+ Returns:\n+ None. A side-effect is that ``fun`` is associated with the VJP rule\n+ specified by ``*vjprules``.\n+\n+ For example:\n+\n+ >>> @jax.custom_transforms\n+ ... def f(x):\n+ ... return np.sin(x ** 2)\n+ ...\n+ >>> print(f(3.))\n+ 0.4121185\n+ >>> print(jax.grad(f)(3.))\n+ >>> jax.defvjp(f, lambda g, x: 8. * g)\n+ >>> print(jax.grad(f)(3.))\n+ 8.0\n+\n+ An example with a function on two arguments:\n+\n+ >>> @jax.custom_transforms\n+ ... def f(x, y):\n+ ... return np.sin(x ** 2 + y)\n+ ...\n+ >>> print(f(3., 4.))\n+ 0.42016703\n+ >>> print(jax.grad(f)(3., 4.))\n+ 5.4446807\n+ >>> print(jax.grad(f, 1)(3., 4.))\n+ 0.9074468\n+ >>> jax.defvjp(f, None, lambda g, x, y: g + x + y)\n+ >>> print(jax.grad(f)(3., 4.))\n+ 0.0\n+ >>> print(jax.grad(f, 1)(3., 4.))\n+ 8.0\n+ \"\"\"\n_check_custom_transforms_type(\"defvjp\", fun)\ndef custom_vjp(*primals):\nans = fun(*primals)\n@@ -1305,6 +1431,45 @@ def defvjp(fun, *vjprules):\ndefvjp_all(fun, custom_vjp)\ndef defvjp2(fun, *vjprules):\n+ \"\"\"Define VJP rules for each argument separately.\n+\n+ This function is a convenience wrapper around ``jax.defvjp_all`` for\n+ separately defining VJP rules for each of the function's arguments. This\n+ convenience wrapper does not provide a mechanism for depending on anything\n+ other than the function arguments and its primal output value.\n+\n+ The signature of each component VJP rule is ``lambda g, ans, *primals: ...``\n+ where ``g`` represents the output cotangent, ``ans`` represents the output\n+ primal, and ``*primals`` represents all the primal positional arguments.\n+\n+ Args:\n+ fun: a custom_transforms function.\n+ *vjprules: a sequence of functions or Nones specifying the VJP rule for each\n+ corresponding positional argument. When an element is None, it indicates\n+ that the Jacobian from the corresponding input to the output is zero.\n+\n+ Returns:\n+ None. A side-effect is that ``fun`` is associated with the VJP rule\n+ specified by ``*vjprules``.\n+\n+ For example:\n+\n+ >>> @jax.custom_transforms\n+ ... def f(x, y):\n+ ... return np.sin(x ** 2 + y)\n+ ...\n+ >>> print(f(3., 4.))\n+ 0.42016703\n+ >>> print(jax.grad(f)(3., 4.))\n+ 5.4446807\n+ >>> print(jax.grad(f, 1)(3., 4.))\n+ 0.9074468\n+ >>> jax.defvjp2(f, None, lambda g, ans, x, y: g + x + y + ans)\n+ >>> print(jax.grad(f)(3., 4.))\n+ 0.0\n+ >>> print(jax.grad(f, 1)(3., 4.))\n+ 8.420167\n+ \"\"\"\n_check_custom_transforms_type(\"defvjp2\", fun)\ndef custom_vjp(*primals):\nans = fun(*primals)\n@@ -1358,6 +1523,18 @@ def custom_gradient(fun):\n9.0\n>>> print(jax.grad(f)(3.))\n3.0\n+\n+ An example with a function on two arguments, so that the VJP function must\n+ return a tuple of length two:\n+\n+ >>> @jax.custom_gradient\n+ ... def f(x, y):\n+ ... return x * y, lambda g: (y, x)\n+ ...\n+ >>> print(f(3., 4.))\n+ 12.0\n+ >>> print(jax.grad(f, argnums=(0, 1))(3., 4.))\n+ (4.0, 3.0)\n\"\"\"\ndef primal_fun(*args, **kwargs):\nans, _ = fun(*args, **kwargs)\n"
}
] | Python | Apache License 2.0 | google/jax | finish drafting defvjp/defjvp docstrings |
260,288 | 05.06.2019 18:43:58 | 25,200 | 305127d814b5b282190f166cd8b911b3fc749a0e | Changes to jax optimizers.py to facilitate serialization of optimizer state. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optimizers.py",
"new_path": "jax/experimental/optimizers.py",
"diff": "@@ -423,3 +423,51 @@ def clip_grads(grad_tree, max_norm):\nnorm = l2_norm(grad_tree)\nnormalize = lambda g: np.where(norm < max_norm, g, g * (max_norm / norm))\nreturn tree_map(normalize, grad_tree)\n+\n+\n+### serialization utilities\n+\n+class JoinPoint(object):\n+ \"\"\"Marks the boundary between two joined (nested) pytrees.\"\"\"\n+ def __init__(self, subtree):\n+ self.subtree = subtree\n+\n+ # Since pytrees are containers of numpy arrays, look iterable.\n+ def __iter__(self):\n+ yield self.subtree\n+\n+def unpack_optimizer_state(opt_state):\n+ \"\"\"Converts an OptimizerState to a marked pytree.\n+\n+ Converts an OptimizerState to a marked pytree with the leaves of the outer\n+ pytree represented as JoinPoints to avoid losing information. This function is\n+ intended to be useful when serializing optimizer states.\n+\n+ Args:\n+ opt_state: An OptimizerState\n+ Returns:\n+ A pytree with JoinPoint leaves that contain a second level of pytrees.\n+ \"\"\"\n+ packed_state, tree_def, subtree_defs = opt_state\n+ subtrees = map(tree_unflatten, subtree_defs, packed_state)\n+ sentinels = [JoinPoint(subtree) for subtree in subtrees]\n+ return tree_util.tree_unflatten(tree_def, sentinels)\n+\n+def pack_optimizer_state(marked_pytree):\n+ \"\"\"Converts a marked pytree to an OptimizerState.\n+\n+ The inverse of unpack_optimizer_state. Converts a marked pytree with the\n+ leaves of the outer pytree represented as JoinPoints back into an\n+ OptimizerState. This function is intended to be useful when deserializing\n+ optimizer states.\n+\n+ Args:\n+ marked_pytree: A pytree containing JoinPoint leaves that hold more pytrees.\n+ Returns:\n+ An equivalent OptimizerState to the input argument.\n+ \"\"\"\n+ sentinels, tree_def = tree_flatten(marked_pytree)\n+ assert all(isinstance(s, JoinPoint) for s in sentinels)\n+ subtrees = [s.subtree for s in sentinels]\n+ packed_state, subtree_defs = unzip2(map(tree_flatten, subtrees))\n+ return OptimizerState(packed_state, tree_def, subtree_defs)\n"
}
] | Python | Apache License 2.0 | google/jax | Changes to jax optimizers.py to facilitate serialization of optimizer state.
Co-authored-by: Matthew Johnson <mattjj@google.com> |
260,335 | 06.06.2019 10:12:07 | 25,200 | 121d78129b8705d7b0bdd55d5bff87ab79b06b40 | docstring improvements from comments | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -979,26 +979,10 @@ def custom_transforms(fun):\ntransformations like ``jax.jit`` and ``jax.vmap``. Custom differentiation\nrules can be supplied using the ``jax.defjvp`` and ``jax.defvjp`` functions.\n- JAX transforms Python functions by tracing which primitive operations (like\n- black-box numerical kernels) are applied to the function's input arguments to\n- produce its output, then transforming that recorded composition of primitives\n- using a table of transformation rules for each primitive. That is, for each\n- transformation (e.g. ``jax.jvp`` or ``jax.vmap``) there is a table of rules\n- that specifies how each primitive is transformed. When a new primitive is\n- added to the system, it also needs a rule for each transformation we might\n- want to apply to it.\n-\n- But in some cases instead of introducing a new primitive and specifying every\n- transformation rule, we might start with a traceable/transformable Python\n- function and want to override just its VJP (i.e. give it a custom gradient).\n- More concretely, we might start with a Python function to which we can already\n- apply ``jax.jit``, but we want to change how ``jax.grad`` behaves on it. These\n- are the cases that ``custom_transforms`` handles.\n-\nThe ``custom_transforms`` decorator wraps ``fun`` so that its transformation\nbehavior can be overridden, but not all transformation rules need to be\n- specified manually. For rules that aren't overridden, a default rule is used\n- for each transformation that relies on tracing ``fun``.\n+ specified manually. The default behavior is retained for any non-overridden\n+ rules.\nArgs:\nfun: a Python callable. Must be functionally pure. Its arguments and return\n@@ -1082,8 +1066,8 @@ def defjvp_all(fun, custom_jvp):\n``custom_jvp`` represents a function with signature ``a -> T a -> (b, T b)``,\nwhere we use ``T x`` to represent a tangent type for the type ``x``.\n- In more detail, ``custom_jvp`` must two arguments, both tuples of length equal\n- to the number of positional arguments to ``fun``. The first argument to\n+ In more detail, ``custom_jvp`` must take two arguments, both tuples of length\n+ equal to the number of positional arguments to ``fun``. The first argument to\n``custom_jvp`` represents the input primal values, and the second represents\nthe input tangent values. ``custom_jvp`` must return a pair where the first\nelement represents the output primal value and the second element represents\n@@ -1097,8 +1081,10 @@ def defjvp_all(fun, custom_jvp):\ncustom_jvp: a Python callable specifying the JVP rule, taking two tuples as\narguments specifying the input primal values and tangent values,\nrespectively. The tuple elements can be arrays, scalars, or (nested)\n- standard Python containers (tuple/list/dict) thereof. Must be functionally\n- pure.\n+ standard Python containers (tuple/list/dict) thereof. The output must be a\n+ pair representing the primal output and tangent output, which can be\n+ arrays, scalars, or (nested) standard Python containers. Must be\n+ functionally pure.\nReturns:\nNone. A side-effect is that ``fun`` is associated with the JVP rule\n@@ -1231,6 +1217,9 @@ def defjvp2(fun, *jvprules):\nwrapper does not provide a mechanism for depending on anything other than the\nfunction arguments and its primal output value.\n+ This function is like ``jax.defjvp`` except the component JVP rules also take\n+ the output primal as an argument.\n+\nThe signature of each component JVP rule is ``lambda g, ans, *primals: ...``\nwhere ``g`` represents the tangent of the corresponding positional argument,\n``ans`` represents the output primal, and ``*primals`` represents all the\n"
}
] | Python | Apache License 2.0 | google/jax | docstring improvements from @skye comments |
260,335 | 07.06.2019 16:00:11 | 25,200 | d622e78e82a408a98334ea2548c0bf9b0e4787ff | fix broken travis path from previous commit | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -11,9 +11,9 @@ env:\n- JAX_ENABLE_X64=1 JAX_NUM_GENERATED_CASES=100\nbefore_install:\n- if [[ \"$TRAVIS_PYTHON_VERSION\" == \"2.7\" ]]; then\n- wget https://repo.continuum.io/miniconda/Miniconda2-0.1.18-Linux-x86_64.sh -O miniconda.sh;\n+ wget https://repo.continuum.io/miniconda/Miniconda2-latest-Linux-x86_64.sh -O miniconda.sh;\nelse\n- wget https://repo.continuum.io/miniconda/Miniconda3-0.1.18-Linux-x86_64.sh -O miniconda.sh;\n+ wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh;\nfi\n- bash miniconda.sh -b -p $HOME/miniconda\n- export PATH=\"$HOME/miniconda/bin:$PATH\"\n"
}
] | Python | Apache License 2.0 | google/jax | fix broken travis path from previous commit |
260,335 | 08.06.2019 08:57:34 | 25,200 | 35de70472933a10030111dad75dadff9a63fc4b1 | add pswapaxes lowering (fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -106,6 +106,9 @@ def ppermute(x, axis_name, perm):\ndef pswapaxes(x, axis_name, axis):\n\"\"\"Swap the pmapped axis ``axis_name`` with the unmapped axis ``axis``.\n+ The mapped axis size must be equal to the size of the unmapped axis; that is,\n+ we must have ``lax.psum(1, axis_name) == x.shape[axis]``.\n+\nThis function is similar to ``psplit`` except the pmapped axis of the input is\nplaced at the position ``axis`` in the output.\n@@ -121,6 +124,11 @@ def pswapaxes(x, axis_name, axis):\nwhere ``axis_size`` is the size of the mapped axis named ``axis_name`` in\nthe input ``x``.\n\"\"\"\n+ axis_size = psum(1, axis_name)\n+ if axis_size != x.shape[axis]:\n+ msg = (\"pswapaxes requires the size of the mapped axis ``axis_name`` equal \"\n+ \"``x.shape[axis]``, but they are {} and {} respectively.\")\n+ raise ValueError(msg.format(axis_size(axis_name), x.shape[axis]))\nreturn pswapaxes_p.bind(x, axis_name=axis_name, axis=axis)\ndef psplit(x, axis_name, axis):\n@@ -233,7 +241,11 @@ def _pswapaxes_serial_pmap_rule(vals, axes, axis):\nperm[axis] = axis_in\nreturn lax.transpose(x, perm), axis_in\n+def _pswapaxes_translation_rule(c, xla_x, axis, replica_groups):\n+ return c.AllToAll(xla_x, axis, axis, replica_groups)\n+\npswapaxes_p = standard_pmap_primitive('pswapaxes')\n+pxla.parallel_translation_rules[pswapaxes_p] = _pswapaxes_translation_rule\nparallel.serial_pmap_primitive_rules[pswapaxes_p] = _pswapaxes_serial_pmap_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -519,6 +519,16 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(expected_bz1, bz1, check_dtypes=False)\nself.assertAllClose(bz2, bz2, check_dtypes=False)\n+ @jtu.skip_on_devices(\"cpu\", \"gpu\")\n+ def testPswapaxes(self):\n+ device_count = xla_bridge.device_count()\n+ shape = (device_count, 3, device_count, 5)\n+ x = onp.arange(prod(shape)).reshape(shape)\n+\n+ ans = pmap(lambda x: lax.pswapaxes(x, 'i', 1), axis_name='i')(x)\n+ expected = onp.swapaxes(x, 0, 2)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add pswapaxes lowering (fixes #827) |
260,335 | 08.06.2019 09:03:55 | 25,200 | d7c7df1bfd3f520dd55e18bcc70e905333b289b8 | temporarily disable a check in pswapaxes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -124,11 +124,12 @@ def pswapaxes(x, axis_name, axis):\nwhere ``axis_size`` is the size of the mapped axis named ``axis_name`` in\nthe input ``x``.\n\"\"\"\n- axis_size = psum(1, axis_name)\n- if axis_size != x.shape[axis]:\n- msg = (\"pswapaxes requires the size of the mapped axis ``axis_name`` equal \"\n- \"``x.shape[axis]``, but they are {} and {} respectively.\")\n- raise ValueError(msg.format(axis_size(axis_name), x.shape[axis]))\n+ # TODO(mattjj): enable this check when _serial_pmap works with psum(1, ax)\n+ # axis_size = psum(1, axis_name)\n+ # if axis_size != x.shape[axis]:\n+ # msg = (\"pswapaxes requires the size of the mapped axis ``axis_name`` equal \"\n+ # \"``x.shape[axis]``, but they are {} and {} respectively.\")\n+ # raise ValueError(msg.format(axis_size(axis_name), x.shape[axis]))\nreturn pswapaxes_p.bind(x, axis_name=axis_name, axis=axis)\ndef psplit(x, axis_name, axis):\n"
}
] | Python | Apache License 2.0 | google/jax | temporarily disable a check in pswapaxes |
260,335 | 08.06.2019 09:11:25 | 25,200 | c061fd7b058759133aa56d48130fad1a0a0a311b | improve error for unimplemented parallel primitive | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -229,6 +229,8 @@ def xla_unshard(c, replica_groups, x):\n### the main pmap machinery lowers SPMD jaxprs to multi-replica XLA computations\n+class PmapPrimitive(core.Primitive): pass\n+\nAxisEnv = namedtuple(\"AxisEnv\", [\"nreps\", \"names\", \"sizes\"])\ndef axis_read(axis_env, axis_name):\n@@ -296,10 +298,14 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nelse:\nin_nodes = [xla.xla_pack(c, map(read, invars)) if type(invars) is tuple\nelse read(invars) for invars in eqn.invars]\n- if eqn.primitive in parallel_translation_rules:\n+ if type(eqn.primitive) is PmapPrimitive:\nname = eqn.params['axis_name']\nparams = {k: eqn.params[k] for k in eqn.params if k != 'axis_name'}\n+ try:\nrule = parallel_translation_rules[eqn.primitive]\n+ except KeyError:\n+ msg = 'XLA translation rule for parallel primitive {} not implemented.'\n+ raise NotImplementedError(msg.format(eqn.primitive.name))\nans = rule(c, *in_nodes, replica_groups=axis_groups(ax_env, name), **params)\nelif eqn.bound_subjaxprs:\nif eqn.primitive is xla_pmap_p:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -17,7 +17,6 @@ Parallelization primitives.\nfrom jax.lax import lax\nfrom jax.abstract_arrays import ShapedArray\n-from jax.core import Primitive\nfrom jax.interpreters import ad\nfrom jax.interpreters import parallel\nfrom jax.interpreters import xla\n@@ -163,7 +162,7 @@ def pcollect(x, axis_name):\n### parallel primitives\ndef standard_pmap_primitive(name):\n- prim = Primitive(name)\n+ prim = pxla.PmapPrimitive(name)\nprim.def_impl(partial(pxla.apply_parallel_primitive, prim))\nprim.def_abstract_eval(lambda x, *args, **params: x)\nreturn prim\n"
}
] | Python | Apache License 2.0 | google/jax | improve error for unimplemented parallel primitive |
260,335 | 09.06.2019 09:49:16 | 25,200 | 4ab89084f1e1764e65e60ff2f3dce1f2c8f328f0 | fix DeviceTuple constant handler (fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -470,9 +470,8 @@ pytype_aval_mappings[DeviceTuple] = op.attrgetter('aval')\ncanonicalize_dtype_handlers[DeviceTuple] = identity\ndef _device_tuple_constant_handler(c, val, canonicalize_types=True):\n- py_val = pack(c.Constant(elt, canonicalize_types=canonicalize_types)\n- for elt in val)\n- return c.Constant(py_val)\n+ const = partial(c.Constant, canonicalize_types=canonicalize_types)\n+ return c.Tuple(*map(const, val))\nxb.register_constant_handler(DeviceTuple, _device_tuple_constant_handler)\n# TODO(mattjj): could jit-compile a computation here\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1325,6 +1325,14 @@ class LaxTest(jtu.JaxTestCase):\nself.skipTest(\"Test is Python 2 specific\")\nself.assertTrue(api.jit(lambda x: lax.lt(x, long(10)))(long(3)))\n+ def testIssue831(self):\n+ # Tests the DeviceTuple constant handler\n+ def f(x):\n+ g = lambda *args: args[1]\n+ return api.jit(lax.fori_loop, static_argnums=(2,))( 0, 10, g, x)\n+\n+ api.jit(f)(1.) # doesn't crash\n+\nclass DeviceConstantTest(jtu.JaxTestCase):\ndef _CheckDeviceConstant(self, make_const, expected):\n"
}
] | Python | Apache License 2.0 | google/jax | fix DeviceTuple constant handler (fixes #831) |
260,335 | 09.06.2019 20:18:18 | 25,200 | 1829508b28b4386ac5511f4d668cbbef308b48b0 | np.arange shouldn't pop its kwargs (fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1379,7 +1379,7 @@ def identity(n, dtype=None):\n@_wraps(onp.arange)\ndef arange(*args, **kwargs):\n- dtype = kwargs.pop(\"dtype\", None)\n+ dtype = kwargs.get(\"dtype\", None)\nif not args:\nraise TypeError(\"Required argument 'start' (pos 1) not found\") # same as numpy error\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1493,7 +1493,6 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nexpected = onp.reshape(a, (3, 2), order='F')\nself.assertAllClose(ans, expected, check_dtypes=True)\n-\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_op={}_dtype={}\".format(\nop, {bool: \"bool\", int: \"int\", float: \"float\"}[dtype]),\n@@ -1538,6 +1537,10 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself.assertFalse(type(lnp.arange(77)) == type(onp.arange(77)))\nself.assertTrue(type(lnp.arange(77)) == type(lax.iota(onp.int32, 77)))\n+ def testIssue830(self):\n+ a = lnp.arange(4, dtype=lnp.complex64)\n+ self.assertEqual(a.dtype, lnp.complex64)\n+\ndef testIssue728(self):\nassert lnp.allclose(lnp.eye(5000), onp.eye(5000))\nself.assertEqual(0, onp.sum(lnp.eye(1050) - onp.eye(1050)))\n"
}
] | Python | Apache License 2.0 | google/jax | np.arange shouldn't pop its kwargs (fixes #830) |
260,335 | 10.06.2019 12:17:20 | 25,200 | aebf7eb0884c695b0d4950667c03c1e251d5ab0f | fix jax.numpy.transpose arg name 'axes' | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -512,9 +512,9 @@ def sinc(x):\n@_wraps(onp.transpose)\n-def transpose(x, axis=None):\n- axis = onp.arange(ndim(x))[::-1] if axis is None else axis\n- return lax.transpose(x, axis)\n+def transpose(x, axes=None):\n+ axes = onp.arange(ndim(x))[::-1] if axes is None else axes\n+ return lax.transpose(x, axes)\n@_wraps(onp.rot90)\n"
}
] | Python | Apache License 2.0 | google/jax | fix jax.numpy.transpose arg name 'axes' |
260,335 | 11.06.2019 06:52:55 | 25,200 | bbf625e0df781a8420f35621e1c99a46cf37130a | fix jax.rst docs (remove defvjp2 / defjvp2) | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.rst",
"new_path": "docs/jax.rst",
"diff": "@@ -19,6 +19,6 @@ Module contents\n---------------\n.. automodule:: jax\n- :members: jit, disable_jit, grad, value_and_grad, vmap, pmap, jacfwd, jacrev, hessian, jvp, linearize, vjp, make_jaxpr, eval_shape, custom_transforms, defjvp, defjvp2, defjvp_all, defvjp, defvjp2, defvjp_all, custom_gradient\n+ :members: jit, disable_jit, grad, value_and_grad, vmap, pmap, jacfwd, jacrev, hessian, jvp, linearize, vjp, make_jaxpr, eval_shape, custom_transforms, defjvp, defjvp_all, defvjp, defvjp_all, custom_gradient\n:undoc-members:\n:show-inheritance:\n"
}
] | Python | Apache License 2.0 | google/jax | fix jax.rst docs (remove defvjp2 / defjvp2) |
260,335 | 11.06.2019 14:56:21 | 25,200 | a56a7d02ffba288f1b5f6dbfb54fa89a3bcb9ec2 | make threefry_2x32 not do any op-by-op stuff | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -146,7 +146,7 @@ def _promote_shapes(*args):\nshapes = [shape(arg) for arg in args]\nnd = len(lax.broadcast_shapes(*shapes))\nreturn [lax.reshape(arg, (1,) * (nd - len(shp)) + shp)\n- if len(shp) != nd else arg for arg, shp in zip(args, shapes)]\n+ if shp and len(shp) != nd else arg for arg, shp in zip(args, shapes)]\ndef _promote_dtypes(*args):\n\"\"\"Convenience function to apply Numpy argument dtype promotion.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -78,7 +78,7 @@ def _make_rotate_left(dtype):\ndef _rotate_left(x, d):\nif lax.dtype(d) != lax.dtype(x):\nd = lax.convert_element_type(d, x.dtype)\n- return (x << d) | lax.shift_right_logical(x, nbits - d)\n+ return lax.shift_left(x, d) | lax.shift_right_logical(x, nbits - d)\nreturn _rotate_left\n@@ -122,7 +122,7 @@ def threefry_2x32(keypair, count):\nelse:\nx = list(np.split(count.ravel(), 2))\n- rotations = [13, 15, 26, 6, 17, 29, 16, 24]\n+ rotations = onp.uint32([13, 15, 26, 6, 17, 29, 16, 24])\nks = [key1, key2, key1 ^ key2 ^ onp.uint32(0x1BD11BDA)]\nx[0] = x[0] + ks[0]\n@@ -211,7 +211,7 @@ def _random_bits(key, bit_width, shape):\nbits = threefry_2x32(key, counts)\nif bit_width == 64:\nbits = [lax.convert_element_type(x, onp.uint64) for x in np.split(bits, 2)]\n- bits = (bits[0] << onp.uint64(32)) | bits[1]\n+ bits = lax.shift_left(bits[0], onp.uint64(32)) | bits[1]\nreturn lax.reshape(bits, shape)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -30,6 +30,7 @@ from jax import api\nfrom jax import lax\nfrom jax import random\nfrom jax import test_util as jtu\n+from jax.interpreters import xla\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -366,6 +367,12 @@ class LaxRandomTest(jtu.JaxTestCase):\nelse:\nself.assertEqual(onp.result_type(w), onp.float32)\n+ def testNoOpByOpUnderHash(self):\n+ def fail(): assert False\n+ apply_primitive, xla.apply_primitive = xla.apply_primitive, fail\n+ out = random.threefry_2x32(onp.zeros(2, onp.uint32), onp.arange(10, dtype=onp.uint32))\n+ xla.apply_primitive = apply_primitive\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | make threefry_2x32 not do any op-by-op stuff |
260,335 | 14.06.2019 11:49:07 | 25,200 | 191206db90088a3c4f6628b6ce0a8fa35860886a | fix the david sussillo bug | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -405,9 +405,8 @@ def trace_to_subjaxpr(master, instantiate, pvals):\nin_tracers = map(trace.new_arg, pvals)\nout_tracer = yield in_tracers, {}\nout_tracer = trace.full_raise(out_tracer)\n-\nout_tracer = instantiate_const_at(trace, instantiate, out_tracer)\n-\n+ out_tracer = trace.full_raise(out_tracer) # instantiation (unpack) can lower\njaxpr, consts, env = tracers_to_jaxpr(in_tracers, out_tracer)\nout_pval = out_tracer.pval\ndel trace, in_tracers, out_tracer\n@@ -582,10 +581,10 @@ def partial_eval_jaxpr(jaxpr, second_components, instantiate):\ndef fun(*vals):\npvals = map(as_pval, jaxpr.in_avals, second_components, vals)\njaxpr_2, out_pval, consts_2 = trace_to_jaxpr(f, pvals, instantiate=instantiate)\n- (out_pv_c, out_pv_b), out_const = out_pval\n- if out_const is core.unit:\n- out_const_c, out_const_b = core.unit, core.unit\n- else:\n+ out_pv, out_const = out_pval\n+ out_pv = (None, None) if out_pv is None else out_pv\n+ out_const = (core.unit, core.unit) if out_const is core.unit else out_const\n+ out_pv_c, out_pv_b = out_pv\nout_const_c, out_const_b = out_const\ncell.append((out_pv_c, out_pv_b, jaxpr_2))\nreturn pack((out_const_c, pack((out_const_b, pack(consts_2)))))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -463,7 +463,8 @@ def _update_arrays(i, aval, xs, x):\nif isinstance(aval, core.AbstractTuple):\nreturn core.pack(map(partial(_update_arrays, i), aval, xs, x))\nelse:\n- return lax.dynamic_update_index_in_dim(xs, x[None, ...], i, axis=0)\n+ x = lax.reshape(x, (1,) + onp.shape(x))\n+ return lax.dynamic_update_index_in_dim(xs, x, i, axis=0)\nclass FixedPointError(Exception): pass\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -808,6 +808,8 @@ class LaxControlFlowTest(jtu.JaxTestCase):\narg = 0.5\nprint(api.jit(api.jacfwd(loop, argnums=(0,)))(arg))\n+ # TODO(mattjj): add a test for \"the David Sussillo bug\"\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix the david sussillo bug
Co-authored-by: Dougal Maclaurin <dougalm@google.com> |
260,335 | 15.06.2019 12:01:20 | 25,200 | 1262ca9b309580eed69c8d7179a58db2c76b71a1 | improve conv rhs batching, add systematic test | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1843,15 +1843,13 @@ def _conv_general_dilated_batch_rule(\nreturn outputs, 0\nelif rhs_bdim is not None:\n- #TODO(#212): use a map construct instead of unrolling.\n- rhs = batching.move_dim_to_front(rhs, rhs_bdim)\n- outputs = [\n- conv_general_dilated(lhs, x, window_strides, padding,\n+ # move and reshape the bdim into the rhs output channels dimension\n+ _, rhs_spec, out_spec = dimension_numbers\n+ new_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\n+ out = conv_general_dilated(lhs, new_rhs, window_strides, padding,\nlhs_dilation, rhs_dilation, dimension_numbers)\n- for x in rhs]\n- outputs = [reshape(out, (1,) + out.shape) for out in outputs]\n- outputs = concatenate(outputs, 0)\n- return outputs, 0\n+ out = _reshape_axis_out_of(out_spec[1], rhs.shape[rhs_bdim], out)\n+ return out, out_spec[1]\nconv_general_dilated_p = standard_primitive(\n_conv_general_dilated_shape_rule, _conv_general_dilated_dtype_rule,\n'conv_general_dilated', _conv_general_dilated_translation_rule)\n@@ -1861,6 +1859,21 @@ ad.defbilinear(conv_general_dilated_p,\nbatching.primitive_batchers[\nconv_general_dilated_p] = _conv_general_dilated_batch_rule\n+def _reshape_axis_into(src, dst, x):\n+ perm = [i for i in range(x.ndim) if i != src]\n+ perm.insert(dst, src)\n+ new_shape = list(onp.delete(x.shape, src))\n+ new_shape[dst] *= x.shape[src]\n+ return reshape(transpose(x, perm), new_shape) # TODO(mattjj): manually fuse\n+\n+def _reshape_axis_out_of(src, size1, x):\n+ shape = list(x.shape)\n+ size2, ragged = divmod(shape[src], size1)\n+ assert not ragged\n+ shape[src:src+1] = [size1, size2]\n+ return reshape(x, shape)\n+\n+\ndef _dot_shape_rule(lhs, rhs):\nif lhs.ndim == 0 or rhs.ndim == 0:\nmsg = \"Dot only supports rank 1 or above, got shapes {} and {}.\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -507,6 +507,7 @@ class JaxTestCase(parameterized.TestCase):\nfor k in x.keys():\nself.assertAllClose(x[k], y[k], check_dtypes, atol=atol, rtol=rtol)\nelif is_sequence(x) and not hasattr(x, '__array__'):\n+ import ipdb; ipdb.set_trace()\nself.assertTrue(is_sequence(y) and not hasattr(y, '__array__'))\nself.assertEqual(len(x), len(y))\nfor x_elt, y_elt in zip(x, y):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -485,7 +485,6 @@ class BatchingTest(jtu.JaxTestCase):\n(5, 21, 5, 1)))\nself.assertAllClose(per_example, per_example_direct, check_dtypes=True)\n-\ndef testMaxPool(self):\nW = np.array(onp.random.randn(3, 3, 1, 5), dtype=onp.float32)\nX = np.array(onp.random.randn(10, 5, 5, 1), dtype=onp.float32)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1656,12 +1656,12 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nfor lhs_dil in lhs_dils\nfor dtype in [onp.float32]\nfor padding in all_pads\n- for rng in [jtu.rand_default()]\nfor dim_nums, perms in [\n((\"NCHW\", \"OIHW\", \"NCHW\"), ([0, 1, 2, 3], [0, 1, 2, 3])),\n((\"NHWC\", \"HWIO\", \"NHWC\"), ([0, 2, 3, 1], [2, 3, 1, 0])),\n- ((\"NHWC\", \"OIHW\", \"NCHW\"), ([0, 2, 3, 1], [0, 1, 2, 3]))\n- ]))\n+ ((\"NHWC\", \"OIHW\", \"NCHW\"), ([0, 2, 3, 1], [0, 1, 2, 3]))]\n+ for rng in [jtu.rand_default()]\n+ ))\n@jtu.skip_on_devices(\"tpu\")\ndef testConvGeneralDilatedGrad(self, lhs_shape, rhs_shape, dtype, strides,\npadding, lhs_dil, rhs_dil, dimension_numbers,\n@@ -2153,5 +2153,78 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=True)\n+def slicer(x, bdim):\n+ if bdim is None:\n+ return lambda _: x\n+ else:\n+ return lambda i: lax.index_in_dim(x, i, bdim, keepdims=False)\n+\n+class LaxVmapTest(jtu.JaxTestCase):\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}_lhs_dilation={}_\"\n+ \"rhs_dilation={}_dims={}_lhs_bdim={}_rhs_bdim={}\"\n+ .format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype),\n+ strides, padding, lhs_dil, rhs_dil, \",\".join(dim_nums),\n+ lhs_bdim, rhs_bdim),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"strides\": strides, \"padding\": padding, \"lhs_dil\": lhs_dil,\n+ \"rhs_dil\": rhs_dil, \"rng\": rng, \"dimension_numbers\": dim_nums,\n+ \"perms\": perms, \"lhs_bdim\": lhs_bdim, \"rhs_bdim\": rhs_bdim}\n+ for lhs_shape, rhs_shape, all_strides, all_pads, lhs_dils, rhs_dils in [\n+ ((b, i, 6, 7), # lhs_shape\n+ (j, i, 1, 2), # rhs_shape\n+ [(1, 1), (1, 2), (2, 1)], # strides\n+ [((0, 0), (0, 0)), ((1, 0), (0, 1)), ((0, -1), (0, 0))], # pads\n+ [(1, 1), (2, 1)], # lhs_dils\n+ [(1, 1), (2, 2)]) # rhs_dils\n+ for b, i, j in itertools.product([1, 2], repeat=3)]\n+ for strides in all_strides\n+ for rhs_dil in rhs_dils\n+ for lhs_dil in lhs_dils\n+ for dtype in [onp.float32]\n+ for padding in all_pads\n+ for dim_nums, perms in [\n+ ((\"NCHW\", \"OIHW\", \"NCHW\"), ([0, 1, 2, 3], [0, 1, 2, 3])),\n+ ((\"NHWC\", \"HWIO\", \"NHWC\"), ([0, 2, 3, 1], [2, 3, 1, 0])),\n+ ((\"NHWC\", \"OIHW\", \"NCHW\"), ([0, 2, 3, 1], [0, 1, 2, 3]))]\n+ for lhs_bdim in itertools.chain([None], range(len(lhs_shape) + 1))\n+ for rhs_bdim in itertools.chain([None], range(len(rhs_shape) + 1))\n+ if (lhs_bdim, rhs_bdim) != (None, None)\n+ for rng in [jtu.rand_default()]\n+ ))\n+ def testConvGeneralDilatedBatching(\n+ self, lhs_shape, rhs_shape, dtype, strides, padding, lhs_dil, rhs_dil,\n+ dimension_numbers, perms, lhs_bdim, rhs_bdim, rng):\n+ tol = 1e-1 if onp.finfo(dtype).bits == 32 else 1e-3\n+ bdim_size = 10\n+\n+ # permute shapes to match dimension_numbers\n+ lhs_perm, rhs_perm = perms\n+ lhs_shape = list(onp.take(lhs_shape, lhs_perm))\n+ rhs_shape = list(onp.take(rhs_shape, rhs_perm))\n+\n+ # add batch dimension\n+ if lhs_bdim is not None:\n+ lhs_shape.insert(lhs_bdim, bdim_size)\n+ if rhs_bdim is not None:\n+ rhs_shape.insert(rhs_bdim, bdim_size)\n+\n+ # create arg values and sliced versions\n+ lhs = rng(lhs_shape, dtype)\n+ rhs = rng(rhs_shape, dtype)\n+ lhs_slice = slicer(lhs, lhs_bdim)\n+ rhs_slice = slicer(rhs, rhs_bdim)\n+\n+ conv = partial(lax.conv_general_dilated, window_strides=strides,\n+ padding=padding, lhs_dilation=lhs_dil, rhs_dilation=rhs_dil,\n+ dimension_numbers=dimension_numbers)\n+ ans = api.vmap(conv, (lhs_bdim, rhs_bdim))(lhs, rhs)\n+ expected = onp.stack([conv(lhs_slice(i), rhs_slice(i)) for i in range(bdim_size)])\n+ self.assertAllClose(ans, expected, check_dtypes=True)\n+\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | improve conv rhs batching, add systematic test |
260,335 | 15.06.2019 13:38:55 | 25,200 | ff29d582e8f287954ba446fb08924bae5eba2857 | t # This is a combination of 2 commits.
make all conv vmap rules generate a single call
also plumb feature_group_count and batch_group_count everywhere | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -371,7 +371,8 @@ def concatenate(operands, dimension):\noperand_shapes=tuple(o.shape for o in operands))\ndef conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation=None,\n- rhs_dilation=None, dimension_numbers=None):\n+ rhs_dilation=None, dimension_numbers=None,\n+ feature_group_count=1, batch_group_count=1):\n\"\"\"General n-dimensional convolution operator, with optional dilation.\nWraps XLA's `Conv\n@@ -395,6 +396,8 @@ def conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation=None,\ndimension_numbers: either `None`, a `ConvDimensionNumbers` object, or\na 3-tuple `(lhs_spec, rhs_spec, out_spec)`, where each element is a string\nof length `n+2`.\n+ feature_group_count: integer, default 1. See XLA HLO docs.\n+ batch_group_count: integer, default 1. See XLA HLO docs.\nReturns:\nAn array containing the convolution result.\n@@ -438,8 +441,10 @@ def conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation=None,\nreturn conv_general_dilated_p.bind(\nlhs, rhs, window_strides=tuple(window_strides), padding=tuple(padding),\nlhs_dilation=tuple(lhs_dilation), rhs_dilation=tuple(rhs_dilation),\n- dimension_numbers=dimension_numbers, lhs_shape=lhs.shape,\n- rhs_shape=rhs.shape)\n+ dimension_numbers=dimension_numbers,\n+ feature_group_count=feature_group_count,\n+ batch_group_count=batch_group_count,\n+ lhs_shape=lhs.shape, rhs_shape=rhs.shape)\ndef dot(lhs, rhs):\n\"\"\"Vector/vector, matrix/vector, and matrix/matrix multiplication.\n@@ -1737,8 +1742,33 @@ batching.defvectorized(bitcast_convert_type_p)\ndef _conv_general_dilated_shape_rule(\nlhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers, **unused_kwargs):\n+ dimension_numbers, feature_group_count, batch_group_count, **unused_kwargs):\nassert type(dimension_numbers) is ConvDimensionNumbers\n+ if not feature_group_count > 0 or not batch_group_count > 0:\n+ msg = (\"conv_general_dilated feature_group_count and batch_group_count \"\n+ \"must be positive integers, got {} and {}.\")\n+ raise ValueError(msg.format(feature_group_count, batch_group_count))\n+ if feature_group_count > 1 and batch_group_count > 1:\n+ msg = (\"conv_general_dilated feature_group_count and batch_group_count \"\n+ \"cannot both be greater than 1, got {} and {}.\")\n+ raise ValueError(msg.format(feature_group_count, batch_group_count))\n+ lhs_feature_count = lhs.shape[dimension_numbers.lhs_spec[1]]\n+ quot, rem = divmod(lhs_feature_count, feature_group_count)\n+ if rem:\n+ msg = (\"conv_general_dilated feature_group_count must divide lhs feature \"\n+ \"dimension size, but {} does not divide {}.\")\n+ raise ValueError(msg.format(feature_group_count, lhs_feature_count))\n+ if quot != rhs.shape[dimension_numbers.rhs_spec[1]]:\n+ msg = (\"conv_general_dilated lhs feature dimension size divided by \"\n+ \"feature_group_count must equal the rhs input feature dimension \"\n+ \"size, but {} // {} != {}.\")\n+ raise ValueError(msg.format(lhs_feature_count, feature_group_count,\n+ rhs.shape[dimension_numbers.rhs_spec[1]]))\n+ if rhs.shape[dimension_numbers.rhs_spec[0]] % feature_group_count:\n+ msg = (\"conv_general_dilated rhs output feature dimension size must be a \"\n+ \"multiple of feature_group_count, but {} is not a multiple of {}.\")\n+ raise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],\n+ feature_group_count))\nlhs_perm, rhs_perm, out_perm = dimension_numbers\nlhs_trans = _dilate_shape(onp.take(lhs.shape, lhs_perm), lhs_dilation)\nrhs_trans = _dilate_shape(onp.take(rhs.shape, rhs_perm), rhs_dilation)\n@@ -1751,16 +1781,27 @@ def _conv_general_dilated_dtype_rule(\nreturn binop_dtype_rule(_input_dtype, [_f32, _f32], 'conv_general_dilated',\nlhs, rhs)\n-_conv_transpose = lambda spec: (spec[1], spec[0]) + spec[2:]\n+_conv_spec_transpose = lambda spec: (spec[1], spec[0]) + spec[2:]\n_conv_sdims = lambda spec: spec[2:]\ndef _conv_general_dilated_transpose_lhs(\ng, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers, lhs_shape, rhs_shape):\n+ dimension_numbers, feature_group_count, batch_group_count,\n+ lhs_shape, rhs_shape):\nassert type(dimension_numbers) is ConvDimensionNumbers\n+ if batch_group_count != 1:\n+ msg = (\"conv_general_dilated transpose rule is only implemented for \"\n+ \"batch_group_count = 1, but got {}. Open a feature request!\")\n+ raise NotImplementedError(msg.format(batch_group_count)) # TODO(mattjj)\nlhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\nlhs_spec, rhs_spec, out_spec = dimension_numbers\n- t_rhs_spec = _conv_transpose(rhs_spec)\n+ t_rhs_spec = _conv_spec_transpose(rhs_spec)\n+ if feature_group_count > 1:\n+ # in addition to switching the dims in the spec, need to move the feature\n+ # group axis into the transposed rhs's output feature dim\n+ rhs = _reshape_axis_out_of(rhs_spec[0], feature_group_count, rhs)\n+ rhs = _reshape_axis_into(rhs_spec[0],\n+ rhs_spec[1] + int(rhs_spec[0] < rhs_spec[1]), rhs)\ntrans_dimension_numbers = ConvDimensionNumbers(out_spec, t_rhs_spec, lhs_spec)\npadding = _conv_general_vjp_lhs_padding(\nonp.take(lhs_shape, lhs_sdims), onp.take(rhs_shape, rhs_sdims),\n@@ -1770,14 +1811,22 @@ def _conv_general_dilated_transpose_lhs(\nreturn conv_general_dilated(\ng, revd_weights, window_strides=lhs_dilation, padding=padding,\nlhs_dilation=window_strides, rhs_dilation=rhs_dilation,\n- dimension_numbers=trans_dimension_numbers)\n+ dimension_numbers=trans_dimension_numbers,\n+ feature_group_count=feature_group_count,\n+ batch_group_count=batch_group_count)\ndef _conv_general_dilated_transpose_rhs(\ng, lhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers, lhs_shape, rhs_shape):\n+ dimension_numbers, feature_group_count, batch_group_count,\n+ lhs_shape, rhs_shape):\nassert type(dimension_numbers) is ConvDimensionNumbers\n+ if not feature_group_count == batch_group_count == 1:\n+ msg = (\"conv_general_dilated transpose rule is only implemented for \"\n+ \"feature_group_count == batch_group_count == 1, but got {} and {}. \"\n+ \"Open a feature request!\")\n+ raise NotImplementedError(msg.format(feature_group_count, batch_group_count))\nlhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\n- lhs_trans, rhs_trans, out_trans = map(_conv_transpose, dimension_numbers)\n+ lhs_trans, rhs_trans, out_trans = map(_conv_spec_transpose, dimension_numbers)\ntrans_dimension_numbers = ConvDimensionNumbers(lhs_trans, out_trans, rhs_trans)\npadding = _conv_general_vjp_rhs_padding(\nonp.take(lhs_shape, lhs_sdims), onp.take(rhs_shape, rhs_sdims),\n@@ -1786,70 +1835,75 @@ def _conv_general_dilated_transpose_rhs(\nreturn conv_general_dilated(\nlhs, g, window_strides=rhs_dilation, padding=padding,\nlhs_dilation=lhs_dilation, rhs_dilation=window_strides,\n- dimension_numbers=trans_dimension_numbers)\n+ dimension_numbers=trans_dimension_numbers,\n+ feature_group_count=feature_group_count,\n+ batch_group_count=batch_group_count)\ndef _conv_general_dilated_translation_rule(\nc, lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers, **unused_kwargs):\n+ dimension_numbers, feature_group_count, batch_group_count, **unused_kwargs):\nassert type(dimension_numbers) is ConvDimensionNumbers\ndimension_numbers = _conv_general_proto(dimension_numbers)\nreturn c.ConvGeneralDilated(lhs, rhs, window_strides, padding, lhs_dilation,\n- rhs_dilation, dimension_numbers)\n+ rhs_dilation, dimension_numbers,\n+ feature_group_count, batch_group_count)\ndef _conv_general_dilated_batch_rule(\nbatched_args, batch_dims, window_strides, padding,\n- lhs_dilation, rhs_dilation, dimension_numbers, **unused_kwargs):\n+ lhs_dilation, rhs_dilation, dimension_numbers,\n+ feature_group_count, batch_group_count, **unused_kwargs):\nlhs, rhs = batched_args\nlhs_bdim, rhs_bdim = batch_dims\n- lhs_dim, rhs_dim, out_dim = dimension_numbers\n+ lhs_spec, rhs_spec, out_spec = dimension_numbers\nif lhs_bdim is not None and rhs_bdim is not None:\n- #TODO(#212): use a map construct instead of unrolling.\n- lhs = batching.move_dim_to_front(lhs, lhs_bdim)\n- rhs = batching.move_dim_to_front(rhs, rhs_bdim)\n- outputs = [\n- conv_general_dilated(l, r, window_strides, padding,\n- lhs_dilation, rhs_dilation, dimension_numbers)\n- for l, r in zip(lhs, rhs)]\n- outputs = [reshape(out, (1,) + out.shape) for out in outputs]\n- outputs = concatenate(outputs, 0)\n- return outputs, 0\n+ assert lhs.shape[lhs_bdim] == rhs.shape[rhs_bdim]\n+ new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[1], lhs)\n+ new_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\n+ out = conv_general_dilated(new_lhs, new_rhs, window_strides, padding,\n+ lhs_dilation, rhs_dilation, dimension_numbers,\n+ feature_group_count=lhs.shape[lhs_bdim] * feature_group_count,\n+ batch_group_count=batch_group_count)\n+ out = _reshape_axis_out_of(out_spec[1], lhs.shape[lhs_bdim], out)\n+ return out, out_spec[1]\nelif lhs_bdim is not None:\n- lhs = batching.move_dim_to_front(lhs, lhs_bdim)\n- lhs_perm = ((0, lhs_dim[0] + 1) + tuple(range(1, lhs_dim[0] + 1)) +\n- tuple(range(lhs_dim[0] + 2, len(lhs_dim) + 1)))\n- new_lhs_dim = (0,) + tuple(x + 1 if x < lhs_dim[0] else x\n- for x in lhs_dim[1:])\n- new_out_dim = (0,) + tuple(x + 1 if x < out_dim[0] else x\n- for x in out_dim[1:])\n-\n- batched_size = lhs.shape[0]\n- n_size = lhs.shape[lhs_dim[0] + 1]\n- if lhs_dim[0] != 0:\n- lhs = transpose(lhs, lhs_perm)\n- lhs = reshape(lhs, (batched_size * n_size,) + lhs.shape[2:])\n- outputs = conv_general_dilated(\n- lhs, rhs, window_strides, padding,\n- lhs_dilation, rhs_dilation,\n- ConvDimensionNumbers(new_lhs_dim, dimension_numbers.rhs_spec,\n- new_out_dim))\n- outputs = reshape(outputs, (batched_size, n_size,) + outputs.shape[1:])\n-\n- if out_dim[0] != 0:\n- out_perm = ((0,) + tuple(range(2, out_dim[0] + 2)) + (1,) +\n- tuple(range(out_dim[0] + 2, len(out_dim) + 1)))\n- outputs = transpose(outputs, out_perm)\n+ new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[0], lhs)\n+ out = conv_general_dilated(new_lhs, rhs, window_strides, padding,\n+ lhs_dilation, rhs_dilation, dimension_numbers,\n+ feature_group_count, batch_group_count)\n+ out = _reshape_axis_out_of(out_spec[0], lhs.shape[lhs_bdim], out)\n+ return out, out_spec[0]\n- return outputs, 0\nelif rhs_bdim is not None:\n- # move and reshape the bdim into the rhs output channels dimension\n- _, rhs_spec, out_spec = dimension_numbers\n+ num_output_features = feature_group_count\n+ if feature_group_count == 1:\nnew_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\nout = conv_general_dilated(lhs, new_rhs, window_strides, padding,\n- lhs_dilation, rhs_dilation, dimension_numbers)\n+ lhs_dilation, rhs_dilation, dimension_numbers,\n+ feature_group_count, batch_group_count)\nout = _reshape_axis_out_of(out_spec[1], rhs.shape[rhs_bdim], out)\nreturn out, out_spec[1]\n+ else:\n+ # feature_group needs to be outermost, so we need to factor it out of the\n+ # rhs output feature dim, then factor the batch dim into the remaining rhs\n+ # output feature dim, then put feature_group back in. we do something\n+ # similar on the output. an alternative which would require more FLOPs but\n+ # fewer reshapes would be to broadcast lhs.\n+ new_rhs = _reshape_axis_out_of(rhs_spec[0] + int(rhs_bdim <= rhs_spec[0]),\n+ feature_group_count, rhs)\n+ new_rhs = _reshape_axis_into(rhs_bdim + int(rhs_spec[0] < rhs_bdim),\n+ rhs_spec[0] + 1,\n+ new_rhs)\n+ new_rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[0], new_rhs)\n+ out = conv_general_dilated(lhs, new_rhs, window_strides, padding,\n+ lhs_dilation, rhs_dilation, dimension_numbers,\n+ feature_group_count, batch_group_count)\n+ out = _reshape_axis_out_of(out_spec[1], feature_group_count, out)\n+ out = _reshape_axis_out_of(out_spec[1] + 1, rhs.shape[rhs_bdim], out)\n+ out = _reshape_axis_into(out_spec[1], out_spec[1] + 1, out)\n+ return out, out_spec[1]\n+\nconv_general_dilated_p = standard_primitive(\n_conv_general_dilated_shape_rule, _conv_general_dilated_dtype_rule,\n'conv_general_dilated', _conv_general_dilated_translation_rule)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -507,7 +507,6 @@ class JaxTestCase(parameterized.TestCase):\nfor k in x.keys():\nself.assertAllClose(x[k], y[k], check_dtypes, atol=atol, rtol=rtol)\nelif is_sequence(x) and not hasattr(x, '__array__'):\n- import ipdb; ipdb.set_trace()\nself.assertTrue(is_sequence(y) and not hasattr(y, '__array__'))\nself.assertEqual(len(x), len(y))\nfor x_elt, y_elt in zip(x, y):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1635,14 +1635,15 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n\"_lhs_shape={}_rhs_shape={}_strides={}_padding={}_lhs_dilation={}_\"\n- \"rhs_dilation={}_dims={}\"\n+ \"rhs_dilation={}_dims={}_feature_group_count={}\"\n.format(jtu.format_shape_dtype_string(lhs_shape, dtype),\njtu.format_shape_dtype_string(rhs_shape, dtype),\n- strides, padding, lhs_dil, rhs_dil, \",\".join(dim_nums)),\n+ strides, padding, lhs_dil, rhs_dil, \",\".join(dim_nums),\n+ feature_group_count),\n\"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n\"strides\": strides, \"padding\": padding, \"lhs_dil\": lhs_dil,\n\"rhs_dil\": rhs_dil, \"rng\": rng, \"dimension_numbers\": dim_nums,\n- \"perms\": perms}\n+ \"perms\": perms, \"feature_group_count\": feature_group_count}\nfor lhs_shape, rhs_shape, all_strides, all_pads, lhs_dils, rhs_dils in [\n((b, i, 6, 7), # lhs_shape\n(j, i, 1, 2), # rhs_shape\n@@ -1651,6 +1652,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n[(1, 1), (2, 1)], # lhs_dils\n[(1, 1), (2, 2)]) # rhs_dils\nfor b, i, j in itertools.product([1, 2], repeat=3)]\n+ for feature_group_count in [1] # TODO(mattjj): feature_group_count=2\nfor strides in all_strides\nfor rhs_dil in rhs_dils\nfor lhs_dil in lhs_dils\n@@ -1665,14 +1667,23 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef testConvGeneralDilatedGrad(self, lhs_shape, rhs_shape, dtype, strides,\npadding, lhs_dil, rhs_dil, dimension_numbers,\n- perms, rng):\n+ perms, feature_group_count, rng):\ntol = 1e-1 if onp.finfo(dtype).bits == 32 else 1e-3\n- lhs_perm, rhs_perm = perms # permute to compatible shapes\n- lhs = onp.transpose(rng(lhs_shape, dtype), lhs_perm)\n- rhs = onp.transpose(rng(rhs_shape, dtype), rhs_perm)\n+\n+ # permute shapes to match dim_spec, scale by feature_group_count\n+ lhs_perm, rhs_perm = perms\n+ lhs_shape = list(onp.take(lhs_shape, lhs_perm))\n+ rhs_shape = list(onp.take(rhs_shape, rhs_perm))\n+ dim_spec = lax.conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers)\n+ lhs_shape[dim_spec.lhs_spec[1]] *= feature_group_count\n+ rhs_shape[dim_spec.rhs_spec[0]] *= feature_group_count\n+\n+ lhs = rng(lhs_shape, dtype)\n+ rhs = rng(rhs_shape, dtype)\nconv = partial(lax.conv_general_dilated, window_strides=strides,\npadding=padding, lhs_dilation=lhs_dil, rhs_dilation=rhs_dil,\n- dimension_numbers=dimension_numbers)\n+ dimension_numbers=dimension_numbers,\n+ feature_group_count=feature_group_count)\ncheck_grads_bilinear(conv, (lhs, rhs), order=2, modes=[\"fwd\", \"rev\"],\natol=tol, rtol=tol)\n@@ -2164,15 +2175,16 @@ class LaxVmapTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n\"_lhs_shape={}_rhs_shape={}_strides={}_padding={}_lhs_dilation={}_\"\n- \"rhs_dilation={}_dims={}_lhs_bdim={}_rhs_bdim={}\"\n+ \"rhs_dilation={}_dims={}_feature_group_count={}_lhs_bdim={}_rhs_bdim={}\"\n.format(jtu.format_shape_dtype_string(lhs_shape, dtype),\njtu.format_shape_dtype_string(rhs_shape, dtype),\nstrides, padding, lhs_dil, rhs_dil, \",\".join(dim_nums),\n- lhs_bdim, rhs_bdim),\n+ feature_group_count, lhs_bdim, rhs_bdim),\n\"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n\"strides\": strides, \"padding\": padding, \"lhs_dil\": lhs_dil,\n\"rhs_dil\": rhs_dil, \"rng\": rng, \"dimension_numbers\": dim_nums,\n- \"perms\": perms, \"lhs_bdim\": lhs_bdim, \"rhs_bdim\": rhs_bdim}\n+ \"perms\": perms, \"lhs_bdim\": lhs_bdim, \"rhs_bdim\": rhs_bdim,\n+ \"feature_group_count\": feature_group_count}\nfor lhs_shape, rhs_shape, all_strides, all_pads, lhs_dils, rhs_dils in [\n((b, i, 6, 7), # lhs_shape\n(j, i, 1, 2), # rhs_shape\n@@ -2181,6 +2193,7 @@ class LaxVmapTest(jtu.JaxTestCase):\n[(1, 1), (2, 1)], # lhs_dils\n[(1, 1), (2, 2)]) # rhs_dils\nfor b, i, j in itertools.product([1, 2], repeat=3)]\n+ for feature_group_count in [1, 2]\nfor strides in all_strides\nfor rhs_dil in rhs_dils\nfor lhs_dil in lhs_dils\n@@ -2197,14 +2210,17 @@ class LaxVmapTest(jtu.JaxTestCase):\n))\ndef testConvGeneralDilatedBatching(\nself, lhs_shape, rhs_shape, dtype, strides, padding, lhs_dil, rhs_dil,\n- dimension_numbers, perms, lhs_bdim, rhs_bdim, rng):\n+ dimension_numbers, perms, feature_group_count, lhs_bdim, rhs_bdim, rng):\ntol = 1e-1 if onp.finfo(dtype).bits == 32 else 1e-3\nbdim_size = 10\n- # permute shapes to match dimension_numbers\n+ # permute shapes to match dim_spec, scale by feature_group_count\nlhs_perm, rhs_perm = perms\nlhs_shape = list(onp.take(lhs_shape, lhs_perm))\nrhs_shape = list(onp.take(rhs_shape, rhs_perm))\n+ dim_spec = lax.conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers)\n+ lhs_shape[dim_spec.lhs_spec[1]] *= feature_group_count\n+ rhs_shape[dim_spec.rhs_spec[0]] *= feature_group_count\n# add batch dimension\nif lhs_bdim is not None:\n@@ -2220,10 +2236,11 @@ class LaxVmapTest(jtu.JaxTestCase):\nconv = partial(lax.conv_general_dilated, window_strides=strides,\npadding=padding, lhs_dilation=lhs_dil, rhs_dilation=rhs_dil,\n- dimension_numbers=dimension_numbers)\n+ dimension_numbers=dimension_numbers,\n+ feature_group_count=feature_group_count)\nans = api.vmap(conv, (lhs_bdim, rhs_bdim))(lhs, rhs)\nexpected = onp.stack([conv(lhs_slice(i), rhs_slice(i)) for i in range(bdim_size)])\n- self.assertAllClose(ans, expected, check_dtypes=True)\n+ self.assertAllClose(ans, expected, True, tol, tol)\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | t # This is a combination of 2 commits.
make all conv vmap rules generate a single call
also plumb feature_group_count and batch_group_count everywhere |
260,273 | 17.06.2019 12:18:58 | -7,200 | 077d56529fcfd98f773a0cfeb6315e22273427ed | grouped convolution support | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -438,6 +438,18 @@ def conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation=None,\nlhs_dilation = (1,) * (lhs.ndim - 2)\nif rhs_dilation is None:\nrhs_dilation = (1,) * (rhs.ndim - 2)\n+ if batch_group_count != 1 and batch_group_count != lhs.shape[dimension_numbers[0][0]]:\n+ # XLA currently doesn't support 1 < batch_group_count < batch_size\n+ # so we use the batch rule to rewrite into a convolution using feature_group_count\n+ lhs = _reshape_axis_out_of(dimension_numbers[0][0], batch_group_count, lhs)\n+ rhs = _reshape_axis_out_of(dimension_numbers[1][0], batch_group_count, rhs)\n+ out, out_batch_dim = _conv_general_dilated_batch_rule((lhs, rhs),\n+ (dimension_numbers[0][0], dimension_numbers[1][0]),\n+ window_strides, padding,\n+ lhs_dilation, rhs_dilation, dimension_numbers,\n+ feature_group_count, batch_group_count=1)\n+ out = _reshape_axis_into(out_batch_dim, dimension_numbers[2][1], out)\n+ return out\nreturn conv_general_dilated_p.bind(\nlhs, rhs, window_strides=tuple(window_strides), padding=tuple(padding),\nlhs_dilation=tuple(lhs_dilation), rhs_dilation=tuple(rhs_dilation),\n@@ -1769,10 +1781,21 @@ def _conv_general_dilated_shape_rule(\n\"multiple of feature_group_count, but {} is not a multiple of {}.\")\nraise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],\nfeature_group_count))\n+ if lhs.shape[dimension_numbers.lhs_spec[0]] % batch_group_count:\n+ msg = (\"conv_general_dilated lhs input batch dimension size must be a \"\n+ \"multiple of batch_group_count, but {} is not a multiple of {}.\")\n+ raise ValueError(msg.format(lhs.shape[dimension_numbers.lhs_spec[0]],\n+ batch_group_count))\n+ if rhs.shape[dimension_numbers.rhs_spec[0]] % batch_group_count:\n+ msg = (\"conv_general_dilated rhs output feature dimension size must be a \"\n+ \"multiple of batch_group_count, but {} is not a multiple of {}.\")\n+ raise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],\n+ batch_group_count))\nlhs_perm, rhs_perm, out_perm = dimension_numbers\nlhs_trans = _dilate_shape(onp.take(lhs.shape, lhs_perm), lhs_dilation)\nrhs_trans = _dilate_shape(onp.take(rhs.shape, rhs_perm), rhs_dilation)\n- out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding)\n+ out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding,\n+ batch_group_count)\nreturn tuple(onp.take(out_trans, onp.argsort(out_perm)))\ndef _conv_general_dilated_dtype_rule(\n@@ -1820,11 +1843,7 @@ def _conv_general_dilated_transpose_rhs(\ndimension_numbers, feature_group_count, batch_group_count,\nlhs_shape, rhs_shape):\nassert type(dimension_numbers) is ConvDimensionNumbers\n- if not feature_group_count == batch_group_count == 1:\n- msg = (\"conv_general_dilated transpose rule is only implemented for \"\n- \"feature_group_count == batch_group_count == 1, but got {} and {}. \"\n- \"Open a feature request!\")\n- raise NotImplementedError(msg.format(feature_group_count, batch_group_count))\n+\nlhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\nlhs_trans, rhs_trans, out_trans = map(_conv_spec_transpose, dimension_numbers)\ntrans_dimension_numbers = ConvDimensionNumbers(lhs_trans, out_trans, rhs_trans)\n@@ -1836,8 +1855,8 @@ def _conv_general_dilated_transpose_rhs(\nlhs, g, window_strides=rhs_dilation, padding=padding,\nlhs_dilation=lhs_dilation, rhs_dilation=window_strides,\ndimension_numbers=trans_dimension_numbers,\n- feature_group_count=feature_group_count,\n- batch_group_count=batch_group_count)\n+ feature_group_count=batch_group_count,\n+ batch_group_count=feature_group_count)\ndef _conv_general_dilated_translation_rule(\nc, lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n@@ -1876,7 +1895,6 @@ def _conv_general_dilated_batch_rule(\nreturn out, out_spec[0]\nelif rhs_bdim is not None:\n- num_output_features = feature_group_count\nif feature_group_count == 1:\nnew_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\nout = conv_general_dilated(lhs, new_rhs, window_strides, padding,\n@@ -3934,7 +3952,7 @@ def _check_conv_shapes(name, lhs_shape, rhs_shape, window_strides):\nraise TypeError(msg.format(name, expected_length, len(window_strides)))\n-def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads):\n+def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1):\n\"\"\"Compute the shape tuple of a conv given input shapes in canonical order.\"\"\"\nif isinstance(pads, str):\npads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)\n@@ -3946,16 +3964,17 @@ def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads):\nout_space = onp.floor_divide(\nonp.subtract(lhs_padded, rhs_shape[2:]), strides) + 1\nout_space = onp.maximum(0, out_space)\n- out_shape = (lhs_shape[0], rhs_shape[0]) + tuple(out_space)\n+ out_shape = (lhs_shape[0] // batch_group_count, rhs_shape[0]) + tuple(out_space)\nreturn tuple(out_shape)\ndef conv_general_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\n- dimension_numbers):\n+ dimension_numbers, batch_group_count=1):\nlhs_perm, rhs_perm, out_perm = conv_general_permutations(dimension_numbers)\nlhs_trans = onp.take(lhs_shape, lhs_perm)\nrhs_trans = onp.take(rhs_shape, rhs_perm)\n- out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding)\n+ out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding,\n+ batch_group_count)\nreturn tuple(onp.take(out_trans, onp.argsort(out_perm)))\n"
}
] | Python | Apache License 2.0 | google/jax | grouped convolution support |
260,335 | 17.06.2019 11:49:54 | 25,200 | fef68deef62157baaed3d5e4672dfca4ae593611 | fix reshape transpose bug (and add tests)
This version of reshape (taking a `dimensions` argument, which
effectively fuses in a transpose) seems only to be used in the JVP rule
for lax._reduce_prod (basically np.product), but its transpose rule was
totally busted and untested. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1600,7 +1600,7 @@ ad.defjvp(sub_p,\nad.primitive_transposes[sub_p] = _sub_transpose\nmul_p = standard_binop([_num, _num], 'mul')\n-ad.defbilinear_broadcasting(_brcast, mul_p, mul, mul) # TODO\n+ad.defbilinear_broadcasting(_brcast, mul_p, mul, mul)\ndef _safe_mul_translation_rule(c, x, y):\n@@ -2272,11 +2272,11 @@ def _reshape_translation_rule(c, operand, new_sizes, dimensions, old_sizes):\nreturn c.Reshape(operand, new_sizes=new_sizes, dimensions=dimensions)\ndef _reshape_transpose_rule(t, new_sizes, dimensions, old_sizes):\n- out = reshape(t, old_sizes)\nif dimensions is None:\n- return [out]\n+ return [reshape(t, old_sizes)]\nelse:\n- return [transpose(out, onp.argsort(dimensions))]\n+ return [transpose(reshape(t, onp.take(old_sizes, dimensions)),\n+ onp.argsort(dimensions))]\ndef _reshape_batch_rule(batched_args, batch_dims, new_sizes, dimensions, **unused):\noperand, = batched_args\n@@ -3084,8 +3084,6 @@ ad.deflinear(reduce_sum_p, _reduce_sum_transpose_rule)\nbatching.defreducer(reduce_sum_p)\n-\n-\ndef _reduce_prod_shape_rule(operand, axes):\nreturn tuple(onp.delete(operand.shape, axes))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1035,6 +1035,7 @@ class LaxTest(jtu.JaxTestCase):\n\"dims\": dims, \"rng\": rng}\nfor init_val, op, dtypes in [\n(0, lax.add, default_dtypes),\n+ (1, lax.mul, default_dtypes),\n(-onp.inf, lax.max, float_dtypes),\n(onp.iinfo(onp.int32).min, lax.max, [onp.int32]),\n(onp.iinfo(onp.int64).min, lax.max, [onp.int64]),\n@@ -1754,20 +1755,29 @@ class LaxAutodiffTest(jtu.JaxTestCase):\ncheck_grads(broadcast_in_dim, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_inshape={}_outshape={}\".format(\n+ {\"testcase_name\": \"_inshape={}_outshape={}_perm={}\".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+ permutation),\n\"arg_shape\": arg_shape, \"out_shape\": out_shape, \"dtype\": dtype,\n- \"rng\": rng}\n+ \"rng\": rng, \"permutation\": permutation}\nfor dtype in float_dtypes\n- for arg_shape, out_shape in [\n- [(3, 4), (12,)], [(2, 1, 4), (8,)], [(2, 2, 4), (2, 8)]\n+ for arg_shape, out_shape, permutation in [\n+ [(3, 4), (12,), None],\n+ [(2, 1, 4), (8,), None],\n+ [(2, 2, 4), (2, 8), None],\n+ [(3, 4), (12,), (0, 1)],\n+ [(3, 4), (12,), (1, 0)],\n+ [(2, 1, 4), (8,), (0, 2, 1)],\n+ [(2, 1, 4), (8,), (2, 0, 1)],\n+ [(2, 2, 4), (2, 8), (0, 2, 1)],\n+ [(2, 2, 4), (2, 8), (2, 0, 1)],\n]\nfor rng in [jtu.rand_default()]))\n- def testReshapeGrad(self, arg_shape, out_shape, dtype, rng):\n+ def testReshapeGrad(self, arg_shape, out_shape, permutation, dtype, rng):\ntol = 1e-2 if onp.finfo(dtype).bits == 32 else None\noperand = rng(arg_shape, dtype)\n- reshape = lambda x: lax.reshape(x, out_shape)\n+ reshape = lambda x: lax.reshape(x, out_shape, permutation)\ncheck_grads(reshape, (operand,), 2, [\"fwd\", \"rev\"], tol, tol, tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -1916,9 +1926,9 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n\"dims\": dims, \"rng\": rng}\nfor init_val, op, dtypes in [\n(0, lax.add, inexact_dtypes),\n- (1, lax.mul, inexact_dtypes),\n(-onp.inf, lax.max, inexact_dtypes),\n(onp.inf, lax.min, inexact_dtypes),\n+ (1, lax.mul, inexact_dtypes),\n]\nfor dtype in dtypes\nfor shape, dims in [\n@@ -1926,7 +1936,8 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n[(3, 4, 5), (0,)],\n[(3, 4, 5), (1, 2)],\n[(3, 4, 5), (0, 2)],\n- [(3, 4, 5), (0, 1, 2)]\n+ [(3, 4, 5), (0, 1, 2)],\n+ [(3, 1), (1,)],\n]\nfor rng in [jtu.rand_small()]))\ndef testReduceGrad(self, op, init_val, shape, dtype, dims, rng):\n"
}
] | Python | Apache License 2.0 | google/jax | fix reshape transpose bug (and add tests)
This version of reshape (taking a `dimensions` argument, which
effectively fuses in a transpose) seems only to be used in the JVP rule
for lax._reduce_prod (basically np.product), but its transpose rule was
totally busted and untested. |
260,273 | 17.06.2019 20:40:31 | -7,200 | e3462fd8b177bca761aface385e76867830e0a41 | write out batch_feature_groups to simplify and correct implementation | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -372,7 +372,7 @@ def concatenate(operands, dimension):\ndef conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation=None,\nrhs_dilation=None, dimension_numbers=None,\n- feature_group_count=1, batch_group_count=1):\n+ feature_group_count=1):\n\"\"\"General n-dimensional convolution operator, with optional dilation.\nWraps XLA's `Conv\n@@ -397,7 +397,6 @@ def conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation=None,\na 3-tuple `(lhs_spec, rhs_spec, out_spec)`, where each element is a string\nof length `n+2`.\nfeature_group_count: integer, default 1. See XLA HLO docs.\n- batch_group_count: integer, default 1. See XLA HLO docs.\nReturns:\nAn array containing the convolution result.\n@@ -438,24 +437,11 @@ def conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation=None,\nlhs_dilation = (1,) * (lhs.ndim - 2)\nif rhs_dilation is None:\nrhs_dilation = (1,) * (rhs.ndim - 2)\n- if batch_group_count != 1 and batch_group_count != lhs.shape[dimension_numbers[0][0]]:\n- # XLA currently doesn't support 1 < batch_group_count < batch_size\n- # so we use the batch rule to rewrite into a convolution using feature_group_count\n- lhs = _reshape_axis_out_of(dimension_numbers[0][0], batch_group_count, lhs)\n- rhs = _reshape_axis_out_of(dimension_numbers[1][0], batch_group_count, rhs)\n- out, out_batch_dim = _conv_general_dilated_batch_rule((lhs, rhs),\n- (dimension_numbers[0][0], dimension_numbers[1][0]),\n- window_strides, padding,\n- lhs_dilation, rhs_dilation, dimension_numbers,\n- feature_group_count, batch_group_count=1)\n- out = _reshape_axis_into(out_batch_dim, dimension_numbers[2][1], out)\n- return out\nreturn conv_general_dilated_p.bind(\nlhs, rhs, window_strides=tuple(window_strides), padding=tuple(padding),\nlhs_dilation=tuple(lhs_dilation), rhs_dilation=tuple(rhs_dilation),\ndimension_numbers=dimension_numbers,\nfeature_group_count=feature_group_count,\n- batch_group_count=batch_group_count,\nlhs_shape=lhs.shape, rhs_shape=rhs.shape)\ndef dot(lhs, rhs):\n@@ -1754,16 +1740,12 @@ batching.defvectorized(bitcast_convert_type_p)\ndef _conv_general_dilated_shape_rule(\nlhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers, feature_group_count, batch_group_count, **unused_kwargs):\n+ dimension_numbers, feature_group_count, **unused_kwargs):\nassert type(dimension_numbers) is ConvDimensionNumbers\n- if not feature_group_count > 0 or not batch_group_count > 0:\n- msg = (\"conv_general_dilated feature_group_count and batch_group_count \"\n- \"must be positive integers, got {} and {}.\")\n- raise ValueError(msg.format(feature_group_count, batch_group_count))\n- if feature_group_count > 1 and batch_group_count > 1:\n- msg = (\"conv_general_dilated feature_group_count and batch_group_count \"\n- \"cannot both be greater than 1, got {} and {}.\")\n- raise ValueError(msg.format(feature_group_count, batch_group_count))\n+ if not feature_group_count > 0:\n+ msg = (\"conv_general_dilated feature_group_count \"\n+ \"must be a positive integer, got {}.\")\n+ raise ValueError(msg.format(feature_group_count))\nlhs_feature_count = lhs.shape[dimension_numbers.lhs_spec[1]]\nquot, rem = divmod(lhs_feature_count, feature_group_count)\nif rem:\n@@ -1781,21 +1763,10 @@ def _conv_general_dilated_shape_rule(\n\"multiple of feature_group_count, but {} is not a multiple of {}.\")\nraise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],\nfeature_group_count))\n- if lhs.shape[dimension_numbers.lhs_spec[0]] % batch_group_count:\n- msg = (\"conv_general_dilated lhs input batch dimension size must be a \"\n- \"multiple of batch_group_count, but {} is not a multiple of {}.\")\n- raise ValueError(msg.format(lhs.shape[dimension_numbers.lhs_spec[0]],\n- batch_group_count))\n- if rhs.shape[dimension_numbers.rhs_spec[0]] % batch_group_count:\n- msg = (\"conv_general_dilated rhs output feature dimension size must be a \"\n- \"multiple of batch_group_count, but {} is not a multiple of {}.\")\n- raise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],\n- batch_group_count))\nlhs_perm, rhs_perm, out_perm = dimension_numbers\nlhs_trans = _dilate_shape(onp.take(lhs.shape, lhs_perm), lhs_dilation)\nrhs_trans = _dilate_shape(onp.take(rhs.shape, rhs_perm), rhs_dilation)\n- out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding,\n- batch_group_count)\n+ out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding)\nreturn tuple(onp.take(out_trans, onp.argsort(out_perm)))\ndef _conv_general_dilated_dtype_rule(\n@@ -1809,13 +1780,9 @@ _conv_sdims = lambda spec: spec[2:]\ndef _conv_general_dilated_transpose_lhs(\ng, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers, feature_group_count, batch_group_count,\n+ dimension_numbers, feature_group_count,\nlhs_shape, rhs_shape):\nassert type(dimension_numbers) is ConvDimensionNumbers\n- if batch_group_count != 1:\n- msg = (\"conv_general_dilated transpose rule is only implemented for \"\n- \"batch_group_count = 1, but got {}. Open a feature request!\")\n- raise NotImplementedError(msg.format(batch_group_count)) # TODO(mattjj)\nlhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\nlhs_spec, rhs_spec, out_spec = dimension_numbers\nt_rhs_spec = _conv_spec_transpose(rhs_spec)\n@@ -1823,8 +1790,7 @@ def _conv_general_dilated_transpose_lhs(\n# in addition to switching the dims in the spec, need to move the feature\n# group axis into the transposed rhs's output feature dim\nrhs = _reshape_axis_out_of(rhs_spec[0], feature_group_count, rhs)\n- rhs = _reshape_axis_into(rhs_spec[0],\n- rhs_spec[1] + int(rhs_spec[0] < rhs_spec[1]), rhs)\n+ rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[1], rhs)\ntrans_dimension_numbers = ConvDimensionNumbers(out_spec, t_rhs_spec, lhs_spec)\npadding = _conv_general_vjp_lhs_padding(\nonp.take(lhs_shape, lhs_sdims), onp.take(rhs_shape, rhs_sdims),\n@@ -1835,17 +1801,19 @@ def _conv_general_dilated_transpose_lhs(\ng, revd_weights, window_strides=lhs_dilation, padding=padding,\nlhs_dilation=window_strides, rhs_dilation=rhs_dilation,\ndimension_numbers=trans_dimension_numbers,\n- feature_group_count=feature_group_count,\n- batch_group_count=batch_group_count)\n+ feature_group_count=feature_group_count)\ndef _conv_general_dilated_transpose_rhs(\ng, lhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers, feature_group_count, batch_group_count,\n+ dimension_numbers, feature_group_count,\nlhs_shape, rhs_shape):\nassert type(dimension_numbers) is ConvDimensionNumbers\nlhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\nlhs_trans, rhs_trans, out_trans = map(_conv_spec_transpose, dimension_numbers)\n+ if feature_group_count > 1:\n+ lhs = _reshape_axis_out_of(lhs_trans[0], feature_group_count, lhs)\n+ lhs = _reshape_axis_into(lhs_trans[0], lhs_trans[1], lhs)\ntrans_dimension_numbers = ConvDimensionNumbers(lhs_trans, out_trans, rhs_trans)\npadding = _conv_general_vjp_rhs_padding(\nonp.take(lhs_shape, lhs_sdims), onp.take(rhs_shape, rhs_sdims),\n@@ -1855,22 +1823,21 @@ def _conv_general_dilated_transpose_rhs(\nlhs, g, window_strides=rhs_dilation, padding=padding,\nlhs_dilation=lhs_dilation, rhs_dilation=window_strides,\ndimension_numbers=trans_dimension_numbers,\n- feature_group_count=batch_group_count,\n- batch_group_count=feature_group_count)\n+ feature_group_count=feature_group_count)\ndef _conv_general_dilated_translation_rule(\nc, lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers, feature_group_count, batch_group_count, **unused_kwargs):\n+ dimension_numbers, feature_group_count, **unused_kwargs):\nassert type(dimension_numbers) is ConvDimensionNumbers\ndimension_numbers = _conv_general_proto(dimension_numbers)\nreturn c.ConvGeneralDilated(lhs, rhs, window_strides, padding, lhs_dilation,\nrhs_dilation, dimension_numbers,\n- feature_group_count, batch_group_count)\n+ feature_group_count)\ndef _conv_general_dilated_batch_rule(\nbatched_args, batch_dims, window_strides, padding,\nlhs_dilation, rhs_dilation, dimension_numbers,\n- feature_group_count, batch_group_count, **unused_kwargs):\n+ feature_group_count, **unused_kwargs):\nlhs, rhs = batched_args\nlhs_bdim, rhs_bdim = batch_dims\nlhs_spec, rhs_spec, out_spec = dimension_numbers\n@@ -1881,8 +1848,7 @@ def _conv_general_dilated_batch_rule(\nnew_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\nout = conv_general_dilated(new_lhs, new_rhs, window_strides, padding,\nlhs_dilation, rhs_dilation, dimension_numbers,\n- feature_group_count=lhs.shape[lhs_bdim] * feature_group_count,\n- batch_group_count=batch_group_count)\n+ feature_group_count=lhs.shape[lhs_bdim] * feature_group_count)\nout = _reshape_axis_out_of(out_spec[1], lhs.shape[lhs_bdim], out)\nreturn out, out_spec[1]\n@@ -1890,7 +1856,7 @@ def _conv_general_dilated_batch_rule(\nnew_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[0], lhs)\nout = conv_general_dilated(new_lhs, rhs, window_strides, padding,\nlhs_dilation, rhs_dilation, dimension_numbers,\n- feature_group_count, batch_group_count)\n+ feature_group_count)\nout = _reshape_axis_out_of(out_spec[0], lhs.shape[lhs_bdim], out)\nreturn out, out_spec[0]\n@@ -1899,7 +1865,7 @@ def _conv_general_dilated_batch_rule(\nnew_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\nout = conv_general_dilated(lhs, new_rhs, window_strides, padding,\nlhs_dilation, rhs_dilation, dimension_numbers,\n- feature_group_count, batch_group_count)\n+ feature_group_count)\nout = _reshape_axis_out_of(out_spec[1], rhs.shape[rhs_bdim], out)\nreturn out, out_spec[1]\nelse:\n@@ -1916,7 +1882,7 @@ def _conv_general_dilated_batch_rule(\nnew_rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[0], new_rhs)\nout = conv_general_dilated(lhs, new_rhs, window_strides, padding,\nlhs_dilation, rhs_dilation, dimension_numbers,\n- feature_group_count, batch_group_count)\n+ feature_group_count)\nout = _reshape_axis_out_of(out_spec[1], feature_group_count, out)\nout = _reshape_axis_out_of(out_spec[1] + 1, rhs.shape[rhs_bdim], out)\nout = _reshape_axis_into(out_spec[1], out_spec[1] + 1, out)\n@@ -3952,7 +3918,7 @@ def _check_conv_shapes(name, lhs_shape, rhs_shape, window_strides):\nraise TypeError(msg.format(name, expected_length, len(window_strides)))\n-def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1):\n+def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads):\n\"\"\"Compute the shape tuple of a conv given input shapes in canonical order.\"\"\"\nif isinstance(pads, str):\npads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)\n@@ -3964,17 +3930,16 @@ def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1):\nout_space = onp.floor_divide(\nonp.subtract(lhs_padded, rhs_shape[2:]), strides) + 1\nout_space = onp.maximum(0, out_space)\n- out_shape = (lhs_shape[0] // batch_group_count, rhs_shape[0]) + tuple(out_space)\n+ out_shape = (lhs_shape[0], rhs_shape[0]) + tuple(out_space)\nreturn tuple(out_shape)\ndef conv_general_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\n- dimension_numbers, batch_group_count=1):\n+ dimension_numbers):\nlhs_perm, rhs_perm, out_perm = conv_general_permutations(dimension_numbers)\nlhs_trans = onp.take(lhs_shape, lhs_perm)\nrhs_trans = onp.take(rhs_shape, rhs_perm)\n- out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding,\n- batch_group_count)\n+ out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding)\nreturn tuple(onp.take(out_trans, onp.argsort(out_perm)))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1652,7 +1652,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n[(1, 1), (2, 1)], # lhs_dils\n[(1, 1), (2, 2)]) # rhs_dils\nfor b, i, j in itertools.product([1, 2], repeat=3)]\n- for feature_group_count in [1] # TODO(mattjj): feature_group_count=2\n+ for feature_group_count in [1, 2]\nfor strides in all_strides\nfor rhs_dil in rhs_dils\nfor lhs_dil in lhs_dils\n"
}
] | Python | Apache License 2.0 | google/jax | write out batch_feature_groups to simplify and correct implementation |
260,335 | 17.06.2019 14:23:26 | 25,200 | 96775a4d40cf2e06c68fe69a8cd0f6f0b7cc2242 | add tuple simplification logic | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -260,6 +260,9 @@ class JaxprTracer(Tracer):\nreturn self\ndef unpack(self):\n+ if type(self.recipe) is JaxprEqn and self.recipe.primitive is core.pack_p:\n+ return tuple(self.recipe.invars)\n+\npv, const = self.pval\nif isinstance(pv, (AbstractValue, JaxprTracerTuple)):\nn = len(pv)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -774,6 +774,16 @@ class APITest(jtu.JaxTestCase):\nself.assertEqual(out_shape, (3, 5))\n+ def test_detuplification(self):\n+ def fun(x):\n+ y = pack((x, x))\n+ z = pack((y, x))\n+ y1, _ = z\n+ y2, _ = y1\n+ return y2\n+\n+ assert len(api.make_jaxpr(fun)(1).eqns) == 0\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add tuple simplification logic
Co-authored-by: Dougal Maclaurin <dougalm@google.com> |
260,335 | 17.06.2019 19:39:14 | 25,200 | 6dd54236665ed1ade1574e453f22a320bc5e9e94 | manually fuse a transpose into a reshape | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1903,7 +1903,7 @@ def _reshape_axis_into(src, dst, x):\nperm.insert(dst, src)\nnew_shape = list(onp.delete(x.shape, src))\nnew_shape[dst] *= x.shape[src]\n- return reshape(transpose(x, perm), new_shape) # TODO(mattjj): manually fuse\n+ return reshape(x, new_shape, perm)\ndef _reshape_axis_out_of(src, size1, x):\nshape = list(x.shape)\n"
}
] | Python | Apache License 2.0 | google/jax | manually fuse a transpose into a reshape |
260,335 | 18.06.2019 08:09:37 | 25,200 | 221426fadcfd99cc4e95f562b51ff33a18621630 | de-duplicate constants staged into jaxprs | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -119,6 +119,9 @@ class Literal(object):\nreturn self.val == other.val if self.hashable else self.val is other.val\ndef __repr__(self):\n+ if self.hashable:\n+ return '{}'.format(self.val)\n+ else:\nreturn 'Literal(val={}, hashable={})'.format(self.val, self.hashable)\nclass Primitive(object):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -454,6 +454,7 @@ def tracers_to_jaxpr(in_tracers, out_tracer):\neqns = []\nenv = {}\nconsts = {}\n+ const_to_var = defaultdict(newvar)\ndestructuring_vars = {}\nfor t in sorted_tracers:\nrecipe = t.recipe\n@@ -464,7 +465,8 @@ def tracers_to_jaxpr(in_tracers, out_tracer):\nelif isinstance(recipe, FreeVar):\nenv[var(t)] = recipe.val\nelif isinstance(recipe, ConstVar):\n- consts[var(t)] = recipe.val\n+ v = t_to_var[id(t)] = const_to_var[id(recipe.val)]\n+ consts[v] = recipe.val\nelif isinstance(recipe, Literal):\nt_to_var[id(t)] = recipe\nelif isinstance(recipe, Destructuring):\n"
}
] | Python | Apache License 2.0 | google/jax | de-duplicate constants staged into jaxprs
Co-authored-by: Peter Hawkins <phawkins@google.com>
Co-authored-by: Dougal Maclaurin <dougalm@google.com> |
260,335 | 18.06.2019 09:18:44 | 25,200 | eb01b8bfef577ea94125ee77137d02eb539be5f9 | improve linearize error message
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -762,13 +762,23 @@ def linearize(fun, *primals):\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- lifted_jvp = partial(lift_linearized, jaxpr, consts, (in_trees, out_tree), out_pval)\n+ primal_avals = list(map(core.get_aval, primals_flat))\n+ lifted_jvp = partial(lift_linearized, jaxpr, primal_avals, consts,\n+ (in_trees, out_tree), out_pval)\nreturn out_primal_py, lifted_jvp\n-def lift_linearized(jaxpr, consts, io_tree, out_pval, *py_args):\n- def fun(*args):\n- primals = pack(args) # doesn't matter what these are-they'll be ignored\n- tangents = pack(args)\n+def lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pval, *py_args):\n+ def fun(*tangents):\n+ tangent_avals = list(map(core.get_aval, tangents))\n+ for primal_aval, tangent_aval in zip(primal_avals, tangent_avals):\n+ try:\n+ core.lattice_join(primal_aval, tangent_aval)\n+ except TypeError:\n+ msg = (\"linearized function called on tangent values inconsistent with \"\n+ \"the original primal values.\")\n+ raise ValueError(msg)\n+ primals = pack(tangents) # doesn't matter what these are-they'll be ignored\n+ tangents = pack(tangents)\n_, ans = eval_jaxpr(jaxpr, consts, (), primals, tangents)\nreturn pe.merge_pvals(ans, out_pval)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -784,6 +784,20 @@ class APITest(jtu.JaxTestCase):\nassert len(api.make_jaxpr(fun)(1).eqns) == 0\n+ def test_issue_871(self):\n+ T = np.array([[1., 2.], [3., 4.], [5., 6.]])\n+ x = np.array([1, 2, 3])\n+\n+ y, f_jvp = api.linearize(np.sum, x)\n+ jtu.check_raises(lambda: f_jvp(T), ValueError,\n+ (\"linearized function called on tangent values \"\n+ \"inconsistent with the original primal values.\"))\n+\n+ y, f_jvp = api.linearize(api.jit(np.sum), x)\n+ jtu.check_raises(lambda: f_jvp(T), ValueError,\n+ (\"linearized function called on tangent values \"\n+ \"inconsistent with the original primal values.\"))\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | improve linearize error message
fixes #871 |
260,335 | 18.06.2019 21:23:52 | 25,200 | e939e7291a6c07ad41fddc7f0325e62540f46457 | lower args in JaxprTrace.process_eval | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -94,6 +94,9 @@ class JaxprTrace(Trace):\npartial_eval = custom_partial_eval_rules[primitive]\nreturn partial_eval(self, *tracers, **params)\nelse:\n+ pvs, consts = unzip2(t.pval for t in tracers)\n+ if all(pv is None for pv in pvs):\n+ return primitive.bind(*consts, **params)\ntracers = map(self.instantiate_const, tracers)\navals = [t.aval for t in tracers]\nout_aval = primitive.abstract_eval(*avals, **params)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -24,7 +24,7 @@ import six\nimport jax.numpy as np\nfrom jax import jit, grad, device_get, device_put, jacfwd, jacrev, hessian\n-from jax import api\n+from jax import api, lax\nfrom jax.core import Primitive, pack, JaxTuple\nfrom jax.interpreters import ad\nfrom jax.interpreters.xla import DeviceArray, DeviceTuple\n@@ -798,6 +798,23 @@ class APITest(jtu.JaxTestCase):\n(\"linearized function called on tangent values \"\n\"inconsistent with the original primal values.\"))\n+ def test_partial_eval_lower(self):\n+ # this is a simplified model of a bug that arose when we first used @jit in\n+ # a jvp rule. it's in this file because we want to use make_jaxpr.\n+ @api.jit\n+ def f(a, b, c):\n+ a = lax.broadcast(a, (2,))\n+ return lax.select(a, b, c)\n+\n+ a = onp.ones((3, 3), dtype=onp.bool_)\n+ b = onp.ones((2, 3, 3))\n+ c = onp.ones((2, 3, 3))\n+\n+ jaxpr = api.make_jaxpr(lambda b, c: f(a, b, c))(b, c)\n+ subjaxpr = next(eqn.bound_subjaxprs[0][0] for eqn in jaxpr.eqns\n+ if eqn.bound_subjaxprs)\n+ self.assertEqual(len(subjaxpr.eqns), 1)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | lower args in JaxprTrace.process_eval |
260,335 | 18.06.2019 21:51:51 | 25,200 | b53bccc5d07436e3aedc28a220e43675fb60b607 | make more literals nontrivially hashable | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -20,9 +20,11 @@ from operator import attrgetter\nfrom contextlib import contextmanager\nfrom collections import namedtuple, Counter, defaultdict\nfrom weakref import ref\n-import six\nimport types\n+import numpy as onp\n+import six\n+\nfrom . import linear_util as lu\nfrom .util import unzip2, safe_zip, safe_map, partial, curry, WrapHashably\nfrom .pprint_util import pp, vcat, hcat, pp_kv_pairs\n@@ -101,28 +103,30 @@ JaxprEqn = namedtuple('JaxprEqn', ['invars', 'outvars', 'primitive',\n'bound_subjaxprs', 'restructure',\n'destructure', 'params'])\nclass Literal(object):\n- __slots__ = [\"val\", \"hashable\"]\n+ __slots__ = [\"val\", \"hash\"]\ndef __init__(self, val):\nself.val = val\ntry:\n- hash(val)\n+ self.hash = hash(val)\nexcept TypeError:\n- self.hashable = False\n- else:\n- self.hashable = True\n+ if type(val) is onp.ndarray:\n+ try:\n+ self.hash = hash(val.item())\n+ except (TypeError, AttributeError):\n+ self.hash = None\ndef __hash__(self):\n- return hash(self.val) if self.hashable else id(self.val)\n+ return id(self.val) if self.hash is None else self.hash\ndef __eq__(self, other):\n- return self.val == other.val if self.hashable else self.val is other.val\n+ return self.val is other.val if self.hash is None else self.val == other.val\ndef __repr__(self):\n- if self.hashable:\n- return '{}'.format(self.val)\n- else:\n+ if self.hash is None:\nreturn 'Literal(val={}, hashable={})'.format(self.val, self.hashable)\n+ else:\n+ return '{}'.format(self.val)\nclass Primitive(object):\ndef __init__(self, name):\n"
}
] | Python | Apache License 2.0 | google/jax | make more literals nontrivially hashable |
260,335 | 19.06.2019 07:44:46 | 25,200 | 0a040fcba0659908dca5f3e6ac10dc392e475fb6 | fix parallel axis_index w/ custom partial_eval | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -399,11 +399,17 @@ def axis_index(axis_name):\nreturn axis_index_p.bind(trace.pure(core.unit),\naxis_size=axis_size, axis_name=axis_name)\n+def _axis_index_partial_eval(trace, _, **params):\n+ # This looks like the standard JaxprTrace.process_primitive rule except that\n+ # we don't attempt to lower out of the trace.\n+ out_aval = ShapedArray((), onp.uint32)\n+ eqn = pe.JaxprEqn([], None, axis_index_p, (), False, False, params)\n+ return pe.JaxprTracer(trace, pe.PartialVal((out_aval, core.unit)), eqn)\n+\naxis_index_p = core.Primitive('axis_index')\n-axis_index_p.def_abstract_eval(\n- lambda _, axis_size, axis_name: ShapedArray((), onp.uint32))\n-xla.translations[axis_index_p] = lambda c, _, axis_size, axis_name: \\\n+xla.translations[axis_index_p] = lambda c, axis_size, axis_name: \\\nc.Rem(c.ReplicaId(), c.Constant(onp.array(axis_size, onp.uint32)))\n+pe.custom_partial_eval_rules[axis_index_p] = _axis_index_partial_eval\n### lazy device-memory persistence and result handling\n"
}
] | Python | Apache License 2.0 | google/jax | fix parallel axis_index w/ custom partial_eval |
260,335 | 19.06.2019 10:32:55 | 25,200 | 5aef18f897dfff50b9c9604b1181c0ff55e2f97d | improve literal hashing logic
This fixes a bug where scalar ndarray literals with different dtypes
could hash to the same value. It also makes scalar DeviceArray literals
hashable after | [
{
"change_type": "MODIFY",
"old_path": "jax/abstract_arrays.py",
"new_path": "jax/abstract_arrays.py",
"diff": "@@ -200,6 +200,4 @@ def raise_to_shaped(aval):\nelse:\nraise TypeError(type(aval))\n-def is_scalar(x):\n- return isinstance(x, tuple(scalar_types)) and onp.shape(x) == ()\n-scalar_types = set(array_types)\n+core.literalable_types.update(array_types)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -22,7 +22,6 @@ from collections import namedtuple, Counter, defaultdict\nfrom weakref import ref\nimport types\n-import numpy as onp\nimport six\nfrom . import linear_util as lu\n@@ -110,9 +109,9 @@ class Literal(object):\ntry:\nself.hash = hash(val)\nexcept TypeError:\n- if type(val) is onp.ndarray:\n+ if type(val) in literalable_types:\ntry:\n- self.hash = hash(val.item())\n+ self.hash = hash((val.item(), val.dtype))\nexcept (TypeError, AttributeError):\nself.hash = None\n@@ -128,6 +127,8 @@ class Literal(object):\nelse:\nreturn '{}'.format(self.val)\n+literalable_types = set()\n+\nclass Primitive(object):\ndef __init__(self, name):\nself.name = name\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -23,7 +23,7 @@ import numpy as onp\nfrom .. import core\nfrom .. import linear_util as lu\n-from ..abstract_arrays import ShapedArray, ConcreteArray, is_scalar\n+from ..abstract_arrays import ShapedArray, ConcreteArray\nfrom ..linear_util import thunk, transformation, transformation_with_aux\nfrom ..util import unzip2, safe_zip, safe_map, toposort, partial\nfrom ..core import (Trace, Tracer, new_master, Jaxpr, JaxprEqn, Literal,\n@@ -49,7 +49,7 @@ def identity(x): return x\nclass JaxprTrace(Trace):\ndef pure(self, val):\n- if is_scalar(val):\n+ if type(val) in core.literalable_types and onp.shape(val) == ():\nreturn JaxprTracer(self, PartialVal((None, val)), Literal(val))\nelse:\nreturn self.new_const(val)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -32,7 +32,7 @@ from .. import ad_util\nfrom .. import tree_util\nfrom .. import linear_util as lu\nfrom ..abstract_arrays import (ConcreteArray, ShapedArray, make_shaped_array,\n- array_types, scalar_types)\n+ array_types)\nfrom ..core import AbstractTuple, JaxTuple, pack, valid_jaxtype, Literal\nfrom ..util import partial, partialmethod, memoize, concatenate, safe_map, prod\nfrom ..lib import xla_bridge as xb\n@@ -599,7 +599,7 @@ class DeviceArray(DeviceValue):\n# fine.\nreturn id(self)\n-scalar_types.add(DeviceArray)\n+core.literalable_types.add(DeviceArray)\n# DeviceValues don't need to be canonicalized because we assume values on the\n"
}
] | Python | Apache License 2.0 | google/jax | improve literal hashing logic
This fixes a bug where scalar ndarray literals with different dtypes
could hash to the same value. It also makes scalar DeviceArray literals
hashable after #884. |
260,335 | 19.06.2019 12:43:35 | 25,200 | 7c7031384b55f60ecc943251b1a34e2f7350021d | skip some conv vmap tests on cpu and tpu | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -2219,6 +2219,10 @@ class LaxVmapTest(jtu.JaxTestCase):\nif (lhs_bdim, rhs_bdim) != (None, None)\nfor rng in [jtu.rand_default()]\n))\n+ # TODO(mattjj): some cases fail on CPU with the latest XLA (jaxlib) release\n+ # apparently because of an AVX512 issue, and some cases fail on TPU just due\n+ # to numerical tolerances\n+ @jtu.skip_on_devices(\"tpu\", \"cpu\")\ndef testConvGeneralDilatedBatching(\nself, lhs_shape, rhs_shape, dtype, strides, padding, lhs_dil, rhs_dil,\ndimension_numbers, perms, feature_group_count, lhs_bdim, rhs_bdim, rng):\n"
}
] | Python | Apache License 2.0 | google/jax | skip some conv vmap tests on cpu and tpu |
260,512 | 19.06.2019 19:20:14 | 25,200 | d420517d7ba0a68848226cb80feb201a257faf52 | Add link to XLA header in jax_to_hlo | [
{
"change_type": "MODIFY",
"old_path": "jax/tools/jax_to_hlo.py",
"new_path": "jax/tools/jax_to_hlo.py",
"diff": "@@ -61,7 +61,7 @@ This generates two BUILD targets:\n//your/thing:prog_hlo.txt\nYou can then depend on one of these as a data dependency and invoke it using\n-XLA's public C++ APIs.\n+XLA's public C++ APIs (See tensorflow/compiler/xla/service/hlo_runner.h).\nNote that XLA's backwards-compatibility guarantees for saved HLO are currently\n(2019-06-13) best-effort. It will mostly work, but it will occasionally break,\n"
}
] | Python | Apache License 2.0 | google/jax | Add link to XLA header in jax_to_hlo |
260,335 | 20.06.2019 07:23:14 | 25,200 | 37fd8efa42ed3c0598ab9e75bf39cafc4076b18e | fix a case of const instantiation for scan | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -424,7 +424,7 @@ def instantiate_const_at(trace, instantiate, tracer):\nreturn pack(map(partial(instantiate_const_at, trace), instantiate, tracer))\nelif t is bool:\nif instantiate:\n- return trace.instantiate_const(tracer)\n+ return trace.instantiate_const(trace.full_raise(tracer))\nelse:\nreturn tracer\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | fix a case of const instantiation for scan |
260,535 | 20.06.2019 16:23:13 | 25,200 | 8b163628fdb504ee51975383d35c2d43bdc3085f | map stop_gradient over data structure. otherwise it is silently a no-op | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -45,7 +45,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_unflatten\n+from ..tree_util import build_tree, tree_unflatten, tree_map\nfrom ..lib import xla_bridge\nfrom ..lib.xla_bridge import xla_client\n@@ -971,7 +971,7 @@ def stop_gradient(x):\n>>> jax.grad(jax.grad(lambda x: jax.lax.stop_gradient(x)**2))(3.)\narray(0., dtype=float32)\n\"\"\"\n- return stop_gradient_p.bind(x)\n+ return tree_map(stop_gradient_p.bind, x)\ndef _safe_mul(x, y): return safe_mul_p.bind(x, y)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -2174,6 +2174,10 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nexpected = api.grad(api.grad(f2))(x, x)\nself.assertAllClose(ans, expected, check_dtypes=True)\n+ ans = api.grad(lambda x: lax.stop_gradient({'foo':x})['foo'])(3.)\n+ expected = onp.array(0.0)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef slicer(x, bdim):\nif bdim is None:\n"
}
] | Python | Apache License 2.0 | google/jax | map stop_gradient over data structure. otherwise it is silently a no-op |
260,547 | 23.06.2019 16:26:51 | -3,600 | 2bde78a808eb6b2ca14c6abd6e8de010fe892a15 | Add sigmoid into stax | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -41,6 +41,7 @@ import jax.numpy as np\ndef relu(x): return np.maximum(x, 0.)\ndef softplus(x): return np.logaddexp(x, 0.)\n+def sigmoid(x): return 1. / (1. + np.exp(-x))\ndef logsoftmax(x, axis=-1):\n\"\"\"Apply log softmax to an array of logits, log-normalizing along an axis.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | Add sigmoid into stax |
260,335 | 23.06.2019 15:31:13 | 25,200 | fe7329e8087c23e87d741ed112f410837358bcf8 | iniital soft_pmap implementation | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -597,6 +597,10 @@ def pmap(fun, axis_name=None):\nf_pmapped.__name__ = namestr(f_pmapped.__name__, axis_name)\nreturn f_pmapped\n+class _TempAxisName(object):\n+ def __repr__(self):\n+ return '<temp axis {}>'.format(hex(id(self)))\n+\ndef _pmap_axis_size(args):\nleaves, _ = tree_flatten(args)\naxis_sizes = reduce(set.union, map(_axis_size, leaves), set())\n@@ -624,6 +628,58 @@ def _aval_axis_size(aval):\nraise ValueError(\"pmap can't map over scalars.\")\n+def soft_pmap(fun, axis_name=None):\n+ axis_name = _TempAxisName() if axis_name is None else axis_name\n+\n+ @wraps(fun)\n+ def f_pmapped(*args):\n+ axis_size = _pmap_axis_size(args)\n+ chunk_size, leftover = divmod(axis_size, pxla.unmapped_device_count())\n+ if chunk_size == 0 and leftover:\n+ return pmap(fun, axis_name)(*args) # can map directly onto hardware\n+ elif leftover:\n+ raise ValueError\n+\n+ num_chunks = axis_size // chunk_size\n+ f = lu.wrap_init(fun)\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+ reshaped_args = map(partial(_reshape_split, num_chunks), in_flat)\n+ soft_mapped_fun = pxla.split_axis(jaxtree_fun, axis_name, chunk_size)\n+ reshaped_out = pxla.xla_pmap(soft_mapped_fun, *reshaped_args,\n+ axis_name=axis_name, axis_size=num_chunks)\n+ return build_tree(out_tree(), _reshape_merge(reshaped_out))\n+\n+ namestr = \"soft_pmap({}, axis_name={})\".format\n+ f_pmapped.__name__ = namestr(f_pmapped.__name__, axis_name)\n+ return f_pmapped\n+\n+def _reshape_split(num_chunks, arg):\n+ def split(aval, arg):\n+ t = type(aval)\n+ if t is core.AbstractTuple:\n+ return core.pack(map(split, aval, arg))\n+ elif t is ShapedArray:\n+ prefix = (num_chunks, arg.shape[0] // num_chunks)\n+ return arg.reshape(prefix + arg.shape[1:])\n+ else:\n+ raise TypeError(aval)\n+\n+ return split(batching.get_aval(arg), arg)\n+\n+def _reshape_merge(ans):\n+ def merge(aval, ans):\n+ t = type(aval)\n+ if t is core.AbstractTuple:\n+ return core.pack(map(merge, aval, ans))\n+ elif t is ShapedArray:\n+ return ans.reshape((-1,) + ans.shape[2:])\n+ else:\n+ raise TypeError(aval)\n+\n+ return merge(batching.get_aval(ans), ans)\n+\n+\ndef _serial_pmap(fun, axis_name=None, in_axes=0, out_axes=0):\n\"\"\"Vectorizing pseudo-map for single-program multiple-data (SPMD) functions.\"\"\"\naxis_name = _TempAxisName() if axis_name is None else axis_name\n@@ -638,10 +694,6 @@ def _serial_pmap(fun, axis_name=None, in_axes=0, out_axes=0):\nreturn map_fun\n-class _TempAxisName(object):\n- def __repr__(self):\n- return '<temp axis {}>'.format(hex(id(self)))\n-\ndef _papply(fun, axis_size, in_axes=0, out_axes=0):\n\"\"\"Apply a function using parallel computation by sharding inputs.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -86,16 +86,17 @@ class BatchTracer(Tracer):\nreturn remove_batch_dim_from_aval(self.batch_dim, batched_aval)\ndef unpack(self):\n+ if self.batch_dim is None:\n+ return tuple(self.val)\n+ else:\nt = type(self.batch_dim)\nif t is tuple:\n- batch_dims = self.batch_dim\n+ dims = list(self.batch_dim)\nelif t is int:\n- batch_dims = [self.batch_dim] * len(self.val)\n- elif t is type(None):\n- return tuple(self.val)\n+ dims = [self.batch_dim] * len(self.val)\nelse:\n- raise TypeError(t)\n- return map(partial(BatchTracer, self.trace), self.val, batch_dims)\n+ raise TypeError(self.batch_dim)\n+ return map(partial(BatchTracer, self.trace), self.val, dims)\ndef full_lower(self):\nif self.batch_dim is None:\n@@ -139,7 +140,7 @@ class BatchTrace(Trace):\nif all(dim is None for dim in dims):\nreturn map_primitive.bind(f, *vals, **params)\nelse:\n- size = reduce(set.union, map(dimsize, dims, vals)).pop()\n+ size, = reduce(set.union, map(dimsize, dims, vals))\nis_batched = tuple(map(where_batched, dims))\nvals = map(partial(instantiate_bdim, size, 1), is_batched, dims, vals)\ndims = tuple(map(partial(bools_to_bdims, 0), is_batched))\n@@ -153,13 +154,11 @@ class BatchTrace(Trace):\ndef todo(x):\ntrace = BatchTrace(master, core.cur_sublevel())\nreturn BatchTracer(trace, x, dim)\n-\nreturn val, todo\ndef pack(self, tracers):\n- vals = pack([t.val for t in tracers])\n- batch_dim = tuple(t.batch_dim for t in tracers)\n- return BatchTracer(self, vals, batch_dim)\n+ vals, dims = unzip2((t.val, t.batch_dim) for t in tracers)\n+ return BatchTracer(self, pack(vals), tuple(dims))\n### abstract values\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/parallel.py",
"new_path": "jax/interpreters/parallel.py",
"diff": "@@ -16,6 +16,7 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n+from contextlib import contextmanager\nfrom functools import partial\nimport warnings\n@@ -31,6 +32,7 @@ from ..util import safe_zip, unzip2, unzip3, partialmethod, prod\nfrom ..lib import xla_bridge as xb\nfrom . import partial_eval as pe\nfrom . import batching\n+from . import pxla\nzip = safe_zip\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -409,8 +409,8 @@ def trace_to_subjaxpr(master, instantiate, pvals):\nassert all([isinstance(pv, PartialVal) for pv in pvals]), pvals\ntrace = JaxprTrace(master, core.cur_sublevel())\nin_tracers = map(trace.new_arg, pvals)\n- out_tracer = yield in_tracers, {}\n- out_tracer = trace.full_raise(out_tracer)\n+ ans = yield in_tracers, {}\n+ out_tracer = trace.full_raise(ans)\nout_tracer = instantiate_const_at(trace, instantiate, out_tracer)\nout_tracer = trace.full_raise(out_tracer) # instantiation (unpack) can lower\njaxpr, consts, env = tracers_to_jaxpr(in_tracers, out_tracer)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -36,7 +36,6 @@ from .partial_eval import trace_to_subjaxpr, merge_pvals, JaxprTrace, PartialVal\nfrom .batching import dimsize, broadcast\nfrom . import batching\nfrom . import partial_eval as pe\n-from . import parallel\nfrom . import xla\nfrom . import ad\n@@ -350,7 +349,7 @@ parallel_translation_rules = {}\n# primitive dispatched from Python, rather than being part of a staged-out pmap\n# computation and handled by replicated_comp above:\n# 1. axis_size = psum(1, 'axis_name'),\n-# 2. to enable an outermost implicit pmap-like context for multi-host\n+# 2. to enable an implicit outermost pmap-like context for multi-host\n# multi-controller SPMD programs.\n# In each case, we can't rely on any data dependence on a pmap trace; instead we\n# need some dynamic context, basically modeling the axis name environment stack.\n@@ -359,56 +358,76 @@ parallel_translation_rules = {}\n# globally-scoped root environment frame and compile and execute a single-op\n# XLA collective.\n-# TODO(mattjj, skyewm): op-by-op multi-controller via a global (root) frame\n-\n-DynamicAxisEnvFrame = namedtuple(\"DynamicAxisEnvFrame\", [\"name\", \"size\", \"trace\"])\n+class DynamicAxisEnvFrame(object):\n+ __slots__ = [\"name\", \"pmap_trace\", \"hard_size\", \"soft_trace\", \"soft_size\"]\n+ def __init__(self, name, pmap_trace, hard_size):\n+ self.name = name\n+ self.pmap_trace = pmap_trace\n+ self.hard_size = hard_size\n+ self.soft_trace = None\n+ self.soft_size = None\nclass DynamicAxisEnv(list):\ndef __contains__(self, axis_name):\n- return axis_name in (name for name, _, _ in self)\n+ return axis_name in (frame.name for frame in self)\ndef __getitem__(self, axis_name):\nif axis_name not in self:\nraise NameError(\"unbound axis name: {}\".format(axis_name))\n- for name, size, trace in reversed(self):\n- if name == axis_name:\n- return size, trace\n+ for frame in reversed(self):\n+ if frame.name == axis_name:\n+ return frame\nelse:\nassert False\ndynamic_axis_env = DynamicAxisEnv()\n@contextmanager\n-def extend_dynamic_axis_env(axis_name, axis_size, trace):\n- dynamic_axis_env.append(DynamicAxisEnvFrame(axis_name, axis_size, trace))\n+def extend_dynamic_axis_env(axis_name, pmap_trace, hard_size):\n+ dynamic_axis_env.append(DynamicAxisEnvFrame(axis_name, pmap_trace, hard_size))\nyield\ndynamic_axis_env.pop()\n+def unmapped_device_count():\n+ mapped = prod(frame.hard_size for frame in dynamic_axis_env)\n+ unmapped, ragged = divmod(xb.device_count(), mapped)\n+ assert not ragged and unmapped > 0\n+ return unmapped\n+\ndef apply_parallel_primitive(prim, *args, **params):\n- axis_name = params['axis_name']\n+ # This is the op-by-op version of applying a collective primitive, like a psum\n+ # that doesn't have a data dependence on the argument of a pmap function. In\n+ # particular, this code gets hit when we write `axis_size = psum(1, 'i')`. We\n+ # look up information in the dynamic axis env.\n+ axis_name = params.pop('axis_name')\n+ logical_size = lambda frame: frame.hard_size * (frame.soft_size or 1)\nif isinstance(axis_name, (list, tuple)):\n- shape = tuple(dynamic_axis_env[name][0] for name in axis_name)\n+ shape = tuple(logical_size(dynamic_axis_env[name]) for name in axis_name)\nelse:\n- shape = (dynamic_axis_env[axis_name][0],)\n- return parallel_pure_rules[prim](*args, shape=shape)\n+ shape = (logical_size(dynamic_axis_env[axis_name]),)\n+ return parallel_pure_rules[prim](*args, shape=shape, **params)\nparallel_pure_rules = {}\ndef axis_index(axis_name):\n- axis_size, trace = dynamic_axis_env[axis_name]\n- return axis_index_p.bind(trace.pure(core.unit),\n- axis_size=axis_size, axis_name=axis_name)\n+ frame = dynamic_axis_env[axis_name]\n+ dummy_arg = frame.pmap_trace.pure(core.unit)\n+ if frame.soft_trace:\n+ dummy_arg = frame.soft_trace.pure(dummy_arg)\n+ return axis_index_p.bind(dummy_arg, hard_size=frame.hard_size,\n+ soft_size=frame.soft_size, axis_name=axis_name)\ndef _axis_index_partial_eval(trace, _, **params):\n- # This looks like the standard JaxprTrace.process_primitive rule except that\n- # we don't attempt to lower out of the trace.\n+ # This partial_eval rule adds the axis_index primitive into the jaxpr formed\n+ # during pmap lowering. It is like the standard JaxprTrace.process_primitive\n+ # rule except that we don't attempt to lower out of the trace.\nout_aval = ShapedArray((), onp.uint32)\neqn = pe.JaxprEqn([], None, axis_index_p, (), False, False, params)\nreturn pe.JaxprTracer(trace, pe.PartialVal((out_aval, core.unit)), eqn)\naxis_index_p = core.Primitive('axis_index')\n-xla.translations[axis_index_p] = lambda c, axis_size, axis_name: \\\n- c.Rem(c.ReplicaId(), c.Constant(onp.array(axis_size, onp.uint32)))\n+xla.translations[axis_index_p] = lambda c, hard_size, soft_size, axis_name: \\\n+ c.Rem(c.ReplicaId(), c.Constant(onp.array(hard_size, onp.uint32)))\npe.custom_partial_eval_rules[axis_index_p] = _axis_index_partial_eval\n@@ -566,16 +585,16 @@ def _shard_aval(axis_size, aval):\nassert aval.shape[0] == axis_size\nreturn ShapedArray(aval.shape[1:], aval.dtype)\nelse:\n- raise TypeError(type(aval))\n+ raise TypeError(aval)\n@lu.memoize\ndef parallel_callable(fun, axis_name, axis_size, *avals):\npvals = [PartialVal((aval, core.unit)) for aval in avals]\n- pval = PartialVal((core.AbstractTuple(()), core.unit))\n+ pval = PartialVal((core.AbstractTuple(()), core.unit)) # dummy value\n@lu.wrap_init\ndef dynamic_fun(dummy, *args):\n- with extend_dynamic_axis_env(axis_name, axis_size, dummy.trace):\n+ with extend_dynamic_axis_env(axis_name, dummy.trace, axis_size):\nreturn fun.call_wrapped(*args)\nwith core.new_master(JaxprTrace, True) as master:\n@@ -623,3 +642,178 @@ ad.primitive_transposes[xla_pmap_p] = partial(ad.map_transpose, xla_pmap_p)\npe.map_primitives.add(xla_pmap_p)\n# TODO(mattjj): enable pjit inside jit, maybe by merging xla_pmap and xla_call\n# xla.translations[xla_pmap_p] = xla.xla_call_translation_rule\n+\n+\n+### soft_pmap axis split transformation\n+\n+# To allow pmap to map over logical axes larger than the number of XLA devices\n+# available, we use a transformation that effectively simulates having more\n+# devices in software. The strategy is to split the mapped axis into two axes,\n+# one to be hardware-mapped and the other to be software-mapped. Thus the\n+# transformation rewrites the function to be mapped so that it accepts a new\n+# leading axis (the software-mapped axis), and so that collectives in the\n+# original function correspond to both device-local operations and collective\n+# communication operations across hardware devices that implement the original\n+# logical semantics.\n+\n+@lu.transformation\n+def split_axis(axis_name, chunk_size, *args):\n+ with core.new_master(SplitAxisTrace) as master:\n+ trace = SplitAxisTrace(master, core.cur_sublevel())\n+ in_tracers = map(partial(SplitAxisTracer, trace, axis_name), args)\n+ with add_chunk_to_axis_env(axis_name, trace, chunk_size):\n+ ans = yield in_tracers, {}\n+ out_tracer = trace.full_raise(ans)\n+ out_val, out_axis = out_tracer.val, out_tracer.axis_name\n+ del master, out_tracer\n+ if out_axis is not_mapped:\n+ out_val = batching.broadcast2(chunk_size, 0, out_val)\n+ yield out_val\n+\n+@lu.transformation_with_aux\n+def split_axis_subtrace(master, names, *vals):\n+ trace = SplitAxisTrace(master, core.cur_sublevel())\n+ ans = yield map(partial(SplitAxisTracer, trace), names, vals), {}\n+ out_tracer = trace.full_raise(ans)\n+ out_val, out_name = out_tracer.val, out_tracer.axis_name\n+ yield out_val, out_name\n+\n+class NotMapped(object): pass\n+not_mapped = NotMapped\n+\n+class SplitAxisTuple(tuple): pass\n+\n+@contextmanager\n+def add_chunk_to_axis_env(axis_name, soft_trace, soft_size):\n+ dynamic_axis_env[axis_name].soft_trace = soft_trace\n+ dynamic_axis_env[axis_name].soft_size = soft_size\n+ yield\n+ dynamic_axis_env[axis_name].soft_trace = None\n+ dynamic_axis_env[axis_name].soft_size = None\n+\n+class SplitAxisTracer(core.Tracer):\n+ def __init__(self, trace, axis_name, val):\n+ self.trace = trace\n+ self.axis_name = axis_name\n+ self.val = val\n+\n+ @property\n+ def aval(self):\n+ aval = batching.get_aval(self.val)\n+ if self.axis_name is not_mapped:\n+ return aval\n+ else:\n+ return batching.remove_batch_dim_from_aval(0, aval)\n+\n+ def unpack(self):\n+ if self.name is not_mapped:\n+ return tuple(self.val)\n+ else:\n+ if type(self.name) is SplitAxisTuple:\n+ names = list(self.name)\n+ else:\n+ names = [self.name] * len(self.val)\n+ return map(partial(SplitAxisTracer, self.trace), names, self.val)\n+\n+ def full_lower(self):\n+ if self.axis_name is not_mapped:\n+ return core.full_lower(self.val)\n+ else:\n+ return self\n+\n+class SplitAxisTrace(core.Trace):\n+ def pure(self, val):\n+ return SplitAxisTracer(self, not_mapped, val)\n+\n+ def lift(self, val):\n+ return SplitAxisTracer(self, not_mapped, val)\n+\n+ def sublift(self, val):\n+ return SplitAxisTracer(self, val.axis_name, val.val)\n+\n+ def process_primitive(self, primitive, tracers, params):\n+ vals_in, names_in = unzip2((t.val, t.axis_name) for t in tracers)\n+ if primitive is axis_index_p:\n+ dummy, = vals_in\n+ hard_idx = primitive.bind(dummy, **params)\n+ val_out = hard_idx * params['soft_size'] + onp.arange(params['soft_size'])\n+ return SplitAxisTracer(self, params['axis_name'], val_out)\n+ elif all(axis_name is not_mapped for axis_name in names_in):\n+ return primitive.bind(*vals_in, **params)\n+ else:\n+ name, = set(n for n in names_in if n is not not_mapped)\n+ if type(primitive) is PmapPrimitive:\n+ # if it's a pmap collective primitive, do something special\n+ if name == params['axis_name']:\n+ # if the name matches this tracer's name, apply the split_axis rule\n+ try:\n+ rule = split_axis_rules[primitive]\n+ except KeyError:\n+ msg = \"split_axis for {} not implemented. Open a feature request!\"\n+ raise NotImplementedError(msg.format(primitive))\n+ which_mapped = [n is not not_mapped for n in names_in]\n+ val_out, is_mapped = rule(vals_in, which_mapped, **params)\n+ name_out = name if is_mapped else not_mapped\n+ return SplitAxisTracer(self, name_out, val_out)\n+ else:\n+ # if not, bind the primitive without any processing\n+ val_out = primitive.bind(*vals_in, **params)\n+ return SplitAxisTracer(self, name, val_out)\n+ else:\n+ # if it's not a pmap collective primitive, act just like batching\n+ rule = batching.get_primitive_batcher(primitive)\n+ axes_in = [None if n is not_mapped else 0 for n in names_in]\n+ val_out, axis_out = rule(vals_in, axes_in, **params)\n+ val_out = batching.moveaxis2(axis_out, 0, val_out)\n+ return SplitAxisTracer(self, name, val_out)\n+\n+ def process_call(self, call_primitive, f, tracers, params):\n+ if call_primitive in pe.map_primitives:\n+ return self.process_map(call_primitive, f, tracers, params)\n+ else:\n+ vals, names = unzip2((t.val, t.axis_name) for t in tracers)\n+ if all(name is not_mapped for name in names):\n+ return call_primitive.bind(f, *vals, **params)\n+ else:\n+ f, name_out = split_axis_subtrace(f, self.master, names)\n+ val_out = call_primitive.bind(f, *vals, **params)\n+ return SplitAxisTracer(self, name_out(), val_out)\n+\n+ def process_map(self, map_primitive, f, tracers, params):\n+ vals, names = unzip2((t.val, t.axis_name) for t in tracers)\n+ if all(name is not_mapped for name in names):\n+ return map_primitive.bind(f, *vals, **params)\n+ else:\n+ # because the map primitive maps over leading axes, we need to transpose\n+ # the software-mapped axis on any mapped arguments to be the second axis;\n+ # then we call the map primitive and resume the trace under the call\n+ vals_transposed = map(partial(transpose_mapped, 0, 1), names, vals)\n+ f, name_out = split_axis_subtrace(f, self.master, names)\n+ val_out_transposed = map_primitive.bind(f, *vals_transposed, **params)\n+ val_out = transpose_mapped(1, 0, name_out(), val_out_transposed)\n+ return SplitAxisTracer(self, name_out(), val_out)\n+\n+ def post_process_call(self, call_primitive, out_tracer, params):\n+ val, name = out_tracer.val, out_tracer.axis_name\n+ master = self.master\n+ def todo(x):\n+ trace = SplitAxisTrace(master, core.cur_sublevel())\n+ return SplitAxisTracer(trace, name, x)\n+ return val, todo\n+\n+ def pack(self, tracers):\n+ vals, names = unzip2((t.val, t.axis_name) for t in tracers)\n+ return SplitAxisTracer(self, SplitAxisTuple(names), core.pack(vals))\n+\n+def transpose_mapped(src, dst, name, x):\n+ def transpose(name, x):\n+ if type(name) is SplitAxisTuple:\n+ return core.pack(map(transpose, name, x))\n+ elif name is not_mapped:\n+ return x\n+ else:\n+ return batching.moveaxis2(src, dst, x)\n+ return transpose(name, x)\n+\n+\n+split_axis_rules = {}\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -27,6 +27,8 @@ from jax.interpreters import pxla\nfrom jax.util import partial, unzip2, prod\nfrom jax.lib import xla_bridge\n+from jax.interpreters.pxla import axis_index\n+\n### parallel traceables\n@@ -111,8 +113,9 @@ def pswapaxes(x, axis_name, axis):\nThe mapped axis size must be equal to the size of the unmapped axis; that is,\nwe must have ``lax.psum(1, axis_name) == x.shape[axis]``.\n- This function is similar to ``psplit`` except the pmapped axis of the input is\n- placed at the position ``axis`` in the output.\n+ This function is a special case of ``all_to_all`` where the pmapped axis of\n+ the input is placed at the position ``axis`` in the output. That is, it is\n+ equivalent to ``all_to_all(x, axis_name, axis, axis)``.\nArgs:\nx: array with a mapped axis named ``axis_name``.\n@@ -126,19 +129,17 @@ def pswapaxes(x, axis_name, axis):\nwhere ``axis_size`` is the size of the mapped axis named ``axis_name`` in\nthe input ``x``.\n\"\"\"\n- # TODO(mattjj): enable this check when _serial_pmap works with psum(1, ax)\n- # axis_size = psum(1, axis_name)\n- # if axis_size != x.shape[axis]:\n- # msg = (\"pswapaxes requires the size of the mapped axis ``axis_name`` equal \"\n- # \"``x.shape[axis]``, but they are {} and {} respectively.\")\n- # raise ValueError(msg.format(axis_size(axis_name), x.shape[axis]))\n- return pswapaxes_p.bind(x, axis_name=axis_name, axis=axis)\n+ return all_to_all(x, axis_name, axis, axis)\n+\n+def all_to_all(x, axis_name, split_axis, concat_axis):\n+ \"\"\"Materialize the mapped axis and map a different axis.\n-def psplit(x, axis_name, split_axis, concat_axis):\n- \"\"\"Unmap the pmapped axis ``axis_name`` and map ``axis`` with the same name.\n+ In the output, the input mapped axis ``axis_name`` is materialized at the\n+ logical axis position ``concat_axis``, and the input unmapped axis at position\n+ ``split_axis`` is mapped with the name ``axis_name``.\n- This function is similar to ``pswapaxes`` except the pmapped axis of the input\n- is placed as the leading logical axis of the output.\n+ The input mapped axis size must be equal to the size of the axis to be mapped;\n+ that is, we must have ``lax.psum(1, axis_name) == x.shape[split_axis]``.\nArgs:\nx: array with a mapped axis named ``axis_name``.\n@@ -146,16 +147,22 @@ def psplit(x, axis_name, split_axis, concat_axis):\n``pmap`` docstring for more details).\nsplit_axis: int indicating the unmapped axis of ``x`` to map with the name\n``axis_name``.\n- concat_axis: int indicating the dimension at which to materialize the axis\n- of ``x`` mapped with ``axis_name``.\n+ concat_axis: int indicating the position in the output to materialize the\n+ mapped axis of the input with the name ``axis_name``.\nReturns:\n- An array with shape ``np.insert(np.delete(x.shape, split_axis), concat_axis,\n- axis_size)`` where ``axis_size`` is the size of the mapped axis named\n- ``axis_name`` in the input ``x``.\n+ An array with shape given by the expression::\n+ np.insert(np.delete(x.shape, split_axis), concat_axis, axis_size)\n+\n+ where ``axis_size`` is the size of the mapped axis named ``axis_name`` in\n+ the input ``x``, i.e. ``axis_size = lax.psum(1, axis_name)``.\n\"\"\"\n- return psplit_p.bind(x, axis_name=axis_name, concat_axis=concat_axis,\n- split_axis=split_axis)\n+ if psum(1, axis_name) != x.shape[split_axis]:\n+ msg = (\"all_to_all requires the size of the mapped axis axis_name to equal \"\n+ \"x.shape[split_axis], but they are {} and {} respectively.\")\n+ raise ValueError(msg.format(psum(1, axis_name), x.shape[split_axis]))\n+ return all_to_all_p.bind(x, split_axis=split_axis, concat_axis=concat_axis,\n+ axis_name=axis_name)\ndef psplit_like(x, y, axis_name):\n\"\"\"Ensure the named mapped axis of ``x`` aligns with that of ``y``.\"\"\"\n@@ -179,21 +186,25 @@ def _allreduce_serial_pmap_rule(reducer, vals, axes):\naxis, = axes\nreturn reducer(val, [axis]), None\n+def _allreduce_split_axis_rule(prim, reducer, vals, which_mapped, axis_name):\n+ assert tuple(which_mapped) == (True,)\n+ x, = vals\n+ return prim.bind(reducer(x, [0]), axis_name=axis_name), False\n+\ndef _allreduce_translation_rule(prim, c, val, replica_groups):\ndtype = c.GetShape(val).numpy_dtype()\nscalar = xla_bridge.Shape.array_shape(dtype, ())\ncomputation = xla.primitive_computation(prim, scalar, scalar)\nreturn c.AllReduce(val, computation, replica_groups=replica_groups)\n-\npsum_p = standard_pmap_primitive('psum')\nparallel.defreducer(lax.reduce_sum_p, psum_p)\nparallel.serial_pmap_primitive_rules[psum_p] = \\\npartial(_allreduce_serial_pmap_rule, lax._reduce_sum)\n+pxla.split_axis_rules[psum_p] = \\\n+ partial(_allreduce_split_axis_rule, psum_p, lax._reduce_sum)\npxla.parallel_translation_rules[psum_p] = \\\npartial(_allreduce_translation_rule, lax.add_p)\n-pxla.parallel_translation_rules[psum_p] = \\\n- lambda c, val, replica_groups: c.CrossReplicaSum(val, replica_groups)\npxla.parallel_pure_rules[psum_p] = lambda x, shape: x * prod(shape)\nad.deflinear(psum_p, lambda t, axis_name: [t])\n@@ -237,38 +248,30 @@ ad.deflinear(ppermute_p, _ppermute_transpose_rule)\npxla.parallel_translation_rules[ppermute_p] = _ppermute_translation_rule\n-def _pswapaxes_serial_pmap_rule(vals, axes, axis):\n- x, = vals\n- axis_in, = axes\n- if x.shape[axis_in] != x.shape[axis]:\n- raise ValueError(\"pswapaxes between non-square dimensions\")\n- perm = list(range(x.ndim))\n- perm[axis_in] = axis\n- perm[axis] = axis_in\n- return lax.transpose(x, perm), axis_in\n-\n-def _pswapaxes_translation_rule(c, xla_x, axis, replica_groups):\n- return c.AllToAll(xla_x, axis, axis, replica_groups)\n-\n-pswapaxes_p = standard_pmap_primitive('pswapaxes')\n-pxla.parallel_translation_rules[pswapaxes_p] = _pswapaxes_translation_rule\n-parallel.serial_pmap_primitive_rules[pswapaxes_p] = _pswapaxes_serial_pmap_rule\n-\n+def _all_to_all_translation_rule(c, x, split_axis, concat_axis, replica_groups):\n+ return c.AllToAll(x, split_axis, concat_axis, replica_groups)\n-def _psplit_serial_pmap_rule(vals, axes, split_axis, concat_axis):\n+def _all_to_all_split_axis_rule(vals, which_mapped, split_axis, concat_axis,\n+ axis_name):\n+ assert tuple(which_mapped) == (True,)\nx, = vals\n- axis_in, = axes\n- if x.shape[axis_in] != x.shape[split_axis]:\n- raise ValueError(\n- \"psplit between non-square dimensions {} and {} of {}\".format(\n- axis_in, split_axis, x.shape))\n- perm = list(range(x.ndim))\n- perm[axis_in] = concat_axis\n- perm[concat_axis] = axis_in\n- return lax.transpose(x, perm), split_axis\n-\n-psplit_p = standard_pmap_primitive('psplit')\n-parallel.serial_pmap_primitive_rules[psplit_p] = _psplit_serial_pmap_rule\n+ # perform the communication to swap the hardware-mapped axes\n+ stacked = all_to_all_p.bind(x, split_axis=split_axis + 1, concat_axis=0,\n+ axis_name=axis_name)\n+ # transpose the newly mapped axis to the front, newly unmapped to concat_axis\n+ out = _moveaxis(split_axis + 1, 0, stacked)\n+ out = _moveaxis(1, concat_axis + 1, out)\n+ return out, True\n+\n+def _moveaxis(src, dst, x):\n+ perm = [i for i in range(x.ndim) if i != src]\n+ perm.insert(dst, src)\n+ return lax.transpose(x, perm)\n+\n+\n+all_to_all_p = standard_pmap_primitive('all_to_all')\n+pxla.parallel_translation_rules[all_to_all_p] = _all_to_all_translation_rule\n+pxla.split_axis_rules[all_to_all_p] = _all_to_all_split_axis_rule\ndef _psplit_like_serial_pmap_rule(vals, axes):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -291,14 +291,23 @@ class _JaxComputationBuilder(xla_client.ComputationBuilder):\nelse:\nraise TypeError(\"No constant handler for type: {}\".format(py_type))\n- # TODO(mattjj): remove when CRS is added to XLA:CPU\n+ # TODO(mattjj): remove when CrossReplicaSum is added to XLA:CPU\ndef CrossReplicaSum(self, operand, replica_groups):\n\"\"\"Workaround for CrossReplicaSum not being implemented on some backends.\"\"\"\nif len(replica_groups[0]) == 1:\nreturn operand\nelse:\n- return super(_JaxComputationBuilder, self).CrossReplicaSum(operand,\n- replica_groups)\n+ return super(_JaxComputationBuilder, self).CrossReplicaSum(\n+ operand, replica_groups)\n+\n+ # TODO(mattjj): remove when AllToAll is added to XLA:CPU\n+ def AllToAll(self, operand, split_axis, concat_axis, replica_groups):\n+ \"\"\"Workaround for AllToAll not being implemented on some backends.\"\"\"\n+ if len(replica_groups[0]) == 1:\n+ return operand\n+ else:\n+ return super(_JaxComputationBuilder, self).AllToAll(\n+ operand, split_axis, concat_axis, replica_groups)\ndef make_computation_builder(name):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -167,7 +167,7 @@ def _promote_to_result_dtype(op, *args):\ndef _result_dtype(op, *args):\n\"\"\"Compute result dtype of applying op to arguments with given dtypes.\"\"\"\n- args = (onp.ones((0,) * ndim(arg), _dtype(arg)) for arg in args)\n+ args = [onp.ones((0,) * ndim(arg), _dtype(arg)) for arg in args]\nreturn _dtype(op(*args))\n"
}
] | Python | Apache License 2.0 | google/jax | iniital soft_pmap implementation |
260,335 | 23.06.2019 16:41:59 | 25,200 | e36613da908cca4b5689c4f089d4fd21ed4ffdae | add basic soft_pmap tests | [
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -27,7 +27,8 @@ import jax.numpy as np\nfrom jax import test_util as jtu\nfrom jax import core\nfrom jax import lax\n-from jax.api import pmap, jit, vmap, jvp, grad, make_jaxpr, linearize, device_put\n+from jax.api import (pmap, soft_pmap, jit, vmap, jvp, grad, make_jaxpr,\n+ linearize, device_put)\nfrom jax.lib import xla_bridge\nfrom jax.util import prod\nfrom jax.interpreters import pxla\n@@ -519,7 +520,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(expected_bz1, bz1, check_dtypes=False)\nself.assertAllClose(bz2, bz2, check_dtypes=False)\n- @jtu.skip_on_devices(\"cpu\", \"gpu\")\n+ @jtu.skip_on_devices(\"gpu\")\ndef testPswapaxes(self):\ndevice_count = xla_bridge.device_count()\nshape = (device_count, 3, device_count, 5)\n@@ -529,6 +530,63 @@ class PmapTest(jtu.JaxTestCase):\nexpected = onp.swapaxes(x, 0, 2)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testSoftPmapPsum(self):\n+ n = 4 * xla_bridge.device_count()\n+ def f(x):\n+ return x / lax.psum(x, 'i')\n+ ans = soft_pmap(f, 'i')(np.ones(n))\n+ expected = onp.ones(n) / n\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testSoftPmapAxisIndex(self):\n+ n = 4 * xla_bridge.device_count()\n+ def f(x):\n+ return x * lax.axis_index('i')\n+ ans = soft_pmap(f, 'i')(2 * np.ones(n))\n+ expected = 2 * onp.arange(n)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testSoftPmapOfJit(self):\n+ n = 4 * xla_bridge.device_count()\n+ def f(x):\n+ return 3 * x\n+ ans = soft_pmap(jit(f), 'i')(onp.arange(n))\n+ expected = 3 * onp.arange(n)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testSoftPmapNested(self):\n+ n = 4 * xla_bridge.device_count()\n+\n+ @partial(soft_pmap, axis_name='i')\n+ @partial(soft_pmap, axis_name='j')\n+ def f(x):\n+ i_size = lax.psum(1, 'i')\n+ return x + lax.axis_index('i') + i_size * lax.axis_index('j')\n+\n+ ans = f(np.zeros((n, n)))\n+ expected = onp.arange(n ** 2).reshape(n, n).T\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testGradOfSoftPmap(self):\n+ n = 4 * xla_bridge.device_count()\n+\n+ @partial(soft_pmap, axis_name='i')\n+ def f(x):\n+ return x * lax.axis_index('i')\n+\n+ ans = grad(lambda x: np.sum(f(x)))(np.zeros((n, n)))\n+ expected = onp.repeat(onp.arange(n)[:, None], n, axis=1)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ @jtu.skip_on_devices(\"gpu\")\n+ def testSoftPmapAllToAll(self):\n+ n = 4 * xla_bridge.device_count()\n+ def f(x):\n+ return lax.all_to_all(x, 'i', 0, 0)\n+ ans = soft_pmap(f, 'i')(np.arange(n ** 2).reshape(n, n))\n+ expected = onp.arange(n ** 2).reshape(n, n).T\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add basic soft_pmap tests |
260,335 | 24.06.2019 08:17:15 | 25,200 | 80f6eee865ce190422cfd2ae683e87eeda269799 | added broken test for broadcasting papply | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/parallel.py",
"new_path": "jax/interpreters/parallel.py",
"diff": "@@ -170,6 +170,7 @@ def broadcasting_papply(prim, name, size, vals, axes, **params):\nx, y = vals\nxdim, ydim = axes\n+ # TODO vectors! these asserts are wrong\nif xdim is None:\nif x.shape:\nassert x.shape[ydim] == 1\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/parallel_test.py",
"new_path": "tests/parallel_test.py",
"diff": "@@ -128,6 +128,7 @@ class PapplyTest(jtu.JaxTestCase):\nclass ParallelizeTest(jtu.JaxTestCase):\ndef testNormalize(self):\n+\ndef f(x):\nreturn x / x.sum(0)\n@@ -139,6 +140,17 @@ class ParallelizeTest(jtu.JaxTestCase):\njaxpr = make_jaxpr(_parallelize(f))(x)\nself.assertIn('psum', repr(jaxpr))\n+ def testAdd(self):\n+ x = onp.arange(10)\n+\n+ def f(y):\n+ return x + y\n+\n+ y = 2 * onp.arange(10)\n+ expected = f(y)\n+ ans = _parallelize(f)(y)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"testTranspose_shape={}_perm={}\"\n.format(shape, perm),\n"
}
] | Python | Apache License 2.0 | google/jax | added broken test for broadcasting papply |
260,335 | 24.06.2019 11:10:45 | 25,200 | 40bbf068d8c1e0e5d8360ba191a81187aaf3b1a6 | fix broadcasting papply rule, move to lax_parallel | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/parallel.py",
"new_path": "jax/interpreters/parallel.py",
"diff": "@@ -138,72 +138,3 @@ class PapplyTrace(Trace):\nname = tuple(t.name for t in tracers)\nsize = tuple(t.axis_size for t in tracers)\nreturn PapplyTracer(self, name, size, vals, axis)\n-\n-\n-def vectorized_papply(prim, name, size, vals, axes, **params):\n- assert all(axes[0] == a for a in axes[1:])\n- return prim.bind(*vals, **params), axes[0]\n-\n-def reducer_papply(prim, cprim, name, size, vals, papply_axes, axes, **kwargs):\n- operand, = vals\n- papply_axis, = papply_axes\n-\n- other_axes = [i for i in axes if i != papply_axis]\n- other_axes = [i - 1 if i > papply_axis else i for i in other_axes]\n-\n- if other_axes:\n- if 'input_shape' in kwargs: # special to the reduce-sum family\n- s = kwargs['input_shape']\n- kwargs['input_shape'] = s[:papply_axis] + s[papply_axis + 1:]\n- result = prim.bind(operand, axes=tuple(other_axes), **kwargs)\n- else:\n- result = operand\n-\n- if not axes or papply_axis in axes:\n- return cprim.bind(result, axis_name=name), None\n- else:\n- new_papply_axis = papply_axis - onp.sum(onp.less(other_axes, papply_axis))\n- return result, new_papply_axis\n-\n-\n-def broadcasting_papply(prim, name, size, vals, axes, **params):\n- x, y = vals\n- xdim, ydim = axes\n-\n- # TODO vectors! these asserts are wrong\n- if xdim is None:\n- if x.shape:\n- assert x.shape[ydim] == 1\n- x = x.reshape(onp.delete(x.shape, ydim))\n- return prim.bind(x, y, **params), ydim\n- elif ydim is None:\n- if y.shape:\n- assert y.shape[xdim] == 1\n- y = y.reshape(onp.delete(y.shape, xdim))\n- return prim.bind(x, y, **params), xdim\n- elif xdim == ydim:\n- return prim.bind(x, y, **params), xdim\n- else:\n- from jax.lax.lax_parallel import all_to_all # TODO circular deps\n- x = all_to_all(x, name, ydim - int(xdim <= ydim), xdim)\n- return prim.bind(x, y, **params), ydim\n-\n-\n-def identity_papply(prim, argnum, name, size, vals, axes, **params):\n- return prim.bind(*vals, **params), axes[argnum]\n-\n-\n-papply_primitive_rules = {}\n-\n-def defvectorized(prim):\n- papply_primitive_rules[prim] = partial(vectorized_papply, prim)\n-\n-def defreducer(prim, collective_prim):\n- papply_primitive_rules[prim] = partial(reducer_papply, prim,\n- collective_prim)\n-\n-def defbroadcasting(prim):\n- papply_primitive_rules[prim] = partial(broadcasting_papply, prim)\n-\n-def defidentity(prim, argnum=0):\n- papply_primitive_rules[prim] = partial(identity_papply, prim, argnum)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -43,7 +43,6 @@ from ..interpreters import partial_eval as pe\nfrom ..interpreters import xla\nfrom ..interpreters import ad\nfrom ..interpreters import batching\n-from ..interpreters import parallel\nfrom ..util import curry, memoize, safe_zip, unzip2, prod\nfrom ..tree_util import build_tree, tree_unflatten, tree_map\nfrom ..lib import xla_bridge\n@@ -1430,7 +1429,6 @@ def unop(result_dtype, accepted_dtypes, name):\ndtype_rule = partial(unop_dtype_rule, result_dtype, accepted_dtypes, name)\nprim = standard_primitive(_attrgetter('shape'), dtype_rule, name)\nbatching.defvectorized(prim)\n- parallel.defvectorized(prim)\nreturn prim\nstandard_unop = partial(unop, _identity)\n_attrgetter = lambda name: lambda x, **kwargs: getattr(x, name)\n@@ -1471,7 +1469,6 @@ def binop(result_dtype, accepted_dtypes, name, translation_rule=None):\nprim = standard_primitive(shape_rule, dtype_rule, name,\ntranslation_rule=translation_rule)\nbatching.defbroadcasting(prim)\n- parallel.defbroadcasting(prim)\nreturn prim\nstandard_binop = partial(binop, _input_dtype)\n@@ -3865,7 +3862,6 @@ tie_in_p.def_abstract_eval(lambda x, y: y)\nxla.translations[tie_in_p] = lambda c, x, y: y\nad.deflinear(tie_in_p, _tie_in_transpose_rule)\nbatching.primitive_batchers[tie_in_p] = _tie_in_batch_rule\n-parallel.defidentity(tie_in_p, argnum=1)\nshaped_identity_p = Primitive('shape_id')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -190,7 +190,6 @@ def _allreduce_translation_rule(prim, c, val, replica_groups):\nreturn c.AllReduce(val, computation, replica_groups=replica_groups)\npsum_p = standard_pmap_primitive('psum')\n-parallel.defreducer(lax.reduce_sum_p, psum_p)\npxla.split_axis_rules[psum_p] = \\\npartial(_allreduce_split_axis_rule, psum_p, lax._reduce_sum)\npxla.parallel_translation_rules[psum_p] = \\\n@@ -200,7 +199,6 @@ ad.deflinear(psum_p, lambda t, axis_name: [t])\npmax_p = standard_pmap_primitive('pmax')\n-parallel.defreducer(lax.reduce_max_p, pmax_p)\npxla.parallel_translation_rules[pmax_p] = \\\npartial(_allreduce_translation_rule, lax.max_p)\npxla.split_axis_rules[pmax_p] = \\\n@@ -208,7 +206,6 @@ pxla.split_axis_rules[pmax_p] = \\\npmin_p = standard_pmap_primitive('pmin')\n-parallel.defreducer(lax.reduce_min_p, pmin_p)\npxla.parallel_translation_rules[pmin_p] = \\\npartial(_allreduce_translation_rule, lax.min_p)\npxla.split_axis_rules[pmin_p] = \\\n@@ -268,6 +265,95 @@ pxla.split_axis_rules[all_to_all_p] = _all_to_all_split_axis_rule\n# primitives, but that currently causes circular dependencies. More refactoring\n# might fix this.\n+\n+def _drop(x, dim, axis_name):\n+ return lax.dynamic_index_in_dim(x, axis_index(axis_name), dim, False)\n+\n+\n+def _broadcasting_papply(prim, name, size, vals, axes, **params):\n+ x, y = vals\n+ xdim, ydim = axes\n+\n+ if xdim is None:\n+ if x.shape:\n+ if x.shape[ydim] == 1:\n+ x = x.reshape(onp.delete(x.shape, ydim))\n+ else:\n+ x = _drop(x, ydim, name)\n+ return prim.bind(x, y, **params), ydim\n+ elif ydim is None:\n+ if y.shape:\n+ if y.shape[xdim] == 1:\n+ y = y.reshape(onp.delete(y.shape, xdim))\n+ else:\n+ y = _drop(y, xdim, name)\n+ return prim.bind(x, y, **params), xdim\n+ elif xdim == ydim:\n+ return prim.bind(x, y, **params), xdim\n+ else:\n+ x = all_to_all(x, name, ydim - int(xdim <= ydim), xdim)\n+ return prim.bind(x, y, **params), ydim\n+\n+def _defbroadcasting(prim):\n+ parallel.papply_primitive_rules[prim] = partial(_broadcasting_papply, prim)\n+\n+\n+def _vectorized_papply(prim, name, size, vals, axes, **params):\n+ assert all(axes[0] == a for a in axes[1:])\n+ return prim.bind(*vals, **params), axes[0]\n+\n+def _defvectorized(prim):\n+ parallel.papply_primitive_rules[prim] = partial(_vectorized_papply, prim)\n+\n+\n+def _reducer_papply(prim, cprim, name, size, vals, papply_axes, axes, **kwargs):\n+ operand, = vals\n+ papply_axis, = papply_axes\n+\n+ other_axes = [i for i in axes if i != papply_axis]\n+ other_axes = [i - 1 if i > papply_axis else i for i in other_axes]\n+\n+ if other_axes:\n+ if 'input_shape' in kwargs: # special to the reduce-sum family\n+ s = kwargs['input_shape']\n+ kwargs['input_shape'] = s[:papply_axis] + s[papply_axis + 1:]\n+ result = prim.bind(operand, axes=tuple(other_axes), **kwargs)\n+ else:\n+ result = operand\n+\n+ if not axes or papply_axis in axes:\n+ return cprim.bind(result, axis_name=name), None\n+ else:\n+ new_papply_axis = papply_axis - onp.sum(onp.less(other_axes, papply_axis))\n+ return result, new_papply_axis\n+\n+def _defreducer(prim, collective_prim):\n+ parallel.papply_primitive_rules[prim] = partial(_reducer_papply, prim, collective_prim)\n+\n+\n+def _identity_papply(prim, argnum, name, vals, axes, **params):\n+ return prim.bind(*vals, **params), axes[argnum]\n+\n+def _defidentity(prim, argnum=0):\n+ parallel.papply_primitive_rules[prim] = partial(_identity_papply, prim, argnum)\n+\n+\n+_defvectorized(lax.sin_p)\n+_defvectorized(lax.cos_p)\n+_defvectorized(lax.neg_p)\n+\n+_defbroadcasting(lax.add_p)\n+_defbroadcasting(lax.sub_p)\n+_defbroadcasting(lax.div_p)\n+_defbroadcasting(lax.mul_p)\n+\n+_defidentity(lax.tie_in_p)\n+\n+_defreducer(lax.reduce_sum_p, psum_p)\n+_defreducer(lax.reduce_max_p, pmax_p)\n+_defreducer(lax.reduce_min_p, pmin_p)\n+\n+\ndef _dot_papply_rule(name, size, vals, dims):\nx, y = vals\nxdim, ydim = dims\n@@ -383,13 +469,8 @@ def _select_papply_rule(name, size, vals, dims):\nraise NotImplementedError(\n'papply of select with operands split along different dimensions')\ndim, = dimset\n-\ndef drop(x, d):\n- if d is None:\n- return lax.dynamic_index_in_dim(x, axis_index(name), dim, False)\n- else:\n- return x\n-\n+ return _drop(x, dim, name) if d is None else x\nreturn lax.select_p.bind(*map(drop, vals, dims)), dim\n"
}
] | Python | Apache License 2.0 | google/jax | fix broadcasting papply rule, move to lax_parallel |
260,335 | 24.06.2019 11:18:56 | 25,200 | c118b5cf136736a17de3114242266097ec3f7afc | associate papply rules with more primitives | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -338,14 +338,47 @@ def _defidentity(prim, argnum=0):\nparallel.papply_primitive_rules[prim] = partial(_identity_papply, prim, argnum)\n+_defvectorized(lax.neg_p)\n+_defvectorized(lax.sign_p)\n+_defvectorized(lax.floor_p)\n+_defvectorized(lax.ceil_p)\n+_defvectorized(lax.round_p)\n+_defvectorized(lax.is_finite_p)\n+_defvectorized(lax.exp_p)\n+_defvectorized(lax.log_p)\n+_defvectorized(lax.expm1_p)\n+_defvectorized(lax.log1p_p)\n+_defvectorized(lax.tanh_p)\n_defvectorized(lax.sin_p)\n_defvectorized(lax.cos_p)\n-_defvectorized(lax.neg_p)\n-\n+_defvectorized(lax.lgamma_p)\n+_defvectorized(lax.digamma_p)\n+_defvectorized(lax.erf_p)\n+_defvectorized(lax.erfc_p)\n+_defvectorized(lax.erf_inv_p)\n+_defvectorized(lax.real_p)\n+_defvectorized(lax.imag_p)\n+_defvectorized(lax.conj_p)\n+_defvectorized(lax.abs_p)\n+_defvectorized(lax.sqrt_p)\n+\n+_defbroadcasting(lax.atan2_p)\n+_defbroadcasting(lax.complex_p)\n+_defbroadcasting(lax.pow_p)\n+_defbroadcasting(lax.and_p)\n+_defbroadcasting(lax.or_p)\n+_defbroadcasting(lax.xor_p)\n_defbroadcasting(lax.add_p)\n_defbroadcasting(lax.sub_p)\n-_defbroadcasting(lax.div_p)\n_defbroadcasting(lax.mul_p)\n+_defbroadcasting(lax.safe_mul_p)\n+_defbroadcasting(lax.div_p)\n+_defbroadcasting(lax.rem_p)\n+_defbroadcasting(lax.max_p)\n+_defbroadcasting(lax.min_p)\n+_defbroadcasting(lax.shift_left_p)\n+_defbroadcasting(lax.shift_right_arithmetic_p)\n+_defbroadcasting(lax.shift_right_logical_p)\n_defidentity(lax.tie_in_p)\n"
}
] | Python | Apache License 2.0 | google/jax | associate papply rules with more primitives |
260,335 | 24.06.2019 11:48:33 | 25,200 | 9783fad6aa676cd32e037fc29bb986a045cdb5d1 | more fixes to broadcasting papply rule, tests | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -269,6 +269,13 @@ pxla.split_axis_rules[all_to_all_p] = _all_to_all_split_axis_rule\ndef _drop(x, dim, axis_name):\nreturn lax.dynamic_index_in_dim(x, axis_index(axis_name), dim, False)\n+def _allgather(x, dim, size, axis_name):\n+ shape = list(x.shape)\n+ shape.insert(dim, size)\n+ out = lax.full(shape, lax._const(x, 0))\n+ out = lax.dynamic_update_index_in_dim(out, x, axis_index(axis_name), dim)\n+ return psum(out, axis_name)\n+\ndef _broadcasting_papply(prim, name, size, vals, axes, **params):\nx, y = vals\n@@ -291,7 +298,18 @@ def _broadcasting_papply(prim, name, size, vals, axes, **params):\nelif xdim == ydim:\nreturn prim.bind(x, y, **params), xdim\nelse:\n- x = all_to_all(x, name, ydim - int(xdim <= ydim), xdim)\n+ x_tosplit = ydim - int(xdim <= ydim)\n+ y_tosplit = xdim - int(ydim <= xdim)\n+ if y.shape[y_tosplit] == 1:\n+ y = _allgather(y, ydim, size, name)\n+ y = y.reshape(onp.delete(y.shape, xdim))\n+ return prim.bind(x, y, **params), ydim\n+ elif x.shape[x_tosplit] == 1:\n+ x = _allgather(x, xdim, size, name)\n+ x = x.reshape(onp.delete(x.shape, ydim))\n+ return prim.bind(x, y, **params), ydim\n+ else:\n+ x = all_to_all(x, name, x_tosplit, xdim)\nreturn prim.bind(x, y, **params), ydim\ndef _defbroadcasting(prim):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/parallel_test.py",
"new_path": "tests/parallel_test.py",
"diff": "@@ -142,15 +142,53 @@ class ParallelizeTest(jtu.JaxTestCase):\ndef testAdd(self):\nx = onp.arange(10)\n+ y = 2 * onp.arange(10)\n+ def f(x): return x + y\n+ expected = f(x)\n+ ans = _parallelize(f)(x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n- def f(y):\n+ def testAdd2(self):\n+ x = onp.arange(10)\n+ y = 2 * onp.arange(10)\n+ def f(y): return x + y\n+ expected = f(y)\n+ ans = _parallelize(f)(y)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testAdd3(self):\n+ x = onp.arange(10)\n+ y = 2 * onp.arange(10)\n+ def f(x, y):\nreturn x + y\n+ expected = f(x, y)\n+ ans = _parallelize(f)(x, y)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testOuter(self):\n+ x = onp.arange(10)\n+ y = 2 * onp.arange(10)\n+ def f(x): return x[:, None] * y\n+ expected = f(x)\n+ ans = _parallelize(f)(x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+ def testOuter2(self):\n+ x = onp.arange(10)\ny = 2 * onp.arange(10)\n+ def f(y): return x[:, None] * y\nexpected = f(y)\nans = _parallelize(f)(y)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testOuter3(self):\n+ x = onp.arange(10)\n+ y = 2 * onp.arange(10)\n+ def f(x, y): return x[:, None] * y\n+ expected = f(x, y)\n+ ans = _parallelize(f)(x, y)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"testTranspose_shape={}_perm={}\"\n.format(shape, perm),\n@@ -194,22 +232,22 @@ class ParallelizeTest(jtu.JaxTestCase):\nans = _parallelize(fun)(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- # def testDot(self):\n- # return SkipTest(\"test doesn't pass yet\") # TODO(frostig)\n-\n- # def fun(x, y):\n- # return lax.dot(x, y)\n- # xs = [\n- # onp.reshape(onp.arange(4., dtype=onp.float32), (2, 2)),\n- # onp.reshape(onp.arange(9., dtype=onp.float32), (3, 3)),\n- # ]\n- # in_axes_combos = [(0, 0), (0, 1)] # [(1, 0)]\n- # for in_axes in in_axes_combos:\n- # for x in xs:\n- # expected = fun(x, x)\n- # pfun, axis_name = _papply(fun)\n- # ans = soft_pmap(pfun, axis_name)(x, x)\n- # self.assertAllClose(ans, expected, check_dtypes=False)\n+ def testDot(self):\n+ return SkipTest(\"test doesn't pass yet\") # TODO(frostig)\n+\n+ def fun(x, y):\n+ return lax.dot(x, y)\n+ xs = [\n+ onp.reshape(onp.arange(4., dtype=onp.float32), (2, 2)),\n+ onp.reshape(onp.arange(9., dtype=onp.float32), (3, 3)),\n+ ]\n+ in_axes_combos = [(0, 0), (0, 1)] # [(1, 0)]\n+ for in_axes in in_axes_combos:\n+ for x in xs:\n+ expected = fun(x, x)\n+ pfun, axis_name = _papply(fun)\n+ ans = soft_pmap(pfun, axis_name)(x, x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | more fixes to broadcasting papply rule, tests |
260,335 | 24.06.2019 14:53:24 | 25,200 | cf29492335d48f068dca313af61e06d6a2bcaea3 | soft_pmap device persistence via lazy reshape | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -64,7 +64,7 @@ def shard_arg(device_ordinals, axis_size, arg):\nnrep = len(device_ordinals)\nassignments = assign_shards_to_replicas(nrep, axis_size)\nif (type(arg) in (ShardedDeviceArray, ShardedDeviceTuple)\n- and nrep == len(arg.device_buffers)):\n+ and _axis_size(arg) == axis_size and nrep == len(arg.device_buffers)):\n_, ids = onp.unique(assignments, return_index=True)\nget_shard = memoize_unary(lambda i: arg.device_buffers[i].to_py())\nreturn [buf if buf.device() == device_ordinals[r]\n@@ -82,6 +82,14 @@ def _slice(x, i):\nelse:\nreturn x[i]\n+def _axis_size(x):\n+ if type(x) is ShardedDeviceArray:\n+ return x.shape[0]\n+ elif type(x) is ShardedDeviceTuple:\n+ return x.axis_size\n+ else:\n+ raise TypeError(type(x))\n+\ndef sharded_result_handler(axis_size, aval):\nfull_aval = add_axis_to_aval(axis_size, aval)\n@@ -515,17 +523,40 @@ class ShardedDeviceArray(xla.DeviceArray):\nrepresent distinct logical shards. The correspondence can be computed with\nthe assign_shards_to_replicas function.\n\"\"\"\n- __slots__ = [\"device_buffers\"]\n+ __slots__ = [\"device_buffers\", \"_num_chunks\"]\ndef __init__(self, aval, device_buffers):\nself.device_buffers = device_buffers\nself.shape, self.dtype = aval.shape, aval.dtype\nself.ndim, self.size = len(aval.shape), prod(aval.shape)\n+ self._num_chunks = aval.shape[0]\nself._npy_value = None\n+ def reshape(self, *newshape, **kwargs):\n+ order = kwargs.pop(\"order\", \"C\")\n+ if len(kwargs) == 1:\n+ invalid_kwarg, = kwargs\n+ msg = \"'{}' is an invalid keyword argument for this function\"\n+ raise TypeError(msg.format(invalid_kwarg)) # same as NumPy error\n+ elif kwargs:\n+ invalid_kwargs = \"'{}'\".format(\"'\".join(kwargs))\n+ msg = \"{} are invalid keyword arguments for this function\"\n+ raise TypeError(msg.format(invalid_kwargs)) # different from NumPy error\n+ if len(newshape) == 1 and not isinstance(newshape[0], int):\n+ newshape = newshape[0]\n+\n+ if order == \"C\":\n+ newshape = onp.broadcast_to(0, self.shape).reshape(newshape).shape\n+ new = ShardedDeviceArray(ShapedArray(newshape, self.dtype),\n+ self.device_buffers)\n+ new._num_chunks = self._num_chunks\n+ return new\n+ else:\n+ return super(ShardedDeviceArray, self).reshape(newshape, order=order)\n+\ndef _ids(self):\nnum_bufs = len(self.device_buffers)\n- assignments = assign_shards_to_replicas(num_bufs, self.shape[0])\n+ assignments = assign_shards_to_replicas(num_bufs, self._num_chunks)\n_, ids = onp.unique(assignments, return_index=True)\nreturn ids\n@@ -539,17 +570,18 @@ class ShardedDeviceArray(xla.DeviceArray):\nif self._npy_value is None:\nids = self._ids()\nself.copy_to_host_async()\n- npy_shards = [buf.to_py() for buf in self.device_buffers]\n+ npy_shards = [self.device_buffers[i].to_py() for i in ids]\nself._npy_value = onp.stack([npy_shards[i] for i in ids])\n- return self._npy_value\n+ return self._npy_value.reshape(self.shape)\ndef __getitem__(self, idx):\n- if self._npy_value is None and type(idx) is int:\n+ if (self._npy_value is None and type(idx) is int\n+ and self._num_chunks == self.shape[0]):\n# When we don't have a copy of the data on the host, and we're just trying\n# to extract a simple integer-indexed slice of the logical array, we can\n# avoid transferring from all the devices and just communicate with one.\nids = self._ids()\n- return self.device_buffers[ids[idx]].to_py()\n+ return self.device_buffers[ids[idx]].to_py().reshape(self.shape[1:])\nelse:\nreturn super(ShardedDeviceArray, self).__getitem__(idx)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -457,7 +457,6 @@ class DeviceArray(DeviceValue):\nself.shape, self.dtype, self.ndim, self.size = result_shape\nself._npy_value = None\n- # TODO make device_buffer a property, make the _npy_value writeable, invalidate\n@property\ndef _value(self):\nself._check_if_deleted()\n"
}
] | Python | Apache License 2.0 | google/jax | soft_pmap device persistence via lazy reshape |
260,335 | 24.06.2019 17:24:09 | 25,200 | 73c0458ddaf8b1162a07cbee93414a8f92407026 | remove unneeded code, fix bug | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -256,8 +256,8 @@ class JVPTrace(Trace):\nprimals = [t.primal for t in tracers]\ntangents = [t.tangent for t in tracers]\nnonzero_tangents, in_tree_def = tree_to_jaxtuples(tangents)\n- f, out_tree_def = traceable(jvp_subtrace(f, self.master), in_tree_def)\n- result = call_primitive.bind(f, pack(primals), nonzero_tangents, **params)\n+ f_jvp, out_tree_def = traceable(jvp_subtrace(f, self.master), in_tree_def)\n+ result = call_primitive.bind(f_jvp, pack(primals), nonzero_tangents, **params)\nprimal_out, tangent_out = build_tree(out_tree_def(), result)\nreturn JVPTracer(self, primal_out, tangent_out)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -64,7 +64,7 @@ def shard_arg(device_ordinals, axis_size, arg):\nnrep = len(device_ordinals)\nassignments = assign_shards_to_replicas(nrep, axis_size)\nif (type(arg) in (ShardedDeviceArray, ShardedDeviceTuple)\n- and _axis_size(arg) == axis_size and nrep == len(arg.device_buffers)):\n+ and nrep == len(arg.device_buffers)):\n_, ids = onp.unique(assignments, return_index=True)\nget_shard = memoize_unary(lambda i: arg.device_buffers[i].to_py())\nreturn [buf if buf.device() == device_ordinals[r]\n@@ -82,14 +82,6 @@ def _slice(x, i):\nelse:\nreturn x[i]\n-def _axis_size(x):\n- if type(x) is ShardedDeviceArray:\n- return x.shape[0]\n- elif type(x) is ShardedDeviceTuple:\n- return x.axis_size\n- else:\n- raise TypeError(type(x))\n-\ndef sharded_result_handler(axis_size, aval):\nfull_aval = add_axis_to_aval(axis_size, aval)\n@@ -570,8 +562,7 @@ class ShardedDeviceArray(xla.DeviceArray):\nif self._npy_value is None:\nids = self._ids()\nself.copy_to_host_async()\n- npy_shards = [self.device_buffers[i].to_py() for i in ids]\n- self._npy_value = onp.stack([npy_shards[i] for i in ids])\n+ self._npy_value = onp.stack([self.device_buffers[i].to_py() for i in ids])\nreturn self._npy_value.reshape(self.shape)\ndef __getitem__(self, idx):\n"
}
] | Python | Apache License 2.0 | google/jax | remove unneeded code, fix bug |
260,335 | 24.06.2019 19:45:18 | 25,200 | a663486148e24f8152e98dce740df98248063fdc | fixes from rebase onto master | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/parallel.py",
"new_path": "jax/interpreters/parallel.py",
"diff": "@@ -138,3 +138,6 @@ class PapplyTrace(Trace):\nname = tuple(t.name for t in tracers)\nsize = tuple(t.axis_size for t in tracers)\nreturn PapplyTracer(self, name, size, vals, axis)\n+\n+\n+papply_primitive_rules = {}\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1764,12 +1764,6 @@ def _convert_element_type_translation_rule(c, operand, new_dtype, old_dtype):\nnew_etype = xla_bridge.dtype_to_etype_exact(new_dtype)\nreturn c.ConvertElementType(operand, new_element_type=new_etype)\n-def _convert_element_type_papply_rule(name, size, vals, dims, new_dtype,\n- **kwargs):\n- operand, = vals\n- dim, = dims\n- return convert_element_type(operand, new_dtype), dim\n-\nconvert_element_type_p = standard_primitive(\n_convert_element_type_shape_rule, _convert_element_type_dtype_rule,\n'convert_element_type', _convert_element_type_translation_rule)\n@@ -1777,7 +1771,6 @@ ad.deflinear(\nconvert_element_type_p,\nlambda t, new_dtype, old_dtype: [convert_element_type(t, old_dtype)])\nbatching.defvectorized(convert_element_type_p)\n-parallel.papply_primitive_rules[convert_element_type_p] = _convert_element_type_papply_rule\ndef _bitcast_convert_type_shape_rule(operand, new_dtype):\n@@ -1947,32 +1940,14 @@ def _conv_general_dilated_batch_rule(\nout = _reshape_axis_into(out_spec[1], out_spec[1] + 1, out)\nreturn out, out_spec[1]\n-def _conv_general_dilated_papply_rule(\n- name, size, vals, dims, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers, **unused_kwargs):\n- lhs, rhs = vals\n- lhs_dim, rhs_dim = dims\n- lhs_spec_batch_dim = dimension_numbers.lhs_spec[0]\n- if rhs_dim is None and lhs_dim == lhs_spec_batch_dim:\n- lhs = reshape(lhs, tuple(onp.insert(lhs.shape, lhs_dim, 1)))\n- out = conv_general_dilated(\n- lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n- dimension_numbers)\n- return out, lhs_dim\n- else:\n- raise NotImplementedError(\n- \"splitting a convolution along anything but input batch dimension\")\n-\nconv_general_dilated_p = standard_primitive(\n_conv_general_dilated_shape_rule, _conv_general_dilated_dtype_rule,\n'conv_general_dilated', _conv_general_dilated_translation_rule)\nad.defbilinear(conv_general_dilated_p,\n_conv_general_dilated_transpose_lhs,\n_conv_general_dilated_transpose_rhs)\n-batching.primitive_batchers[\n- conv_general_dilated_p] = _conv_general_dilated_batch_rule\n-parallel.papply_primitive_rules[\n- conv_general_dilated_p] = _conv_general_dilated_papply_rule\n+batching.primitive_batchers[conv_general_dilated_p] = \\\n+ _conv_general_dilated_batch_rule\ndef _reshape_axis_into(src, dst, x):\n@@ -2241,25 +2216,11 @@ def _broadcast_in_dim_batch_rule(batched_args, batch_dims, shape,\nnew_broadcast_dimensions.insert(bdim, bdim)\nreturn broadcast_in_dim(operand, new_shape, new_broadcast_dimensions), bdim\n-def _broadcast_in_dim_papply_rule(name, size, vals, dims, shape,\n- broadcast_dimensions):\n- operand, = vals\n- dim, = dims\n- out_dim = broadcast_dimensions[dim]\n- if shape[out_dim] != shape[dim]:\n- raise ValueError(\n- \"broadcast_in_dim changes hidden dimension size: {} to {}\".format(\n- shape[dim], shape[out_dim]))\n- sub_bdims = tuple(onp.delete(broadcast_dimensions, dim))\n- sub_shape = tuple(onp.delete(shape, out_dim))\n- return broadcast_in_dim(operand, sub_shape, sub_bdims), out_dim\n-\nbroadcast_in_dim_p = standard_primitive(\n_broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')\nad.deflinear(broadcast_in_dim_p, _broadcast_in_dim_transpose_rule)\nbatching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule\n-parallel.papply_primitive_rules[broadcast_in_dim_p] = _broadcast_in_dim_papply_rule\ndef _clamp_shape_rule(min, operand, max):\n@@ -2387,27 +2348,10 @@ def _pad_batch_rule(batched_args, batch_dims, padding_config):\nelse:\nraise NotImplementedError # loop and stack\n-def _pad_papply_rule(name, size, vals, dims, padding_config):\n- operand, padding_value = vals\n- operand_dim, padding_value_dim = dims\n- assert padding_value_dim is None\n- padding_config = list(padding_config)\n- if padding_config[operand_dim] == (0, 0, 0):\n- padded = pad(\n- operand,\n- padding_value,\n- padding_config[:operand_dim] + padding_config[operand_dim + 1:])\n- return padded, operand_dim\n- else:\n- raise NotImplementedError(\n- 'pad changes size of hidden dimension {} with config {}'.format(\n- operand_dim, padding_config))\n-\npad_p = standard_primitive(_pad_shape_rule, _input_dtype, 'pad')\nad.deflinear(pad_p, _pad_transpose)\nad.primitive_transposes[pad_p] = _pad_transpose\nbatching.primitive_batchers[pad_p] = _pad_batch_rule\n-parallel.papply_primitive_rules[pad_p] = _pad_papply_rule\ndef _reshape_shape_rule(operand, new_sizes, dimensions, **unused_kwargs):\n@@ -2647,30 +2591,10 @@ def _slice_batching_rule(batched_args, batch_dims, start_indices, limit_indices,\nout = slice(operand, new_start_indices, new_limit_indices, new_strides)\nreturn out, bdim\n-def _slice_papply_rule(name, size, vals, dims, start_indices, limit_indices,\n- strides, **kwargs):\n- operand, = vals\n- dim, = dims\n- start_indices = list(start_indices)\n- limit_indices = list(limit_indices)\n-\n- if (start_indices[dim] != 0 or\n- limit_indices[dim] != size or\n- strides is not None and strides[dim] != 1):\n- raise NotImplementedError('slice changes side of hidden dimension')\n-\n- out = slice(\n- operand,\n- start_indices[:dim] + start_indices[dim + 1:],\n- limit_indices[:dim] + limit_indices[dim + 1:],\n- strides[:dim] + strides[dim + 1:] if strides is not None else None)\n- return out, dim\n-\nslice_p = standard_primitive(_slice_shape_rule, _input_dtype, 'slice',\n_slice_translation_rule)\nad.deflinear(slice_p, _slice_transpose_rule)\nbatching.primitive_batchers[slice_p] = _slice_batching_rule\n-parallel.papply_primitive_rules[slice_p] = _slice_papply_rule\ndef _dynamic_slice_shape_rule(operand, start_indices, slice_sizes,\n@@ -2933,35 +2857,12 @@ def _gather_batching_rule(batched_args, batch_dims, dimension_numbers,\nreturn gather(operand, start_indices, dimension_numbers=dnums,\nslice_sizes=slice_sizes), 0\n-def _gather_papply_rule(\n- name, size, vals, dims, dimension_numbers, slice_sizes, operand_shape):\n- operand, start_indices = vals\n- operand_dim, start_indices_dim = dims\n- if (operand_dim is None and\n- start_indices_dim is not None and\n- start_indices_dim not in dimension_numbers.offset_dims and\n- dimension_numbers.collapsed_slice_dims == (0,)):\n- offset_dims = tuple(i - 1 if i > start_indices_dim else i\n- for i in dimension_numbers.offset_dims)\n- dnums = GatherDimensionNumbers(\n- offset_dims=offset_dims,\n- collapsed_slice_dims=dimension_numbers.collapsed_slice_dims,\n- start_index_map=dimension_numbers.start_index_map)\n- out = gather(operand, start_indices, dimension_numbers=dnums,\n- slice_sizes=slice_sizes)\n- out_dim = start_indices_dim + onp.sum(\n- onp.less_equal(offset_dims, start_indices_dim))\n- return out, out_dim\n- else:\n- raise NotImplementedError\n-\ngather_p = standard_primitive(\n_gather_shape_rule, _gather_dtype_rule, 'gather',\n_gather_translation_rule)\nad.defjvp(gather_p, _gather_jvp_rule, None)\nad.primitive_transposes[gather_p] = _gather_transpose_rule\nbatching.primitive_batchers[gather_p] = _gather_batching_rule\n-parallel.papply_primitive_rules[gather_p] = _gather_papply_rule\nclass ScatterDimensionNumbers(collections.namedtuple(\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -492,7 +492,7 @@ def _reshape_papply_rule(name, size, vals, axes, new_sizes, dimensions,\nfor i, cur_sz in enumerate(new_sizes):\nif prod == left and cur_sz == size:\nreturn i\n- prod = prod * sz\n+ prod = prod * cur_sz\nreturn None\nif dimensions is None:\n@@ -539,10 +539,117 @@ def _add_jaxvals_papply_rule(name, size, vals, dims):\nreturn ad_util.add_jaxvals_p.bind(x, y), out_dim\n+def _convert_element_type_papply_rule(\n+ name, size, vals, dims, new_dtype, **params):\n+ operand, = vals\n+ dim, = dims\n+ return convert_element_type(operand, new_dtype), dim\n+\n+\n+def _conv_general_dilated_papply_rule(\n+ name, size, vals, dims, window_strides, padding, lhs_dilation, rhs_dilation,\n+ dimension_numbers, **unused_kwargs):\n+ lhs, rhs = vals\n+ lhs_dim, rhs_dim = dims\n+ lhs_spec_batch_dim = dimension_numbers.lhs_spec[0]\n+ if rhs_dim is None and lhs_dim == lhs_spec_batch_dim:\n+ lhs = reshape(lhs, tuple(onp.insert(lhs.shape, lhs_dim, 1)))\n+ out = conv_general_dilated(\n+ lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n+ dimension_numbers)\n+ return out, lhs_dim\n+ else:\n+ raise NotImplementedError(\n+ \"splitting a convolution along anything but input batch dimension\")\n+\n+\n+def _broadcast_in_dim_papply_rule(name, size, vals, dims, shape,\n+ broadcast_dimensions):\n+ operand, = vals\n+ dim, = dims\n+ out_dim = broadcast_dimensions[dim]\n+ if shape[out_dim] != shape[dim]:\n+ raise ValueError(\n+ \"broadcast_in_dim changes hidden dimension size: {} to {}\".format(\n+ shape[dim], shape[out_dim]))\n+ sub_bdims = tuple(onp.delete(broadcast_dimensions, dim))\n+ sub_shape = tuple(onp.delete(shape, out_dim))\n+ return broadcast_in_dim(operand, sub_shape, sub_bdims), out_dim\n+\n+\n+def _pad_papply_rule(name, size, vals, dims, padding_config):\n+ operand, padding_value = vals\n+ operand_dim, padding_value_dim = dims\n+ assert padding_value_dim is None\n+ padding_config = list(padding_config)\n+ if padding_config[operand_dim] == (0, 0, 0):\n+ padded = pad(\n+ operand,\n+ padding_value,\n+ padding_config[:operand_dim] + padding_config[operand_dim + 1:])\n+ return padded, operand_dim\n+ else:\n+ raise NotImplementedError(\n+ 'pad changes size of hidden dimension {} with config {}'.format(\n+ operand_dim, padding_config))\n+\n+\n+def _slice_papply_rule(name, size, vals, dims, start_indices, limit_indices,\n+ strides, **kwargs):\n+ operand, = vals\n+ dim, = dims\n+ start_indices = list(start_indices)\n+ limit_indices = list(limit_indices)\n+\n+ if (start_indices[dim] != 0 or\n+ limit_indices[dim] != size or\n+ strides is not None and strides[dim] != 1):\n+ raise NotImplementedError('slice changes side of hidden dimension')\n+\n+ out = slice(\n+ operand,\n+ start_indices[:dim] + start_indices[dim + 1:],\n+ limit_indices[:dim] + limit_indices[dim + 1:],\n+ strides[:dim] + strides[dim + 1:] if strides is not None else None)\n+ return out, dim\n+\n+\n+def _gather_papply_rule(\n+ name, size, vals, dims, dimension_numbers, slice_sizes, operand_shape):\n+ operand, start_indices = vals\n+ operand_dim, start_indices_dim = dims\n+ if (operand_dim is None and\n+ start_indices_dim is not None and\n+ start_indices_dim not in dimension_numbers.offset_dims and\n+ dimension_numbers.collapsed_slice_dims == (0,)):\n+ offset_dims = tuple(i - 1 if i > start_indices_dim else i\n+ for i in dimension_numbers.offset_dims)\n+ dnums = GatherDimensionNumbers(\n+ offset_dims=offset_dims,\n+ collapsed_slice_dims=dimension_numbers.collapsed_slice_dims,\n+ start_index_map=dimension_numbers.start_index_map)\n+ out = gather(operand, start_indices, dimension_numbers=dnums,\n+ slice_sizes=slice_sizes)\n+ out_dim = start_indices_dim + onp.sum(\n+ onp.less_equal(offset_dims, start_indices_dim))\n+ return out, out_dim\n+ else:\n+ raise NotImplementedError\n+\n+\nparallel.papply_primitive_rules[lax.dot_p] = _dot_papply_rule\nparallel.papply_primitive_rules[lax.dot_general_p] = _dot_general_papply_rule\nparallel.papply_primitive_rules[lax.reshape_p] = _reshape_papply_rule\nparallel.papply_primitive_rules[lax.transpose_p] = _transpose_papply_rule\nparallel.papply_primitive_rules[lax.select_p] = _select_papply_rule\n-parallel.papply_primitive_rules[ad_util.add_jaxvals_p] = (\n- _add_jaxvals_papply_rule)\n+parallel.papply_primitive_rules[ad_util.add_jaxvals_p] = \\\n+ _add_jaxvals_papply_rule\n+parallel.papply_primitive_rules[lax.convert_element_type_p] = \\\n+ _convert_element_type_papply_rule\n+parallel.papply_primitive_rules[lax.conv_general_dilated_p] = \\\n+ _conv_general_dilated_papply_rule\n+parallel.papply_primitive_rules[lax.broadcast_in_dim_p] = \\\n+ _broadcast_in_dim_papply_rule\n+parallel.papply_primitive_rules[lax.pad_p] = _pad_papply_rule\n+parallel.papply_primitive_rules[lax.slice_p] = _slice_papply_rule\n+parallel.papply_primitive_rules[lax.gather_p] = _gather_papply_rule\n"
}
] | Python | Apache License 2.0 | google/jax | fixes from rebase onto master |
260,335 | 25.06.2019 06:37:40 | 25,200 | ae550c102bf915992941989c4237dd9aae08f29c | roll back soft_pmap device persistence (bc broken) | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -515,40 +515,17 @@ class ShardedDeviceArray(xla.DeviceArray):\nrepresent distinct logical shards. The correspondence can be computed with\nthe assign_shards_to_replicas function.\n\"\"\"\n- __slots__ = [\"device_buffers\", \"_num_chunks\"]\n+ __slots__ = [\"device_buffers\"]\ndef __init__(self, aval, device_buffers):\nself.device_buffers = device_buffers\nself.shape, self.dtype = aval.shape, aval.dtype\nself.ndim, self.size = len(aval.shape), prod(aval.shape)\n- self._num_chunks = aval.shape[0]\nself._npy_value = None\n- def reshape(self, *newshape, **kwargs):\n- order = kwargs.pop(\"order\", \"C\")\n- if len(kwargs) == 1:\n- invalid_kwarg, = kwargs\n- msg = \"'{}' is an invalid keyword argument for this function\"\n- raise TypeError(msg.format(invalid_kwarg)) # same as NumPy error\n- elif kwargs:\n- invalid_kwargs = \"'{}'\".format(\"'\".join(kwargs))\n- msg = \"{} are invalid keyword arguments for this function\"\n- raise TypeError(msg.format(invalid_kwargs)) # different from NumPy error\n- if len(newshape) == 1 and not isinstance(newshape[0], int):\n- newshape = newshape[0]\n-\n- if order == \"C\":\n- newshape = onp.broadcast_to(0, self.shape).reshape(newshape).shape\n- new = ShardedDeviceArray(ShapedArray(newshape, self.dtype),\n- self.device_buffers)\n- new._num_chunks = self._num_chunks\n- return new\n- else:\n- return super(ShardedDeviceArray, self).reshape(newshape, order=order)\n-\ndef _ids(self):\nnum_bufs = len(self.device_buffers)\n- assignments = assign_shards_to_replicas(num_bufs, self._num_chunks)\n+ assignments = assign_shards_to_replicas(num_bufs, self.shape[0])\n_, ids = onp.unique(assignments, return_index=True)\nreturn ids\n@@ -563,16 +540,15 @@ class ShardedDeviceArray(xla.DeviceArray):\nids = self._ids()\nself.copy_to_host_async()\nself._npy_value = onp.stack([self.device_buffers[i].to_py() for i in ids])\n- return self._npy_value.reshape(self.shape)\n+ return self._npy_value\ndef __getitem__(self, idx):\n- if (self._npy_value is None and type(idx) is int\n- and self._num_chunks == self.shape[0]):\n+ if self._npy_value is None and type(idx) is int:\n# When we don't have a copy of the data on the host, and we're just trying\n# to extract a simple integer-indexed slice of the logical array, we can\n# avoid transferring from all the devices and just communicate with one.\nids = self._ids()\n- return self.device_buffers[ids[idx]].to_py().reshape(self.shape[1:])\n+ return self.device_buffers[ids[idx]].to_py()\nelse:\nreturn super(ShardedDeviceArray, self).__getitem__(idx)\n"
}
] | Python | Apache License 2.0 | google/jax | roll back soft_pmap device persistence (bc broken) |
260,299 | 26.06.2019 14:21:03 | -3,600 | 9ad18a8a54f05a46a110ea025947e2dbb9a2fad2 | Add failing custom_transforms closure test | [
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -614,6 +614,17 @@ class APITest(jtu.JaxTestCase):\nexpected = {'hi': 2 * onp.arange(3), 'bye': 2 * onp.ones((3, 2))}\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_custom_transforms_jvp_with_closure(self):\n+ def f(x):\n+ @api.custom_transforms\n+ def g(y):\n+ return x * y\n+ return g(x)\n+\n+ ans = api.grad(f)(1.)\n+ expected = 2.\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef test_custom_gradient(self):\n@api.custom_gradient\ndef f(x):\n"
}
] | Python | Apache License 2.0 | google/jax | Add failing custom_transforms closure test |
260,299 | 26.06.2019 16:22:21 | -3,600 | 3cdcd9ce930e7f6ead20125820a8fb9db7ce800b | Draft fix for custom_transform of closure | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -983,12 +983,20 @@ class CustomTransformsFunction(object):\nreturn '<jax.custom_transforms function {fun}>'.format(fun=self.__name__)\ndef __call__(self, *args, **kwargs):\n+ def pv_like(x):\n+ aval = x.aval if hasattr(x, 'aval') else xla.abstractify(x)\n+ return pe.PartialVal((aval, core.unit))\n+ wrapped = lu.wrap_init(self.fun, kwargs)\njax_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\njax_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\n- out_tree = lu.Store()\n- ans = self.prim.bind(jax_kwargs, *jax_args, kwargs_tree=kwargs_tree,\n- in_trees=in_trees, out_tree=out_tree)\n- return build_tree(out_tree.val, ans)\n+ jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun2(\n+ wrapped, kwargs_tree, in_trees)\n+ pvals_in = map(pv_like, (jax_kwargs,) + jax_args)\n+ jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals_in, instantiate=True)\n+ ans = self.prim.bind(\n+ core.pack(consts), jax_kwargs, *jax_args, kwargs_tree=kwargs_tree,\n+ in_trees=in_trees, out_tree=out_tree, jaxpr=jaxpr)\n+ return build_tree(out_tree(), ans)\ndef custom_transforms(fun):\n\"\"\"Wraps a function so that its transformation behavior can be controlled.\n@@ -1030,14 +1038,8 @@ def custom_transforms(fun):\nname = getattr(fun, '__name__', '<unnamed custom_transforms primitive>')\nfun_p = core.Primitive(name)\n- def fun_impl(jax_kwargs, *jax_args, **params):\n- args = map(build_tree, params.pop('in_trees'), jax_args)\n- kwargs = build_tree(params.pop('kwargs_tree'), jax_kwargs)\n- pytree_out = fun(*args, **kwargs)\n- out, out_tree = pytree_to_jaxtupletree(pytree_out)\n- params.pop('out_tree').store(out_tree) # linear_util style side effect\n- assert not params\n- return out\n+ def fun_impl(consts, jax_kwargs, *jax_args, **params):\n+ return core.eval_jaxpr(params['jaxpr'], consts, (), jax_kwargs, *jax_args)\nfun_p.def_impl(fun_impl)\ndef fun_jvp(primals, tangents, **params):\n@@ -1049,26 +1051,17 @@ def custom_transforms(fun):\nreturn out, 0\nbatching.primitive_batchers[fun_p] = fun_batch\n- staged_fun_p = core.Primitive('staged_' + name)\n- def fun_partial_eval(trace, *tracers, **params):\n- tracers = tuple(map(trace.instantiate_const, tracers))\n- avals = [t.aval for t in tracers]\n- pvals_in = [pe.PartialVal((a, core.unit)) for a in avals]\n- jaxpr, pval_out, consts = pe.trace_to_jaxpr(lu.wrap_init(fun_impl, params),\n- pvals_in, instantiate=True)\n- consts = trace.new_instantiated_const(core.pack(consts))\n- eqn = pe.JaxprEqn((consts,) + tracers, None, staged_fun_p, (), False, False,\n- dict(params, jaxpr=jaxpr))\n- return pe.JaxprTracer(trace, pval_out, eqn)\n- pe.custom_partial_eval_rules[fun_p] = fun_partial_eval\n-\n- def staged_fun_translation(c, xla_consts, *xla_args, **params):\n+ def fun_abstract_eval(*avals, **params):\n+ return pe.abstract_eval_fun(fun_impl, *avals, **params)\n+ fun_p.def_abstract_eval(fun_abstract_eval)\n+\n+ def fun_translation(c, xla_consts, *xla_args, **params):\nconsts_shapes = tuple(c.GetShape(xla_consts).tuple_shapes())\nxla_consts = tuple(xla.xla_destructure(c, xla_consts))\narg_shapes = map(c.GetShape, xla_args)\nbuilt_c = xla.jaxpr_computation(params['jaxpr'], (), consts_shapes, *arg_shapes)\nreturn c.Call(built_c, xla_consts + xla_args)\n- xla.translations[staged_fun_p] = staged_fun_translation\n+ xla.translations[fun_p] = fun_translation\nreturn CustomTransformsFunction(fun, fun_p)\n@@ -1131,8 +1124,8 @@ def defjvp_all(fun, custom_jvp):\n\"\"\"\n_check_custom_transforms_type(\"defjvp_all\", fun)\ndef custom_transforms_jvp(primals, tangents, **params):\n- jax_kwargs, jax_args = primals[0], primals[1:]\n- _, jax_args_dot = tangents[0], tangents[1:]\n+ consts, jax_kwargs, jax_args = primals[0], primals[1], primals[2:]\n+ _, _, jax_args_dot = tangents[0], tangents[1], tangents[2:]\nif jax_kwargs:\nmsg = (\"defjvp_all requires the corresponding custom_transforms function \"\n\"not to be called with keyword arguments.\")\n@@ -1147,7 +1140,6 @@ def defjvp_all(fun, custom_jvp):\nmsg = (\"custom jvp rule returned different tree structures for primals \"\n\"and tangents, but they must be equal: {} vs {}.\")\nraise TypeError(msg.format(out_tree, out_tree2))\n- params['out_tree'].store(out_tree) # linear_util style side effect\nreturn out, out_dot\nad.primitive_jvps[fun.prim] = custom_transforms_jvp\n@@ -1272,7 +1264,7 @@ def defvjp_all(fun, custom_vjp):\n(4.0, 3.0)\n\"\"\"\n_check_custom_transforms_type(\"defvjp_all\", fun)\n- def custom_transforms_vjp(jax_kwargs, *jax_args, **params):\n+ def custom_transforms_vjp(consts, jax_kwargs, *jax_args, **params):\nif jax_kwargs:\nmsg = (\"defvjp_all requires the corresponding custom_transforms function \"\n\"not to be called with keyword arguments.\")\n@@ -1280,7 +1272,6 @@ def defvjp_all(fun, custom_vjp):\nargs = map(build_tree, params['in_trees'], jax_args)\npytree_out, vjp_pytree = custom_vjp(*args)\nout, out_tree = pytree_to_jaxtupletree(pytree_out)\n- params['out_tree'].store(out_tree) # linear_util style side effect\ndef vjp_pytree_(ct):\nargs_cts = tuple(vjp_pytree(ct))\nif len(args_cts) != len(params['in_trees']):\n@@ -1288,7 +1279,7 @@ def defvjp_all(fun, custom_vjp):\n\"number of positional arguments to the function being \"\n\"differentiated: expected {}, got {}\")\nraise TypeError(msg.format(len(params['in_trees']), len(args_cts)))\n- return ({},) + args_cts\n+ return ((), {},) + args_cts\nvjp, _ = pytree_fun_to_jaxtupletree_fun(lu.wrap_init(vjp_pytree_), (out_tree,))\nreturn out, vjp.call_wrapped\nad.defvjp_all(fun.prim, custom_transforms_vjp)\n"
}
] | Python | Apache License 2.0 | google/jax | Draft fix for custom_transform of closure |
260,299 | 26.06.2019 16:49:04 | -3,600 | 3d1ba30f2e8b2d444fcbae83c7f5bf57456bd7cb | A few custom_transforms fix-ups | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -986,16 +986,14 @@ class CustomTransformsFunction(object):\ndef pv_like(x):\naval = x.aval if hasattr(x, 'aval') else xla.abstractify(x)\nreturn pe.PartialVal((aval, core.unit))\n- wrapped = lu.wrap_init(self.fun, kwargs)\njax_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\njax_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\njaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun2(\n- wrapped, kwargs_tree, in_trees)\n+ lu.wrap_init(self.fun), kwargs_tree, in_trees)\npvals_in = map(pv_like, (jax_kwargs,) + jax_args)\njaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals_in, instantiate=True)\n- ans = self.prim.bind(\n- core.pack(consts), jax_kwargs, *jax_args, kwargs_tree=kwargs_tree,\n- in_trees=in_trees, out_tree=out_tree, jaxpr=jaxpr)\n+ ans = self.prim.bind(core.pack(consts), jax_kwargs, *jax_args,\n+ in_trees=in_trees, jaxpr=jaxpr)\nreturn build_tree(out_tree(), ans)\ndef custom_transforms(fun):\n@@ -1055,12 +1053,8 @@ def custom_transforms(fun):\nreturn pe.abstract_eval_fun(fun_impl, *avals, **params)\nfun_p.def_abstract_eval(fun_abstract_eval)\n- def fun_translation(c, xla_consts, *xla_args, **params):\n- consts_shapes = tuple(c.GetShape(xla_consts).tuple_shapes())\n- xla_consts = tuple(xla.xla_destructure(c, xla_consts))\n- arg_shapes = map(c.GetShape, xla_args)\n- built_c = xla.jaxpr_computation(params['jaxpr'], (), consts_shapes, *arg_shapes)\n- return c.Call(built_c, xla_consts + xla_args)\n+ def fun_translation(c, *xla_args, **params):\n+ return xla.lower_fun(fun_impl, c, *xla_args, **params)\nxla.translations[fun_p] = fun_translation\nreturn CustomTransformsFunction(fun, fun_p)\n"
}
] | Python | Apache License 2.0 | google/jax | A few custom_transforms fix-ups |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.