author int64 658 755k | date stringlengths 19 19 | timezone int64 -46,800 43.2k | hash stringlengths 40 40 | message stringlengths 5 490 | mods list | language stringclasses 20 values | license stringclasses 3 values | repo stringlengths 5 68 | original_message stringlengths 12 491 |
|---|---|---|---|---|---|---|---|---|---|
260,299 | 27.06.2019 14:13:20 | -3,600 | 31fa0412ea1fd4d1c60319c6e48ba69d02673ad5 | Used shaped aval for custom_transforms jaxpr | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -984,8 +984,7 @@ class CustomTransformsFunction(object):\ndef __call__(self, *args, **kwargs):\ndef pv_like(x):\n- aval = x.aval if hasattr(x, 'aval') else xla.abstractify(x)\n- return pe.PartialVal((aval, core.unit))\n+ return pe.PartialVal((batching.get_aval(x), core.unit)) # Use shaped aval\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"
}
] | Python | Apache License 2.0 | google/jax | Used shaped aval for custom_transforms jaxpr |
260,299 | 27.06.2019 15:35:12 | -3,600 | 323d9f51dc0b7d67f8ee427882be8607c81aedc5 | Raise error when differentiating w.r.t. outer variable with defjvp_all | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1118,7 +1118,13 @@ def defjvp_all(fun, custom_jvp):\n_check_custom_transforms_type(\"defjvp_all\", fun)\ndef custom_transforms_jvp(primals, tangents, **params):\nconsts, jax_kwargs, jax_args = primals[0], primals[1], primals[2:]\n- _, _, jax_args_dot = tangents[0], tangents[1], tangents[2:]\n+ consts_dot, _, jax_args_dot = tangents[0], tangents[1], tangents[2:]\n+ if consts_dot is not ad_util.zero:\n+ msg = (\n+ \"Detected differentiation w.r.t. variables from outside the scope of \"\n+ \"{}, but defjvp and defjvp_all only support differentiation w.r.t. \"\n+ \"positional arguments.\")\n+ raise ValueError(msg.format(str(fun)))\nif jax_kwargs:\nmsg = (\"defjvp_all requires the corresponding custom_transforms function \"\n\"not to be called with keyword arguments.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -562,6 +562,20 @@ class APITest(jtu.JaxTestCase):\nself.assertAllClose(grad_ans, 3. * 4. + onp.cos(onp.sin(3. * 4)),\ncheck_dtypes=False)\n+ def test_defjvp_closure_error(self):\n+ def foo(x):\n+ @api.custom_transforms\n+ def bar(y):\n+ return x * y\n+\n+ api.defjvp(bar, lambda y_dot, ans, y: x * y)\n+ return bar(x)\n+ jtu.check_raises(\n+ lambda: api.jvp(foo, (1.,), (1.,)), ValueError,\n+ \"Detected differentiation w.r.t. variables from outside \"\n+ \"the scope of <jax.custom_transforms function bar>, but defjvp and \"\n+ \"defjvp_all only support differentiation w.r.t. positional arguments.\")\n+\ndef test_custom_transforms_eval_with_pytrees(self):\n@api.custom_transforms\ndef f(x):\n"
}
] | Python | Apache License 2.0 | google/jax | Raise error when differentiating w.r.t. outer variable with defjvp_all |
260,299 | 27.06.2019 17:35:34 | -3,600 | f76a1c963960edd11662b4cf70ae64410e3f26b4 | Add out of scope error to defvjp | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1263,7 +1263,13 @@ 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(consts, jax_kwargs, *jax_args, **params):\n+ def custom_transforms_vjp(argnums, consts, jax_kwargs, *jax_args, **params):\n+ if 0 in argnums:\n+ msg = (\n+ \"Detected differentiation w.r.t. variables from outside the scope of \"\n+ \"{}, but defvjp and defvjp_all only support differentiation w.r.t. \"\n+ \"positional arguments.\")\n+ raise ValueError(msg.format(str(fun)))\nif jax_kwargs:\nmsg = (\"defvjp_all requires the corresponding custom_transforms function \"\n\"not to be called with keyword arguments.\")\n@@ -1281,7 +1287,7 @@ def defvjp_all(fun, custom_vjp):\nreturn ((), {},) + args_cts\nvjp, _ = pytree_fun_to_jaxtupletree_fun(lu.wrap_init(vjp_pytree_), (out_tree,))\nreturn out, vjp.call_wrapped\n- ad.defvjp_all(fun.prim, custom_transforms_vjp)\n+ ad.defvjp_argnums(fun.prim, custom_transforms_vjp)\ndef defvjp(fun, *vjprules):\n\"\"\"Define VJP rules for each argument separately.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -396,11 +396,11 @@ def add_tangents(x, y):\nreturn add_jaxvals(x, y)\n-def defvjp_all(prim, custom_vjp):\n- # see https://github.com/google/jax/pull/636\n+def defvjp_argnums(prim, custom_vjp):\nname = prim.name\ndef fun_jvp(xs, ts, **params):\n+ params['vjp_argnums'] = tuple(i for i, t in enumerate(ts) if t is not zero)\nts = map(instantiate_zeros, xs, ts) # TODO(mattjj): avoid instantiation?\nprimal_out, tangent_out = fun_jvp_p.bind(pack(xs), pack(ts), **params)\nreturn primal_out, tangent_out\n@@ -409,7 +409,8 @@ def defvjp_all(prim, custom_vjp):\nfun_jvp_p = core.Primitive('{name}_jvp'.format(name=name))\ndef fun_jvp_partial_eval(trace, *tracers, **params):\nprimals_tracer, tangents_tracer = tracers\n- primal_out, vjp_py = custom_vjp(*primals_tracer, **params)\n+ argnums = params.pop('vjp_argnums')\n+ primal_out, vjp_py = custom_vjp(argnums, *primals_tracer, **params)\nin_aval = raise_to_shaped(get_aval(primal_out))\nct_pval = pe.PartialVal((in_aval, core.unit))\n@@ -431,6 +432,12 @@ def defvjp_all(prim, custom_vjp):\nreturn [None, None, out]\nprimitive_transposes[fun_lin_p] = fun_lin_transpose\n+def defvjp_all(prim, custom_vjp):\n+ # see https://github.com/google/jax/pull/636\n+ def custom_vjp_(argnums, *args, **params):\n+ return custom_vjp(*args, **params)\n+ defvjp_argnums(prim, custom_vjp_)\n+\ndef defvjp(prim, *vjps):\ndef vjpmaker(*primals):\nans = prim.bind(*primals)\n"
}
] | Python | Apache License 2.0 | google/jax | Add out of scope error to defvjp |
260,299 | 27.06.2019 17:39:42 | -3,600 | ec3fb89d1f7bf19dfc4069fd9601ac50693c6070 | Test for defvjp closure error | [
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -576,6 +576,20 @@ class APITest(jtu.JaxTestCase):\n\"the scope of <jax.custom_transforms function bar>, but defjvp and \"\n\"defjvp_all only support differentiation w.r.t. positional arguments.\")\n+ def test_defvjp_closure_error(self):\n+ def foo(x):\n+ @api.custom_transforms\n+ def bar(y):\n+ return x * y\n+\n+ api.defvjp(bar, lambda g, ans, y: x * y)\n+ return bar(x)\n+ jtu.check_raises(\n+ lambda: grad(foo)(1.,), ValueError,\n+ \"Detected differentiation w.r.t. variables from outside \"\n+ \"the scope of <jax.custom_transforms function bar>, but defvjp and \"\n+ \"defvjp_all only support differentiation w.r.t. positional arguments.\")\n+\ndef test_custom_transforms_eval_with_pytrees(self):\n@api.custom_transforms\ndef f(x):\n"
}
] | Python | Apache License 2.0 | google/jax | Test for defvjp closure error |
260,314 | 27.06.2019 17:28:36 | 14,400 | dc91d00afd48e25cd9c8f27e38e171fe715d635d | use split 2 instead of split 1 | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -545,12 +545,12 @@ def _gamma_one(key, alpha):\nsqueeze_const = _constant_like(alpha, 0.0331)\ndtype = lax.dtype(alpha)\n+ key, subkey = split(key)\n# for alpha < 1, we boost alpha to alpha + 1 and get a sample according to\n# Gamma(alpha) ~ Gamma(alpha+1) * Uniform()^(1 / alpha)\nboost = lax.select(lax.ge(alpha, one),\none,\n- lax.pow(uniform(key, (), dtype=dtype), lax.div(one, alpha)))\n- key, = split(key, 1)\n+ lax.pow(uniform(subkey, (), dtype=dtype), lax.div(one, alpha)))\nalpha = lax.select(lax.ge(alpha, one), alpha, lax.add(alpha, one))\nd = lax.sub(alpha, one_over_three)\n@@ -568,20 +568,19 @@ def _gamma_one(key, alpha):\nreturn cond\ndef _body_fn(kXVU):\n- key = kXVU[0]\n-\ndef _next_kxv(kxv):\n- x_key = kxv[0]\n- x = normal(x_key, (), dtype=dtype)\n+ key = kxv[0]\n+ key, subkey = split(key)\n+ x = normal(subkey, (), dtype=dtype)\nv = lax.add(one, lax.mul(x, c))\n- k, = split(x_key, 1)\n- return k, x, v\n+ return key, x, v\n- key, x, v = lax.while_loop(lambda kxv: lax.le(kxv[2], zero), _next_kxv, (key, zero, minus_one))\n+ key = kXVU[0]\n+ key, x_key, U_key = split(key, 3)\n+ _, x, v = lax.while_loop(lambda kxv: lax.le(kxv[2], zero), _next_kxv, (x_key, zero, minus_one))\nX = lax.mul(x, x)\nV = lax.mul(lax.mul(v, v), v)\n- U = uniform(key, (), dtype=dtype)\n- key, = split(key, 1)\n+ U = uniform(U_key, (), dtype=dtype)\nreturn key, X, V, U\n# initial state is chosen such that _cond_fn will return True\n@@ -602,7 +601,8 @@ def _gamma_grad_one(z, alpha):\n# Ref 1: Pathwise Derivatives Beyond the Reparameterization Trick, Martin & Fritz\n# Ref 2: Case 4 follows https://github.com/fritzo/notebooks/blob/master/gamma-reparameterized.ipynb\n- # TODO: use lax.cond instead of lax.while_loop when available\n+ # TODO: use lax.cond instead of lax.while_loop when its batching rule is available\n+ # See https://github.com/google/jax/issues/490\ndef _case1(zagf):\nz, alpha, _, flag = zagf\n"
}
] | Python | Apache License 2.0 | google/jax | use split 2 instead of split 1 |
260,489 | 01.07.2019 11:02:26 | -32,400 | b7cca2bbc96c96518e3f0553afb654c745d46fd6 | Add Laplace CDF. | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/laplace.py",
"new_path": "jax/scipy/stats/laplace.py",
"diff": "@@ -33,3 +33,16 @@ def logpdf(x, loc=0, scale=1):\n@_wraps(osp_stats.laplace.pdf)\ndef pdf(x, loc=0, scale=1):\nreturn lax.exp(logpdf(x, loc, scale))\n+\n+@_wraps(osp_stats.laplace.cdf)\n+def cdf(x, loc=0, scale=1):\n+ x, loc, scale = _promote_args_like(osp_stats.laplace.cdf, x, loc, scale)\n+ half = _constant_like(x, 0.5)\n+ one = _constant_like(x, 1)\n+ zero = _constant_like(x, 0)\n+ diff = lax.div(lax.sub(x, loc), scale)\n+ case1 = lax.mul(lax.mul(half, lax.exp(diff)),\n+ lax.convert_element_type(lax.lt(diff, zero), onp.float))\n+ case2 = lax.mul(lax.sub(one, lax.mul(half, lax.exp(lax.neg(diff)))),\n+ lax.convert_element_type(lax.ge(diff, zero), onp.float))\n+ return lax.add(case1, case2)\n"
}
] | Python | Apache License 2.0 | google/jax | Add Laplace CDF. |
260,489 | 02.07.2019 10:10:27 | -32,400 | 6dbd0abffd12f8a37f5dc24690cc1b3397636489 | Add tests for Laplace CDF. | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/laplace.py",
"new_path": "jax/scipy/stats/laplace.py",
"diff": "@@ -41,8 +41,6 @@ def cdf(x, loc=0, scale=1):\none = _constant_like(x, 1)\nzero = _constant_like(x, 0)\ndiff = lax.div(lax.sub(x, loc), scale)\n- case1 = lax.mul(lax.mul(half, lax.exp(diff)),\n- lax.convert_element_type(lax.lt(diff, zero), onp.float))\n- case2 = lax.mul(lax.sub(one, lax.mul(half, lax.exp(lax.neg(diff)))),\n- lax.convert_element_type(lax.ge(diff, zero), onp.float))\n- return lax.add(case1, case2)\n+ return lax.select(lax.le(diff, zero),\n+ lax.mul(half, lax.exp(diff)),\n+ lax.sub(one, lax.mul(half, lax.exp(lax.neg(diff)))))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -147,6 +147,20 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=True)\nself._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n+ @genNamedParametersNArgs(3, jtu.rand_default())\n+ def testLaplaceCdf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.laplace.cdf\n+ lax_fun = lsp_stats.laplace.cdf\n+\n+ def args_maker():\n+ x, loc, scale = map(rng, shapes, dtypes)\n+ # ensure that scale is not too low\n+ scale = onp.clip(scale, a_min=0.1, a_max=None)\n+ return [x, loc, scale]\n+\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n+\n# TODO: currently it ignores the argument \"shapes\" and only tests dim=4\n@genNamedParametersNArgs(3, jtu.rand_default())\n# TODO(phawkins): enable when there is an LU implementation for GPU/TPU.\n"
}
] | Python | Apache License 2.0 | google/jax | Add tests for Laplace CDF. |
260,299 | 02.07.2019 13:47:59 | -3,600 | 03d6d0a5bc4e4cccd9bd8e2ca101710cfb856089 | Add note to custom_transorms docstring | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1008,6 +1008,11 @@ def custom_transforms(fun):\nspecified manually. The default behavior is retained for any non-overridden\nrules.\n+ The function ``fun`` must satisfy the same constraints required for jit\n+ compilation. In particular the shapes of arrays in the computation of ``fun``\n+ may depend on the shapes of ``fun``'s arguments, but not their values.\n+ Value dependent Python control flow is also not yet supported.\n+\nArgs:\nfun: a Python callable. Must be functionally pure. Its arguments and return\nvalue should be arrays, scalars, or (nested) standard Python containers\n"
}
] | Python | Apache License 2.0 | google/jax | Add note to custom_transorms docstring |
260,335 | 02.07.2019 12:38:16 | 25,200 | 9790890b7d1e571d60675e65992b8e5cc45e8755 | reduce travis sampled test cases from 100 to 25
This change is just to speed up travis, which has ballooned from ~10
minutes to ~40 minutes. | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -7,8 +7,8 @@ python:\n- \"2.7\"\n- \"3.6\"\nenv:\n- - JAX_ENABLE_X64=0 JAX_NUM_GENERATED_CASES=100\n- - JAX_ENABLE_X64=1 JAX_NUM_GENERATED_CASES=100\n+ - JAX_ENABLE_X64=0 JAX_NUM_GENERATED_CASES=25\n+ - JAX_ENABLE_X64=1 JAX_NUM_GENERATED_CASES=25\nbefore_install:\n- if [[ \"$TRAVIS_PYTHON_VERSION\" == \"2.7\" ]]; then\nwget https://repo.continuum.io/miniconda/Miniconda2-latest-Linux-x86_64.sh -O miniconda.sh;\n"
}
] | Python | Apache License 2.0 | google/jax | reduce travis sampled test cases from 100 to 25
This change is just to speed up travis, which has ballooned from ~10
minutes to ~40 minutes. |
260,299 | 03.07.2019 08:00:00 | -3,600 | ffa43b895b75f4533d17b1b85a01a290c4fe4025 | Update signature fo lower_fun | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1122,7 +1122,7 @@ def custom_transforms(fun):\nfun_p.def_abstract_eval(fun_abstract_eval)\ndef fun_translation(c, *xla_args, **params):\n- return xla.lower_fun(fun_impl, 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 | Update signature fo lower_fun |
260,299 | 03.07.2019 08:13:34 | -3,600 | bf367d3a56ddb28b9ba0ebb068dd6cba75ecf6cf | Set instantiate=True in custom_transforms translation rule | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1122,7 +1122,7 @@ def custom_transforms(fun):\nfun_p.def_abstract_eval(fun_abstract_eval)\ndef fun_translation(c, *xla_args, **params):\n- return xla.lower_fun(fun_impl)(c, *xla_args, **params)\n+ return xla.lower_fun(fun_impl, True)(c, *xla_args, **params)\nxla.translations[fun_p] = fun_translation\nreturn CustomTransformsFunction(fun, fun_p)\n"
}
] | Python | Apache License 2.0 | google/jax | Set instantiate=True in custom_transforms translation rule |
260,285 | 03.07.2019 17:33:10 | -3,600 | 94889ae18fe296029211e6a11e36fb221beb4326 | Support scipy.stats.norm.ppf | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/norm.py",
"new_path": "jax/scipy/stats/norm.py",
"diff": "@@ -48,3 +48,8 @@ def cdf(x, loc=0, scale=1):\ndef logcdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.norm.logcdf, x, loc, scale)\nreturn special.log_ndtr(lax.div(lax.sub(x, loc), scale))\n+\n+\n+@_wraps(osp_stats.norm.ppf)\n+def ppf(q, loc=0, scale=1):\n+ return scale * special.ndtri(q) + loc\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -225,6 +225,23 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nself._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n+ @genNamedParametersNArgs(3, jtu.rand_default())\n+ def testNormPpf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.norm.ppf\n+ lax_fun = lsp_stats.norm.ppf\n+\n+ def args_maker():\n+ q, loc, scale = map(rng, shapes, dtypes)\n+ # ensure probability is between 0 and 1:\n+ q = onp.clip(onp.abs(q / 3), a_min=None, a_max=1)\n+ # clipping to ensure that scale is not too low\n+ scale = onp.clip(onp.abs(scale), a_min=0.1, a_max=None)\n+ return [q, loc, scale]\n+\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n+\n+\n@genNamedParametersNArgs(4, jtu.rand_positive())\ndef testParetoLogPdf(self, rng, shapes, dtypes):\nscipy_fun = osp_stats.pareto.logpdf\n"
}
] | Python | Apache License 2.0 | google/jax | Support scipy.stats.norm.ppf |
260,335 | 03.07.2019 21:15:52 | 25,200 | c2e7336b02cf183f4a2d9618dbb211a6dc234f36 | fix ShardedDeviceValue.block_until_ready()
cf. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -433,7 +433,18 @@ pe.custom_partial_eval_rules[axis_index_p] = _axis_index_partial_eval\n### lazy device-memory persistence and result handling\n-class ShardedDeviceTuple(xla.DeviceTuple):\n+class ShardedDeviceValue(xla.DeviceValue):\n+ def _check_if_deleted(self):\n+ if self.device_buffers is None:\n+ raise ValueError(\"ShardedDeviceValue has been deleted.\")\n+\n+ def block_until_ready(self):\n+ self._check_if_deleted()\n+ for buf in self.device_buffers:\n+ buf.block_host_until_ready()\n+\n+\n+class ShardedDeviceTuple(ShardedDeviceValue, xla.DeviceTuple):\n\"\"\"A ShardedDeviceTuple is a JaxTuple sharded across devices.\nThe purpose of a ShardedDeviceTuple is to reduce the number of transfers when\n@@ -495,7 +506,7 @@ xla.canonicalize_dtype_handlers[ShardedDeviceTuple] = \\\nxla.canonicalize_dtype_handlers[xla.DeviceTuple]\n-class ShardedDeviceArray(xla.DeviceArray):\n+class ShardedDeviceArray(ShardedDeviceValue, xla.DeviceArray):\n\"\"\"A ShardedDeviceArray is an ndarray sharded across devices.\nThe purpose of a ShardedDeviceArray is to reduce the number of transfers when\n@@ -534,6 +545,12 @@ class ShardedDeviceArray(xla.DeviceArray):\nfor buf in self.device_buffers:\nxla._copy_to_host_async(buf)\n+ def delete(self):\n+ for buf in self.device_buffers:\n+ buf.delete()\n+ self.device_buffers = None\n+ self._npy_value = None\n+\n@property\ndef _value(self):\nif self._npy_value is None:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -587,6 +587,11 @@ class PmapTest(jtu.JaxTestCase):\nexpected = onp.arange(n ** 2).reshape(n, n).T\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testShardedDeviceArrayBlockUntilReady(self):\n+ x = onp.arange(xla_bridge.device_count())\n+ x = pmap(lambda x: x)(x)\n+ x.block_until_ready() # doesn't crash\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix ShardedDeviceValue.block_until_ready()
cf. #973 |
260,547 | 04.07.2019 11:25:56 | -3,600 | 83fea8565f60ddf0ee842fdda15acb47b999b88c | Use zeros as initialization for avg_sq_grad in rmsprop
This seems more sensitive thing to do than ones. It is also consistent with Keras, PyTorch and Sonnet 2's implementation. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optimizers.py",
"new_path": "jax/experimental/optimizers.py",
"diff": "@@ -275,7 +275,7 @@ def rmsprop(step_size, gamma=0.9, eps=1e-8):\n\"\"\"\nstep_size = make_schedule(step_size)\ndef init(x0):\n- avg_sq_grad = np.ones_like(x0)\n+ avg_sq_grad = np.zeros_like(x0)\nreturn x0, avg_sq_grad\ndef update(i, g, state):\nx, avg_sq_grad = state\n"
}
] | Python | Apache License 2.0 | google/jax | Use zeros as initialization for avg_sq_grad in rmsprop
This seems more sensitive thing to do than ones. It is also consistent with Keras, PyTorch and Sonnet 2's implementation. |
260,547 | 04.07.2019 18:29:35 | -3,600 | d04954d31f4807655166f2053691d5e005e62ac5 | Convert int input to static_argnums to a tuple
User could make mistake of passing an int to static_argnums, this helps to avoid unnecessary error. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -110,6 +110,9 @@ def _jit(fun, static_argnums, device_values=True):\ndef f_jitted(*args, **kwargs):\nif _jit_is_disabled or config.read('jax_disable_jit'):\nreturn fun(*args, **kwargs)\n+ if isinstance(static_argnums, int):\n+ # static_argnums is a tuple of ints\n+ static_argnums = tuple([static_argnums])\nif static_argnums and max(static_argnums) >= len(args):\nmsg = (\"Jitted function has static_argnums={} but was called with only {}\"\n\" positional arguments.\")\n"
}
] | Python | Apache License 2.0 | google/jax | Convert int input to static_argnums to a tuple
User could make mistake of passing an int to static_argnums, this helps to avoid unnecessary error. |
260,335 | 05.07.2019 07:47:38 | 25,200 | 527fe14838eadc48fede68bd42ce4364e269fed3 | fix simple static_argnums bug | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -106,13 +106,13 @@ def jit(fun, static_argnums=()):\nreturn _jit(fun, static_argnums)\ndef _jit(fun, static_argnums, device_values=True):\n+ if isinstance(static_argnums, int):\n+ static_argnums = (static_argnums,)\n+\n@wraps(fun)\ndef f_jitted(*args, **kwargs):\nif _jit_is_disabled or config.read('jax_disable_jit'):\nreturn fun(*args, **kwargs)\n- if isinstance(static_argnums, int):\n- # static_argnums is a tuple of ints\n- static_argnums = (static_argnums,)\nif static_argnums and max(static_argnums) >= len(args):\nmsg = (\"Jitted function has static_argnums={} but was called with only {}\"\n\" positional arguments.\")\n"
}
] | Python | Apache License 2.0 | google/jax | fix simple static_argnums bug |
260,335 | 05.07.2019 14:32:04 | 25,200 | 93841df8221b76ffb95d02a88ddc6e7eb53e6013 | fix lax.imag jvp and enable test, fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1608,7 +1608,7 @@ real_p = unop(_complex_basetype, _complex, 'real')\nad.deflinear(real_p, lambda t: [complex(t, onp.zeros((), _dtype(t)))])\nimag_p = unop(_complex_basetype, _complex, 'imag')\n-ad.deflinear(imag_p, lambda t: [complex(onp.zeros((), _dtype(t)), t)])\n+ad.defjvp(imag_p, lambda g, _: real(mul(_const(g, -1j), g)))\n_complex_dtype = lambda dtype, *args: (onp.zeros((), dtype) + onp.zeros((), onp.complex64)).dtype\ncomplex_p = binop(_complex_dtype, [_complex_elem_types, _complex_elem_types],\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1523,8 +1523,8 @@ LAX_GRAD_OPS = [\ngrad_test_spec(lax.real, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.complex64]),\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.imag, nargs=1, order=2, rng=jtu.rand_default(),\n+ dtypes=[onp.complex64]),\n# grad_test_spec(lax.complex, nargs=2, order=2, rng=jtu.rand_default(),\n# dtypes=[onp.float32]), # TODO(mattjj): enable\ngrad_test_spec(lax.conj, nargs=1, order=2, rng=jtu.rand_default(),\n"
}
] | Python | Apache License 2.0 | google/jax | fix lax.imag jvp and enable test, fixes #979 |
260,335 | 05.07.2019 14:39:32 | 25,200 | db52d42597d0053c62383e5ee70f98a61b0e80f8 | also fix lax.complex jvp, enable test | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1613,7 +1613,7 @@ ad.defjvp(imag_p, lambda g, _: real(mul(_const(g, -1j), g)))\n_complex_dtype = lambda dtype, *args: (onp.zeros((), dtype) + onp.zeros((), onp.complex64)).dtype\ncomplex_p = binop(_complex_dtype, [_complex_elem_types, _complex_elem_types],\n'complex')\n-ad.deflinear(complex_p, lambda t: [real(t), imag(t)])\n+ad.deflinear(complex_p, lambda t: [real(t), imag(neg(t))])\nconj_p = unop(_complex_dtype, _float | _complex, 'conj')\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1525,8 +1525,8 @@ LAX_GRAD_OPS = [\ndtypes=[onp.complex64]),\ngrad_test_spec(lax.imag, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.complex64]),\n- # grad_test_spec(lax.complex, nargs=2, order=2, rng=jtu.rand_default(),\n- # dtypes=[onp.float32]), # TODO(mattjj): enable\n+ grad_test_spec(lax.complex, nargs=2, order=2, rng=jtu.rand_default(),\n+ dtypes=[onp.float32]),\ngrad_test_spec(lax.conj, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float32, onp.complex64]),\ngrad_test_spec(lax.abs, nargs=1, order=2, rng=jtu.rand_positive(),\n"
}
] | Python | Apache License 2.0 | google/jax | also fix lax.complex jvp, enable test |
260,335 | 05.07.2019 16:55:11 | 25,200 | 0f1d913db3406aceb00bcba107e88ce14ef861c1 | add xla_computation to jax rst docs | [
{
"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, defjvp_all, defvjp, 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, xla_computation\n:undoc-members:\n:show-inheritance:\n"
}
] | Python | Apache License 2.0 | google/jax | add xla_computation to jax rst docs |
260,335 | 06.07.2019 11:16:32 | 25,200 | ce2833367abfbf01a3b1896b717e09a7a9422117 | add jax.numpy.cov and tests (cf.
also add jax.numpy.array(..., ndmin=n) | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1358,34 +1358,36 @@ def atleast_3d(*arys):\n@_wraps(onp.array)\ndef array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\n- if ndmin != 0 or (order is not None and order != \"K\"):\n- raise NotImplementedError(\"Only implemented for order='K', ndmin=0.\")\n+ if order is not None and order != \"K\":\n+ raise NotImplementedError(\"Only implemented for order='K'\")\nif isinstance(object, ndarray):\n- if dtype and _dtype(object) != dtype:\n- return lax.convert_element_type(object, dtype)\n+ if dtype and _dtype(object) != xla_bridge.canonicalize_dtype(dtype):\n+ out = lax.convert_element_type(object, dtype)\nelif copy:\n# If a copy was requested, we must copy.\n- return device_put(object)\n+ out = device_put(object)\nelse:\n- return object\n+ out = object\nelif hasattr(object, '__array__'):\n# this case is for duck-typed handling of objects that implement `__array__`\n- return array(object.__array__(), dtype)\n+ out = array(object.__array__(), dtype and xla_bridge.canonicalize_dtype(dtype))\nelif isinstance(object, (list, tuple)):\nif object:\n- return stack([array(elt, dtype=dtype) for elt in object])\n+ out = stack([array(elt, dtype=dtype) for elt in object])\nelse:\n- return onp.array([], dtype)\n+ out = onp.array([], dtype)\nelif isscalar(object):\nout = lax.reshape(object, ())\n- if dtype and _dtype(out) != dtype:\n- return lax.convert_element_type(out, dtype)\n- else:\n- return out\n+ if dtype and _dtype(out) != xla_bridge.canonicalize_dtype(dtype):\n+ out = lax.convert_element_type(out, dtype)\nelse:\nraise TypeError(\"Unexpected input type for array: {}\".format(type(object)))\n+ if ndmin > ndim(out):\n+ out = lax.reshape(out, (1,) * (ndmin - ndim(out)) + shape(out))\n+ return out\n+\n@_wraps(onp.asarray)\ndef asarray(a, dtype=None, order=None):\nreturn array(a, dtype=dtype, copy=False, order=order)\n@@ -2389,6 +2391,56 @@ def lcm(x1, x2):\nreturn where(d == 0, lax._const(d, 0),\nlax.div(lax.abs(multiply(x1, x2)), d))\n+@_wraps(onp.cov)\n+def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,\n+ aweights=None):\n+ msg = (\"jax.numpy.cov not implemented for nontrivial {}. \"\n+ \"Open a feature request at https://github.com/google/jax/issues !\")\n+ if y is not None: raise NotImplementedError(msg.format('y'))\n+ # These next two are actually implemented, just not tested.\n+ if fweights is not None: raise NotImplementedError(msg.format('fweights'))\n+ if aweights is not None: raise NotImplementedError(msg.format('aweights'))\n+\n+ if m.ndim > 2:\n+ raise ValueError(\"m has more than 2 dimensions\") # same as numpy error\n+ X = array(m, ndmin=2, dtype=result_type(m, onp.float64), copy=False)\n+ if not rowvar and X.shape[0] != 1:\n+ X = X.T\n+ if X.shape[0] == 0:\n+ return onp.array([]).reshape(0, 0)\n+ if ddof is None:\n+ ddof = 1 if bias == 0 else 0\n+\n+ w = None\n+ if fweights is not None:\n+ if onp.ndim(fweights) > 1:\n+ raise RuntimeError(\"cannot handle multidimensional fweights\")\n+ if onp.shape(fweights)[0] != X.shape[1]:\n+ raise RuntimeError(\"incompatible numbers of samples and fweights\")\n+ w = asarray(fweights)\n+ if aweights is not None:\n+ if onp.ndim(aweights) > 1:\n+ raise RuntimeError(\"cannot handle multidimensional aweights\")\n+ if onp.shape(aweights)[0] != X.shape[1]:\n+ raise RuntimeError(\"incompatible numbers of samples and aweights\")\n+ w = aweights if w is None else w * aweights\n+\n+ avg, w_sum = average(X, axis=1, weights=w, returned=True)\n+ w_sum = w_sum[0]\n+\n+ if w is None:\n+ f = X.shape[1] - ddof\n+ elif ddof == 0:\n+ f = w_sum\n+ elif aweights is None:\n+ f = w_sum - ddof\n+ else:\n+ f = w_sum - ddof * sum(w * aweights) / w_sum\n+\n+ X = X - avg[:, None]\n+ X_T = X.T if w is None else (X * w).T\n+ return true_divide(dot(X, X_T.conj()), f).squeeze()\n+\n### track unimplemented functions\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1084,16 +1084,24 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_arg{}\".format(i), \"arg\": arg}\n+ {\"testcase_name\": \"_arg{}_ndmin={}\".format(i, ndmin),\n+ \"arg\": arg, \"ndmin\": ndmin}\nfor i, arg in enumerate([\n3., [1, 2, 3], [1., 2., 3.],\n[[1, 2], [3, 4], [5, 6]], [[1, 2.], [3, 4], [5, 6]],\n[[3, onp.array(2), 1], onp.arange(3.)],\n- ])))\n- def testArray(self, arg):\n+ ])\n+ for ndmin in [None, onp.ndim(arg), onp.ndim(arg) + 1, onp.ndim(arg) + 2]))\n+ def testArray(self, arg, ndmin):\nargs_maker = lambda: [arg]\n- self._CheckAgainstNumpy(onp.array, lnp.array, args_maker, check_dtypes=True)\n- self._CompileAndCheck(lnp.array, args_maker, check_dtypes=True)\n+ if ndmin is not None:\n+ onp_fun = partial(onp.array, ndmin=ndmin)\n+ lnp_fun = partial(lnp.array, ndmin=ndmin)\n+ else:\n+ onp_fun = onp.array\n+ lnp_fun = lnp.array\n+ self._CheckAgainstNumpy(onp_fun, lnp_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\ndef testIssue121(self):\nassert not onp.isscalar(lnp.array(3))\n@@ -1682,6 +1690,25 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ndef testIssue956(self):\nself.assertRaises(TypeError, lambda: lnp.ndarray((1, 1)))\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_dtype={}_rowvar={}_ddof={}_bias={}\".format(\n+ shape, dtype, rowvar, ddof, bias),\n+ \"shape\":shape, \"dtype\":dtype, \"rowvar\":rowvar, \"ddof\":ddof,\n+ \"bias\":bias, \"rng\": rng}\n+ for shape in [(5,), (10, 5), (3, 10)]\n+ for dtype in all_dtypes\n+ for rowvar in [True, False]\n+ for bias in [True, False]\n+ for ddof in [None, 2, 3]\n+ for rng in [jtu.rand_default()]))\n+ def testCov(self, shape, dtype, rowvar, ddof, bias, rng):\n+ args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n+ onp_fun = partial(onp.cov, rowvar=rowvar, ddof=ddof, bias=bias)\n+ lnp_fun = partial(lnp.cov, rowvar=rowvar, ddof=ddof, bias=bias)\n+ self._CheckAgainstNumpy(onp_fun, lnp_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add jax.numpy.cov and tests (cf. #70)
also add jax.numpy.array(..., ndmin=n) |
260,335 | 17.06.2019 20:44:33 | 25,200 | ccb1760f499bbac0801fbef67f6bdede65509ddb | add a lot of systematic vmap tests | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -822,19 +822,20 @@ def _reduction_jaxpr(computation, init_value):\ndef _get_monoid_reducer(monoid_op, x):\naval = core.get_aval(x)\n+ dtype = _dtype(x)\nif (type(aval) is ConcreteArray) and aval.shape == ():\nif monoid_op is add:\nreturn aval.val == 0 and _reduce_sum\nif monoid_op is mul:\nreturn aval.val == 1 and _reduce_prod\n+ elif monoid_op is bitwise_or and dtype == onp.bool_:\n+ return aval.val == _get_max_identity(dtype) and _reduce_or\n+ elif monoid_op is bitwise_and and dtype == onp.bool_:\n+ return aval.val == _get_min_identity(dtype) and _reduce_and\nelif monoid_op is max:\n- return aval.val == _get_max_identity(aval.dtype) and _reduce_max\n+ return aval.val == _get_max_identity(dtype) and _reduce_max\nelif monoid_op is min:\n- return aval.val == _get_min_identity(aval.dtype) and _reduce_min\n- elif monoid_op is bitwise_or and aval.dtype == onp.bool_:\n- return aval.val == _get_max_identity(aval.dtype) and _reduce_or\n- elif monoid_op is bitwise_and and aval.dtype == onp.bool_:\n- return aval.val == _get_min_identity(aval.dtype) and _reduce_and\n+ return aval.val == _get_min_identity(dtype) and _reduce_min\ndef _get_max_identity(dtype):\nif onp.issubdtype(dtype, onp.inexact):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -622,13 +622,11 @@ class LaxTest(jtu.JaxTestCase):\n\"lhs_contracting\": lhs_contracting, \"rhs_contracting\": rhs_contracting,\n\"rng\": rng}\nfor lhs_shape, rhs_shape, lhs_contracting, rhs_contracting in [\n- # these all fail with \"RuntimeError: Unimplemented: Dot with\n- # non-standard contracting dimensions not implemented.\"\n- # [(3, 5), (2, 5), [1], [1]],\n- # [(5, 3), (5, 2), [0], [0]],\n- # [(5, 3, 2), (5, 2, 4), [0], [0]],\n- # [(5, 3, 2), (5, 2, 4), [0,2], [0,1]],\n- # [(1, 2, 2, 3), (1, 2, 3, 1), [1], [1]],\n+ [(3, 5), (2, 5), [1], [1]],\n+ [(5, 3), (5, 2), [0], [0]],\n+ [(5, 3, 2), (5, 2, 4), [0], [0]],\n+ [(5, 3, 2), (5, 2, 4), [0,2], [0,1]],\n+ [(1, 2, 2, 3), (1, 2, 3, 1), [1], [1]],\n[(3, 2), (2, 4), [1], [0]],\n]\nfor dtype in default_dtypes\n@@ -2241,14 +2239,52 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\n+def all_bdims(*shapes):\n+ bdims = (itertools.chain([None], range(len(shape) + 1)) for shape in shapes)\n+ return (t for t in itertools.product(*bdims) if not all(e is None for e in t))\n+\n+def add_bdim(bdim_size, bdim, shape):\n+ shape = list(shape)\n+ if bdim is not None:\n+ shape.insert(bdim, bdim_size)\n+ return tuple(shape)\n+\ndef slicer(x, bdim):\nif bdim is None:\nreturn lambda _: x\nelse:\nreturn lambda i: lax.index_in_dim(x, i, bdim, keepdims=False)\n+def args_slicer(args, bdims):\n+ slicers = list(map(slicer, args, bdims))\n+ return lambda i: [sl(i) for sl in slicers]\n+\nclass LaxVmapTest(jtu.JaxTestCase):\n+ def _CheckBatching(self, op, bdim_size, bdims, shapes, dtype, rng,\n+ rtol=None, atol=None):\n+ batched_shapes = map(partial(add_bdim, bdim_size), bdims, shapes)\n+ args = [rng(shape, dtype) for shape in batched_shapes]\n+ args_slice = args_slicer(args, bdims)\n+ ans = api.vmap(op, bdims)(*args)\n+ expected = onp.stack([op(*args_slice(i)) for i in range(bdim_size)])\n+ self.assertAllClose(ans, expected, check_dtypes=True, rtol=rtol, atol=atol)\n+\n+ @parameterized.named_parameters(itertools.chain.from_iterable(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": \"{}_bdims={}\".format(\n+ jtu.format_test_name_suffix(rec.op.__name__, shapes,\n+ itertools.repeat(dtype)), bdims),\n+ \"op\": rec.op, \"rng\": rec.rng, \"shapes\": shapes, \"dtype\": dtype,\n+ \"bdims\": bdims}\n+ for shape_group in compatible_shapes\n+ for shapes in CombosWithReplacement(shape_group, rec.nargs)\n+ for bdims in all_bdims(*shapes)\n+ for dtype in rec.dtypes)\n+ for rec in LAX_OPS))\n+ def testOp(self, op, rng, shapes, dtype, bdims):\n+ self._CheckBatching(op, 10, bdims, shapes, dtype, rng)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\":\n\"_lhs_shape={}_rhs_shape={}_strides={}_padding={}_lhs_dilation={}_\"\n@@ -2293,7 +2329,6 @@ class LaxVmapTest(jtu.JaxTestCase):\nself, lhs_shape, rhs_shape, dtype, strides, padding, lhs_dil, rhs_dil,\ndimension_numbers, perms, feature_group_count, lhs_bdim, rhs_bdim, rng):\ntol = 1e-1 if onp.finfo(dtype).bits == 32 else 1e-3\n- bdim_size = 10\n# permute shapes to match dim_spec, scale by feature_group_count\nlhs_perm, rhs_perm = perms\n@@ -2303,26 +2338,322 @@ class LaxVmapTest(jtu.JaxTestCase):\nlhs_shape[dim_spec.lhs_spec[1]] *= feature_group_count\nrhs_shape[dim_spec.rhs_spec[0]] *= feature_group_count\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-\nconv = partial(lax.conv_general_dilated, window_strides=strides,\npadding=padding, lhs_dilation=lhs_dil, rhs_dilation=rhs_dil,\ndimension_numbers=dimension_numbers,\nfeature_group_count=feature_group_count,\nprecision=lax.Precision.HIGHEST)\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, True, tol, tol)\n+ self._CheckBatching(conv, 5, (lhs_bdim, rhs_bdim), (lhs_shape, rhs_shape),\n+ dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_from_dtype={}_to_dtype={}_bdims={}\".format(\n+ shape, from_dtype, to_dtype, bdims),\n+ \"shape\": shape, \"from_dtype\": from_dtype, \"to_dtype\": to_dtype,\n+ \"bdims\": bdims, \"rng\": rng}\n+ for from_dtype, to_dtype in itertools.product(\n+ [onp.float32, onp.int32, \"float32\", \"int32\"], repeat=2)\n+ for shape in [(2, 3)]\n+ for bdims in all_bdims(shape)\n+ for rng in [jtu.rand_default()]))\n+ def testConvertElementType(self, shape, from_dtype, to_dtype, bdims, rng):\n+ op = lambda x: lax.convert_element_type(x, to_dtype)\n+ self._CheckBatching(op, 10, bdims, (shape,), from_dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_from_dtype={}_to_dtype={}_bdims={}\".format(\n+ shape, from_dtype, to_dtype, bdims),\n+ \"shape\": shape, \"from_dtype\": from_dtype, \"to_dtype\": to_dtype,\n+ \"bdims\": bdims, \"rng\": rng}\n+ for from_dtype, to_dtype in itertools.product(\n+ [onp.float32, onp.int32, \"float32\", \"int32\"], repeat=2)\n+ for shape in [(2, 3)]\n+ for bdims in all_bdims(shape)\n+ for rng in [jtu.rand_default()]))\n+ def testBitcastElementType(self, shape, from_dtype, to_dtype, bdims, rng):\n+ op = lambda x: lax.bitcast_convert_type(x, to_dtype)\n+ self._CheckBatching(op, 10, bdims, (shape,), from_dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_min_shape={}_operand_shape={}_max_shape={}_bdims={}\"\n+ .format(jtu.format_shape_dtype_string(min_shape, dtype),\n+ jtu.format_shape_dtype_string(operand_shape, dtype),\n+ jtu.format_shape_dtype_string(max_shape, dtype),\n+ bdims),\n+ \"min_shape\": min_shape, \"operand_shape\": operand_shape,\n+ \"max_shape\": max_shape, \"dtype\": dtype, \"bdims\": bdims, \"rng\": rng}\n+ for min_shape, operand_shape, max_shape in [\n+ [(), (2, 3), ()],\n+ [(2, 3), (2, 3), ()],\n+ [(), (2, 3), (2, 3)],\n+ [(2, 3), (2, 3), (2, 3)],\n+ ]\n+ for dtype in default_dtypes\n+ for bdims in all_bdims(min_shape, operand_shape, max_shape)\n+ for rng in [jtu.rand_default()]))\n+ def testClamp(self, min_shape, operand_shape, max_shape, dtype, bdims, rng):\n+ raise SkipTest(\"batching rule for clamp not implemented\") # TODO(mattj)\n+ shapes = [min_shape, operand_shape, max_shape]\n+ self._CheckBatching(lax.clamp, 10, bdims, shapes, dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_lhs_shape={}_rhs_shape={}_bdims={}\".format(\n+ jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype),\n+ bdims),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"bdims\": bdims, \"rng\": rng}\n+ for lhs_shape in [(3,), (4, 3)] for rhs_shape in [(3,), (3, 6)]\n+ for bdims in all_bdims(lhs_shape, rhs_shape)\n+ for dtype in default_dtypes\n+ for rng in [jtu.rand_default()]))\n+ def testDot(self, lhs_shape, rhs_shape, dtype, bdims, rng):\n+ self._CheckBatching(lax.dot, 5, bdims, (lhs_shape, rhs_shape), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_rhs_shape={}_lhs_contracting={}_rhs_contracting={}_bdims={}\"\n+ .format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype),\n+ lhs_contracting, rhs_contracting, bdims),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"lhs_contracting\": lhs_contracting, \"rhs_contracting\": rhs_contracting,\n+ \"bdims\": bdims, \"rng\": rng}\n+ for lhs_shape, rhs_shape, lhs_contracting, rhs_contracting in [\n+ [(3, 5), (2, 5), [1], [1]],\n+ [(5, 3), (5, 2), [0], [0]],\n+ [(5, 3, 2), (5, 2, 4), [0], [0]],\n+ [(5, 3, 2), (5, 2, 4), [0,2], [0,1]],\n+ [(1, 2, 2, 3), (1, 2, 3, 1), [1], [1]],\n+ [(3, 2), (2, 4), [1], [0]],\n+ ]\n+ for bdims in all_bdims(lhs_shape, rhs_shape)\n+ for dtype in default_dtypes\n+ for rng in [jtu.rand_small()]))\n+ def testDotGeneralContractOnly(self, lhs_shape, rhs_shape, dtype,\n+ lhs_contracting, rhs_contracting, bdims, rng):\n+ dimension_numbers = ((lhs_contracting, rhs_contracting), ([], []))\n+ dot = partial(lax.dot_general, dimension_numbers=dimension_numbers)\n+ self._CheckBatching(dot, 5, bdims, (lhs_shape, rhs_shape), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_rhs_shape={}_dimension_numbers={}_bdims={}\"\n+ .format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype),\n+ dimension_numbers, bdims),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"dimension_numbers\": dimension_numbers, \"bdims\": bdims, \"rng\": rng}\n+ for lhs_shape, rhs_shape, dimension_numbers in [\n+ ((3, 3, 2), (3, 2, 4), (([2], [1]), ([0], [0]))),\n+ ((3, 4, 2, 4), (3, 4, 3, 2), (([2], [3]), ([0, 1], [0, 1]))),\n+ ]\n+ for bdims in all_bdims(lhs_shape, rhs_shape)\n+ for dtype in default_dtypes\n+ for rng in [jtu.rand_small()]))\n+ def testDotGeneralContractAndBatch(self, lhs_shape, rhs_shape, dtype,\n+ dimension_numbers, bdims, rng):\n+ dot = partial(lax.dot_general, dimension_numbers=dimension_numbers)\n+ self._CheckBatching(dot, 5, bdims, (lhs_shape, rhs_shape), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_dtype={}_broadcast_sizes={}_bdims={}\".format(\n+ shape, onp.dtype(dtype).name, broadcast_sizes, bdims),\n+ \"shape\": shape, \"dtype\": dtype, \"broadcast_sizes\": broadcast_sizes,\n+ \"bdims\": bdims, \"rng\": rng}\n+ for shape in [(), (2, 3)]\n+ for dtype in default_dtypes\n+ for broadcast_sizes in [(), (2,), (1, 2)]\n+ for bdims in all_bdims(shape)\n+ for rng in [jtu.rand_default()]))\n+ def testBroadcast(self, shape, dtype, broadcast_sizes, bdims, rng):\n+ op = lambda x: lax.broadcast(x, broadcast_sizes)\n+ self._CheckBatching(op, 5, bdims, (shape,), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_inshape={}_outshape={}_bcdims={}_bdims={}\".format(\n+ jtu.format_shape_dtype_string(inshape, dtype),\n+ outshape, broadcast_dimensions, bdims),\n+ \"inshape\": inshape, \"dtype\": dtype, \"outshape\": outshape,\n+ \"dimensions\": broadcast_dimensions, \"bdims\": bdims, \"rng\": rng}\n+ for inshape, outshape, broadcast_dimensions in [\n+ ([2], [2, 2], [0]),\n+ ([2], [2, 2], [1]),\n+ ([2], [2, 3], [0]),\n+ ([], [2, 3], []),\n+ ]\n+ for dtype in default_dtypes\n+ for bdims in all_bdims(inshape)\n+ for rng in [jtu.rand_default()]))\n+ def testBroadcastInDim(self, inshape, dtype, outshape, dimensions, bdims, rng):\n+ raise SkipTest(\"this test has failures in some cases\") # TODO(mattjj)\n+ op = lambda x: lax.broadcast_in_dim(x, outshape, dimensions)\n+ self._CheckBatching(op, 5, bdims, (inshape,), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_inshape={}_outshape={}_bdims={}\".format(\n+ jtu.format_shape_dtype_string(arg_shape, dtype),\n+ jtu.format_shape_dtype_string(out_shape, dtype),\n+ bdims),\n+ \"arg_shape\": arg_shape, \"out_shape\": out_shape, \"dtype\": dtype,\n+ \"bdims\": bdims, \"rng\": rng}\n+ for dtype in default_dtypes\n+ for arg_shape, out_shape in [\n+ [(3, 4), (12,)], [(2, 1, 4), (8,)], [(2, 2, 4), (2, 8)]\n+ ]\n+ for bdims in all_bdims(arg_shape)\n+ for rng in [jtu.rand_default()]))\n+ def testReshape(self, arg_shape, out_shape, dtype, bdims, rng):\n+ op = lambda x: lax.reshape(x, out_shape)\n+ self._CheckBatching(op, 10, bdims, (arg_shape,), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_inshape={}_pads={}_bdims={}\"\n+ .format(jtu.format_shape_dtype_string(shape, dtype), pads, bdims),\n+ \"shape\": shape, \"dtype\": dtype, \"pads\": pads, \"rng\": jtu.rand_small(),\n+ \"bdims\": bdims}\n+ for shape in [(2, 3)]\n+ for bdims in all_bdims(shape)\n+ for dtype in default_dtypes\n+ for pads in [[(1, 2, 1), (0, 1, 0)]]))\n+ def testPad(self, shape, dtype, pads, bdims, rng):\n+ fun = lambda operand: lax.pad(operand, onp.array(0, dtype), pads)\n+ self._CheckBatching(fun, 5, bdims, (shape,), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_predshape={}_argshapes={}_bdims={}\".format(\n+ jtu.format_shape_dtype_string(pred_shape, onp.bool_),\n+ jtu.format_shape_dtype_string(arg_shape, arg_dtype),\n+ bdims),\n+ \"pred_shape\": pred_shape, \"arg_shape\": arg_shape, \"arg_dtype\": arg_dtype,\n+ \"bdims\": bdims, \"rng\": rng}\n+ for arg_shape in [(), (3,), (2, 3)]\n+ for pred_shape in ([(), arg_shape] if arg_shape else [()])\n+ for bdims in all_bdims(pred_shape, arg_shape, arg_shape)\n+ for arg_dtype in default_dtypes\n+ for rng in [jtu.rand_default()]))\n+ def testSelect(self, pred_shape, arg_shape, arg_dtype, bdims, rng):\n+ raise SkipTest(\"this test has failures in some cases\") # TODO(mattjj)\n+ op = lambda c, x, y: lax.select(c < 0, x, y)\n+ self._CheckBatching(op, 5, bdims, (pred_shape, arg_shape, arg_shape,),\n+ arg_dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_shape={}_start_indices={}_limit_indices={}_strides={}_bdims={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype),\n+ start_indices, limit_indices, strides, bdims),\n+ \"shape\": shape, \"dtype\": dtype, \"starts\": start_indices,\n+ \"limits\": limit_indices, \"strides\": strides, \"bdims\": bdims, \"rng\": rng}\n+ for shape, start_indices, limit_indices, strides in [\n+ [(3,), (1,), (2,), None],\n+ [(7,), (4,), (7,), None],\n+ [(5,), (1,), (5,), (2,)],\n+ [(8,), (1,), (6,), (2,)],\n+ [(5, 3), (1, 1), (3, 2), None],\n+ [(5, 3), (1, 1), (3, 1), None],\n+ [(7, 5, 3), (4, 0, 1), (7, 1, 3), None],\n+ [(5, 3), (1, 1), (2, 1), (1, 1)],\n+ [(5, 3), (1, 1), (5, 3), (2, 1)],\n+ ]\n+ for bdims in all_bdims(shape)\n+ for dtype in default_dtypes\n+ for rng in [jtu.rand_default()]))\n+ def testSlice(self, shape, dtype, starts, limits, strides, bdims, rng):\n+ op = lambda x: lax.slice(x, starts, limits, strides)\n+ self._CheckBatching(op, 5, bdims, (shape,), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_perm={}_bdims={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), perm, bdims),\n+ \"shape\": shape, \"dtype\": dtype, \"perm\": perm, \"bdims\": bdims, \"rng\": rng}\n+ for shape, perm in [\n+ [(3, 4), (1, 0)],\n+ [(3, 4), (0, 1)],\n+ [(3, 4, 5), (2, 1, 0)],\n+ [(3, 4, 5), (1, 0, 2)],\n+ ]\n+ for bdims in all_bdims(shape)\n+ for dtype in default_dtypes\n+ for rng in [jtu.rand_default()]))\n+ def testTranspose(self, shape, dtype, perm, bdims, rng):\n+ op = lambda x: lax.transpose(x, perm)\n+ self._CheckBatching(op, 5, bdims, (shape,), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_op={}_inshape={}_reducedims={}_bdims={}\"\n+ .format(op.__name__, jtu.format_shape_dtype_string(shape, dtype), dims,\n+ bdims),\n+ \"op\": op, \"init_val\": init_val, \"shape\": shape, \"dtype\": dtype,\n+ \"dims\": dims, \"bdims\": bdims, \"rng\": rng}\n+ for 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+ (onp.iinfo(onp.uint32).min, lax.max, [onp.uint32]),\n+ (onp.iinfo(onp.uint64).min, lax.max, [onp.uint64]),\n+ (onp.inf, lax.min, float_dtypes),\n+ (onp.iinfo(onp.int32).max, lax.min, [onp.int32]),\n+ (onp.iinfo(onp.int64).max, lax.min, [onp.int64]),\n+ (onp.iinfo(onp.uint32).max, lax.min, [onp.uint32]),\n+ (onp.iinfo(onp.uint64).max, lax.min, [onp.uint64]),\n+ ]\n+ for dtype in dtypes\n+ for shape, dims in [\n+ [(3, 4, 5), (0,)], [(3, 4, 5), (1, 2)],\n+ [(3, 4, 5), (0, 2)], [(3, 4, 5), (0, 1, 2)]\n+ ]\n+ for bdims in all_bdims(shape)\n+ for rng in [jtu.rand_small()]))\n+ def testReduce(self, op, init_val, shape, dtype, dims, bdims, rng):\n+ init_val = onp.asarray(init_val, dtype=dtype)\n+ fun = lambda operand: lax.reduce(operand, init_val, op, dims)\n+ self._CheckBatching(fun, 5, bdims, (shape,), dtype, rng)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_op={}_dtype={}_padding={}\"\n+ .format(op.__name__, onp.dtype(dtype).name, padding),\n+ \"op\": op, \"init_val\": init_val, \"dtype\": dtype, \"padding\": padding,\n+ \"rng\": rng}\n+ for init_val, op, dtypes in [\n+ (0, lax.add, [onp.float32]),\n+ (-onp.inf, lax.max, [onp.float32]),\n+ (onp.inf, lax.min, [onp.float32]),\n+ ]\n+ for dtype in dtypes\n+ for padding in [\"VALID\", \"SAME\"]\n+ for rng in [jtu.rand_small()]))\n+ def testReduceWindow(self, op, init_val, dtype, padding, rng):\n+ raise SkipTest(\"this test has failures in some cases\") # TODO(mattjj)\n+ init_val = onp.asarray(init_val, dtype=dtype)\n+\n+ all_configs = itertools.chain(\n+ itertools.product(\n+ [(4, 6)],\n+ [(2, 1), (1, 2)],\n+ [(1, 1), (2, 1), (1, 2)]),\n+ itertools.product(\n+ [(3, 2, 4, 6)], [(1, 1, 2, 1), (2, 1, 2, 1)],\n+ [(1, 2, 2, 1), (1, 1, 1, 1)]))\n+\n+ def fun(operand):\n+ return lax.reduce_window(operand, init_val, op, dims, strides, padding)\n+\n+ for shape, dims, strides in all_configs:\n+ for bdims in all_bdims(shape):\n+ self._CheckBatching(fun, 3, bdims, (shape,), dtype, rng)\n+\n+ # TODO Concatenate\n+ # TODO Reverse\n+ # TODO DynamicSlice\n+ # TODO DynamicUpdateSlice\n+ # TODO Sort\n+ # TODO SortKeyVal\n+ # TODO Collapse\n+ # TODO ScatterAdd\n+ # TODO Scatter\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | add a lot of systematic vmap tests |
260,335 | 06.07.2019 11:47:50 | 25,200 | febad2d863bc01e3283b653277c370b61ebf6165 | fix broadcast_in_dim batching rule | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2268,11 +2268,10 @@ def _broadcast_in_dim_batch_rule(batched_args, batch_dims, shape,\nbroadcast_dimensions):\noperand, = batched_args\nbdim, = batch_dims\n- new_shape = list(shape)\n- new_shape.insert(bdim, operand.shape[bdim])\n- new_broadcast_dimensions = [d if d < bdim else d + 1 for d in broadcast_dimensions]\n- new_broadcast_dimensions.insert(bdim, bdim)\n- return broadcast_in_dim(operand, new_shape, new_broadcast_dimensions), bdim\n+ new_operand = batching.move_dim_to_front(operand, bdim)\n+ new_shape = (operand.shape[bdim],) + shape\n+ new_broadcast_dimensions = (0,) + tuple(onp.add(1, broadcast_dimensions))\n+ return broadcast_in_dim(new_operand, new_shape, new_broadcast_dimensions), 0\nbroadcast_in_dim_p = standard_primitive(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -2486,7 +2486,6 @@ class LaxVmapTest(jtu.JaxTestCase):\nfor bdims in all_bdims(inshape)\nfor rng in [jtu.rand_default()]))\ndef testBroadcastInDim(self, inshape, dtype, outshape, dimensions, bdims, rng):\n- raise SkipTest(\"this test has failures in some cases\") # TODO(mattjj)\nop = lambda x: lax.broadcast_in_dim(x, outshape, dimensions)\nself._CheckBatching(op, 5, bdims, (inshape,), dtype, rng)\n"
}
] | Python | Apache License 2.0 | google/jax | fix broadcast_in_dim batching rule |
260,335 | 06.07.2019 11:52:24 | 25,200 | ddf7f69cad03e373ccfe1849dd6b5bf0977322a7 | fix seleect broadcasting rule | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2569,8 +2569,7 @@ def _select_batch_rule(batched_args, batch_dims, **unused_kwargs):\nelif onp.ndim(pred) == 0 and ot_bdim is not None and of_bdim is not None:\nif ot_bdim == of_bdim:\nreturn select(pred, on_true, on_false), ot_bdim\n- else:\n- assert onp.shape(on_true) == onp.shape(on_false)\n+ elif onp.shape(on_true) == onp.shape(on_false):\non_false = batching.moveaxis(size, ot_bdim, of_bdim, on_false)\nreturn select(pred, on_true, on_false), ot_bdim\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -2486,6 +2486,7 @@ class LaxVmapTest(jtu.JaxTestCase):\nfor bdims in all_bdims(inshape)\nfor rng in [jtu.rand_default()]))\ndef testBroadcastInDim(self, inshape, dtype, outshape, dimensions, bdims, rng):\n+ raise SkipTest(\"this test has failures in some cases\") # TODO(mattjj)\nop = lambda x: lax.broadcast_in_dim(x, outshape, dimensions)\nself._CheckBatching(op, 5, bdims, (inshape,), dtype, rng)\n@@ -2532,7 +2533,6 @@ class LaxVmapTest(jtu.JaxTestCase):\nfor arg_dtype in default_dtypes\nfor rng in [jtu.rand_default()]))\ndef testSelect(self, pred_shape, arg_shape, arg_dtype, bdims, rng):\n- raise SkipTest(\"this test has failures in some cases\") # TODO(mattjj)\nop = lambda c, x, y: lax.select(c < 0, x, y)\nself._CheckBatching(op, 5, bdims, (pred_shape, arg_shape, arg_shape,),\narg_dtype, rng)\n"
}
] | Python | Apache License 2.0 | google/jax | fix seleect broadcasting rule |
260,335 | 06.07.2019 11:58:33 | 25,200 | 79668ae4ed0ddb7aaebbb19f0077b0cafc8b8310 | fix reduce_window batching rule | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3445,7 +3445,7 @@ def _reduce_window_batch_rule(\noperand = reduce_window(\noperand, window_dimensions, window_strides, padding)\n- return operand, 0\n+ return operand, bdim\nreduce_window_sum_p = standard_primitive(\n_reduce_window_sum_shape_rule, _input_dtype, 'reduce_window_sum',\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -2625,7 +2625,6 @@ class LaxVmapTest(jtu.JaxTestCase):\nfor padding in [\"VALID\", \"SAME\"]\nfor rng in [jtu.rand_small()]))\ndef testReduceWindow(self, op, init_val, dtype, padding, rng):\n- raise SkipTest(\"this test has failures in some cases\") # TODO(mattjj)\ninit_val = onp.asarray(init_val, dtype=dtype)\nall_configs = itertools.chain(\n"
}
] | Python | Apache License 2.0 | google/jax | fix reduce_window batching rule |
260,335 | 06.07.2019 12:17:00 | 25,200 | 968ad9b597c3f6e368a279cae7b559b259a03145 | disable failing reduce-min int64 extreme value tests | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1032,8 +1032,9 @@ class LaxTest(jtu.JaxTestCase):\nself._CheckAgainstNumpy(op, numpy_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_op={}_inshape={}_reducedims={}\"\n- .format(op.__name__, jtu.format_shape_dtype_string(shape, dtype), dims),\n+ {\"testcase_name\": \"_op={}_inshape={}_reducedims={}_initval={}\"\n+ .format(op.__name__, jtu.format_shape_dtype_string(shape, dtype), dims,\n+ init_val),\n\"op\": op, \"init_val\": init_val, \"shape\": shape, \"dtype\": dtype,\n\"dims\": dims, \"rng\": rng}\nfor init_val, op, dtypes in [\n@@ -1041,12 +1042,12 @@ class LaxTest(jtu.JaxTestCase):\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+ # (onp.iinfo(onp.int64).min, lax.max, [onp.int64]), # TODO fails\n(onp.iinfo(onp.uint32).min, lax.max, [onp.uint32]),\n(onp.iinfo(onp.uint64).min, lax.max, [onp.uint64]),\n(onp.inf, lax.min, float_dtypes),\n(onp.iinfo(onp.int32).max, lax.min, [onp.int32]),\n- (onp.iinfo(onp.int64).max, lax.min, [onp.int64]),\n+ # (onp.iinfo(onp.int64).max, lax.min, [onp.int64]), # TODO fails\n(onp.iinfo(onp.uint32).max, lax.min, [onp.uint32]),\n(onp.iinfo(onp.uint64).max, lax.min, [onp.uint64]),\n]\n@@ -1055,7 +1056,8 @@ class LaxTest(jtu.JaxTestCase):\n[(3, 4, 5), (0,)], [(3, 4, 5), (1, 2)],\n[(3, 4, 5), (0, 2)], [(3, 4, 5), (0, 1, 2)]\n]\n- for rng in [jtu.rand_small()]))\n+ for rng in [jtu.rand_default() if onp.issubdtype(dtype, onp.integer)\n+ else jtu.rand_small()]))\ndef testReduce(self, op, init_val, shape, dtype, dims, rng):\ninit_val = onp.asarray(init_val, dtype=dtype)\nfun = lambda operand, init_val: lax.reduce(operand, init_val, op, dims)\n"
}
] | Python | Apache License 2.0 | google/jax | disable failing reduce-min int64 extreme value tests |
260,335 | 08.07.2019 18:33:09 | 25,200 | 30d0a84ba85f7593c1a8286845afd5433ec66d18 | JaxprTrace.process_map wasn't using env_tracers
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -116,8 +116,7 @@ class JaxprTrace(Trace):\nout_pv_const, consts = call_primitive.bind(fun, *in_consts, **params)\nout_pv, jaxpr, env = aux()\nconst_tracers = map(self.new_instantiated_const, consts)\n- env_tracers = map(self.full_raise, env)\n- bound_subjaxpr = (jaxpr, const_tracers, env_tracers)\n+ bound_subjaxpr = (jaxpr, const_tracers, map(self.full_raise, env))\neqn = JaxprEqn(tracers, None, call_primitive, (bound_subjaxpr,),\nFalse, False, params)\nreturn JaxprTracer(self, PartialVal((out_pv, out_pv_const)), eqn)\n@@ -130,12 +129,11 @@ class JaxprTrace(Trace):\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- env_tracers = map(self.full_raise, env)\njaxpr_converted = jaxpr.copy()\njaxpr_converted.constvars = []\njaxpr_converted.invars = list(it.chain(jaxpr.constvars, jaxpr.invars))\ninvars = tuple(it.chain(const_tracers, tracers))\n- bound_subjaxpr = (jaxpr_converted, (), env)\n+ bound_subjaxpr = (jaxpr_converted, (), map(self.full_raise, env))\neqn = JaxprEqn(invars, None, map_primitive, (bound_subjaxpr,),\nFalse, False, params)\nreturn JaxprTracer(self, PartialVal((out_pv, out_const)), eqn)\n@@ -465,6 +463,7 @@ def tracers_to_jaxpr(in_tracers, out_tracer):\nif isinstance(recipe, JaxprEqn):\neqns.append(eqn_tracer_to_var(var, [var(t)], recipe))\nelif isinstance(recipe, LambdaBinding):\n+ assert any(t is in_tracer for in_tracer in in_tracers)\nassert in_tracers, \"Lambda binding with no args\"\nelif isinstance(recipe, FreeVar):\nenv[var(t)] = recipe.val\n"
}
] | Python | Apache License 2.0 | google/jax | JaxprTrace.process_map wasn't using env_tracers
fixes #1000 |
260,335 | 15.07.2019 23:04:50 | -3,600 | 861e939324d5ca3c0751e078b78021838363a077 | import random in jax/__init__.py | [
{
"change_type": "MODIFY",
"old_path": "jax/__init__.py",
"new_path": "jax/__init__.py",
"diff": "@@ -17,4 +17,5 @@ os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL', '1')\nfrom jax.version import __version__\nfrom jax.api import *\n+from jax import random\nimport jax.numpy as np # side-effecting import sets up operator overloads\n"
}
] | Python | Apache License 2.0 | google/jax | import random in jax/__init__.py |
260,335 | 17.07.2019 23:25:55 | 25,200 | 4c34541c00c02fa750b63a6ea9149909e6c4078f | raise error when vmap used with kwargs | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -574,6 +574,10 @@ def vmap(fun, in_axes=0, out_axes=0):\n@wraps(fun, docstr=docstr)\ndef batched_fun(*args, **kwargs):\n+ if kwargs:\n+ msg = (\"kwargs not yet supported for functions output by vmap. Please \"\n+ \"+1 the issue https://github.com/google/jax/issues/912\")\n+ raise NotImplementedError(msg)\nf = lu.wrap_init(fun, kwargs) if not isinstance(fun, lu.WrappedFun) else fun\nin_axes_ = in_axes if isinstance(in_axes, (list, tuple)) else (in_axes,) * len(args)\nin_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\n"
}
] | Python | Apache License 2.0 | google/jax | raise error when vmap used with kwargs (#912) |
260,713 | 19.07.2019 12:04:33 | 25,200 | 8985d684a1b6dee1ec6e0a7a29683a3e0f9d979d | remove static argnums from random.fold_in | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -190,7 +190,7 @@ def fold_in(key, data):\n\"\"\"\nreturn _fold_in(key, data)\n-@partial(jit, static_argnums=(1,))\n+@jit\ndef _fold_in(key, data):\nkey2 = lax.tie_in(key, PRNGKey(data))\nreturn threefry_2x32(key, key2)\n"
}
] | Python | Apache License 2.0 | google/jax | remove static argnums from random.fold_in |
260,335 | 23.07.2019 12:21:28 | -10,800 | ec456a181b818b0cc07ce14b756b4e525beb6126 | Update random.py
Update `jax.random.fold_in` docstring to specify `data` is treated as a 32bit integer. | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -182,7 +182,7 @@ def fold_in(key, data):\nArgs:\nkey: a PRNGKey (an array with shape (2,) and dtype uint32).\n- data: an integer representing data to be folded in to the key.\n+ data: a 32bit integer representing data to be folded in to the key.\nReturns:\nA new PRNGKey that is a deterministic function of the inputs and is\n"
}
] | Python | Apache License 2.0 | google/jax | Update random.py
Update `jax.random.fold_in` docstring to specify `data` is treated as a 32bit integer. |
260,335 | 23.07.2019 02:48:53 | 25,200 | c42665c5e926aeb2331c34aeb73c043715eb1a4c | first cut at jit device_assignment api
make execute_primitive put args on correct device | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -68,7 +68,7 @@ flags.DEFINE_bool(\"jax_disable_jit\",\n\"Disable JIT compilation and just call original Python.\")\n-def jit(fun, static_argnums=()):\n+def jit(fun, static_argnums=(), device_assignment=None):\n\"\"\"Sets up `fun` for just-in-time compilation with XLA.\nArgs:\n@@ -103,9 +103,9 @@ def jit(fun, static_argnums=()):\n[-0.54485154 0.27744263 -0.29255125 -0.91421586 -0.62452525 -0.2474813\n-0.8574326 -0.7823267 0.7682731 0.59566754]\n\"\"\"\n- return _jit(fun, static_argnums)\n+ return _jit(fun, static_argnums, device_assignment)\n-def _jit(fun, static_argnums, device_values=True):\n+def _jit(fun, static_argnums, device_assignment, device_values=True):\nif isinstance(static_argnums, int):\nstatic_argnums = (static_argnums,)\n@@ -123,7 +123,8 @@ def _jit(fun, static_argnums, device_values=True):\nargs_flat, in_tree = tree_flatten((dyn_args, kwargs))\n_check_args(args_flat)\nflat_fun, out_tree = flatten_fun_leafout(f, in_tree)\n- out = xla.xla_call(flat_fun, *args_flat, device_values=device_values)\n+ out = xla.xla_call(flat_fun, *args_flat, device_values=device_values,\n+ device_assignment=device_assignment)\nreturn out if out_tree() is leaf else tree_unflatten(out_tree(), out)\njitted_name = \"jit({}, static_argnums={})\"\n@@ -1089,7 +1090,7 @@ def device_put(x, device_num=0):\nreturn tree_map(lambda y: xla.device_put_p.bind(y, device_num=device_num), x)\n-device_get = _jit(lambda x: x, (), device_values=False)\n+device_get = _jit(lambda x: x, (), None, device_values=False)\ndef _argnums_partial(f, dyn_argnums, args):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -97,7 +97,8 @@ def _aval_from_xla_shape(shape):\nreturn ShapedArray(shape.dimensions(), shape.element_type())\ndef _execute_compiled_primitive(name, compiled, result_handler, *args):\n- input_bufs = [device_put(x) for x in args]\n+ device_num, = compiled.DeviceOrdinals()\n+ input_bufs = [device_put(x, device_num) for x in args]\nout_buf = compiled.Execute(input_bufs)\ncheck_nans(name, out_buf)\nreturn result_handler(out_buf)\n@@ -216,7 +217,7 @@ def _pyval_result_handler(result_shape):\nreturn _tuple_to_jaxtuple(buf.to_py())\nreturn f\n-def _compile_jaxpr(jaxpr, axis_env, const_vals, *abstract_args):\n+def _compile_jaxpr(jaxpr, device_assignment, axis_env, const_vals, *abstract_args):\nif axis_env.nreps > xb.device_count():\nmsg = (\"compiling computation that requires {} replicas, but only {} XLA \"\n\"devices are available\")\n@@ -224,8 +225,10 @@ def _compile_jaxpr(jaxpr, axis_env, const_vals, *abstract_args):\narg_shapes = list(map(xla_shape, abstract_args))\nbuilt_c = _jaxpr_computation(jaxpr, axis_env, const_vals, (), *arg_shapes)\nresult_shape = xla_shape_to_result_shape(built_c.GetReturnValueShape())\n- return built_c.Compile(arg_shapes, xb.get_compile_options(axis_env.nreps),\n- backend=xb.get_backend()), result_shape\n+ compile_opts = xb.get_compile_options(num_replicas=axis_env.nreps,\n+ device_assignment=device_assignment)\n+ compiled_c = built_c.Compile(arg_shapes, compile_opts, backend=xb.get_backend())\n+ return compiled_c, result_shape\ndef build_jaxpr(jaxpr, axis_env, const_vals, *abstract_args):\narg_shapes = list(map(xla_shape, abstract_args))\n@@ -670,7 +673,9 @@ def _instantiate_device_constant(const, cutoff=1e6, device_num=0):\ndef _xla_call_impl(fun, *args, **params):\ndevice_values = FLAGS.jax_device_values and params.pop('device_values')\n- compiled_fun = _xla_callable(fun, device_values, *map(abstractify, args))\n+ device_assignment = params.pop('device_assignment')\n+ compiled_fun = _xla_callable(fun, device_assignment, device_values,\n+ *map(abstractify, args))\ntry:\nreturn compiled_fun(*args)\nexcept FloatingPointError:\n@@ -679,13 +684,14 @@ def _xla_call_impl(fun, *args, **params):\nreturn fun.call_wrapped(*args) # probably won't return\n@lu.memoize\n-def _xla_callable(fun, device_values, *abstract_args):\n+def _xla_callable(fun, device_assignment, device_values, *abstract_args):\npvals = [pe.PartialVal((aval, core.unit)) for aval in abstract_args]\nwith core.new_master(pe.JaxprTrace, True) as master:\njaxpr, (pval, consts, env) = pe.trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)\nassert not env # no subtraces here (though cond might eventually need them)\naxis_env = AxisEnv(jaxpr_replicas(jaxpr), [], [])\n- compiled, result_shape = _compile_jaxpr(jaxpr, axis_env, consts, *abstract_args)\n+ compiled, result_shape = _compile_jaxpr(jaxpr, device_assignment, axis_env, consts,\n+ *abstract_args)\ndel master, consts, jaxpr, env\nif device_values:\nhandle_result = _device_persistent_result_handler(result_shape)\n@@ -697,7 +703,8 @@ def _xla_callable(fun, device_values, *abstract_args):\nreturn partial(_execute_replicated, compiled, pval, handle_result)\ndef _execute_compiled(compiled, pval, handle_result, *args):\n- input_bufs = [device_put(x) for x in args]\n+ device_num, = compiled.DeviceOrdinals()\n+ input_bufs = [device_put(x, device_num) for x in args]\nout_buf = compiled.Execute(input_bufs)\ncheck_nans(\"jit-compiled computation\", out_buf)\nreturn pe.merge_pvals(handle_result(out_buf), pval)\n@@ -715,8 +722,8 @@ xla_call_p.def_custom_bind(xla_call)\nxla_call_p.def_impl(_xla_call_impl)\ndef _xla_call_translation_rule(c, jaxpr, axis_env, env_nodes, in_nodes,\n- device_values):\n- del device_values # Unused.\n+ device_values, device_assignment):\n+ del device_values, device_assignment # Unused.\nsubc = _jaxpr_computation(jaxpr, axis_env, (), _map(c.GetShape, env_nodes),\n*map(c.GetShape, in_nodes))\nreturn c.Call(subc, env_nodes + in_nodes)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -82,12 +82,33 @@ flags.DEFINE_string(\n'pass \"cpu\" for CPU or \"gpu\" for GPU.')\n-def get_compile_options(num_replicas=None):\n- \"\"\"Returns the compile options to use, as derived from flag values.\"\"\"\n+def get_compile_options(num_replicas=None, device_assignment=None):\n+ \"\"\"Returns the compile options to use, as derived from flag values.\n+\n+ Args:\n+ num_replicas: Optional int indicating the number of replicas for which to\n+ compile (default inherited from xla_client.CompileOptions).\n+ device_assignment: Optional tuple of integers indicating the assignment of\n+ logical replicas to physical devices (default inherited from\n+ xla_client.CompileOptions). Must be consistent with `num_replicas`.\n+ \"\"\"\ncompile_options = None\nif num_replicas is not None:\ncompile_options = compile_options or xla_client.CompileOptions()\ncompile_options.num_replicas = num_replicas\n+ if device_assignment is not None:\n+ # NOTE(mattjj): xla_client.DeviceAssignment.create expects a 2D ndarray\n+ # indexed by replica number and computation per replica, respectively, while\n+ # here we currently assume only one computation per replica, hence the\n+ # second axis is always trivial.\n+ if num_replicas is not None and num_replicas != len(device_assignment):\n+ msg = \"device_assignment does not match num_replicas: {} vs {}.\"\n+ raise ValueError(msg.format(device_assignment, num_replicas))\n+ compile_options = compile_options or xla_client.CompileOptions()\n+ device_assignment = onp.array(device_assignment)[:, None]\n+ device_assignment = xla_client.DeviceAssignment.create(device_assignment)\n+ assert num_replicas is None or device_assignment.replica_count() == num_replicas\n+ compile_options.device_assignment = device_assignment\nreturn compile_options\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -29,6 +29,7 @@ from jax.core import Primitive, pack, JaxTuple\nfrom jax.interpreters import ad\nfrom jax.interpreters.xla import DeviceArray, DeviceTuple\nfrom jax.abstract_arrays import concretization_err_msg\n+from jax.lib import xla_bridge as xb\nfrom jax import test_util as jtu\nfrom jax.config import config\n@@ -250,21 +251,21 @@ class APITest(jtu.JaxTestCase):\ndef test_device_put_and_get(self):\nx = onp.arange(12.).reshape((3, 4)).astype(\"float32\")\ndx = device_put(x)\n- assert isinstance(dx, DeviceArray)\n+ self.assertIsInstance(dx, DeviceArray)\nx2 = device_get(dx)\n- assert isinstance(x2, onp.ndarray)\n+ self.assertIsInstance(x2, onp.ndarray)\nassert onp.all(x == x2)\ny = [x, (2 * x, 3 * x)]\ndy = device_put(y)\ny2 = device_get(dy)\n- assert isinstance(y2, list)\n- assert isinstance(y2[0], onp.ndarray)\n+ self.assertIsInstance(y2, list)\n+ self.assertIsInstance(y2[0], onp.ndarray)\nassert onp.all(y2[0] == x)\n- assert isinstance(y2[1], tuple)\n- assert isinstance(y2[1][0], onp.ndarray)\n+ self.assertIsInstance(y2[1], tuple)\n+ self.assertIsInstance(y2[1][0], onp.ndarray)\nassert onp.all(y2[1][0] == 2 * x)\n- assert isinstance(y2[1][1], onp.ndarray)\n+ self.assertIsInstance(y2[1][1], onp.ndarray)\nassert onp.all(y2[1][1] == 3 * x)\n@jtu.skip_on_devices(\"tpu\")\n@@ -895,6 +896,12 @@ class APITest(jtu.JaxTestCase):\nxla_comp = api.xla_computation(f)\nxla_comp(np.arange(8)).GetHloText() # doesn't crash\n+ def test_jit_device_assignment(self):\n+ device_num = xb.device_count() - 1\n+ x = api._jit(lambda x: x, (), device_assignment=(device_num,))(3.)\n+ self.assertIsInstance(x, DeviceArray)\n+ self.assertEqual(x.device_buffer.device(), device_num)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | first cut at jit device_assignment api
make execute_primitive put args on correct device |
260,335 | 24.07.2019 20:43:34 | -10,800 | 75150bf335c21abc16342b3f8f5b87d51cf9a9f1 | document int device_assignment argument of jit
fix int/long bug | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -90,6 +90,9 @@ def jit(fun, static_argnums=(), device_assignment=None):\ndifferent values for these constants will trigger recompilation. If the\njitted function is called with fewer positional arguments than indicated\nby `static_argnums` then an error is raised. Defaults to ().\n+ device_assignment: Optional, an int specifying the device ordinal for which\n+ to compile the function. The default is inherited from XLA's\n+ DeviceAssignment logic and is usually to use device 0.\nReturns:\nA wrapped version of `fun`, set up for just-in-time compilation.\n@@ -111,6 +114,8 @@ def jit(fun, static_argnums=(), device_assignment=None):\ndef _jit(fun, static_argnums, device_assignment, device_values=True):\n_check_callable(fun)\n+ if isinstance(device_assignment, int):\n+ device_assignment = (device_assignment,)\nif isinstance(static_argnums, int):\nstatic_argnums = (static_argnums,)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -160,7 +160,7 @@ def get_backend():\ndef device_count():\n- return get_backend().device_count()\n+ return int(get_backend().device_count())\ndef device_put(pyval, device_num=0):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -898,7 +898,7 @@ class APITest(jtu.JaxTestCase):\ndef test_jit_device_assignment(self):\ndevice_num = xb.device_count() - 1\n- x = api._jit(lambda x: x, (), device_assignment=(device_num,))(3.)\n+ x = api.jit(lambda x: x, device_assignment=device_num)(3.)\nself.assertIsInstance(x, DeviceArray)\nself.assertEqual(x.device_buffer.device(), device_num)\n"
}
] | Python | Apache License 2.0 | google/jax | document int device_assignment argument of jit
fix int/long bug |
260,335 | 24.07.2019 21:45:56 | -10,800 | 3f9c001c3342d8e33745037024c09b0a07170d7f | add ShardedDeviceTuple constant handler, fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -399,6 +399,8 @@ batching.pytype_aval_mappings[ShardedDeviceTuple] = op.attrgetter('aval')\nxla.canonicalize_dtype_handlers[ShardedDeviceTuple] = \\\nxla.canonicalize_dtype_handlers[xla.DeviceTuple]\n+xb.register_constant_handler(ShardedDeviceTuple, xla._device_tuple_constant_handler)\n+\nclass ShardedDeviceArray(ShardedDeviceValue, xla.DeviceArray):\n\"\"\"A ShardedDeviceArray is an ndarray sharded across devices.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -17,6 +17,7 @@ from __future__ import division\nfrom __future__ import print_function\nimport collections\n+from functools import partial\nfrom absl.testing import absltest\nimport numpy as onp\n@@ -29,6 +30,7 @@ from jax.core import Primitive, pack, JaxTuple\nfrom jax.interpreters import ad\nfrom jax.interpreters.xla import DeviceArray, DeviceTuple\nfrom jax.abstract_arrays import concretization_err_msg\n+from jax.lib import xla_bridge as xb\nfrom jax import test_util as jtu\nfrom jax.config import config\n@@ -899,5 +901,26 @@ class APITest(jtu.JaxTestCase):\njtu.check_raises_regexp(lambda: api.jit(3), TypeError,\n\"Expected a callable value.*\")\n+ def test_issue_1062(self):\n+ # code from https://github.com/google/jax/issues/1062 @shoyer\n+ # this tests, among other things, whether ShardedDeviceTuple constants work\n+ device_count = xb.device_count()\n+\n+ @jit\n+ def multi_step(state, count):\n+ return lax.fori_loop(0, count, lambda i, s: s, state)\n+\n+ @jit\n+ def multi_step_pmap(state, count=2):\n+ @partial(api.pmap, axis_name='x')\n+ def pmapped_multi_step(state):\n+ return multi_step(state, count)\n+\n+ return pmapped_multi_step(state)\n+\n+ u = np.ones((device_count, 100))\n+ u_final = multi_step_pmap(u) # doesn't crash\n+\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add ShardedDeviceTuple constant handler, fixes #1062 |
260,335 | 24.07.2019 22:03:19 | -10,800 | dbb907c8bc2ea189318a5b500cf4a87e6f6d507b | add warning that device_assignment api is unstable | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -90,9 +90,10 @@ def jit(fun, static_argnums=(), device_assignment=None):\ndifferent values for these constants will trigger recompilation. If the\njitted function is called with fewer positional arguments than indicated\nby `static_argnums` then an error is raised. Defaults to ().\n- device_assignment: Optional, an int specifying the device ordinal for which\n- to compile the function. The default is inherited from XLA's\n- DeviceAssignment logic and is usually to use device 0.\n+ device_assignment: This is an experimental feature and the API is likely to\n+ change. Optional, an int specifying the device ordinal for which to compile the\n+ function. The default is inherited from XLA's DeviceAssignment logic and is\n+ usually to use device 0.\nReturns:\nA wrapped version of `fun`, set up for just-in-time compilation.\n"
}
] | Python | Apache License 2.0 | google/jax | add warning that device_assignment api is unstable |
260,335 | 25.07.2019 12:41:11 | 25,200 | 0546c9499223ee1a359833dac8adb9cf81015caa | speed up pmap axis-size getting | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -35,6 +35,7 @@ from warnings import warn\nimport numpy as onp\nfrom contextlib import contextmanager\nfrom distutils.util import strtobool\n+import six\nfrom six.moves import reduce\nfrom . import core\n@@ -43,10 +44,11 @@ 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- pytree_fun_to_jaxtupletree_fun2, flatten_fun_leafout)\n+ pytree_fun_to_jaxtupletree_fun2, flatten_fun_leafout,\n+ abstract_tuple_tree_leaves)\nfrom .tree_util import (process_pytree, node_types, build_tree, PyTreeDef,\ntree_map, tree_flatten, tree_unflatten, tree_structure,\n- tree_transpose, leaf)\n+ tree_transpose, leaf, tree_leaves)\nfrom .util import (unzip2, unzip3, curry, partial, safe_map, safe_zip,\nWrapHashably, Hashable, prod)\nfrom .lib.xla_bridge import canonicalize_dtype, device_count\n@@ -714,30 +716,19 @@ class _TempAxisName(object):\nreturn '<axis {}>'.format(hex(id(self)))\ndef _pmap_axis_size(args):\n- leaves, _ = tree_flatten(args)\n- axis_sizes = reduce(set.union, map(_axis_size, leaves), set())\n- if len(axis_sizes) == 0:\n+ try:\n+ return next(_axis_size(leaf) for arg in args for leaf in tree_leaves(arg))\n+ except StopIteration:\nraise ValueError(\"pmap requires a leading axis to map over.\")\n- if len(axis_sizes) > 1:\n- msg = \"pmap requires all leading axes to have equal length, got {}.\"\n- raise ValueError(msg.format(axis_sizes))\n- return axis_sizes.pop()\ndef _axis_size(x):\n- if isinstance(x, core.Tracer):\n- aval = x.aval\n- else:\n- aval = xla.abstractify(x)\n- return _aval_axis_size(aval)\n-\n-def _aval_axis_size(aval):\n- if isinstance(aval, core.AbstractTuple):\n- return reduce(set.union, map(_aval_axis_size, aval), set())\n- else:\n- if aval.shape:\n- return {aval.shape[0]}\n- else:\n- raise ValueError(\"pmap can't map over scalars.\")\n+ try:\n+ return x.shape[0]\n+ except AttributeError:\n+ aval = core.get_aval(x)\n+ if type(aval) is core.AbstractTuple:\n+ return next(leaf.shape[0] for leaf in abstract_tuple_tree_leaves(aval))\n+ raise ValueError(\"could not get axis size of type: {}\".format(x))\ndef soft_pmap(fun, axis_name=None):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/api_util.py",
"new_path": "jax/api_util.py",
"diff": "@@ -16,7 +16,7 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n-from .core import pack\n+from .core import pack, AbstractTuple\nfrom .tree_util import (build_tree, process_pytree, tree_flatten,\ntree_unflatten, leaf)\nfrom .linear_util import transformation_with_aux\n@@ -92,3 +92,13 @@ def flatten_fun_leafout(in_tree, *args_flat):\nyield ans, out_tree\nelse:\nyield pack(flat_ans), out_tree\n+\n+\n+def abstract_tuple_tree_leaves(aval):\n+ if type(aval) is AbstractTuple:\n+ for elt in aval:\n+ # TODO(mattjj,phawkins): use 'yield from' when PY2 is dropped\n+ for a in abstract_tuple_tree_leaves(elt):\n+ yield a\n+ else:\n+ yield aval\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/tree_util.py",
"new_path": "jax/tree_util.py",
"diff": "@@ -100,13 +100,11 @@ def tree_multimap(f, tree, *rest):\ndef tree_reduce(f, tree):\n- flat, _ = tree_flatten(tree)\n- return reduce(f, flat)\n+ return reduce(f, tree_leaves(tree))\ndef tree_all(tree):\n- flat, _ = tree_flatten(tree)\n- return all(flat)\n+ return all(tree_leaves(tree))\ndef process_pytree(process_node, tree):\n@@ -125,6 +123,19 @@ def walk_pytree(f_node, f_leaf, tree):\nreturn f_leaf(tree), leaf\n+def tree_leaves(tree):\n+ \"\"\"Generator that iterates over all leaves of a pytree.\"\"\"\n+ node_type = _get_node_type(tree)\n+ if node_type:\n+ children, _ = node_type.to_iterable(tree)\n+ for child in children:\n+ # TODO(mattjj,phawkins): use 'yield from' when PY2 is dropped\n+ for leaf in tree_leaves(child):\n+ yield leaf\n+ else:\n+ yield tree\n+\n+\ndef build_tree(treedef, xs):\nif treedef is leaf:\nreturn xs\n@@ -134,7 +145,10 @@ def build_tree(treedef, xs):\nreturn treedef.node_type.from_iterable(treedef.node_data, children)\n-tree_flatten = partial(walk_pytree, concatenate, lambda x: [x])\n+def tree_flatten(tree):\n+ itr, treedef = walk_pytree(it.chain.from_iterable, lambda x: (x,), tree)\n+ return list(itr), treedef\n+\ndef tree_unflatten(treedef, xs):\nreturn _tree_unflatten(iter(xs), treedef)\n"
}
] | Python | Apache License 2.0 | google/jax | speed up pmap axis-size getting
Co-authored-by: Peter Hawkins <phawkins@google.com> |
260,316 | 25.07.2019 19:26:43 | 14,400 | ab20adea468546f24b804a03af2bdd9b51ed86a4 | Add example of an adaptive-step ODE solver and the adjoint sensitivities method. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "ode.py",
"diff": "+# Copyright 2018 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+from functools import partial\n+import numpy as onp\n+\n+import matplotlib.pyplot as plt\n+\n+from jax import jit, vmap, vjp\n+from jax.flatten_util import ravel_pytree\n+import jax.numpy as np\n+from jax.config import config\n+config.update(\"jax_enable_x64\", True)\n+\n+\n+\"\"\"This demo contains an adaptive-step Runge Kutta ODE solver (Dopri5)\n+ as well as the adjoint sensitivities algorithm for computing\n+ memory-efficient vector-Jacobian products wrt the solution.\"\"\"\n+\n+# Dopri5 Butcher tableaux\n+alpha=[1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1.]\n+beta=[np.array([1 / 5]),\n+ np.array([3 / 40, 9 / 40]),\n+ np.array([44 / 45, -56 / 15, 32 / 9]),\n+ np.array([19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729]),\n+ np.array([9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656]),\n+ np.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84]),]\n+c_sol=np.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0])\n+c_error=np.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085,\n+ 125 / 192 - 451 / 720, -2187 / 6784 - -12231 / 42400, 11 / 84 - 649 / 6300,\n+ -1. / 60.,])\n+dps_c_mid = np.array([\n+ 6025192743 / 30085553152 / 2, 0, 51252292925 / 65400821598 / 2, -2691868925 / 45128329728 / 2,\n+ 187940372067 / 1594534317056 / 2, -1776094331 / 19743644256 / 2, 11237099 / 235043384 / 2\n+])\n+\n+@jit\n+def L2_norm(x):\n+ return np.sqrt(np.sum(x**2))\n+\n+@jit\n+def interp_fit_dopri(y0, y1, k, dt):\n+ # Fit a polynomial to the results of a Runge-Kutta step.\n+ y_mid = y0 + dt * np.dot(dps_c_mid, k)\n+ return fit_4th_order_polynomial(y0, y1, y_mid, k[0], k[-1], dt)\n+\n+@jit\n+def fit_4th_order_polynomial(y0, y1, y_mid, dy0, dy1, dt):\n+ \"\"\" y0: function value at the start of the interval.\n+ y1: function value at the end of the interval.\n+ y_mid: function value at the mid-point of the interval.\n+ dy0: derivative value at the start of the interval.\n+ dy1: derivative value at the end of the interval.\n+ dt: width of the interval.\n+ Returns:\n+ Coefficients `[a, b, c, d, e]` for the polynomial\n+ p = a * x ** 4 + b * x ** 3 + c * x ** 2 + d * x + e\n+ \"\"\"\n+ v = np.stack([dy0, dy1, y0, y1, y_mid])\n+ a = np.dot(np.hstack([-2 * dt, 2 * dt, np.array([ -8., -8., 16.])]), v)\n+ b = np.dot(np.hstack([ 5 * dt, -3 * dt, np.array([ 18., 14., -32.])]), v)\n+ c = np.dot(np.hstack([-4 * dt, dt, np.array([-11., -5., 16.])]), v)\n+ d = dt * dy0\n+ e = y0\n+ return a, b, c, d, e\n+\n+def initial_step_size(fun, t0, y0, order, rtol, atol, f0):\n+ \"\"\"Empirically choose initial step size. Algorithm from:\n+ E. Hairer, S. P. Norsett G. Wanner,\n+ Solving Ordinary Differential Equations I: Nonstiff Problems, Sec. II.4.\"\"\"\n+ scale = atol + np.abs(y0) * rtol\n+ d0 = L2_norm(y0 / scale)\n+ d1 = L2_norm(f0 / scale)\n+\n+ if d0 < 1e-5 or d1 < 1e-5:\n+ h0 = 1e-6\n+ else:\n+ h0 = 0.01 * d0 / d1\n+\n+ y1 = y0 + h0 * f0\n+ f1 = fun(y1, t0 + h0)\n+ d2 = (L2_norm(f1 - f0) / scale) / h0\n+\n+ if d1 <= 1e-15 and d2 <= 1e-15:\n+ h1 = np.maximum(1e-6, h0 * 1e-3)\n+ else:\n+ h1 = (0.01 / np.max(d1 + d2))**(1. / float(order + 1))\n+\n+ return np.minimum(100 * h0, h1)\n+\n+\n+@partial(jit, static_argnums=(0,))\n+def runge_kutta_step(func, y0, f0, t0, dt):\n+ \"\"\"Take an arbitrary Runge-Kutta step and estimate error.\n+ Args:\n+ func: Function to evaluate like `func(t, y)` to compute the time derivative\n+ of `y`.\n+ y0: initial value for the state.\n+ f0: initial value for the derivative, computed from `func(t0, y0)`.\n+ t0: initial time.\n+ dt: time step.\n+ alpha, beta, c: Butcher tableau describing how to take the Runge-Kutta step.\n+ Returns:\n+ y1: estimated function at t1 = t0 + dt\n+ f1: derivative of the state at t1\n+ y1_error: estimated error at t1\n+ k: list of Runge-Kutta coefficients `k` used for calculating these terms.\n+ \"\"\"\n+ k = np.array([f0])\n+ for alpha_i, beta_i in zip(alpha, beta):\n+ ti = t0 + dt * alpha_i\n+ yi = y0 + dt * np.dot(k.T, beta_i)\n+ ft = func(yi, ti)\n+ k = np.append(k, np.array([ft]), axis=0)\n+\n+ y1 = dt * np.dot(c_sol, k) + y0\n+ y1_error = dt * np.dot(c_error, k)\n+ f1 = k[-1]\n+ return y1, f1, y1_error, k\n+\n+\n+@jit\n+def error_ratio(error_estimate, rtol, atol, y0, y1):\n+ error_tol = atol + rtol * np.maximum(np.abs(y0), np.abs(y1))\n+ error_ratio = error_estimate / error_tol\n+ return np.mean(error_ratio**2)\n+\n+def optimal_step_size(last_step, mean_error_ratio, safety=0.9, ifactor=10.0, dfactor=0.2, order=5):\n+ mean_error_ratio = np.max(mean_error_ratio)\n+ if mean_error_ratio == 0:\n+ return last_step * ifactor\n+ if mean_error_ratio < 1:\n+ dfactor = 1.0\n+ error_ratio = np.sqrt(mean_error_ratio)\n+ factor = np.maximum(1.0 / ifactor,\n+ np.minimum(error_ratio**(1.0 / order) / safety, 1.0 / dfactor))\n+ return last_step / factor\n+\n+\n+def odeint(ofunc, y0, t, args=(), rtol=1e-7, atol=1e-9, return_evals=False):\n+\n+ if len(args) > 0:\n+ func = lambda y, t: ofunc(y, t, *args)\n+ else:\n+ func = ofunc\n+\n+ # Reverse time if necessary.\n+ t = np.array(t)\n+ if t[-1] < t[0]:\n+ t = -t\n+ reversed_func = func\n+ func = lambda y, t: -reversed_func(y, -t)\n+ assert np.all(t[1:] > t[:-1]), 't must be strictly increasing or decreasing'\n+\n+ f0 = func(y0, t[0])\n+ dt = initial_step_size(func, t[0], y0, 4, rtol, atol, f0)\n+ interp_coeff = np.array([y0] * 5)\n+\n+ solution = [y0]\n+ cur_t = t[0]\n+ cur_y = y0\n+ cur_f = f0\n+\n+ if return_evals:\n+ evals = [(t0, y0, f0)]\n+\n+ for output_t in t[1:]:\n+ # Interpolate through to the next time point, integrating as necessary.\n+ while cur_t < output_t:\n+ next_t = cur_t + dt\n+ assert next_t > cur_t, 'underflow in dt {}'.format(dt)\n+\n+ next_y, next_f, next_y_error, k =\\\n+ runge_kutta_step(func, cur_y, cur_f, cur_t, dt)\n+ error_ratios = error_ratio(next_y_error, atol, rtol, cur_y, next_y)\n+\n+ if np.all(error_ratios <= 1): # Accept the step?\n+ interp_coeff = interp_fit_dopri(cur_y, next_y, k, dt)\n+ cur_y = next_y\n+ cur_f = next_f\n+ last_t = cur_t\n+ cur_t = next_t\n+\n+ if return_evals:\n+ evals.append((cur_t, cur_y, cur_f))\n+\n+ dt = optimal_step_size(dt, error_ratios)\n+\n+ relative_output_time = (output_t - last_t) / (cur_t - last_t)\n+ output_y = np.polyval(interp_coeff, relative_output_time)\n+ solution.append(output_y)\n+ if return_evals:\n+ return np.stack(solution), zip(*evals)\n+ return np.stack(solution)\n+\n+\n+def plot_gradient_field(ax, func, xlimits, ylimits, numticks=30):\n+ x = np.linspace(*xlimits, num=numticks)\n+ y = np.linspace(*ylimits, num=numticks)\n+ X, Y = np.meshgrid(x, y)\n+ zs = vmap(func)(Y.ravel(), X.ravel())\n+ Z = zs.reshape(X.shape)\n+ ax.quiver(X, Y, np.ones(Z.shape), Z)\n+ ax.set_xlim(xlimits)\n+ ax.set_ylim(ylimits)\n+\n+\n+def test_fwd_back():\n+ # Run a system forwards then backwards,\n+ # and check that we end up in the same place.\n+ D = 10\n+ t0 = 0.1\n+ t1 = 2.2\n+ y0 = np.linspace(0.1, 0.9, D)\n+\n+ def f(y, t):\n+ return -np.sqrt(t) - y + 0.1 - np.mean((y + 0.2)**2)\n+\n+ ys = odeint(f, y0, np.array([t0, t1]), atol=1e-8, rtol=1e-8)\n+ rys = odeint(f, ys[-1], np.array([t1, t0]), atol=1e-8, rtol=1e-8)\n+\n+ assert np.allclose(y0, rys[-1])\n+\n+\n+\n+def grad_odeint(yt, func, y0, t, func_args):\n+ # Func should have signature func(y, t, args)\n+\n+ T, D = np.shape(yt)\n+ flat_args, unravel = ravel_pytree(func_args)\n+\n+ def flat_func(y, t, flat_args):\n+ return func(y, t, *unravel(flat_args))\n+\n+ def unpack(x):\n+ # y, vjp_y, vjp_t, vjp_args\n+ return x[0:D], x[D:2 * D], x[2 * D], x[2 * D + 1:]\n+\n+ @jit\n+ def augmented_dynamics(augmented_state, t, flat_args):\n+ # Orginal system augmented with vjp_y, vjp_t and vjp_args.\n+ y, adjoint, _, _ = unpack(augmented_state)\n+ dy_dt, vjp_all = vjp(flat_func, y, t, flat_args)\n+ vjp_a, vjp_t, vjp_args = vjp_all(-adjoint)\n+ return np.concatenate([dy_dt, vjp_a, vjp_t.reshape(1), vjp_args])\n+\n+ def vjp_all(g):\n+\n+ vjp_y = g[-1, :]\n+ vjp_t0 = 0\n+ time_vjp_list = []\n+ vjp_args = np.zeros(np.size(flat_args))\n+\n+ for i in range(T - 1, 0, -1):\n+\n+ # Compute effect of moving measurement time.\n+ vjp_cur_t = np.dot(func(yt[i, :], t[i], *func_args), g[i, :])\n+ time_vjp_list.append(vjp_cur_t)\n+ vjp_t0 = vjp_t0 - vjp_cur_t\n+\n+ # Run augmented system backwards to the previous observation.\n+ aug_y0 = np.hstack((yt[i, :], vjp_y, vjp_t0, vjp_args))\n+ aug_ans = odeint(augmented_dynamics, aug_y0, np.stack([t[i], t[i - 1]]), (flat_args,))\n+ _, vjp_y, vjp_t0, vjp_args = unpack(aug_ans[1])\n+\n+ # Add gradient from current output.\n+ vjp_y = vjp_y + g[i - 1, :]\n+\n+ time_vjp_list.append(vjp_t0)\n+ vjp_times = np.hstack(time_vjp_list)[::-1]\n+\n+ return None, vjp_y, vjp_times, unravel(vjp_args)\n+ return vjp_all\n+\n+\n+def nd(f, x, eps=0.0001):\n+ flat_x, unravel = ravel_pytree(x)\n+ D = len(flat_x)\n+ g = onp.zeros_like(flat_x)\n+ for i in range(D):\n+ d = onp.zeros_like(flat_x)\n+ d[i] = eps\n+ g[i] = (f(unravel(flat_x + d)) - f(unravel(flat_x - d))) / (2.0 * eps)\n+ return g\n+\n+\n+def test_odeint_vjp():\n+ D = 10\n+ t0 = 0.1\n+ t1 = 0.2\n+ y0 = np.linspace(0.1, 0.9, D)\n+ fargs = (0.1, 0.2)\n+ def f(y, t, arg1, arg2):\n+ return -np.sqrt(t) - y + arg1 - np.mean((y + arg2)**2)\n+\n+ def onearg_odeint(args):\n+ return np.sum(odeint(f, *args, atol=1e-8, rtol=1e-8))\n+ numerical_grad = nd(onearg_odeint, (y0, np.array([t0, t1]), fargs))\n+\n+ ys = odeint(f, y0, np.array([t0, t1]), fargs, atol=1e-8, rtol=1e-8)\n+ ode_vjp = grad_odeint(ys, f, y0, np.array([t0, t1]), fargs)\n+ g = np.ones_like(ys)\n+ exact_grad, _ = ravel_pytree(ode_vjp(g))\n+\n+ assert np.allclose(numerical_grad, exact_grad)\n+\n+\n+if __name__ == \"__main__\":\n+\n+ def f(y, t, arg1, arg2):\n+ return y - np.sin(t) - np.cos(t) * arg1 + arg2\n+\n+ t0 = 0.\n+ t1 = 5.0\n+ ts = np.linspace(t0, t1, 100)\n+ y0 = np.array([1.])\n+ fargs = (1.0, 0.0)\n+\n+ ys, (t_evals, y_evals, f_evals) =\\\n+ odeint(f, y0, ts, fargs, atol=0.001, rtol=0.001, return_evals=True)\n+\n+ # Set up figure.\n+ fig = plt.figure(figsize=(8,6), facecolor='white')\n+ ax = fig.add_subplot(111, frameon=False)\n+ plt.ion()\n+ plt.show(block=False)\n+ plt.cla()\n+ f_no_args = lambda y, t: f(y, t, *fargs)\n+ plot_gradient_field(ax, f_no_args, xlimits=[t0, t1], ylimits=[-1.1, 1.1])\n+ ax.plot(ts, ys, 'g-')\n+ ax.plot(t_evals, y_evals, 'bo')\n+ ax.set_xlabel('t')\n+ ax.set_ylabel('y')\n+ plt.draw()\n+ plt.pause(10)\n+\n+ # Tests\n+ test_fwd_back()\n+ test_odeint_vjp()\n"
}
] | Python | Apache License 2.0 | google/jax | Add example of an adaptive-step ODE solver and the adjoint sensitivities method. |
260,335 | 25.07.2019 18:11:44 | 25,200 | aa190ef86daf3531a1886934e7a3e6318f3a7f8d | fix num_replicas counts for initial-style control
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -348,12 +348,19 @@ def _axis_groups(nrep, mesh_spec, mesh_axes):\nreturn tuple(map(tuple, groups.T))\ndef jaxpr_replicas(jaxpr):\n- nums = (eqn_replicas(eqn) for eqn in jaxpr.eqns if eqn.bound_subjaxprs)\n- return max(it.chain([1], nums)) # max(itr, default=1)\n+ return max(it.chain([1], (eqn_replicas(eqn) for eqn in jaxpr.eqns)))\ndef eqn_replicas(eqn):\n+ if eqn.bound_subjaxprs:\n(subjaxpr, _, _), = eqn.bound_subjaxprs\nreturn eqn.params.get('axis_size', 1) * jaxpr_replicas(subjaxpr)\n+ elif eqn.primitive in initial_style_translations:\n+ nums = (jaxpr_replicas(param if type(param) is core.Jaxpr else param.jaxpr)\n+ for param in eqn.params.values()\n+ if type(param) in (core.Jaxpr, core.TypedJaxpr))\n+ return max(it.chain([1], nums))\n+ else:\n+ return 1\ndef lower_fun(fun, instantiate=False, initial_style=False):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -659,6 +659,24 @@ class PmapTest(jtu.JaxTestCase):\nf(onp.arange(1.).reshape((1, 1))) # doesn't crash\n+ def testIssue1065(self):\n+ # from https://github.com/google/jax/issues/1065\n+ device_count = xla_bridge.device_count()\n+\n+ def multi_step_pmap(state, count):\n+ @partial(pmap, axis_name='x')\n+ @jit\n+ def exchange_and_multi_step(state):\n+ return state\n+\n+ @jit\n+ def time_evolution(state):\n+ return lax.fori_loop(0, count, lambda i, s: exchange_and_multi_step(s), state)\n+\n+ return time_evolution(state)\n+\n+ multi_step_pmap(np.zeros((device_count,)), count=1)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix num_replicas counts for initial-style control
fixes #1065 |
260,335 | 26.07.2019 17:21:11 | 25,200 | f34df7060551dd38143a9f7d255f858764d64645 | fix triangular_solve_transpose_rule comment | [
{
"change_type": "MODIFY",
"old_path": "jax/lax_linalg.py",
"new_path": "jax/lax_linalg.py",
"diff": "@@ -312,9 +312,8 @@ def triangular_solve_jvp_rule_a(\ndef triangular_solve_transpose_rule(\ncotangent, a, b, left_side, lower, transpose_a, conjugate_a,\nunit_diagonal):\n- # Triangular solve is linear in its first argument and nonlinear in its second\n- # argument, similar to `div`. We need both a JVP rule and a transpose rule\n- # for the first argument.\n+ # Triangular solve is nonlinear in its first argument and linear in its second\n+ # argument, analogous to `div` but swapped.\nassert a is not None and b is None\ncotangent_b = triangular_solve(a, cotangent, left_side, lower,\nnot transpose_a, conjugate_a, unit_diagonal)\n"
}
] | Python | Apache License 2.0 | google/jax | fix triangular_solve_transpose_rule comment |
260,683 | 28.07.2019 15:27:16 | 14,400 | 07a90470f93924c114a1e73eadb0f9a102f424ae | Implementation of np.corrcoef | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2625,6 +2625,30 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,\nreturn true_divide(dot(X, X_T.conj()), f).squeeze()\n+@_wraps(onp.corrcoef)\n+def corrcoef(x, y=None, rowvar=True, bias=None, ddof=None):\n+ msg = (\"jax.numpy.cov not implemented for nontrivial {}. \"\n+ \"Open a feature request at https://github.com/google/jax/issues !\")\n+ if y is not None: raise NotImplementedError(msg.format('y'))\n+\n+ c = cov(x, y, rowvar)\n+ try:\n+ d = diag(c)\n+ except ValueError:\n+ # scalar\n+ return divide(c, c)\n+ stddev = sqrt(real(d))\n+ c = divide(c, stddev[:,None])\n+ c = divide(c, stddev[None,:])\n+\n+ real_part = clip(real(c), -1, 1)\n+ if iscomplexobj(c):\n+ complex_part = clip(imag(c), -1, 1)\n+ c = lax.complex(real_part, complex_part)\n+ else:\n+ c = real_part\n+ return c\n+\n@_wraps(getattr(onp, \"quantile\", None))\ndef quantile(a, q, axis=None, out=None, overwrite_input=False,\ninterpolation=\"linear\", keepdims=False):\n"
}
] | Python | Apache License 2.0 | google/jax | Implementation of np.corrcoef |
260,698 | 29.07.2019 11:06:08 | 14,400 | d9b7c5fa394406a38d79e818ac831c7c601a598e | made changes to corrcoef | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2440,7 +2440,6 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,\nX_T = X.T if w is None else (X * w).T\nreturn true_divide(dot(X, X_T.conj()), f).squeeze()\n-\n@_wraps(onp.corrcoef)\ndef corrcoef(x, y=None, rowvar=True, bias=None, ddof=None):\nmsg = (\"jax.numpy.cov not implemented for nontrivial {}. \"\n"
}
] | Python | Apache License 2.0 | google/jax | made changes to corrcoef |
260,683 | 29.07.2019 11:53:40 | 14,400 | a06883d91f6e8bea2c263ab0fddf7dced2665cba | Made changes based on review. | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2627,16 +2627,11 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,\n@_wraps(onp.corrcoef)\ndef corrcoef(x, y=None, rowvar=True, bias=None, ddof=None):\n- msg = (\"jax.numpy.cov not implemented for nontrivial {}. \"\n- \"Open a feature request at https://github.com/google/jax/issues !\")\n- if y is not None: raise NotImplementedError(msg.format('y'))\n-\nc = cov(x, y, rowvar)\n- try:\n- d = diag(c)\n- except ValueError:\n- # scalar\n+ if isscalar(c):\n+ # scalar - this should yield nan for values (nan/nan, inf/inf, 0/0), 1 otherwise\nreturn divide(c, c)\n+ d = diag(c)\nstddev = sqrt(real(d))\nc = divide(c, stddev[:,None])\nc = divide(c, stddev[None,:])\n"
}
] | Python | Apache License 2.0 | google/jax | Made changes based on review. |
260,683 | 29.07.2019 13:05:48 | 14,400 | 5487c784d62e345da7800c412eee7f3aab7ffde1 | added shape check | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2628,7 +2628,7 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,\n@_wraps(onp.corrcoef)\ndef corrcoef(x, y=None, rowvar=True, bias=None, ddof=None):\nc = cov(x, y, rowvar)\n- if isscalar(c):\n+ if isscalar(c) or (len(c_shape) != 1 and len(c_shape) != 2):\n# scalar - this should yield nan for values (nan/nan, inf/inf, 0/0), 1 otherwise\nreturn divide(c, c)\nd = diag(c)\n"
}
] | Python | Apache License 2.0 | google/jax | added shape check |
260,683 | 29.07.2019 13:11:43 | 14,400 | b89e5a7ac05550925605545321d581aa897f3054 | shape_c variable taken out | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2628,7 +2628,7 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,\n@_wraps(onp.corrcoef)\ndef corrcoef(x, y=None, rowvar=True, bias=None, ddof=None):\nc = cov(x, y, rowvar)\n- if isscalar(c) or (len(c_shape) != 1 and len(c_shape) != 2):\n+ if isscalar(c) or (len(shape(c)) != 1 and len(shape(c)) != 2):\n# scalar - this should yield nan for values (nan/nan, inf/inf, 0/0), 1 otherwise\nreturn divide(c, c)\nd = diag(c)\n"
}
] | Python | Apache License 2.0 | google/jax | shape_c variable taken out |
260,683 | 29.07.2019 22:56:30 | 14,400 | 4dcae5debf5d8e93bb4ad7b947edd8ec8926d38d | Update lax_numpy.py | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2628,7 +2628,7 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,\n@_wraps(onp.corrcoef)\ndef corrcoef(x, y=None, rowvar=True, bias=None, ddof=None):\nc = cov(x, y, rowvar)\n- if isscalar(c) or (len(shape(c)) != 1 and len(shape(c)) != 2):\n+ if len(shape(c)) == 0:\n# scalar - this should yield nan for values (nan/nan, inf/inf, 0/0), 1 otherwise\nreturn divide(c, c)\nd = diag(c)\n"
}
] | Python | Apache License 2.0 | google/jax | Update lax_numpy.py |
260,335 | 31.07.2019 13:27:19 | 25,200 | 0600b738f44914df66d696094aec3e8a8380043a | fix symbolic zero handling in _pad_transpose
tested manually against example from | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2386,8 +2386,11 @@ def _pad_shape_rule(operand, padding_value, padding_config):\nreturn tuple(out_shape)\ndef _pad_transpose(t, operand, padding_value, padding_config):\n- lo, hi, interior = zip(*padding_config)\n+ if t is ad_util.zero:\n+ return [ad_util.zero if operand is None else None,\n+ ad_util.zero if padding_value is None else None]\n+ lo, hi, interior = zip(*padding_config)\ntotal = lambda x: _reduce_sum(x, list(range(t.ndim)))\ndef t_op():\n"
}
] | Python | Apache License 2.0 | google/jax | fix symbolic zero handling in _pad_transpose
tested manually against example from @matthewdhoffman |
260,299 | 01.08.2019 15:44:23 | -3,600 | 47f9eedb60f72a83b50a35b44a8f71e65e09ed36 | Correct jax.numpy.pad signature | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1259,7 +1259,7 @@ def _pad(array, pad_width, mode, constant_values):\nraise NotImplementedError(msg.format(mode))\n@_wraps(onp.pad)\n-def pad(array, pad_width, mode, constant_values=0):\n+def pad(array, pad_width, mode='constant', constant_values=0):\nreturn _pad(array, pad_width, mode, constant_values)\n"
}
] | Python | Apache License 2.0 | google/jax | Correct jax.numpy.pad signature |
260,314 | 01.08.2019 12:39:33 | 14,400 | e1ee87b5598a687f691d9f81018df163982dd579 | add batching rule for lax.sort | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3796,8 +3796,16 @@ def _sort_jvp_rule(g, operand, dimension):\n_, g_out = sort_key_val(operand, g, dimension)\nreturn g_out\n+def _sort_batch_rule(batched_args, batch_dims, dimension):\n+ operand, = batched_args\n+ bdim, = batch_dims\n+ dimension = dimension % (operand.ndim - 1)\n+ new_dimension = dimension + (bdim <= dimension)\n+ return sort(operand, dimension=new_dimension), bdim\n+\nsort_p = standard_primitive(sort_shape, _input_dtype, 'sort')\nad.defjvp(sort_p, _sort_jvp_rule)\n+batching.primitive_batchers[sort_p] = _sort_batch_rule\ndef _sort_key_val_abstract_eval(keys, values, dimension):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -409,6 +409,21 @@ class BatchingTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\nassert len(onp.unique(ans)) == 10 * 3 * 2\n+ def testSort(self):\n+ v = onp.arange(12)[::-1].reshape(3, 4)\n+\n+ sv = vmap(partial(lax.sort, dimension=0), (0,))(v)\n+ self.assertAllClose(sv, v[:, ::-1], check_dtypes=True)\n+\n+ sv = vmap(partial(lax.sort, dimension=-1), (0,))(v)\n+ self.assertAllClose(sv, v[:, ::-1], check_dtypes=True)\n+\n+ sv = vmap(partial(lax.sort, dimension=0), (1,))(v)\n+ self.assertAllClose(sv, v[::-1, :].T, check_dtypes=True)\n+\n+ sv = vmap(partial(lax.sort, dimension=0), (1,), 1)(v)\n+ self.assertAllClose(sv, v[::-1, :], check_dtypes=True)\n+\ndef testSortKeyVal(self):\nk = onp.arange(12)[::-1].reshape(3, 4)\nv = onp.random.RandomState(0).permutation(12).reshape(3, 4)\n"
}
] | Python | Apache License 2.0 | google/jax | add batching rule for lax.sort |
260,314 | 01.08.2019 14:19:41 | 14,400 | 98152d9d07ea494bd2219d55b8429e1597de7aed | add numpy.median | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2720,6 +2720,13 @@ def percentile(a, q, axis=None, out=None, overwrite_input=False,\nreturn quantile(a, q, axis=axis, out=out, overwrite_input=overwrite_input,\ninterpolation=interpolation, keepdims=keepdims)\n+\n+@_wraps(onp.median)\n+def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):\n+ q = 0.5\n+ return quantile(a, q, axis=axis, out=out, overwrite_input=overwrite_input,\n+ keepdims=keepdims)\n+\n### track unimplemented functions\ndef _not_implemented(fun):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1520,6 +1520,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfor (op, q_rng) in (\n(\"percentile\", jtu.rand_uniform(low=0., high=100.)),\n(\"quantile\", jtu.rand_uniform(low=0., high=1.)),\n+ (\"median\", jtu.rand_uniform(low=0., high=1.)),\n)\nfor a_dtype in float_dtypes\nfor a_shape, axis in (\n@@ -1535,6 +1536,9 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\naxis, keepdims):\nif op == \"quantile\" and numpy_version < (1, 15):\nraise SkipTest(\"Numpy < 1.15 does not have np.quantile\")\n+ if op == \"median\":\n+ args_maker = lambda: [a_rng(a_shape, a_dtype)]\n+ else:\nargs_maker = lambda: [a_rng(a_shape, a_dtype), q_rng(q_shape, q_dtype)]\nonp_fun = partial(getattr(onp, op), axis=axis, keepdims=keepdims)\nlnp_fun = partial(getattr(lnp, op), axis=axis, keepdims=keepdims)\n"
}
] | Python | Apache License 2.0 | google/jax | add numpy.median |
260,314 | 01.08.2019 16:20:08 | 14,400 | 45c5bd4fbace397d26fe37c1e417d0e158954421 | support ddof for var | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1083,8 +1083,6 @@ def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):\nif out is not None:\nraise ValueError(\"var does not support the `out` argument.\")\n- if ddof != 0:\n- raise NotImplementedError(\"Only implemented for ddof=0.\")\nif dtype is None:\nif (onp.issubdtype(_dtype(a), onp.bool_) or\nonp.issubdtype(_dtype(a), onp.integer)):\n@@ -1092,7 +1090,16 @@ def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):\ncentered = subtract(a, mean(a, axis, dtype=dtype, keepdims=True))\nif iscomplexobj(centered):\ncentered = lax.abs(centered)\n- return mean(lax.mul(centered, centered), axis, dtype=dtype, keepdims=keepdims)\n+\n+ if axis is None:\n+ normalizer = size(a)\n+ else:\n+ normalizer = onp.prod(onp.take(shape(a), axis))\n+ normalizer = normalizer - ddof\n+\n+ return lax.div(\n+ sum(lax.mul(centered, centered), axis, dtype=dtype, keepdims=keepdims),\n+ lax.convert_element_type(normalizer, dtype))\n@_wraps(onp.std)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1742,6 +1742,26 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ndef testIssue956(self):\nself.assertRaises(TypeError, lambda: lnp.ndarray((1, 1)))\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_dtype={}_axis={}_ddof={}_keepdims={}\"\n+ .format(shape, dtype, axis, ddof, keepdims),\n+ \"shape\": shape, \"dtype\": dtype, \"out_dtype\": out_dtype, \"axis\": axis,\n+ \"ddof\": ddof, \"keepdims\": keepdims, \"rng\": rng}\n+ for shape in [(5,), (10, 5)]\n+ for dtype in all_dtypes\n+ for out_dtype in number_dtypes\n+ for axis in [None, 0, -1]\n+ for ddof in [0, 1, 2]\n+ for keepdims in [False, True]\n+ for rng in [jtu.rand_default()]))\n+ def testVar(self, shape, dtype, out_dtype, axis, ddof, keepdims, rng):\n+ args_maker = self._GetArgsMaker(rng, [shape], [dtype])\n+ onp_fun = partial(onp.var, dtype=out_dtype, axis=axis, ddof=ddof, keepdims=keepdims)\n+ lnp_fun = partial(lnp.var, dtype=out_dtype, axis=axis, ddof=ddof, keepdims=keepdims)\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(\njtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_dtype={}_rowvar={}_ddof={}_bias={}\".format(\n"
}
] | Python | Apache License 2.0 | google/jax | support ddof for var |
260,314 | 01.08.2019 16:39:08 | 14,400 | 2836d03b5e5cfccc4cd547e299c8ed945ab8382a | add some nonlinearity | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -42,6 +42,8 @@ import jax.numpy as np\ndef relu(x): return np.maximum(x, 0.)\ndef softplus(x): return np.logaddexp(x, 0.)\ndef sigmoid(x): return 1. / (1. + np.exp(-x))\n+def elu(x): return np.where(x > 0, x, np.exp(x) - 1)\n+def leaky_relu(x): return np.where(x >= 0, x, 0.01 * x)\ndef logsoftmax(x, axis=-1):\n\"\"\"Apply log softmax to an array of logits, log-normalizing along an axis.\"\"\"\n@@ -196,6 +198,8 @@ Exp = elementwise(np.exp)\nLogSoftmax = elementwise(logsoftmax, axis=-1)\nSoftmax = elementwise(softmax, axis=-1)\nSoftplus = elementwise(softplus)\n+Elu = elementwise(elu)\n+LeakyRelu = elementwise(leaky_relu)\ndef _pooling_layer(reducer, init_val, rescaler=None):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/stax_test.py",
"new_path": "tests/stax_test.py",
"diff": "@@ -127,11 +127,13 @@ class StaxTest(jtu.JaxTestCase):\n_CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_input_shape={}\".format(input_shape),\n- \"input_shape\": input_shape}\n- for input_shape in [(2, 3), (2, 3, 4)]))\n- def testReluShape(self, input_shape):\n- init_fun, apply_fun = stax.Relu\n+ {\"testcase_name\": \"_input_shape={}_nonlinear={}\"\n+ .format(input_shape, nonlinear),\n+ \"input_shape\": input_shape, \"nonlinear\": nonlinear}\n+ for input_shape in [(2, 3), (2, 3, 4)]\n+ for nonlinear in [stax.Relu, stax.Elu, stax.LeakyRelu]))\n+ def testNonlinearShape(self, input_shape, nonlinear):\n+ init_fun, apply_fun = nonlinear\n_CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n@parameterized.named_parameters(jtu.cases_from_list(\n"
}
] | Python | Apache License 2.0 | google/jax | add some nonlinearity |
260,314 | 01.08.2019 16:41:06 | 14,400 | 688d77f4326cc04f0a358f070a228b06b02efdb8 | better test str message | [
{
"change_type": "MODIFY",
"old_path": "tests/stax_test.py",
"new_path": "tests/stax_test.py",
"diff": "@@ -131,9 +131,9 @@ class StaxTest(jtu.JaxTestCase):\n.format(input_shape, nonlinear),\n\"input_shape\": input_shape, \"nonlinear\": nonlinear}\nfor input_shape in [(2, 3), (2, 3, 4)]\n- for nonlinear in [stax.Relu, stax.Elu, stax.LeakyRelu]))\n+ for nonlinear in [\"Relu\", \"Elu\", \"LeakyRelu\"]))\ndef testNonlinearShape(self, input_shape, nonlinear):\n- init_fun, apply_fun = nonlinear\n+ init_fun, apply_fun = getattr(stax, nonlinear)\n_CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n@parameterized.named_parameters(jtu.cases_from_list(\n"
}
] | Python | Apache License 2.0 | google/jax | better test str message |
260,314 | 01.08.2019 17:11:31 | 14,400 | 5ffe2ae5dd8ef5625bbd0ad2c5c15fd3bc142964 | expose sigmoid too | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -198,6 +198,7 @@ Exp = elementwise(np.exp)\nLogSoftmax = elementwise(logsoftmax, axis=-1)\nSoftmax = elementwise(softmax, axis=-1)\nSoftplus = elementwise(softplus)\n+Sigmoid = elementwise(sigmoid)\nElu = elementwise(elu)\nLeakyRelu = elementwise(leaky_relu)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/stax_test.py",
"new_path": "tests/stax_test.py",
"diff": "@@ -131,7 +131,7 @@ class StaxTest(jtu.JaxTestCase):\n.format(input_shape, nonlinear),\n\"input_shape\": input_shape, \"nonlinear\": nonlinear}\nfor input_shape in [(2, 3), (2, 3, 4)]\n- for nonlinear in [\"Relu\", \"Elu\", \"LeakyRelu\"]))\n+ for nonlinear in [\"Relu\", \"Sigmoid\", \"Elu\", \"LeakyRelu\"]))\ndef testNonlinearShape(self, input_shape, nonlinear):\ninit_fun, apply_fun = getattr(stax, nonlinear)\n_CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n"
}
] | Python | Apache License 2.0 | google/jax | expose sigmoid too |
260,314 | 01.08.2019 19:12:03 | 14,400 | 7f4dc87a4c33a0b56631632b9b8b12c96db71514 | add multigammaln, entr | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -99,6 +99,27 @@ def xlog1py(x, y):\nreturn lax._safe_mul(x, lax.log1p(y))\n+@_wraps(osp_special.entr)\n+def entr(x):\n+ x, = _promote_args_like(osp_special.entr, x)\n+ return lax.select(lax.lt(x, _constant_like(x, 0)),\n+ lax.full_like(x, -onp.inf),\n+ lax.neg(xlogy(x, x)))\n+\n+\n+@_wraps(osp_special.multigammaln)\n+def multigammaln(a, d):\n+ a, = _promote_args_like(lambda a: osp_special.multigammaln(a, 1), a)\n+ d = lax.convert_element_type(d, lax.dtype(a))\n+ constant = lax.mul(lax.mul(lax.mul(_constant_like(a, 0.25), d),\n+ lax.sub(d, _constant_like(a, 1))),\n+ lax.log(_constant_like(a, onp.pi)))\n+ res = np.sum(gammaln(np.expand_dims(a, axis=-1) -\n+ lax.div(np.arange(d), _constant_like(a, 2))),\n+ axis=-1)\n+ return res + constant\n+\n+\n# Normal distributions\n# Functions \"ndtr\" and \"ndtri\" are derived from calculations made in:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_scipy_test.py",
"new_path": "tests/lax_scipy_test.py",
"diff": "@@ -68,6 +68,7 @@ JAX_SPECIAL_FUNCTION_RECORDS = [\nop_record(\"log_ndtr\", 1, float_dtypes, jtu.rand_default(), True),\nop_record(\"ndtri\", 1, float_dtypes, jtu.rand_uniform(0.05, 0.95), True),\nop_record(\"ndtr\", 1, float_dtypes, jtu.rand_default(), True),\n+ op_record(\"entr\", 1, float_dtypes, jtu.rand_default(), True),\n]\nCombosWithReplacement = itertools.combinations_with_replacement\n@@ -121,6 +122,24 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nif test_autodiff:\njtu.check_grads(lax_op, args, order=1, atol=1e-3, rtol=3e-3, eps=1e-3)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_inshape={}_d={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), d),\n+ \"rng\": jtu.rand_positive(), \"shape\": shape, \"dtype\": dtype, \"d\": d}\n+ for shape in all_shapes\n+ for dtype in float_dtypes\n+ for d in [1, 2, 5]))\n+ def testMultigammaln(self, rng, shape, dtype, d):\n+ def scipy_fun(a):\n+ return osp_special.multigammaln(a, d)\n+\n+ def lax_fun(a):\n+ return lsp_special.multigammaln(a, d)\n+\n+ args_maker = lambda: [rng(shape, dtype) + (d - 1) / 2.]\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n+\ndef testIssue980(self):\nx = onp.full((4,), -1e20, dtype=onp.float32)\nself.assertAllClose(onp.zeros((4,), dtype=onp.float32),\n"
}
] | Python | Apache License 2.0 | google/jax | add multigammaln, entr |
260,335 | 02.08.2019 11:26:17 | 25,200 | 3168006f4add95224082515a3e4fc84b3c42a144 | fix np.var dtype bug | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1097,9 +1097,9 @@ def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):\nnormalizer = onp.prod(onp.take(shape(a), axis))\nnormalizer = normalizer - ddof\n- return lax.div(\n- sum(lax.mul(centered, centered), axis, dtype=dtype, keepdims=keepdims),\n- lax.convert_element_type(normalizer, dtype))\n+ result = sum(lax.mul(centered, centered), axis,\n+ dtype=dtype, keepdims=keepdims)\n+ return lax.div(result, lax.convert_element_type(normalizer, _dtype(result)))\n@_wraps(onp.std)\n"
}
] | Python | Apache License 2.0 | google/jax | fix np.var dtype bug |
260,288 | 02.08.2019 16:42:17 | 25,200 | 444aced7912de6d4b7d91ed29ec164ebf7f52a76 | Fix pack_optimizer_state to correctly use tuples everywhere in the packed state and add a unit test to check round trip unpack/pack. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optimizers.py",
"new_path": "jax/experimental/optimizers.py",
"diff": "@@ -506,5 +506,6 @@ def pack_optimizer_state(marked_pytree):\nsentinels, tree_def = tree_flatten(marked_pytree)\nassert all(isinstance(s, JoinPoint) for s in sentinels)\nsubtrees = [s.subtree for s in sentinels]\n- packed_state, subtree_defs = unzip2(map(tree_flatten, subtrees))\n+ states_flat, subtree_defs = unzip2(map(tree_flatten, subtrees))\n+ packed_state = pack(map(pack, states_flat))\nreturn OptimizerState(packed_state, tree_def, subtree_defs)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/optimizers_test.py",
"new_path": "tests/optimizers_test.py",
"diff": "@@ -288,6 +288,13 @@ class OptimizerTests(jtu.JaxTestCase):\nJ2 = jacfwd(loss, argnums=(0,))(initial_params)\nself.assertAllClose(J1, J2, check_dtypes=True)\n+ def testUnpackPackRoundTrip(self):\n+ opt_init, _, _ = optimizers.momentum(0.1, mass=0.9)\n+ params = [{'w': onp.random.randn(1, 2), 'bias': onp.random.randn(2)}]\n+ expected = opt_init(params)\n+ ans = optimizers.pack_optimizer_state(\n+ optimizers.unpack_optimizer_state(expected))\n+ self.assertEqual(ans, expected)\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | Fix pack_optimizer_state to correctly use tuples everywhere in the packed state and add a unit test to check round trip unpack/pack. |
260,389 | 03.08.2019 21:27:06 | 25,200 | d0c9f453497a9a647df3b7710b8dc732bac3058a | fix jax.numpy reduction init_val for bools | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3255,7 +3255,7 @@ def _reduction_computation(c, jaxpr, consts, init_value):\nreduce_p = standard_primitive(_reduce_shape_rule, _input_dtype, 'reduce',\n_reduce_translation_rule)\n-# batching.primitive_batchers[reduce_p] = _reduce_batch_rule # TODO(mattjj): test\n+batching.primitive_batchers[reduce_p] = _reduce_batch_rule\ndef _reduce_sum_shape_rule(operand, axes, input_shape):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -991,6 +991,8 @@ def _reduction_dims(a, axis):\ndef _reduction_init_val(a, init_val):\na_dtype = xla_bridge.canonicalize_dtype(_dtype(a))\n+ if a_dtype == 'bool':\n+ return onp.array(init_val > 0, dtype=a_dtype)\ntry:\nreturn onp.array(init_val, dtype=a_dtype)\nexcept OverflowError:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1040,6 +1040,7 @@ class LaxTest(jtu.JaxTestCase):\nfor init_val, op, dtypes in [\n(0, lax.add, default_dtypes),\n(1, lax.mul, default_dtypes),\n+ (0, lax.max, all_dtypes), # non-monoidal\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]), # TODO fails\n@@ -2591,14 +2592,15 @@ class LaxVmapTest(jtu.JaxTestCase):\nself._CheckBatching(op, 5, bdims, (shape,), dtype, rng)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_op={}_inshape={}_reducedims={}_bdims={}\"\n+ {\"testcase_name\": \"_op={}_inshape={}_reducedims={}_initval={}_bdims={}\"\n.format(op.__name__, jtu.format_shape_dtype_string(shape, dtype), dims,\n- bdims),\n+ init_val, bdims),\n\"op\": op, \"init_val\": init_val, \"shape\": shape, \"dtype\": dtype,\n\"dims\": dims, \"bdims\": bdims, \"rng\": rng}\nfor init_val, op, dtypes in [\n(0, lax.add, default_dtypes),\n(1, lax.mul, default_dtypes),\n+ (0, lax.max, all_dtypes), # non-monoidal\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"
}
] | Python | Apache License 2.0 | google/jax | fix jax.numpy reduction init_val for bools |
260,299 | 06.08.2019 11:55:59 | -3,600 | 45e52b8f3fcef719e692d275ac05c970ced06351 | Fix ks test and rm randint ks test | [
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -51,8 +51,7 @@ class LaxRandomTest(jtu.JaxTestCase):\ndef _CheckKolmogorovSmirnovCDF(self, samples, cdf):\nfail_prob = 0.01 # conservative bound on statistical fail prob by Kolmo CDF\n- statistic = scipy.stats.kstest(samples, cdf).statistic\n- self.assertLess(1. - scipy.special.kolmogorov(statistic), fail_prob)\n+ self.assertGreater(scipy.stats.kstest(samples, cdf).pvalue, fail_prob)\ndef _CheckChiSquared(self, samples, pmf):\nalpha = 0.01 # significance level, threshold for p-value\n@@ -128,7 +127,6 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor samples in [uncompiled_samples, compiled_samples]:\nself.assertTrue(onp.all(lo <= samples))\nself.assertTrue(onp.all(samples < hi))\n- self._CheckKolmogorovSmirnovCDF(samples, scipy.stats.randint(lo, hi).cdf)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}\".format(dtype), \"dtype\": onp.dtype(dtype).name}\n"
}
] | Python | Apache License 2.0 | google/jax | Fix ks test and rm randint ks test |
260,299 | 06.08.2019 12:19:05 | -3,600 | f351dedbb7b3ade9252ec7096c7c8012cc536aba | Add logistic distribution to jax.random | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -35,6 +35,7 @@ from .api import custom_transforms, defjvp, jit, vmap\nfrom .numpy.lax_numpy import _constant_like, asarray\nfrom jax.lib import xla_bridge\nfrom jax import core\n+from jax.scipy.special import logit\ndef PRNGKey(seed):\n@@ -787,6 +788,28 @@ def _laplace(key, shape, dtype):\nreturn lax.mul(lax.sign(u), lax.log1p(lax.neg(lax.abs(u))))\n+def logistic(key, shape=(), dtype=onp.float64):\n+ \"\"\"Sample logistic random values with given shape and float dtype.\n+\n+ Args:\n+ key: a PRNGKey used as the random key.\n+ shape: optional, a tuple of nonnegative integers representing the shape\n+ (default scalar).\n+ dtype: optional, a float dtype for the returned values (default float64 if\n+ jax_enable_x64 is true, otherwise float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ dtype = xla_bridge.canonicalize_dtype(dtype)\n+ return _logistic(key, shape, dtype)\n+\n+@partial(jit, static_argnums=(1, 2))\n+def _logistic(key, shape, dtype):\n+ _check_shape(\"logistic\", shape)\n+ return logit(uniform(key, shape, dtype))\n+\n+\ndef pareto(key, b, shape=(), dtype=onp.float64):\n\"\"\"Sample Pareto random values with given shape and float dtype.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -312,6 +312,20 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor samples in [uncompiled_samples, compiled_samples]:\nself._CheckKolmogorovSmirnovCDF(samples, scipy.stats.laplace().cdf)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}\".format(dtype), \"dtype\": onp.dtype(dtype).name}\n+ for dtype in [onp.float32, onp.float64]))\n+ def testLogistic(self, dtype):\n+ key = random.PRNGKey(0)\n+ rand = lambda key: random.logistic(key, (10000,), dtype)\n+ crand = api.jit(rand)\n+\n+ uncompiled_samples = rand(key)\n+ compiled_samples = crand(key)\n+\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ self._CheckKolmogorovSmirnovCDF(samples, scipy.stats.logistic().cdf)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_b={}_{}\".format(b, dtype),\n\"b\": b, \"dtype\": onp.dtype(dtype).name}\n"
}
] | Python | Apache License 2.0 | google/jax | Add logistic distribution to jax.random |
260,335 | 08.08.2019 08:59:44 | 25,200 | 873d8e4001f29ad15214e35ce1209cc989b19476 | compiled while_loop impl cf. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -79,11 +79,17 @@ def primitive_computation(prim, *shapes, **params):\nc = xb.make_computation_builder(\"primitive_computation\")\nplatform = xb.get_backend().platform\nxla_args = map(c.ParameterWithShape, shapes)\n- try:\n- rule = backend_specific_translations[platform].get(prim) or translations[prim]\n- except KeyError:\n- raise NotImplementedError(\"XLA translation rule for {} not found\".format(prim))\n+ if prim in backend_specific_translations[platform]:\n+ rule = backend_specific_translations[platform][prim]\nrule(c, *xla_args, **params) # return val set as a side-effect on c\n+ elif prim in translations:\n+ rule = translations[prim]\n+ rule(c, *xla_args, **params) # return val set as a side-effect on c\n+ elif prim in initial_style_translations:\n+ rule = initial_style_translations[prim]\n+ rule(c, AxisEnv(1, [], []), *xla_args, **params) # side-effect on c\n+ else:\n+ raise NotImplementedError(\"XLA translation rule for {} not found\".format(prim))\ntry:\nreturn c.Build()\nexcept RuntimeError as e:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -156,16 +156,6 @@ def while_loop(cond_fun, body_fun, init_val):\nreturn build_tree(out_tree(), out_flat)\n-def _while_loop_impl(init_val, cond_consts, body_consts, aval_out, cond_jaxpr,\n- body_jaxpr):\n- cond_fun = partial(core.eval_jaxpr, cond_jaxpr, cond_consts, ())\n- body_fun = partial(core.eval_jaxpr, body_jaxpr, body_consts, ())\n-\n- val = init_val\n- while cond_fun(val):\n- val = body_fun(val)\n- return val\n-\ndef _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@@ -261,7 +251,7 @@ def _jaxtupletree_select(pred, on_true, on_false):\nwhile_p = lax.Primitive('while')\n-while_p.def_impl(_while_loop_impl)\n+while_p.def_impl(partial(xla.apply_primitive, while_p))\nwhile_p.def_abstract_eval(_while_loop_abstract_eval)\nxla.initial_style_translations[while_p] = _while_loop_translation_rule\nbatching.primitive_batchers[while_p] = _while_loop_batching_rule\n"
}
] | Python | Apache License 2.0 | google/jax | compiled while_loop impl cf. #1131 #1130 #852 |
260,344 | 08.08.2019 19:42:59 | -10,800 | 442ce9701c0e1edbdd42082da20b47ce9343edc6 | update notes and comments in tutorial | [
{
"change_type": "MODIFY",
"old_path": "notebooks/score_matching.ipynb",
"new_path": "notebooks/score_matching.ipynb",
"diff": "\" net_params = get_params(opt_state)\\n\",\n\" loss = compute_loss(net_params, batch)\\n\",\n\" grads = jax.grad(compute_loss, argnums=0)(net_params, batch)\\n\",\n- \" return loss, opt_update(step_i, grads, opt_state)\"\n+ \" return loss, opt_update(step_i, grads, opt_state)\\n\",\n+ \"\\n\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"__Note__: we use `jax.jacfwd` since the input dimention is only 2\"\n]\n},\n{\n\"$$\\\\hat x_{t+1} := \\\\hat x_t + \\\\frac \\\\epsilon 2 \\\\nabla_{\\\\hat x_t} log p(\\\\hat x_t) + \\\\sqrt \\\\epsilon z_t, \\\\quad z_t \\\\sim N(0, I)$$\\n\",\n\"\\n\",\n\"\\n\",\n- \"Performing this update multiple times in an MCMC fashion is a special case of Langevin Dynamics. Under $\\\\epsilon \\\\rightarrow 0, t \\\\rightarrow \\\\inf$: $\\\\hat x_t$ converges to a sample from $p(x)$. You can find a more detailed explanation and a formal proof in [Welling et al. (2011)](https://www.ics.uci.edu/~welling/publications/papers/stoclangevin_v6.pdf). \\n\",\n+ \"Performing this update multiple times in an MCMC fashion is a special case of Langevin Dynamics. Under $\\\\epsilon \\\\rightarrow 0, t \\\\rightarrow \\\\inf$: $\\\\hat x_t$ converges to a sample from $p(x)$. You can find a more detailed explanation and a formal proof in [Welling et al. (2011)](https://www.ics.uci.edu/~welling/publications/papers/stoclangevin_v6.pdf) and further exploration of SGLD in [Teh et al. (2014)](https://arxiv.org/abs/1409.0578) and [Vollmer et al. (2015)](https://arxiv.org/abs/1501.00438).\\n\",\n\"\\n\",\n\"In practice, we can initialize $x_0$ from some initial guess (e.g. uniform distribution over data space) and $\\\\epsilon$ to some positive value. As the sampling progresses, we can anneal $\\\\epsilon$ it until we are satisfied with the samples. Okay, now let's go implement that :)\"\n]\n\" return loss, opt_update(step_i, grads, opt_state)\"\n]\n},\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"__Note:__ we compute Jacobian with `jax.jacfwd` (forward-mode differentiation) because the input dimension of the network is just 2. You can read more about autograd modes in jax [documentation](https://jax.readthedocs.io/en/latest/jax.html?highlight=jacfwd#jax.jacfwd) and on wikipedia [wiki](https://en.wikipedia.org/wiki/Automatic_differentiation)\"\n+ ]\n+ },\n{\n\"cell_type\": \"code\",\n\"execution_count\": 0,\n"
}
] | Python | Apache License 2.0 | google/jax | update notes and comments in tutorial |
260,344 | 08.08.2019 22:56:51 | -10,800 | 2fbe6daacd462c04b80e7799bf0e0fa241e30ce1 | fix: typo in collab link | [
{
"change_type": "MODIFY",
"old_path": "notebooks/README.md",
"new_path": "notebooks/README.md",
"diff": "@@ -27,7 +27,7 @@ Use the links below to open any of these for interactive exploration in colab.\n[Common_Gotchas_in_JAX]:https://colab.sandbox.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb\n[gufuncs]:https://colab.sandbox.google.com/github/google/jax/blob/master/notebooks/gufuncs.ipynb\n[maml]:https://colab.sandbox.google.com/github/google/jax/blob/master/notebooks/maml.ipynb\n-[gmegdd]:https://colab.sandbox.google.com/github/google/jax/blob/master/notebooks/score-matching.ipynb\n+[gmegdd]:https://colab.sandbox.google.com/github/google/jax/blob/master/notebooks/score_matching.ipynb\n[vmapped log-probs]:https://colab.sandbox.google.com/github/google/jax/blob/master/notebooks/vmapped%20log-probs.ipynb\n[neural_network_with_tfds_data]:https://colab.sandbox.google.com/github/google/jax/blob/master/notebooks/neural_network_with_tfds_data.ipynb\n[neural_network_and_data_loading]:https://colab.sandbox.google.com/github/google/jax/blob/master/notebooks/neural_network_and_data_loading.ipynb\n"
}
] | Python | Apache License 2.0 | google/jax | fix: typo in collab link |
260,344 | 08.08.2019 23:09:57 | -10,800 | 0b22d4db20e74161030b86494d6b7989e5a3c5cc | update colab link inside tutorial notebook | [
{
"change_type": "MODIFY",
"old_path": "notebooks/score_matching.ipynb",
"new_path": "notebooks/score_matching.ipynb",
"diff": "\"source\": [\n\"### Score Matching with JAX\\n\",\n\"\\n\",\n- \"[](https://colab.research.google.com/gist/deniskamazur/2ea41beeab7895166393f74ddd16235f/score_matching_jax.ipynb)\\n\",\n+ \"[](https://colab.sandbox.google.com/github/google/jax/blob/master/notebooks/score_matching.ipynb)\\n\",\n\"\\n\",\n\"In this notebook we'll implement __Generative Modeling by Estimating Gradients of the Data Distribution__ [[arxiv]](https://arxiv.org/abs/1907.05600).\\n\",\n\"\\n\",\n"
}
] | Python | Apache License 2.0 | google/jax | update colab link inside tutorial notebook |
260,565 | 08.08.2019 16:24:46 | 25,200 | d8271179b3372a6776cb792537a41cc14cdea7a6 | Fix documentation for jax.lax.ppermute | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -107,11 +107,11 @@ def ppermute(x, axis_name, perm):\n``axis_name``. Any two pairs should not have the same source index or the\nsame destination index. For each index of the axis ``axis_name`` that does\nnot correspond to a destination index in ``perm``, the corresponding\n- values in ``x`` are filled with zeros of the appropriate type.\n+ values in the result are filled with zeros of the appropriate type.\nReturns:\n- An array with the same shape as ``x`` representing the result of an\n- all-reduce min along the axis ``axis_name``.\n+ An array with the same shape as ``x`` with slices along the axis\n+ ``axis_name`` gathered from ``x`` according to the permutation ``perm``.\n\"\"\"\nreturn ppermute_p.bind(x, axis_name=axis_name, perm=perm)\n"
}
] | Python | Apache License 2.0 | google/jax | Fix documentation for jax.lax.ppermute |
260,646 | 09.08.2019 20:31:43 | 0 | 5887fe3d413fed1ae58e5e601ed2bc57ebe349cc | Add adaptive-step ODE solver and VJP calculation with JAX control flow operators for fast compilation | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/odeint.py",
"diff": "+\"\"\"JAX-based Dormand-Prince ODE integration with adaptive stepsize.\n+\n+Integrate systems of ordinary differential equations (ODEs) using the JAX\n+autograd/diff library and the Dormand-Prince method for adaptive integration\n+stepsize calculation. Provides improved integration accuracy over fixed\n+stepsize integration methods.\n+\"\"\"\n+\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+import functools\n+import jax\n+from jax.config import config\n+from jax.flatten_util import ravel_pytree\n+import jax.lax\n+import jax.numpy as np\n+import jax.ops\n+import numpy as onp\n+import scipy.integrate as osp_integrate\n+config.update('jax_enable_x64', True)\n+\n+\n+# Dopri5 Butcher tableaux\n+alpha = [1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1.]\n+beta = [onp.array([1 / 5]),\n+ onp.array([3 / 40, 9 / 40]),\n+ onp.array([44 / 45, -56 / 15, 32 / 9]),\n+ onp.array([19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729]),\n+ onp.array([9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176,\n+ -5103 / 18656]),\n+ onp.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84]),]\n+c_sol = onp.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84,\n+ 0])\n+c_error = onp.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085,\n+ 125 / 192 - 451 / 720, -2187 / 6784 - -12231 / 42400,\n+ 11 / 84 - 649 / 6300, -1. / 60.,])\n+dps_c_mid = onp.array([\n+ 6025192743 / 30085553152 / 2, 0, 51252292925 / 65400821598 / 2,\n+ -2691868925 / 45128329728 / 2, 187940372067 / 1594534317056 / 2,\n+ -1776094331 / 19743644256 / 2, 11237099 / 235043384 / 2])\n+\n+\n+@jax.jit\n+def interp_fit_dopri(y0, y1, k, dt):\n+ # Fit a polynomial to the results of a Runge-Kutta step.\n+ y_mid = y0 + dt * np.dot(dps_c_mid, k)\n+ return np.array(fit_4th_order_polynomial(y0, y1, y_mid, k[0], k[-1], dt))\n+\n+\n+@jax.jit\n+def fit_4th_order_polynomial(y0, y1, y_mid, dy0, dy1, dt):\n+ \"\"\"Fit fourth order polynomial over function interval.\n+\n+ Args:\n+ y0: function value at the start of the interval.\n+ y1: function value at the end of the interval.\n+ y_mid: function value at the mid-point of the interval.\n+ dy0: derivative value at the start of the interval.\n+ dy1: derivative value at the end of the interval.\n+ dt: width of the interval.\n+ Returns:\n+ Coefficients `[a, b, c, d, e]` for the polynomial\n+ p = a * x ** 4 + b * x ** 3 + c * x ** 2 + d * x + e\n+ \"\"\"\n+ v = np.stack([dy0, dy1, y0, y1, y_mid])\n+ a = np.dot(np.hstack([-2. * dt, 2. * dt, np.array([-8., -8., 16.])]), v)\n+ b = np.dot(np.hstack([5. * dt, -3. * dt, np.array([18., 14., -32.])]), v)\n+ c = np.dot(np.hstack([-4. * dt, dt, np.array([-11., -5., 16.])]), v)\n+ d = dt * dy0\n+ e = y0\n+ return a, b, c, d, e\n+\n+\n+@functools.partial(jax.jit, static_argnums=(0,))\n+def initial_step_size(fun, t0, y0, order, rtol, atol, f0):\n+ \"\"\"Empirically choose initial step size.\n+\n+ Args:\n+ fun: Function to evaluate like `func(y, t)` to compute the time\n+ derivative of `y`.\n+ t0: initial time.\n+ y0: initial value for the state.\n+ order: order of interpolation\n+ rtol: relative local error tolerance for solver.\n+ atol: absolute local error tolerance for solver.\n+ f0: initial value for the derivative, computed from `func(t0, y0)`.\n+ Returns:\n+ Initial step size for odeint algorithm.\n+\n+ Algorithm from:\n+ E. Hairer, S. P. Norsett G. Wanner,\n+ Solving Ordinary Differential Equations I: Nonstiff Problems, Sec. II.4.\n+ \"\"\"\n+ scale = atol + np.abs(y0) * rtol\n+ d0 = np.linalg.norm(y0 / scale)\n+ d1 = np.linalg.norm(f0 / scale)\n+ order_pow = (1. / (order + 1.))\n+\n+ h0 = jax.lax.cond(np.any(np.asarray([d0 < 1e-5, d1 < 1e-5])),\n+ 1e-6,\n+ lambda x: x,\n+ 0.01 * d0 / d1,\n+ lambda x: x)\n+\n+ y1 = y0 + h0 * f0\n+ f1 = fun(y1, t0 + h0)\n+ d2 = (np.linalg.norm(f1 - f0) / scale) / h0\n+\n+ h1 = jax.lax.cond(np.all(np.asarray([d0 <= 1e-15, d1 < 1e-15])),\n+ np.maximum(1e-6, h0 * 1e-3),\n+ lambda x: x,\n+ # order is always 4\n+ (0.01 / np.max(d1 + d2))**order_pow,\n+ lambda x: x)\n+\n+ return np.minimum(100. * h0, h1)\n+\n+\n+@functools.partial(jax.jit, static_argnums=(0,))\n+def runge_kutta_step(func, y0, f0, t0, dt):\n+ \"\"\"Take an arbitrary Runge-Kutta step and estimate error.\n+\n+ Args:\n+ func: Function to evaluate like `func(y, t)` to compute the time\n+ derivative of `y`.\n+ y0: initial value for the state.\n+ f0: initial value for the derivative, computed from `func(t0, y0)`.\n+ t0: initial time.\n+ dt: time step.\n+ alpha, beta, c: Butcher tableau describing how to take the Runge-Kutta\n+ step.\n+\n+ Returns:\n+ y1: estimated function at t1 = t0 + dt\n+ f1: derivative of the state at t1\n+ y1_error: estimated error at t1\n+ k: list of Runge-Kutta coefficients `k` used for calculating these terms.\n+ \"\"\"\n+ k = np.array([f0])\n+ for alpha_i, beta_i in zip(alpha, beta):\n+ ti = t0 + dt * alpha_i\n+ yi = y0 + dt * np.dot(k.T, beta_i)\n+ ft = func(yi, ti)\n+ k = np.append(k, np.array([ft]), axis=0)\n+\n+ y1 = dt * np.dot(c_sol, k) + y0\n+ y1_error = dt * np.dot(c_error, k)\n+ f1 = k[-1]\n+ return y1, f1, y1_error, k\n+\n+\n+@jax.jit\n+def error_ratio(error_estimate, rtol, atol, y0, y1):\n+ err_tol = atol + rtol * np.maximum(np.abs(y0), np.abs(y1))\n+ err_ratio = error_estimate / err_tol\n+ return np.mean(err_ratio**2)\n+\n+\n+@jax.jit\n+def optimal_step_size(last_step,\n+ mean_error_ratio,\n+ safety=0.9,\n+ ifactor=10.0,\n+ dfactor=0.2,\n+ order=5.0):\n+ \"\"\"Compute optimal Runge-Kutta stepsize.\"\"\"\n+ mean_error_ratio = np.max(mean_error_ratio)\n+ dfactor = jax.lax.cond(mean_error_ratio < 1,\n+ 1.0,\n+ lambda x: x,\n+ dfactor,\n+ lambda x: x)\n+\n+ err_ratio = np.sqrt(mean_error_ratio)\n+ factor = np.maximum(1.0 / ifactor,\n+ np.minimum(err_ratio**(1.0 / order) / safety,\n+ 1.0 / dfactor))\n+ return jax.lax.cond(mean_error_ratio == 0,\n+ last_step * ifactor,\n+ lambda x: x,\n+ last_step / factor,\n+ lambda x: x)\n+\n+\n+@functools.partial(jax.jit, static_argnums=(0, 1))\n+def odeint(ofunc, args, y0, t, rtol=1.4e-8, atol=1.4e-8):\n+ \"\"\"Adaptive stepsize (Dormand-Prince) Runge-Kutta odeint implementation.\n+\n+ Args:\n+ ofunc: Function to evaluate `yt = ofunc(y, t, *args)` that\n+ returns the time derivative of `y`.\n+ args: Additional arguments to `ofunc`.\n+ y0: initial value for the state.\n+ t: Timespan for `ofunc` evaluation like `np.linspace(0., 10., 101)`.\n+ rtol: Relative local error tolerance for solver.\n+ atol: Absolute local error tolerance for solver.\n+ Returns:\n+ Integrated system values at each timepoint.\n+ \"\"\"\n+ @functools.partial(jax.jit, static_argnums=(0,))\n+ def _fori_body_fun(func, i, val, rtol=1.4e-8, atol=1.4e-8):\n+ \"\"\"Internal fori_loop body to interpolate an integral at each timestep.\"\"\"\n+ t, cur_y, cur_f, cur_t, dt, last_t, interp_coeff, solution = val\n+ cur_y, cur_f, cur_t, dt, last_t, interp_coeff = jax.lax.while_loop(\n+ lambda x: x[2] < t[i],\n+ functools.partial(_while_body_fun, func, rtol=rtol, atol=atol),\n+ (cur_y, cur_f, cur_t, dt, last_t, interp_coeff))\n+\n+ relative_output_time = (t[i] - last_t) / (cur_t - last_t)\n+ out_x = np.polyval(interp_coeff, relative_output_time)\n+\n+ return (t, cur_y, cur_f, cur_t, dt, last_t, interp_coeff,\n+ jax.ops.index_update(solution,\n+ jax.ops.index[i, :],\n+ out_x))\n+\n+ @functools.partial(jax.jit, static_argnums=(0,))\n+ def _while_body_fun(func, x, atol=atol, rtol=rtol):\n+ \"\"\"Internal while_loop body to determine interpolation coefficients.\"\"\"\n+ cur_y, cur_f, cur_t, dt, last_t, interp_coeff = x\n+ next_t = cur_t + dt\n+ next_y, next_f, next_y_error, k = runge_kutta_step(\n+ func, cur_y, cur_f, cur_t, dt)\n+ error_ratios = error_ratio(next_y_error, rtol, atol, cur_y, next_y)\n+ new_interp_coeff = interp_fit_dopri(cur_y, next_y, k, dt)\n+ dt = optimal_step_size(dt, error_ratios)\n+ return jax.lax.cond(np.all(error_ratios <= 1.),\n+ (next_y, next_f, next_t, dt, cur_t, new_interp_coeff),\n+ lambda x: x,\n+ (cur_y, cur_f, cur_t, dt, last_t, interp_coeff),\n+ lambda x: x)\n+\n+ func = lambda y, t: ofunc(y, t, *args)\n+ f0 = func(y0, t[0])\n+ dt = initial_step_size(func, t[0], y0, 4, rtol, atol, f0)\n+ interp_coeff = np.array([y0] * 5)\n+\n+ return jax.lax.fori_loop(1,\n+ t.shape[0],\n+ functools.partial(_fori_body_fun, func),\n+ (t, y0, f0, t[0], dt, t[0], interp_coeff,\n+ jax.ops.index_update(\n+ np.zeros((t.shape[0], y0.shape[0])),\n+ jax.ops.index[0, :],\n+ y0)))[-1]\n+\n+\n+def grad_odeint(ofunc, args):\n+ \"\"\"Return a function that calculates `vjp(odeint(func(y, t, args))`.\n+\n+ Args:\n+ ofunc: Function `ydot = ofunc(y, t, *args)` to compute the time\n+ derivative of `y`.\n+ args: Additional arguments to `ofunc`.\n+\n+ Returns:\n+ VJP function `vjp = vjp_all(g, yt, t)` where `yt = ofunc(y, t, *args)`\n+ and g is used for VJP calculation. To evaluate the gradient w/ the VJP,\n+ supply `g = np.ones_like(yt)`.\n+ \"\"\"\n+ flat_args, unravel_args = ravel_pytree(args)\n+ flat_func = lambda y, t, flat_args: ofunc(y, t, *unravel_args(flat_args))\n+\n+ @jax.jit\n+ def aug_dynamics(augmented_state, t):\n+ \"\"\"Original system augmented with vjp_y, vjp_t and vjp_args.\"\"\"\n+ D = int(np.floor_divide(\n+ augmented_state.shape[0] - flat_args.shape[0] - 1, 2))\n+ y = augmented_state[:D]\n+ adjoint = augmented_state[D:2*D]\n+ dy_dt, vjpfun = jax.vjp(flat_func, y, t, flat_args)\n+ return np.hstack([np.ravel(dy_dt), np.hstack(vjpfun(-adjoint))])\n+\n+ rev_aug_dynamics = lambda y, t: -aug_dynamics(y, -t)\n+\n+ @jax.jit\n+ def _fori_loop_func(i, val):\n+ \"\"\"fori_loop function for VJP calculation.\"\"\"\n+ scan_yt, scan_t, scan_tarray, scan_gi, vjp_y, vjp_t0, vjp_args, time_vjp_list = val\n+ this_yt = scan_yt[i, :]\n+ this_t = scan_t[i]\n+ this_tarray = scan_tarray[i, :]\n+ this_gi = scan_gi[i, :]\n+ this_gim1 = scan_gi[i-1, :]\n+ D = this_yt.shape[0]\n+ vjp_cur_t = np.dot(flat_func(this_yt, this_t, flat_args), this_gi)\n+ vjp_t0 = vjp_t0 - vjp_cur_t\n+ # Run augmented system backwards to the previous observation.\n+ aug_y0 = np.hstack((this_yt, vjp_y, vjp_t0, vjp_args))\n+ aug_ans = odeint(rev_aug_dynamics, (), aug_y0, this_tarray)\n+ vjp_y = aug_ans[1][D:2*D] + this_gim1\n+ vjp_t0 = aug_ans[1][2*D]\n+ vjp_args = aug_ans[1][2*D+1:]\n+ time_vjp_list = jax.ops.index_update(time_vjp_list, i, vjp_cur_t)\n+ return scan_yt, scan_t, scan_tarray, scan_gi, vjp_y, vjp_t0, vjp_args, time_vjp_list\n+\n+ @jax.jit\n+ def vjp_all_scan(g, yt, t):\n+ \"\"\"Calculate the VJP g * Jac(odeint(ofunc(yt, t, *args), t).\"\"\"\n+ scan_yt = yt[-1:0:-1, :]\n+ scan_t = t[-1:0:-1]\n+ scan_tarray = -np.array([t[-1:0:-1], t[-2::-1]]).T\n+ scan_gi = g[-1:0:-1, :]\n+\n+ vjp_y = scan_gi[-1, :]\n+ vjp_t0 = 0.\n+ vjp_args = np.zeros_like(flat_args)\n+ time_vjp_list = np.zeros_like(t)\n+\n+ result = jax.lax.fori_loop(0,\n+ scan_t.shape[0],\n+ _fori_loop_func,\n+ (scan_yt,\n+ scan_t,\n+ scan_tarray,\n+ scan_gi,\n+ vjp_y,\n+ vjp_t0,\n+ vjp_args,\n+ time_vjp_list))\n+\n+ time_vjp_list = jax.ops.index_update(result[-1], -1, result[-3])\n+ vjp_times = np.hstack(time_vjp_list)[::-1]\n+ return None, result[-4], vjp_times, unravel_args(result[-2])\n+\n+ return jax.jit(vjp_all_scan)\n+\n+\n+def test_grad_odeint():\n+ \"\"\"Compare numerical and exact differentiation of a simple odeint.\"\"\"\n+ def nd(f, x, eps=0.0001):\n+ flat_x, unravel = ravel_pytree(x)\n+ dim = len(flat_x)\n+ g = onp.zeros_like(flat_x)\n+ for i in range(dim):\n+ d = onp.zeros_like(flat_x)\n+ d[i] = eps\n+ g[i] = (f(unravel(flat_x + d)) - f(unravel(flat_x - d))) / (2.0 * eps)\n+ return g\n+\n+ def f(y, t, arg1, arg2):\n+ return -np.sqrt(t) - y + arg1 - np.mean((y + arg2)**2)\n+\n+ def onearg_odeint(args):\n+ return np.sum(\n+ odeint(f, args[2], args[0], args[1], atol=1e-8, rtol=1e-8))\n+\n+ dim = 10\n+ t0 = 0.1\n+ t1 = 0.2\n+ y0 = np.linspace(0.1, 0.9, dim)\n+ fargs = (0.1, 0.2)\n+\n+ numerical_grad = nd(onearg_odeint, (y0, np.array([t0, t1]), fargs))\n+ ys = odeint(f, fargs, y0, np.array([t0, t1]), atol=1e-8, rtol=1e-8)\n+ ode_vjp = grad_odeint(f, fargs)\n+ g = np.ones_like(ys)\n+ exact_grad, _ = ravel_pytree(ode_vjp(g, ys, np.array([t0, t1])))\n+\n+ assert np.allclose(numerical_grad, exact_grad)\n+\n+\n+if __name__ == '__main__':\n+\n+ test_grad_odeint()\n+\n"
}
] | Python | Apache License 2.0 | google/jax | Add adaptive-step ODE solver and VJP calculation with JAX control flow operators for fast compilation |
260,646 | 09.08.2019 21:19:45 | 0 | 156b3c86e5c3d3be8c6698d3feaf1a844fde2e40 | Cleaning up variable & function names | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/odeint.py",
"new_path": "jax/experimental/odeint.py",
"diff": "@@ -276,14 +276,14 @@ def grad_odeint(ofunc, args):\nrev_aug_dynamics = lambda y, t: -aug_dynamics(y, -t)\n@jax.jit\n- def _fori_loop_func(i, val):\n+ def _fori_body_fun(i, val):\n\"\"\"fori_loop function for VJP calculation.\"\"\"\n- scan_yt, scan_t, scan_tarray, scan_gi, vjp_y, vjp_t0, vjp_args, time_vjp_list = val\n- this_yt = scan_yt[i, :]\n- this_t = scan_t[i]\n- this_tarray = scan_tarray[i, :]\n- this_gi = scan_gi[i, :]\n- this_gim1 = scan_gi[i-1, :]\n+ rev_yt, rev_t, rev_tarray, rev_gi, vjp_y, vjp_t0, vjp_args, time_vjp_list = val\n+ this_yt = rev_yt[i, :]\n+ this_t = rev_t[i]\n+ this_tarray = rev_tarray[i, :]\n+ this_gi = rev_gi[i, :]\n+ this_gim1 = rev_gi[i-1, :]\nD = this_yt.shape[0]\nvjp_cur_t = np.dot(flat_func(this_yt, this_t, flat_args), this_gi)\nvjp_t0 = vjp_t0 - vjp_cur_t\n@@ -294,28 +294,28 @@ def grad_odeint(ofunc, args):\nvjp_t0 = aug_ans[1][2*D]\nvjp_args = aug_ans[1][2*D+1:]\ntime_vjp_list = jax.ops.index_update(time_vjp_list, i, vjp_cur_t)\n- return scan_yt, scan_t, scan_tarray, scan_gi, vjp_y, vjp_t0, vjp_args, time_vjp_list\n+ return rev_yt, rev_t, rev_tarray, rev_gi, vjp_y, vjp_t0, vjp_args, time_vjp_list\n@jax.jit\n- def vjp_all_scan(g, yt, t):\n+ def vjp_all(g, yt, t):\n\"\"\"Calculate the VJP g * Jac(odeint(ofunc(yt, t, *args), t).\"\"\"\n- scan_yt = yt[-1:0:-1, :]\n- scan_t = t[-1:0:-1]\n- scan_tarray = -np.array([t[-1:0:-1], t[-2::-1]]).T\n- scan_gi = g[-1:0:-1, :]\n+ rev_yt = yt[-1:0:-1, :]\n+ rev_t = t[-1:0:-1]\n+ rev_tarray = -np.array([t[-1:0:-1], t[-2::-1]]).T\n+ rev_gi = g[-1:0:-1, :]\n- vjp_y = scan_gi[-1, :]\n+ vjp_y = rev_gi[-1, :]\nvjp_t0 = 0.\nvjp_args = np.zeros_like(flat_args)\ntime_vjp_list = np.zeros_like(t)\nresult = jax.lax.fori_loop(0,\n- scan_t.shape[0],\n- _fori_loop_func,\n- (scan_yt,\n- scan_t,\n- scan_tarray,\n- scan_gi,\n+ rev_t.shape[0],\n+ _fori_body_fun,\n+ (rev_yt,\n+ rev_t,\n+ rev_tarray,\n+ rev_gi,\nvjp_y,\nvjp_t0,\nvjp_args,\n@@ -325,7 +325,7 @@ def grad_odeint(ofunc, args):\nvjp_times = np.hstack(time_vjp_list)[::-1]\nreturn None, result[-4], vjp_times, unravel_args(result[-2])\n- return jax.jit(vjp_all_scan)\n+ return jax.jit(vjp_all)\ndef test_grad_odeint():\n"
}
] | Python | Apache License 2.0 | google/jax | Cleaning up variable & function names |
260,646 | 12.08.2019 17:56:46 | 0 | a7323ec5df415a7d245aad86901b058046339ecb | Restored license header + plotting example, added benchmark | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ode.py",
"new_path": "jax/experimental/ode.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\"\"\"JAX-based Dormand-Prince ODE integration with adaptive stepsize.\nIntegrate systems of ordinary differential equations (ODEs) using the JAX\n@@ -17,8 +31,11 @@ from jax.flatten_util import ravel_pytree\nimport jax.lax\nimport jax.numpy as np\nimport jax.ops\n+import matplotlib.pyplot as plt\nimport numpy as onp\nimport scipy.integrate as osp_integrate\n+import time\n+\nconfig.update('jax_enable_x64', True)\n@@ -362,6 +379,82 @@ def test_grad_odeint():\nassert np.allclose(numerical_grad, exact_grad)\n+def plot_gradient_field(ax, func, xlimits, ylimits, numticks=30):\n+ \"\"\"Plot the gradient field of `func` on `ax`.\"\"\"\n+ x = np.linspace(*xlimits, num=numticks)\n+ y = np.linspace(*ylimits, num=numticks)\n+ x_mesh, y_mesh = np.meshgrid(x, y)\n+ zs = jax.vmap(func)(y_mesh.ravel(), x_mesh.ravel())\n+ z_mesh = zs.reshape(x_mesh.shape)\n+ ax.quiver(x_mesh, y_mesh, np.ones(z_mesh.shape), z_mesh)\n+ ax.set_xlim(xlimits)\n+ ax.set_ylim(ylimits)\n+\n+\n+def plot_demo():\n+ \"\"\"Demo plot of simple ode integration and gradient field.\"\"\"\n+ def f(y, t, arg1, arg2):\n+ return y - np.sin(t) - np.cos(t) * arg1 + arg2\n+\n+ t0 = 0.\n+ t1 = 5.0\n+ ts = np.linspace(t0, t1, 100)\n+ y0 = np.array([1.])\n+ fargs = (1.0, 0.0)\n+\n+ ys = odeint(f, fargs, y0, ts, atol=0.001, rtol=0.001)\n+\n+ # Set up figure.\n+ fig = plt.figure(figsize=(8, 6), facecolor='white')\n+ ax = fig.add_subplot(111, frameon=False)\n+ f_no_args = lambda y, t: f(y, t, *fargs)\n+ plot_gradient_field(ax, f_no_args, xlimits=[t0, t1], ylimits=[-1.1, 1.1])\n+ ax.plot(ts, ys, 'g-')\n+ ax.set_xlabel('t')\n+ ax.set_ylabel('y')\n+ plt.show()\n+\n+\n+def pend(y, t, b, c):\n+ \"\"\"Simple pendulum system for odeint testing.\"\"\"\n+ del t\n+ theta, omega = y\n+ dydt = np.array([omega, -b*omega - c*np.sin(theta)])\n+ return dydt\n+\n+\n+def benchmark_odeint(fun, args, y0, tspace):\n+ \"\"\"Time performance of JAX odeint method against scipy.integrate.odeint.\"\"\"\n+ n_trials = 10\n+ for k in range(n_trials):\n+ start = time.time()\n+ scipy_result = osp_integrate.odeint(fun, y0, tspace, args)\n+ end = time.time()\n+ print(\n+ 'scipy odeint elapsed time ({} of {}): {}'.format(k+1, n_trials, end-start))\n+ for k in range(n_trials):\n+ start = time.time()\n+ jax_result = odeint(fun,\n+ args,\n+ np.asarray(y0),\n+ np.asarray(tspace))\n+ jax_result.block_until_ready()\n+ end = time.time()\n+ print(\n+ 'JAX odeint elapsed time ({} of {}): {}'.format(k+1, n_trials, end-start))\n+ print('norm(scipy result-jax result): {}'.format(\n+ np.linalg.norm(np.asarray(scipy_result) - jax_result)))\n+\n+ return scipy_result, jax_result\n+\n+\n+def pend_benchmark_odeint():\n+ _, _ = benchmark_odeint(pend,\n+ (0.25, 9.8),\n+ (onp.pi - 0.1, 0.0),\n+ onp.linspace(0., 10., 101))\n+\n+\nif __name__ == '__main__':\ntest_grad_odeint()\n"
}
] | Python | Apache License 2.0 | google/jax | Restored license header + plotting example, added benchmark |
260,646 | 12.08.2019 22:11:42 | 0 | 225c90b7e8e954e30aafbfa2f377e16061de6b7a | Convert tableaux & runge_kutta_step to JAX control flow, use np.where | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ode.py",
"new_path": "jax/experimental/ode.py",
"diff": "@@ -25,6 +25,8 @@ from __future__ import division\nfrom __future__ import print_function\nimport functools\n+import time\n+\nimport jax\nfrom jax.config import config\nfrom jax.flatten_util import ravel_pytree\n@@ -34,26 +36,25 @@ import jax.ops\nimport matplotlib.pyplot as plt\nimport numpy as onp\nimport scipy.integrate as osp_integrate\n-import time\nconfig.update('jax_enable_x64', True)\n# Dopri5 Butcher tableaux\n-alpha = [1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1.]\n-beta = [onp.array([1 / 5]),\n- onp.array([3 / 40, 9 / 40]),\n- onp.array([44 / 45, -56 / 15, 32 / 9]),\n- onp.array([19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729]),\n- onp.array([9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176,\n- -5103 / 18656]),\n- onp.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84]),]\n-c_sol = onp.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84,\n+alpha = np.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0])\n+beta = np.array(\n+ [[1 / 5, 0, 0, 0, 0, 0, 0],\n+ [3 / 40, 9 / 40, 0, 0, 0, 0, 0],\n+ [44 / 45, -56 / 15, 32 / 9, 0, 0, 0, 0],\n+ [19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729, 0, 0, 0],\n+ [9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656, 0, 0],\n+ [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0]])\n+c_sol = np.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84,\n0])\n-c_error = onp.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085,\n+c_error = np.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085,\n125 / 192 - 451 / 720, -2187 / 6784 - -12231 / 42400,\n- 11 / 84 - 649 / 6300, -1. / 60.,])\n-dps_c_mid = onp.array([\n+ 11 / 84 - 649 / 6300, -1. / 60.])\n+dps_c_mid = np.array([\n6025192743 / 30085553152 / 2, 0, 51252292925 / 65400821598 / 2,\n-2691868925 / 45128329728 / 2, 187940372067 / 1594534317056 / 2,\n-1776094331 / 19743644256 / 2, 11237099 / 235043384 / 2])\n@@ -115,22 +116,17 @@ def initial_step_size(fun, t0, y0, order, rtol, atol, f0):\nd1 = np.linalg.norm(f0 / scale)\norder_pow = (1. / (order + 1.))\n- h0 = jax.lax.cond(np.any(np.asarray([d0 < 1e-5, d1 < 1e-5])),\n+ h0 = np.where(np.any(np.asarray([d0 < 1e-5, d1 < 1e-5])),\n1e-6,\n- lambda x: x,\n- 0.01 * d0 / d1,\n- lambda x: x)\n+ 0.01 * d0 / d1)\ny1 = y0 + h0 * f0\nf1 = fun(y1, t0 + h0)\nd2 = (np.linalg.norm(f1 - f0) / scale) / h0\n- h1 = jax.lax.cond(np.all(np.asarray([d0 <= 1e-15, d1 < 1e-15])),\n+ h1 = np.where(np.all(np.asarray([d0 <= 1e-15, d1 < 1e-15])),\nnp.maximum(1e-6, h0 * 1e-3),\n- lambda x: x,\n- # order is always 4\n- (0.01 / np.max(d1 + d2))**order_pow,\n- lambda x: x)\n+ (0.01 / np.max(d1 + d2))**order_pow)\nreturn np.minimum(100. * h0, h1)\n@@ -155,12 +151,17 @@ def runge_kutta_step(func, y0, f0, t0, dt):\ny1_error: estimated error at t1\nk: list of Runge-Kutta coefficients `k` used for calculating these terms.\n\"\"\"\n- k = np.array([f0])\n- for alpha_i, beta_i in zip(alpha, beta):\n- ti = t0 + dt * alpha_i\n- yi = y0 + dt * np.dot(k.T, beta_i)\n+ def _fori_body_fun(i, val):\n+ ti = t0 + dt * alpha[i-1]\n+ yi = y0 + dt * np.dot(beta[i-1, :], val)\nft = func(yi, ti)\n- k = np.append(k, np.array([ft]), axis=0)\n+ return jax.ops.index_update(val, jax.ops.index[i, :], ft)\n+\n+ k = jax.lax.fori_loop(\n+ 1,\n+ 7,\n+ _fori_body_fun,\n+ jax.ops.index_update(np.zeros((7, f0.shape[0])), jax.ops.index[0, :], f0))\ny1 = dt * np.dot(c_sol, k) + y0\ny1_error = dt * np.dot(c_error, k)\n@@ -184,21 +185,17 @@ def optimal_step_size(last_step,\norder=5.0):\n\"\"\"Compute optimal Runge-Kutta stepsize.\"\"\"\nmean_error_ratio = np.max(mean_error_ratio)\n- dfactor = jax.lax.cond(mean_error_ratio < 1,\n+ dfactor = np.where(mean_error_ratio < 1,\n1.0,\n- lambda x: x,\n- dfactor,\n- lambda x: x)\n+ dfactor)\nerr_ratio = np.sqrt(mean_error_ratio)\nfactor = np.maximum(1.0 / ifactor,\nnp.minimum(err_ratio**(1.0 / order) / safety,\n1.0 / dfactor))\n- return jax.lax.cond(mean_error_ratio == 0,\n+ return np.where(mean_error_ratio == 0,\nlast_step * ifactor,\n- lambda x: x,\n- last_step / factor,\n- lambda x: x)\n+ last_step / factor,)\n@functools.partial(jax.jit, static_argnums=(0, 1))\n@@ -243,11 +240,15 @@ def odeint(ofunc, args, y0, t, rtol=1.4e-8, atol=1.4e-8):\nerror_ratios = error_ratio(next_y_error, rtol, atol, cur_y, next_y)\nnew_interp_coeff = interp_fit_dopri(cur_y, next_y, k, dt)\ndt = optimal_step_size(dt, error_ratios)\n- return jax.lax.cond(np.all(error_ratios <= 1.),\n- (next_y, next_f, next_t, dt, cur_t, new_interp_coeff),\n- lambda x: x,\n- (cur_y, cur_f, cur_t, dt, last_t, interp_coeff),\n- lambda x: x)\n+\n+ new_rav, unravel = ravel_pytree(\n+ (next_y, next_f, next_t, dt, cur_t, new_interp_coeff))\n+ old_rav, _ = ravel_pytree(\n+ (cur_y, cur_f, cur_t, dt, last_t, interp_coeff))\n+\n+ return unravel(np.where(np.all(error_ratios <= 1.),\n+ new_rav,\n+ old_rav))\nfunc = lambda y, t: ofunc(y, t, *args)\nf0 = func(y0, t[0])\n@@ -283,10 +284,10 @@ def grad_odeint(ofunc, args):\n@jax.jit\ndef aug_dynamics(augmented_state, t):\n\"\"\"Original system augmented with vjp_y, vjp_t and vjp_args.\"\"\"\n- D = int(np.floor_divide(\n+ state_len = int(np.floor_divide(\naugmented_state.shape[0] - flat_args.shape[0] - 1, 2))\n- y = augmented_state[:D]\n- adjoint = augmented_state[D:2*D]\n+ y = augmented_state[:state_len]\n+ adjoint = augmented_state[state_len:2*state_len]\ndy_dt, vjpfun = jax.vjp(flat_func, y, t, flat_args)\nreturn np.hstack([np.ravel(dy_dt), np.hstack(vjpfun(-adjoint))])\n@@ -301,15 +302,15 @@ def grad_odeint(ofunc, args):\nthis_tarray = rev_tarray[i, :]\nthis_gi = rev_gi[i, :]\nthis_gim1 = rev_gi[i-1, :]\n- D = this_yt.shape[0]\n+ state_len = this_yt.shape[0]\nvjp_cur_t = np.dot(flat_func(this_yt, this_t, flat_args), this_gi)\nvjp_t0 = vjp_t0 - vjp_cur_t\n# Run augmented system backwards to the previous observation.\naug_y0 = np.hstack((this_yt, vjp_y, vjp_t0, vjp_args))\naug_ans = odeint(rev_aug_dynamics, (), aug_y0, this_tarray)\n- vjp_y = aug_ans[1][D:2*D] + this_gim1\n- vjp_t0 = aug_ans[1][2*D]\n- vjp_args = aug_ans[1][2*D+1:]\n+ vjp_y = aug_ans[1][state_len:2*state_len] + this_gim1\n+ vjp_t0 = aug_ans[1][2*state_len]\n+ vjp_args = aug_ans[1][2*state_len+1:]\ntime_vjp_list = jax.ops.index_update(time_vjp_list, i, vjp_cur_t)\nreturn rev_yt, rev_t, rev_tarray, rev_gi, vjp_y, vjp_t0, vjp_args, time_vjp_list\n@@ -430,8 +431,8 @@ def benchmark_odeint(fun, args, y0, tspace):\nstart = time.time()\nscipy_result = osp_integrate.odeint(fun, y0, tspace, args)\nend = time.time()\n- print(\n- 'scipy odeint elapsed time ({} of {}): {}'.format(k+1, n_trials, end-start))\n+ print('scipy odeint elapsed time ({} of {}): {}'.format(\n+ k+1, n_trials, end-start))\nfor k in range(n_trials):\nstart = time.time()\njax_result = odeint(fun,\n@@ -440,8 +441,8 @@ def benchmark_odeint(fun, args, y0, tspace):\nnp.asarray(tspace))\njax_result.block_until_ready()\nend = time.time()\n- print(\n- 'JAX odeint elapsed time ({} of {}): {}'.format(k+1, n_trials, end-start))\n+ print('JAX odeint elapsed time ({} of {}): {}'.format(\n+ k+1, n_trials, end-start))\nprint('norm(scipy result-jax result): {}'.format(\nnp.linalg.norm(np.asarray(scipy_result) - jax_result)))\n"
}
] | Python | Apache License 2.0 | google/jax | Convert tableaux & runge_kutta_step to JAX control flow, use np.where |
260,335 | 12.08.2019 18:03:25 | 25,200 | 4a4304e08c103dc1adb20550cd9c1d55a6f784ac | make pmap read axis size from kwargs
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -711,7 +711,7 @@ def pmap(fun, axis_name=None):\n@wraps(fun)\ndef f_pmapped(*args, **kwargs):\n- axis_size = _pmap_axis_size(args)\n+ axis_size = _pmap_axis_size((args, kwargs))\nf = lu.wrap_init(fun)\nargs_flat, in_tree = tree_flatten((args, kwargs))\nflat_fun, out_tree = flatten_fun_leafout(f, in_tree)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -955,6 +955,14 @@ class BatchingTest(jtu.JaxTestCase):\nresult = vmap(f, (None, 0, None))(onp.zeros((10,)), onp.arange(10,), 1.)\nself.assertAllClose(result, onp.eye(10), check_dtypes=False)\n+ def testIssue1170(self):\n+ def f(index1, index2):\n+ return np.arange(36).reshape(6, 6)[index1, index2]\n+ g = jax.jit(jax.pmap(f))\n+ ans = g(index1=onp.asarray([1]), index2=onp.asarray([2]))\n+ expected = g(onp.asarray([1]), onp.asarray([2]))\n+ self.assertAllClose(ans, expected, check_dtypes=True)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | make pmap read axis size from kwargs
fixes #1170 |
260,335 | 13.08.2019 07:20:09 | 25,200 | 275bf9da6d29bb6b39e05c2a4886a6123d4ecddc | improve prng compile times with loop rolling
cf. | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -123,34 +123,29 @@ def threefry_2x32(keypair, count):\nelse:\nx = list(np.split(count.ravel(), 2))\n- rotations = onp.uint32([13, 15, 26, 6, 17, 29, 16, 24])\n+ rotations = asarray([13, 15, 26, 6, 17, 29, 16, 24], dtype=\"uint32\")\nks = [key1, key2, key1 ^ key2 ^ onp.uint32(0x1BD11BDA)]\nx[0] = x[0] + ks[0]\nx[1] = x[1] + ks[1]\n- for r in rotations[:4]:\n- x = apply_round(x, r)\n+ x = lax.fori_loop(0, 4, lambda i, x: apply_round(x, rotations[i]), x)\nx[0] = x[0] + ks[1]\nx[1] = x[1] + ks[2] + onp.uint32(1)\n- for r in rotations[4:]:\n- x = apply_round(x, r)\n+ x = lax.fori_loop(4, 8, lambda i, x: apply_round(x, rotations[i]), x)\nx[0] = x[0] + ks[2]\nx[1] = x[1] + ks[0] + onp.uint32(2)\n- for r in rotations[:4]:\n- x = apply_round(x, r)\n+ x = lax.fori_loop(0, 4, lambda i, x: apply_round(x, rotations[i]), x)\nx[0] = x[0] + ks[0]\nx[1] = x[1] + ks[1] + onp.uint32(3)\n- for r in rotations[4:]:\n- x = apply_round(x, r)\n+ x = lax.fori_loop(4, 8, lambda i, x: apply_round(x, rotations[i]), x)\nx[0] = x[0] + ks[1]\nx[1] = x[1] + ks[2] + onp.uint32(4)\n- for r in rotations[:4]:\n- x = apply_round(x, r)\n+ x = lax.fori_loop(0, 4, lambda i, x: apply_round(x, rotations[i]), x)\nx[0] = x[0] + ks[2]\nx[1] = x[1] + ks[0] + onp.uint32(5)\n"
}
] | Python | Apache License 2.0 | google/jax | improve prng compile times with loop rolling
cf. #1172 |
260,335 | 13.08.2019 09:43:44 | 25,200 | d857d3f595f387495b016b6b60de91ed9636af79 | improve prng compile times with outer-loop rolling | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -123,33 +123,19 @@ def threefry_2x32(keypair, count):\nelse:\nx = list(np.split(count.ravel(), 2))\n- rotations = asarray([13, 15, 26, 6, 17, 29, 16, 24], dtype=\"uint32\")\n- ks = [key1, key2, key1 ^ key2 ^ onp.uint32(0x1BD11BDA)]\n+ rotations = asarray([[13, 15, 26, 6], [17, 29, 16, 24]], dtype=\"uint32\")\n+ ks = asarray([key1, key2, key1 ^ key2 ^ onp.uint32(0x1BD11BDA)], dtype=\"uint32\")\n+ idxs = asarray([[1, 2], [2, 0], [0, 1], [1, 2], [2, 0]])\nx[0] = x[0] + ks[0]\nx[1] = x[1] + ks[1]\n- x = lax.fori_loop(0, 4, lambda i, x: apply_round(x, rotations[i]), x)\n- x[0] = x[0] + ks[1]\n- x[1] = x[1] + ks[2] + onp.uint32(1)\n-\n- x = lax.fori_loop(4, 8, lambda i, x: apply_round(x, rotations[i]), x)\n- x[0] = x[0] + ks[2]\n- x[1] = x[1] + ks[0] + onp.uint32(2)\n-\n- x = lax.fori_loop(0, 4, lambda i, x: apply_round(x, rotations[i]), x)\n- x[0] = x[0] + ks[0]\n- x[1] = x[1] + ks[1] + onp.uint32(3)\n-\n- x = lax.fori_loop(4, 8, lambda i, x: apply_round(x, rotations[i]), x)\n- x[0] = x[0] + ks[1]\n- x[1] = x[1] + ks[2] + onp.uint32(4)\n-\n- x = lax.fori_loop(0, 4, lambda i, x: apply_round(x, rotations[i]), x)\n- x[0] = x[0] + ks[2]\n- x[1] = x[1] + ks[0] + onp.uint32(5)\n-\n- out = np.concatenate(x)\n+ def step(i, x):\n+ for r in rotations[i % 2]:\n+ x = apply_round(x, r)\n+ i0, i1 = idxs[i]\n+ return [x[0] + ks[i0], x[1] + ks[i1] + asarray(i + 1, dtype=\"uint32\")]\n+ out = np.concatenate(lax.fori_loop(0, 5, step, x))\nassert out.dtype == onp.uint32\nreturn lax.reshape(out[:-1] if odd_size else out, count.shape)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -398,6 +398,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertEqual(onp.result_type(w), onp.float32)\ndef testNoOpByOpUnderHash(self):\n+ raise SkipTest() # TODO(mattjj): re-enable this test\ndef fail(): assert False\napply_primitive, xla.apply_primitive = xla.apply_primitive, fail\nout = random.threefry_2x32(onp.zeros(2, onp.uint32), onp.arange(10, dtype=onp.uint32))\n"
}
] | Python | Apache License 2.0 | google/jax | improve prng compile times with outer-loop rolling |
260,335 | 13.08.2019 11:30:24 | 25,200 | 75bb38e7418aa5203badea7d0bcf6afc1272a177 | address reviewer comments, no op-by-op in threefry | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -32,7 +32,7 @@ from . import lax\nfrom . import numpy as np\nfrom . import tree_util\nfrom .api import custom_transforms, defjvp, jit, vmap\n-from .numpy.lax_numpy import _constant_like, asarray\n+from .numpy.lax_numpy import _constant_like, asarray, stack\nfrom jax.lib import xla_bridge\nfrom jax import core\nfrom jax.scipy.special import logit\n@@ -123,18 +123,21 @@ def threefry_2x32(keypair, count):\nelse:\nx = list(np.split(count.ravel(), 2))\n- rotations = asarray([[13, 15, 26, 6], [17, 29, 16, 24]], dtype=\"uint32\")\n- ks = asarray([key1, key2, key1 ^ key2 ^ onp.uint32(0x1BD11BDA)], dtype=\"uint32\")\n- idxs = asarray([[1, 2], [2, 0], [0, 1], [1, 2], [2, 0]])\n+ rotations = onp.array([[13, 15, 26, 6], [17, 29, 16, 24]], dtype=onp.uint32)\n+ ks = stack([key1, key2, key1 ^ key2 ^ onp.uint32(0x1BD11BDA)])\n+ idxs = onp.array([[1, 2], [2, 0], [0, 1], [1, 2], [2, 0]])\nx[0] = x[0] + ks[0]\nx[1] = x[1] + ks[1]\n+ get = partial(lax.dynamic_index_in_dim, keepdims=False)\n+\ndef step(i, x):\n- for r in rotations[i % 2]:\n+ for r in get(rotations, i % 2):\nx = apply_round(x, r)\n- i0, i1 = idxs[i]\n- return [x[0] + ks[i0], x[1] + ks[i1] + asarray(i + 1, dtype=\"uint32\")]\n+ i0, i1 = get(idxs, i)\n+ return [x[0] + ks[i0],\n+ x[1] + ks[i1] + asarray(i + 1, dtype=onp.uint32)]\nout = np.concatenate(lax.fori_loop(0, 5, step, x))\nassert out.dtype == onp.uint32\nreturn lax.reshape(out[:-1] if odd_size else out, count.shape)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -398,10 +398,11 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertEqual(onp.result_type(w), onp.float32)\ndef testNoOpByOpUnderHash(self):\n- raise SkipTest() # TODO(mattjj): re-enable this test\n- def fail(): assert False\n+ def fail(*args, **kwargs): assert False\napply_primitive, xla.apply_primitive = xla.apply_primitive, fail\n+ try:\nout = random.threefry_2x32(onp.zeros(2, onp.uint32), onp.arange(10, dtype=onp.uint32))\n+ finally:\nxla.apply_primitive = apply_primitive\n"
}
] | Python | Apache License 2.0 | google/jax | address reviewer comments, no op-by-op in threefry |
260,329 | 13.08.2019 17:37:15 | 18,000 | 8718e30528e0e9626934ab3b3509ccc39640fafd | Make DeviceValue and subclasses weakref friendly | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -434,7 +434,7 @@ for _t in array_types:\nclass DeviceValue(object):\n\"\"\"A DeviceValue represents a value backed by device memory.\"\"\"\n- __slots__ = [\"aval\", \"device_buffer\"]\n+ __slots__ = [\"aval\", \"device_buffer\", \"__weakref__\"]\ndef __init__(self, aval, device_buffer):\nself.aval = aval\n"
}
] | Python | Apache License 2.0 | google/jax | Make DeviceValue and subclasses weakref friendly
https://stackoverflow.com/questions/19526340/weakref-and-slots |
260,335 | 14.08.2019 07:13:42 | 25,200 | 2dec779b49709454e5ccdc7488d02ef4a26ed267 | remove author info in notebook (old, redundant) | [
{
"change_type": "MODIFY",
"old_path": "notebooks/XLA_in_Python.ipynb",
"new_path": "notebooks/XLA_in_Python.ipynb",
"diff": "\"\\n\",\n\"_Anselm Levskaya_ \\n\",\n\"\\n\",\n- \"_The Python XLA client was designed by Roy Frostig._\\n\",\n- \"\\n\",\n- \"_JAX was written by Dougal Maclaurin, Peter Hawkins, Matthew Johnson, Roy Frostig, Alex Wiltschko, Chris Leary._ \\n\",\n- \"\\n\",\n\"XLA is the compiler that JAX uses, and the compiler that TF uses for TPUs and will soon use for all devices, so it's worth some study. However, it's not exactly easy to play with XLA computations directly using the raw C++ interface. JAX exposes the underlying XLA computation builder API through a python wrapper, and makes interacting with the XLA compute model accessible for messing around and prototyping.\\n\",\n\"\\n\",\n\"XLA computations are built as computation graphs in HLO IR, which is then lowered to LLO that is device specific (CPU, GPU, TPU, etc.). \\n\",\n"
}
] | Python | Apache License 2.0 | google/jax | remove author info in notebook (old, redundant) |
260,329 | 15.08.2019 11:26:25 | 18,000 | 4b693777aaa19ab54cf811acf3fa96f0b4534e5b | Ensure reps is a tuple (allows list or other iterable) | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1297,7 +1297,7 @@ def tile(a, reps):\nif isinstance(reps, int):\nreps = (reps,)\na = reshape(a, (1,) * (len(reps) - ndim(a)) + shape(a))\n- reps = (1,) * (ndim(a) - len(reps)) + reps\n+ reps = (1,) * (ndim(a) - len(reps)) + tuple(reps)\nfor i, rep in enumerate(reps):\na = concatenate([a] * rep, axis=i)\nreturn a\n"
}
] | Python | Apache License 2.0 | google/jax | Ensure reps is a tuple (allows list or other iterable) |
260,329 | 16.08.2019 12:31:53 | 18,000 | 48f64ec86361968ca59131abbbcbb00b9bbb9be5 | Avoid a TypeError when reps is or contains a ndarray
Something along the lines of `TypeError: multiply only accepts scalar or ndarray, but got a list.` | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1300,7 +1300,7 @@ def tile(a, reps):\na = reshape(a, (1,) * (len(reps) - ndim(a)) + shape(a))\nreps = (1,) * (ndim(a) - len(reps)) + tuple(reps)\nfor i, rep in enumerate(reps):\n- a = concatenate([a] * rep, axis=i)\n+ a = concatenate([a] * int(rep), axis=i)\nreturn a\n@_wraps(onp.concatenate)\n"
}
] | Python | Apache License 2.0 | google/jax | Avoid a TypeError when reps is or contains a ndarray
Something along the lines of `TypeError: multiply only accepts scalar or ndarray, but got a list.` |
260,329 | 16.08.2019 17:18:44 | 18,000 | d07107af5a395b33ac0a67ab4201b301568c82c4 | Makes the `Tracer` object `weakref`-able | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -282,7 +282,7 @@ class Trace(object):\nclass Tracer(object):\n__array_priority__ = 1000\n- __slots__ = ['trace']\n+ __slots__ = ['trace', '__weakref__']\ndef __array__(self):\nraise Exception(\"Tracer can't be used with raw numpy functions. \"\n"
}
] | Python | Apache License 2.0 | google/jax | Makes the `Tracer` object `weakref`-able |
260,403 | 19.08.2019 23:45:36 | 25,200 | cc87fb601332855c8a6d753ac461935a1c664d9f | WIP: experimental multibackend jit | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -83,7 +83,7 @@ class _ThreadLocalState(threading.local):\n_thread_local_state = _ThreadLocalState()\n-def jit(fun, static_argnums=(), device_assignment=None):\n+def jit(fun, static_argnums=(), device_assignment=None, backend=None):\n\"\"\"Sets up `fun` for just-in-time compilation with XLA.\nArgs:\n@@ -122,9 +122,9 @@ def jit(fun, static_argnums=(), device_assignment=None):\n[-0.54485154 0.27744263 -0.29255125 -0.91421586 -0.62452525 -0.2474813\n-0.8574326 -0.7823267 0.7682731 0.59566754]\n\"\"\"\n- return _jit(fun, static_argnums, device_assignment)\n+ return _jit(fun, static_argnums, device_assignment, backend)\n-def _jit(fun, static_argnums, device_assignment):\n+def _jit(fun, static_argnums, device_assignment, backend):\n_check_callable(fun)\nif isinstance(device_assignment, int):\ndevice_assignment = (device_assignment,)\n@@ -148,7 +148,7 @@ def _jit(fun, static_argnums, device_assignment):\nargs_flat, in_tree = tree_flatten((dyn_args, kwargs))\nflat_fun, out_tree = flatten_fun_leafout(f, in_tree)\nout = xla.xla_call(flat_fun, *args_flat,\n- device_assignment=device_assignment)\n+ device_assignment=device_assignment, backend=backend)\nreturn out if treedef_is_leaf(out_tree()) else tree_unflatten(out_tree(), out)\njitted_name = \"jit({}, static_argnums={})\"\n@@ -198,7 +198,7 @@ def disable_jit():\n_thread_local_state.jit_is_disabled = prev_val\n-def xla_computation(fun, static_argnums=(), axis_env=None):\n+def xla_computation(fun, static_argnums=(), axis_env=None, backend=None):\n\"\"\"Creates a function that produces its XLA computation given example args.\nArgs:\n@@ -293,7 +293,7 @@ def xla_computation(fun, static_argnums=(), axis_env=None):\npvals = map(pv_like, jax_args)\njaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals)\naxis_env_ = make_axis_env(xla.jaxpr_replicas(jaxpr))\n- return xla.build_jaxpr(jaxpr, axis_env_, consts,\n+ return xla.build_jaxpr(jaxpr, backend, axis_env_, consts,\n*map(xla.abstractify, jax_args))\nelse:\njax_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\n@@ -301,7 +301,7 @@ def xla_computation(fun, static_argnums=(), axis_env=None):\npvals = map(pv_like, (jax_kwargs,) + tuple(jax_args))\njaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals)\naxis_env_ = make_axis_env(xla.jaxpr_replicas(jaxpr))\n- return xla.build_jaxpr(jaxpr, axis_env_, consts, xla.abstractify(jax_kwargs),\n+ return xla.build_jaxpr(jaxpr, backend, axis_env_, consts, xla.abstractify(jax_kwargs),\n*map(xla.abstractify, jax_args))\nreturn computation_maker\n@@ -626,7 +626,7 @@ def vmap(fun, in_axes=0, out_axes=0):\nreturn batched_fun\n-def pmap(fun, axis_name=None):\n+def pmap(fun, axis_name=None, backend=None):\n\"\"\"Parallel map with support for collectives.\nThe purpose of ``pmap`` is to express single-program multiple-data (SPMD)\n@@ -720,7 +720,7 @@ def pmap(fun, axis_name=None):\nargs_flat, in_tree = tree_flatten((args, kwargs))\nflat_fun, out_tree = flatten_fun_leafout(f, in_tree)\nout = pxla.xla_pmap(flat_fun, *args_flat,\n- axis_name=axis_name, axis_size=axis_size)\n+ axis_name=axis_name, axis_size=axis_size, backend=backend)\nreturn out if treedef_is_leaf(out_tree()) else tree_unflatten(out_tree(), out)\nnamestr = \"pmap({}, axis_name={})\".format\n@@ -1113,8 +1113,8 @@ def make_jaxpr(fun):\ntree_to_pval_tuples = partial(process_pytree, pe.pack_pvals)\n-def device_put(x, device_num=0):\n- return tree_map(lambda y: xla.device_put_p.bind(y, device_num=device_num), x)\n+def device_put(x, device_num=0, backend=None):\n+ return tree_map(lambda y: xla.device_put_p.bind(y, device_num=device_num, backend=backend), x)\ndef _device_get(x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -45,7 +45,7 @@ from . import ad\ndef identity(x): return x\n# TODO(mattjj, phawkins): improve re-distribution not to copy to host\n-def shard_args(device_ordinals, assignments, axis_size, nrep, args):\n+def shard_args(backend, device_ordinals, assignments, axis_size, nrep, args):\n\"\"\"Shard an argument data array arg along its leading axis.\nArgs:\n@@ -76,11 +76,11 @@ def shard_args(device_ordinals, assignments, axis_size, nrep, args):\nelse:\ni = assignments[r]\nbuffers[r][a] = xla.device_put(arg.device_buffers[i].to_py(),\n- device_ordinals[r])\n+ device_ordinals[r], backend=backend)\nelse:\nfor r in range(nrep):\nv = _slice(arg, assignments[r])\n- buffers[r][a] = xla.device_put(v, device_ordinals[r])\n+ buffers[r][a] = xla.device_put(v, device_ordinals[r], backend=backend)\nreturn buffers\ndef _slice(x, i):\n@@ -231,18 +231,18 @@ def replica_groups(nrep, mesh_spec, mesh_axes):\n### the main pmap machinery lowers SPMD jaxprs to multi-replica XLA computations\n-def compile_replicated(jaxpr, axis_name, axis_size, consts, *abstract_args):\n+def compile_replicated(jaxpr, backend, axis_name, axis_size, consts, *abstract_args):\nnum_replicas = axis_size * xla.jaxpr_replicas(jaxpr)\n- if num_replicas > xb.device_count():\n+ if num_replicas > xb.device_count(backend):\nmsg = (\"compiling computation that requires {} replicas, but only {} XLA \"\n\"devices are available\")\n- raise ValueError(msg.format(num_replicas, xb.device_count()))\n+ raise ValueError(msg.format(num_replicas, xb.device_count(backend)))\naxis_env = xla.AxisEnv(num_replicas, [axis_name], [axis_size])\narg_shapes = list(map(xla_shape, abstract_args))\n- built_c = xla._jaxpr_computation(jaxpr, axis_env, consts, (), *arg_shapes)\n+ built_c = xla._jaxpr_computation(jaxpr, backend, axis_env, consts, (), *arg_shapes)\nresult_shape = aval_from_xla_shape(built_c.GetReturnValueShape())\ncompiled = built_c.Compile(arg_shapes, xb.get_compile_options(num_replicas),\n- backend=xb.get_backend())\n+ backend=xb.get_backend(backend))\nreturn compiled, num_replicas, result_shape\n@@ -295,10 +295,10 @@ def extend_dynamic_axis_env(axis_name, pmap_trace, hard_size):\nyield\ndynamic_axis_env.pop()\n-def unmapped_device_count():\n+def unmapped_device_count(backend=None):\ndynamic_axis_env = _thread_local_state.dynamic_axis_env\nmapped = prod(frame.hard_size for frame in dynamic_axis_env)\n- unmapped, ragged = divmod(xb.device_count(), mapped)\n+ unmapped, ragged = divmod(xb.device_count(backend), mapped)\nassert not ragged and unmapped > 0\nreturn unmapped\n@@ -519,9 +519,10 @@ xb.register_constant_handler(ChunkedDeviceArray,\ndef xla_pmap_impl(fun, *args, **params):\naxis_name = params.pop('axis_name')\naxis_size = params.pop('axis_size')\n+ backend = params.pop('backend')\nassert not params\nabstract_args = map(xla.abstractify, args)\n- compiled_fun = parallel_callable(fun, axis_name, axis_size, *abstract_args)\n+ compiled_fun = parallel_callable(fun, backend, axis_name, axis_size, *abstract_args)\nreturn compiled_fun(*args)\ndef _shard_aval(axis_size, aval):\n@@ -534,7 +535,7 @@ def _shard_aval(axis_size, aval):\nraise TypeError(aval)\n@lu.cache\n-def parallel_callable(fun, axis_name, axis_size, *avals):\n+def parallel_callable(fun, backend, axis_name, axis_size, *avals):\navals = tuple(_shard_aval(axis_size, a) for a in avals)\npvals = [PartialVal((aval, core.unit)) for aval in avals]\npval = PartialVal((core.AbstractTuple(()), core.unit)) # dummy value\n@@ -558,15 +559,15 @@ def parallel_callable(fun, axis_name, axis_size, *avals):\nresult_handler = sharded_result_handler(axis_size, xla.abstractify(out_const))\nreturn lambda *args: result_handler([out_const] * axis_size)\nelse:\n- out = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\n+ out = compile_replicated(jaxpr, backend, axis_name, axis_size, consts, *avals)\ncompiled, nrep, shard_result_shape = out\ndevice_ordinals = compiled.DeviceOrdinals()\nassignments = assign_shards_to_replicas(nrep, axis_size)\n- handle_args = partial(shard_args, device_ordinals, assignments, axis_size,\n+ handle_args = partial(shard_args, backend, device_ordinals, assignments, axis_size,\nnrep)\nhandle_replica_result = xla.result_handler(shard_result_shape)\nhandle_full_result = sharded_result_handler(axis_size, merged_aval(out_pval))\n- return partial(execute_replicated, compiled, out_pval, nrep,\n+ return partial(execute_replicated, compiled, backend, out_pval, nrep,\nhandle_args, handle_replica_result, handle_full_result)\ndef merged_aval(pval):\n@@ -580,12 +581,12 @@ def merged_aval(pval):\nelse:\nraise TypeError(type(pv))\n-def execute_replicated(compiled, pval, nrep, handle_in,\n+def execute_replicated(compiled, backend, pval, nrep, handle_in,\nhandle_replica_result, handle_full_result, *args):\n- if nrep > xb.device_count():\n+ if nrep > xb.device_count(backend):\nmsg = (\"executing pmap computation that requires {} replicas, but only {} \"\n\"XLA devices are available\")\n- raise ValueError(msg.format(nrep, xb.device_count()))\n+ raise ValueError(msg.format(nrep, xb.device_count(backend)))\ninput_bufs = handle_in(args)\nout_bufs = compiled.ExecutePerReplica(list(input_bufs))\nresults = [merge_pvals(handle_replica_result(buf), pval) for buf in out_bufs]\n@@ -597,11 +598,11 @@ xla_pmap = partial(core.call_bind, xla_pmap_p)\nxla_pmap_p.def_custom_bind(xla_pmap)\nxla_pmap_p.def_impl(xla_pmap_impl)\n-def _xla_pmap_translation_rule(c, jaxpr, axis_env, env_nodes, in_nodes,\n+def _xla_pmap_translation_rule(c, jaxpr, backend, axis_env, env_nodes, in_nodes,\naxis_name, axis_size):\nnew_env = xla.extend_axis_env(axis_env, axis_name, axis_size)\nin_nodes_sharded = list(map(partial(xla_shard, c, new_env.sizes), in_nodes))\n- subc = xla._jaxpr_computation(jaxpr, new_env, (),\n+ subc = xla._jaxpr_computation(jaxpr, backend, new_env, (),\ntuple(map(c.GetShape, env_nodes)),\n*map(c.GetShape, in_nodes_sharded))\nsharded_result = c.Call(subc, env_nodes + in_nodes_sharded)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -53,13 +53,14 @@ def apply_primitive(prim, *args, **params):\n@cache()\ndef _xla_primitive_callable(prim, *abstract_args, **params):\n+ backend = params.get('backend', None)\nshapes = tuple(map(xla_shape, abstract_args))\nbuilt_c = primitive_computation(prim, *shapes, **params)\nresult_shape = aval_from_xla_shape(built_c.GetReturnValueShape())\nhandle_result = result_handler(result_shape)\ncompiled = built_c.Compile(shapes, xb.get_compile_options(),\n- backend=xb.get_backend())\n- return partial(_execute_compiled_primitive, prim.name, compiled, handle_result)\n+ backend=xb.get_backend(backend))\n+ return partial(_execute_compiled_primitive, prim.name, compiled, backend, handle_result)\ndef xla_shape(x):\ntry:\n@@ -73,8 +74,9 @@ def xla_shape(x):\n@cache()\ndef primitive_computation(prim, *shapes, **params):\n\"\"\"Builds an XLA computation for `prim` with argument `shapes`.\"\"\"\n+ backend = params.pop('backend', None)\nc = xb.make_computation_builder(\"primitive_computation\")\n- platform = xb.get_backend().platform\n+ platform = xb.get_backend(backend).platform\nxla_args = map(c.ParameterWithShape, shapes)\nif prim in backend_specific_translations[platform]:\nrule = backend_specific_translations[platform][prim]\n@@ -82,9 +84,12 @@ def primitive_computation(prim, *shapes, **params):\nelif prim in translations:\nrule = translations[prim]\nrule(c, *xla_args, **params) # return val set as a side-effect on c\n+ elif prim in reduction_translations:\n+ rule = translations[prim]\n+ rule(c, *xla_args, backend=backend, **params) # return val set as a side-effect on c\nelif prim in initial_style_translations:\nrule = initial_style_translations[prim]\n- rule(c, AxisEnv(1, [], []), *xla_args, **params) # side-effect on c\n+ rule(c, AxisEnv(1, [], []), *xla_args, backend=backend, **params) # side-effect on c\nelse:\nraise NotImplementedError(\"XLA translation rule for {} not found\".format(prim))\ntry:\n@@ -100,9 +105,9 @@ def aval_from_xla_shape(shape):\nelse:\nreturn ShapedArray(shape.dimensions(), shape.element_type())\n-def _execute_compiled_primitive(name, compiled, result_handler, *args):\n+def _execute_compiled_primitive(name, compiled, backend, result_handler, *args):\ndevice_num, = compiled.DeviceOrdinals()\n- input_bufs = [device_put(x, device_num) for x in args]\n+ input_bufs = [device_put(x, device_num, backend=backend) for x in args]\nout_buf = compiled.Execute(input_bufs)\ncheck_nans(name, out_buf)\nreturn result_handler(out_buf)\n@@ -120,7 +125,7 @@ def _check_nans(name, xla_shape, buf):\nmsg = \"invalid value (nan) encountered in {}\"\nraise FloatingPointError(msg.format(name))\n-def device_put(x, device_num=0):\n+def device_put(x, device_num=0, backend=None):\n\"\"\"Place a Python value `x` on device number `device_num`.\nThis is a wrapper around xla_client.Buffer.from_pyval to handle\n@@ -152,13 +157,13 @@ def device_put(x, device_num=0):\nelse:\nreturn x.device_buffer.copy_to_device(device_num)\nelif isinstance(x, DeviceConstant):\n- return _instantiate_device_constant(x, device_num=device_num)\n+ return _instantiate_device_constant(x, device_num=device_num, backend=backend)\nelif isinstance(x, (DeviceArray, onp.ndarray)):\n- return xla_client.Buffer.from_pyval(x, device_num, backend=xb.get_backend())\n+ return xla_client.Buffer.from_pyval(x, device_num, backend=xb.get_backend(backend))\nelif isinstance(x, JaxTuple):\n- element_bufs = tuple(map(partial(device_put, device_num=device_num), x))\n+ element_bufs = tuple(map(partial(device_put, device_num=device_num, backend=backend), x))\nreturn xla_client.Buffer.make_tuple(element_bufs, device=device_num,\n- backend=xb.get_backend())\n+ backend=xb.get_backend(backend))\nelse:\nraise TypeError(t)\n@@ -187,22 +192,22 @@ def result_handler(aval):\nreturn partial(DeviceArray, aval)\n-def _compile_jaxpr(jaxpr, device_assignment, axis_env, const_vals, *abstract_args):\n+def _compile_jaxpr(jaxpr, device_assignment, backend, axis_env, const_vals, *abstract_args):\nif axis_env.nreps > xb.device_count():\nmsg = (\"compiling computation that requires {} replicas, but only {} XLA \"\n\"devices are available\")\nraise ValueError(msg.format(axis_env.nreps, xb.device_count()))\narg_shapes = list(map(xla_shape, abstract_args))\n- built_c = _jaxpr_computation(jaxpr, axis_env, const_vals, (), *arg_shapes)\n+ built_c = _jaxpr_computation(jaxpr, backend, axis_env, const_vals, (), *arg_shapes)\nresult_shape = aval_from_xla_shape(built_c.GetReturnValueShape())\ncompile_opts = xb.get_compile_options(num_replicas=axis_env.nreps,\ndevice_assignment=device_assignment)\n- compiled_c = built_c.Compile(arg_shapes, compile_opts, backend=xb.get_backend())\n+ compiled_c = built_c.Compile(arg_shapes, compile_opts, backend=xb.get_backend(backend))\nreturn compiled_c, result_shape\n-def build_jaxpr(jaxpr, axis_env, const_vals, *abstract_args):\n+def build_jaxpr(jaxpr, backend, axis_env, const_vals, *abstract_args):\narg_shapes = list(map(xla_shape, abstract_args))\n- built_c = _jaxpr_computation(jaxpr, axis_env, const_vals, (), *arg_shapes)\n+ built_c = _jaxpr_computation(jaxpr, backend, axis_env, const_vals, (), *arg_shapes)\nreturn built_c\n@@ -217,14 +222,14 @@ def _prefetch_jaxpr_literals(jaxpr):\n_prefetch_jaxpr_literals(subjaxpr)\n-def jaxpr_computation(jaxpr, const_vals, freevar_shapes, *arg_shapes):\n+def jaxpr_computation(jaxpr, backend, const_vals, freevar_shapes, *arg_shapes):\naxis_env = AxisEnv(1, [], [])\n- return _jaxpr_computation(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes)\n+ return _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *arg_shapes)\n-def _jaxpr_computation(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes):\n+def _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *arg_shapes):\nassert not any(type(invar) in (tuple, list) for invar in jaxpr.invars)\nc = xb.make_computation_builder(\"jaxpr_computation\")\n- platform = xb.get_backend().platform\n+ platform = xb.get_backend(backend).platform\ndef read(v):\nif type(v) is Literal:\n@@ -261,19 +266,21 @@ def _jaxpr_computation(jaxpr, axis_env, const_vals, freevar_shapes, *arg_shapes)\nans = rule(c, *in_nodes, **eqn.params)\nelif eqn.primitive in translations:\nans = translations[eqn.primitive](c, *in_nodes, **eqn.params)\n+ elif eqn.primitive in reduction_translations:\n+ ans = reduction_translations[eqn.primitive](c, *in_nodes, backend=backend, **eqn.params)\nelif eqn.primitive in initial_style_translations:\nrule = initial_style_translations[eqn.primitive]\n- ans = rule(c, axis_env, *in_nodes, **eqn.params)\n+ ans = rule(c, axis_env, *in_nodes, backend=backend, **eqn.params)\nelif eqn.primitive in parallel_translations:\nreplica_groups = axis_groups(axis_env, eqn.params['axis_name'])\nnew_params = {k: eqn.params[k] for k in eqn.params if k != 'axis_name'}\nrule = parallel_translations[eqn.primitive]\n- ans = rule(c, *in_nodes, replica_groups=replica_groups, **new_params)\n+ ans = rule(c, *in_nodes, replica_groups=replica_groups, backend=backend, **new_params)\nelif eqn.primitive in call_translations:\n(subjaxpr, const_bindings, freevar_bindings), = eqn.bound_subjaxprs\nenv_nodes = list(map(read, const_bindings + freevar_bindings))\nrule = call_translations[eqn.primitive]\n- ans = rule(c, subjaxpr, axis_env, env_nodes, in_nodes, **eqn.params)\n+ ans = rule(c, subjaxpr, backend, axis_env, env_nodes, in_nodes, **eqn.params)\nelse:\nmsg = \"XLA translation rule for primitive '{}' not found\"\nraise NotImplementedError(msg.format(eqn.primitive.name))\n@@ -345,6 +352,7 @@ def lower_fun(fun, instantiate=False, initial_style=False):\nhigher-level lax or NumPy APIs.\n\"\"\"\ndef f(c, *args, **params):\n+ backend = params.pop('backend', None)\nif initial_style:\naxis_env, xla_args = args[0], args[1:]\nelse:\n@@ -354,12 +362,13 @@ def lower_fun(fun, instantiate=False, initial_style=False):\npvals = [pe.PartialVal((a, core.unit)) for a in avals]\njaxpr, _, consts = pe.trace_unwrapped_to_jaxpr(fun, pvals, instantiate,\n**params)\n- built_c = _jaxpr_computation(jaxpr, axis_env, consts, (), *xla_shapes)\n+ built_c = _jaxpr_computation(jaxpr, backend, axis_env, consts, (), *xla_shapes)\nreturn c.Call(built_c, xla_args)\nreturn f\ntranslations = {}\n+reduction_translations = {}\nparallel_translations = {}\ninitial_style_translations = {}\ncall_translations = {}\n@@ -646,7 +655,7 @@ class DeviceConstant(DeviceArray):\ndef constant_handler(c, constant_instance, canonicalize_types=True):\nassert False\n-def _instantiate_device_constant(const, cutoff=1e6, device_num=0):\n+def _instantiate_device_constant(const, cutoff=1e6, device_num=0, backend=None):\n# dispatch an XLA Computation to build the constant on the device if it's\n# large, or alternatively build it on the host and transfer it if it's small\n# TODO(mattjj): need a way to instantiate on a specific device\n@@ -655,15 +664,16 @@ def _instantiate_device_constant(const, cutoff=1e6, device_num=0):\nc = xb.make_computation_builder(\"constant_instantiating_computation\")\nxla_const = const.constant_handler(c, const)\ncompiled = c.Build(xla_const).Compile((), xb.get_compile_options(),\n- backend=xb.get_backend())\n+ backend=xb.get_backend(backend))\nreturn compiled.Execute(())\nelse:\nreturn xla_client.Buffer.from_pyval(onp.asarray(const), device_num,\n- backend=xb.get_backend())\n+ backend=xb.get_backend(backend))\ndef _xla_call_impl(fun, *args, **params):\ndevice_assignment = params.pop('device_assignment')\n- compiled_fun = _xla_callable(fun, device_assignment,\n+ backend = params.pop('backend')\n+ compiled_fun = _xla_callable(fun, device_assignment, backend,\n*map(abstractify, args))\ntry:\nreturn compiled_fun(*args)\n@@ -673,30 +683,30 @@ def _xla_call_impl(fun, *args, **params):\nreturn fun.call_wrapped(*args) # probably won't return\n@lu.cache\n-def _xla_callable(fun, device_assignment, *abstract_args):\n+def _xla_callable(fun, device_assignment, backend, *abstract_args):\npvals = [pe.PartialVal((aval, core.unit)) for aval in abstract_args]\nwith core.new_master(pe.JaxprTrace, True) as master:\njaxpr, (pval, consts, env) = pe.trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)\nassert not env # no subtraces here (though cond might eventually need them)\naxis_env = AxisEnv(jaxpr_replicas(jaxpr), [], [])\n- compiled, result_shape = _compile_jaxpr(jaxpr, device_assignment, axis_env, consts,\n+ compiled, result_shape = _compile_jaxpr(jaxpr, device_assignment, backend, axis_env, consts,\n*abstract_args)\ndel master, consts, jaxpr, env\nhandle_result = result_handler(result_shape)\nif axis_env.nreps == 1:\n- return partial(_execute_compiled, compiled, pval, handle_result)\n+ return partial(_execute_compiled, compiled, backend, pval, handle_result)\nelse:\n- return partial(_execute_replicated, compiled, pval, handle_result)\n+ return partial(_execute_replicated, compiled, backend, pval, handle_result)\n-def _execute_compiled(compiled, pval, handle_result, *args):\n+def _execute_compiled(compiled, backend, pval, handle_result, *args):\ndevice_num, = compiled.DeviceOrdinals()\n- input_bufs = [device_put(x, device_num) for x in args]\n+ input_bufs = [device_put(x, device_num, backend=backend) for x in args]\nout_buf = compiled.Execute(input_bufs)\ncheck_nans(\"jit-compiled computation\", out_buf)\nreturn pe.merge_pvals(handle_result(out_buf), pval)\n-def _execute_replicated(compiled, pval, handle_result, *args):\n- input_bufs = [[device_put(x, i) for x in args] for i in compiled.DeviceOrdinals()]\n+def _execute_replicated(compiled, backend, pval, handle_result, *args):\n+ input_bufs = [[device_put(x, i, backend=backend) for x in args] for i in compiled.DeviceOrdinals()]\nout_buf = compiled.ExecutePerReplica(input_bufs)[0]\ncheck_nans(\"jit-compiled computation\", out_buf)\nreturn pe.merge_pvals(handle_result(out_buf), pval)\n@@ -707,17 +717,17 @@ xla_call = partial(core.call_bind, xla_call_p)\nxla_call_p.def_custom_bind(xla_call)\nxla_call_p.def_impl(_xla_call_impl)\n-def _xla_call_translation_rule(c, jaxpr, axis_env, env_nodes, in_nodes,\n+def _xla_call_translation_rule(c, jaxpr, backend, axis_env, env_nodes, in_nodes,\ndevice_assignment):\ndel device_assignment # Unused.\n- subc = _jaxpr_computation(jaxpr, axis_env, (), _map(c.GetShape, env_nodes),\n+ subc = _jaxpr_computation(jaxpr, backend, axis_env, (), _map(c.GetShape, env_nodes),\n*map(c.GetShape, in_nodes))\nreturn c.Call(subc, env_nodes + in_nodes)\ncall_translations[xla_call_p] = _xla_call_translation_rule\nad.primitive_transposes[xla_call_p] = partial(ad.call_transpose, xla_call_p)\n-def _device_put_impl(x, device_num=0):\n+def _device_put_impl(x, device_num=0, backend=None):\ntry:\na = abstractify(x)\nexcept TypeError:\n@@ -725,7 +735,7 @@ def _device_put_impl(x, device_num=0):\n.format(x, type(x)))\nhandler = result_handler(a)\n- return handler(device_put(x, device_num))\n+ return handler(device_put(x, device_num, backend))\ndevice_put_p = core.Primitive('device_put')\ndevice_put_p.def_impl(_device_put_impl)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1445,10 +1445,13 @@ _input_dtype = lambda *args, **_: xla_bridge.canonicalize_dtype(args[0].dtype)\n_fixed_dtype = lambda dtype: lambda *args, **kwargs: xla_bridge.canonicalize_dtype(dtype)\n_complex_basetype = lambda dtype: onp.abs(onp.zeros((), dtype)).dtype\n-def standard_primitive(shape_rule, dtype_rule, name, translation_rule=None):\n+def standard_primitive(shape_rule, dtype_rule, name, translation_rule=None, reduction=False):\nprim = Primitive(name)\nprim.def_impl(partial(xla.apply_primitive, prim))\nprim.def_abstract_eval(partial(standard_abstract_eval, shape_rule, dtype_rule))\n+ if reduction:\n+ xla.reduction_translations[prim] = translation_rule or partial(standard_translate, name)\n+ else:\nxla.translations[prim] = translation_rule or partial(standard_translate, name)\nreturn prim\n@@ -3034,11 +3037,11 @@ def _scatter_shape_rule(operand, scatter_indices, updates, **kwargs):\ndef _scatter_translation_rule(c, operand, scatter_indices, updates,\nupdate_jaxpr, update_consts, dimension_numbers,\n- updates_shape):\n+ updates_shape, backend=None):\ndtype = c.GetShape(operand).numpy_dtype()\ninit_value = c.Constant(onp.array(0, dtype))\nupdate_computation = _reduction_computation(\n- c, update_jaxpr, update_consts, init_value)\n+ c, update_jaxpr, backend, update_consts, init_value)\nindices_shape = c.GetShape(scatter_indices)\nreturn c.Scatter(operand, scatter_indices, updates, update_computation,\n_scatter_dimensions_proto(indices_shape, dimension_numbers))\n@@ -3143,7 +3146,7 @@ def _scatter_batching_rule(\nscatter_add_p = standard_primitive(\n_scatter_shape_rule, _scatter_dtype_rule, 'scatter-add',\n- _scatter_translation_rule)\n+ _scatter_translation_rule, reduction=True)\nad.primitive_jvps[scatter_add_p] = _scatter_add_jvp\nad.primitive_transposes[scatter_add_p] = _scatter_add_transpose_rule\nbatching.primitive_batchers[scatter_add_p] = (\n@@ -3152,14 +3155,14 @@ batching.primitive_batchers[scatter_add_p] = (\n# TODO(jlebar): Add derivatives.\nscatter_min_p = standard_primitive(\n_scatter_shape_rule, _scatter_dtype_rule, 'scatter-min',\n- _scatter_translation_rule)\n+ _scatter_translation_rule, reduction=True)\nbatching.primitive_batchers[scatter_min_p] = (\npartial(_scatter_batching_rule, scatter_min))\n# TODO(jlebar): Add derivatives.\nscatter_max_p = standard_primitive(\n_scatter_shape_rule, _scatter_dtype_rule, 'scatter-max',\n- _scatter_translation_rule)\n+ _scatter_translation_rule, reduction=True)\nbatching.primitive_batchers[scatter_max_p] = (\npartial(_scatter_batching_rule, scatter_max))\n@@ -3259,7 +3262,7 @@ def _scatter_jvp(primals, tangents, update_jaxpr, update_consts,\nscatter_p = standard_primitive(\n_scatter_shape_rule, _scatter_dtype_rule, 'scatter',\n- _scatter_translation_rule)\n+ _scatter_translation_rule, reduction=True)\nad.primitive_jvps[scatter_p] = _scatter_jvp\nbatching.primitive_batchers[scatter_p] = (\npartial(_scatter_batching_rule, scatter))\n@@ -3268,8 +3271,9 @@ batching.primitive_batchers[scatter_p] = (\ndef _reduce_shape_rule(operand, init_value, computation, jaxpr, consts, dimensions):\nreturn tuple(onp.delete(operand.shape, dimensions))\n-def _reduce_translation_rule(c, operand, init_value, computation, jaxpr, consts, dimensions):\n- xla_computation = _reduction_computation(c, jaxpr, consts, init_value)\n+def _reduce_translation_rule(c, operand, init_value, computation, jaxpr, consts, dimensions,\n+ backend=None):\n+ xla_computation = _reduction_computation(c, jaxpr, backend, consts, init_value)\nreturn c.Reduce(operand, init_value, xla_computation, dimensions)\ndef _reduce_batch_rule(batched_args, batch_dims, computation, jaxpr, consts, dimensions):\n@@ -3283,12 +3287,12 @@ def _reduce_batch_rule(batched_args, batch_dims, computation, jaxpr, consts, dim\nelse:\nraise NotImplementedError # loop and stack\n-def _reduction_computation(c, jaxpr, consts, init_value):\n+def _reduction_computation(c, jaxpr, backend, consts, init_value):\nshape = c.GetShape(init_value)\n- return xla.jaxpr_computation(jaxpr, consts, (), shape, shape)\n+ return xla.jaxpr_computation(jaxpr, backend, consts, (), shape, shape)\nreduce_p = standard_primitive(_reduce_shape_rule, _input_dtype, 'reduce',\n- _reduce_translation_rule)\n+ _reduce_translation_rule, reduction=True)\nbatching.primitive_batchers[reduce_p] = _reduce_batch_rule\n@@ -3432,8 +3436,8 @@ def _reduce_window_shape_rule(operand, init_value, jaxpr, consts,\nwindow_strides, padding)\ndef _reduce_window_translation_rule(c, operand, init_value, jaxpr, consts,\n- window_dimensions, window_strides, padding):\n- xla_computation = _reduction_computation(c, jaxpr, consts, init_value)\n+ window_dimensions, window_strides, padding, backend=None):\n+ xla_computation = _reduction_computation(c, jaxpr, backend, consts, init_value)\nreturn c.ReduceWindow(operand, init_value, xla_computation, window_dimensions,\nwindow_strides, padding)\n@@ -3456,7 +3460,7 @@ def _generic_reduce_window_batch_rule(\nreduce_window_p = standard_primitive(\n_reduce_window_shape_rule, _input_dtype, 'reduce_window',\n- _reduce_window_translation_rule)\n+ _reduce_window_translation_rule, reduction=True)\nbatching.primitive_batchers[reduce_window_p] = _generic_reduce_window_batch_rule\n@@ -3587,15 +3591,15 @@ def _select_and_scatter_shape_rule(\ndef _select_and_scatter_translation(\nc, operand, source, init_value, select_jaxpr, select_consts, scatter_jaxpr,\n- scatter_consts, window_dimensions, window_strides, padding):\n- select = _reduction_computation(c, select_jaxpr, select_consts, init_value)\n- scatter = _reduction_computation(c, scatter_jaxpr, scatter_consts, init_value)\n+ scatter_consts, window_dimensions, window_strides, padding, backend=None):\n+ select = _reduction_computation(c, select_jaxpr, backend, select_consts, init_value)\n+ scatter = _reduction_computation(c, scatter_jaxpr, backend, scatter_consts, init_value)\nreturn c.SelectAndScatter(operand, select, window_dimensions, window_strides,\npadding, source, init_value, scatter)\nselect_and_scatter_p = standard_primitive(\n_select_and_scatter_shape_rule, _input_dtype, 'select_and_scatter',\n- _select_and_scatter_translation)\n+ _select_and_scatter_translation, reduction=True)\ndef _select_and_scatter_add_shape_rule(\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -162,7 +162,7 @@ def _while_loop_abstract_eval(init_val, cond_consts, body_consts, aval_out,\nreturn _maybe_tracer_tuple_to_abstract_tuple(aval_out)\ndef _while_loop_translation_rule(c, axis_env, init_val, cond_consts,\n- body_consts, aval_out, cond_jaxpr, body_jaxpr):\n+ body_consts, aval_out, cond_jaxpr, body_jaxpr, backend=None):\nloop_carry = c.Tuple(init_val, cond_consts, body_consts)\nshape = c.GetShape(loop_carry)\n@@ -191,8 +191,8 @@ def _while_loop_translation_rule(c, axis_env, init_val, cond_consts,\n+ list(body_jaxpr.eqns) +\n[_pack_eqn([body_jaxpr.outvar, cond_var, body_var], outvar)])\n- cond_c = xla._jaxpr_computation(cond_jaxpr_converted, axis_env, (), (), shape)\n- body_c = xla._jaxpr_computation(body_jaxpr_converted, axis_env, (), (), shape)\n+ cond_c = xla._jaxpr_computation(cond_jaxpr_converted, backend, axis_env, (), (), shape)\n+ body_c = xla._jaxpr_computation(body_jaxpr_converted, backend, axis_env, (), (), shape)\nfull_ans = c.While(cond_c, body_c, loop_carry)\nreturn c.GetTupleElement(full_ans, 0)\n@@ -362,7 +362,7 @@ def _cond_abstract_eval(pred, true_op, true_consts, false_op, false_consts,\ndef _cond_translation_rule(c, axis_env, pred, true_op, true_consts, false_op,\n- false_consts, aval_out, true_jaxpr, false_jaxpr):\n+ false_consts, aval_out, true_jaxpr, false_jaxpr, backend=None):\ndef make_computation(jaxpr, operand):\nassert len(jaxpr.invars) == 1\narg_var = pe.Var(0, \"arg\")\n@@ -374,7 +374,7 @@ def _cond_translation_rule(c, axis_env, pred, true_op, true_consts, false_op,\n[_unpack_eqn(arg_var, [jaxpr.invars[0], consts_var]),\n_unpack_eqn(consts_var, jaxpr.constvars)]\n+ list(jaxpr.eqns))\n- return xla._jaxpr_computation(jaxpr_converted, axis_env, (), (),\n+ return xla._jaxpr_computation(jaxpr_converted, backend, axis_env, (), (),\nc.GetShape(operand))\ntrue_arg = c.Tuple(true_op, true_consts)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_parallel.py",
"new_path": "jax/lax/lax_parallel.py",
"diff": "@@ -187,10 +187,10 @@ def _allreduce_split_axis_rule(prim, reducer, vals, which_mapped, axis_name):\nx, = vals\nreturn prim.bind(reducer(x, [0]), axis_name=axis_name), False\n-def _allreduce_translation_rule(prim, c, val, replica_groups):\n+def _allreduce_translation_rule(prim, c, val, replica_groups, backend=None):\ndtype = c.GetShape(val).numpy_dtype()\nscalar = xla_client.Shape.array_shape(dtype, ())\n- computation = xla.primitive_computation(prim, scalar, scalar)\n+ computation = xla.primitive_computation(prim, scalar, scalar, backend=backend)\nreturn c.AllReduce(val, computation, replica_groups=replica_groups)\npsum_p = standard_pmap_primitive('psum')\n@@ -216,7 +216,8 @@ pxla.split_axis_rules[pmin_p] = \\\npartial(_allreduce_split_axis_rule, pmin_p, lax._reduce_min)\n-def _ppermute_translation_rule(c, x, replica_groups, perm):\n+def _ppermute_translation_rule(c, x, replica_groups, perm, backend=None):\n+ del backend\ngroup_size = len(replica_groups[0])\nsrcs, dsts = unzip2((src % group_size, dst % group_size) for src, dst in perm)\nif not (len(srcs) == len(set(srcs)) and len(dsts) == len(set(dsts))):\n@@ -239,7 +240,8 @@ ad.deflinear(ppermute_p, _ppermute_transpose_rule)\nxla.parallel_translations[ppermute_p] = _ppermute_translation_rule\n-def _all_to_all_translation_rule(c, x, split_axis, concat_axis, replica_groups):\n+def _all_to_all_translation_rule(c, x, split_axis, concat_axis, replica_groups, backend=None):\n+ del backend\nreturn c.AllToAll(x, split_axis, concat_axis, replica_groups)\ndef _all_to_all_split_axis_rule(vals, which_mapped, split_axis, concat_axis,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -88,7 +88,8 @@ _backends = {}\ndef register_backend(name, factory):\n_backends[name] = factory\n-def _get_local_backend():\n+def _get_local_backend(platform=None):\n+ if not platform:\nplatform = FLAGS.jax_platform_name\n# Canonicalize platform names.\n@@ -110,7 +111,8 @@ def _get_local_backend():\nreturn backend\n-def _get_xrt_backend():\n+def _get_xrt_backend(platform=None):\n+ del platform\n# TODO(phawkins): support non-TPU devices.\ntf_device_name = \"TPU\"\nworker = \"tpu_worker\"\n@@ -125,17 +127,17 @@ register_backend('xrt', _get_xrt_backend)\n_backend_lock = threading.Lock()\n@util.memoize\n-def get_backend():\n+def get_backend(platform=None):\nwith _backend_lock:\nbackend = _backends.get(FLAGS.jax_xla_backend)\nif backend is None:\nmsg = 'Unknown jax_xla_backend value \"{}\".'\nraise ValueError(msg.format(FLAGS.jax_xla_backend))\n- return backend()\n+ return backend(platform)\n-def device_count():\n- return int(get_backend().device_count())\n+def device_count(backend=None):\n+ return int(get_backend(backend).device_count())\n### utility functions\n"
}
] | Python | Apache License 2.0 | google/jax | WIP: experimental multibackend jit |
260,403 | 20.08.2019 00:24:30 | 25,200 | 29c6fe889969c866c9a9bd5f0e751ceaf2000697 | small fix for multibackend | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -255,6 +255,7 @@ def _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *ar\n_map(write, jaxpr.invars, map(c.ParameterWithShape, arg_shapes))\n_prefetch_jaxpr_literals(jaxpr)\nfor eqn in jaxpr.eqns:\n+ eqn.params.pop('backend', None)\nif not eqn.restructure:\nin_nodes = list(map(read, eqn.invars))\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | small fix for multibackend |
260,403 | 20.08.2019 01:00:34 | 25,200 | 7529815614ad09ccaad16d1fbfca714a8daa9051 | fix missing pop default | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -519,7 +519,7 @@ xb.register_constant_handler(ChunkedDeviceArray,\ndef xla_pmap_impl(fun, *args, **params):\naxis_name = params.pop('axis_name')\naxis_size = params.pop('axis_size')\n- backend = params.pop('backend')\n+ backend = params.pop('backend', None)\nassert not params\nabstract_args = map(xla.abstractify, args)\ncompiled_fun = parallel_callable(fun, backend, axis_name, axis_size, *abstract_args)\n"
}
] | Python | Apache License 2.0 | google/jax | fix missing pop default |
260,403 | 21.08.2019 00:22:53 | 25,200 | f01fc35ce5644586f4c4239ab3bc7ff0bbd2b0d5 | Make op-by-op work with all jit-returned devicearrays. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -105,6 +105,8 @@ def jit(fun, static_argnums=(), device_assignment=None, backend=None):\nchange. Optional, an int specifying the device ordinal for which to compile the\nfunction. The default is inherited from XLA's DeviceAssignment logic and is\nusually to use device 0.\n+ backend: This is an experimental feature and the API is likely to change.\n+ Optional, a string representing the xla backend. 'cpu','gpu', or 'tpu'.\nReturns:\nA wrapped version of `fun`, set up for just-in-time compilation.\n@@ -210,6 +212,8 @@ def xla_computation(fun, static_argnums=(), axis_env=None, backend=None):\nfunctions that involve parallel communication collectives, and it\nspecifies the axis name/size environment that would be set up by\napplications of ``jax.pmap``. See the examples below.\n+ backend: This is an experimental feature and the API is likely to change.\n+ Optional, a string representing the xla backend. 'cpu','gpu', or 'tpu'.\nReturns:\nA wrapped version of ``fun`` that when applied to example arguments returns a\n@@ -649,6 +653,8 @@ def pmap(fun, axis_name=None, backend=None):\nfun: Function to be mapped over argument axes.\naxis_name: Optional, a hashable Python object used to identify the mapped\naxis so that parallel collectives can be applied.\n+ backend: This is an experimental feature and the API is likely to change.\n+ Optional, a string representing the xla backend. 'cpu','gpu', or 'tpu'.\nReturns:\nA parallelized version of ``fun`` with arguments that correspond to those of\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -598,8 +598,8 @@ xla_pmap = partial(core.call_bind, xla_pmap_p)\nxla_pmap_p.def_custom_bind(xla_pmap)\nxla_pmap_p.def_impl(xla_pmap_impl)\n-def _xla_pmap_translation_rule(c, jaxpr, backend, axis_env, env_nodes, in_nodes,\n- axis_name, axis_size):\n+def _xla_pmap_translation_rule(c, jaxpr, axis_env, env_nodes, in_nodes,\n+ axis_name, axis_size, backend=None):\nnew_env = xla.extend_axis_env(axis_env, axis_name, axis_size)\nin_nodes_sharded = list(map(partial(xla_shard, c, new_env.sizes), in_nodes))\nsubc = xla._jaxpr_computation(jaxpr, backend, new_env, (),\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -145,6 +145,7 @@ def device_put(x, device_num=0, backend=None):\nDeviceTuple, and arraylike includes DeviceArray, DeviceConstant, and\nanything that has an '__array__' attr.\ndevice_num: an int representing the target physical device number.\n+ backend: a string representing the xla backend. ('cpu','gpu','tpu')\nReturns:\nA buffer representing the input `x` placed on the appropriate device.\n@@ -152,10 +153,20 @@ def device_put(x, device_num=0, backend=None):\nx = _canonicalize_pyval_dtype(x)\nt = type(x)\nif t is DeviceArray or t is DeviceTuple:\n+ # TODO(levskaya) remove if-condition after increasing minimum Jaxlib version to\n+ # 0.1.24.\n+ if hasattr(x.device_buffer, 'platform'):\n+ backend_match = x.device_buffer.platform() == backend\n+ else:\n+ backend_match = True\n+ if backend_match:\nif x.device_buffer.device() == device_num:\nreturn x.device_buffer\nelse:\nreturn x.device_buffer.copy_to_device(device_num)\n+ else:\n+ # Buffers from different XLA backends are passed through the host.\n+ return xla_client.Buffer.from_pyval(x, device_num, backend=xb.get_backend(backend))\nelif isinstance(x, DeviceConstant):\nreturn _instantiate_device_constant(x, device_num=device_num, backend=backend)\nelif isinstance(x, (DeviceArray, onp.ndarray)):\n@@ -281,7 +292,7 @@ def _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *ar\n(subjaxpr, const_bindings, freevar_bindings), = eqn.bound_subjaxprs\nenv_nodes = list(map(read, const_bindings + freevar_bindings))\nrule = call_translations[eqn.primitive]\n- ans = rule(c, subjaxpr, backend, axis_env, env_nodes, in_nodes, **eqn.params)\n+ ans = rule(c, subjaxpr, axis_env, env_nodes, in_nodes, backend=backend, **eqn.params)\nelse:\nmsg = \"XLA translation rule for primitive '{}' not found\"\nraise NotImplementedError(msg.format(eqn.primitive.name))\n@@ -718,8 +729,8 @@ xla_call = partial(core.call_bind, xla_call_p)\nxla_call_p.def_custom_bind(xla_call)\nxla_call_p.def_impl(_xla_call_impl)\n-def _xla_call_translation_rule(c, jaxpr, backend, axis_env, env_nodes, in_nodes,\n- device_assignment):\n+def _xla_call_translation_rule(c, jaxpr, axis_env, env_nodes, in_nodes,\n+ device_assignment=None, backend=None):\ndel device_assignment # Unused.\nsubc = _jaxpr_computation(jaxpr, backend, axis_env, (), _map(c.GetShape, env_nodes),\n*map(c.GetShape, in_nodes))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1445,16 +1445,22 @@ _input_dtype = lambda *args, **_: xla_bridge.canonicalize_dtype(args[0].dtype)\n_fixed_dtype = lambda dtype: lambda *args, **kwargs: xla_bridge.canonicalize_dtype(dtype)\n_complex_basetype = lambda dtype: onp.abs(onp.zeros((), dtype)).dtype\n-def standard_primitive(shape_rule, dtype_rule, name, translation_rule=None, reduction=False):\n+def standard_primitive(shape_rule, dtype_rule, name, translation_rule=None):\nprim = Primitive(name)\nprim.def_impl(partial(xla.apply_primitive, prim))\nprim.def_abstract_eval(partial(standard_abstract_eval, shape_rule, dtype_rule))\n- if reduction:\n- xla.reduction_translations[prim] = translation_rule or partial(standard_translate, name)\n- else:\nxla.translations[prim] = translation_rule or partial(standard_translate, name)\nreturn prim\n+\n+def standard_reduction_primitive(shape_rule, dtype_rule, name, translation_rule=None):\n+ prim = Primitive(name)\n+ prim.def_impl(partial(xla.apply_primitive, prim))\n+ prim.def_abstract_eval(partial(standard_abstract_eval, shape_rule, dtype_rule))\n+ xla.reduction_translations[prim] = translation_rule or partial(standard_translate, name)\n+ return prim\n+\n+\ndef standard_abstract_eval(shape_rule, dtype_rule, *args, **kwargs):\nassert all(isinstance(arg, UnshapedArray) for arg in args), args\nleast_specialized = _max(\n@@ -3144,25 +3150,25 @@ def _scatter_batching_rule(\nscatter_dims_to_operand_dims=scatter_dims_to_operand_dims)\nreturn scatter_op(operand, scatter_indices, updates, dnums), 0\n-scatter_add_p = standard_primitive(\n+scatter_add_p = standard_reduction_primitive(\n_scatter_shape_rule, _scatter_dtype_rule, 'scatter-add',\n- _scatter_translation_rule, reduction=True)\n+ _scatter_translation_rule)\nad.primitive_jvps[scatter_add_p] = _scatter_add_jvp\nad.primitive_transposes[scatter_add_p] = _scatter_add_transpose_rule\nbatching.primitive_batchers[scatter_add_p] = (\npartial(_scatter_batching_rule, scatter_add))\n# TODO(jlebar): Add derivatives.\n-scatter_min_p = standard_primitive(\n+scatter_min_p = standard_reduction_primitive(\n_scatter_shape_rule, _scatter_dtype_rule, 'scatter-min',\n- _scatter_translation_rule, reduction=True)\n+ _scatter_translation_rule)\nbatching.primitive_batchers[scatter_min_p] = (\npartial(_scatter_batching_rule, scatter_min))\n# TODO(jlebar): Add derivatives.\n-scatter_max_p = standard_primitive(\n+scatter_max_p = standard_reduction_primitive(\n_scatter_shape_rule, _scatter_dtype_rule, 'scatter-max',\n- _scatter_translation_rule, reduction=True)\n+ _scatter_translation_rule)\nbatching.primitive_batchers[scatter_max_p] = (\npartial(_scatter_batching_rule, scatter_max))\n@@ -3260,9 +3266,9 @@ def _scatter_jvp(primals, tangents, update_jaxpr, update_consts,\nreturn val_out, tangent_out\n-scatter_p = standard_primitive(\n+scatter_p = standard_reduction_primitive(\n_scatter_shape_rule, _scatter_dtype_rule, 'scatter',\n- _scatter_translation_rule, reduction=True)\n+ _scatter_translation_rule)\nad.primitive_jvps[scatter_p] = _scatter_jvp\nbatching.primitive_batchers[scatter_p] = (\npartial(_scatter_batching_rule, scatter))\n@@ -3291,8 +3297,9 @@ def _reduction_computation(c, jaxpr, backend, consts, init_value):\nshape = c.GetShape(init_value)\nreturn xla.jaxpr_computation(jaxpr, backend, consts, (), shape, shape)\n-reduce_p = standard_primitive(_reduce_shape_rule, _input_dtype, 'reduce',\n- _reduce_translation_rule, reduction=True)\n+reduce_p = standard_reduction_primitive(\n+ _reduce_shape_rule, _input_dtype, 'reduce',\n+ _reduce_translation_rule)\nbatching.primitive_batchers[reduce_p] = _reduce_batch_rule\n@@ -3458,9 +3465,9 @@ def _generic_reduce_window_batch_rule(\nwindow_dimensions, window_strides, padding)\n-reduce_window_p = standard_primitive(\n+reduce_window_p = standard_reduction_primitive(\n_reduce_window_shape_rule, _input_dtype, 'reduce_window',\n- _reduce_window_translation_rule, reduction=True)\n+ _reduce_window_translation_rule)\nbatching.primitive_batchers[reduce_window_p] = _generic_reduce_window_batch_rule\n@@ -3597,9 +3604,9 @@ def _select_and_scatter_translation(\nreturn c.SelectAndScatter(operand, select, window_dimensions, window_strides,\npadding, source, init_value, scatter)\n-select_and_scatter_p = standard_primitive(\n+select_and_scatter_p = standard_reduction_primitive(\n_select_and_scatter_shape_rule, _input_dtype, 'select_and_scatter',\n- _select_and_scatter_translation, reduction=True)\n+ _select_and_scatter_translation)\ndef _select_and_scatter_add_shape_rule(\n"
}
] | Python | Apache License 2.0 | google/jax | Make op-by-op work with all jit-returned devicearrays. |
260,403 | 21.08.2019 01:06:04 | 25,200 | dbe4bdf944188e8de7d797aae39086aa1c1ff629 | add multibackend option to soft_pmap | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -753,16 +753,16 @@ def _axis_size(x):\nraise ValueError(\"could not get axis size of type: {}\".format(x))\n-def soft_pmap(fun, axis_name=None):\n+def soft_pmap(fun, axis_name=None, backend=None):\n_check_callable(fun)\naxis_name = _TempAxisName() if axis_name is None else axis_name\n@wraps(fun)\ndef f_pmapped(*args):\naxis_size = _pmap_axis_size(args)\n- chunk_size, leftover = divmod(axis_size, pxla.unmapped_device_count())\n+ chunk_size, leftover = divmod(axis_size, pxla.unmapped_device_count(backend))\nif chunk_size == 0 and leftover:\n- return pmap(fun, axis_name)(*args) # can map directly onto hardware\n+ return pmap(fun, axis_name, backend)(*args) # can map directly onto hardware\nelif leftover:\nraise ValueError\nnum_chunks = axis_size // chunk_size\n@@ -773,7 +773,8 @@ def soft_pmap(fun, axis_name=None):\nreshaped_args = map(partial(_reshape_split, num_chunks), in_flat)\nsoft_mapped_fun = pxla.split_axis(jaxtree_fun, axis_name, chunk_size)\nreshaped_out = pxla.xla_pmap(soft_mapped_fun, *reshaped_args,\n- axis_name=axis_name, axis_size=num_chunks)\n+ axis_name=axis_name, axis_size=num_chunks,\n+ backend=backend)\nreturn build_tree(out_tree(), _reshape_merge(reshaped_out))\nnamestr = \"soft_pmap({}, axis_name={})\".format\n"
}
] | Python | Apache License 2.0 | google/jax | add multibackend option to soft_pmap |
260,299 | 21.08.2019 14:27:23 | -3,600 | 9b19afd4d90956f10ed1a444bea52c3096db7812 | Implement Jaxpr __hash__
This means that primitives like scatter, which have a Jaxpr in their
**params, will get cache hits appropriately. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -54,6 +54,12 @@ class Jaxpr(object):\ndef __repr__(self):\nreturn self.__str__()\n+ def __hash__(self):\n+ return hash(self.__str__())\n+\n+ def __eq__(self, other):\n+ return type(other) is type(self) and str(self) == str(other)\n+\ndef copy(self):\nreturn Jaxpr(self.constvars[:], self.freevars[:], self.invars[:],\nself.outvar, self.eqns[:])\n"
}
] | Python | Apache License 2.0 | google/jax | Implement Jaxpr __hash__
This means that primitives like scatter, which have a Jaxpr in their
**params, will get cache hits appropriately. |
260,474 | 26.07.2019 18:01:38 | 14,400 | 20fad746a8407d3ba661edfcb1871557cf61cecf | De-dup equations with multiple lhs vars when creating a jaxpr | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -105,8 +105,12 @@ def jaxpr_as_fun(typed_jaxpr, *args):\nreturn out\n-JaxprEqn = namedtuple('JaxprEqn', ['invars', 'outvars', 'primitive',\n+def new_jaxpr_eqn(*args):\n+ return JaxprEqn(object(), *args)\n+\n+JaxprEqn = namedtuple('JaxprEqn', ['eqn_id', 'invars', 'outvars', 'primitive',\n'bound_subjaxprs', 'params'])\n+\nclass Literal(object):\n__slots__ = [\"val\", \"hash\"]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -28,7 +28,7 @@ from ..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,\nget_aval, AbstractValue, unit, unitvar,\n- Primitive, call_p, TypedJaxpr)\n+ Primitive, call_p, TypedJaxpr, new_jaxpr_eqn)\nmap = safe_map\nzip = safe_zip\n@@ -98,8 +98,10 @@ class JaxprTrace(Trace):\ntracers = map(self.instantiate_const, tracers)\navals = [t.aval for t in tracers]\nout_aval = primitive.abstract_eval(*avals, **params)\n- eqn = JaxprEqn(tracers, None, primitive, (), params)\n- return JaxprTracer(self, PartialVal((out_aval, unit)), eqn)\n+ out_tracer = JaxprTracer(self, PartialVal((out_aval, unit)), None)\n+ # TODO(dougalm): think about whether these ref cycles will leak memory\n+ out_tracer.recipe = new_jaxpr_eqn(tracers, [out_tracer], primitive, (), params)\n+ return out_tracer\ndef process_call(self, call_primitive, f, tracers, params):\nif call_primitive in map_primitives:\n@@ -112,9 +114,12 @@ class JaxprTrace(Trace):\nout_pv_consts, consts = (stuff[-N:], stuff[:-N])\nconst_tracers = map(self.new_instantiated_const, consts)\nbound_subjaxpr = (jaxpr, const_tracers, map(self.full_raise, env))\n- eqn = JaxprEqn(tracers, None, call_primitive, (bound_subjaxpr,), params)\n- return [JaxprTracer(self, PartialVal((out_pv, out_pv_const)), eqn)\n+ out_tracers = [JaxprTracer(self, PartialVal((out_pv, out_pv_const)), None)\nfor out_pv, out_pv_const in zip(out_pvs, out_pv_consts)]\n+ eqn = new_jaxpr_eqn(tracers, out_tracers, call_primitive, (bound_subjaxpr,), params)\n+ for t in out_tracers:\n+ t.recipe = eqn\n+ return out_tracers\ndef process_map(self, map_primitive, f, tracers, params):\nin_pvs, in_consts = unzip2([t.pval for t in tracers])\n@@ -406,12 +411,13 @@ FreeVar = namedtuple('FreeVar', ['val'])\nConstVar = namedtuple('ConstVar', ['val'])\nLambdaBinding = namedtuple('LambdaBinding', [])\n-def eqn_tracer_to_var(var, outvars, eqn):\n- invars, _, primitive, bound_subjaxprs, params = eqn\n- invars = map(var, invars)\n+def eqn_tracer_to_var(var, eqn):\n+ _, in_tracers, out_tracers, primitive, bound_subjaxprs, params = eqn\n+ invars = map(var, in_tracers)\n+ outvars = map(var, out_tracers)\nnew_bound_subjaxprs = [(j, map(var, c), map(var, f))\nfor j, c, f in bound_subjaxprs]\n- return JaxprEqn(invars, outvars, primitive, new_bound_subjaxprs, params)\n+ return new_jaxpr_eqn(invars, outvars, primitive, new_bound_subjaxprs, params)\ndef tracers_to_jaxpr(in_tracers, out_tracers):\n@@ -425,10 +431,13 @@ def tracers_to_jaxpr(in_tracers, out_tracers):\nconsts = {}\nconst_to_var = defaultdict(newvar)\ndestructuring_vars = {}\n+ processed_eqns = set()\nfor t in sorted_tracers:\nrecipe = t.recipe\nif isinstance(recipe, JaxprEqn):\n- eqns.append(eqn_tracer_to_var(var, [var(t)], recipe))\n+ if recipe.eqn_id not in processed_eqns:\n+ eqns.append(eqn_tracer_to_var(var, recipe))\n+ processed_eqns.add(recipe.eqn_id)\nelif isinstance(recipe, LambdaBinding):\nassert any(t is in_tracer for in_tracer in in_tracers)\nassert in_tracers, \"Lambda binding with no args\"\n@@ -439,15 +448,6 @@ def tracers_to_jaxpr(in_tracers, out_tracers):\nconsts[v] = recipe.val\nelif isinstance(recipe, Literal):\nt_to_var[id(t)] = recipe\n- elif isinstance(recipe, Destructuring):\n- i, eqn, key = recipe\n- if key not in destructuring_vars:\n- outvars = [newvar() for _ in eqn.outvars]\n- eqns.append(eqn_tracer_to_var(var, outvars, eqn))\n- destructuring_vars[key] = outvars\n- else:\n- outvars = destructuring_vars[key]\n- t_to_var[id(t)] = outvars[i]\nelif recipe is unit:\nt_to_var[id(t)] = unitvar\nelse:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -625,7 +625,6 @@ def _xla_callable(fun, device_assignment, *abstract_args):\naxis_env = AxisEnv(jaxpr_replicas(jaxpr), [], [])\ncompiled, result_shapes = _compile_jaxpr(jaxpr, device_assignment, axis_env, consts,\n*abstract_args)\n- print(jaxpr)\ndel master, consts, jaxpr, env\nhandle_result = result_handler(result_shape)\nif axis_env.nreps == 1:\n"
}
] | Python | Apache License 2.0 | google/jax | De-dup equations with multiple lhs vars when creating a jaxpr
Co-authored-by: Matthew Johnson <mattjj@google.com> |
260,474 | 26.07.2019 23:17:21 | 14,400 | c53c8bbb438a01310d48a27a46087651e820bd07 | Some progress de-tupling ad.py | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -44,7 +44,7 @@ from . import core\nfrom . import linear_util as lu\nfrom . import ad_util\nfrom .core import eval_jaxpr\n-from .api_util import (wraps, flatten_fun, abstract_tuple_tree_leaves)\n+from .api_util import (wraps, flatten_fun, abstract_tuple_tree_leaves, apply_flat_fun)\nfrom .tree_util import (process_pytree, node_types, build_tree, PyTreeDef,\ntree_map, tree_flatten, tree_unflatten, tree_structure,\ntree_transpose, leaf, tree_leaves)\n@@ -283,23 +283,13 @@ def xla_computation(fun, static_argnums=(), axis_env=None):\n@wraps(fun)\ndef computation_maker(*args, **kwargs):\nwrapped = lu.wrap_init(fun)\n- jax_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+ jax_args, in_tree = tree_flatten((args, kwargs))\n+ jaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)\npvals = map(pv_like, jax_args)\njaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals)\naxis_env_ = make_axis_env(xla.jaxpr_replicas(jaxpr))\nreturn xla.build_jaxpr(jaxpr, axis_env_, consts,\n*map(xla.abstractify, jax_args))\n- else:\n- jax_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\n- jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun2(wrapped, kwargs_tree, in_trees)\n- pvals = map(pv_like, (jax_kwargs,) + tuple(jax_args))\n- jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals)\n- axis_env_ = make_axis_env(xla.jaxpr_replicas(jaxpr))\n- return xla.build_jaxpr(jaxpr, axis_env_, consts, xla.abstractify(jax_kwargs),\n- *map(xla.abstractify, jax_args))\n-\nreturn computation_maker\ndef grad(fun, argnums=0, has_aux=False, holomorphic=False):\n@@ -773,9 +763,7 @@ def soft_pmap(fun, axis_name=None):\ndef _reshape_split(num_chunks, arg):\ndef split(aval, arg):\nt = type(aval)\n- if t is core.AbstractTuple:\n- return core.pack(map(split, aval, arg))\n- elif t is ShapedArray:\n+ if t is ShapedArray:\nprefix = (num_chunks, arg.shape[0] // num_chunks)\nreturn arg.reshape(prefix + arg.shape[1:])\nelse:\n@@ -786,9 +774,7 @@ def _reshape_split(num_chunks, arg):\ndef _reshape_merge(ans):\ndef merge(aval, ans):\nt = type(aval)\n- if t is core.AbstractTuple:\n- return core.pack(map(merge, aval, ans))\n- elif t is ShapedArray:\n+ if t is ShapedArray:\nreturn ans.reshape((-1,) + ans.shape[2:])\nelse:\nraise TypeError(aval)\n@@ -866,18 +852,16 @@ def jvp(fun, primals, tangents):\n>>> print(v)\n0.19900084\n\"\"\"\n- def trim_arg(primal, tangent):\n- primal_jtuple, tree_def = pytree_to_jaxtupletree(primal)\n- tangent_jtuple, tree_def_2 = pytree_to_jaxtupletree(tangent)\n- assert tree_def == tree_def_2, (tree_def, tree_def_2)\n- return primal_jtuple, tangent_jtuple, tree_def\n-\nif not isinstance(fun, lu.WrappedFun):\nfun = lu.wrap_init(fun)\n- ps_flat, ts_flat, in_trees = unzip3(map(trim_arg, primals, tangents))\n- jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(fun, in_trees)\n- out_primal, out_tangent = ad.jvp(jaxtree_fun).call_wrapped(ps_flat, ts_flat)\n- return (build_tree(out_tree(), out_primal), build_tree(out_tree(), out_tangent))\n+\n+ ps_flat, tree_def = tree_flatten((primals, {}))\n+ ts_flat, tree_def_2 = tree_flatten((tangents, {}))\n+ assert tree_def == tree_def_2, (tree_def, tree_def_2)\n+ flat_fun, out_tree = flatten_fun(fun, tree_def)\n+ out_primals, out_tangents = ad.jvp(flat_fun).call_wrapped(ps_flat, ts_flat)\n+ return (tree_unflatten(out_tree(), out_primals),\n+ tree_unflatten(out_tree(), out_tangents))\ndef linearize(fun, *primals):\n\"\"\"Produce a linear approximation to `fun` using `jvp` and partial evaluation.\n@@ -934,14 +918,14 @@ def linearize(fun, *primals):\n-6.676704\n\"\"\"\nf = lu.wrap_init(fun)\n- primals_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, primals))\n- jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(f, in_trees)\n- out_primal, out_pval, jaxpr, consts = ad.linearize(jaxtree_fun, *primals_flat)\n+ primals_flat, in_tree = tree_flatten((primals, {}))\n+ jaxtree_fun, out_tree = flatten_fun(f, in_tree)\n+ out_primals, out_pvals, jaxpr, consts = ad.linearize(jaxtree_fun, *primals_flat)\nout_tree = out_tree()\n- out_primal_py = build_tree(out_tree, out_primal)\n+ out_primal_py = tree_unflatten(out_tree, out_primals)\nprimal_avals = list(map(core.get_aval, primals_flat))\nlifted_jvp = partial(lift_linearized, jaxpr, primal_avals, consts,\n- (in_trees, out_tree), out_pval)\n+ (in_tree, out_tree), out_pvals)\nreturn out_primal_py, lifted_jvp\ndef lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pval, *py_args):\n@@ -954,12 +938,11 @@ def lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pval, *py_args):\nmsg = (\"linearized function called on tangent values inconsistent with \"\n\"the original primal values.\")\nraise 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)\n+ dummy = tangents\n+ _, ans = eval_jaxpr(jaxpr, consts, (), dummy, tangents)\nreturn pe.merge_pvals(ans, out_pval)\n- return apply_jaxtree_fun(fun, io_tree, *py_args)\n+ return apply_flat_fun(fun, io_tree, *py_args)\ndef _check_inexact_input_vjp(x):\naval = core.get_aval(x)\n@@ -1007,10 +990,10 @@ def vjp(fun, *primals, **kwargs):\nassert not kwargs\nif not isinstance(fun, lu.WrappedFun):\nfun = lu.wrap_init(fun)\n- primals_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, primals))\n+ primals_flat, in_tree = tree_flatten(primals)\n_check_args(primals_flat)\ntree_map(_check_inexact_input_vjp, primals)\n- jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(fun, in_trees)\n+ jaxtree_fun, out_tree = flatten_fun(fun, in_tree)\nif not has_aux:\nout_primal, out_vjp = ad.vjp(jaxtree_fun, primals_flat)\nelse:\n@@ -1018,7 +1001,7 @@ def vjp(fun, *primals, **kwargs):\nout_tree = out_tree()\nif has_aux:\nout_tree, aux_tree = treedef_children(out_tree)\n- out_primal_py = build_tree(out_tree, out_primal)\n+ out_primal_py = tree_unflatten(out_tree, out_primal)\nct_in_trees = [out_tree]\nct_out_tree = treedef_tuple(in_trees)\ndef out_vjp_packed(cotangent_in):\n@@ -1027,7 +1010,7 @@ def vjp(fun, *primals, **kwargs):\nif not has_aux:\nreturn out_primal_py, vjp_py\nelse:\n- return out_primal_py, vjp_py, build_tree(aux_tree, aux)\n+ return out_primal_py, vjp_py, tree_unflatten(aux_tree, aux)\ndef trace_to_jaxpr(traceable, py_pvals, **kwargs):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/api_util.py",
"new_path": "jax/api_util.py",
"diff": "@@ -44,6 +44,14 @@ def flatten_fun(in_tree, *args_flat):\nans = yield py_args, py_kwargs\nyield tree_flatten(ans)\n+def apply_flat_fun(fun, io_tree, *py_args):\n+ in_tree_expected, out_tree = io_tree\n+ args, in_tree = tree_flatten((py_args, {}))\n+ if in_tree != in_tree_expected:\n+ raise TypeError(\"Expected {}, got {}\".format(in_tree_expected, in_tree))\n+ ans = fun(*args)\n+ return tree_unflatten(out_tree, ans)\n+\ndef abstract_tuple_tree_leaves(aval):\nif type(aval) is AbstractTuple:\nfor elt in aval:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -27,6 +27,8 @@ from ..abstract_arrays import raise_to_shaped\nfrom ..util import unzip2, unzip3, safe_map, safe_zip, partial\nfrom ..tree_util import process_pytree, build_tree, register_pytree_node, tree_map\nfrom ..linear_util import thunk, staged, transformation, transformation_with_aux, wrap_init\n+from ..api_util import flatten_fun # TODO: can we avoid this?\n+from ..tree_util import tree_flatten, tree_unflatten\nfrom six.moves import builtins, reduce\n@@ -58,9 +60,9 @@ def jvp_subtrace(master, primals, tangents):\nif isinstance(x, Tracer):\nassert x.trace.level < trace.level\nans = yield map(partial(JVPTracer, trace), primals, tangents), {}\n- out_tracer = trace.full_raise(ans)\n- out_primal, out_tangent = out_tracer.primal, out_tracer.tangent\n- yield (out_primal, out_tangent)\n+ out_tracers = map(trace.full_raise, ans)\n+ yield unzip2([(out_tracer.primal, out_tracer.tangent)\n+ for out_tracer in out_tracers])\n@transformation_with_aux\ndef jvp_subtrace_aux(instantiate, master, primals, tangents):\n@@ -75,30 +77,27 @@ def jvp_subtrace_aux(instantiate, master, primals, tangents):\nout_tangent = instantiate_zeros_at(instantiate, out_primal, out_tangent)\nyield (out_primal, out_tangent), aux\n-\n-@transformation\n-def pack_output(*args):\n- ans = yield args, {}\n- yield pack(ans)\n-\ndef linearize(traceable, *primals, **kwargs):\nhas_aux = kwargs.pop('has_aux', False)\nif not has_aux:\n- jvpfun = pack_output(jvp(traceable))\n+ jvpfun = jvp(traceable)\nelse:\n+ assert False, \"TODO\"\njvpfun, aux = jvp(traceable, has_aux=True)\n- jvpfun = pack_output(jvpfun)\n- tangent_avals = [get_aval(p).at_least_vspace() for p in primals]\n- in_pvals = (pe.PartialVal((None, pack(primals))),\n- pe.PartialVal((core.AbstractTuple(tangent_avals), core.unit)))\n- jaxpr, out_pval, consts = pe.trace_to_jaxpr(jvpfun, in_pvals)\n- pval_primal, pval_tangent = unpair_pval(out_pval)\n- aval_primal, const_primal = pval_primal\n- assert aval_primal is None\n+\n+ in_pvals = (tuple(pe.PartialVal((None, p)) for p in primals)\n+ + tuple(pe.PartialVal((get_aval(p).at_least_vspace(), core.unit))\n+ for p in primals))\n+ _, in_tree = tree_flatten(((primals, primals), {}))\n+ jvpfun_flat, out_tree = flatten_fun(jvpfun, in_tree)\n+ jaxpr, out_pvals, consts = pe.trace_to_jaxpr(jvpfun_flat, in_pvals)\n+ pval_primals, pval_tangents = tree_unflatten(out_tree(), out_pvals)\n+ aval_primals, const_primals = unzip2(pval_primals)\n+ assert all(aval_primal is None for aval_primal in aval_primals)\nif not has_aux:\n- return const_primal, pval_tangent, jaxpr, consts\n+ return const_primals, pval_tangents, jaxpr, consts\nelse:\n- return const_primal, pval_tangent, jaxpr, consts, aux()\n+ return const_primals, pval_tangents, jaxpr, consts, aux()\ndef vjp(traceable, primals, has_aux=False):\nif not has_aux:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -31,9 +31,9 @@ import jax\nimport jax.numpy as np\nfrom jax import jit, grad, device_get, device_put, jacfwd, jacrev, hessian\nfrom jax import api, lax\n-from jax.core import Primitive, pack, JaxTuple\n+from jax.core import Primitive\nfrom jax.interpreters import ad\n-from jax.interpreters.xla import DeviceArray, DeviceTuple\n+from jax.interpreters.xla import DeviceArray\nfrom jax.abstract_arrays import concretization_err_msg\nfrom jax.lib import xla_bridge as xb\nfrom jax import test_util as jtu\n"
}
] | Python | Apache License 2.0 | google/jax | Some progress de-tupling ad.py |
260,474 | 27.07.2019 10:43:40 | 14,400 | 3c37a3260ab96c73d17270cb8c198d4c51eb0536 | Update linearize to no-tuple version | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -928,7 +928,7 @@ def linearize(fun, *primals):\n(in_tree, out_tree), out_pvals)\nreturn out_primal_py, lifted_jvp\n-def lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pval, *py_args):\n+def lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args):\ndef fun(*tangents):\ntangent_avals = list(map(core.get_aval, tangents))\nfor primal_aval, tangent_aval in zip(primal_avals, tangent_avals):\n@@ -939,8 +939,9 @@ def lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pval, *py_args):\n\"the original primal values.\")\nraise ValueError(msg)\ndummy = tangents\n- _, ans = eval_jaxpr(jaxpr, consts, (), dummy, tangents)\n- return pe.merge_pvals(ans, out_pval)\n+ out = eval_jaxpr(jaxpr, consts, (), *(dummy + tangents))\n+ tangents_out = out[len(out)//2:]\n+ return tuple(map(pe.merge_pvals, tangents_out, out_pvals))\nreturn apply_flat_fun(fun, io_tree, *py_args)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -140,6 +140,8 @@ class Literal(object):\nliteralable_types = set()\nclass Primitive(object):\n+ multiple_results = False # override for multi-output primitives\n+\ndef __init__(self, name):\nself.name = name\n@@ -197,20 +199,18 @@ def eval_jaxpr(jaxpr, consts, freevar_vals, *args):\npat_fmap(write, jaxpr.invars, args)\npat_fmap(write, jaxpr.freevars, freevar_vals)\nfor eqn in jaxpr.eqns:\n- if not eqn.restructure:\nin_vals = map(read, eqn.invars)\n- else:\n- in_vals = [pack(map(read, invars)) if type(invars) is tuple\n- else read(invars) for invars in eqn.invars]\nsubfuns = [partial(eval_jaxpr, subjaxpr, map(read, const_bindings),\nmap(read, freevar_bindings))\nfor subjaxpr, const_bindings, freevar_bindings\nin eqn.bound_subjaxprs]\nsubfuns = map(lu.wrap_init, subfuns)\nans = eqn.primitive.bind(*(subfuns + in_vals), **eqn.params)\n- outvals = list(ans) if eqn.destructure else [ans]\n- map(write, eqn.outvars, outvals)\n- return read(jaxpr.outvar)\n+ if eqn.primitive.multiple_results:\n+ map(write, eqn.outvars, ans)\n+ else:\n+ write(eqn.outvars[0], ans)\n+ return tuple(map(read, jaxpr.outvars))\ndef pat_fmap(f, v, *xs):\n"
}
] | Python | Apache License 2.0 | google/jax | Update linearize to no-tuple version |
260,329 | 21.08.2019 13:40:50 | 14,400 | 451ff2d694f497e94d1f68e281308a0c840e2e00 | Cope with old numpy lacking axis arg | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1516,11 +1516,18 @@ def _wrap_numpy_nullary_function(f):\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,\naxis=0):\n+ try:\nout = onp.linspace(start, stop, num, endpoint, retstep, dtype, axis)\nif retstep:\nreturn asarray(out[0]), out[1]\nelse:\nreturn asarray(out)\n+ except TypeError: # Old versions of onp may lack axis arg.\n+ out = onp.linspace(start, stop, num, endpoint, retstep, dtype)\n+ if retstep:\n+ return moveaxis(asarray(out[0]), 0, axis), out[1]\n+ else:\n+ return moveaxis(asarray(out), 0, axis)\nlogspace = _wrap_numpy_nullary_function(onp.logspace)\ngeomspace = _wrap_numpy_nullary_function(onp.geomspace)\n"
}
] | Python | Apache License 2.0 | google/jax | Cope with old numpy lacking axis arg |
260,335 | 21.08.2019 13:53:57 | 25,200 | f56312bbfff3973ac3d2ca813c0699a0bfce61ad | remove pat_fmap | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -172,9 +172,9 @@ def eval_jaxpr(jaxpr, consts, freevar_vals, *args):\nenv = {}\nwrite(unitvar, unit)\n- pat_fmap(write, jaxpr.constvars, consts)\n- pat_fmap(write, jaxpr.invars, args)\n- pat_fmap(write, jaxpr.freevars, freevar_vals)\n+ map(write, jaxpr.constvars, consts)\n+ map(write, jaxpr.invars, args)\n+ map(write, jaxpr.freevars, freevar_vals)\nfor eqn in jaxpr.eqns:\nin_vals = map(read, eqn.invars)\nsubfuns = [partial(eval_jaxpr, subjaxpr, map(read, const_bindings),\n@@ -190,16 +190,6 @@ def eval_jaxpr(jaxpr, consts, freevar_vals, *args):\nreturn map(read, jaxpr.outvars)\n-def pat_fmap(f, v, *xs):\n- if type(v) in (tuple, list):\n- if len(xs) == 1 and xs[0] is None:\n- return tuple(map(partial(pat_fmap, f), v, [None] * len(v)))\n- else:\n- return tuple(map(partial(pat_fmap, f), v, *xs))\n- else:\n- return f(v, *xs)\n-\n-\ndef full_lower(val):\nif isinstance(val, Tracer):\nreturn val.full_lower()\n@@ -612,9 +602,9 @@ def check_jaxpr(jaxpr):\nwrite = partial(write_env, env)\nwrite(unitvar)\n- pat_fmap(write, jaxpr.constvars)\n- pat_fmap(write, jaxpr.freevars)\n- pat_fmap(write, jaxpr.invars)\n+ map(write, jaxpr.constvars)\n+ map(write, jaxpr.freevars)\n+ map(write, jaxpr.invars)\nfor eqn in jaxpr.eqns:\nmap(read, eqn.invars)\nfor subjaxpr, constvars, freevars in eqn.bound_subjaxprs:\n"
}
] | Python | Apache License 2.0 | google/jax | remove pat_fmap |
260,335 | 21.08.2019 15:28:23 | 25,200 | 765af9774916cd8f75a842754a444a7b1822e634 | make stax.sigmoid call scipy.special.expit
improves numerical stability of differentiation, so that in particular
now jax.hessian(sigmoid)(-100.) doesn't produce a nan | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -30,7 +30,7 @@ from six.moves import reduce\nfrom jax import lax\nfrom jax import random\n-from jax.scipy.special import logsumexp\n+from jax.scipy.special import logsumexp, expit\nimport jax.numpy as np\n@@ -41,7 +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))\n+def sigmoid(x): return expit(x)\ndef elu(x): return np.where(x > 0, x, np.expm1(x))\ndef leaky_relu(x): return np.where(x >= 0, x, 0.01 * x)\n"
}
] | Python | Apache License 2.0 | google/jax | make stax.sigmoid call scipy.special.expit
improves numerical stability of differentiation, so that in particular
now jax.hessian(sigmoid)(-100.) doesn't produce a nan |
260,335 | 21.08.2019 16:39:32 | 25,200 | 06b5c402dcc38d3bdcb10fd45dd803134da36296 | update tree_util_tests w/ None not a pytree | [
{
"change_type": "MODIFY",
"old_path": "tests/tree_util_tests.py",
"new_path": "tests/tree_util_tests.py",
"diff": "@@ -57,10 +57,10 @@ PYTREES = [\n((),),\n(([()]),),\n((1, 2),),\n- (((1, \"foo\"), [\"bar\", (3, None, 7)]),),\n+ (((1, \"foo\"), [\"bar\", (3, (), 7)]),),\n([3],),\n- ([3, ATuple(foo=(3, ATuple(foo=3, bar=None)), bar={\"baz\": 34})],),\n- ([AnObject(3, None, [4, \"foo\"])],),\n+ ([3, ATuple(foo=(3, ATuple(foo=3, bar=())), bar={\"baz\": 34})],),\n+ ([AnObject(3, (), [4, \"foo\"])],),\n({\"a\": 1, \"b\": 2},),\n]\n@@ -112,19 +112,19 @@ class TreeTest(jtu.JaxTestCase):\nself.assertEqual([c0, c1], tree.children())\ndef testFlattenUpTo(self):\n- _, tree = tree_util.tree_flatten([(1, 2), None, ATuple(foo=3, bar=7)])\n+ _, tree = tree_util.tree_flatten([(1, 2), (), ATuple(foo=3, bar=7)])\nif not hasattr(tree, \"flatten_up_to\"):\nself.skipTest(\"Test requires Jaxlib >= 0.1.23\")\nout = tree.flatten_up_to([({\n\"foo\": 7\n- }, (3, 4)), None, ATuple(foo=(11, 9), bar=None)])\n- self.assertEqual(out, [{\"foo\": 7}, (3, 4), (11, 9), None])\n+ }, (3, 4)), (), ATuple(foo=(11, 9), bar=())])\n+ self.assertEqual(out, [{\"foo\": 7}, (3, 4), (11, 9), ()])\ndef testTreeMultimap(self):\nx = ((1, 2), (3, 4, 5))\n- y = (([3], None), ({\"foo\": \"bar\"}, 7, [5, 6]))\n+ y = (([3], ()), ({\"foo\": \"bar\"}, 7, [5, 6]))\nout = tree_util.tree_multimap(lambda *xs: tuple(xs), x, y)\n- self.assertEqual(out, (((1, [3]), (2, None)),\n+ self.assertEqual(out, (((1, [3]), (2, ())),\n((3, {\"foo\": \"bar\"}), (4, 7), (5, [5, 6]))))\n"
}
] | Python | Apache License 2.0 | google/jax | update tree_util_tests w/ None not a pytree |
260,335 | 21.08.2019 16:39:59 | 25,200 | 7323e1546e45c5e6820666bb7a3a55afa21cb41f | fix ShardedDeviceArray.__getitem__ | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -344,8 +344,7 @@ class ShardedDeviceArray(ShardedDeviceValue, xla.DeviceArray):\nif self._npy_value is None and type(idx) is int:\nids = self._ids()\ndevice_buffer = self.device_buffers[ids[idx]]\n- result_shape = aval_from_xla_shape(device_buffer.shape())\n- handler = xla.result_handler(result_shape)\n+ handler = xla.aval_to_result_handler(self.aval)\nreturn handler(device_buffer)\nelse:\nreturn super(ShardedDeviceArray, self).__getitem__(idx)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -657,6 +657,19 @@ class PmapTest(jtu.JaxTestCase):\nmulti_step_pmap(np.zeros((device_count,)), count=1)\n+ def testShardedDeviceArrayGetItem(self):\n+ f = lambda x: 2 * x\n+ f = pmap(f, axis_name='i')\n+\n+ shape = (xla_bridge.device_count(), 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+\n+ y = f(x)\n+ self.assertIsInstance(y, np.ndarray)\n+ self.assertIsInstance(y, pxla.ShardedDeviceArray)\n+\n+ z = y[0] # doesn't crash\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix ShardedDeviceArray.__getitem__ |
260,403 | 21.08.2019 18:07:14 | 25,200 | 88a1fbf68548aab5abc88d511784d274d73ea749 | Error on nested conflicting explicit jit backend specifications. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -266,7 +266,15 @@ def _jaxpr_computation(jaxpr, backend, axis_env, const_vals, freevar_shapes, *ar\n_map(write, jaxpr.invars, map(c.ParameterWithShape, arg_shapes))\n_prefetch_jaxpr_literals(jaxpr)\nfor eqn in jaxpr.eqns:\n- eqn.params.pop('backend', None)\n+ # For nested jits, the outer jit sets the backend on all inner jits unless\n+ # an inner-jit also has a conflicting explicit backend specification.\n+ inner_backend = eqn.params.pop('backend', None)\n+ if inner_backend and inner_backend != backend:\n+ msg = (\n+ \"Explicit outer-jit backend specification {} must match\"\n+ \"explicit inner-jit backend specification {}.\")\n+ raise ValueError(msg.format(backend, inner_backend))\n+\nif not eqn.restructure:\nin_nodes = list(map(read, eqn.invars))\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | Error on nested conflicting explicit jit backend specifications. |
260,335 | 21.08.2019 20:36:47 | 25,200 | 8517997518d10aa1885be0b67ad60cc3fc7e28b8 | minor fixes from trax, revise eval_shape api | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1660,15 +1660,33 @@ def _make_graphviz(fun):\nreturn graphviz_maker\n+class ShapeDtypeStruct(object):\n+ __slots__ = [\"shape\", \"dtype\"]\n+ def __init__(self, shape, dtype):\n+ self.shape = shape\n+ self.dtype = dtype\n+\ndef eval_shape(fun, *args, **kwargs):\n- \"\"\"Compute the shape of ``fun(*args, **kwargs)`` without incurring any FLOPs.\n+ \"\"\"Compute the shape/dtype of ``fun(*args, **kwargs)`` without any FLOPs.\nThis utility function is useful for performing shape inference. Its\ninput/output behavior is defined by:\ndef eval_shape(fun, *args, **kwargs):\nout = fun(*args, **kwargs)\n- return jax.tree_util.tree_map(np.shape, out)\n+ return jax.tree_util.tree_map(shape_dtype_struct, out)\n+\n+ def shape_dtype_struct(x):\n+ return ShapeDtypeStruct(x.shape, x.dtype)\n+\n+ class ShapeDtypeStruct(object):\n+ __slots__ = [\"shape\", \"dtype\"]\n+ def __init__(self, shape, dtype):\n+ self.shape = shape\n+ self.dtype = dtype\n+\n+ In particular, the output is a pytree of objects that have ``shape`` and\n+ ``dtype`` attributes, but nothing else about them is guaranteed by the API.\nBut instead of applying ``fun`` directly, which might be expensive, it uses\nJAX's abstract interpretation machinery to evaluate the shapes without doing\n@@ -1698,16 +1716,20 @@ def eval_shape(fun, *args, **kwargs):\n...\n>>> A = MyArgArray((2000, 3000), np.float32)\n>>> x = MyArgArray((3000, 1000), np.float32)\n- >>> out_shape = jax.eval_shape(f, A, x) # no FLOPs performed\n- >>> print(out_shape)\n+ >>> out = jax.eval_shape(f, A, x) # no FLOPs performed\n+ >>> print(out.shape)\n(2000, 1000)\n+ >>> print(out.dtype)\n+ dtype('float32')\n\"\"\"\ndef abstractify(x):\nreturn ShapedArray(onp.shape(x), onp.result_type(x))\nargs_flat, in_tree = tree_flatten((args, kwargs))\nfun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\nout = pe.abstract_eval_fun(fun.call_wrapped, *map(abstractify, args_flat))\n- return tree_map(onp.shape, tree_unflatten(out_tree(), out))\n+ out = [ShapeDtypeStruct(x.shape, x.dtype) for x in out]\n+ return tree_unflatten(out_tree(), out)\n+\ndef _custom_implicit_solve(solve, tangent_solve):\n\"\"\"Define gradients for a function that performs an implicit solve.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -344,7 +344,8 @@ class ShardedDeviceArray(ShardedDeviceValue, xla.DeviceArray):\nif self._npy_value is None and type(idx) is int:\nids = self._ids()\ndevice_buffer = self.device_buffers[ids[idx]]\n- handler = xla.aval_to_result_handler(self.aval)\n+ aval = ShapedArray(self.aval.shape[1:], self.aval.dtype)\n+ handler = xla.aval_to_result_handler(aval)\nreturn handler(device_buffer)\nelse:\nreturn super(ShardedDeviceArray, self).__getitem__(idx)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -37,6 +37,7 @@ from jax.interpreters.xla import DeviceArray\nfrom jax.abstract_arrays import concretization_err_msg\nfrom jax.lib import xla_bridge as xb\nfrom jax import test_util as jtu\n+from jax import tree_util\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -734,7 +735,7 @@ class APITest(jtu.JaxTestCase):\ny = np.ones((3, 4))\nout_shape = api.eval_shape(fun, x, y)\n- self.assertEqual(out_shape, (2, 4))\n+ self.assertEqual(out_shape.shape, (2, 4))\ndef test_eval_shape_constants(self):\ndef fun():\n@@ -744,7 +745,7 @@ class APITest(jtu.JaxTestCase):\nout_shape = api.eval_shape(fun)\n- self.assertEqual(out_shape, (2, 4))\n+ self.assertEqual(out_shape.shape, (2, 4))\ndef test_eval_shape_tuple_unpacking(self):\ndef fun(x, y):\n@@ -755,7 +756,7 @@ class APITest(jtu.JaxTestCase):\ny = 3.\nout_shape = api.eval_shape(fun, x, y)\n- self.assertEqual(out_shape, (2,))\n+ self.assertEqual(out_shape.shape, (2,))\ndef test_eval_shape_tuple_itemgetting(self):\ndef fun(x, y):\n@@ -765,7 +766,7 @@ class APITest(jtu.JaxTestCase):\ny = 3.\nout_shape = api.eval_shape(fun, x, y)\n- self.assertEqual(out_shape, (2,))\n+ self.assertEqual(out_shape.shape, (2,))\ndef test_eval_shape_output_dict(self):\ndef fun(x, y):\n@@ -774,6 +775,7 @@ class APITest(jtu.JaxTestCase):\nx = (np.ones(2), np.ones(2))\ny = 3.\nout_shape = api.eval_shape(fun, x, y)\n+ out_shape = tree_util.tree_map(onp.shape, out_shape)\nself.assertEqual(out_shape, {'hi': (2,)})\n@@ -800,7 +802,7 @@ class APITest(jtu.JaxTestCase):\nx = MyArgArray((4, 5), np.float32)\nout_shape = api.eval_shape(fun, A, b, x)\n- self.assertEqual(out_shape, (3, 5))\n+ self.assertEqual(out_shape.shape, (3, 5))\ndef test_issue_871(self):\nT = np.array([[1., 2.], [3., 4.], [5., 6.]])\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -669,6 +669,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertIsInstance(y, pxla.ShardedDeviceArray)\nz = y[0] # doesn't crash\n+ self.assertAllClose(z, 2 * x[0], check_dtypes=False)\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | minor fixes from trax, revise eval_shape api |
260,403 | 21.08.2019 20:59:18 | 25,200 | c839c6a602ed9eb9e97715c31b481a6ba2a2bd0b | Added basic behavior unit tests of multibackend jit. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/multibackend_test.py",
"diff": "+# Copyright 2018 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+from functools import partial\n+\n+from absl.testing import absltest\n+from absl.testing import parameterized\n+\n+import numpy as onp\n+import numpy.random as npr\n+import six\n+\n+from jax import api\n+from jax import test_util as jtu\n+from jax import numpy as np\n+\n+from jax.config import config\n+config.parse_flags_with_absl()\n+FLAGS = config.FLAGS\n+npr.seed(0)\n+\n+\n+class MultiBackendTest(jtu.JaxTestCase):\n+ \"\"\"Tests jit targeting to different backends.\"\"\"\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_backend={}\".format(backend),\n+ \"backend\": backend,\n+ }\n+ for backend in ['cpu', 'gpu']\n+ ))\n+ @jtu.skip_on_devices('cpu', 'tpu')\n+ def testGpuMultiBackend(self, backend):\n+ @partial(api.jit, backend=backend)\n+ def fun(x, y):\n+ return np.matmul(x, y)\n+ x = npr.uniform(size=(10,10))\n+ y = npr.uniform(size=(10,10))\n+ z_host = onp.matmul(x, y)\n+ z = fun(x, y)\n+ self.assertAllClose(z, z_host, check_dtypes=True)\n+ self.assertEqual(z.device_buffer.platform(), backend)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_backend={}\".format(backend),\n+ \"backend\": backend,\n+ }\n+ for backend in ['cpu', 'tpu']\n+ ))\n+ @jtu.skip_on_devices('cpu', 'gpu')\n+ def testTpuMultiBackend(self, backend):\n+ @partial(api.jit, backend=backend)\n+ def fun(x, y):\n+ return np.matmul(x, y)\n+ x = npr.uniform(size=(10,10))\n+ y = npr.uniform(size=(10,10))\n+ z_host = onp.matmul(x, y)\n+ z = fun(x, y)\n+ self.assertAllClose(z, z_host, check_dtypes=True)\n+ self.assertEqual(z.device_buffer.platform(), backend)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_ordering={}\".format(ordering),\n+ \"ordering\": ordering,}\n+ for ordering in [('cpu', None), ('tpu', None)]))\n+ @jtu.skip_on_devices('cpu', 'gpu')\n+ def testTpuMultiBackendNestedJit(self, ordering):\n+ outer, inner = ordering\n+ @partial(api.jit, backend=outer)\n+ def fun(x, y):\n+ @partial(api.jit, backend=inner)\n+ def infun(x, y):\n+ return np.matmul(x, y)\n+ return infun(x, y) + np.ones_like(x)\n+ x = npr.uniform(size=(10,10))\n+ y = npr.uniform(size=(10,10))\n+ z_host = onp.matmul(x, y) + onp.ones_like(x)\n+ z = fun(x, y)\n+ self.assertAllClose(z, z_host, check_dtypes=True)\n+ self.assertEqual(z.device_buffer.platform(), outer)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_ordering={}\".format(ordering),\n+ \"ordering\": ordering,}\n+ for ordering in [('cpu', None), ('gpu', None)]))\n+ @jtu.skip_on_devices('cpu', 'tpu')\n+ def testGpuMultiBackendNestedJit(self, ordering):\n+ outer, inner = ordering\n+ @partial(api.jit, backend=outer)\n+ def fun(x, y):\n+ @partial(api.jit, backend=inner)\n+ def infun(x, y):\n+ return np.matmul(x, y)\n+ return infun(x, y) + np.ones_like(x)\n+ x = npr.uniform(size=(10,10))\n+ y = npr.uniform(size=(10,10))\n+ z_host = onp.matmul(x, y) + onp.ones_like(x)\n+ z = fun(x, y)\n+ self.assertAllClose(z, z_host, check_dtypes=True)\n+ self.assertEqual(z.device_buffer.platform(), outer)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_ordering={}\".format(ordering),\n+ \"ordering\": ordering,}\n+ for ordering in [\n+ ('cpu', 'tpu'), ('tpu', 'cpu'), (None, 'cpu'), (None, 'tpu'),\n+ ]))\n+ @jtu.skip_on_devices('cpu', 'gpu')\n+ def testTpuMultiBackendNestedJitConflict(self, ordering):\n+ outer, inner = ordering\n+ @partial(api.jit, backend=outer)\n+ def fun(x, y):\n+ @partial(api.jit, backend=inner)\n+ def infun(x, y):\n+ return np.matmul(x, y)\n+ return infun(x, y) + np.ones_like(x)\n+ x = npr.uniform(size=(10,10))\n+ y = npr.uniform(size=(10,10))\n+ self.assertRaises(ValueError, lambda: fun(x, y))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_ordering={}\".format(ordering),\n+ \"ordering\": ordering,}\n+ for ordering in [\n+ ('cpu', 'gpu'), ('gpu', 'cpu'), (None, 'cpu'), (None, 'gpu'),\n+ ]))\n+ @jtu.skip_on_devices('cpu', 'tpu')\n+ def testGpuMultiBackendNestedJitConflict(self, ordering):\n+ outer, inner = ordering\n+ @partial(api.jit, backend=outer)\n+ def fun(x, y):\n+ @partial(api.jit, backend=inner)\n+ def infun(x, y):\n+ return np.matmul(x, y)\n+ return infun(x, y) + np.ones_like(x)\n+ x = npr.uniform(size=(10,10))\n+ y = npr.uniform(size=(10,10))\n+ self.assertRaises(ValueError, lambda: fun(x, y))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_backend={}\".format(backend),\n+ \"backend\": backend,}\n+ for backend in ['cpu', 'gpu']\n+ ))\n+ @jtu.skip_on_devices('cpu', 'tpu')\n+ def testGpuMultiBackendOpByOpReturn(self, backend):\n+ @partial(api.jit, backend=backend)\n+ def fun(x, y):\n+ return np.matmul(x, y)\n+ x = npr.uniform(size=(10,10))\n+ y = npr.uniform(size=(10,10))\n+ z = fun(x, y)\n+ w = np.sin(z)\n+ self.assertEqual(z.device_buffer.platform(), backend)\n+ self.assertEqual(w.device_buffer.platform(), 'gpu')\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_backend={}\".format(backend),\n+ \"backend\": backend,}\n+ for backend in ['cpu', 'tpu']\n+ ))\n+ @jtu.skip_on_devices('cpu', 'gpu')\n+ def testTpuMultiBackendOpByOpReturn(self, backend):\n+ @partial(api.jit, backend=backend)\n+ def fun(x, y):\n+ return np.matmul(x, y)\n+ x = npr.uniform(size=(10,10))\n+ y = npr.uniform(size=(10,10))\n+ z = fun(x, y)\n+ w = np.sin(z)\n+ self.assertEqual(z.device_buffer.platform(), backend)\n+ self.assertEqual(w.device_buffer.platform(), 'tpu')\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | Added basic behavior unit tests of multibackend jit. |
260,335 | 22.08.2019 12:50:47 | 25,200 | de6ce2a55584ed05d371070e1767cd73ae7357d9 | allow vmap in_axes to be lists | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -616,7 +616,7 @@ def _flatten_axes(treedef, axis_tree):\n# TODO(mattjj): remove this when jaxlib is updated past 0.1.25\ndef _replace_nones(tuptree):\n- if type(tuptree) is tuple:\n+ if type(tuptree) in (list, tuple):\nreturn tuple(map(_replace_nones, tuptree))\nelse:\nreturn tuptree if tuptree is not None else _none_proxy\n"
}
] | Python | Apache License 2.0 | google/jax | allow vmap in_axes to be lists |
260,314 | 22.08.2019 22:53:31 | 14,400 | 9f876c485028d0f94ddd0cd60fa0fe8ec23ed9f8 | fix cond with true_consts | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -304,8 +304,9 @@ def cond(pred, true_operand, true_fun, false_operand, false_fun):\ndef _cond_impl(pred, *args, **kwargs):\ntrue_jaxpr, false_jaxpr, true_nconsts, false_nconsts = split_dict(\nkwargs, [\"true_jaxpr\", \"false_jaxpr\", \"true_nconsts\", \"false_nconsts\"])\n+ true_nops = len(true_jaxpr.in_avals) - true_nconsts\ntrue_consts, true_ops, false_consts, false_ops = split_list(\n- args, [true_nconsts, len(true_jaxpr.in_avals), false_nconsts])\n+ args, [true_nconsts, true_nops, false_nconsts])\nif pred:\nreturn core.jaxpr_as_fun(true_jaxpr)(*(true_consts + true_ops))\n@@ -319,7 +320,6 @@ def _cond_translation_rule(c, axis_env, pred, *args, **kwargs):\ntrue_jaxpr, false_jaxpr, true_nconsts, false_nconsts = split_dict(\nkwargs, [\"true_jaxpr\", \"false_jaxpr\", \"true_nconsts\", \"false_nconsts\"])\ntrue_nops = len(true_jaxpr.in_avals) - true_nconsts\n- false_nops = len(false_jaxpr.in_avals) - false_nconsts\ntrue_consts, true_ops, false_consts, false_ops = split_list(\nargs, [true_nconsts, true_nops, false_nconsts])\n"
}
] | Python | Apache License 2.0 | google/jax | fix cond with true_consts |
260,403 | 22.08.2019 20:50:31 | 25,200 | 8bbe1b0c6a6455535bcd1ced1056c555e46625c9 | fix kwarg order bug for device constant put handler | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -77,7 +77,7 @@ xla_result_handlers[ConcreteArray] = array_result_handler\ndef device_put(x, device_num=0, backend=None):\nx = canonicalize_dtype(x)\ntry:\n- return device_put_handlers[type(x)](x, device_num, backend)\n+ return device_put_handlers[type(x)](x, device_num, backend=backend)\nexcept KeyError:\nraise TypeError(\"No device_put handler for type: {}\".format(type(x)))\ndevice_put_handlers = {}\n@@ -670,7 +670,7 @@ class DeviceConstant(DeviceArray):\ndef constant_handler(c, constant_instance, canonicalize_types=True):\nassert False\n-def _instantiate_device_constant(const, device_num=0, cutoff=1e6, backend=None):\n+def _instantiate_device_constant(const, device_num=0, backend=None, cutoff=1e6):\n# dispatch an XLA Computation to build the constant on the device if it's\n# large, or alternatively build it on the host and transfer it if it's small\nassert isinstance(const, DeviceConstant)\n"
}
] | Python | Apache License 2.0 | google/jax | fix kwarg order bug for device constant put handler |
260,403 | 22.08.2019 21:17:05 | 25,200 | 78c04fe3bd330cec4026ca9c99ba592c3a2af769 | fix default kwarg issue | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -346,7 +346,7 @@ def eqn_replicas(eqn):\ndef _xla_call_impl(fun, *args, **params):\ndevice_assignment = params['device_assignment']\n- backend = params['backend']\n+ backend = params.get('backend', None)\ncompiled_fun = _xla_callable(fun, device_assignment, backend,\n*map(abstractify, args))\ntry:\n"
}
] | Python | Apache License 2.0 | google/jax | fix default kwarg issue |
260,403 | 23.08.2019 01:20:39 | 25,200 | ceca1b7ae04b5502169fe089ddea06e7504e7664 | try not to sabotage all jax users, use normalized platform names to control device_put behavior. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -629,9 +629,9 @@ def _device_array_constant_handler(c, val, canonicalize_types=True):\nxb.register_constant_handler(DeviceArray, _device_array_constant_handler)\ndef _device_put_device_array(x, device_num, backend):\n# TODO(levskaya) remove if-condition after increasing minimum Jaxlib version to\n- # 0.1.24.\n+ # 0.1.24. We assume users with older Jaxlib won't use multiple backends.\nif hasattr(x.device_buffer, 'platform'):\n- backend_match = x.device_buffer.platform() == backend\n+ backend_match = xb.get_backend(backend).platform == x.device_buffer.platform()\nelse:\nbackend_match = True\nif backend_match:\n"
}
] | Python | Apache License 2.0 | google/jax | try not to sabotage all jax users, use normalized platform names to control device_put behavior. |
260,335 | 23.08.2019 07:47:42 | 25,200 | 7539325f26f6527537013812abf7b531374bb414 | ensure DeviceArray.aval is ShapedArray
Fixes which was caused by DeviceArray.aval, and hence
xla.abstractify(device_array), being a ConcreteArray, leading to
compilation cache misses all the time because those are necessarily
cached on id. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -308,12 +308,14 @@ class ShardedDeviceArray(ShardedDeviceValue, xla.DeviceArray):\n_collect = staticmethod(onp.stack)\ndef __init__(self, aval, device_buffers):\n- # aval must be a ShapedArray instance, because the aval_mapping rules\n- # return it unmodified.\nself.aval = aval\nself.device_buffers = device_buffers\nself.axis_size = aval.shape[0]\nself._npy_value = None\n+ if not core.skip_checks:\n+ assert type(aval) is ShapedArray\n+ npy_value = self._value\n+ assert npy_value.dtype == aval.dtype and npy_value.shape == aval.shape\ndef _ids(self):\nnum_bufs = len(self.device_buffers)\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)\n+ array_types, raise_to_shaped)\nfrom ..core import valid_jaxtype, Literal\nfrom ..util import partial, partialmethod, cache, safe_map, prod, unzip2\nfrom ..lib import xla_bridge as xb\n@@ -70,7 +70,7 @@ def aval_to_result_handler(aval):\nraise TypeError(\"No xla_result_handler for type: {}\".format(type(aval)))\nxla_result_handlers = {}\nxla_result_handlers[core.AbstractUnit] = lambda _: lambda _: core.unit\n-def array_result_handler(aval): return partial(DeviceArray, aval)\n+def array_result_handler(aval): return partial(DeviceArray, raise_to_shaped(aval))\nxla_result_handlers[ShapedArray] = array_result_handler\nxla_result_handlers[ConcreteArray] = array_result_handler\n@@ -483,6 +483,7 @@ class DeviceArray(DeviceValue):\nself.device_buffer = device_buffer\nself._npy_value = None\nif not core.skip_checks:\n+ assert type(aval) is ShapedArray\nnpy_value = self._value\nassert npy_value.dtype == aval.dtype and npy_value.shape == aval.shape\n"
}
] | Python | Apache License 2.0 | google/jax | ensure DeviceArray.aval is ShapedArray
Fixes #1239, which was caused by DeviceArray.aval, and hence
xla.abstractify(device_array), being a ConcreteArray, leading to
compilation cache misses all the time because those are necessarily
cached on id. |
260,335 | 23.08.2019 08:17:41 | 25,200 | 98c7567a0d1ba9ca4bc3e72d6043632f96dcddc7 | add flag for logging when jit performs compilation | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -476,6 +476,7 @@ bot = Bot()\nclass AbstractUnit(AbstractValue):\ndef join(self, other): return self\n+ def _eq(self, self_traced, other): return get_aval(other) is self\nabstract_unit = AbstractUnit()\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -314,8 +314,6 @@ class ShardedDeviceArray(ShardedDeviceValue, xla.DeviceArray):\nself._npy_value = None\nif not core.skip_checks:\nassert type(aval) is ShapedArray\n- npy_value = self._value\n- assert npy_value.dtype == aval.dtype and npy_value.shape == aval.shape\ndef _ids(self):\nnum_bufs = len(self.device_buffers)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -44,6 +44,9 @@ FLAGS = flags.FLAGS\nflags.DEFINE_bool('jax_debug_nans',\nstrtobool(os.getenv('JAX_DEBUG_NANS', \"False\")),\n'Add nan checks to every operation.')\n+flags.DEFINE_bool('jax_log_compiles',\n+ strtobool(os.getenv('JAX_LOG_COMPILES', \"False\")),\n+ 'Print a message each time a `jit` computation is compiled.')\ndef _map(f, *xs): return tuple(map(f, *xs))\ndef identity(x): return x\n@@ -339,6 +342,8 @@ def _xla_call_impl(fun, *args, **params):\n@lu.cache\ndef _xla_callable(fun, device_assignment, *abstract_args):\n+ if FLAGS.jax_log_compiles:\n+ print(\"Compiling {} for args {}.\".format(fun.__name__, abstract_args))\npvals = [pe.PartialVal((aval, core.unit)) for aval in abstract_args]\nwith core.new_master(pe.JaxprTrace, True) as master:\njaxpr, (pvals, consts, env) = pe.trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/linear_util.py",
"new_path": "jax/linear_util.py",
"diff": "@@ -141,6 +141,10 @@ class WrappedFun(object):\nself.stores = stores\nself.params = params\n+ @property\n+ def __name__(self):\n+ return getattr(self.f, '__name__', '<unnamed wrapped function>')\n+\ndef wrap(self, gen, gen_args, out_store):\nreturn WrappedFun(self.f, ((gen, gen_args),) + self.transforms,\n(out_store,) + self.stores, self.params)\n"
}
] | Python | Apache License 2.0 | google/jax | add flag for logging when jit performs compilation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.