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,314 | 28.03.2019 17:59:42 | 14,400 | a0636eaedd3934e65f877c2159449d04d4b84a9d | implement cauchy pdf and random sampler | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -32,6 +32,7 @@ from . import lax\nfrom . import numpy as np\nfrom . import tree_util\nfrom .api import jit\n+from .numpy.lax_numpy import _constant_like\nfrom jax.lib import xla_bridge\nfrom jax import core\n@@ -381,3 +382,21 @@ def bernoulli(key, mean=onp.float32(0.5), shape=()):\nif onp.shape(mean) != shape:\nmean = np.broadcast_to(mean, shape)\nreturn lax.lt(uniform(key, shape), mean)\n+\n+\n+@partial(jit, static_argnums=(1, 2))\n+def cauchy(key, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Cauchy 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 float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ u = uniform(key, shape, dtype)\n+ pi = _constant_like(u, onp.pi)\n+ return lax.tan(pi * lax.sub(u, _constant_like(u, 0.5)))\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/scipy/stats/cauchy.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+import numpy as onp\n+import scipy.stats as osp_stats\n+\n+from ... import lax\n+from ...numpy.lax_numpy import _promote_args_like, _constant_like, _wraps\n+\n+\n+@_wraps(osp_stats.cauchy.logpdf)\n+def logpdf(x, loc=0, scale=1):\n+ x, loc, scale = _promote_args_like(osp_stats.cauchy.logpdf, x, loc, scale)\n+ one = _constant_like(x, 1)\n+ pi = _constant_like(x, onp.pi)\n+ scaled_x = lax.div((lax.sub(x, loc)), scale)\n+ normalize_term = lax.log(lax.mul(pi, scale))\n+ return lax.neg(lax.add(normalize_term, lax.log(one + scaled_x * scaled_x)))\n+\n+@_wraps(osp_stats.cauchy.pdf)\n+def pdf(x, loc=0, scale=1):\n+ return lax.exp(logpdf(x, loc, scale))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -156,6 +156,20 @@ class LaxRandomTest(jtu.JaxTestCase):\nx = random.bernoulli(key, onp.array([0.2, 0.3]), shape=(3, 2))\nassert x.shape == (3, 2)\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 testCauchy(self, dtype):\n+ key = random.PRNGKey(0)\n+ rand = lambda key: random.cauchy(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.cauchy().cdf)\n+\ndef testIssue222(self):\nx = random.randint(random.PRNGKey(10003), (), 0, 0)\nassert x == 0\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -177,5 +177,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+\n+ @genNamedParametersNArgs(3, jtu.rand_default())\n+ def testNormLogPdf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.norm.logpdf\n+ lax_fun = lsp_stats.norm.logpdf\n+\n+ def args_maker():\n+ x, loc, scale = map(rng, shapes, dtypes)\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 [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+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | implement cauchy pdf and random sampler |
260,314 | 28.03.2019 18:02:20 | 14,400 | 16be2262e333eaced41bca300a2d0d777932c9a2 | add cauchy to init file | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/__init__.py",
"new_path": "jax/scipy/stats/__init__.py",
"diff": "from __future__ import absolute_import\nfrom . import beta\n+from . import cauchy\nfrom . import expon\nfrom . import gamma\nfrom . import laplace\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -179,9 +179,9 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\n@genNamedParametersNArgs(3, jtu.rand_default())\n- def testNormLogPdf(self, rng, shapes, dtypes):\n- scipy_fun = osp_stats.norm.logpdf\n- lax_fun = lsp_stats.norm.logpdf\n+ def testCauchyLogPdf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.cauchy.logpdf\n+ lax_fun = lsp_stats.cauchy.logpdf\ndef args_maker():\nx, loc, scale = map(rng, shapes, dtypes)\n"
}
] | Python | Apache License 2.0 | google/jax | add cauchy to init file |
260,299 | 28.03.2019 22:06:27 | 0 | ce3953ebb34b2b59a9187b3aa2cfb32241b7cbb2 | Stabler expit and logit derivatives | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -20,6 +20,8 @@ import numpy as onp\nimport scipy.special as osp_special\nfrom .. import lax\n+from ..api import custom_transforms\n+from ..interpreters import ad\nfrom ..numpy import lax_numpy as np\nfrom ..numpy.lax_numpy import _wraps, asarray, _reduction_dims, _constant_like\n@@ -33,16 +35,20 @@ erfinv = _wraps(osp_special.erfinv)(lambda x: lax.erf_inv(x))\n@_wraps(osp_special.logit)\n+@custom_transforms\ndef logit(x):\nx = asarray(x)\nreturn lax.log(lax.div(x, lax.sub(lax._const(x, 1), x)))\n+ad.defjvp2(logit.primitive, lambda g, ans, x: g / (x * (1 - x)))\n@_wraps(osp_special.expit)\n+@custom_transforms\ndef expit(x):\nx = asarray(x)\none = lax._const(x, 1)\nreturn lax.div(one, lax.add(one, lax.exp(lax.neg(x))))\n+ad.defjvp2(expit.primitive, lambda g, ans, x: g * ans * (1 - ans))\n@_wraps(osp_special.logsumexp)\n"
}
] | Python | Apache License 2.0 | google/jax | Stabler expit and logit derivatives |
260,299 | 28.03.2019 22:18:04 | 0 | b2bd93c801b8d8fdb63fc97279ba50e18c62d755 | Setup batching for expit and logit | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -21,7 +21,7 @@ import scipy.special as osp_special\nfrom .. import lax\nfrom ..api import custom_transforms\n-from ..interpreters import ad\n+from ..interpreters import ad, batching\nfrom ..numpy import lax_numpy as np\nfrom ..numpy.lax_numpy import _wraps, asarray, _reduction_dims, _constant_like\n@@ -40,6 +40,7 @@ def logit(x):\nx = asarray(x)\nreturn lax.log(lax.div(x, lax.sub(lax._const(x, 1), x)))\nad.defjvp2(logit.primitive, lambda g, ans, x: g / (x * (1 - x)))\n+batching.defvectorized(logit.primitive)\n@_wraps(osp_special.expit)\n@@ -49,6 +50,7 @@ def expit(x):\none = lax._const(x, 1)\nreturn lax.div(one, lax.add(one, lax.exp(lax.neg(x))))\nad.defjvp2(expit.primitive, lambda g, ans, x: g * ans * (1 - ans))\n+batching.defvectorized(expit.primitive)\n@_wraps(osp_special.logsumexp)\n"
}
] | Python | Apache License 2.0 | google/jax | Setup batching for expit and logit |
260,299 | 28.03.2019 22:27:37 | 0 | 13d1d7c4591e7f5f5f40c0ed9b92cbef3bce86c4 | Remove logit todo from lax_scipy_test | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_scipy_test.py",
"new_path": "tests/lax_scipy_test.py",
"diff": "@@ -66,7 +66,6 @@ JAX_SPECIAL_FUNCTION_RECORDS = [\nop_record(\"expit\", 1, float_dtypes, jtu.rand_small_positive(), True),\n# TODO: gammaln has slightly high error.\nop_record(\"gammaln\", 1, float_dtypes, jtu.rand_positive(), False),\n- # TODO: NaNs in gradient for logit.\nop_record(\"logit\", 1, float_dtypes, jtu.rand_small_positive(), False),\nop_record(\"log_ndtr\", 1, float_dtypes, jtu.rand_small(), True),\nop_record(\"ndtri\", 1, float_dtypes, jtu.rand_uniform(0., 1.), True),\n"
}
] | Python | Apache License 2.0 | google/jax | Remove logit todo from lax_scipy_test |
260,314 | 28.03.2019 23:57:00 | 14,400 | 890ba842a91b53faef77208df3f641aeea2bc428 | implement expon and laplace sampler | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -399,4 +399,39 @@ def cauchy(key, shape=(), dtype=onp.float32):\n\"\"\"\nu = uniform(key, shape, dtype)\npi = _constant_like(u, onp.pi)\n- return lax.tan(pi * lax.sub(u, _constant_like(u, 0.5)))\n+ return lax.tan(lax.mul(pi, lax.sub(u, _constant_like(u, 0.5))))\n+\n+\n+@partial(jit, static_argnums=(1, 2))\n+def exponential(key, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Exponential 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 float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ u = uniform(key, shape, dtype)\n+ # taking 1 - u to move the domain of log to (0, 1] instead of [0, 1)\n+ return lax.neg(lax.log(lax.sub(_constant_like(u, 1), u)))\n+\n+\n+@partial(jit, static_argnums=(1, 2))\n+def laplace(key, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Laplace 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 float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ u = uniform(key, shape, dtype, minval=-1., maxval=1.)\n+ return lax.mul(lax.sign(u), lax.log1p(lax.neg(lax.abs(u))))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -170,6 +170,34 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor samples in [uncompiled_samples, compiled_samples]:\nself._CheckKolmogorovSmirnovCDF(samples, scipy.stats.cauchy().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 testExponential(self, dtype):\n+ key = random.PRNGKey(0)\n+ rand = lambda key: random.exponential(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.expon().cdf)\n+\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 testLaplace(self, dtype):\n+ key = random.PRNGKey(0)\n+ rand = lambda key: random.laplace(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.laplace().cdf)\n+\ndef testIssue222(self):\nx = random.randint(random.PRNGKey(10003), (), 0, 0)\nassert x == 0\n"
}
] | Python | Apache License 2.0 | google/jax | implement expon and laplace sampler |
260,335 | 29.03.2019 08:03:58 | 25,200 | aa6cebff440519bddd611b0f6b9bc841bdec0b18 | fix typo in vmap (fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -413,8 +413,7 @@ def vmap(fun, in_axes=0, out_axes=0):\n@wraps(fun, docstr=docstr)\ndef batched_fun(*args, **kwargs):\n- if not isinstance(fun, lu.WrappedFun):\n- f = lu.wrap_init(fun, kwargs)\n+ f = 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))\njaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(f, in_trees)\n"
}
] | Python | Apache License 2.0 | google/jax | fix typo in vmap (fixes #536) |
260,314 | 30.03.2019 00:00:15 | 14,400 | 0bb657d646d4994407c4177642dc8892e7dea04b | add stats.t.pdf | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/__init__.py",
"new_path": "jax/scipy/stats/__init__.py",
"diff": "@@ -20,4 +20,5 @@ from . import gamma\nfrom . import laplace\nfrom . import multivariate_normal\nfrom . import norm\n+from . import t\nfrom . import uniform\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/cauchy.py",
"new_path": "jax/scipy/stats/cauchy.py",
"diff": "@@ -28,9 +28,9 @@ def logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.cauchy.logpdf, x, loc, scale)\none = _constant_like(x, 1)\npi = _constant_like(x, onp.pi)\n- scaled_x = lax.div((lax.sub(x, loc)), scale)\n+ scaled_x = lax.div(lax.sub(x, loc), scale)\nnormalize_term = lax.log(lax.mul(pi, scale))\n- return lax.neg(lax.add(normalize_term, lax.log(one + scaled_x * scaled_x)))\n+ return lax.neg(lax.add(normalize_term, lax.log(one + lax.mul(scaled_x, scaled_x))))\n@_wraps(osp_stats.cauchy.pdf)\ndef pdf(x, loc=0, scale=1):\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/scipy/stats/t.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+import numpy as onp\n+import scipy.stats as osp_stats\n+\n+from ... import lax\n+from ...numpy.lax_numpy import _promote_args_like, _constant_like, _wraps\n+\n+\n+@_wraps(osp_stats.t.logpdf)\n+def logpdf(x, df, loc=0, scale=1):\n+ x, df, loc, scale = _promote_args_like(osp_stats.t.logpdf, x, df, loc, scale)\n+ two = _constant_like(x, 2)\n+ scaled_x = lax.div(lax.sub(x, loc), scale)\n+ df_over_two = lax.div(df, two)\n+ df_plus_one_over_two = lax.add(df_over_two, _constant_like(x, 0.5))\n+ normalize_term_const = lax.mul(lax.mul(scale, scale), _constant_like(x, onp.pi))\n+ normalize_term_tmp = lax.div(lax.log(lax.mul(normalize_term_const, df)), two)\n+ normalize_term = lax.sub(lax.add(lax.lgamma(df_over_two), normalize_term_tmp),\n+ lax.lgamma(df_plus_one_over_two))\n+ quadratic = lax.div(lax.mul(scaled_x, scaled_x), df)\n+ return lax.neg(lax.add(normalize_term, lax.mul(df_plus_one_over_two, lax.log1p(quadratic))))\n+\n+@_wraps(osp_stats.t.pdf)\n+def pdf(x, loc=0, scale=1):\n+ return lax.exp(logpdf(x, loc, scale))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -62,6 +62,20 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\ntol=1e-4)\nself._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n+ @genNamedParametersNArgs(3, jtu.rand_default())\n+ def testCauchyLogPdf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.cauchy.logpdf\n+ lax_fun = lsp_stats.cauchy.logpdf\n+\n+ def args_maker():\n+ x, loc, scale = map(rng, shapes, dtypes)\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 [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@genNamedParametersNArgs(3, jtu.rand_positive())\ndef testExponLogPdf(self, rng, shapes, dtypes):\nscipy_fun = osp_stats.expon.logpdf\n@@ -165,29 +179,29 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nself._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n- @genNamedParametersNArgs(3, jtu.rand_default())\n- def testUniformLogPdf(self, rng, shapes, dtypes):\n- scipy_fun = osp_stats.uniform.logpdf\n- lax_fun = lsp_stats.uniform.logpdf\n+ @genNamedParametersNArgs(4, jtu.rand_default())\n+ def testTLogPdf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.t.logpdf\n+ lax_fun = lsp_stats.t.logpdf\ndef args_maker():\n- x, loc, scale = map(rng, shapes, dtypes)\n- return [x, loc, onp.abs(scale)]\n+ x, df, loc, scale = map(rng, shapes, dtypes)\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 [x, df, loc, scale]\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 testCauchyLogPdf(self, rng, shapes, dtypes):\n- scipy_fun = osp_stats.cauchy.logpdf\n- lax_fun = lsp_stats.cauchy.logpdf\n+ def testUniformLogPdf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.uniform.logpdf\n+ lax_fun = lsp_stats.uniform.logpdf\ndef args_maker():\nx, loc, scale = map(rng, shapes, dtypes)\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 [x, loc, scale]\n+ return [x, loc, onp.abs(scale)]\nself._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=True)\nself._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n"
}
] | Python | Apache License 2.0 | google/jax | add stats.t.pdf |
260,660 | 30.03.2019 17:18:53 | -32,400 | eb4945c0112ebf5550b41929e78802c1a6139424 | DOC: Fix typo in `ops.index_update` | [
{
"change_type": "MODIFY",
"old_path": "jax/ops/scatter.py",
"new_path": "jax/ops/scatter.py",
"diff": "@@ -214,7 +214,7 @@ def index_update(x, idx, y):\nReturns the value of `x` that would result from the\nNumPy-style :mod:`indexed assignment <numpy.doc.indexing>`::\n- x[idx] += y\n+ x[idx] = y\nNote the `index_update` operator is pure; `x` itself is\nnot modified, instead the new value that `x` would have taken is returned.\n"
}
] | Python | Apache License 2.0 | google/jax | DOC: Fix typo in `ops.index_update` |
260,314 | 30.03.2019 16:34:20 | 14,400 | bb095d3df534a8f5d6c55cc449ee923160a90d6f | implement pareto logpdf and sampler | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -435,3 +435,26 @@ def laplace(key, shape=(), dtype=onp.float32):\n\"\"\"\nu = uniform(key, shape, dtype, minval=-1., maxval=1.)\nreturn lax.mul(lax.sign(u), lax.log1p(lax.neg(lax.abs(u))))\n+\n+\n+@partial(jit, static_argnums=(2, 3))\n+def pareto(key, b, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Pareto random values with given shape and float dtype.\n+\n+ Args:\n+ key: a PRNGKey used as the random key.\n+ b: an array-like broadcastable to `shape` and used as the shape parameter\n+ of the random variables.\n+ shape: optional, a tuple of nonnegative integers representing the shape\n+ (default scalar).\n+ dtype: optional, a float dtype for the returned values (default float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ b = lax.convert_element_type(b, dtype)\n+ shape = shape or onp.shape(b)\n+ if onp.shape(b) != shape:\n+ b = np.broadcast_to(b, shape)\n+ e = exponential(key, shape, dtype)\n+ return lax.exp(lax.div(e, b))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/__init__.py",
"new_path": "jax/scipy/stats/__init__.py",
"diff": "@@ -20,5 +20,6 @@ from . import gamma\nfrom . import laplace\nfrom . import multivariate_normal\nfrom . import norm\n+from . import pareto\nfrom . import t\nfrom . import uniform\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/scipy/stats/pareto.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+import numpy as onp\n+import scipy.stats as osp_stats\n+\n+from ... import lax\n+from ...numpy.lax_numpy import _promote_args_like, _constant_like, _wraps, inf, where\n+\n+\n+@_wraps(osp_stats.pareto.logpdf)\n+def logpdf(x, b, loc=0, scale=1):\n+ x, b, loc, scale = _promote_args_like(osp_stats.pareto.logpdf, x, b, loc, scale)\n+ one = _constant_like(x, 1)\n+ scaled_x = lax.div(lax.sub(x, loc), scale)\n+ normalize_term = lax.log(lax.div(scale, b))\n+ log_probs = lax.neg(lax.add(normalize_term, lax.mul(lax.add(b, one), lax.log(scaled_x))))\n+ return where(lax.lt(x, lax.add(loc, scale)), -inf, log_probs)\n+\n+@_wraps(osp_stats.pareto.pdf)\n+def pdf(x, b, loc=0, scale=1):\n+ return lax.exp(logpdf(x, b, loc, scale))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -151,7 +151,8 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertFalse(onp.all(perm1 == x)) # seems unlikely!\nself.assertTrue(onp.all(onp.sort(perm1) == x))\n- def testBernoulli(self):\n+ # TODO: add Kolmogorov-Smirnov test for Bernoulli\n+ def testBernoulliShape(self):\nkey = random.PRNGKey(0)\nx = random.bernoulli(key, onp.array([0.2, 0.3]), shape=(3, 2))\nassert x.shape == (3, 2)\n@@ -198,6 +199,27 @@ 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\": \"_b={}_{}\".format(b, dtype),\n+ \"b\": b, \"dtype\": onp.dtype(dtype).name}\n+ for b in [0.1, 1., 10.]\n+ for dtype in [onp.float32, onp.float64]))\n+ def testPareto(self, b, dtype):\n+ key = random.PRNGKey(0)\n+ rand = lambda key, b: random.pareto(key, b, (10000,), dtype)\n+ crand = api.jit(rand)\n+\n+ uncompiled_samples = rand(key, b)\n+ compiled_samples = crand(key, b)\n+\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ self._CheckKolmogorovSmirnovCDF(samples, scipy.stats.pareto(b).cdf)\n+\n+ def testParetoShape(self):\n+ key = random.PRNGKey(0)\n+ x = random.pareto(key, onp.array([0.2, 0.3]), shape=(3, 2))\n+ assert x.shape == (3, 2)\n+\ndef testIssue222(self):\nx = random.randint(random.PRNGKey(10003), (), 0, 0)\nassert x == 0\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -179,6 +179,19 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nself._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n+ @genNamedParametersNArgs(4, jtu.rand_positive())\n+ def testParetoLogPdf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.pareto.logpdf\n+ lax_fun = lsp_stats.pareto.logpdf\n+\n+ def args_maker():\n+ x, b, loc, scale = map(rng, shapes, dtypes)\n+ return [x, b, 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_default())\ndef testTLogPdf(self, rng, shapes, dtypes):\nscipy_fun = osp_stats.t.logpdf\n"
}
] | Python | Apache License 2.0 | google/jax | implement pareto logpdf and sampler |
260,314 | 30.03.2019 16:45:17 | 14,400 | 096ba63ba6f5c8514c21f7390ce45b7734e2245e | correct TODO test name for bernoulli | [
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -151,7 +151,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertFalse(onp.all(perm1 == x)) # seems unlikely!\nself.assertTrue(onp.all(onp.sort(perm1) == x))\n- # TODO: add Kolmogorov-Smirnov test for Bernoulli\n+ # TODO: add Chi-squared test for Bernoulli\ndef testBernoulliShape(self):\nkey = random.PRNGKey(0)\nx = random.bernoulli(key, onp.array([0.2, 0.3]), shape=(3, 2))\n"
}
] | Python | Apache License 2.0 | google/jax | correct TODO test name for bernoulli |
260,314 | 30.03.2019 17:15:49 | 14,400 | 5309d53a3626dc14504c63a8742511158ae3dfa1 | change behaviour at distribution boundary | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/beta.py",
"new_path": "jax/scipy/stats/beta.py",
"diff": "@@ -35,8 +35,8 @@ def logpdf(x, a, b, loc=0, scale=1):\nlog_linear_term = lax.add(lax.mul(lax.sub(a, one), lax.log(y)),\nlax.mul(lax.sub(b, one), lax.log(lax.sub(one, y))))\nlog_probs = lax.sub(lax.add(shape_term, log_linear_term), lax.log(scale))\n- return where(logical_or(lax.ge(x, lax.add(loc, scale)),\n- lax.le(x, loc)), -inf, log_probs)\n+ return where(logical_or(lax.gt(x, lax.add(loc, scale)),\n+ lax.lt(x, loc)), -inf, log_probs)\n@_wraps(osp_stats.beta.pdf)\ndef pdf(x, a, b, loc=0, scale=1):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/expon.py",
"new_path": "jax/scipy/stats/expon.py",
"diff": "@@ -29,7 +29,7 @@ def logpdf(x, loc=0, scale=1):\nlog_scale = lax.log(scale)\nlinear_term = lax.div(lax.sub(x, loc), scale)\nlog_probs = lax.neg(lax.add(linear_term, log_scale))\n- return where(lax.le(x, loc), -inf, log_probs)\n+ return where(lax.lt(x, loc), -inf, log_probs)\n@_wraps(osp_stats.expon.pdf)\ndef pdf(x, loc=0, scale=1):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/gamma.py",
"new_path": "jax/scipy/stats/gamma.py",
"diff": "@@ -33,7 +33,7 @@ def logpdf(x, a, loc=0, scale=1):\nlog_linear_term = lax.sub(lax.mul(lax.sub(a, one), lax.log(y)), y)\nshape_terms = lax.add(gammaln(a), lax.log(scale))\nlog_probs = lax.sub(log_linear_term, shape_terms)\n- return where(lax.le(x, loc), -inf, log_probs)\n+ return where(lax.lt(x, loc), -inf, log_probs)\n@_wraps(osp_stats.gamma.pdf)\ndef pdf(x, a, loc=0, scale=1):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/uniform.py",
"new_path": "jax/scipy/stats/uniform.py",
"diff": "@@ -26,8 +26,8 @@ from ...numpy.lax_numpy import _promote_args_like, _wraps, where, inf, logical_o\ndef logpdf(x, loc=0, scale=1):\nx, loc, scale = _promote_args_like(osp_stats.uniform.logpdf, x, loc, scale)\nlog_probs = lax.neg(lax.log(scale))\n- return where(logical_or(lax.ge(x, lax.add(loc, scale)),\n- lax.le(x, loc)), -inf, log_probs)\n+ return where(logical_or(lax.gt(x, lax.add(loc, scale)),\n+ lax.lt(x, loc)), -inf, log_probs)\n@_wraps(osp_stats.uniform.pdf)\ndef pdf(x, loc=0, scale=1):\n"
}
] | Python | Apache License 2.0 | google/jax | change behaviour at distribution boundary |
260,314 | 30.03.2019 18:07:34 | 14,400 | e0567b6d169c2a4598139d9b9e49670d0b744587 | add Gamma sampler | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -31,7 +31,7 @@ import numpy as onp\nfrom . import lax\nfrom . import numpy as np\nfrom . import tree_util\n-from .api import jit\n+from .api import jit, vmap\nfrom .numpy.lax_numpy import _constant_like\nfrom jax.lib import xla_bridge\nfrom jax import core\n@@ -420,6 +420,68 @@ def exponential(key, shape=(), dtype=onp.float32):\nreturn lax.neg(lax.log(lax.sub(_constant_like(u, 1), u)))\n+def _gamma_one(key, alpha):\n+ # Ref: A simple method for generating gamma variables, George Marsaglia and Wai Wan Tsang\n+ key, subkey = split(key)\n+ boost = np.where(alpha >= 1.0, 1.0, uniform(subkey, ()) ** (1.0 / alpha))\n+ alpha = np.where(alpha >= 1.0, alpha, alpha + 1.0)\n+\n+ d = alpha - 1.0 / 3.0\n+ c = 1.0 / np.sqrt(9.0 * d)\n+\n+ def _cond_fn(kXVU):\n+ _, X, V, U = kXVU\n+ # FIXME: find a way to avoid evaluating second condition which involves log+log\n+ # if the first condition is satisfied\n+ # note: lax.cond does not support batching rule yet\n+ return (U >= 1.0 - 0.0331 * X * X) & (np.log(U) >= 0.5 * X + d * (1.0 - V + np.log(V)))\n+\n+ def _body_fn(kXVU):\n+ def _next_kxv(kxv):\n+ key = kxv[0]\n+ key, subkey = split(key)\n+ x = normal(subkey, ())\n+ v = 1.0 + c * x\n+ return key, x, v\n+\n+ key = kXVU[0]\n+ key, x, v = lax.while_loop(lambda kxv: kxv[2] <= 0.0, _next_kxv, (key, 0.0, -1.0))\n+ key, subkey = split(key)\n+ X = x * x\n+ V = v * v * v\n+ U = uniform(subkey, ())\n+ return key, X, V, U\n+\n+ _, _, V, _ = lax.while_loop(_cond_fn, _body_fn, (key, 1.0, 1.0, 2.0))\n+ z = d * V * boost\n+ return np.where(z == 0, np.finfo(z.dtype).tiny, z)\n+\n+\n+@partial(jit, static_argnums=(2, 3))\n+def gamma(key, a, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Gamma random values with given shape and float dtype.\n+\n+ Args:\n+ key: a PRNGKey used as the random key.\n+ a: an array-like broadcastable to `shape` and used as the shape parameter\n+ of the random variables.\n+ shape: optional, a tuple of nonnegative integers representing the shape\n+ (default scalar).\n+ dtype: optional, a float dtype for the returned values (default float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ a = lax.convert_element_type(a, dtype)\n+ shape = shape or onp.shape(a)\n+ if onp.shape(a) != shape:\n+ a = np.broadcast_to(a, shape)\n+ alphas = np.reshape(a, -1)\n+ keys = split(key, onp.size(alphas))\n+ samples = vmap(_gamma_one)(keys, alphas)\n+ return np.reshape(samples, shape)\n+\n+\n@partial(jit, static_argnums=(1, 2))\ndef laplace(key, shape=(), dtype=onp.float32):\n\"\"\"Sample Laplace 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": "@@ -184,6 +184,27 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor samples in [uncompiled_samples, compiled_samples]:\nself._CheckKolmogorovSmirnovCDF(samples, scipy.stats.expon().cdf)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_a={}_{}\".format(a, dtype),\n+ \"a\": a, \"dtype\": onp.dtype(dtype).name}\n+ for a in [0.1, 1., 10.]\n+ for dtype in [onp.float32, onp.float64]))\n+ def testGamma(self, a, dtype):\n+ key = random.PRNGKey(0)\n+ rand = lambda key, a: random.gamma(key, a, (10000,), dtype)\n+ crand = api.jit(rand)\n+\n+ uncompiled_samples = rand(key, a)\n+ compiled_samples = crand(key, a)\n+\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ self._CheckKolmogorovSmirnovCDF(samples, scipy.stats.gamma(a).cdf)\n+\n+ def testGammaShape(self):\n+ key = random.PRNGKey(0)\n+ x = random.gamma(key, onp.array([0.2, 0.3]), shape=(3, 2))\n+ assert x.shape == (3, 2)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}\".format(dtype), \"dtype\": onp.dtype(dtype).name}\nfor dtype in [onp.float32, onp.float64]))\n"
}
] | Python | Apache License 2.0 | google/jax | add Gamma sampler |
260,335 | 31.03.2019 13:26:10 | 25,200 | f7a696f55cbefee15adfef3f968cb41cbc3f8707 | add forward-over-reverse hvp, timings from | [
{
"change_type": "MODIFY",
"old_path": "notebooks/autodiff_cookbook.ipynb",
"new_path": "notebooks/autodiff_cookbook.ipynb",
"diff": "\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"JTYyZkSO6vuy\",\n- \"outputId\": \"7e9004a9-135a-4376-dfc7-585c60d02508\",\n+ \"outputId\": \"a447ccef-4d24-47e9-e74e-2ee4d3686a03\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 51\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"0NLO4Wfknzmk\",\n- \"outputId\": \"a27c9855-20c1-4016-a481-1f54d9d0b934\",\n+ \"outputId\": \"bd52f84f-3d72-4881-9163-15654418c498\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 34\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"RDGk1GDsoawu\",\n- \"outputId\": \"2798d061-fe0c-4f0f-d58b-0cd40a809599\",\n+ \"outputId\": \"5386f672-16ed-4c49-fe72-0099d855523b\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 51\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"bpmd8W8-6vu6\",\n- \"outputId\": \"cdeede13-f09c-4d5f-d1d0-9c4e0d4f57cf\",\n+ \"outputId\": \"b009556f-e65c-430a-c967-2522033edd4d\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 102\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"IY82kdAe6vu_\",\n- \"outputId\": \"347768d1-0f4f-4828-9a1d-68ea225f65e6\",\n+ \"outputId\": \"f7d9c99f-bb79-4c50-e106-ccb67180cba8\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 34\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"RsQSyT5p7OJW\",\n- \"outputId\": \"5b2ede32-a599-42a1-a54e-144fe94e990e\",\n+ \"outputId\": \"6a567de9-fa4e-4c54-8dc6-0a6d868693d2\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 51\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"R8q5RiY3l7Fw\",\n- \"outputId\": \"ac91aeed-3051-4f46-d915-eed4e0286a06\",\n+ \"outputId\": \"d87a3b94-8fa7-453d-e1ed-dce15983521f\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 85\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"cbETzAvKvf5I\",\n- \"outputId\": \"51dc2541-36c7-4d04-a7b2-fc6babfd1e03\",\n+ \"outputId\": \"f88e5207-bff4-4d87-8536-2dfe5838c543\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 187\n\"metadata\": {\n\"id\": \"eH46Xnm88bfm\",\n\"colab_type\": \"code\",\n- \"outputId\": \"e63556ae-9929-4e99-f9c1-e2224cf5e864\",\n+ \"outputId\": \"e5b18818-5796-497a-9c30-7cbe6d91e134\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 136\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"n155ypD9rfIZ\",\n- \"outputId\": \"f32a7914-b4e3-41a9-b6f1-3818c37457ee\",\n+ \"outputId\": \"dd6db0a6-af8a-49b3-9599-b9a7c44fc67f\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 289\n\"\\n\",\n\"$(x, v) \\\\mapsto \\\\partial^2 f(x) v$\\n\",\n\"\\n\",\n- \"Just like before, to implement that we can first define the helper function $g : \\\\mathbb{R}^n \\\\to \\\\mathbb{R}$ as\\n\",\n+ \"Consider the helper function $g : \\\\mathbb{R}^n \\\\to \\\\mathbb{R}^n$ defined to be the derivative (or gradient) of $f$, namely $g(x) = \\\\partial f(x)$. All we need is its JVP, since that will give us\\n\",\n\"\\n\",\n- \"$g(x) = \\\\partial f(x) v$\\n\",\n+ \"$(x, v) \\\\mapsto \\\\partial g(x) v = \\\\partial^2 f(x) v$.\\n\",\n\"\\n\",\n- \"Now that should look familiar: it's just a Jacobian-vector product of $f$, which is exactly what forward-mode computes for us. And given its signature $g : \\\\mathbb{R}^n \\\\to \\\\mathbb{R}$, we know we can use reverse-mode to differentiate it efficiently, giving us what we wanted:\\n\",\n- \"\\n\",\n- \"$\\\\partial g(x) = \\\\partial^2 f(x) v$.\\n\",\n- \"\\n\",\n- \"Putting that together in code, we have\"\n+ \"We can translate that almost directly into code:\"\n]\n},\n{\n\"source\": [\n\"from jax import jvp, grad\\n\",\n\"\\n\",\n+ \"# forward-over-reverse\\n\",\n\"def hvp(f, primals, tangents):\\n\",\n- \" g = lambda primals: jvp(f, primals, tangents)[1]\\n\",\n- \" return grad(g)(primals)\"\n+ \" return jvp(grad(f), primals, tangents)[1]\"\n],\n\"execution_count\": 0,\n\"outputs\": []\n\"colab_type\": \"code\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n- \"height\": 85\n+ \"height\": 34\n},\n- \"outputId\": \"541057e0-0bb0-45f5-df1a-a103eeb42284\"\n+ \"outputId\": \"e46e2ac2-5b31-4c0c-dafb-1459bffbe7e7\"\n},\n\"cell_type\": \"code\",\n\"source\": [\n\" return np.sum(np.tanh(X)**2)\\n\",\n\"\\n\",\n\"key, subkey1, subkey2 = random.split(key, 3)\\n\",\n- \"X = random.normal(subkey1, (2, 3))\\n\",\n- \"V = random.normal(subkey2, (2, 3))\\n\",\n+ \"X = random.normal(subkey1, (30, 40))\\n\",\n+ \"V = random.normal(subkey2, (30, 40))\\n\",\n\"\\n\",\n- \"ans1, = hvp(f, (X,), (V,))\\n\",\n+ \"ans1 = hvp(f, (X,), (V,))\\n\",\n\"ans2 = np.tensordot(hessian(f)(X), V, 2)\\n\",\n\"\\n\",\n- \"print(ans1)\\n\",\n- \"print(ans2)\"\n+ \"print(np.allclose(ans1, ans2, 1e-4, 1e-4))\"\n],\n\"execution_count\": 19,\n\"outputs\": [\n{\n\"output_type\": \"stream\",\n\"text\": [\n- \"[[-0.26937994 -0.10539325 -0.00273675]\\n\",\n- \" [-0.29016215 0.2623394 -1.4582032 ]]\\n\",\n- \"[[-0.26937994 -0.10539327 -0.00273675]\\n\",\n- \" [-0.29016218 0.26233944 -1.4582031 ]]\\n\"\n+ \"True\\n\"\n+ ],\n+ \"name\": \"stdout\"\n+ }\n+ ]\n+ },\n+ {\n+ \"metadata\": {\n+ \"id\": \"aWTii5TyXL5C\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"cell_type\": \"markdown\",\n+ \"source\": [\n+ \"Another way you might consider writing this is using reverse-over-forward:\"\n+ ]\n+ },\n+ {\n+ \"metadata\": {\n+ \"id\": \"YxwmXZH2XQrw\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {}\n+ },\n+ \"cell_type\": \"code\",\n+ \"source\": [\n+ \"# reverse-over-forward\\n\",\n+ \"def hvp_revfwd(f, primals, tangents):\\n\",\n+ \" g = lambda primals: jvp(f, primals, tangents)[1]\\n\",\n+ \" return grad(g)(primals)\"\n+ ],\n+ \"execution_count\": 0,\n+ \"outputs\": []\n+ },\n+ {\n+ \"metadata\": {\n+ \"id\": \"8z-QG_xTXR4I\",\n+ \"colab_type\": \"text\"\n+ },\n+ \"cell_type\": \"markdown\",\n+ \"source\": [\n+ \"That's not quite as good, though, because forward-mode has less overhead than reverse-mode, and since the outer differentiation operator here has to differentiate a larger computation than the inner one, keeping forward-mode on the outside works best:\"\n+ ]\n+ },\n+ {\n+ \"metadata\": {\n+ \"id\": \"lxfv25qTX5gZ\",\n+ \"colab_type\": \"code\",\n+ \"colab\": {\n+ \"base_uri\": \"https://localhost:8080/\",\n+ \"height\": 153\n+ },\n+ \"outputId\": \"7ef0894e-99d4-4765-fe5c-b5fcfe6918c5\"\n+ },\n+ \"cell_type\": \"code\",\n+ \"source\": [\n+ \"# reverse-over-reverse, only works for single arguments\\n\",\n+ \"def hvp_revrev(f, primals, tangents):\\n\",\n+ \" x, = primals\\n\",\n+ \" v, = tangents\\n\",\n+ \" return grad(lambda x: np.vdot(grad(f)(x), v))(x)\\n\",\n+ \"\\n\",\n+ \"\\n\",\n+ \"print(\\\"Forward over reverse\\\")\\n\",\n+ \"%timeit -n10 -r3 hvp(f, (X,), (V,))\\n\",\n+ \"print(\\\"Reverse over forward\\\")\\n\",\n+ \"%timeit -n10 -r3 hvp_revfwd(f, (X,), (V,))\\n\",\n+ \"print(\\\"Reverse over reverse\\\")\\n\",\n+ \"%timeit -n10 -r3 hvp_revrev(f, (X,), (V,))\\n\",\n+ \"\\n\",\n+ \"print(\\\"Naive full Hessian materialization\\\")\\n\",\n+ \"%timeit -n10 -r3 np.tensordot(hessian(f)(X), V, 2)\"\n+ ],\n+ \"execution_count\": 21,\n+ \"outputs\": [\n+ {\n+ \"output_type\": \"stream\",\n+ \"text\": [\n+ \"Forward over reverse\\n\",\n+ \"10 loops, best of 3: 14.3 ms per loop\\n\",\n+ \"Reverse over forward\\n\",\n+ \"10 loops, best of 3: 17.1 ms per loop\\n\",\n+ \"Reverse over reverse\\n\",\n+ \"10 loops, best of 3: 19.6 ms per loop\\n\",\n+ \"Naive full Hessian materialization\\n\",\n+ \"10 loops, best of 3: 99.2 ms per loop\\n\"\n],\n\"name\": \"stdout\"\n}\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"asAWvxVaCmsx\",\n- \"outputId\": \"e89db180-9f58-4f75-c14f-ac17498fa470\",\n+ \"outputId\": \"cf23fb5d-49da-4392-ba49-05a847577a7c\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 102\n\"\\n\",\n\"assert np.allclose(loop_vs, vmap_vs), 'Vmap and non-vmapped Matrix-Jacobian Products should be identical'\"\n],\n- \"execution_count\": 20,\n+ \"execution_count\": 22,\n\"outputs\": [\n{\n\"output_type\": \"stream\",\n\"text\": [\n\"Non-vmapped Matrix-Jacobian product\\n\",\n- \"10 loops, best of 3: 149 ms per loop\\n\",\n+ \"10 loops, best of 3: 156 ms per loop\\n\",\n\"\\n\",\n\"Vmapped Matrix-Jacobian product\\n\",\n- \"10 loops, best of 3: 6.56 ms per loop\\n\"\n+ \"10 loops, best of 3: 6.7 ms per loop\\n\"\n],\n\"name\": \"stdout\"\n}\n\"metadata\": {\n\"colab_type\": \"code\",\n\"id\": \"TDaxsJrlDraK\",\n- \"outputId\": \"6c319204-3d8b-4113-cb31-ce694dcfb4bd\",\n+ \"outputId\": \"88973626-83ff-4293-c47b-070872e76760\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 102\n\"\\n\",\n\"assert np.allclose(loop_vs, vmap_vs), 'Vmap and non-vmapped Jacobian-Matrix products should be identical'\"\n],\n- \"execution_count\": 21,\n+ \"execution_count\": 23,\n\"outputs\": [\n{\n\"output_type\": \"stream\",\n\"text\": [\n\"Non-vmapped Jacobian-Matrix product\\n\",\n- \"10 loops, best of 3: 511 ms per loop\\n\",\n+ \"10 loops, best of 3: 529 ms per loop\\n\",\n\"\\n\",\n\"Vmapped Jacobian-Matrix product\\n\",\n- \"10 loops, best of 3: 5.4 ms per loop\\n\"\n+ \"10 loops, best of 3: 5.74 ms per loop\\n\"\n],\n\"name\": \"stdout\"\n}\n\"metadata\": {\n\"id\": \"_5jDflC08bgB\",\n\"colab_type\": \"code\",\n- \"outputId\": \"b9d88994-7545-4681-8221-93ab2653a12d\",\n+ \"outputId\": \"483e7276-b6e7-4b09-9476-30fe997fc0d2\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 34\n\"y, f_vjp = vjp(f, 4.)\\n\",\n\"print(jit(f_vjp)(1.))\"\n],\n- \"execution_count\": 24,\n+ \"execution_count\": 26,\n\"outputs\": [\n{\n\"output_type\": \"stream\",\n\"metadata\": {\n\"id\": \"WrDHHfKI8bgM\",\n\"colab_type\": \"code\",\n- \"outputId\": \"66d7a055-3c72-4751-b168-6428c68cd097\",\n+ \"outputId\": \"fbc24428-2df8-4d5f-eff1-7a291af56e05\",\n\"colab\": {\n\"base_uri\": \"https://localhost:8080/\",\n\"height\": 173\n\"\\n\",\n\"grad(f)(A)\"\n],\n- \"execution_count\": 27,\n+ \"execution_count\": 29,\n\"outputs\": [\n{\n\"output_type\": \"stream\",\n\"metadata\": {\n\"tags\": []\n},\n- \"execution_count\": 27\n+ \"execution_count\": 29\n}\n]\n},\n"
}
] | Python | Apache License 2.0 | google/jax | add forward-over-reverse hvp, timings from @alexbw |
260,314 | 31.03.2019 23:54:31 | 14,400 | cbf45282ee16f910c48b63ad027848787b174abf | convert gamma_one to lax api and move the inner while_loop to the outside | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -422,39 +422,52 @@ def exponential(key, shape=(), dtype=onp.float32):\ndef _gamma_one(key, alpha):\n# Ref: A simple method for generating gamma variables, George Marsaglia and Wai Wan Tsang\n+ # The algorithm can also be founded in:\n+ # https://en.wikipedia.org/wiki/Gamma_distribution#Generating_gamma-distributed_random_variables\n+ zero = _constant_like(alpha, 0)\n+ one = _constant_like(alpha, 1)\n+ one_over_two = _constant_like(alpha, 0.5)\n+ one_over_three = _constant_like(alpha, 1. / 3.)\n+ squeeze_const = _constant_like(alpha, 0.0331)\n+\nkey, subkey = split(key)\n- boost = np.where(alpha >= 1.0, 1.0, uniform(subkey, ()) ** (1.0 / alpha))\n- alpha = np.where(alpha >= 1.0, alpha, alpha + 1.0)\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)\n+ boost = lax.select(lax.ge(alpha, one),\n+ one,\n+ lax.pow(uniform(subkey, ()), lax.div(one, alpha)))\n+ alpha = lax.select(lax.ge(alpha, one), alpha, lax.add(alpha, one))\n- d = alpha - 1.0 / 3.0\n- c = 1.0 / np.sqrt(9.0 * d)\n+ d = lax.sub(alpha, one_over_three)\n+ c = lax.div(one_over_three, lax.pow(d, one_over_two))\ndef _cond_fn(kXVU):\n_, X, V, U = kXVU\n- # FIXME: find a way to avoid evaluating second condition which involves log+log\n+ # TODO: use lax.cond when its batching rule is supported\n+ # The reason is to avoid evaluating second condition which involves log+log\n# if the first condition is satisfied\n- # note: lax.cond does not support batching rule yet\n- return (U >= 1.0 - 0.0331 * X * X) & (np.log(U) >= 0.5 * X + d * (1.0 - V + np.log(V)))\n+ cond = lax.bitwise_and(lax.ge(U, lax.sub(one, lax.mul(squeeze_const, lax.mul(X, X)))),\n+ lax.ge(lax.log(U), lax.add(lax.mul(X, one_over_two),\n+ lax.mul(d, lax.add(lax.sub(one, V),\n+ lax.log(V))))))\n+ return lax.bitwise_or(lax.le(V, zero), cond)\ndef _body_fn(kXVU):\n- def _next_kxv(kxv):\n- key = kxv[0]\n- key, subkey = split(key)\n- x = normal(subkey, ())\n- v = 1.0 + c * x\n- return key, x, v\n-\nkey = kXVU[0]\n- key, x, v = lax.while_loop(lambda kxv: kxv[2] <= 0.0, _next_kxv, (key, 0.0, -1.0))\n- key, subkey = split(key)\n- X = x * x\n- V = v * v * v\n- U = uniform(subkey, ())\n+ key, x_key, U_key = split(key, 3)\n+ x = normal(x_key, ())\n+ v = lax.add(one, lax.mul(x, c))\n+ X = lax.mul(x, x)\n+ V = lax.mul(lax.mul(v, v), v)\n+ U = uniform(U_key, ())\nreturn key, X, V, U\n- _, _, V, _ = lax.while_loop(_cond_fn, _body_fn, (key, 1.0, 1.0, 2.0))\n- z = d * V * boost\n- return np.where(z == 0, np.finfo(z.dtype).tiny, z)\n+ # initial state is chosen such that _cond_fn will return True\n+ _, _, V, _ = lax.while_loop(_cond_fn,\n+ _body_fn,\n+ (key, zero, _constant_like(alpha, -1), zero))\n+ z = lax.mul(lax.mul(d, V), boost)\n+ return lax.select(lax.eq(z, zero), onp.finfo(z.dtype).tiny, z)\n@partial(jit, static_argnums=(2, 3))\n"
}
] | Python | Apache License 2.0 | google/jax | convert gamma_one to lax api and move the inner while_loop to the outside |
260,314 | 01.04.2019 00:32:42 | 14,400 | 69c4e225241578b4b5ed25c64a39e4d4951bd503 | add dtype for samplers in gamma_one | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -429,13 +429,14 @@ def _gamma_one(key, alpha):\none_over_two = _constant_like(alpha, 0.5)\none_over_three = _constant_like(alpha, 1. / 3.)\nsqueeze_const = _constant_like(alpha, 0.0331)\n+ dtype = lax._dtype(alpha)\nkey, 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(subkey, ()), lax.div(one, alpha)))\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@@ -455,11 +456,11 @@ def _gamma_one(key, alpha):\ndef _body_fn(kXVU):\nkey = kXVU[0]\nkey, x_key, U_key = split(key, 3)\n- x = normal(x_key, ())\n+ x = normal(x_key, (), dtype=dtype)\nv = lax.add(one, lax.mul(x, c))\nX = lax.mul(x, x)\nV = lax.mul(lax.mul(v, v), v)\n- U = uniform(U_key, ())\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"
}
] | Python | Apache License 2.0 | google/jax | add dtype for samplers in gamma_one |
260,335 | 01.04.2019 17:21:50 | 25,200 | f17d31fdf21248eafb4f6cd0c197ec1af9c694b8 | rename xla_pcall -> xla_pmap | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -440,7 +440,7 @@ def pmap(fun, axis_name=None):\n_check_args(jaxtupletree_args)\nf = lu.wrap_init(fun, kwargs)\nf, out_tree = pytree_fun_to_jaxtupletree_fun(f, in_trees)\n- jaxtupletree_out = pxla.xla_pcall(f, *jaxtupletree_args,\n+ jaxtupletree_out = pxla.xla_pmap(f, *jaxtupletree_args,\naxis_name=axis_name, axis_size=axis_size)\nreturn build_tree(out_tree(), jaxtupletree_out)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -114,8 +114,8 @@ def replica_groups(nrep, mesh_spec, mesh_axis):\nArgs:\nnrep: int, number of replicas (a computation-dependent value).\nmesh_spec: tuple of integers, a specification of the logical device mesh,\n- which depends on the lexical context of nested xla_pcalls. In particular,\n- each xla_pcall effectively appends its mapped axis size to this tuple.\n+ which depends on the lexical context of nested xla_pmaps. In particular,\n+ each xla_pmap effectively appends its mapped axis size to this tuple.\nmesh_axis: int, logical device mesh axis index indicating the axis along\nwhich collective operations are to be executed.\n@@ -173,7 +173,7 @@ def xla_unshard(c, device_groups, x):\nreturn _xla_unshard(c.GetShape(x), x)\n-### xla_pcall\n+### xla_pmap\nAxisEnv = namedtuple(\"AxisEnv\", [\"nreps\", \"names\", \"sizes\"])\n@@ -197,7 +197,7 @@ def compile_replicated(jaxpr, axis_name, axis_size, consts, *abstract_args):\ndef jaxpr_replicas(jaxpr):\nreturn _max(eqn.params['axis_size'] * jaxpr_replicas(eqn.bound_subjaxprs[0][0])\n- for eqn in jaxpr.eqns if eqn.primitive is xla_pcall_p)\n+ for eqn in jaxpr.eqns if eqn.primitive is xla_pmap_p)\ndef _max(itr): return max(list(itr) or [1])\ndef replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\n@@ -230,7 +230,7 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nrule = parallel_translation_rules[eqn.primitive]\nans = rule(c, *in_nodes, device_groups=axis_groups(ax_env, name), **params)\nelif eqn.bound_subjaxprs:\n- if eqn.primitive is xla_pcall_p:\n+ if eqn.primitive is xla_pmap_p:\nname, size = eqn.params['axis_name'], eqn.params['axis_size']\nnew_env = axis_env_extend(name, size)\nin_shards = map(partial(xla_shard, c, new_env.sizes), in_nodes)\n@@ -292,7 +292,7 @@ xb.register_constant_handler(ShardedDeviceArray,\nxla._device_array_constant_handler)\n-def xla_pcall_impl(fun, *args, **params):\n+def xla_pmap_impl(fun, *args, **params):\naxis_name = params.pop('axis_name')\naxis_size = params.pop('axis_size')\nassert not params\n@@ -347,14 +347,14 @@ def execute_replicated(compiled, pval, axis_size, nrep, handle_in, handle_out,\nreturn map(partial(unshard_output, axis_size), zip(*replica_results))\n-xla_pcall_p = core.Primitive('xla_pcall')\n-xla_pcall = partial(core.call_bind, xla_pcall_p)\n-xla_pcall_p.def_custom_bind(xla_pcall)\n-xla_pcall_p.def_impl(xla_pcall_impl)\n-ad.primitive_transposes[xla_pcall_p] = partial(ad.map_transpose, xla_pcall_p)\n-pe.map_primitives.add(xla_pcall_p)\n-# TODO(mattjj): enable pjit inside jit, maybe by merging xla_pcall and xla_call\n-# xla.translations[xla_pcall_p] = xla.xla_call_translation_rule\n+xla_pmap_p = core.Primitive('xla_pmap')\n+xla_pmap = partial(core.call_bind, xla_pmap_p)\n+xla_pmap_p.def_custom_bind(xla_pmap)\n+xla_pmap_p.def_impl(xla_pmap_impl)\n+ad.primitive_transposes[xla_pmap_p] = partial(ad.map_transpose, xla_pmap_p)\n+pe.map_primitives.add(xla_pmap_p)\n+# TODO(mattjj): enable pjit inside jit, maybe by merging xla_pmap and xla_call\n+# xla.translations[xla_pmap_p] = xla.xla_call_translation_rule\nparallel_translation_rules = {}\n"
}
] | Python | Apache License 2.0 | google/jax | rename xla_pcall -> xla_pmap |
260,335 | 01.04.2019 17:56:23 | 25,200 | 8ace5191b666cc7a497551c085e817a4afa4b25d | enable spmd collectives over multiple axes at once
e.g. lax.psum(x, (i, j)) | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -108,7 +108,7 @@ def assign_shards_to_replicas(nrep, size):\nindices = onp.tile(onp.arange(size)[:, None], (1, groupsize))\nreturn tuple(indices.ravel())\n-def replica_groups(nrep, mesh_spec, mesh_axis):\n+def replica_groups(nrep, mesh_spec, mesh_axes):\n\"\"\"Compute XLA replica groups from a replica count and device mesh data.\nArgs:\n@@ -116,8 +116,8 @@ def replica_groups(nrep, mesh_spec, mesh_axis):\nmesh_spec: tuple of integers, a specification of the logical device mesh,\nwhich depends on the lexical context of nested xla_pcalls. In particular,\neach xla_pcall effectively appends its mapped axis size to this tuple.\n- mesh_axis: int, logical device mesh axis index indicating the axis along\n- which collective operations are to be executed.\n+ mesh_axes: tuple of ints, logical device mesh axis indices indicating the\n+ axes along which collective operations are to be executed.\nReturns:\nreplica_groups, a list of lists of ints encoding a partition of the set\n@@ -127,10 +127,11 @@ def replica_groups(nrep, mesh_spec, mesh_axis):\ntrailing_size, ragged = divmod(nrep, prod(mesh_spec))\nassert not ragged\nfull_spec = mesh_spec + [trailing_size]\n- groups = onp.split(onp.arange(prod(full_spec)).reshape(full_spec),\n- full_spec[mesh_axis], axis=mesh_axis)\n- groups = map(onp.ravel, groups)\n- return tuple(tuple(group) for group in zip(*groups))\n+ iota = onp.arange(prod(full_spec)).reshape(full_spec)\n+ groups = onp.reshape(\n+ onp.moveaxis(iota, mesh_axes, onp.arange(len(mesh_axes))),\n+ (prod(onp.take(full_spec, mesh_axes)), -1))\n+ return tuple(map(tuple, groups.T))\ndef xla_shard(c, sizes, x):\n\"\"\"Analog of shard_arg that performs sharding within an XLA computation.\"\"\"\n@@ -182,8 +183,11 @@ def axis_read(axis_env, axis_name):\nreturn max(i for i, name in enumerate(axis_env.names) if name == axis_name)\ndef axis_groups(axis_env, name):\n- mesh_axis = axis_read(axis_env, name)\n- return replica_groups(axis_env.nreps, axis_env.sizes, mesh_axis)\n+ if isinstance(name, (list, tuple)):\n+ mesh_axes = tuple(map(partial(axis_read, axis_env), name))\n+ else:\n+ mesh_axes = (axis_read(axis_env, name),)\n+ return replica_groups(axis_env.nreps, axis_env.sizes, mesh_axes)\ndef compile_replicated(jaxpr, axis_name, axis_size, consts, *abstract_args):\nnum_replicas = axis_size * jaxpr_replicas(jaxpr)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -222,6 +222,40 @@ class PmapTest(jtu.JaxTestCase):\nz = f(y)\nself.assertAllClose(z, 2 * 2 * x[::-1], check_dtypes=False)\n+ def testPsumMultiple(self):\n+ f = lambda x: lax.psum(x, ('i', 'j'))\n+ f = pmap(pmap(f, 'i'), 'j')\n+\n+ def sum_and_broadcast(x, axis):\n+ return onp.repeat(onp.sum(x, axis, keepdims=True), x.shape[axis], axis)\n+\n+ device_count = xla_bridge.device_count()\n+ num_pairs, ragged = divmod(device_count, 2)\n+ if num_pairs > 1 and not ragged:\n+ shape = (num_pairs, 2, 4)\n+ else:\n+ shape = (device_count, 1, 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+\n+ ans = f(x)\n+ expected = sum_and_broadcast(sum_and_broadcast(x, 0), 1)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def testReplicaGroups(self):\n+ groups = pxla.replica_groups(8, [4, 2], (0,))\n+ self.assertEqual(groups, ((0, 2, 4, 6), (1, 3, 5, 7)))\n+\n+ groups = pxla.replica_groups(8, [4, 2], (1,))\n+ self.assertEqual(groups, ((0, 1), (2, 3), (4, 5), (6, 7)))\n+\n+ groups = pxla.replica_groups(8, [4, 2], (0, 1))\n+ self.assertEqual(groups, ((0, 1, 2, 3, 4, 5, 6, 7,),))\n+\n+ groups = pxla.replica_groups(8, [4, 2], (1, 0))\n+ self.assertEqual(len(groups), 1)\n+ self.assertEqual((tuple(sorted(groups[0])),),\n+ ((0, 1, 2, 3, 4, 5, 6, 7,),)) # order doesn't matter\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | enable spmd collectives over multiple axes at once
e.g. lax.psum(x, (i, j)) |
260,335 | 01.04.2019 21:19:55 | 25,200 | dfdfac55c0d8082cd6168e27ed452c84bb6ec632 | update tensorflow version for new xla | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -17,10 +17,10 @@ http_archive(\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"1db7390bd4c51be7526dc22d665b451109cdce56eb101f9e70996ed91dbdf746\",\n- strip_prefix = \"tensorflow-5e8df789cc30098d791475c14a623ec68b50b4ed\",\n+ sha256 = \"8d3c20b3c0b447d45668ead18077b96aedddd42308d3e73f245e2830f371a739\",\n+ strip_prefix = \"tensorflow-27ec48b174597b8d430edaa8164a60048f254dcf\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/5e8df789cc30098d791475c14a623ec68b50b4ed.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/27ec48b174597b8d430edaa8164a60048f254dcf.tar.gz\",\n],\n)\n"
}
] | Python | Apache License 2.0 | google/jax | update tensorflow version for new xla |
260,299 | 02.04.2019 10:55:03 | -3,600 | 7b13ae4b41f616abe2328c11999ca837d002efce | Add Gumbel to jax.random, and test | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -458,3 +458,19 @@ def pareto(key, b, shape=(), dtype=onp.float32):\nb = np.broadcast_to(b, shape)\ne = exponential(key, shape, dtype)\nreturn lax.exp(lax.div(e, b))\n+\n+\n+@partial(jit, static_argnums=(1, 2))\n+def gumbel(key, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Gumbel 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 float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ return -np.log(-np.log(uniform(key, shape, dtype=dtype)))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -229,6 +229,20 @@ class LaxRandomTest(jtu.JaxTestCase):\nkeys = [random.fold_in(key, i) for i in range(10)]\nassert onp.unique(onp.ravel(keys)).shape == (20,)\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 testGumbel(self, dtype):\n+ key = random.PRNGKey(0)\n+ rand = lambda key: random.gumbel(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.gumbel_r().cdf)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | Add Gumbel to jax.random, and test |
260,299 | 02.04.2019 10:56:44 | -3,600 | 996c62337c23f16ccb3d8c46b4d1eae0bde851eb | Rm unnecessary dtype arg name | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -473,4 +473,4 @@ def gumbel(key, shape=(), dtype=onp.float32):\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n- return -np.log(-np.log(uniform(key, shape, dtype=dtype)))\n+ return -np.log(-np.log(uniform(key, shape, dtype)))\n"
}
] | Python | Apache License 2.0 | google/jax | Rm unnecessary dtype arg name |
260,335 | 02.04.2019 11:22:19 | 25,200 | 51d2722185edc3559a1732bcce7f086e714bcbc6 | add graphviz-dumping function | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -712,10 +712,9 @@ def make_jaxpr(fun):\naval = xla.abstractify(x)\nreturn pe.PartialVal((aval, core.unit))\n- wrapped = lu.wrap_init(fun)\n-\n@wraps(fun)\ndef jaxpr_maker(*args, **kwargs):\n+ wrapped = lu.wrap_init(fun)\njax_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\njaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(wrapped, in_trees)\npvals = map(pv_like, jax_args)\n@@ -811,3 +810,63 @@ def jarrett(fun):\nad.primitive_jvps[new_fun.primitive] = elementwise_jvp\nreturn new_fun\n+\n+\n+def make_graphviz(fun):\n+ \"\"\"Adapts `fun` to return a graphviz dot string of its program representation.\n+\n+ Args:\n+ fun: The function whose `jaxpr` is to be rendered into graphviz dot. Its\n+ positional arguments and return value should be arrays, scalars, or\n+ standard Python containers (tuple/list/dict) thereof.\n+\n+ Returns:\n+ A wrapped version of `fun`, set up to return a graphviz dot string.\n+\n+ See make_jaxpr for a related function.\n+ \"\"\"\n+\n+ def pv_like(x):\n+ aval = xla.abstractify(x)\n+ return pe.PartialVal((aval, core.unit))\n+\n+ id_names = (\"id{}\".format(i) for i in itertools.count())\n+\n+ def jaxpr_to_graphviz(jaxpr, consts):\n+ fragment = ''\n+\n+ fragment += ''.join(map(invar_node, jaxpr.invars, jaxpr.invars))\n+ fragment += ''.join(map(freevar_node, jaxpr.freevars, jaxpr.freevars))\n+ fragment += ''.join(map(constant_node, jaxpr.constvars, consts))\n+\n+ for eqn in jaxpr.eqns:\n+ if eqn.destructure:\n+ id_name = next(id_names)\n+ fragment += function_node(id_name, eqn.primitive.name)\n+ fragment += ''.join(edge(invar, id_name) for invar in eqn.invars)\n+ fragment += ''.join(edge(id_name, outvar) for outvar in eqn.outvars)\n+ else:\n+ fragment += function_node(eqn.outvars[0], eqn.primitive.name)\n+ fragment += ''.join(edge(invar, eqn.outvars[0]) for invar in eqn.invars)\n+ fragment += outvar_node(jaxpr.outvar, \"out\")\n+ return graph(fragment)\n+\n+ edge = '{} -> {} [color=gray30];\\n'.format\n+ function_node = '{} [label=\"{}\", shape=box, color=lightskyblue, style=filled];\\n'.format\n+ invar_node = '{} [rank=2, label=\"{}\", color=mediumspringgreen, style=filled];\\n'.format\n+ outvar_node = '{} [label=\"{}\", fillcolor=indianred1, style=\"filled,dashed\", color=black];\\n'.format\n+ constant_node = '{} [rank=2, label=\"{}\", color=goldenrod1, style=filled];\\n'.format\n+ freevar_node = '{} [rank=2, label=\"{}\", color=palegreen, style=filled];\\n'.format\n+ graph = 'digraph G {{{}}}'.format\n+\n+ @wraps(fun)\n+ def graphviz_maker(*args, **kwargs):\n+ wrapped = lu.wrap_init(fun)\n+ jax_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\n+ jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(wrapped, in_trees)\n+ pvals = map(pv_like, jax_args)\n+ jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals, **kwargs)\n+ return jaxpr_to_graphviz(jaxpr, consts)\n+\n+ graphviz_maker.__name__ = \"make_graphviz({})\".format(graphviz_maker.__name__)\n+ return graphviz_maker\n"
}
] | Python | Apache License 2.0 | google/jax | add graphviz-dumping function |
260,335 | 02.04.2019 21:17:24 | 25,200 | 61ce283f3efc571b108e245a15afff92c6af0483 | graphviz: concat strings only at the end | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -833,23 +833,23 @@ def make_graphviz(fun):\nid_names = (\"id{}\".format(i) for i in itertools.count())\ndef jaxpr_to_graphviz(jaxpr, consts):\n- fragment = ''\n+ fragment = []\n- fragment += ''.join(map(invar_node, jaxpr.invars, jaxpr.invars))\n- fragment += ''.join(map(freevar_node, jaxpr.freevars, jaxpr.freevars))\n- fragment += ''.join(map(constant_node, jaxpr.constvars, consts))\n+ fragment.extend(map(invar_node, jaxpr.invars, jaxpr.invars))\n+ fragment.extend(map(freevar_node, jaxpr.freevars, jaxpr.freevars))\n+ fragment.extend(map(constant_node, jaxpr.constvars, consts))\nfor eqn in jaxpr.eqns:\nif eqn.destructure:\nid_name = next(id_names)\n- fragment += function_node(id_name, eqn.primitive.name)\n- fragment += ''.join(edge(invar, id_name) for invar in eqn.invars)\n- fragment += ''.join(edge(id_name, outvar) for outvar in eqn.outvars)\n+ fragment.append(function_node(id_name, eqn.primitive.name))\n+ fragment.extend(edge(invar, id_name) for invar in eqn.invars)\n+ fragment.extend(edge(id_name, outvar) for outvar in eqn.outvars)\nelse:\n- fragment += function_node(eqn.outvars[0], eqn.primitive.name)\n- fragment += ''.join(edge(invar, eqn.outvars[0]) for invar in eqn.invars)\n- fragment += outvar_node(jaxpr.outvar, \"out\")\n- return graph(fragment)\n+ fragment.append(function_node(eqn.outvars[0], eqn.primitive.name))\n+ fragment.extend(edge(invar, eqn.outvars[0]) for invar in eqn.invars)\n+ fragment.append(outvar_node(jaxpr.outvar, \"out\"))\n+ return graph(''.join(fragment))\nedge = '{} -> {} [color=gray30];\\n'.format\nfunction_node = '{} [label=\"{}\", shape=box, color=lightskyblue, style=filled];\\n'.format\n"
}
] | Python | Apache License 2.0 | google/jax | graphviz: concat strings only at the end |
260,299 | 03.04.2019 12:54:02 | -3,600 | 1c9b9a57fd971abd5791c82492a7a0ece581878e | Use jax.random for stax initialization | [
{
"change_type": "MODIFY",
"old_path": "examples/mnist_classifier.py",
"new_path": "examples/mnist_classifier.py",
"diff": "@@ -27,7 +27,7 @@ import numpy.random as npr\nimport jax.numpy as np\nfrom jax.config import config\n-from jax import jit, grad\n+from jax import jit, grad, random\nfrom jax.experimental import optimizers\nfrom jax.experimental import stax\nfrom jax.experimental.stax import Dense, Relu, LogSoftmax\n@@ -51,6 +51,8 @@ init_random_params, predict = stax.serial(\nDense(10), LogSoftmax)\nif __name__ == \"__main__\":\n+ rng = random.PRNGKey(0)\n+\nstep_size = 0.001\nnum_epochs = 10\nbatch_size = 128\n@@ -77,7 +79,7 @@ if __name__ == \"__main__\":\nparams = optimizers.get_params(opt_state)\nreturn opt_update(i, grad(loss)(params, batch), opt_state)\n- _, init_params = init_random_params((-1, 28 * 28))\n+ _, init_params = init_random_params(rng, (-1, 28 * 28))\nopt_state = opt_init(init_params)\nitercount = itertools.count()\n"
},
{
"change_type": "MODIFY",
"old_path": "examples/mnist_vae.py",
"new_path": "examples/mnist_vae.py",
"diff": "@@ -97,8 +97,9 @@ if __name__ == \"__main__\":\nnum_complete_batches, leftover = divmod(train_images.shape[0], batch_size)\nnum_batches = num_complete_batches + bool(leftover)\n- _, init_encoder_params = encoder_init((batch_size, 28 * 28))\n- _, init_decoder_params = decoder_init((batch_size, 10))\n+ enc_init_rng, dec_init_rng = random.split(random.PRNGKey(2))\n+ _, init_encoder_params = encoder_init(enc_init_rng, (batch_size, 28 * 28))\n+ _, init_decoder_params = decoder_init(dec_init_rng, (batch_size, 10))\ninit_params = init_encoder_params, init_decoder_params\nopt_init, opt_update = optimizers.momentum(step_size, mass=0.9)\n"
},
{
"change_type": "MODIFY",
"old_path": "examples/resnet50.py",
"new_path": "examples/resnet50.py",
"diff": "@@ -27,7 +27,7 @@ from six.moves import xrange\nimport jax.numpy as np\nfrom jax.config import config\n-from jax import jit, grad\n+from jax import jit, grad, random\nfrom jax.experimental import optimizers\nfrom jax.experimental import stax\nfrom jax.experimental.stax import (AvgPool, BatchNorm, Conv, Dense, FanInSum,\n@@ -87,6 +87,8 @@ def ResNet50(num_classes):\nif __name__ == \"__main__\":\n+ rng_key = random.PRNGKey(0)\n+\nbatch_size = 8\nnum_classes = 1001\ninput_shape = (224, 224, 3, batch_size)\n@@ -94,7 +96,7 @@ if __name__ == \"__main__\":\nnum_steps = 10\ninit_fun, predict_fun = ResNet50(num_classes)\n- _, init_params = init_fun(input_shape)\n+ _, init_params = init_fun(rng_key, input_shape)\ndef loss(params, batch):\ninputs, targets = batch\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -26,7 +26,6 @@ import itertools\nimport operator as op\nimport numpy as onp\n-import numpy.random as npr\nfrom six.moves import reduce\nfrom jax import lax\n@@ -59,37 +58,38 @@ def fastvar(x, axis, keepdims):\n# Initializers\n-def randn(stddev=1e-2, rng=npr):\n+def randn(stddev=1e-2):\n\"\"\"An initializer function for random normal coefficients.\"\"\"\n- def init(shape):\n- return rng.normal(size=shape, scale=stddev).astype('float32')\n+ def init(rng, shape):\n+ return stddev * random.normal(rng, shape)\nreturn init\n-def glorot(out_dim=0, in_dim=1, scale=onp.sqrt(2), rng=npr):\n+def glorot(out_dim=0, in_dim=1, scale=onp.sqrt(2)):\n\"\"\"An initializer function for random Glorot-scaled coefficients.\"\"\"\n- def init(shape):\n+ def init(rng, shape):\nfan_in, fan_out = shape[in_dim], shape[out_dim]\nsize = onp.prod(onp.delete(shape, [in_dim, out_dim]))\nstd = scale / np.sqrt((fan_in + fan_out) / 2. * size)\n- return rng.normal(size=shape, scale=std).astype('float32')\n+ return std * random.normal(rng, shape)\nreturn init\n-zeros = functools.partial(np.zeros, dtype='float32')\n-ones = functools.partial(np.ones, dtype='float32')\n+zeros = lambda rng, shape: np.zeros(shape, dtype='float32')\n+ones = lambda rng, shape: np.ones(shape, dtype='float32')\n# Layers\n# Each layer constructor function returns an (init_fun, apply_fun) pair, where\n-# init_fun: takes an input shape and returns an (output_shape, params) pair,\n+# init_fun: takes an rng key and an input shape and returns an\n+# (output_shape, params) pair,\n# apply_fun: takes params, inputs, and an rng key and applies the layer.\ndef Dense(out_dim, W_init=glorot(), b_init=randn()):\n\"\"\"Layer constructor function for a dense (fully-connected) layer.\"\"\"\n- def init_fun(input_shape):\n+ def init_fun(rng, input_shape):\noutput_shape = input_shape[:-1] + (out_dim,)\n- W, b = W_init((input_shape[-1], out_dim)), b_init((out_dim,))\n+ W, b = W_init(rng, (input_shape[-1], out_dim)), b_init(rng, (out_dim,))\nreturn output_shape, (W, b)\ndef apply_fun(params, inputs, **kwargs):\nW, b = params\n@@ -104,7 +104,7 @@ def GeneralConv(dimension_numbers, out_chan, filter_shape,\none = (1,) * len(filter_shape)\nstrides = strides or one\nW_init = W_init or glorot(rhs_spec.index('O'), rhs_spec.index('I'))\n- def init_fun(input_shape):\n+ def init_fun(rng, input_shape):\nfilter_shape_iter = iter(filter_shape)\nkernel_shape = [out_chan if c == 'O' else\ninput_shape[lhs_spec.index('C')] if c == 'I' else\n@@ -113,7 +113,7 @@ def GeneralConv(dimension_numbers, out_chan, filter_shape,\ninput_shape, kernel_shape, strides, padding, dimension_numbers)\nbias_shape = [out_chan if c == 'C' else 1 for c in out_spec]\nbias_shape = tuple(itertools.dropwhile(lambda x: x == 1, bias_shape))\n- W, b = W_init(kernel_shape), b_init(bias_shape)\n+ W, b = W_init(rng, kernel_shape), b_init(rng, bias_shape)\nreturn output_shape, (W, b)\ndef apply_fun(params, inputs, **kwargs):\nW, b = params\n@@ -126,12 +126,12 @@ Conv = functools.partial(GeneralConv, ('NHWC', 'HWIO', 'NHWC'))\ndef BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True,\nbeta_init=zeros, gamma_init=ones):\n\"\"\"Layer construction function for a batch normalization layer.\"\"\"\n- _beta_init = lambda shape: beta_init(shape) if center else ()\n- _gamma_init = lambda shape: gamma_init(shape) if scale else ()\n+ _beta_init = lambda rng, shape: beta_init(rng, shape) if center else ()\n+ _gamma_init = lambda rng, shape: gamma_init(rng, shape) if scale else ()\naxis = (axis,) if np.isscalar(axis) else axis\n- def init_fun(input_shape):\n+ def init_fun(rng, input_shape):\nshape = tuple(d for i, d in enumerate(input_shape) if i not in axis)\n- beta, gamma = _beta_init(shape), _gamma_init(shape)\n+ beta, gamma = _beta_init(rng, shape), _gamma_init(rng, shape)\nreturn input_shape, (beta, gamma)\ndef apply_fun(params, x, **kwargs):\nbeta, gamma = params\n@@ -150,7 +150,7 @@ def BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True,\ndef _elemwise_no_params(fun, **fun_kwargs):\n- init_fun = lambda input_shape: (input_shape, ())\n+ init_fun = lambda rng, input_shape: (input_shape, ())\napply_fun = lambda params, inputs, **kwargs: fun(inputs, **fun_kwargs)\nreturn init_fun, apply_fun\nTanh = _elemwise_no_params(np.tanh)\n@@ -168,7 +168,7 @@ def _pooling_layer(reducer, init_val, rescaler=None):\nrescale = rescaler(window_shape, strides, padding) if rescaler else None\ndims = (1,) + window_shape + (1,) # NHWC\nstrides = (1,) + strides + (1,)\n- def init_fun(input_shape):\n+ def init_fun(rng, input_shape):\nout_shape = lax.reduce_window_shape_tuple(input_shape, dims, strides, padding)\nreturn out_shape, ()\ndef apply_fun(params, inputs, **kwargs):\n@@ -191,7 +191,7 @@ AvgPool = _pooling_layer(lax.add, 0., _normalize_by_window_size)\ndef Flatten():\n\"\"\"Layer construction function for flattening all but the leading dim.\"\"\"\n- def init_fun(input_shape):\n+ def init_fun(rng, input_shape):\noutput_shape = input_shape[0], reduce(op.mul, input_shape[1:], 1)\nreturn output_shape, ()\ndef apply_fun(params, inputs, **kwargs):\n@@ -202,7 +202,7 @@ Flatten = Flatten()\ndef Identity():\n\"\"\"Layer construction function for an identity layer.\"\"\"\n- init_fun = lambda input_shape: (input_shape, ())\n+ init_fun = lambda rng, input_shape: (input_shape, ())\napply_fun = lambda params, inputs, **kwargs: inputs\nreturn init_fun, apply_fun\nIdentity = Identity()\n@@ -210,14 +210,14 @@ Identity = Identity()\ndef FanOut(num):\n\"\"\"Layer construction function for a fan-out layer.\"\"\"\n- init_fun = lambda input_shape: ([input_shape] * num, ())\n+ init_fun = lambda rng, input_shape: ([input_shape] * num, ())\napply_fun = lambda params, inputs, **kwargs: [inputs] * num\nreturn init_fun, apply_fun\ndef FanInSum():\n\"\"\"Layer construction function for a fan-in sum layer.\"\"\"\n- init_fun = lambda input_shape: (input_shape[0], ())\n+ init_fun = lambda rng, input_shape: (input_shape[0], ())\napply_fun = lambda params, inputs, **kwargs: sum(inputs)\nreturn init_fun, apply_fun\nFanInSum = FanInSum()\n@@ -225,7 +225,7 @@ FanInSum = FanInSum()\ndef FanInConcat(axis=-1):\n\"\"\"Layer construction function for a fan-in concatenation layer.\"\"\"\n- def init_fun(input_shape):\n+ def init_fun(rng, input_shape):\nax = axis % len(input_shape[0])\nconcat_size = sum(shape[ax] for shape in input_shape)\nout_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]\n@@ -237,7 +237,7 @@ def FanInConcat(axis=-1):\ndef Dropout(rate, mode='train'):\n\"\"\"Layer construction function for a dropout layer with given rate.\"\"\"\n- def init_fun(input_shape):\n+ def init_fun(rng, input_shape):\nreturn input_shape, ()\ndef apply_fun(params, inputs, **kwargs):\nrng = kwargs.get('rng', None)\n@@ -270,10 +270,11 @@ def serial(*layers):\n\"\"\"\nnlayers = len(layers)\ninit_funs, apply_funs = zip(*layers)\n- def init_fun(input_shape):\n+ def init_fun(rng, input_shape):\nparams = []\nfor init_fun in init_funs:\n- input_shape, param = init_fun(input_shape)\n+ rng, layer_rng = random.split(rng)\n+ input_shape, param = init_fun(layer_rng, input_shape)\nparams.append(param)\nreturn input_shape, params\ndef apply_fun(params, inputs, **kwargs):\n@@ -302,8 +303,10 @@ def parallel(*layers):\n\"\"\"\nnlayers = len(layers)\ninit_funs, apply_funs = zip(*layers)\n- def init_fun(input_shape):\n- return zip(*[init(shape) for init, shape in zip(init_funs, input_shape)])\n+ def init_fun(rng, input_shape):\n+ rngs = random.split(rng, len(init_funs))\n+ return zip(*[init(rng, shape) for init, rng, shape\n+ in zip(init_funs, rngs, input_shape)])\ndef apply_fun(params, inputs, **kwargs):\nrng = kwargs.pop('rng', None)\nrngs = random.split(rng, nlayers) if rng is not None else (None,) * nlayers\n@@ -323,8 +326,8 @@ def shape_dependent(make_layer):\nlayer as returned by `make_layer` but with its construction delayed until\ninput shapes are known.\n\"\"\"\n- def init_fun(input_shape):\n- return make_layer(input_shape)[0](input_shape)\n+ def init_fun(rng, input_shape):\n+ return make_layer(input_shape)[0](rng, input_shape)\ndef apply_fun(params, inputs, **kwargs):\nreturn make_layer(inputs.shape)[1](params, inputs, **kwargs)\nreturn init_fun, apply_fun\n"
},
{
"change_type": "MODIFY",
"old_path": "notebooks/maml.ipynb",
"new_path": "notebooks/maml.ipynb",
"diff": "\"from jax import vmap # for auto-vectorizing functions\\n\",\n\"from functools import partial # for use with vmap\\n\",\n\"from jax import jit # for compiling functions for speedup\\n\",\n+ \"from jax import random # Stax initialization uses jax.random\n\"from jax.experimental import stax # neural network library\\n\",\n\"from jax.experimental.stax import Conv, Dense, MaxPool, Relu, Flatten, LogSoftmax # neural network layers\\n\",\n\"import matplotlib.pyplot as plt # visualization\"\n\" Dense(1)\\n\",\n\")\\n\",\n\"in_shape = (-1, 1,)\\n\",\n- \"out_shape, net_params = net_init(in_shape)\"\n+ \"rng = random.PRNGKey(0)\n+ \"out_shape, net_params = net_init(rng, in_shape)\"\n]\n},\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/stax_test.py",
"new_path": "tests/stax_test.py",
"diff": "@@ -40,9 +40,10 @@ def random_inputs(rng, input_shape):\ndef _CheckShapeAgreement(test_case, init_fun, apply_fun, input_shape):\n- result_shape, params = init_fun(input_shape)\n- inputs = random_inputs(onp.random.RandomState(0), input_shape)\nrng_key = random.PRNGKey(0)\n+ rng_key, init_key = random.split(rng_key)\n+ result_shape, params = init_fun(init_key, input_shape)\n+ inputs = random_inputs(onp.random.RandomState(0), input_shape)\nresult = apply_fun(params, inputs, rng=rng_key)\ntest_case.assertEqual(result.shape, result_shape)\n@@ -53,14 +54,16 @@ class StaxTest(jtu.JaxTestCase):\n{\"testcase_name\": \"_shape={}\".format(shape), \"shape\": shape}\nfor shape in [(2, 3), (5,)]))\ndef testRandnInitShape(self, shape):\n- out = stax.randn()(shape)\n+ key = random.PRNGKey(0)\n+ out = stax.randn()(key, shape)\nself.assertEqual(out.shape, shape)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}\".format(shape), \"shape\": shape}\nfor shape in [(2, 3), (2, 3, 4)]))\ndef testGlorotInitShape(self, shape):\n- out = stax.glorot()(shape)\n+ key = random.PRNGKey(0)\n+ out = stax.glorot()(key, shape)\nself.assertEqual(out.shape, shape)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -164,11 +167,12 @@ class StaxTest(jtu.JaxTestCase):\n_CheckShapeAgreement(self, init_fun, apply_fun, input_shapes)\ndef testIssue182(self):\n+ key = random.PRNGKey(0)\ninit_fun, apply_fun = stax.Softmax\ninput_shape = (10, 3)\ninputs = onp.arange(30.).astype(\"float32\").reshape(input_shape)\n- out_shape, params = init_fun(input_shape)\n+ out_shape, params = init_fun(key, input_shape)\nout = apply_fun(params, inputs)\nassert out_shape == out.shape\n@@ -176,11 +180,12 @@ class StaxTest(jtu.JaxTestCase):\ndef testBatchNormShapeNHWC(self):\n+ key = random.PRNGKey(0)\ninit_fun, apply_fun = stax.BatchNorm(axis=(0, 1, 2))\ninput_shape = (4, 5, 6, 7)\ninputs = random_inputs(onp.random.RandomState(0), input_shape)\n- out_shape, params = init_fun(input_shape)\n+ out_shape, params = init_fun(key, input_shape)\nout = apply_fun(params, inputs)\nself.assertEqual(out_shape, input_shape)\n@@ -190,12 +195,13 @@ class StaxTest(jtu.JaxTestCase):\nself.assertEqual(out_shape, out.shape)\ndef testBatchNormShapeNCHW(self):\n+ key = random.PRNGKey(0)\n# Regression test for https://github.com/google/jax/issues/461\ninit_fun, apply_fun = stax.BatchNorm(axis=(0, 2, 3))\ninput_shape = (4, 5, 6, 7)\ninputs = random_inputs(onp.random.RandomState(0), input_shape)\n- out_shape, params = init_fun(input_shape)\n+ out_shape, params = init_fun(key, input_shape)\nout = apply_fun(params, inputs)\nself.assertEqual(out_shape, input_shape)\n"
}
] | Python | Apache License 2.0 | google/jax | Use jax.random for stax initialization |
260,299 | 03.04.2019 13:27:23 | -3,600 | 44c38391ccd9337aa7d29a76ad772f884f1775e6 | Cleaner stax.parallel init | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -304,7 +304,7 @@ def parallel(*layers):\nnlayers = len(layers)\ninit_funs, apply_funs = zip(*layers)\ndef init_fun(rng, input_shape):\n- rngs = random.split(rng, len(init_funs))\n+ rngs = random.split(rng, nlayers)\nreturn zip(*[init(rng, shape) for init, rng, shape\nin zip(init_funs, rngs, input_shape)])\ndef apply_fun(params, inputs, **kwargs):\n"
}
] | Python | Apache License 2.0 | google/jax | Cleaner stax.parallel init |
260,299 | 03.04.2019 13:32:14 | -3,600 | 70fc02504b63c25de7efbdb428223492cdfcbe92 | Fix examples_test.py | [
{
"change_type": "MODIFY",
"old_path": "examples/examples_test.py",
"new_path": "examples/examples_test.py",
"diff": "@@ -25,6 +25,7 @@ from absl.testing import parameterized\nimport numpy as onp\nfrom jax import test_util as jtu\n+from jax import random\nimport jax.numpy as np\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n@@ -38,7 +39,8 @@ FLAGS = config.FLAGS\ndef _CheckShapeAgreement(test_case, init_fun, apply_fun, input_shape):\n- result_shape, params = init_fun(input_shape)\n+ jax_rng = random.PRNGKey(0)\n+ result_shape, params = init_fun(jax_rng, input_shape)\nrng = onp.random.RandomState(0)\nresult = apply_fun(params, rng.randn(*input_shape).astype(dtype=\"float32\"))\ntest_case.assertEqual(result.shape, result_shape)\n"
}
] | Python | Apache License 2.0 | google/jax | Fix examples_test.py |
260,299 | 03.04.2019 15:03:29 | -3,600 | ccb88c4eaab896854085f1d2154591524f0e6f1d | Fix stax x64 dtype issues | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -61,7 +61,7 @@ def fastvar(x, axis, keepdims):\ndef randn(stddev=1e-2):\n\"\"\"An initializer function for random normal coefficients.\"\"\"\ndef init(rng, shape):\n- return stddev * random.normal(rng, shape)\n+ return (stddev * random.normal(rng, shape)).astype('float32')\nreturn init\ndef glorot(out_dim=0, in_dim=1, scale=onp.sqrt(2)):\n@@ -70,7 +70,7 @@ def glorot(out_dim=0, in_dim=1, scale=onp.sqrt(2)):\nfan_in, fan_out = shape[in_dim], shape[out_dim]\nsize = onp.prod(onp.delete(shape, [in_dim, out_dim]))\nstd = scale / np.sqrt((fan_in + fan_out) / 2. * size)\n- return std * random.normal(rng, shape)\n+ return (std * random.normal(rng, shape)).astype('float32')\nreturn init\nzeros = lambda rng, shape: np.zeros(shape, dtype='float32')\n"
}
] | Python | Apache License 2.0 | google/jax | Fix stax x64 dtype issues |
260,335 | 03.04.2019 09:43:44 | 25,200 | f0e2ff0c95a89d7b6be077a8dcce64c20f1d8609 | make DeviceArray.__repr__ show it's not an ndarray
reverts 33bd02 | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -302,6 +302,10 @@ class DeviceArray(DeviceValue):\n\"\"\"Returns an ndarray (backed by host memory, not device memory).\"\"\"\nreturn onp.asarray(self)\n+ def __repr__(self):\n+ shape_str = \",\".join(map(str, self.shape))\n+ return \"DeviceArray{{{}[{}]}}\".format(onp.dtype(self.dtype).name, shape_str)\n+\ndef __len__(self):\ntry:\nreturn self.shape[0]\n@@ -329,7 +333,6 @@ class DeviceArray(DeviceValue):\n__array__ = partialmethod(forward_to_value, onp.asarray)\n__str__ = partialmethod(forward_to_value, str)\n- __repr__ = partialmethod(forward_to_value, repr)\n__bool__ = __nonzero__ = partialmethod(forward_to_value, bool)\n__float__ = partialmethod(forward_to_value, float)\n__int__ = partialmethod(forward_to_value, int)\n"
}
] | Python | Apache License 2.0 | google/jax | make DeviceArray.__repr__ show it's not an ndarray
reverts 33bd02 |
260,268 | 03.04.2019 10:18:49 | 25,200 | 026a743000900a96bf8701b4a1aad712b93d63b5 | Change MNIST Data URL to CVDF mirror
Change the MNIST data download url to the CVDF mirror, as is done in the main tensorflow and tfds datasets. | [
{
"change_type": "MODIFY",
"old_path": "examples/datasets.py",
"new_path": "examples/datasets.py",
"diff": "@@ -53,7 +53,8 @@ def _one_hot(x, k, dtype=np.float32):\ndef mnist_raw():\n\"\"\"Download and parse the raw MNIST dataset.\"\"\"\n- base_url = \"http://yann.lecun.com/exdb/mnist/\"\n+ # CVDF mirror of http://yann.lecun.com/exdb/mnist/\n+ base_url = \"https://storage.googleapis.com/cvdf-datasets/mnist/\"\ndef parse_labels(filename):\nwith gzip.open(filename, \"rb\") as fh:\n"
}
] | Python | Apache License 2.0 | google/jax | Change MNIST Data URL to CVDF mirror
Change the MNIST data download url to the CVDF mirror, as is done in the main tensorflow and tfds datasets. |
260,299 | 04.04.2019 09:12:27 | -3,600 | 49f3f991d4faae22fcd9d8248f3d36575b5004f6 | Use safe mul for exp jvp | [
{
"change_type": "MODIFY",
"old_path": "jax/lax.py",
"new_path": "jax/lax.py",
"diff": "@@ -1611,7 +1611,7 @@ is_finite_p = unop(_fixed_dtype(onp.bool_), _float, 'is_finite')\nad.defjvp_zero(is_finite_p)\nexp_p = standard_unop(_float | _complex, 'exp')\n-ad.defjvp2(exp_p, lambda g, ans, x: mul(g, ans))\n+ad.defjvp2(exp_p, lambda g, ans, x: _safe_mul(g, ans))\nlog_p = standard_unop(_float | _complex, 'log')\nad.defjvp(log_p, lambda g, x: div(g, x))\n"
}
] | Python | Apache License 2.0 | google/jax | Use safe mul for exp jvp |
260,403 | 04.04.2019 02:09:35 | 25,200 | 116e329e10e22c04f2bcb591c49be83b54dd83c2 | correctly update jax config.values after absl flag parsing | [
{
"change_type": "MODIFY",
"old_path": "jax/config.py",
"new_path": "jax/config.py",
"diff": "@@ -73,6 +73,8 @@ class Config(object):\nflag_type, meta_args, meta_kwargs = self.meta[name]\nabsl_defs[flag_type](name, val, *meta_args, **meta_kwargs)\n+ app.call_after_init(lambda: self.complete_absl_config(absl_flags))\n+\ndef complete_absl_config(self, absl_flags):\nfor name, _ in self.values.items():\nself.update(name, getattr(absl_flags.FLAGS, name))\n@@ -83,6 +85,7 @@ class Config(object):\nimport absl.flags\nself.config_with_absl()\nabsl.flags.FLAGS(sys.argv)\n+ self.complete_absl_config(absl.flags)\nalready_configured_with_absl = True\n"
}
] | Python | Apache License 2.0 | google/jax | correctly update jax config.values after absl flag parsing |
260,335 | 04.04.2019 17:40:48 | 25,200 | 054d210a3210d950a8371e1687136701acfb5e1b | fix typo in xla_computation | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -157,15 +157,15 @@ def xla_computation(fun, static_argnums=()):\naval = xla.abstractify(x)\nreturn pe.PartialVal((aval, core.unit))\n- wrapped = lu.wrap_init(fun)\n@wraps(fun)\ndef computation_maker(*args, **kwargs):\n+ wrapped = lu.wrap_init(fun)\njax_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\njaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(wrapped, in_trees)\npvals = map(pv_like, jax_args)\njaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals, **kwargs)\n- return xla.build_jaxpr(jaxpr, consts, *map(xla.abstractify, args))\n+ return xla.build_jaxpr(jaxpr, consts, *map(xla.abstractify, jax_args))\nreturn computation_maker\n"
}
] | Python | Apache License 2.0 | google/jax | fix typo in xla_computation |
260,335 | 05.04.2019 12:59:52 | 25,200 | 027c94da4c04521ed037b5b6753165477b23d05a | update readme gotchas section | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -716,9 +716,10 @@ code to compile and end-to-end optimize much bigger functions.\nFor a survey of current gotchas, with examples and explanations, we highly recommend reading the [Gotchas Notebook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb).\n-Two stand-out gotchas that might surprise NumPy users:\n-1. In-place mutation of arrays isn't supported. Generally JAX requires functional code.\n-2. PRNGs can be awkward, and non-reuse (linearity) is not checked.\n+Some stand-out gotchas that might surprise NumPy users:\n+1. [`np.isnan` doesn't yet work](https://github.com/google/jax/issues/276), and in general nan semantics aren't preserved on some backends.\n+1. In-place mutation of arrays isn't supported, though [there is an alternative](https://jax.readthedocs.io/en/latest/jax.ops.html). Generally JAX requires functional code.\n+2. PRNGs are different and can be awkward, though for [good reasons](https://github.com/google/jax/blob/master/design_notes/prng.md), and non-reuse (linearity) is not yet checked.\nSee [the notebook](https://colab.research.google.com/github/google/jax/blob/master/notebooks/Common_Gotchas_in_JAX.ipynb) for much more information.\n"
}
] | Python | Apache License 2.0 | google/jax | update readme gotchas section |
260,335 | 06.04.2019 10:33:18 | 25,200 | 1be9abd322d1879440f6c45fc94b0217d1c5d848 | add jax.numpy.einsum_path (fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1509,6 +1509,11 @@ def einsum(*operands):\ncontractions = tuple(data[:3] for data in contractions)\nreturn _einsum(operands, contractions)\n+@_wraps(onp.einsum_path)\n+def einsum_path(subscripts, *operands, **kwargs):\n+ optimize = kwargs.pop('optimize', 'greedy')\n+ # using einsum_call=True here is an internal api for opt_einsum\n+ return opt_einsum.contract_path(subscripts, *operands, optimize=optimize)\n@partial(jit, static_argnums=(1,))\ndef _einsum(operands, contractions):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_einsum_test.py",
"new_path": "tests/lax_numpy_einsum_test.py",
"diff": "@@ -277,6 +277,22 @@ class EinsumTest(jtu.JaxTestCase):\ns = 'ijkl,ijml->ijkm'\nself._check(s, x, y)\n+ def test_einsum_path(self):\n+ # just check examples from onp.einsum_path docstring\n+ a = onp.random.rand(2, 2)\n+ b = onp.random.rand(2, 5)\n+ c = onp.random.rand(5, 2)\n+\n+ path_info = onp.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy')\n+ self.assertEqual(str(path_info[0]), \"['einsum_path', (1, 2), (0, 1)]\")\n+ self.assertEqual(path_info[1].split('\\n')[0],\n+ ' Complete contraction: ij,jk,kl->il')\n+\n+ # check this doesn't crash\n+ I = onp.random.rand(10, 10, 10, 10)\n+ C = onp.random.rand(10, 10)\n+ onp.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C, optimize='greedy')\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add jax.numpy.einsum_path (fixes #579) |
260,335 | 06.04.2019 12:52:47 | 25,200 | 6ec2eb72e5614bbc5e0f6bd8e8a96eca44cc5172 | make np.arange(N) create lazy const, arange tests | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1260,16 +1260,18 @@ def identity(n, dtype=None):\n@_wraps(onp.arange)\ndef arange(*args, **kwargs):\n- # attempt to generate a lazy IotaConstant, otherwise fall back to raw numpy\n- # TODO(mattjj): add tests for this function, then re-enable\n- # dtype = kwargs.pop(\"dtype\", None)\n- # if not args:\n- # raise TypeError(\"Required argument 'start' (pos 1) not found\") # same as numpy error\n- # elif len(args) == 1 and not kwargs:\n- # stop, = args\n- # dtype = dtype or _dtype(stop)\n- # if onp.issubdtype(dtype, onp.integer):\n- # return lax.iota(dtype, stop) # avoids materializing\n+ dtype = kwargs.pop(\"dtype\", None)\n+ if not args:\n+ raise TypeError(\"Required argument 'start' (pos 1) not found\") # same as numpy error\n+\n+ # if called like np.arange(N) we create a lazy lax._IotaConstant\n+ if len(args) == 1 and not kwargs:\n+ stop, = args\n+ dtype = dtype or _dtype(stop)\n+ if onp.issubdtype(dtype, onp.integer):\n+ return lax.iota(dtype, stop) # avoids materializing\n+\n+ # fall back to instantiating an ndarray in host memory\nreturn onp.arange(*args, **kwargs)\nlinspace = onp.linspace\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1187,7 +1187,6 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nans = onp.mean(x)\nself.assertAllClose(ans, onp.array(1./3), check_dtypes=False)\n- # TODO(mattjj): more exhaustive arange tests\ndef testArangeOnFloats(self):\n# from https://github.com/google/jax/issues/145\nexpected = onp.arange(0.0, 1.0, 0.1)\n@@ -1375,6 +1374,30 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself.assertAllClose(onp.int64(7), api.jit(lambda x: x)(onp.longlong(7)),\ncheck_dtypes=True)\n+ def testArange(self):\n+ # test cases inspired by dask tests at\n+ # https://github.com/dask/dask/blob/master/dask/array/tests/test_creation.py#L92\n+ self.assertAllClose(lnp.arange(77),\n+ onp.arange(77), check_dtypes=True)\n+ self.assertAllClose(lnp.arange(2, 13),\n+ onp.arange(2, 13), check_dtypes=True)\n+ self.assertAllClose(lnp.arange(4, 21, 9),\n+ onp.arange(4, 21, 9), check_dtypes=True)\n+ self.assertAllClose(lnp.arange(53, 5, -3),\n+ onp.arange(53, 5, -3), check_dtypes=True)\n+ self.assertAllClose(lnp.arange(77, dtype=float),\n+ onp.arange(77, dtype=float), check_dtypes=True)\n+ self.assertAllClose(lnp.arange(2, 13, dtype=int),\n+ onp.arange(2, 13, dtype=int), check_dtypes=True)\n+ self.assertAllClose(lnp.arange(0, 1, -0.5),\n+ onp.arange(0, 1, -0.5), check_dtypes=True)\n+\n+ self.assertRaises(TypeError, lambda: lnp.arange())\n+\n+ # test that lnp.arange(N) doesn't instantiate an ndarray\n+ self.assertFalse(type(lnp.arange(77)) == type(onp.arange(77)))\n+ self.assertTrue(type(lnp.arange(77)) == type(lax.iota(onp.int32, 77)))\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | make np.arange(N) create lazy const, arange tests |
260,335 | 06.04.2019 14:16:22 | 25,200 | 299977eeef300b46be40f42baf3929be742d2ff4 | exclude examples dir from setup.py find_packages
fixes | [
{
"change_type": "MODIFY",
"old_path": "setup.py",
"new_path": "setup.py",
"diff": "@@ -23,7 +23,7 @@ setup(\ndescription='Differentiate, compile, and transform Numpy code.',\nauthor='JAX team',\nauthor_email='jax-dev@google.com',\n- packages=find_packages(),\n+ packages=find_packages(exclude=[\"examples\"]),\ninstall_requires=[\n'numpy>=1.12', 'six', 'protobuf>=3.6.0', 'absl-py', 'opt_einsum'\n],\n"
}
] | Python | Apache License 2.0 | google/jax | exclude examples dir from setup.py find_packages
fixes #582 |
260,335 | 06.04.2019 15:08:22 | 25,200 | 1feaf639893422bf45b72c4f001c7ffb204c1cef | comment out failing arange tests | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1385,10 +1385,11 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nonp.arange(4, 21, 9), check_dtypes=True)\nself.assertAllClose(lnp.arange(53, 5, -3),\nonp.arange(53, 5, -3), check_dtypes=True)\n- self.assertAllClose(lnp.arange(77, dtype=float),\n- onp.arange(77, dtype=float), check_dtypes=True)\n- self.assertAllClose(lnp.arange(2, 13, dtype=int),\n- onp.arange(2, 13, dtype=int), check_dtypes=True)\n+ # TODO(mattjj): make these tests work when jax_enable_x64=True\n+ # self.assertAllClose(lnp.arange(77, dtype=float),\n+ # onp.arange(77, dtype=float), check_dtypes=True)\n+ # self.assertAllClose(lnp.arange(2, 13, dtype=int),\n+ # onp.arange(2, 13, dtype=int), check_dtypes=True)\nself.assertAllClose(lnp.arange(0, 1, -0.5),\nonp.arange(0, 1, -0.5), check_dtypes=True)\n"
}
] | Python | Apache License 2.0 | google/jax | comment out failing arange tests |
260,335 | 06.04.2019 14:42:27 | 25,200 | f4e141d30e8768d09f69365f445d34e54cf16ee2 | add 'optimize' kwarg to jax.numpy.einsum | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1504,10 +1504,15 @@ def tensordot(a, b, axes=2):\n@_wraps(onp.einsum)\n-def einsum(*operands):\n+def einsum(*operands, **kwargs):\n+ optimize = kwargs.pop('optimize', 'auto')\n+ optimize = 'greedy' if optimize is True else optimize\n+ if kwargs:\n+ msg = 'invalid keyword arguments for einsum: {}'\n+ raise TypeError(msg.format(', '.join(kwargs)))\n# using einsum_call=True here is an internal api for opt_einsum\noperands, contractions = opt_einsum.contract_path(\n- *operands, einsum_call=True, use_blas=True)\n+ *operands, einsum_call=True, use_blas=True, optimize=optimize)\ncontractions = tuple(data[:3] for data in contractions)\nreturn _einsum(operands, contractions)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_einsum_test.py",
"new_path": "tests/lax_numpy_einsum_test.py",
"diff": "@@ -293,6 +293,25 @@ class EinsumTest(jtu.JaxTestCase):\nC = onp.random.rand(10, 10)\nonp.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C, optimize='greedy')\n+ def test_einsum_kpmurphy_example(self):\n+ N = 2; C = 3; D = 4; K = 5; T = 6;\n+ r = rng()\n+ S = r.randn(N, T, K)\n+ W = r.randn(K, D)\n+ V = r.randn(D, C)\n+ L = onp.zeros((N,C))\n+ for n in range(N):\n+ for c in range(C):\n+ s = 0\n+ for d in range(D):\n+ for k in range(K):\n+ for t in range(T):\n+ s += S[n,t,k] * W[k,d] * V[d,c]\n+ L[n,c] = s\n+\n+ path = np.einsum_path('ntk,kd,dc->nc', S, W, V, optimize='optimal')[0]\n+ assert np.allclose(L, np.einsum('ntk,kd,dc->nc', S, W, V, optimize=path))\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add 'optimize' kwarg to jax.numpy.einsum |
260,335 | 06.04.2019 15:02:53 | 25,200 | 46e26a790a46059ad27cf879183c812263f1bc4e | add a comment about kpmurphy einsum test | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_einsum_test.py",
"new_path": "tests/lax_numpy_einsum_test.py",
"diff": "@@ -294,6 +294,7 @@ class EinsumTest(jtu.JaxTestCase):\nonp.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C, optimize='greedy')\ndef test_einsum_kpmurphy_example(self):\n+ # code from an email with @murphyk\nN = 2; C = 3; D = 4; K = 5; T = 6;\nr = rng()\nS = r.randn(N, T, K)\n"
}
] | Python | Apache License 2.0 | google/jax | add a comment about kpmurphy einsum test |
260,335 | 08.04.2019 09:52:47 | 25,200 | 108a2dbb9cbc7ad2809f339cf7930525f254b7ad | tweak an einsum test | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_einsum_test.py",
"new_path": "tests/lax_numpy_einsum_test.py",
"diff": "@@ -311,7 +311,8 @@ class EinsumTest(jtu.JaxTestCase):\nL[n,c] = s\npath = np.einsum_path('ntk,kd,dc->nc', S, W, V, optimize='optimal')[0]\n- assert np.allclose(L, np.einsum('ntk,kd,dc->nc', S, W, V, optimize=path))\n+ self.assertAllClose(L, np.einsum('ntk,kd,dc->nc', S, W, V, optimize=path),\n+ check_dtypes=False)\nif __name__ == '__main__':\n"
}
] | Python | Apache License 2.0 | google/jax | tweak an einsum test |
260,407 | 08.04.2019 19:15:47 | -7,200 | d42f515c65c8154caa55df32cebb9f6a40e16de8 | Fixed numpy.zeros shape generator error | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -21,6 +21,7 @@ import itertools\nimport re\nimport string\nimport warnings\n+import types\nimport numpy as onp\nimport opt_einsum\n@@ -1221,6 +1222,8 @@ def full_like(a, fill_value, dtype=None):\n@_wraps(onp.zeros)\ndef zeros(shape, dtype=onp.dtype(\"float64\")):\n+ if isinstance(shape, types.GeneratorType):\n+ raise TypeError(\"expected sequence object with len >= 0 or a single integer\")\nshape = (shape,) if onp.isscalar(shape) else shape\nreturn lax.full(shape, 0, dtype)\n"
}
] | Python | Apache License 2.0 | google/jax | Fixed numpy.zeros shape generator error |
260,403 | 09.04.2019 15:06:46 | 25,200 | 797d411eebd0f22dbdf5556a462072666251fe1a | initial tranpose conv implementation | [
{
"change_type": "MODIFY",
"old_path": "jax/lax.py",
"new_path": "jax/lax.py",
"diff": "@@ -1229,6 +1229,88 @@ def conv_with_general_padding(lhs, rhs, window_strides, padding,\nrhs_dilation=rhs_dilation)\n+def _conv_transpose_padding(k, s, padding):\n+ \"\"\"Calculate before and after padding for a dim of transposed convolution.\n+\n+ Args:\n+ k: int: kernel dimension.\n+ s: int: dimension stride value.\n+ padding: 'same' or 'valid' padding mode for original forward conv.\n+\n+ Returns:\n+ 2-tuple: ints: before and after padding for transposed convolution.\n+ \"\"\"\n+ if padding.lower() == 'same':\n+ pad_len = k + s - 2\n+ if s > k - 1:\n+ pad_a = k - 1\n+ else:\n+ pad_a = int(onp.ceil(pad_len / 2))\n+ elif padding.lower() == 'valid':\n+ pad_len = k + s - 2 + max(k - s, 0)\n+ pad_a = k - 1\n+ else:\n+ raise ValueError('Padding mode must be `same` or `valid`.')\n+ pad_b = pad_len - pad_a\n+ return pad_a, pad_b\n+\n+\n+def _flip_axes(x, axes):\n+ \"\"\"Flip ndarray 'x' along each axis specified in axes tuple.\"\"\"\n+ for axis in axes:\n+ x = onp.flip(x, axis)\n+ return x\n+\n+\n+def conv_transpose(data, kernel, strides, padding, dimension_numbers=None):\n+ \"\"\"Convenience wrapper for calculating the N-d convolution transpose.\n+\n+ This function directly calculates convT rather than indirectly calculating\n+ the gradient (transpose) of a forward convolution.\n+\n+ Args:\n+ data: a rank `n+2` dimensional input array.\n+ kernel: a rank `n+2` dimensional array of kernel weights.\n+ strides: sequence of `n` integers, sets fractional stride.\n+ padding: 'same', 'valid' will set as transpose of corresponding forward\n+ conv, or a sequence of `n` integer 2-tuples describing before-and-after\n+ padding for each `n` spatial dimension.\n+ dimension_numbers: tuple of dimension descriptors as in\n+ lax.conv_general_dilated. Defaults to tensorflow convention.\n+\n+ Returns:\n+ Transposed N-d convolution, with padding following the conventions of the\n+ corresponding keras and tensorflow conv-transpose operators.\n+ \"\"\"\n+ assert len(data.shape) == len(kernel.shape) and len(data.shape) > 2\n+ ndims = len(data.shape)\n+ one = (1,) * (ndims - 2)\n+ #Set dimensional layout defaults if not specified.\n+ if dimension_numbers is None:\n+ if ndims == 3:\n+ dimension_numbers = ('NHC', 'HIO', 'NHC')\n+ elif ndims == 4:\n+ dimension_numbers = ('NHWC', 'HWIO', 'NHWC')\n+ elif ndims == 5:\n+ dimension_numbers = ('NHWDC', 'HWDIO', 'NHWDC')\n+ else:\n+ raise ValueError('No 4+ dimensional dimension_number defaults.')\n+ dn = conv_dimension_numbers(data.shape, kernel.shape, dimension_numbers)\n+ k_shape = onp.take(kernel.shape, dn.rhs_spec)\n+ k_sdims = k_shape[2:]\n+ # Calculate correct output shape given padding and strides.\n+ if padding.lower() in {'same', 'valid'}:\n+ pads = [_conv_transpose_padding(k, s, padding)\n+ for k,s in zip(k_sdims.tolist(), strides)]\n+ else:\n+ pads = padding\n+ # transposed conv = flipped kernel plus LHS dilation\n+ kernel_t = _flip_axes(kernel, onp.array(dn.rhs_spec)[2:])\n+ # flip input/output channel axes\n+ kernel_t = onp.swapaxes(kernel_t, dn.rhs_spec[0], dn.rhs_spec[1])\n+ return conv_general_dilated(data, kernel_t, one, pads, strides, one, dn)\n+\n+\ndef full_like(x, fill_value, dtype=None, shape=None):\n\"\"\"Create a full array like np.full based on the example array `x`.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -445,6 +445,67 @@ class LaxTest(jtu.JaxTestCase):\n# TODO(mattjj): test conv_general_dilated against numpy\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\".format(\n+ jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"strides\": strides, \"padding\": padding, \"rng\": rng, 'dspec': dspec}\n+ for lhs_shape, rhs_shape in [\n+ ((b, 9, 10, i), (3, 3, i, j))\n+ for b, i, j in itertools.product([2, 3], repeat=3)]\n+ for dtype in [onp.float32]\n+ for strides in [(1, 1), (1, 2), (2, 1), (2, 2), (3, 3)]\n+ for padding in [\"VALID\", \"SAME\"]\n+ for dspec in [('NHWC', 'HWIO', 'NHWC'),]\n+ for rng in [jtu.rand_small()]))\n+ def testConvTranspose(self, lhs_shape, rhs_shape, dtype, strides,\n+ padding, dspec, rng):\n+ def deconv_output_length(input_length, filter_size, padding, stride=0):\n+ if padding.lower() == 'valid':\n+ length = input_length * stride + max(filter_size - stride, 0)\n+ elif padding.lower() == 'same':\n+ length = input_length * stride\n+ return length\n+ def inv_permutation(p):\n+ return [x[0] for x in sorted(enumerate(p), key=lambda x: x[1])]\n+ def conv_transpose_via_grad(data, kernel, strides, padding,\n+ dimension_numbers=dspec):\n+ assert len(data.shape) == len(kernel.shape)\n+ ndims = len(data.shape)\n+ nspatial = ndims - 2\n+ one = (1,) * nspatial\n+ dn = lax.conv_dimension_numbers(data.shape, kernel.shape,\n+ dimension_numbers)\n+ in_shape = onp.take(data.shape, dn.lhs_spec)\n+ in_sdims = in_shape[2:]\n+ k_shape = onp.take(kernel.shape, dn.rhs_spec)\n+ k_sdims = k_shape[2:]\n+ o_sdims = [deconv_output_length(in_sdims[i], k_sdims[i], padding,\n+ stride=strides[i])\n+ for i in range(nspatial)]\n+ o_shape = [in_shape[0], k_shape[1]] + o_sdims\n+ o_layout = onp.take(onp.array(o_shape), inv_permutation(dn.out_spec))\n+ placeholder = onp.ones(o_layout, data.dtype)\n+ conv = lambda x: lax.conv_general_dilated(x, kernel, strides, padding,\n+ one, one, dn)\n+ _, g = api.vjp(conv, placeholder)\n+ return g(data)[0]\n+\n+ args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n+\n+ def fun(lhs, rhs):\n+ return lax.conv_transpose(lhs, rhs, strides, padding,\n+ dimension_numbers=dspec)\n+\n+ def fun_via_grad(lhs, rhs):\n+ return conv_transpose_via_grad(lhs, rhs, strides, padding,\n+ dimension_numbers=dspec)\n+\n+ # self._CompileAndCheck(fun, args_maker, check_dtypes=True)\n+ self._CheckAgainstNumpy(fun, fun_via_grad, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_lhs_shape={}_rhs_shape={}\".format(\njtu.format_shape_dtype_string(lhs_shape, dtype),\n"
}
] | Python | Apache License 2.0 | google/jax | initial tranpose conv implementation |
260,335 | 09.04.2019 18:59:42 | 25,200 | d60cd4ec591c00e879e95988dc64872ca0299f72 | use SkipTest instead of
nose doesn't like DISABLED_ name prefixes, but dirctly running the
Python file doesn't like | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -21,7 +21,7 @@ import functools\nfrom functools import partial\nimport itertools\nimport unittest\n-from unittest import skip\n+from unittest import SkipTest\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -1368,9 +1368,9 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nexpected = onp.reshape(a, (3, 2), order='F')\nself.assertAllClose(ans, expected, check_dtypes=True)\n- # TODO(phawkins): enable after a Jaxlib update.\n- @skip(\"Test disabled until jaxlib 0.1.13 is released.\")\ndef testLongLong(self):\n+ # TODO(phawkins): enable after a Jaxlib update.\n+ return SkipTest(\"Test disabled until jaxlib 0.1.13 is released.\")\nself.assertAllClose(onp.int64(7), api.jit(lambda x: x)(onp.longlong(7)),\ncheck_dtypes=True)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -368,7 +368,6 @@ class LaxTest(jtu.JaxTestCase):\nself._CompileAndCheck(fun, args_maker, check_dtypes=True)\n- @skip\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\"\n\"_lhs_dilation={}_rhs_dilation={}\".format(\n@@ -390,6 +389,7 @@ class LaxTest(jtu.JaxTestCase):\nself, lhs_shape, rhs_shape, dtype, strides, padding, lhs_dilation,\nrhs_dilation, rng):\n# TODO(mattjj): make this test pass\n+ return SkipTest(\"this test is incomplete\")\nargs_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\ndef fun(lhs, rhs):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/parallel_test.py",
"new_path": "tests/parallel_test.py",
"diff": "@@ -16,7 +16,7 @@ from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n-from unittest import skip\n+from unittest import SkipTest\nimport numpy as onp\nfrom absl.testing import absltest\n@@ -145,8 +145,8 @@ class PapplyTest(jtu.JaxTestCase):\nexpected = lax.select(p, t, f)\nself.assertAllClose(ans, expected, check_dtypes=True)\n- @skip\n- def DISABLED_testLogSoftmax(self):\n+ def testLogSoftmax(self):\n+ return SkipTest(\"test doesn't pass yet\") # TODO(frostig)\ndef fun(x):\nreturn x - np.log(np.sum(np.exp(x)))\n@@ -170,8 +170,8 @@ class PapplyTest(jtu.JaxTestCase):\nans = serial_pmap(pfun, axis_name)(x, x)\nself.assertAllClose(ans, expected, check_dtypes=True)\n- @skip\n- def DISABLED_testAddBroadcasting(self):\n+ def testAddBroadcasting(self):\n+ return SkipTest(\"test doesn't pass yet\") # TODO(frostig)\ndef fun(x):\nreturn x + 3\n@@ -225,8 +225,7 @@ class PapplyTest(jtu.JaxTestCase):\nans = serial_pmap(pfun, axis_name)(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @skip\n- def DISABLED_testTransposeAndAddRank3(self):\n+ def testTransposeAndAddRank3(self):\ndef fun(x):\nreturn x + x.T\n@@ -238,9 +237,8 @@ class PapplyTest(jtu.JaxTestCase):\nans = serial_pmap(pfun, axis_name)(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- # Fails with shape mismatch.\n- @skip\ndef testDot(self):\n+ return SkipTest(\"test doesn't pass yet\") # TODO(frostig)\ndef fun(x, y):\nreturn lax.dot(x, y)\n"
}
] | Python | Apache License 2.0 | google/jax | use SkipTest instead of @skip
nose doesn't like DISABLED_ name prefixes, but dirctly running the
Python file doesn't like @skip. |
260,403 | 09.04.2019 22:59:03 | 25,200 | cef4c94c13753f9531d780dd4146a6baa6d5413c | finish transposed convolution implementation and tests | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/stax.py",
"new_path": "jax/experimental/stax.py",
"diff": "@@ -123,6 +123,35 @@ def GeneralConv(dimension_numbers, out_chan, filter_shape,\nConv = functools.partial(GeneralConv, ('NHWC', 'HWIO', 'NHWC'))\n+def GeneralConvTranspose(dimension_numbers, out_chan, filter_shape,\n+ strides=None, padding='VALID', W_init=None,\n+ b_init=randn(1e-6)):\n+ \"\"\"Layer construction function for a general transposed-convolution layer.\"\"\"\n+ lhs_spec, rhs_spec, out_spec = dimension_numbers\n+ one = (1,) * len(filter_shape)\n+ strides = strides or one\n+ W_init = W_init or glorot(rhs_spec.index('O'), rhs_spec.index('I'))\n+ def init_fun(rng, input_shape):\n+ filter_shape_iter = iter(filter_shape)\n+ kernel_shape = [out_chan if c == 'O' else\n+ input_shape[lhs_spec.index('C')] if c == 'I' else\n+ next(filter_shape_iter) for c in rhs_spec]\n+ output_shape = lax.conv_transpose_shape_tuple(\n+ input_shape, kernel_shape, strides, padding, dimension_numbers)\n+ bias_shape = [out_chan if c == 'C' else 1 for c in out_spec]\n+ bias_shape = tuple(itertools.dropwhile(lambda x: x == 1, bias_shape))\n+ W, b = W_init(rng, kernel_shape), b_init(rng, bias_shape)\n+ return output_shape, (W, b)\n+ def apply_fun(params, inputs, **kwargs):\n+ W, b = params\n+ return lax.conv_transpose(inputs, W, strides, padding,\n+ dimension_numbers) + b\n+ return init_fun, apply_fun\n+Conv1DTranspose = functools.partial(GeneralConvTranspose, ('NHC', 'HIO', 'NHC'))\n+ConvTranspose = functools.partial(GeneralConvTranspose,\n+ ('NHWC', 'HWIO', 'NHWC'))\n+\n+\ndef BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True,\nbeta_init=zeros, gamma_init=ones):\n\"\"\"Layer construction function for a batch normalization layer.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax.py",
"new_path": "jax/lax.py",
"diff": "@@ -1240,17 +1240,17 @@ def _conv_transpose_padding(k, s, padding):\nReturns:\n2-tuple: ints: before and after padding for transposed convolution.\n\"\"\"\n- if padding.lower() == 'same':\n+ if padding == 'SAME':\npad_len = k + s - 2\nif s > k - 1:\npad_a = k - 1\nelse:\npad_a = int(onp.ceil(pad_len / 2))\n- elif padding.lower() == 'valid':\n+ elif padding == 'VALID':\npad_len = k + s - 2 + max(k - s, 0)\npad_a = k - 1\nelse:\n- raise ValueError('Padding mode must be `same` or `valid`.')\n+ raise ValueError('Padding mode must be `SAME` or `VALID`.')\npad_b = pad_len - pad_a\nreturn pad_a, pad_b\n@@ -1262,28 +1262,34 @@ def _flip_axes(x, axes):\nreturn x\n-def conv_transpose(data, kernel, strides, padding, dimension_numbers=None):\n- \"\"\"Convenience wrapper for calculating the N-d convolution transpose.\n+def conv_transpose(lhs, rhs, strides, padding, dimension_numbers=None,\n+ transpose_kernel=False):\n+ \"\"\"Convenience wrapper for calculating the N-d convolution \"transpose\".\n- This function directly calculates convT rather than indirectly calculating\n- the gradient (transpose) of a forward convolution.\n+ This function directly calculates a fractionally strided conv rather than\n+ indirectly calculating the gradient (transpose) of a forward convolution.\nArgs:\n- data: a rank `n+2` dimensional input array.\n- kernel: a rank `n+2` dimensional array of kernel weights.\n+ lhs: a rank `n+2` dimensional input array.\n+ rhs: a rank `n+2` dimensional array of kernel weights.\nstrides: sequence of `n` integers, sets fractional stride.\n- padding: 'same', 'valid' will set as transpose of corresponding forward\n+ padding: 'SAME', 'VALID' will set as transpose of corresponding forward\nconv, or a sequence of `n` integer 2-tuples describing before-and-after\npadding for each `n` spatial dimension.\ndimension_numbers: tuple of dimension descriptors as in\nlax.conv_general_dilated. Defaults to tensorflow convention.\n+ transpose_kernel: if True flips spatial axes and swaps the input/output\n+ channel axes of the kernel. This makes the output of this function identical\n+ to the gradient-derived functions like keras.layers.Conv2DTranspose\n+ applied to the same kernel. For typical use in neural nets this is completely\n+ pointless and just makes input/output channel specification confusing.\nReturns:\n- Transposed N-d convolution, with padding following the conventions of the\n- corresponding keras and tensorflow conv-transpose operators.\n+ Transposed N-d convolution, with output padding following the conventions of\n+ keras.layers.Conv2DTranspose.\n\"\"\"\n- assert len(data.shape) == len(kernel.shape) and len(data.shape) > 2\n- ndims = len(data.shape)\n+ assert len(lhs.shape) == len(rhs.shape) and len(lhs.shape) > 2\n+ ndims = len(lhs.shape)\none = (1,) * (ndims - 2)\n# Set dimensional layout defaults if not specified.\nif dimension_numbers is None:\n@@ -1295,20 +1301,20 @@ def conv_transpose(data, kernel, strides, padding, dimension_numbers=None):\ndimension_numbers = ('NHWDC', 'HWDIO', 'NHWDC')\nelse:\nraise ValueError('No 4+ dimensional dimension_number defaults.')\n- dn = conv_dimension_numbers(data.shape, kernel.shape, dimension_numbers)\n- k_shape = onp.take(kernel.shape, dn.rhs_spec)\n+ dn = conv_dimension_numbers(lhs.shape, rhs.shape, dimension_numbers)\n+ k_shape = onp.take(rhs.shape, dn.rhs_spec)\nk_sdims = k_shape[2:]\n# Calculate correct output shape given padding and strides.\n- if padding.lower() in {'same', 'valid'}:\n+ if padding in {'SAME', 'VALID'}:\npads = [_conv_transpose_padding(k, s, padding)\nfor k,s in zip(k_sdims.tolist(), strides)]\nelse:\npads = padding\n- # transposed conv = flipped kernel plus LHS dilation\n- kernel_t = _flip_axes(kernel, onp.array(dn.rhs_spec)[2:])\n- # flip input/output channel axes\n- kernel_t = onp.swapaxes(kernel_t, dn.rhs_spec[0], dn.rhs_spec[1])\n- return conv_general_dilated(data, kernel_t, one, pads, strides, one, dn)\n+ if transpose_kernel:\n+ # flip spatial dims and swap input / output channel axes\n+ rhs = _flip_axes(rhs, onp.array(dn.rhs_spec)[2:])\n+ rhs = onp.swapaxes(rhs, dn.rhs_spec[0], dn.rhs_spec[1])\n+ return conv_general_dilated(lhs, rhs, one, pads, strides, one, dn)\ndef full_like(x, fill_value, dtype=None, shape=None):\n@@ -4385,6 +4391,24 @@ def conv_general_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\nreturn tuple(onp.take(out_trans, onp.argsort(out_perm)))\n+def conv_transpose_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\n+ dimension_numbers):\n+ lhs_perm, rhs_perm, out_perm = conv_general_permutations(dimension_numbers)\n+ lhs_trans = onp.take(lhs_shape, lhs_perm)\n+ rhs_trans = onp.take(rhs_shape, rhs_perm)\n+ if isinstance(padding, str):\n+ padding = [_conv_transpose_padding(k, s, padding)\n+ for k,s in zip(rhs_trans[2:], window_strides)]\n+ padding = list(map(onp.sum, padding))\n+ unpad_out_space = [(i-1) * s - k + 2\n+ for i, k, s in zip(lhs_trans[2:],\n+ rhs_trans[2:],\n+ window_strides)]\n+ out_space = onp.sum([unpad_out_space, padding], axis=0).tolist()\n+ out_trans = tuple((lhs_trans[0], rhs_trans[0]) + tuple(out_space))\n+ return tuple(onp.take(out_trans, onp.argsort(out_perm)))\n+\n+\ndef _check_shapelike(fun_name, arg_name, obj):\n\"\"\"Check that `obj` is a shape-like value (e.g. tuple of nonnegative ints).\"\"\"\nif not isinstance(obj, (tuple, list, onp.ndarray)):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -445,36 +445,12 @@ class LaxTest(jtu.JaxTestCase):\n# TODO(mattjj): test conv_general_dilated against numpy\n- @parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\":\n- \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\".format(\n- jtu.format_shape_dtype_string(lhs_shape, dtype),\n- jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding),\n- \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n- \"strides\": strides, \"padding\": padding, \"rng\": rng, 'dspec': dspec}\n- for lhs_shape, rhs_shape in [\n- ((b, 9, 10, i), (3, 3, i, j))\n- for b, i, j in itertools.product([2, 3], repeat=3)]\n- for dtype in [onp.float32]\n- for strides in [(1, 1), (1, 2), (2, 1), (2, 2), (3, 3)]\n- for padding in [\"VALID\", \"SAME\"]\n- for dspec in [('NHWC', 'HWIO', 'NHWC'),]\n- for rng in [jtu.rand_small()]))\n- def testConvTranspose(self, lhs_shape, rhs_shape, dtype, strides,\n- padding, dspec, rng):\n- def deconv_output_length(input_length, filter_size, padding, stride=0):\n- if padding.lower() == 'valid':\n- length = input_length * stride + max(filter_size - stride, 0)\n- elif padding.lower() == 'same':\n- length = input_length * stride\n- return length\n- def inv_permutation(p):\n- return [x[0] for x in sorted(enumerate(p), key=lambda x: x[1])]\n- def conv_transpose_via_grad(data, kernel, strides, padding,\n- dimension_numbers=dspec):\n+ @staticmethod\n+ def _conv_transpose_via_grad(data, kernel, strides, padding,\n+ dimension_numbers=None):\n+ \"\"\"Helper method: calculates conv tranpose via grad for testing.\"\"\"\nassert len(data.shape) == len(kernel.shape)\n- ndims = len(data.shape)\n- nspatial = ndims - 2\n+ nspatial = len(data.shape) - 2\none = (1,) * nspatial\ndn = lax.conv_dimension_numbers(data.shape, kernel.shape,\ndimension_numbers)\n@@ -482,28 +458,126 @@ class LaxTest(jtu.JaxTestCase):\nin_sdims = in_shape[2:]\nk_shape = onp.take(kernel.shape, dn.rhs_spec)\nk_sdims = k_shape[2:]\n- o_sdims = [deconv_output_length(in_sdims[i], k_sdims[i], padding,\n- stride=strides[i])\n+ if padding == 'VALID':\n+ o_sdims = [in_sdims[i]*strides[i] + max(k_sdims[i]-strides[i],0)\nfor i in range(nspatial)]\n+ elif padding == 'SAME':\n+ o_sdims = [in_sdims[i]*strides[i] for i in range(nspatial)]\no_shape = [in_shape[0], k_shape[1]] + o_sdims\n- o_layout = onp.take(onp.array(o_shape), inv_permutation(dn.out_spec))\n+ out_spec_inv = [x[0] for x in\n+ sorted(enumerate(dn.out_spec), key=lambda x: x[1])]\n+ o_layout = onp.take(onp.array(o_shape), out_spec_inv)\nplaceholder = onp.ones(o_layout, data.dtype)\nconv = lambda x: lax.conv_general_dilated(x, kernel, strides, padding,\none, one, dn)\n_, g = api.vjp(conv, placeholder)\nreturn g(data)[0]\n+ @staticmethod\n+ def _transpose_conv_kernel(data, kernel, dimension_numbers):\n+ dn = lax.conv_dimension_numbers(data.shape, kernel.shape,\n+ dimension_numbers)\n+ spatial_axes = onp.array(dn.rhs_spec)[2:]\n+ for axis in spatial_axes:\n+ kernel = onp.flip(kernel, axis)\n+ kernel = onp.swapaxes(kernel, dn.rhs_spec[0], dn.rhs_spec[1])\n+ return kernel\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\".format(\n+ jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"strides\": strides, \"padding\": padding, \"rng\": rng, 'dspec': dspec}\n+ for lhs_shape, rhs_shape in [\n+ ((b, 9, 10, i), (k, k, j, i)) # NB: i,j flipped in RHS for transpose\n+ for b, i, j, k in itertools.product([2,3],[2,3],[2,3],[3,4,5])]\n+ for dtype in [onp.float32]\n+ for strides in [(1, 1), (1, 2), (2, 1), (2, 2), (3, 3)]\n+ for padding in [\"VALID\", \"SAME\"]\n+ for dspec in [('NHWC', 'HWIO', 'NHWC'),]\n+ for rng in [jtu.rand_small()]))\n+ def testConvTranspose2DT(self, lhs_shape, rhs_shape, dtype, strides,\n+ padding, dspec, rng):\nargs_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n+ # NB: this test calculates conv_transpose performing identically to the\n+ # lhs-grad of conv.\ndef fun(lhs, rhs):\nreturn lax.conv_transpose(lhs, rhs, strides, padding,\n+ dimension_numbers=dspec,\n+ transpose_kernel=True)\n+\n+ def fun_via_grad(lhs, rhs):\n+ return self._conv_transpose_via_grad(lhs, rhs, strides, padding,\ndimension_numbers=dspec)\n+ # NB: below just checks for agreement, we're not calling numpy.\n+ self._CheckAgainstNumpy(fun, fun_via_grad, args_maker)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\".format(\n+ jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"strides\": strides, \"padding\": padding, \"rng\": rng, 'dspec': dspec}\n+ for lhs_shape, rhs_shape in [\n+ ((b, 9, 10, i), (k, k, i, j))\n+ for b, i, j, k in itertools.product([2,3],[2,3],[2,3],[3,4,5])]\n+ for dtype in [onp.float32]\n+ for strides in [(1, 1), (1, 2), (2, 1), (2, 2), (3, 3)]\n+ for padding in [\"VALID\", \"SAME\"]\n+ for dspec in [('NHWC', 'HWIO', 'NHWC'),]\n+ for rng in [jtu.rand_small()]))\n+ def testConvTranspose2D(self, lhs_shape, rhs_shape, dtype, strides,\n+ padding, dspec, rng):\n+ args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n+\n+ def fun(lhs, rhs):\n+ return lax.conv_transpose(lhs, rhs, strides, padding,\n+ dimension_numbers=dspec,\n+ transpose_kernel=False)\n+\n+ def fun_via_grad(lhs, rhs):\n+ rhs_t = self._transpose_conv_kernel(lhs, rhs, dimension_numbers=dspec)\n+ return self._conv_transpose_via_grad(lhs, rhs_t, strides, padding,\n+ dimension_numbers=dspec)\n+\n+ # NB: below just checks for agreement, we're not calling numpy.\n+ self._CheckAgainstNumpy(fun, fun_via_grad, args_maker)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_rhs_shape={}_strides={}_padding={}\".format(\n+ jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype), strides, padding),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"strides\": strides, \"padding\": padding, \"rng\": rng, 'dspec': dspec}\n+ for lhs_shape, rhs_shape in [\n+ ((b, 10, i), (k, i, j))\n+ for b, i, j, k in itertools.product([2,3],[2,3],[2,3],[3,4,5])]\n+ for dtype in [onp.float32]\n+ for strides in [(1,), (2,), (3,)]\n+ for padding in [\"VALID\", \"SAME\"]\n+ for dspec in [('NHC', 'HIO', 'NHC'),]\n+ for rng in [jtu.rand_small()]))\n+ def testConvTranspose1D(self, lhs_shape, rhs_shape, dtype, strides,\n+ padding, dspec, rng):\n+ args_maker = lambda: [rng(lhs_shape, dtype), rng(rhs_shape, dtype)]\n+\n+ def fun(lhs, rhs):\n+ return lax.conv_transpose(lhs, rhs, strides, padding,\n+ dimension_numbers=dspec,\n+ transpose_kernel=False)\n+\ndef fun_via_grad(lhs, rhs):\n- return conv_transpose_via_grad(lhs, rhs, strides, padding,\n+ rhs_t = self._transpose_conv_kernel(lhs, rhs, dimension_numbers=dspec)\n+ return self._conv_transpose_via_grad(lhs, rhs_t, strides, padding,\ndimension_numbers=dspec)\n- # self._CompileAndCheck(fun, args_maker, check_dtypes=True)\n+ # NB: below just checks for agreement, we're not calling numpy.\nself._CheckAgainstNumpy(fun, fun_via_grad, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/stax_test.py",
"new_path": "tests/stax_test.py",
"diff": "@@ -83,6 +83,39 @@ class StaxTest(jtu.JaxTestCase):\npadding=padding)\n_CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_channels={}_filter_shape={}_padding={}_strides={}_input_shape={}\"\n+ .format(channels, filter_shape, padding, strides, input_shape),\n+ \"channels\": channels, \"filter_shape\": filter_shape, \"padding\": padding,\n+ \"strides\": strides, \"input_shape\": input_shape}\n+ for channels in [2, 3]\n+ for filter_shape in [(1, 1), (2, 3), (3, 3)]\n+ for padding in [\"SAME\", \"VALID\"]\n+ for strides in [None, (2, 1), (2, 2)]\n+ for input_shape in [(2, 10, 11, 1)]))\n+ def testConvTransposeShape(self, channels, filter_shape, padding, strides,\n+ input_shape):\n+ init_fun, apply_fun = stax.ConvTranspose(channels, filter_shape,\n+ strides=strides, padding=padding)\n+ _CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_channels={}_filter_shape={}_padding={}_strides={}_input_shape={}\"\n+ .format(channels, filter_shape, padding, strides, input_shape),\n+ \"channels\": channels, \"filter_shape\": filter_shape, \"padding\": padding,\n+ \"strides\": strides, \"input_shape\": input_shape}\n+ for channels in [2, 3]\n+ for filter_shape in [(1,), (2,), (3,)]\n+ for padding in [\"SAME\", \"VALID\"]\n+ for strides in [None, (1,), (2,)]\n+ for input_shape in [(2, 10, 1)]))\n+ def testConv1DTransposeShape(self, channels, filter_shape, padding, strides,\n+ input_shape):\n+ init_fun, apply_fun = stax.Conv1DTranspose(channels, filter_shape,\n+ strides=strides, padding=padding)\n+ _CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_out_dim={}_input_shape={}\"\n.format(out_dim, input_shape),\n"
}
] | Python | Apache License 2.0 | google/jax | finish transposed convolution implementation and tests |
260,403 | 10.04.2019 00:57:02 | 25,200 | aee66b5a24d1cdf352a00925ae65e3ba92f5431f | comment to trigger travis rebuild | [
{
"change_type": "MODIFY",
"old_path": "tests/stax_test.py",
"new_path": "tests/stax_test.py",
"diff": "@@ -96,7 +96,7 @@ class StaxTest(jtu.JaxTestCase):\nfor input_shape in [(2, 10, 11, 1)]))\ndef testConvTransposeShape(self, channels, filter_shape, padding, strides,\ninput_shape):\n- init_fun, apply_fun = stax.ConvTranspose(channels, filter_shape,\n+ init_fun, apply_fun = stax.ConvTranspose(channels, filter_shape, # 2D\nstrides=strides, padding=padding)\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 | comment to trigger travis rebuild |
260,335 | 10.04.2019 22:17:54 | 25,200 | 2582598294daf38cc7b8b243b31bc3fe2427500f | remove assert that fails on python3 map objects | [
{
"change_type": "MODIFY",
"old_path": "jax/linear_util.py",
"new_path": "jax/linear_util.py",
"diff": "@@ -141,7 +141,6 @@ class WrappedFun(object):\nfor gen, gen_args, out_store in self.transforms:\ngen = gen(*(gen_args + tuple(args)), **kwargs)\nargs, kwargs = next(gen)\n- assert type(args) in (tuple, list) and type(kwargs) is dict\nstack.append((gen, out_store))\ndel gen\n"
}
] | Python | Apache License 2.0 | google/jax | remove assert that fails on python3 map objects |
260,335 | 11.04.2019 06:58:09 | 25,200 | de2a5f725d1f476e037496833ef8e9bb929c7aca | add warning, fix typo in kwargs test and bug | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -27,6 +27,7 @@ from __future__ import print_function\nimport itertools\nimport operator as op\nimport os\n+from warnings import warn\nimport numpy as onp\nfrom contextlib import contextmanager\n@@ -101,9 +102,17 @@ def jit(fun, static_argnums=()):\nif _jit_is_disabled or config.read('jax_disable_jit'):\nreturn fun(*args, **kwargs)\nif static_argnums and max(static_argnums) >= len(args):\n- msg = (\"jitted function has static_argnums={} but was called with only {}\"\n- \" positional arguments\")\n+ msg = (\"Jitted function has static_argnums={} but was called with only {}\"\n+ \" positional arguments.\")\nraise TypeError(msg.format(static_argnums, len(args)))\n+ if kwargs:\n+ # TODO(mattjj, dougalm): remove warning by May 1 2019\n+ msg = (\"Until recently jitted functions called with keyword arguments \"\n+ \"treated those arguments as if they were part of static_argnums, \"\n+ \"but now they are treated just like other arguments. If you were \"\n+ \"relying on the previous behavior, you may need to update your \"\n+ \"code to use static_argnums. See the jit docstring.\")\n+ warn(msg)\nf = lu.wrap_init(fun)\ndyn_argnums = [i for i in range(len(args)) if i not in static_argnums]\nf, dyn_args = _argnums_partial(f, dyn_argnums, args)\n@@ -757,11 +766,11 @@ def _argnums_partial(f, dyn_argnums, args):\nreturn _argnums_partial_(f, dyn_argnums, fixed_args), dyn_args\n@lu.transformation\n-def _argnums_partial_(dyn_argnums, fixed_args, *dyn_args):\n+def _argnums_partial_(dyn_argnums, fixed_args, *dyn_args, **kwargs):\nargs = [None if arg is None else arg.val for arg in fixed_args]\nfor i, arg in zip(dyn_argnums, dyn_args):\nargs[i] = arg\n- ans = yield args, {}\n+ ans = yield args, kwargs\nyield ans\ndef _check_args(args):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -93,12 +93,12 @@ class APITest(jtu.JaxTestCase):\nreturn 100*x + 10*y + z\nf1 = jit(f)\n- assert f(1, 2, 3) == 123\n+ assert f1(1, 2, 3) == 123\nassert len(side) == 1\n- assert f(1, 2, z=3) == 123\n+ assert f1(1, 2, z=3) == 123\n# assert len(side) == 1 # actually recompiles\n- f(1, 2, z=onp.zeros(3)) # doesn't crash\n+ f1(1, 2, z=onp.zeros(3)) # doesn't crash\ndef test_grad_of_jit(self):\nside = []\n"
}
] | Python | Apache License 2.0 | google/jax | add warning, fix typo in kwargs test and bug |
260,335 | 11.04.2019 08:07:32 | 25,200 | 6de4b573966e9c8d4496c3a439b779745a770c81 | improve kwargs test | [
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -92,13 +92,18 @@ class APITest(jtu.JaxTestCase):\nside.append(None)\nreturn 100*x + 10*y + z\n- f1 = jit(f)\n- assert f1(1, 2, 3) == 123\n+ f = jit(f)\n+ assert f(1, 2, 3) == 123\nassert len(side) == 1\n- assert f1(1, 2, z=3) == 123\n- # assert len(side) == 1 # actually recompiles\n+ assert f(1, 2, 3) == 123\n+ assert len(side) == 1\n+\n+ assert f(1, 2, z=3) == 123\n+ assert len(side) == 2 # actually recompiles from kwarg\n+ assert f(1, 2, z=3) == 123\n+ assert len(side) == 2 # but should still cache\n- f1(1, 2, z=onp.zeros(3)) # doesn't crash\n+ f(1, 2, z=onp.zeros(3)) # doesn't crash\ndef test_grad_of_jit(self):\nside = []\n"
}
] | Python | Apache License 2.0 | google/jax | improve kwargs test |
260,335 | 11.04.2019 21:26:06 | 25,200 | 7dab5e025ffb771e78733e6d51dd50ae1e6ce509 | remove the current lax.scan implementation
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/lax.py",
"new_path": "jax/lax.py",
"diff": "@@ -1000,94 +1000,6 @@ def _revise_cond_jaxpr(new_pval, old_pval, jaxpr, consts):\nreturn new_jaxpr, new_consts\n-def scan(f, a, bs):\n- \"\"\"Scans over the leading axis of an array.\n-\n- Arguments:\n- f: function with signature `a -> b -> a`\n- a: `a` value, or a pytree of `a` values.\n- bs: an array of `b` values, or a pytree of arrays of `b` values with the\n- same leading axis size.\n-\n- Returns:\n- An array of `a` values, or a pytree of arrays of `a` values, representing\n- the result of scanning the function `f` over the leading axis of `bs`, with\n- each application producing an `a` for the next and collecting the results.\n- \"\"\"\n- a, a_tree = pytree_to_flatjaxtuple(a)\n- bs, b_tree = pytree_to_flatjaxtuple(bs) # b_tree is the same as bs_tree\n- f, out_tree = pytree_fun_to_flatjaxtuple_fun(lu.wrap_init(f), (a_tree, b_tree))\n-\n- if not bs:\n- raise TypeError(\"bs argument to scan does not contain any arrays\")\n- if any([b.ndim == 0 for b in bs]):\n- msg = \"bs argument arrays must be rank >=1, got shapes {}.\"\n- raise TypeError(msg.format(\", \".format(str(b.shape) for b in bs)))\n- if len({b.shape[0] for b in bs}) != 1:\n- msg = \"arrays in bs must have equal most-major dimensions, got shapes {}.\"\n- raise TypeError(msg.format(\", \".format(str(b.shape) for b in bs)))\n-\n- a_pval = a_aval, _ = _abstractify(a)\n- bs_aval, _ = _abstractify(bs)\n- b_aval = core.AbstractTuple([ShapedArray(b.shape[1:], b.dtype) for b in bs_aval])\n- b_pval = pe.PartialVal((b_aval, core.unit))\n- jaxpr, pval_out, consts = pe.trace_to_jaxpr(f, (a_pval, b_pval))\n- aval_out, _ = pval_out\n-\n- if a_tree != out_tree():\n- msg = \"scanned function input and output must have identical structure\"\n- raise TypeError(msg)\n- if a_aval != aval_out:\n- msg = \"output shape mismatch for scanned function: {} vs {}\"\n- raise TypeError(msg.format(a_aval, aval_out))\n-\n- out = scan_p.bind(a, bs, core.pack(consts), aval_out=aval_out, jaxpr=jaxpr)\n- return tree_unflatten(out_tree(), out)\n-\n-def _scan_impl(a, bs, consts, aval_out, jaxpr):\n- length = tuple(bs)[0].shape[0]\n- state = [full((length,) + elt.shape, 0, _dtype(elt)) for elt in a]\n-\n- def body_fun(i, vals):\n- a, state = vals\n- assert len(a) == len(state)\n- b = [dynamic_index_in_dim(b, i, keepdims=False) for b in bs]\n- a_out = core.eval_jaxpr(jaxpr, consts, (), a, core.pack(b))\n- state_out = [dynamic_update_index_in_dim(s, a[None, ...], i, axis=0)\n- for a, s in zip(a_out, state)]\n- return a_out, state_out\n-\n- _, out = fori_loop(0, length, body_fun, (a, state))\n- return core.pack(out)\n-\n-# TODO(mattjj, phawkins): figure out what to do with consts_tangents, and the\n-# jaxtuple packing issues\n-def _scan_jvp(primals, tangents, aval_out, jaxpr):\n- a, bs, consts_primals = primals\n- a_dot, bs_dot, consts_tangents = tangents\n-\n- primal_out = scan_p.bind(a, bs, consts_primals,\n- aval_out=aval_out, jaxpr=jaxpr)\n-\n- def f_jvp(a_pt, b_pt):\n- a, a_dot = a_pt\n- b, b_dot = b_pt\n- f = lambda a, b, c: core.eval_jaxpr(jaxpr, c, (), a, b)\n- return api.jvp(f, (a, b, consts), (b, b_dot, consts_tangents))\n- tangent_out = scan(f_jvp, (a, a_dot), (b, b_dot))\n-\n- return primal_out, tangent_out\n-\n-def _scan_abstract_eval(a, bs, consts, aval_out, jaxpr):\n- return maybe_tracer_tuple_to_abstract_tuple(aval_out)\n-\n-scan_p = core.Primitive(\"scan\")\n-scan_p.def_impl(_scan_impl)\n-scan_p.def_abstract_eval(_scan_abstract_eval)\n-xla.translations[scan_p] = partial(xla.lower_fun, _scan_impl)\n-# ad.primitive_jvps[scan_p] = _scan_jvp # TODO(mattjj, phawkins)\n-\n-\ndef tie_in(x, y):\nreturn tie_in_p.bind(x, y)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1562,45 +1562,6 @@ class LaxTest(jtu.JaxTestCase):\n(0, 0), lambda x: (x[0], 0),\n(1, 1), lambda x: x)\n- def testScanAdd(self):\n- def f(x, y):\n- return x + y\n-\n- g = partial(lax.scan, f)\n- a = onp.array(7, onp.float32)\n- bs = onp.array([2, 4, -2, 6], onp.float32)\n- out = g(a, bs)\n- self.assertAllClose(out, onp.array([9, 13, 11, 17], onp.float32),\n- check_dtypes=True)\n-\n- # jtu.check_jvp(g, partial(api.jvp, g), (a, bs))\n-\n- def testScanMul(self):\n- def f(x, y):\n- return x * y\n-\n- g = partial(lax.scan, f)\n- a = onp.array(7, onp.float32)\n- bs = onp.array([2, 4, -2, 6], onp.float32)\n- out = g(a, bs)\n- self.assertAllClose(out, onp.array([14, 56, -112, -672], onp.float32),\n- check_dtypes=True)\n-\n- # jtu.check_jvp(g, partial(api.jvp, g), (a, bs))\n-\n- def testScanJit(self):\n- @api.jit\n- def f(x, yz):\n- y, z = yz\n- return 5. * lax.exp(lax.sin(x) * lax.cos(y)) + z\n-\n- a = onp.array(7, onp.float32)\n- bs = (onp.array([3., 1., -4., 1.], onp.float32),\n- onp.array([5., 9., -2., 6.], onp.float32))\n- ans = lax.scan(f, a, bs)\n- expected = onp.array([7.609, 17.445, 7.52596, 14.3389172], onp.float32)\n- self.assertAllClose(ans, expected, check_dtypes=True)\n-\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_lhs_shape={}_rhs_shape={}\"\n.format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n"
}
] | Python | Apache License 2.0 | google/jax | remove the current lax.scan implementation (#599)
fixes #598 |
260,335 | 12.04.2019 12:01:19 | 25,200 | 18671fa027214db32b0b60ee8dc39892e85a428d | add error checks so that isn't silent fail | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -271,7 +271,7 @@ def value_and_grad(fun, argnums=0, has_aux=False):\nans, vjp_py = vjp(f_partial, *dyn_args)\nelse:\nans, vjp_py, aux = vjp(f_partial, *dyn_args, has_aux=True)\n- _check_scalar(ans)\n+ _check_scalar_real(ans)\ng = vjp_py(onp.ones((), onp.result_type(ans)))\ng = g[0] if isinstance(argnums, int) else g\nif not has_aux:\n@@ -309,6 +309,7 @@ def jacfwd(fun, argnums=0):\nf_partial, dyn_args = _argnums_partial(f, argnums, args)\npushfwd = partial(jvp, f_partial, dyn_args)\ny, jac = vmap(pushfwd, out_axes=(None, -1))(_std_basis(dyn_args))\n+ _check_real(y)\nexample_args = dyn_args[0] if isinstance(argnums, int) else dyn_args\nreturn tree_map(partial(_unravel_array_into_pytree, example_args, -1), jac)\n@@ -338,6 +339,7 @@ def jacrev(fun, argnums=0):\ndef jacfun(*args, **kwargs):\nf = lu.wrap_init(fun, kwargs)\nf_partial, dyn_args = _argnums_partial(f, argnums, args)\n+ _check_real(dyn_args)\ny, pullback = vjp(f_partial, *dyn_args)\njac = vmap(pullback)(_std_basis(y))\njac = jac[0] if isinstance(argnums, int) else jac\n@@ -372,7 +374,13 @@ def _std_basis(pytree):\nleaves, _ = tree_flatten(pytree)\nndim = sum(map(onp.size, leaves))\n# TODO(mattjj): use a symbolic identity matrix here\n- return _unravel_array_into_pytree(pytree, 1, onp.eye(ndim))\n+ dtype = onp.result_type(*leaves)\n+ if not onp.issubdtype(dtype, onp.floating):\n+ msg = (\"Jacobian only defined for functions with floating input and output \"\n+ \"dtypes (i.e. dtypes that model real numbers), got {}.\")\n+ raise TypeError(msg.format(dtype)) # TODO(mattjj, dougalm): handle complex\n+ flat_basis = onp.eye(ndim, dtype=dtype)\n+ return _unravel_array_into_pytree(pytree, 1, flat_basis)\ndef _unravel_array_into_pytree(pytree, axis, arr):\nleaves, treedef = tree_flatten(pytree)\n@@ -779,14 +787,28 @@ def _check_args(args):\nraise TypeError(\"Argument '{}' of type {} is not a valid JAX type\"\n.format(arg, type(arg)))\n-def _check_scalar(x):\n+def _check_scalar_real(x):\nmsg = \"Gradient only defined for scalar-output functions. Output was: {}\".format\ntry:\naval = core.get_aval(x)\n- if not (isinstance(aval, ShapedArray) and aval.shape == ()):\n- raise TypeError(msg(x))\nexcept TypeError:\nraise TypeError(msg(x))\n+ else:\n+ if not (isinstance(aval, ShapedArray) and aval.shape == ()):\n+ raise TypeError(msg(x))\n+ if not onp.issubdtype(aval.dtype, onp.floating):\n+ msg2 = (\"Gradient only defined for functions with output dtypes that are \"\n+ \"sub-dtypes of `np.floating` (i.e. that model real scalars), but \"\n+ \"got {}. For holomorphic differentiation, apply `np.real` at the \"\n+ \"end of the function.\")\n+ raise TypeError(msg2.format(aval.dtype.name))\n+\n+def _check_real(x):\n+ aval = core.get_aval(x)\n+ if not onp.issubdtype(aval.dtype, onp.floating):\n+ msg = (\"Jacobian only defined for functions with floating input and output \"\n+ \"dtypes (i.e. dtypes that model real numbers), got {}.\")\n+ raise TypeError(msg.format(aval.dtype.name))\ndef custom_transforms(fun):\n@@ -814,8 +836,13 @@ def _elementwise_std_basis(pytree):\narity = len(leaves)\ndims = map(onp.size, leaves)\n# TODO(mattjj): use symbolic constants\n- basis_array = onp.stack(\n- [onp.concatenate([onp.ones(dims[j]) if i == j else onp.zeros(dims[j])\n+ dtype = onp.result_type(*leaves)\n+ if not onp.issubdtype(dtype, onp.floating):\n+ msg = (\"Jacobian only defined for functions with floating input and output \"\n+ \"dtypes (i.e. dtypes that model real numbers), got {}.\")\n+ raise TypeError(msg.format(dtype)) # TODO(mattjj, dougalm): handle complex\n+ basis_array = onp.stack([onp.concatenate(\n+ [onp.ones(dims[j], dtype) if i == j else onp.zeros(dims[j], dtype)\nfor j in range(arity)]) for i in range(arity)])\nreturn _unravel_array_into_pytree(pytree, 1, basis_array)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -427,6 +427,48 @@ class APITest(jtu.JaxTestCase):\njaxpr2 = api.make_jaxpr(f2_vjp)(y)\nassert len(jaxpr2.constvars) == 2\n+ def test_complex_grad_raises_error(self):\n+ self.assertRaises(TypeError, lambda: grad(lambda x: np.sin(x))(1 + 2j))\n+ grad(lambda x: np.real(np.sin(x)))(1 + 2j) # doesn't crash\n+\n+ # TODO(mattjj, dougalm): make this work if we can, and delete subsequent test\n+ # def test_complex_jacfwd(self):\n+ # # code based on https://github.com/google/jax/issues/603\n+ # zs = 0.5j * onp.arange(5) + onp.arange(5)\n+\n+ # def f(z):\n+ # return np.cos(np.linalg.norm(2 * z))\n+\n+ # ans = jacfwd(f)(zs)\n+ # expected = grad(f)(zs)\n+ # self.assertAllClose(ans, expected, check_dtypes=True)\n+\n+ def test_complex_jacfwd_raises_error(self):\n+ # code based on https://github.com/google/jax/issues/603\n+ zs = 0.5j * onp.arange(5) + onp.arange(5)\n+ def f(z):\n+ return np.cos(np.linalg.norm(2 * z))\n+ self.assertRaises(TypeError, lambda: jacfwd(f)(zs))\n+\n+ # TODO(mattjj, dougalm): make this work if we can, and delete subsequent test\n+ # def test_complex_jacrev(self):\n+ # # code based on https://github.com/google/jax/issues/603\n+ # zs = 0.5j * onp.arange(5) + onp.arange(5)\n+\n+ # def f(z):\n+ # return np.cos(np.linalg.norm(2 * z))\n+\n+ # ans = jacrev(f)(zs)\n+ # expected = grad(f)(zs)\n+ # self.assertAllClose(ans, expected, check_dtypes=True)\n+\n+ def test_complex_jacrev_raises_error(self):\n+ # code based on https://github.com/google/jax/issues/603\n+ zs = 0.5j * onp.arange(5) + onp.arange(5)\n+ def f(z):\n+ return np.cos(np.linalg.norm(2 * z))\n+ self.assertRaises(TypeError, lambda: jacrev(f)(zs))\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add error checks so that #603 isn't silent fail |
260,335 | 12.04.2019 12:24:58 | 25,200 | aaf50c9f681d99695c9dbbed2a1c2a49189db7e8 | add complex64 to sin/cos tests in lax | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1790,9 +1790,9 @@ LAX_GRAD_OPS = [\nGradTestSpec(lax.tanh, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\nGradTestSpec(lax.sin, nargs=1, order=2, rng=jtu.rand_default(),\n- dtypes=[onp.float64]),\n+ dtypes=[onp.float64, onp.complex64]),\nGradTestSpec(lax.cos, nargs=1, order=2, rng=jtu.rand_default(),\n- dtypes=[onp.float64]),\n+ dtypes=[onp.float64, onp.complex64]),\nGradTestSpec(lax.erf, nargs=1, order=2, rng=jtu.rand_small(),\ndtypes=[onp.float64]),\n"
}
] | Python | Apache License 2.0 | google/jax | add complex64 to sin/cos tests in lax |
260,335 | 12.04.2019 13:29:07 | 25,200 | 849ea87b33edd402158db0772ec1ed9709883aca | tree-map the real dtype check in api.py | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -309,7 +309,7 @@ def jacfwd(fun, argnums=0):\nf_partial, dyn_args = _argnums_partial(f, argnums, args)\npushfwd = partial(jvp, f_partial, dyn_args)\ny, jac = vmap(pushfwd, out_axes=(None, -1))(_std_basis(dyn_args))\n- _check_real(y)\n+ tree_map(_check_real, y)\nexample_args = dyn_args[0] if isinstance(argnums, int) else dyn_args\nreturn tree_map(partial(_unravel_array_into_pytree, example_args, -1), jac)\n@@ -339,7 +339,7 @@ def jacrev(fun, argnums=0):\ndef jacfun(*args, **kwargs):\nf = lu.wrap_init(fun, kwargs)\nf_partial, dyn_args = _argnums_partial(f, argnums, args)\n- _check_real(dyn_args)\n+ tree_map(_check_real, dyn_args)\ny, pullback = vjp(f_partial, *dyn_args)\njac = vmap(pullback)(_std_basis(y))\njac = jac[0] if isinstance(argnums, int) else jac\n"
}
] | Python | Apache License 2.0 | google/jax | tree-map the real dtype check in api.py |
260,335 | 13.04.2019 08:18:57 | 25,200 | f49ab50ec1de80e1f9966d90346654918ec25264 | expose lax._safe_mul again (c.f. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/__init__.py",
"new_path": "jax/lax/__init__.py",
"diff": "@@ -17,6 +17,6 @@ from .lax import *\nfrom .lax import (_reduce_sum, _reduce_max, _reduce_min, _reduce_or,\n_reduce_and, _reduce_window_sum, _reduce_window_max,\n_reduce_window_min, _reduce_window_prod, _float, _complex,\n- _input_dtype, _const, _eq_meet)\n+ _input_dtype, _const, _eq_meet, _safe_mul)\nfrom .lax_control_flow import *\nfrom .lax_parallel import *\n"
}
] | Python | Apache License 2.0 | google/jax | expose lax._safe_mul again (c.f. #608) |
260,407 | 13.04.2019 18:53:59 | -7,200 | d7f623ca9d2df81ac6bd79c8ea72529634405f29 | Added np.array_equal
Added test for np.isrealobj, added np.array_equal | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1238,6 +1238,17 @@ def ones(shape, dtype=onp.dtype(\"float64\")):\nreturn lax.full(shape, 1, dtype)\n+@_wraps(onp.array_equal)\n+def array_equal(a1, a2):\n+ try:\n+ a1, a2 = asarray(a1), asarray(a2)\n+ except Exception:\n+ return False\n+ if a1.shape != a2.shape:\n+ return False\n+ return asarray(a1==a2).all()\n+\n+\n# We can't create uninitialized arrays in XLA; use zeros for empty.\nempty_like = zeros_like\nempty = zeros\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -94,6 +94,7 @@ JAX_ONE_TO_ONE_OP_RECORDS = [\nop_record(\"multiply\", 2, number_dtypes, all_shapes, jtu.rand_default(), [\"rev\"]),\nop_record(\"negative\", 1, number_dtypes, all_shapes, jtu.rand_default(), [\"rev\"]),\nop_record(\"not_equal\", 2, number_dtypes, all_shapes, jtu.rand_some_equal(), [\"rev\"]),\n+ op_record(\"array_equal\", 2, number_dtypes, all_shapes, jtu.rand_some_equal(), [\"rev\"]),\nop_record(\"reciprocal\", 1, inexact_dtypes, all_shapes, jtu.rand_default(), []),\nop_record(\"subtract\", 2, number_dtypes, all_shapes, jtu.rand_default(), [\"rev\"]),\nop_record(\"sin\", 1, number_dtypes, all_shapes, jtu.rand_default(), [\"rev\"]),\n"
}
] | Python | Apache License 2.0 | google/jax | Added np.array_equal (#609)
Added test for np.isrealobj, added np.array_equal |
260,335 | 15.04.2019 07:07:58 | 25,200 | 3a633dbdb4d1e3fd1f53fd813808972ca86bac37 | mention lack of windows support in readme | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -91,9 +91,13 @@ And for a deeper dive into JAX:\n- [MAML Tutorial with JAX](https://colab.research.google.com/github/google/jax/blob/master/notebooks/maml.ipynb).\n## Installation\n-JAX is written in pure Python, but it depends on XLA, which needs to be\n-compiled and installed as the `jaxlib` package. Use the following instructions\n-to build JAX from source or install a binary package with pip.\n+JAX is written in pure Python, but it depends on XLA, which needs to be compiled\n+and installed as the `jaxlib` package. Use the following instructions to build\n+JAX from source or install a binary package with pip.\n+\n+We support installing or building `jaxlib` on Linux and macOS platforms, but not\n+Windows. We're not currently working on Windows support, but contributions are\n+welcome (see #438).\n### Building JAX from source\nFirst, obtain the JAX source code, and make sure `scipy` is installed.\n"
}
] | Python | Apache License 2.0 | google/jax | mention lack of windows support in readme (#612) |
260,335 | 15.04.2019 07:45:10 | 25,200 | aa5b036d6d69f10ce88d8745287c834054980d13 | misc python performance improvements | [
{
"change_type": "MODIFY",
"old_path": "jax/abstract_arrays.py",
"new_path": "jax/abstract_arrays.py",
"diff": "@@ -44,13 +44,16 @@ class UnshapedArray(core.AbstractValue):\narray_abstraction_level = 3\ndef __init__(self, dtype):\n- self.dtype = dtype\n+ self.dtype = onp.dtype(xla_bridge.canonicalize_dtype(dtype))\ndef __eq__(self, other):\nreturn type(self) is type(other) and self.dtype == other.dtype\ndef __hash__(self):\n- return hash(str(self.dtype))\n+ # can use hash(self.dtype) and rely on the fact that numpy reuses base dtype\n+ # objects, e.g. `onp.zeros(3).dtype is onp.zeros(4).dtype`, or we can use\n+ # the unique character code via hash(self.dtype.char)\n+ return hash(self.dtype)\ndef __repr__(self):\nreturn '{}({})'.format(self.__class__.__name__, self.str_short())\n@@ -74,7 +77,7 @@ class UnshapedArray(core.AbstractValue):\nraise TypeError(other)\ndef str_short(self):\n- return onp.dtype(self.dtype).name\n+ return self.dtype.name\nclass ShapedArray(UnshapedArray):\n@@ -93,7 +96,10 @@ class ShapedArray(UnshapedArray):\nand self.dtype == other.dtype and self.shape == other.shape)\ndef __hash__(self):\n- return hash((self.shape, str(self.dtype)))\n+ # can use hash(self.dtype) and rely on the fact that numpy reuses base dtype\n+ # objects, e.g. `onp.zeros(3).dtype is onp.zeros(4).dtype`, or we can use\n+ # the unique character code via hash(self.dtype.char)\n+ return hash((self.shape, self.dtype))\ndef at_least_vspace(self):\nreturn self\n@@ -107,9 +113,8 @@ class ShapedArray(UnshapedArray):\nraise TypeError(other)\ndef str_short(self):\n- dtypestr = onp.dtype(self.dtype).name\nshapestr = ','.join(map(str, self.shape))\n- return '{}[{}]'.format(dtypestr, shapestr)\n+ return '{}[{}]'.format(self.dtype.name, shapestr)\ndef __len__(self):\ntry:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -28,7 +28,7 @@ from .. import ad_util\nfrom .. import tree_util\nfrom .. import linear_util as lu\nfrom ..abstract_arrays import ConcreteArray, ShapedArray\n-from ..util import partial, unzip2, concatenate, safe_map, prod, memoize_unary\n+from ..util import partial, unzip2, concatenate, prod, memoize_unary\nfrom ..lib import xla_bridge as xb\nfrom .xla import (xla_shape, xla_destructure, translation_rule,\nxla_shape_to_result_shape, jaxpr_computation)\n@@ -39,8 +39,6 @@ from . import parallel\nfrom . import xla\nfrom . import ad\n-map = safe_map\n-\n### util\n@@ -220,14 +218,14 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nenv = {}\nwrite(core.unitvar, c.Tuple())\nif const_vals:\n- map(write, jaxpr.constvars, map(c.Constant, const_vals))\n- map(write, jaxpr.freevars, map(c.ParameterWithShape, freevar_shapes))\n+ _map(write, jaxpr.constvars, map(c.Constant, const_vals))\n+ _map(write, jaxpr.freevars, map(c.ParameterWithShape, freevar_shapes))\nelse:\nall_freevars = it.chain(jaxpr.constvars, jaxpr.freevars)\n- map(write, all_freevars, map(c.ParameterWithShape, freevar_shapes))\n- map(write, jaxpr.invars, map(c.ParameterWithShape, arg_shapes))\n+ _map(write, all_freevars, map(c.ParameterWithShape, freevar_shapes))\n+ _map(write, jaxpr.invars, map(c.ParameterWithShape, arg_shapes))\nfor eqn in jaxpr.eqns:\n- in_nodes = map(read, eqn.invars)\n+ in_nodes = tuple(map(read, eqn.invars))\nif eqn.primitive in parallel_translation_rules:\nname = eqn.params['axis_name']\nparams = {k: eqn.params[k] for k in eqn.params if k != 'axis_name'}\n@@ -237,23 +235,21 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nif eqn.primitive is xla_pmap_p:\nname, size = eqn.params['axis_name'], eqn.params['axis_size']\nnew_env = axis_env_extend(name, size)\n- in_shards = map(partial(xla_shard, c, new_env.sizes), in_nodes)\n- in_shapes = map(c.GetShape, in_shards)\n+ in_shards = tuple(map(partial(xla_shard, c, new_env.sizes), in_nodes))\n(subjaxpr, const_bindings, freevar_bindings), = eqn.bound_subjaxprs\nsubc = replicated_comp(\nsubjaxpr, new_env, (),\n- map(c.GetShape, map(read, const_bindings + freevar_bindings)),\n- *in_shapes)\n+ tuple(map(c.GetShape, map(read, const_bindings + freevar_bindings))),\n+ *map(c.GetShape, in_shards))\nsubfun = (subc, tuple(map(read, const_bindings + freevar_bindings)))\nsharded_result = xla.xla_call_translation_rule(c, subfun, *in_shards)\nans = xla_unshard(c, axis_groups(new_env, name), sharded_result)\nelse:\n- in_shapes = map(c.GetShape, in_nodes)\nsubcs = [\njaxpr_computation(\nsubjaxpr, (),\n- map(c.GetShape, map(read, const_bindings + freevar_bindings)),\n- *in_shapes)\n+ tuple(map(c.GetShape, map(read, const_bindings + freevar_bindings))),\n+ *map(c.GetShape, in_nodes))\nfor subjaxpr, const_bindings, freevar_bindings in eqn.bound_subjaxprs]\nsubfuns = [(subc, tuple(map(read, const_bindings + freevar_bindings)))\nfor subc, (_, const_bindings, freevar_bindings)\n@@ -263,9 +259,12 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\nans = translation_rule(eqn.primitive)(c, *in_nodes, **eqn.params)\nout_nodes = xla_destructure(c, ans) if eqn.destructure else [ans]\n- map(write, eqn.outvars, out_nodes)\n+ _map(write, eqn.outvars, out_nodes)\nreturn c.Build(read(jaxpr.outvar))\n+def _map(f, *xs):\n+ return tuple(map(f, *xs))\n+\nclass ShardedDeviceArray(xla.DeviceArray):\n__slots__ = [\"device_buffers\"]\n@@ -348,7 +347,7 @@ def execute_replicated(compiled, pval, axis_size, nrep, handle_in, handle_out,\nif out_tree is xla.leaf:\nreturn unshard_output(axis_size, replica_results)\nelse:\n- return map(partial(unshard_output, axis_size), zip(*replica_results))\n+ return tuple(map(partial(unshard_output, axis_size), zip(*replica_results)))\nxla_pmap_p = core.Primitive('xla_pmap')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -46,8 +46,6 @@ flags.DEFINE_bool('jax_debug_nans',\nstrtobool(os.getenv('JAX_DEBUG_NANS', \"False\")),\n'Add nan checks to every operation.')\n-map = safe_map\n-\ndef apply_primitive(prim, *args, **kwargs):\nabstract_args = map(abstractify, args)\ncompiled_fun = xla_primitive_callable(prim, *abstract_args, **kwargs)\n@@ -55,7 +53,7 @@ def apply_primitive(prim, *args, **kwargs):\n@memoize\ndef xla_primitive_callable(prim, *abstract_args, **kwargs):\n- shapes = map(xla_shape, abstract_args)\n+ shapes = tuple(map(xla_shape, abstract_args))\nbuilt_c = primitive_computation(prim, *shapes, **kwargs)\nresult_shape = xla_shape_to_result_shape(built_c.GetReturnValueShape())\nhandle_result = result_handler(result_shape)\n@@ -202,29 +200,31 @@ def jaxpr_computation(jaxpr, const_vals, freevar_shapes, *arg_shapes):\nconsts_env = dict(zip(jaxpr.constvars, const_vals))\nwrite(core.unitvar, c.Tuple())\nif const_vals:\n- map(write, jaxpr.constvars, map(c.Constant, const_vals))\n- map(write, jaxpr.freevars, map(c.ParameterWithShape, freevar_shapes))\n+ _map(write, jaxpr.constvars, map(c.Constant, const_vals))\n+ _map(write, jaxpr.freevars, map(c.ParameterWithShape, freevar_shapes))\nelse:\nall_freevars = it.chain(jaxpr.constvars, jaxpr.freevars)\n- map(write, all_freevars, map(c.ParameterWithShape, freevar_shapes))\n- map(write, jaxpr.invars, map(c.ParameterWithShape, arg_shapes))\n+ _map(write, all_freevars, map(c.ParameterWithShape, freevar_shapes))\n+ _map(write, jaxpr.invars, map(c.ParameterWithShape, arg_shapes))\nfor eqn in jaxpr.eqns:\n- in_nodes = map(read, eqn.invars)\n- in_shapes = map(c.GetShape, in_nodes)\n+ in_nodes = list(map(read, eqn.invars))\nsubcs = [\njaxpr_computation(\nsubjaxpr, (),\n- map(c.GetShape, map(read, const_bindings + freevar_bindings)),\n- *in_shapes)\n+ tuple(map(c.GetShape, map(read, const_bindings + freevar_bindings))),\n+ *map(c.GetShape, in_nodes))\nfor subjaxpr, const_bindings, freevar_bindings in eqn.bound_subjaxprs]\nsubfuns = [(subc, tuple(map(read, const_bindings + freevar_bindings)))\nfor subc, (_, const_bindings, freevar_bindings)\nin zip(subcs, eqn.bound_subjaxprs)]\nans = translation_rule(eqn.primitive)(c, *(subfuns + in_nodes), **eqn.params)\nout_nodes = xla_destructure(c, ans) if eqn.destructure else [ans]\n- map(write, eqn.outvars, out_nodes)\n+ _map(write, eqn.outvars, out_nodes)\nreturn c.Build(read(jaxpr.outvar))\n+def _map(f, *xs):\n+ return tuple(map(f, *xs))\n+\ndef xla_destructure(c, ans):\nnum_elements = len(c.GetShape(ans).tuple_shapes())\nreturn [c.GetTupleElement(ans, i) for i in range(num_elements)]\n@@ -244,7 +244,7 @@ def translation_rule(p):\ndef lower_fun(fun, c, *xla_args, **params):\n- xla_shapes = map(c.GetShape, xla_args)\n+ xla_shapes = tuple(map(c.GetShape, xla_args))\navals = map(aval_from_xla_shape, xla_shapes)\npvals = [pe.PartialVal((a, core.unit)) for a in avals]\njaxpr, pvout, consts = pe.trace_unwrapped_to_jaxpr(fun, pvals, **params)\n@@ -305,7 +305,7 @@ def abstractify(x):\npytype_aval_mappings = {}\ndef abstractify_tuple(tup):\n- return AbstractTuple(tuple(map(abstractify, tup)))\n+ return AbstractTuple(map(abstractify, tup))\npytype_aval_mappings[JaxTuple] = abstractify_tuple\npytype_aval_mappings[AbstractTuple] = abstractify_tuple\n@@ -466,8 +466,11 @@ def flatten_fun(in_trees, *flat_args):\ndef tree_flatten(maybe_tree):\naval = core.get_aval(maybe_tree)\n+ return _tree_flatten(aval, maybe_tree)\n+\n+def _tree_flatten(aval, maybe_tree):\nif type(aval) is AbstractTuple:\n- flat_children, child_specs = unzip2(map(tree_flatten, maybe_tree))\n+ flat_children, child_specs = unzip2(map(_tree_flatten, aval, maybe_tree))\nreturn it.chain.from_iterable(flat_children), JTupleTreeDef(child_specs)\nelif core.skip_checks or valid_jaxtype(maybe_tree):\nreturn [maybe_tree], leaf\n"
}
] | Python | Apache License 2.0 | google/jax | misc python performance improvements |
260,335 | 15.04.2019 09:14:43 | 25,200 | c5a381ed4d5db7f5ae1abf2bec62837283113e01 | misc test skips | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_indexing_test.py",
"new_path": "tests/lax_numpy_indexing_test.py",
"diff": "@@ -730,6 +730,10 @@ class IndexedUpdateTest(jtu.JaxTestCase):\n# TODO(b/127315062): this case causes an XLA crash on CPU/TPU. Reenable\n# when fixed.\nraise unittest.SkipTest(\"Test case crashes on CPU\")\n+ if (FLAGS.jax_test_dut == \"tpu\" and isinstance(indexer, slice)\n+ and onp.zeros(shape)[indexer].size == 0):\n+ # TODO(phawkins): this case causes an XLA crash on TPU. Reenable when fixed.\n+ raise unittest.SkipTest(\"Test case crashes on TPU\")\njax_op = ops.index_update if op == UpdateOps.UPDATE else ops.index_add\njax_fn = lambda x, y: jax_op(x, indexer, y)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -190,6 +190,7 @@ class LaxRandomTest(jtu.JaxTestCase):\n\"a\": a, \"dtype\": onp.dtype(dtype).name}\nfor a in [0.1, 1., 10.]\nfor dtype in [onp.float32, onp.float64]))\n+ @jtu.skip_on_devices(\"tpu\") # TODO(phawkins): re-enable\ndef testGamma(self, a, dtype):\nkey = random.PRNGKey(0)\nrand = lambda key, a: random.gamma(key, a, (10000,), dtype)\n@@ -201,6 +202,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor samples in [uncompiled_samples, compiled_samples]:\nself._CheckKolmogorovSmirnovCDF(samples, scipy.stats.gamma(a).cdf)\n+ @jtu.skip_on_devices(\"tpu\") # TODO(phawkins): re-enable\ndef testGammaShape(self):\nkey = random.PRNGKey(0)\nx = random.gamma(key, onp.array([0.2, 0.3]), shape=(3, 2))\n"
}
] | Python | Apache License 2.0 | google/jax | misc test skips |
260,335 | 15.04.2019 12:06:21 | 25,200 | 782d6f3b6166d7ebae401b442497bb0877be3d55 | fix tuple/list typo | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -225,7 +225,7 @@ def replicated_comp(jaxpr, ax_env, const_vals, freevar_shapes, *arg_shapes):\n_map(write, all_freevars, map(c.ParameterWithShape, freevar_shapes))\n_map(write, jaxpr.invars, map(c.ParameterWithShape, arg_shapes))\nfor eqn in jaxpr.eqns:\n- in_nodes = tuple(map(read, eqn.invars))\n+ in_nodes = list(map(read, eqn.invars))\nif eqn.primitive in parallel_translation_rules:\nname = eqn.params['axis_name']\nparams = {k: eqn.params[k] for k in eqn.params if k != 'axis_name'}\n"
}
] | Python | Apache License 2.0 | google/jax | fix tuple/list typo |
260,656 | 17.04.2019 18:51:12 | 14,400 | 60539a2612e2c648d984076df8282e8283e4f33c | Implement jvp for atan2 | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1441,6 +1441,7 @@ cos_p = standard_unop(_float | _complex, 'cos')\nad.defjvp(cos_p, lambda g, x: neg(mul(g, sin(x))))\natan2_p = standard_binop([_float, _float], 'atan2')\n+ad.defjvp(atan2_p, lambda g, x, y: -mul(g,y)/(mul(x,x)+mul(y,y)), lambda g, x, y: mul(g,x)/(mul(x,x)+mul(y,y)))\nlgamma_p = standard_unop(_float, 'lgamma')\nad.defjvp(lgamma_p, lambda g, x: mul(g, digamma(x)))\n"
}
] | Python | Apache License 2.0 | google/jax | Implement jvp for atan2 |
260,656 | 17.04.2019 19:53:06 | 14,400 | 36e5ec21898b68de789dee4c858b91e80ac23ce9 | Add jax tests and fix style. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1441,7 +1441,9 @@ cos_p = standard_unop(_float | _complex, 'cos')\nad.defjvp(cos_p, lambda g, x: neg(mul(g, sin(x))))\natan2_p = standard_binop([_float, _float], 'atan2')\n-ad.defjvp(atan2_p, lambda g, x, y: -mul(g,y)/(mul(x,x)+mul(y,y)), lambda g, x, y: mul(g,x)/(mul(x,x)+mul(y,y)))\n+ad.defjvp(atan2_p,\n+ lambda g, x, y: -(g*y)/(square(x)+square(y)),\n+ lambda g, x, y: (g*x)/(square(x)+square(y)))\nlgamma_p = standard_unop(_float, 'lgamma')\nad.defjvp(lgamma_p, lambda g, x: mul(g, digamma(x)))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1419,6 +1419,11 @@ LAX_GRAD_OPS = [\ndtypes=[onp.float64, onp.complex64]),\nGradTestSpec(lax.cos, nargs=1, order=2, rng=jtu.rand_default(),\ndtypes=[onp.float64, onp.complex64]),\n+ # TODO(proteneer): atan2 input is already a representation of a\n+ # complex number. Need to think harder about what this even means\n+ # if each input itself is a complex number.\n+ GradTestSpec(lax.atan2, nargs=2, order=2, rng=jtu.rand_default(),\n+ dtypes=[onp.float64]),\nGradTestSpec(lax.erf, nargs=1, order=2, rng=jtu.rand_small(),\ndtypes=[onp.float64]),\n"
}
] | Python | Apache License 2.0 | google/jax | Add jax tests and fix style. |
260,656 | 17.04.2019 19:57:42 | 14,400 | dfd3d9335020011adc409f8ef5f4d2a5968c1439 | Fix bug in order of y,x in grad of atan2. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1442,8 +1442,8 @@ ad.defjvp(cos_p, lambda g, x: neg(mul(g, sin(x))))\natan2_p = standard_binop([_float, _float], 'atan2')\nad.defjvp(atan2_p,\n- lambda g, x, y: -(g*y)/(square(x)+square(y)),\n- lambda g, x, y: (g*x)/(square(x)+square(y)))\n+ lambda g, x, y: g * y / (square(x) + square(y)),\n+ lambda g, x, y: g * -x / (square(x) + square(y)))\nlgamma_p = standard_unop(_float, 'lgamma')\nad.defjvp(lgamma_p, lambda g, x: mul(g, digamma(x)))\n"
}
] | Python | Apache License 2.0 | google/jax | Fix bug in order of y,x in grad of atan2. |
260,656 | 17.04.2019 20:54:01 | 14,400 | bbf0d5c55eeab3029f86844d1775e2a586e86590 | Add brcast to deal with inconsistent shapes. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1442,8 +1442,8 @@ ad.defjvp(cos_p, lambda g, x: neg(mul(g, sin(x))))\natan2_p = standard_binop([_float, _float], 'atan2')\nad.defjvp(atan2_p,\n- lambda g, x, y: g * y / (square(x) + square(y)),\n- lambda g, x, y: g * -x / (square(x) + square(y)))\n+ lambda g, x, y: _brcast(g, y) * (y / (square(x) + square(y))),\n+ lambda g, x, y: _brcast(g, x) * -x / (square(x) + square(y)))\nlgamma_p = standard_unop(_float, 'lgamma')\nad.defjvp(lgamma_p, lambda g, x: mul(g, digamma(x)))\n"
}
] | Python | Apache License 2.0 | google/jax | Add brcast to deal with inconsistent shapes. |
260,389 | 20.04.2019 17:06:35 | 25,200 | b940245730063ed16b65cdc0ac747f08c70f3a6c | add VJP for `lax._select_and_scatter_add` (2nd-order grad of maxpool) | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3252,13 +3252,30 @@ def _select_and_scatter_add_translation(\nreturn c.SelectAndScatter(operand, select, window_dimensions, window_strides,\npadding, source, zero, scatter)\n+def _select_and_scatter_add_jvp(\n+ primals, tangents, select_prim, window_dimensions, window_strides,\n+ padding):\n+ source, operand = primals\n+ g_source, g_operand = tangents\n+ val_out = _select_and_scatter_add(\n+ source, operand, select_prim, window_dimensions, window_strides,\n+ padding)\n+ del g_operand\n+ if g_source is ad_util.zero:\n+ tangent_out = ad_util.zero\n+ else:\n+ tangent_out = _select_and_scatter_add(\n+ g_source, operand, select_prim, window_dimensions,\n+ window_strides, padding)\n+ return val_out, tangent_out\n+\ndef _select_and_scatter_add_transpose(\nt, source, operand, select_prim, window_dimensions, window_strides,\npadding):\nassert source is None and operand is not None\n- result = _select_and_gather_add(t, operand, select_prim, window_dimensions,\n+ source_t = _select_and_gather_add(t, operand, select_prim, window_dimensions,\nwindow_strides, padding)\n- return [result, None]\n+ return [source_t, None]\ndef _select_and_scatter_add_batch_rule(batched_args, batch_dims, **kwargs):\nsource, operand = batched_args\n@@ -3295,6 +3312,7 @@ select_and_scatter_add_p = standard_primitive(\n_select_and_scatter_add_translation)\nad.primitive_transposes[select_and_scatter_add_p] = \\\n_select_and_scatter_add_transpose\n+ad.primitive_jvps[select_and_scatter_add_p] = _select_and_scatter_add_jvp\nbatching.primitive_batchers[select_and_scatter_add_p] = \\\n_select_and_scatter_add_batch_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1945,9 +1945,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nself.assertEqual(onp.unique(operand).size, operand.size,\nmsg=\"test requires operand elements to be unique.\")\njtu.check_vjp(fun, partial(api.vjp, fun), (operand,), 1e-2, 1e-2, 1e-2)\n-\n- # TODO(phawkins): enable both gradients after a jaxlib update.\n- # check_grads(fun, (operand,), 1, 1e-2, 1e-2, 1e-2)\n+ check_grads(fun, (operand,), 2, 1e-2, 1e-2, 1e-2)\n# pylint: enable=cell-var-from-loop\n# TODO(b/205052657): enable more tests when supported\n"
}
] | Python | Apache License 2.0 | google/jax | add VJP for `lax._select_and_scatter_add` (2nd-order grad of maxpool) |
260,389 | 20.04.2019 17:06:56 | 25,200 | 55d74d862494a8c0a19f252088591bf14a738e83 | add VJP for `lax._select_and_gather_add` (3rd-order grad of maxpool) | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3393,6 +3393,23 @@ def _select_and_gather_add_translation(\nout = c.ConvertElementType(out, uint_etype)\nreturn c.BitcastConvertType(out, etype)\n+def _select_and_gather_add_jvp(\n+ primals, tangents, select_prim, window_dimensions, window_strides,\n+ padding):\n+ source, operand = primals\n+ g_source, g_operand = tangents\n+ val_out = _select_and_gather_add(\n+ source, operand, select_prim, window_dimensions, window_strides,\n+ padding)\n+ del g_operand\n+ if g_source is ad_util.zero:\n+ tangent_out = ad_util.zero\n+ else:\n+ tangent_out = _select_and_gather_add(\n+ g_source, operand, select_prim, window_dimensions,\n+ window_strides, padding)\n+ return val_out, tangent_out\n+\ndef _select_and_gather_add_transpose(\nt, tangents, operand, select_prim, window_dimensions, window_strides,\npadding):\n@@ -3404,6 +3421,7 @@ def _select_and_gather_add_transpose(\nselect_and_gather_add_p = standard_primitive(\n_select_and_gather_add_shape_rule, _input_dtype, 'select_and_gather_add',\n_select_and_gather_add_translation)\n+ad.primitive_jvps[select_and_gather_add_p] = _select_and_gather_add_jvp\nad.primitive_transposes[select_and_gather_add_p] = \\\n_select_and_gather_add_transpose\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1945,7 +1945,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nself.assertEqual(onp.unique(operand).size, operand.size,\nmsg=\"test requires operand elements to be unique.\")\njtu.check_vjp(fun, partial(api.vjp, fun), (operand,), 1e-2, 1e-2, 1e-2)\n- check_grads(fun, (operand,), 2, 1e-2, 1e-2, 1e-2)\n+ check_grads(fun, (operand,), 3, 1e-2, 1e-2, 1e-2)\n# pylint: enable=cell-var-from-loop\n# TODO(b/205052657): enable more tests when supported\n"
}
] | Python | Apache License 2.0 | google/jax | add VJP for `lax._select_and_gather_add` (3rd-order grad of maxpool) |
260,314 | 21.04.2019 16:25:20 | 14,400 | e5ccf0534dd84e313a74f07e2ebac679bb0527e0 | add beta/t random samplers | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -405,6 +405,35 @@ def _bernoulli(key, mean, shape):\nreturn lax.lt(uniform(key, shape), mean)\n+def beta(key, a, b, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Bernoulli random values with given shape and mean.\n+\n+ Args:\n+ key: a PRNGKey used as the random key.\n+ a: an array-like broadcastable to `shape` and used as the shape parameter\n+ alpha of the random variables.\n+ b: an array-like broadcastable to `shape` and used as the shape parameter\n+ beta of the random variables.\n+ shape: optional, a tuple of nonnegative integers representing the shape\n+ (default scalar).\n+ dtype: optional, a float dtype for the returned values (default float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ return _beta(key, a, b, shape, dtype)\n+\n+@partial(jit, static_argnums=(3, 4))\n+def _beta(key, a, b, shape, dtype):\n+ a = lax.convert_element_type(a, dtype)\n+ b = lax.convert_element_type(b, dtype)\n+ shape = shape or lax.broadcast_shapes(np.shape(a), np.shape(b))\n+ key_a, key_b = random.split(key)\n+ gamma_a = gamma(key_a, a, shape, dtype)\n+ gamma_b = gamma(key_b, b, shape, dtype)\n+ return gamma_a / (gamma_a + gamma_b)\n+\n+\ndef cauchy(key, shape=(), dtype=onp.float32):\n\"\"\"Sample Cauchy random values with given shape and float dtype.\n@@ -525,6 +554,25 @@ def _gamma(key, a, shape=(), dtype=onp.float32):\nreturn np.reshape(samples, shape)\n+def gumbel(key, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Gumbel 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 float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ return _gumbel(key, shape, dtype)\n+\n+@partial(jit, static_argnums=(1, 2))\n+def _gumbel(key, shape, dtype):\n+ return -np.log(-np.log(uniform(key, shape, dtype)))\n+\n+\ndef laplace(key, shape=(), dtype=onp.float32):\n\"\"\"Sample Laplace random values with given shape and float dtype.\n@@ -571,11 +619,13 @@ def _pareto(key, b, shape, dtype):\nreturn lax.exp(lax.div(e, b))\n-def gumbel(key, shape=(), dtype=onp.float32):\n- \"\"\"Sample Gumbel random values with given shape and float dtype.\n+def t(key, df, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Student's t random values with given shape and float dtype.\nArgs:\nkey: a PRNGKey used as the random key.\n+ df: an array-like broadcastable to `shape` and used as the shape parameter\n+ of the random variables.\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\ndtype: optional, a float dtype for the returned values (default float32).\n@@ -583,8 +633,15 @@ def gumbel(key, shape=(), dtype=onp.float32):\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n- return _gumbel(key, shape, dtype)\n+ return _t(key, df, shape, dtype)\n-@partial(jit, static_argnums=(1, 2))\n-def _gumbel(key, shape, dtype):\n- return -np.log(-np.log(uniform(key, shape, dtype)))\n+@partial(jit, static_argnums=(2, 3))\n+def _t(key, df, shape, dtype):\n+ df = lax.convert_element_type(df, dtype)\n+ shape = shape or onp.shape(df)\n+ key_n, key_g = random.split(key)\n+ n = normal(key_n, shape, dtype)\n+ two = _constant_like(n, 2)\n+ half_df = lax.div(df, two)\n+ g = gamma(key_n, half_df, shape=self._size)\n+ return n * np.sqrt(half_df / g)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/t.py",
"new_path": "jax/scipy/stats/t.py",
"diff": "@@ -38,5 +38,5 @@ def logpdf(x, df, loc=0, scale=1):\nreturn lax.neg(lax.add(normalize_term, lax.mul(df_plus_one_over_two, lax.log1p(quadratic))))\n@_wraps(osp_stats.t.pdf)\n-def pdf(x, loc=0, scale=1):\n- return lax.exp(logpdf(x, loc, scale))\n+def pdf(x, df, loc=0, scale=1):\n+ return lax.exp(logpdf(x, df, loc, scale))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -208,6 +208,20 @@ class LaxRandomTest(jtu.JaxTestCase):\nx = random.gamma(key, onp.array([0.2, 0.3]), shape=(3, 2))\nassert x.shape == (3, 2)\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 testGumbel(self, dtype):\n+ key = random.PRNGKey(0)\n+ rand = lambda key: random.gumbel(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.gumbel_r().cdf)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}\".format(dtype), \"dtype\": onp.dtype(dtype).name}\nfor dtype in [onp.float32, onp.float64]))\n@@ -252,20 +266,6 @@ class LaxRandomTest(jtu.JaxTestCase):\nkeys = [random.fold_in(key, i) for i in range(10)]\nassert onp.unique(onp.ravel(keys)).shape == (20,)\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 testGumbel(self, dtype):\n- key = random.PRNGKey(0)\n- rand = lambda key: random.gumbel(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.gumbel_r().cdf)\n-\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add beta/t random samplers |
260,314 | 21.04.2019 21:22:50 | 14,400 | 665e72a23adf1abab6553177807f9a63639411b7 | implement bernoulli pmf | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -380,12 +380,12 @@ def _normal(key, shape, dtype):\nreturn onp.array(onp.sqrt(2), dtype) * lax.erf_inv(u)\n-def bernoulli(key, mean=onp.float32(0.5), shape=()):\n+def bernoulli(key, p=onp.float32(0.5), shape=()):\n\"\"\"Sample Bernoulli random values with given shape and mean.\nArgs:\nkey: a PRNGKey used as the random key.\n- mean: optional, an array-like broadcastable to `shape` for the mean of the\n+ p: optional, an array-like broadcastable to `shape` for the mean of the\nrandom variables (default 0.5).\nshape: optional, a tuple of nonnegative integers representing the shape\n(default scalar).\n@@ -393,16 +393,16 @@ def bernoulli(key, mean=onp.float32(0.5), shape=()):\nReturns:\nA random array with the specified shape and boolean dtype.\n\"\"\"\n- return _bernoulli(key, mean, shape)\n+ return _bernoulli(key, p, shape)\n@partial(jit, static_argnums=(2,))\n-def _bernoulli(key, mean, shape):\n- shape = shape or onp.shape(mean)\n- if not onp.issubdtype(lax.dtype(mean), onp.float32):\n- mean = lax.convert_element_type(mean, onp.float32)\n- if onp.shape(mean) != shape:\n- mean = np.broadcast_to(mean, shape)\n- return lax.lt(uniform(key, shape), mean)\n+def _bernoulli(key, p, shape):\n+ shape = shape or onp.shape(p)\n+ if not onp.issubdtype(onp.float32, lax.dtype(p)):\n+ p = lax.convert_element_type(p, onp.float32)\n+ if onp.shape(p) != shape:\n+ p = np.broadcast_to(p, shape)\n+ return lax.lt(uniform(key, shape, lax.dtype(p)), p)\ndef cauchy(key, shape=(), dtype=onp.float32):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -23,7 +23,8 @@ from .. import lax\nfrom ..api import custom_transforms\nfrom ..interpreters import ad, batching\nfrom ..numpy import lax_numpy as np\n-from ..numpy.lax_numpy import _wraps, asarray, _reduction_dims, _constant_like\n+from ..numpy.lax_numpy import (_wraps, asarray, _reduction_dims, _constant_like,\n+ _promote_args_like)\n# need to create new functions because _wraps sets the __name__ attribute\n@@ -67,6 +68,18 @@ def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):\nreturn dimadd(out) if keepdims else out\n+@_wraps(osp_special.xlogy)\n+def xlogy(x, y):\n+ x, y = _promote_args_like(osp_special.xlogy, x, y)\n+ return lax._safe_mul(x, lax.log(y))\n+\n+\n+@_wraps(osp_special.xlog1py)\n+def xlog1py(x, y):\n+ x, y = _promote_args_like(osp_special.xlog1py, x, y)\n+ return lax._safe_mul(x, lax.log1p(y))\n+\n+\n# Normal distributions\n# Functions \"ndtr\" and \"ndtri\" are derived from calculations made in:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/__init__.py",
"new_path": "jax/scipy/stats/__init__.py",
"diff": "# limitations under the License.\nfrom __future__ import absolute_import\n+from . import bernoulli\nfrom . import beta\nfrom . import cauchy\nfrom . import expon\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -51,6 +51,13 @@ class LaxRandomTest(jtu.JaxTestCase):\nstatistic = scipy.stats.kstest(samples, cdf).statistic\nself.assertLess(1. - scipy.special.kolmogorov(statistic), fail_prob)\n+ def _CheckChiSquared(self, samples, pmf):\n+ alpha = 0.01 # significance level, threshold for p-value\n+ values, actual_freq = onp.unique(samples, return_counts=True)\n+ expected_freq = pmf(values) * len(values)\n+ _, p_value = scipy.stats.chisquare(actual_freq, expected_freq)\n+ self.assertLess(p_value, alpha)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}\".format(dtype), \"dtype\": onp.dtype(dtype).name}\nfor dtype in [onp.float32, onp.float64]))\n@@ -151,7 +158,23 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertFalse(onp.all(perm1 == x)) # seems unlikely!\nself.assertTrue(onp.all(onp.sort(perm1) == x))\n- # TODO: add Chi-squared test for Bernoulli\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_p={}_{}\".format(p, dtype),\n+ \"p\": p, \"dtype\": onp.dtype(dtype).name}\n+ for p in [0.1, 0.5, 0.9]\n+ for dtype in [onp.float32, onp.float64]))\n+ def testBernoulli(self, p, dtype):\n+ key = random.PRNGKey(0)\n+ p = onp.array(p, dtype=dtype)\n+ rand = lambda key, p: random.bernoulli(key, p, (10000,))\n+ crand = api.jit(rand)\n+\n+ uncompiled_samples = rand(key, p)\n+ compiled_samples = crand(key, p)\n+\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ self._CheckChiSquared(samples, scipy.stats.bernoulli(p).pmf)\n+\ndef testBernoulliShape(self):\nkey = random.PRNGKey(0)\nx = random.bernoulli(key, onp.array([0.2, 0.3]), shape=(3, 2))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -27,6 +27,7 @@ from scipy.stats import random_correlation\nfrom jax import test_util as jtu\nfrom jax.scipy import stats as lsp_stats\n+from jax.scipy.special import expit\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -49,6 +50,22 @@ def genNamedParametersNArgs(n, rng):\nclass LaxBackedScipyStatsTests(jtu.JaxTestCase):\n\"\"\"Tests for LAX-backed scipy.stats implementations\"\"\"\n+ @genNamedParametersNArgs(3, jtu.rand_default())\n+ def testBernoulliLogPmf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.bernoulli.logpmf\n+ lax_fun = lsp_stats.bernoulli.logpmf\n+\n+ def args_maker():\n+ x, logit, loc = map(rng, shapes, dtypes)\n+ x = onp.floor(x)\n+ p = expit(logit)\n+ loc = onp.floor(loc)\n+ return [x, p, loc]\n+\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=True,\n+ tol=1e-4)\n+ self._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n+\n@genNamedParametersNArgs(5, jtu.rand_positive())\ndef testBetaLogPdf(self, rng, shapes, dtypes):\nscipy_fun = osp_stats.beta.logpdf\n"
}
] | Python | Apache License 2.0 | google/jax | implement bernoulli pmf |
260,314 | 22.04.2019 10:24:11 | 14,400 | 36c4df6f24a1eb08e8d84319265cc9349aa682f0 | implement dirichlet pdf | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -23,7 +23,8 @@ from .. import lax\nfrom ..api import custom_transforms\nfrom ..interpreters import ad, batching\nfrom ..numpy import lax_numpy as np\n-from ..numpy.lax_numpy import _wraps, asarray, _reduction_dims, _constant_like\n+from ..numpy.lax_numpy import (_wraps, asarray, _reduction_dims, _constant_like,\n+ _promote_args_like)\n# need to create new functions because _wraps sets the __name__ attribute\n@@ -67,6 +68,12 @@ def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):\nreturn dimadd(out) if keepdims else out\n+@_wraps(osp_special.xlogy)\n+def xlogy(x, y):\n+ x, y = _promote_args_like(osp_special.xlogy, x, y)\n+ return lax._safe_mul(x, lax.log(y))\n+\n+\n# Normal distributions\n# Functions \"ndtr\" and \"ndtri\" are derived from calculations made in:\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/scipy/stats/dirichlet.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+import numpy as onp\n+import scipy.stats as osp_stats\n+\n+from ... import lax\n+from ...numpy.lax_numpy import _promote_args_like, _constant_like, _wraps, all, sum\n+from ..special import gammaln, xlogy\n+\n+\n+def _is_simplex(x):\n+ x_sum = sum(x, axis=-1)\n+ return all(x > 0, axis=-1) & (x_sum <= 1) & (x_sum > 1 - 1e-6)\n+\n+\n+@_wraps(osp_stats.dirichlet.logpdf)\n+def logpdf(x, alpha):\n+ args = (onp.ones((0,), lax.dtype(x)), onp.ones((1,), lax.dtype(alpha)))\n+ to_dtype = lax.dtype(osp_stats.dirichlet.logpdf(*args))\n+ x, alpha = [lax.convert_element_type(arg, to_dtype) for arg in (x, alpha)]\n+ one = _constant_like(x, 1)\n+ normalize_term = sum(gammaln(alpha), axis=-1) - gammaln(sum(alpha, axis=-1))\n+ log_probs = lax.sub(sum(xlogy(lax.sub(alpha, one), x), axis=-1), normalize_term)\n+ return where(_is_simplex(x), log_probs, -inf)\n+\n+\n+@_wraps(osp_stats.dirichlet.pdf)\n+def pdf(x, alpha):\n+ return lax.exp(logpdf(x, alpha))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -76,6 +76,21 @@ 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(2, jtu.rand_positive())\n+ def testDirichletLogPdf(self, rng, shapes, dtypes):\n+ scipy_fun = osp_stats.cauchy.logpdf\n+ lax_fun = lsp_stats.cauchy.logpdf\n+ dim = 4\n+ shapes = (shapes[0] + (dim,), shapes[1] + (dim,))\n+\n+ def args_maker():\n+ x, alpha = map(rng, shapes, dtypes)\n+ x = x / onp.sum(x, axis=-1, keepdims=True)\n+ return [x, alpha]\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@genNamedParametersNArgs(3, jtu.rand_positive())\ndef testExponLogPdf(self, rng, shapes, dtypes):\nscipy_fun = osp_stats.expon.logpdf\n"
}
] | Python | Apache License 2.0 | google/jax | implement dirichlet pdf |
260,314 | 22.04.2019 11:55:02 | 14,400 | a790436be404cea22f59ea1ffec1082a5a672e52 | add dirichlet sampler | [
{
"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 jit, vmap\n-from .numpy.lax_numpy import _constant_like\n+from .numpy.lax_numpy import _constant_like, asarray\nfrom jax.lib import xla_bridge\nfrom jax import core\n@@ -426,6 +426,30 @@ def _cauchy(key, shape, dtype):\nreturn lax.tan(lax.mul(pi, lax.sub(u, _constant_like(u, 0.5))))\n+def dirichlet(key, alpha, shape=(), dtype=onp.float32):\n+ \"\"\"Sample Cauchy random values with given shape and float dtype.\n+\n+ Args:\n+ key: a PRNGKey used as the random key.\n+ alpha: an array-like with `alpha.shape[:-1]` broadcastable to `shape` and\n+ used as the concentration parameter of the random variables.\n+ shape: optional, a tuple of nonnegative integers representing the batch\n+ shape (defaults to `alpha.shape[:-1]`).\n+ dtype: optional, a float dtype for the returned values (default float32).\n+\n+ Returns:\n+ A random array with the specified shape and dtype.\n+ \"\"\"\n+ return _dirichlet(key, alpha, shape, dtype)\n+\n+@partial(jit, static_argnums=(2, 3))\n+def _dirichlet(key, alpha, shape, dtype):\n+ alpha = asarray(alpha, dtype)\n+ shape = shape or alpha.shape[:-1]\n+ gamma_samples = gamma(key, alpha, shape + alpha.shape[-1:], dtype)\n+ return gamma_samples / np.sum(gamma_samples, axis=-1, keepdims=True)\n+\n+\ndef exponential(key, shape=(), dtype=onp.float32):\n\"\"\"Sample Exponential 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": "@@ -171,6 +171,26 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor samples in [uncompiled_samples, compiled_samples]:\nself._CheckKolmogorovSmirnovCDF(samples, scipy.stats.cauchy().cdf)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_alpha={}_{}\".format(alpha, dtype),\n+ \"alpha\": alpha, \"dtype\": onp.dtype(dtype).name}\n+ for alpha in [[0.2, 1., 5.]]\n+ for dtype in [onp.float32, onp.float64]))\n+ @jtu.skip_on_devices(\"tpu\") # TODO(phawkins): re-enable\n+ def testDirichlet(self, alpha, dtype):\n+ key = random.PRNGKey(0)\n+ rand = lambda key, alpha: random.dirichlet(key, alpha, (10000,), dtype)\n+ crand = api.jit(rand)\n+\n+ uncompiled_samples = rand(key, alpha)\n+ compiled_samples = crand(key, alpha)\n+\n+ for samples in [uncompiled_samples, compiled_samples]:\n+ self.assertAllClose(samples.sum(-1), onp.ones(10000, dtype=dtype), check_dtypes=True)\n+ alpha_sum = sum(alpha)\n+ for i, a in enumerate(alpha):\n+ self._CheckKolmogorovSmirnovCDF(samples[..., i], scipy.stats.beta(a, alpha_sum - a).cdf)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}\".format(dtype), \"dtype\": onp.dtype(dtype).name}\nfor dtype in [onp.float32, onp.float64]))\n"
}
] | Python | Apache License 2.0 | google/jax | add dirichlet sampler |
260,314 | 22.04.2019 11:55:41 | 14,400 | 8874d7d8eb38d5a158aae0cfe91eeb7401679b26 | add missing stats.bernoulli file | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/scipy/stats/bernoulli.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+import numpy as onp\n+import scipy.stats as osp_stats\n+\n+from ... import lax\n+from ...numpy.lax_numpy import (_promote_args_like, _constant_like, _wraps,\n+ where, inf, logical_or)\n+from ..special import xlogy, xlog1py\n+\n+\n+@_wraps(osp_stats.bernoulli.logpmf)\n+def logpmf(k, p, loc=0):\n+ k, p, loc = _promote_args_like(osp_stats.bernoulli.logpmf, k, p, loc)\n+ zero = _constant_like(k, 0)\n+ one = _constant_like(k, 1)\n+ x = lax.sub(k, loc)\n+ log_probs = xlogy(x, p) + xlog1py(lax.sub(one, x), -p)\n+ return where(logical_or(lax.lt(x, zero), lax.gt(x, one)), -inf, log_probs)\n+\n+@_wraps(osp_stats.bernoulli.pmf)\n+def pmf(k, p, loc=0):\n+ return np.exp(pmf(k, p, loc))\n"
}
] | Python | Apache License 2.0 | google/jax | add missing stats.bernoulli file |
260,335 | 23.04.2019 11:09:38 | 25,200 | d5efe88d0c352e3742b9b9d4eb2c8058a6a66846 | add custom partial eval rules | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -66,6 +66,10 @@ class JaxprTrace(Trace):\nraise TypeError(pv)\ndef process_primitive(self, primitive, tracers, params):\n+ if primitive in custom_partial_eval_rules:\n+ partial_eval = custom_partial_eval_rules[primitive]\n+ return partial_eval(self, *tracers, **params)\n+ else:\ntracers = map(self.instantiate_const, tracers)\navals = [t.aval for t in tracers]\nout_aval = primitive.abstract_eval(*avals, **params)\n@@ -478,3 +482,5 @@ compiled_call_p = Primitive('compiled_call')\ncompiled_call = partial(core.call_bind, compiled_call_p)\ncompiled_call_p.def_custom_bind(compiled_call)\ncompiled_call_p.def_impl(compiled_call_impl)\n+\n+custom_partial_eval_rules = {}\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -247,7 +247,7 @@ def lower_fun(fun, c, *xla_args, **params):\nxla_shapes = tuple(map(c.GetShape, xla_args))\navals = map(aval_from_xla_shape, xla_shapes)\npvals = [pe.PartialVal((a, core.unit)) for a in avals]\n- jaxpr, pvout, consts = pe.trace_unwrapped_to_jaxpr(fun, pvals, **params)\n+ jaxpr, _, consts = pe.trace_unwrapped_to_jaxpr(fun, pvals, **params)\nbuilt_c = jaxpr_computation(jaxpr, consts, (), *xla_shapes)\nreturn c.Call(built_c, xla_args)\n"
}
] | Python | Apache License 2.0 | google/jax | add custom partial eval rules |
260,335 | 23.04.2019 17:47:28 | 25,200 | 85755820bb1b45106e46fce1b45a06509be4ebf5 | add defvjp functions for custom VJPs
c.f. which won't be closed until we add documentation | [
{
"change_type": "MODIFY",
"old_path": "jax/abstract_arrays.py",
"new_path": "jax/abstract_arrays.py",
"diff": "@@ -178,3 +178,12 @@ array_types = [onp.ndarray, onp.float64, onp.float32, onp.float16,\nfor t in array_types:\ncore.pytype_aval_mappings[t] = ConcreteArray\nad_util.jaxval_zeros_likers[t] = zeros_like_array\n+\n+\n+def raise_to_shaped(aval):\n+ if type(aval) is core.AbstractTuple:\n+ return core.AbstractTuple(map(raise_to_shaped, aval))\n+ elif isinstance(aval, ShapedArray):\n+ return ShapedArray(aval.shape, aval.dtype)\n+ else:\n+ raise TypeError(type(aval))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -23,6 +23,7 @@ from .. import core as core\nfrom ..core import JaxTuple, Trace, Tracer, new_master, get_aval, pack, call_p, Primitive\nfrom ..ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval,\nzeros_like_p, zero, Zero)\n+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@@ -307,7 +308,6 @@ def deflinear(primitive, transpose_rule):\nprimitive_jvps[primitive] = partial(linear_jvp, primitive)\nprimitive_transposes[primitive] = partial(linear_transpose, transpose_rule)\n-\ndef linear_jvp(primitive, primals, tangents, **params):\nval_out = primitive.bind(*primals, **params)\nif all(tangent is zero for tangent in tangents):\n@@ -316,7 +316,6 @@ def linear_jvp(primitive, primals, tangents, **params):\ntangents = map(instantiate_zeros, primals, tangents)\nreturn val_out, primitive.bind(*tangents, **params)\n-\ndef linear_transpose(transpose_rule, cotangent, *args, **kwargs):\nreturn zero if cotangent is zero else transpose_rule(cotangent, **kwargs)\n@@ -332,19 +331,16 @@ def standard_jvp(jvprules, primitive, primals, tangents, **params):\nif rule is not None and t is not zero]\nreturn val_out, reduce(add_tangents, tangents_out, zero)\n-\ndef defjvp2(primitive, *jvprules):\nassert isinstance(primitive, Primitive)\nprimitive_jvps[primitive] = partial(standard_jvp2, jvprules, primitive)\n-\ndef standard_jvp2(jvprules, primitive, primals, tangents, **params):\nval_out = primitive.bind(*primals, **params)\ntangents_out = (rule(t, val_out, *primals, **params) for rule, t in zip(jvprules, tangents)\nif rule is not None and t is not zero)\nreturn val_out, reduce(add_tangents, tangents_out, zero)\n-\ndef add_tangents(x, y):\nif x is zero:\nreturn y\n@@ -354,6 +350,57 @@ def add_tangents(x, y):\nreturn add_jaxvals(x, y)\n+def defvjp_all(prim, custom_vjp):\n+ name = prim.name\n+\n+ def fun_jvp(xs, ts):\n+ ts = map(instantiate_zeros, xs, ts) # TODO(mattjj): avoid instantiation?\n+ primal_out, tangent_out = fun_jvp_p.bind(pack(xs), pack(ts))\n+ return primal_out, tangent_out\n+ primitive_jvps[prim] = fun_jvp\n+\n+ fun_jvp_p = core.Primitive('{name}_jvp'.format(name=name))\n+ def fun_jvp_partial_eval(trace, *tracers):\n+ primals_tracer, tangents_tracer = tracers\n+ primal_out, vjp_py = custom_vjp(*primals_tracer)\n+\n+ in_aval = raise_to_shaped(get_aval(primal_out))\n+ ct_pval = pe.PartialVal((in_aval, core.unit))\n+ vjp_jaxpr, out_pval, residuals = pe.trace_unwrapped_to_jaxpr(\n+ lambda ct: pack(vjp_py(ct)), (ct_pval,))\n+ out_pv, out_const = out_pval\n+ tangent_out = fun_lin_p.bind(out_const, pack(residuals), tangents_tracer,\n+ in_aval=in_aval, out_pv=out_pv, vjp_jaxpr=vjp_jaxpr)\n+\n+ return pack((primal_out, tangent_out))\n+ pe.custom_partial_eval_rules[fun_jvp_p] = fun_jvp_partial_eval\n+\n+ fun_lin_p = core.Primitive('{name}_lin'.format(name=name))\n+ fun_lin_p.def_abstract_eval(lambda c, r, ts, in_aval, out_pv, vjp_jaxpr: in_aval)\n+ def fun_lin_transpose(ct, out_const, residuals, ts, in_aval, out_pv, vjp_jaxpr):\n+ assert ts is None and out_const is not None and residuals is not None\n+ ans = core.eval_jaxpr(vjp_jaxpr, residuals, (), ct)\n+ out = pe.merge_pvals(ans, pe.PartialVal((out_pv, out_const)))\n+ return [None, None, out]\n+ primitive_transposes[fun_lin_p] = fun_lin_transpose\n+\n+def defvjp(prim, *vjps):\n+ def vjpmaker(*primals):\n+ ans = prim.bind(*primals)\n+ vjpfun = lambda ct: [vjp(ct, *primals) if vjp else zeros_like_jaxval(x)\n+ for x, vjp in zip(primals, vjps)]\n+ return ans, vjpfun\n+ defvjp_all(prim, vjpmaker)\n+\n+def defvjp2(prim, *vjps):\n+ def vjpmaker(*primals):\n+ ans = prim.bind(*primals)\n+ vjpfun = lambda ct: [vjp(ct, ans, *primals) if vjp else zeros_like_jaxval(x)\n+ for x, vjp in zip(primals, vjps)]\n+ return ans, vjpfun\n+ defvjp_all(prim, vjpmaker)\n+\n+\ndef defbilinear_broadcasting(bcast, prim, lhs_rule, rhs_rule):\nassert isinstance(prim, Primitive)\nlhs_jvp = lambda g, x, y, **kwargs: prim.bind(bcast(g, y), y, **kwargs)\n@@ -362,7 +409,6 @@ def defbilinear_broadcasting(bcast, prim, lhs_rule, rhs_rule):\nprimitive_transposes[prim] = partial(bilinear_transpose, lhs_rule, rhs_rule)\ndefbilinear = partial(defbilinear_broadcasting, lambda g, x: g)\n-\ndef bilinear_transpose(lhs_rule, rhs_rule, cotangent, x, y, **kwargs):\nassert (x is None) ^ (y is None)\nif x is None:\n@@ -377,7 +423,6 @@ def defjvp_zero(primitive):\nassert isinstance(primitive, Primitive)\nprimitive_jvps[primitive] = partial(zero_jvp, primitive)\n-\ndef zero_jvp(primitive, primals, tangents, **params):\nreturn primitive.bind(*primals, **params), zero\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -26,7 +26,7 @@ from six.moves import reduce\nfrom .. import core\nfrom ..core import Trace, Tracer, new_master, pack, AbstractTuple, JaxTuple\n-from ..abstract_arrays import ShapedArray, make_shaped_array, array_types\n+from ..abstract_arrays import ShapedArray, make_shaped_array, array_types, raise_to_shaped\nfrom ..ad_util import add_jaxvals_p, zeros_like_p, zeros_like_jaxval\nfrom ..linear_util import transformation, transformation_with_aux, wrap_init\nfrom ..tree_util import register_pytree_node\n@@ -160,14 +160,6 @@ def shaped_aval(x):\nexcept KeyError:\nraise TypeError(\"{} is not a valid type for batching\".format(type(x)))\n-def raise_to_shaped(aval):\n- if type(aval) is AbstractTuple:\n- return AbstractTuple(map(raise_to_shaped, aval))\n- elif isinstance(aval, ShapedArray):\n- return ShapedArray(aval.shape, aval.dtype)\n- else:\n- raise TypeError(type(aval))\n-\ndef remove_batch_dim_from_aval(bdim, aval):\nt = type(aval)\nif t is AbstractTuple:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -36,7 +36,7 @@ from .. import linear_util as lu\nfrom ..config import flags\nfrom ..core import Primitive\nfrom ..abstract_arrays import (UnshapedArray, ShapedArray, ConcreteArray,\n- array_types, make_shaped_array)\n+ array_types, make_shaped_array, raise_to_shaped)\nfrom ..api_util import (pytree_fun_to_jaxtupletree_fun, pytree_to_jaxtupletree,\npytree_fun_to_flatjaxtuple_fun, pytree_to_flatjaxtuple)\nfrom ..interpreters import partial_eval as pe\n@@ -3951,8 +3951,5 @@ def subvals(lst, replace):\ndef _abstractify(x):\n- # abstractify wrapper used internally for primitives like while_loop\n- if isinstance(x, core.Tracer):\n- return pe.PartialVal((xla.abstractify(x.aval), core.unit))\n- else:\n- return pe.PartialVal((xla.abstractify(x), core.unit))\n+ # used internally for initial-style higher-order primitives\n+ return pe.PartialVal((raise_to_shaped(core.get_aval(x)), core.unit))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -26,7 +26,7 @@ import jax.numpy as np\nfrom jax import jit, grad, device_get, device_put, jacfwd, jacrev, hessian\nfrom jax import api\nfrom jax.core import Primitive\n-from jax.interpreters.ad import defjvp\n+from jax.interpreters.ad import defjvp, defvjp, defvjp2, defvjp_all\nfrom jax.interpreters.xla import DeviceArray\nfrom jax.abstract_arrays import concretization_err_msg\n@@ -466,6 +466,77 @@ class APITest(jtu.JaxTestCase):\ndef test_complex_input_jacfwd_raises_error(self):\nself.assertRaises(TypeError, lambda: jacfwd(lambda x: np.sin(x))(1 + 2j))\n+ def test_defvjp_all(self):\n+ foo_p = Primitive('foo')\n+ def foo(x): return 2. * foo_p.bind(x)\n+\n+ defvjp_all(foo_p, lambda x: (x**2, lambda g: (4 * g * np.sin(x),)))\n+ val_ans, grad_ans = api.value_and_grad(foo)(3.)\n+ self.assertAllClose(val_ans, 2 * 3.**2, check_dtypes=False)\n+ self.assertAllClose(grad_ans, 4 * 2 * onp.sin(3.), check_dtypes=False)\n+\n+ def test_defvjp_all_const(self):\n+ foo_p = Primitive('foo')\n+ def foo(x): return foo_p.bind(x)\n+\n+ defvjp_all(foo_p, lambda x: (x**2, lambda g: (12.,)))\n+ val_ans, grad_ans = api.value_and_grad(foo)(3.)\n+ self.assertAllClose(val_ans, 9., check_dtypes=False)\n+ self.assertAllClose(grad_ans, 12., check_dtypes=True)\n+\n+ def test_defvjp_all_higher_order_revmode(self):\n+ foo_p = Primitive('foo')\n+ def foo(x): return 2. * foo_p.bind(x)\n+\n+ defvjp_all(foo_p, lambda x: (x**2, lambda g: (g * x ** 2,)))\n+ ans = api.grad(api.grad(foo))(3.)\n+ self.assertAllClose(ans, 2 * 2 * 3., check_dtypes=False)\n+\n+ def test_defvjp_all_multiple_arguments(self):\n+ # also tests passing in symbolic zero tangents b/c we differentiate wrt only\n+ # the first argument in one case\n+\n+ foo_p = Primitive('foo')\n+ def foo(x, y): return foo_p.bind(x, y)\n+\n+ def vjpfun(x, y):\n+ out = x**2 + y**3\n+ vjp = lambda g: (g + x + y, g * x * 9.)\n+ return out, vjp\n+\n+ defvjp_all(foo_p, vjpfun)\n+ val_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\n+ self.assertAllClose(val_ans, 3.**2 + 4.**3, check_dtypes=False)\n+ self.assertAllClose(grad_ans, 1. + 3. + 4., check_dtypes=False)\n+\n+ ans = api.grad(foo, (0, 1))(3., 4.)\n+ self.assertAllClose(ans, (1. + 3. + 4., 1. * 3. * 9.), check_dtypes=False)\n+\n+ def test_defvjp(self):\n+ @api.custom_transforms\n+ def foo(x, y):\n+ return np.sin(x * y)\n+\n+ defvjp(foo.primitive, None, lambda g, x, y: g * x * y)\n+ val_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\n+ self.assertAllClose(val_ans, onp.sin(3. * 4.), check_dtypes=False)\n+ self.assertAllClose(grad_ans, 0., check_dtypes=False)\n+\n+ ans_0, ans_1 = api.grad(foo, (0, 1))(3., 4.)\n+ self.assertAllClose(ans_0, 0., check_dtypes=False)\n+ self.assertAllClose(ans_1, 3. * 4., check_dtypes=False)\n+\n+ def test_defvjp2(self):\n+ @api.custom_transforms\n+ def foo(x, y):\n+ return np.sin(x * y)\n+\n+ defvjp2(foo.primitive, None, lambda g, ans, x, y: g * x * y + np.cos(ans))\n+ val_ans, grad_ans = api.value_and_grad(foo, 1)(3., 4.)\n+ self.assertAllClose(val_ans, onp.sin(3. * 4.), check_dtypes=False)\n+ self.assertAllClose(grad_ans, 3. * 4. + onp.cos(onp.sin(3. * 4)),\n+ check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add defvjp functions for custom VJPs
c.f. #116, which won't be closed until we add documentation |
260,335 | 23.04.2019 18:21:33 | 25,200 | 0cc8d7c2b14d48ffa73e8811c5d438aaa34eb0ef | update docstrings to fix | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -91,11 +91,9 @@ def jit(fun, static_argnums=()):\n>>>\n>>> key = jax.random.PRNGKey(0)\n>>> x = jax.random.normal(key, (10,))\n- >>> selu(x)\n- array([-0.54485154, 0.27744263, -0.29255125, -0.91421586, -0.62452525,\n- -0.2474813 , -0.8574326 , -0.7823267 , 0.7682731 , 0.59566754],\n- dtype=float32)\n-\n+ >>> print(selu(x))\n+ [-0.54485154 0.27744263 -0.29255125 -0.91421586 -0.62452525 -0.2474813\n+ -0.8574326 -0.7823267 0.7682731 0.59566754]\n\"\"\"\n@wraps(fun)\ndef f_jitted(*args, **kwargs):\n@@ -214,9 +212,8 @@ def grad(fun, argnums=0, has_aux=False, holomorphic=False):\nFor example:\n>>> grad_tanh = jax.grad(jax.numpy.tanh)\n- >>> grad_tanh(0.2)\n- array(0.961043, dtype=float32)\n-\n+ >>> print(grad_tanh(0.2))\n+ 0.961043\n\"\"\"\nvalue_and_grad_f = value_and_grad(fun, argnums, has_aux=has_aux,\nholomorphic=holomorphic)\n@@ -320,11 +317,11 @@ def jacfwd(fun, argnums=0, holomorphic=False):\n>>> def f(x):\n>>> return jax.numpy.asarray(\n>>> [x[0], 5*x[2], 4*x[1]**2 - 2*x[2], x[2] * jax.numpy.sin(x[0])])\n- >>> jax.jacfwd(f)(np.array([1., 2., 3.]))\n- array([[ 1. , 0. , 0. ],\n+ >>> print(jax.jacfwd(f)(np.array([1., 2., 3.])))\n+ [[ 1. , 0. , 0. ],\n[ 0. , 0. , 5. ],\n[ 0. , 16. , -2. ],\n- [ 1.6209068 , 0. , 0.84147096]], dtype=float32)\n+ [ 1.6209068 , 0. , 0.84147096]]\n\"\"\"\ndef jacfun(*args, **kwargs):\n@@ -364,11 +361,11 @@ def jacrev(fun, argnums=0, holomorphic=False):\n>>> def f(x):\n>>> return jax.numpy.asarray(\n>>> [x[0], 5*x[2], 4*x[1]**2 - 2*x[2], x[2] * jax.numpy.sin(x[0])])\n- >>> jax.jacrev(f)(np.array([1., 2., 3.]))\n- array([[ 1. , 0. , 0. ],\n+ >>> print(jax.jacrev(f)(np.array([1., 2., 3.])))\n+ [[ 1. , 0. , 0. ],\n[ 0. , 0. , 5. ],\n[ 0. , 16. , -2. ],\n- [ 1.6209068 , 0. , 0.84147096]], dtype=float32)\n+ [ 1.6209068 , 0. , 0.84147096]]\n\"\"\"\ndef jacfun(*args, **kwargs):\nf = lu.wrap_init(fun, kwargs)\n@@ -408,9 +405,9 @@ def hessian(fun, argnums=0, holomorphic=False):\n`fun`.\n>>> g = lambda(x): x[0]**3 - 2*x[0]*x[1] - x[1]**6\n- >>> jax.hessian(g)(jax.numpy.array([1., 2.]))\n- array([[ 6., -2.],\n- [ -2., -480.]], dtype=float32)\n+ >>> print(jax.hessian(g)(jax.numpy.array([1., 2.])))\n+ [[ 6., -2.],\n+ [ -2., -480.]]\n\"\"\"\nreturn jacfwd(jacrev(fun, argnums, holomorphic), argnums, holomorphic)\n@@ -463,7 +460,7 @@ def vmap(fun, in_axes=0, out_axes=0):\n>>> mv = vmap(vv, (0, None), 0) # ([a,b], [b]) -> [a]\n>>> mm = vmap(mv, (None, 1), 1) # ([a,b], [b,c]) -> [a,c]\n- (`[a,b]` indicates an array with shape (a,b))\n+ (here we use `[a,b]` to indicate an array with shape (a,b))\n\"\"\"\ndocstr = (\"Vectorized version of {fun}. Takes similar arguments as {fun} \"\n@@ -572,8 +569,11 @@ def jvp(fun, primals, tangents):\nFor example:\n- >>> jax.jvp(jax.numpy.sin, (0.1,), (0.2,))\n- (array(0.09983342, dtype=float32), array(0.19900084, dtype=float32))\n+ >>> y, v = jax.jvp(jax.numpy.sin, (0.1,), (0.2,))\n+ >>> print(y)\n+ 0.09983342\n+ >>> print(v)\n+ 0.19900084\n\"\"\"\ndef trim_arg(primal, tangent):\nprimal_jtuple, tree_def = pytree_to_jaxtupletree(primal)\n@@ -635,12 +635,12 @@ def linearize(fun, *primals):\n>>> jax.jvp(f, (2.,), (3.,))\n(array(3.2681944, dtype=float32), array(-5.007528, dtype=float32))\n>>> y, f_jvp = jax.linearize(f, 2.)\n- >>> y\n- array(3.2681944, dtype=float32)\n- >>> f_jvp(3.)\n- array(-5.007528, dtype=float32)\n- >>> f_jvp(4.)\n- array(-6.676704, dtype=float32)\n+ >>> print(y)\n+ 3.2681944\n+ >>> print(f_jvp(3.))\n+ -5.007528\n+ >>> print(f_jvp(4.))\n+ -6.676704\n\"\"\"\nf = lu.wrap_init(fun)\nprimals_flat, in_trees = unzip2(map(pytree_to_jaxtupletree, primals))\n@@ -686,9 +686,12 @@ def vjp(fun, *primals, **kwargs):\n>>> def f(x, y):\n>>> return jax.numpy.sin(x), jax.numpy.cos(y)\n- >>> primals, g = jax.vjp(f, 0.5, 1.0)\n- >>> g((-0.7, 0.3))\n- (array(-0.61430776, dtype=float32), array(-0.2524413, dtype=float32))\n+ >>> primals, f_vjp = jax.vjp(f, 0.5, 1.0)\n+ >>> xbar, ybar = f_vjp((-0.7, 0.3))\n+ >>> print(xbar)\n+ -0.61430776\n+ >>> print(ybar)\n+ -0.2524413\n\"\"\"\nhas_aux = kwargs.pop('has_aux', False)\nassert not kwargs\n@@ -752,8 +755,8 @@ def make_jaxpr(fun):\ninstead give a few examples.\n>>> def f(x): return jax.numpy.sin(jax.numpy.cos(x))\n- >>> f(3.0)\n- array(-0.83602184, dtype=float32)\n+ >>> print(f(3.0))\n+ -0.83602184\n>>> jax.make_jaxpr(f)(3.0)\n{ lambda ; ; a.\nlet b = cos a\n"
}
] | Python | Apache License 2.0 | google/jax | update docstrings to fix #637 |
260,335 | 23.04.2019 18:35:32 | 25,200 | 74fb30cd171473afec9b855a55dc9d7651eaff3e | make DeviceArray.__repr__ call onp.array_repr | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -347,8 +347,7 @@ class DeviceArray(DeviceValue):\nreturn onp.asarray(self)\ndef __repr__(self):\n- shape_str = \",\".join(map(str, self.shape))\n- return \"DeviceArray{{{}[{}]}}\".format(onp.dtype(self.dtype).name, shape_str)\n+ return onp.array_repr(self)\ndef __len__(self):\ntry:\n"
}
] | Python | Apache License 2.0 | google/jax | make DeviceArray.__repr__ call onp.array_repr |
260,609 | 25.04.2019 01:01:02 | 18,000 | 40e3056e655f824929c9071050b29617c530274a | Fix 'atleast_<n>d' for scalars | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1180,7 +1180,7 @@ def column_stack(tup):\ndef atleast_1d(*arys):\nif len(arys) == 1:\narr = array(arys[0])\n- return arr if arr.ndim >= 1 else arr.reshape(-1)\n+ return arr if ndim(arr) >= 1 else reshape(arr, -1)\nelse:\nreturn [atleast_1d(arr) for arr in arys]\n@@ -1189,7 +1189,7 @@ def atleast_1d(*arys):\ndef atleast_2d(*arys):\nif len(arys) == 1:\narr = array(arys[0])\n- return arr if arr.ndim >= 2 else arr.reshape((1, -1))\n+ return arr if ndim(arr) >= 2 else reshape(arr, (1, -1))\nelse:\nreturn [atleast_2d(arr) for arr in arys]\n@@ -1199,9 +1199,9 @@ def atleast_3d(*arys):\nif len(arys) == 1:\narr = array(arys[0])\nif ndim(arr) <= 1:\n- arr = arr.reshape((1, -1, 1))\n+ arr = reshape(arr, (1, -1, 1))\nelif ndim(arr) == 2:\n- arr = arr.reshape(shape(arr) + (1,))\n+ arr = reshape(arr, shape(arr) + (1,))\nreturn arr\nelse:\nreturn [atleast_3d(arr) for arr in arys]\n"
}
] | Python | Apache License 2.0 | google/jax | Fix 'atleast_<n>d' for scalars |
260,609 | 29.04.2019 02:57:02 | 18,000 | 801f0824d9f072b5b1382a9b3a25d3d4d97379ab | Added test for literals in 'atleast_<n>d' | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1373,6 +1373,22 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nexpected = onp.reshape(a, (3, 2), order='F')\nself.assertAllClose(ans, expected, check_dtypes=True)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_op={}_dtype={}\".format(\n+ op, {bool: \"bool\", int: \"int\", float: \"float\"}[dtype]),\n+ \"dtype\": dtype, \"op\": op}\n+ for dtype in [int, float, bool]\n+ for op in [\"atleast_1d\", \"atleast_2d\", \"atleast_3d\"]))\n+ def testAtLeastNdLiterals(self, dtype, op):\n+ # Fixes: https://github.com/google/jax/issues/634\n+ onp_fun = lambda arg: getattr(onp, op)(arg)\n+ lnp_fun = lambda arg: getattr(lnp, op)(arg)\n+ args_maker = lambda: [dtype(2)]\n+ self._CheckAgainstNumpy(onp_fun, lnp_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n+\n+\ndef testLongLong(self):\n# TODO(phawkins): enable after a Jaxlib update.\nreturn SkipTest(\"Test disabled until jaxlib 0.1.13 is released.\")\n"
}
] | Python | Apache License 2.0 | google/jax | Added test for literals in 'atleast_<n>d' |
260,328 | 29.04.2019 16:26:18 | 14,400 | 6d9f465b96d33f0db88847939efe7e527f45bce4 | Add Differentially Private SGD example | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "examples/differentially_private_sgd.py",
"diff": "+# Copyright 2019 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+r\"\"\"JAX trains a differentially private conv net on MNIST 30X faster than TF.\n+\n+This script contains a JAX implementation of Differentially Private Stochastic\n+Gradient Descent (https://arxiv.org/abs/1607.00133). DPSGD requires clipping\n+the per-example parameter gradients, which is non-trivial to implement\n+efficiently for convolutional neural networks. For example, the reference\n+tensorflow implementation\n+(https://github.com/tensorflow/privacy/tree/master/tutorials) takes upwards of 2\n+minutes per epoch to train on MNIST. The JAX XLA compilier shines in this\n+setting, cutting train time down to a few seconds per epoch (after tens of\n+seconds to compile the algorithm to XLA instructions on the first call).\n+\n+We can now reproduce the MNIST results from the tensorflow reference\n+implementation at a 30X speedup for the simple convolutional architecture used\n+in the original DPSGD paper.\n+\n+This code depends on tensorflow_privacy (https://github.com/tensorflow/privacy)\n+ Install instructions:\n+ $ pip install tensorflow\n+ $ git clone https://github.com/tensorflow/privacy\n+ $ cd privacy\n+ $ pip install .\n+\n+The results match those in the tensorflow baseline implementation:\n+ https://github.com/tensorflow/privacy/tree/master/tutorials\n+\n+Example invocations:\n+ # this non-private baseline should get ~99% acc\n+ python -m examples.differentially_private_sgd \\\n+ --dpsgd=False \\\n+ --learning_rate=.1 \\\n+ --epochs=20 \\\n+\n+ this private baseline should get ~95% acc\n+ python -m examples.differentially_private_sgd \\\n+ --dpsgd=True \\\n+ --noise_multiplier=1.3 \\\n+ --l2_norm_clip=1.5 \\\n+ --epochs=15 \\\n+ --learning_rate=.25 \\\n+\n+ # this private baseline should get ~96.6% acc\n+ python -m examples.differentially_private_sgd \\\n+ --dpsgd=True \\\n+ --noise_multiplier=1.1 \\\n+ --l2_norm_clip=1.0 \\\n+ --epochs=60 \\\n+ --learning_rate=.15 \\\n+\n+ # this private baseline should get ~97% acc\n+ python -m examples.differentially_private_sgd \\\n+ --dpsgd=True \\\n+ --noise_multiplier=0.7 \\\n+ --l2_norm_clip=1.5 \\\n+ --epochs=45 \\\n+ --learning_rate=.25 \\\n+\"\"\"\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+\n+import itertools\n+import time\n+import warnings\n+\n+from absl import app\n+from absl import flags\n+\n+from jax import grad\n+from jax import jit\n+from jax import partial\n+from jax import random\n+from jax import tree_util\n+from jax import vmap\n+from jax.experimental import optimizers\n+from jax.experimental import stax\n+from jax.lax import stop_gradient\n+import jax.numpy as np\n+from examples import datasets\n+import numpy.random as npr\n+\n+# https://github.com/tensorflow/privacy\n+from privacy.analysis.rdp_accountant import compute_rdp\n+from privacy.analysis.rdp_accountant import get_privacy_spent\n+\n+FLAGS = flags.FLAGS\n+\n+flags.DEFINE_boolean(\n+ 'dpsgd', True, 'If True, train with DP-SGD. If False, '\n+ 'train with vanilla SGD.')\n+flags.DEFINE_float('learning_rate', .15, 'Learning rate for training')\n+flags.DEFINE_float('noise_multiplier', 1.1,\n+ 'Ratio of the standard deviation to the clipping norm')\n+flags.DEFINE_float('l2_norm_clip', 1.0, 'Clipping norm')\n+flags.DEFINE_integer('batch_size', 256, 'Batch size')\n+flags.DEFINE_integer('epochs', 60, 'Number of epochs')\n+flags.DEFINE_integer('seed', 0, 'Seed for jax PRNG')\n+flags.DEFINE_integer(\n+ 'microbatches', None, 'Number of microbatches '\n+ '(must evenly divide batch_size)')\n+flags.DEFINE_string('model_dir', None, 'Model directory')\n+\n+\n+init_random_params, predict = stax.serial(\n+ stax.Conv(16, (8, 8), padding='SAME', strides=(2, 2)),\n+ stax.Relu,\n+ stax.MaxPool((2, 2), (1, 1)),\n+ stax.Conv(32, (4, 4), padding='VALID', strides=(2, 2)),\n+ stax.Relu,\n+ stax.MaxPool((2, 2), (1, 1)),\n+ stax.Flatten,\n+ stax.Dense(32),\n+ stax.Relu,\n+ stax.Dense(10),\n+)\n+\n+\n+def loss(params, batch):\n+ inputs, targets = batch\n+ logits = predict(params, inputs)\n+ logits = stax.logsoftmax(logits) # log normalize\n+ return -np.mean(np.sum(logits * targets, 1)) # cross entropy loss\n+\n+\n+def accuracy(params, batch):\n+ inputs, targets = batch\n+ target_class = np.argmax(targets, axis=1)\n+ predicted_class = np.argmax(predict(params, inputs), axis=1)\n+ return np.mean(predicted_class == target_class)\n+\n+\n+def private_grad(params, batch, rng, l2_norm_clip, noise_multiplier,\n+ batch_size):\n+ \"\"\"Return differentially private gradients for params, evaluated on batch.\"\"\"\n+\n+ def _clipped_grad(params, single_example_batch):\n+ \"\"\"Evaluate gradient for a single-example batch and clip its grad norm.\"\"\"\n+ grads = grad(loss)(params, single_example_batch)\n+\n+ nonempty_grads, tree_def = tree_util.tree_flatten(grads)\n+ total_grad_norm = np.linalg.norm(\n+ [np.linalg.norm(neg.ravel()) for neg in nonempty_grads])\n+ divisor = stop_gradient(np.amax((total_grad_norm / l2_norm_clip, 1.)))\n+ normalized_nonempty_grads = [g / divisor for g in nonempty_grads]\n+ return tree_util.tree_unflatten(tree_def, normalized_nonempty_grads)\n+\n+ px_clipped_grad_fn = vmap(partial(_clipped_grad, params))\n+ std_dev = l2_norm_clip * noise_multiplier\n+ noise_ = lambda n: n + std_dev * random.normal(rng, n.shape)\n+ normalize_ = lambda n: n / float(batch_size)\n+ tree_map = tree_util.tree_map\n+ sum_ = lambda n: np.sum(n, 0) # aggregate\n+ aggregated_clipped_grads = tree_map(sum_, px_clipped_grad_fn(batch))\n+ noised_aggregated_clipped_grads = tree_map(noise_, aggregated_clipped_grads)\n+ normalized_noised_aggregated_clipped_grads = (\n+ tree_map(normalize_, noised_aggregated_clipped_grads)\n+ )\n+ return normalized_noised_aggregated_clipped_grads\n+\n+\n+def shape_as_image(images, labels, dummy_dim=False):\n+ target_shape = (-1, 1, 28, 28, 1) if dummy_dim else (-1, 28, 28, 1)\n+ return np.reshape(images, target_shape), labels\n+\n+\n+def compute_epsilon(steps, num_examples=60000, target_delta=1e-5):\n+ if num_examples * target_delta > 1.:\n+ warnings.warn('Your delta might be too high.')\n+ q = FLAGS.batch_size / float(num_examples)\n+ orders = list(np.linspace(1.1, 10.9, 99)) + range(11, 64)\n+ rdp_const = compute_rdp(q, FLAGS.noise_multiplier, steps, orders)\n+ eps, _, _ = get_privacy_spent(orders, rdp_const, target_delta=target_delta)\n+ return eps\n+\n+\n+def main(_):\n+\n+ if FLAGS.microbatches:\n+ raise NotImplementedError(\n+ 'Microbatches < batch size not currently supported'\n+ )\n+\n+ train_images, train_labels, test_images, test_labels = datasets.mnist()\n+ num_train = train_images.shape[0]\n+ num_complete_batches, leftover = divmod(num_train, FLAGS.batch_size)\n+ num_batches = num_complete_batches + bool(leftover)\n+ key = random.PRNGKey(FLAGS.seed)\n+\n+ def data_stream():\n+ rng = npr.RandomState(FLAGS.seed)\n+ while True:\n+ perm = rng.permutation(num_train)\n+ for i in range(num_batches):\n+ batch_idx = perm[i * FLAGS.batch_size:(i + 1) * FLAGS.batch_size]\n+ yield train_images[batch_idx], train_labels[batch_idx]\n+\n+ batches = data_stream()\n+\n+ opt_init, opt_update = optimizers.sgd(FLAGS.learning_rate)\n+\n+ @jit\n+ def update(_, i, opt_state, batch):\n+ params = optimizers.get_params(opt_state)\n+ return opt_update(i, grad(loss)(params, batch), opt_state)\n+\n+ @jit\n+ def private_update(rng, i, opt_state, batch):\n+ params = optimizers.get_params(opt_state)\n+ rng = random.fold_in(rng, i) # get new key for new random numbers\n+ return opt_update(\n+ i,\n+ private_grad(params, batch, rng, FLAGS.l2_norm_clip,\n+ FLAGS.noise_multiplier, FLAGS.batch_size), opt_state)\n+\n+ _, init_params = init_random_params(key, (-1, 28, 28, 1))\n+ opt_state = opt_init(init_params)\n+ itercount = itertools.count()\n+\n+ steps_per_epoch = 60000 // FLAGS.batch_size\n+ print('\\nStarting training...')\n+ for epoch in range(1, FLAGS.epochs + 1):\n+ start_time = time.time()\n+ # pylint: disable=no-value-for-parameter\n+ for _ in range(num_batches):\n+ if FLAGS.dpsgd:\n+ opt_state = \\\n+ private_update(\n+ key, next(itercount), opt_state,\n+ shape_as_image(*next(batches), dummy_dim=True))\n+ else:\n+ opt_state = update(\n+ key, next(itercount), opt_state, shape_as_image(*next(batches)))\n+ # pylint: enable=no-value-for-parameter\n+ epoch_time = time.time() - start_time\n+ print('Epoch {} in {:0.2f} sec'.format(epoch, epoch_time))\n+\n+ # evaluate test accuracy\n+ params = optimizers.get_params(opt_state)\n+ test_acc = accuracy(params, shape_as_image(test_images, test_labels))\n+ test_loss = loss(params, shape_as_image(test_images, test_labels))\n+ print('Test set loss, accuracy (%): ({:.2f}, {:.2f})'.format(\n+ test_loss, 100 * test_acc))\n+\n+ # determine privacy loss so far\n+ if FLAGS.dpsgd:\n+ delta = 1e-5\n+ num_examples = 60000\n+ eps = compute_epsilon(epoch * steps_per_epoch, num_examples, delta)\n+ print(\n+ 'For delta={:.0e}, the current epsilon is: {:.2f}'.format(delta, eps))\n+ else:\n+ print('Trained with vanilla non-private SGD optimizer')\n+\n+\n+if __name__ == '__main__':\n+ app.run(main)\n"
}
] | Python | Apache License 2.0 | google/jax | Add Differentially Private SGD example |
260,328 | 30.04.2019 09:26:16 | 14,400 | 948def817fd7cc2ee7a988b5142401a580b1bbd3 | docstring touchups | [
{
"change_type": "MODIFY",
"old_path": "examples/differentially_private_sgd.py",
"new_path": "examples/differentially_private_sgd.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-r\"\"\"JAX trains a differentially private conv net on MNIST 30X faster than TF.\n+r\"\"\"JAX efficiently trains a differentially private conv net on MNIST.\nThis script contains a JAX implementation of Differentially Private Stochastic\nGradient Descent (https://arxiv.org/abs/1607.00133). DPSGD requires clipping\nthe per-example parameter gradients, which is non-trivial to implement\n-efficiently for convolutional neural networks. For example, the reference\n-tensorflow implementation\n-(https://github.com/tensorflow/privacy/tree/master/tutorials) takes upwards of 2\n-minutes per epoch to train on MNIST. The JAX XLA compilier shines in this\n-setting, cutting train time down to a few seconds per epoch (after tens of\n-seconds to compile the algorithm to XLA instructions on the first call).\n-\n-We can now reproduce the MNIST results from the tensorflow reference\n-implementation at a 30X speedup for the simple convolutional architecture used\n-in the original DPSGD paper.\n+efficiently for convolutional neural networks. The JAX XLA compiler shines in\n+this setting by optimizing the minibatch-vectorized computation for\n+convolutional architectures. Train time takes a few seconds per epoch on a\n+commodity GPU.\nThis code depends on tensorflow_privacy (https://github.com/tensorflow/privacy)\nInstall instructions:\n@@ -35,7 +29,7 @@ This code depends on tensorflow_privacy (https://github.com/tensorflow/privacy)\n$ cd privacy\n$ pip install .\n-The results match those in the tensorflow baseline implementation:\n+The results match those in the reference TensorFlow baseline implementation:\nhttps://github.com/tensorflow/privacy/tree/master/tutorials\nExample invocations:\n"
}
] | Python | Apache License 2.0 | google/jax | docstring touchups |
260,335 | 30.04.2019 09:19:48 | 25,200 | 6c7dde59f59fb5be7e37ea820047364864eee32a | move isclose test behind numpy version check | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -24,4 +24,4 @@ install:\n- pip install jaxlib\n- pip install -v .\nscript:\n- - pytest -n 2 tests examples\n+ - pytest -n 2 tests examples -W ignore\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -135,7 +135,6 @@ JAX_COMPOUND_OP_RECORDS = [\nop_record(\"kron\", 2, number_dtypes, nonempty_shapes, jtu.rand_default(), []),\nop_record(\"outer\", 2, number_dtypes, all_shapes, jtu.rand_default(), []),\nop_record(\"imag\", 1, number_dtypes, all_shapes, jtu.rand_some_inf(), []),\n- op_record(\"isclose\", 2, all_dtypes, all_shapes, jtu.rand_small_positive(), []),\nop_record(\"iscomplex\", 1, number_dtypes, all_shapes, jtu.rand_some_inf(), []),\nop_record(\"isreal\", 1, number_dtypes, all_shapes, jtu.rand_some_inf(), []),\nop_record(\"isrealobj\", 1, number_dtypes, all_shapes, jtu.rand_some_inf(), []),\n@@ -242,6 +241,7 @@ if numpy_version >= (1, 15):\nif six.PY2:\nJAX_OPERATOR_OVERLOADS += [\n+ op_record(\"isclose\", 2, all_dtypes, all_shapes, jtu.rand_small_positive(), []),\nop_record(\"__div__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero(), []),\nop_record(\"__rdiv__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero(), []),\n]\n"
}
] | Python | Apache License 2.0 | google/jax | move isclose test behind numpy version check |
260,335 | 30.04.2019 10:33:27 | 25,200 | 97b5fc982e68cf3983e7b8a414b86acaf1ac93d8 | fix incorrectly-pasted line | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -232,6 +232,7 @@ JAX_OPERATOR_OVERLOADS = [\nnumpy_version = tuple(map(int, onp.version.version.split('.')))\nif numpy_version >= (1, 15):\nJAX_COMPOUND_OP_RECORDS += [\n+ op_record(\"isclose\", 2, all_dtypes, all_shapes, jtu.rand_small_positive(), []),\nop_record(\"gcd\", 2, int_dtypes, all_shapes, jtu.rand_default(), []),\nop_record(\"lcm\", 2, int_dtypes, all_shapes, jtu.rand_default(), []),\n]\n@@ -241,7 +242,6 @@ if numpy_version >= (1, 15):\nif six.PY2:\nJAX_OPERATOR_OVERLOADS += [\n- op_record(\"isclose\", 2, all_dtypes, all_shapes, jtu.rand_small_positive(), []),\nop_record(\"__div__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero(), []),\nop_record(\"__rdiv__\", 2, number_dtypes, all_shapes, jtu.rand_nonzero(), []),\n]\n"
}
] | Python | Apache License 2.0 | google/jax | fix incorrectly-pasted line |
260,335 | 30.04.2019 10:48:34 | 25,200 | 75ec03e22cc3dd45e6699a207c26dda3b4d89dce | instantiate consts when tracing while's body_fun
fixes
The instantiate-consts logic in partial_eval.py is originally by
in (on the differentiable-scan branch). | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -169,7 +169,7 @@ def add_axis_to_aval(size, aval):\ndef partial_eval(f, trace, pvs):\n- f = trace_to_subjaxpr(f, trace.master)\n+ f = trace_to_subjaxpr(f, trace.master, False)\nreturn partial_eval_wrapper(f, tuple(pvs))\n@@ -341,10 +341,11 @@ def abstractify(x):\ndef trace_unwrapped_to_jaxpr(fun, pvals, **kwargs):\nreturn trace_to_jaxpr(lu.wrap_init(fun, kwargs), pvals)\n-def trace_to_jaxpr(fun, pvals):\n+def trace_to_jaxpr(fun, pvals, **kwargs):\n\"\"\"Traces a function, given abstract inputs, to a jaxpr.\"\"\"\n+ instantiate = kwargs.pop('instantiate', False)\nwith new_master(JaxprTrace) as master:\n- fun = trace_to_subjaxpr(fun, master)\n+ fun = trace_to_subjaxpr(fun, master, instantiate)\njaxpr, (out_pval, consts, env) = fun.call_wrapped(pvals)\nassert not env\ndel master\n@@ -352,12 +353,16 @@ def trace_to_jaxpr(fun, pvals):\nreturn jaxpr, out_pval, consts\n@transformation\n-def trace_to_subjaxpr(master, pvals):\n+def trace_to_subjaxpr(master, instantiate, pvals):\nassert all([isinstance(pv, PartialVal) for pv in pvals]), pvals\ntrace = JaxprTrace(master, core.cur_sublevel())\nin_tracers = map(trace.new_arg, pvals)\nout_tracer = yield in_tracers, {}\nout_tracer = trace.full_raise(out_tracer)\n+\n+ if instantiate:\n+ out_tracer = trace.instantiate_const(out_tracer)\n+\njaxpr, consts, env = tracers_to_jaxpr(in_tracers, out_tracer)\nout_pval = out_tracer.pval\ndel trace, in_tracers, out_tracer\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -69,10 +69,26 @@ def while_loop(cond_fun, body_fun, init_val):\nflat_body_fun, out_tree = pytree_fun_to_jaxtupletree_fun(lu.wrap_init(body_fun), (in_tree,))\nflat_cond_fun, _ = pytree_fun_to_jaxtupletree_fun(lu.wrap_init(cond_fun), (in_tree,))\n- pval_flat = lax._abstractify(init_val_flat)\n- cond_jaxpr, _, cond_consts = pe.trace_to_jaxpr(flat_cond_fun, (pval_flat,))\n- body_jaxpr, pval_out, body_consts = pe.trace_to_jaxpr(flat_body_fun, (pval_flat,))\n- aval_out, _ = pval_out\n+ carry_pval_flat = carry_aval, _ = lax._abstractify(init_val_flat)\n+ cond_jaxpr, cond_pval_out, cond_consts = pe.trace_to_jaxpr(flat_cond_fun, (carry_pval_flat,))\n+ body_jaxpr, body_pval_out, body_consts = pe.trace_to_jaxpr(flat_body_fun, (carry_pval_flat,), instantiate=True)\n+ carry_aval_out, _ = body_pval_out\n+ assert isinstance(carry_aval_out, core.AbstractValue)\n+ assert carry_aval == core.lattice_join(carry_aval, carry_aval_out)\n+\n+ cond_pv, cond_const = cond_pval_out\n+ if cond_pv is None:\n+ # cond_fun evaluates to a constant, so don't need to generate a while_loop\n+ if cond_const:\n+ raise ValueError(\"infinite loop with no effects\")\n+ else:\n+ return init_val\n+ else:\n+ assert isinstance(cond_pv, core.AbstractValue)\n+ if (not isinstance(cond_pv, ShapedArray) or cond_pv.shape\n+ or cond_pv.dtype != onp.bool_):\n+ msg = \"while_loop cond_fun must return a scalar boolean, got {}.\"\n+ raise TypeError(msg.format(cond_pv))\n# We don't want to promote literal constants as loop arguments; there are\n# sometimes many of them. We pass tracers as loop arguments, but leave\n@@ -97,7 +113,6 @@ def while_loop(cond_fun, body_fun, init_val):\nbody_split = split_tracers_and_nontracers(body_jaxpr, body_consts)\nbody_jaxpr.constvars, body_nontracer_consts, body_tracer_consts = body_split\n-\nif out_tree() != in_tree:\nraise TypeError(\"body_fun input and output must have identical structure\")\nout_flat = while_p.bind(\n@@ -105,7 +120,7 @@ def while_loop(cond_fun, body_fun, init_val):\ncore.pack(cond_tracer_consts), core.pack(body_tracer_consts),\ncond_consts=lax._OpaqueParam(cond_nontracer_consts),\nbody_consts=lax._OpaqueParam(body_nontracer_consts),\n- aval_out=aval_out, cond_jaxpr=cond_jaxpr, body_jaxpr=body_jaxpr)\n+ aval_out=carry_aval_out, cond_jaxpr=cond_jaxpr, body_jaxpr=body_jaxpr)\nreturn build_tree(out_tree(), out_flat)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -404,6 +404,20 @@ class LaxControlFlowTest(jtu.JaxTestCase):\n(0, 0), lambda x: (x[0], 0),\n(1, 1), lambda x: x)\n+ def testIssue649(self):\n+ from jax import lax\n+\n+ def body(x):\n+ a, b = x\n+ return (7, b + 1)\n+\n+ def cond(x):\n+ a, b = x\n+ return b < 10\n+\n+ out = lax.while_loop(cond, body, (33, 4))\n+ self.assertEqual(out, (7, 10))\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | instantiate consts when tracing while's body_fun
fixes #649
The instantiate-consts logic in partial_eval.py is originally by
@dougalm in 13fa383 (on the differentiable-scan branch). |
260,335 | 30.04.2019 11:52:33 | 25,200 | 64bcaa4cfe059be5a71693a7e80959c142644792 | fix up other trace_to_subjaxpr call sites | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -477,7 +477,7 @@ def eval_jaxpr_raw(jaxpr, consts, freevar_vals, *args):\ndef compiled_call_impl(fun, *args):\nwith new_master(JaxprTrace, True) as master:\npvals = map(abstractify, args)\n- jaxpr, (pval, consts, env) = trace_to_subjaxpr(fun, master).call_wrapped(pvals)\n+ jaxpr, (pval, consts, env) = trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)\njaxpr_ans = eval_jaxpr_raw(jaxpr, consts, env, *args)\nans = merge_pvals(jaxpr_ans, pval)\ndel master, pvals, pval, consts, env, jaxpr_ans, jaxpr\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -329,7 +329,7 @@ def _shard_aval(axis_size, aval):\ndef parallel_callable(fun, axis_name, axis_size, *avals):\npvals = [PartialVal((aval, core.unit)) for aval in avals]\nwith core.new_master(JaxprTrace, True) as master:\n- jaxpr, (pval, consts, env) = trace_to_subjaxpr(fun, master).call_wrapped(pvals)\n+ jaxpr, (pval, consts, env) = trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)\nassert not env\nout = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\ncompiled, nrep, result_shape = out\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -516,7 +516,7 @@ def xla_call_impl(fun, *args):\ndef xla_callable(fun, *abstract_args):\npvals = [pe.PartialVal((aval, core.unit)) for aval in abstract_args]\nwith core.new_master(pe.JaxprTrace, True) as master:\n- jaxpr, (pval, consts, env) = pe.trace_to_subjaxpr(fun, master).call_wrapped(pvals)\n+ jaxpr, (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)\ncompiled, result_shape = compile_jaxpr(jaxpr, consts, *abstract_args)\ndel master, consts, jaxpr, env\n"
}
] | Python | Apache License 2.0 | google/jax | fix up other trace_to_subjaxpr call sites |
260,510 | 30.04.2019 12:56:48 | 25,200 | d92fb06939bcf721764ea0b78ac41af869130650 | add lax numpy.tile implementation | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1135,6 +1135,15 @@ def stack(arrays, axis=0):\nnew_arrays.append(reshape(a, new_shape))\nreturn concatenate(new_arrays, axis=axis)\n+@_wraps(onp.tile)\n+def tile(a, reps):\n+ if isinstance(reps, int):\n+ reps = (reps,)\n+ a = a[(None,) * (len(reps) - a.ndim)]\n+ reps = (1,) * (a.ndim - len(reps)) + reps\n+ for i, rep in enumerate(reps):\n+ a = concatenate([a] * rep, axis=i)\n+ return a\n@_wraps(onp.concatenate)\ndef concatenate(arrays, axis=0):\n@@ -2302,7 +2311,7 @@ _nondiff_methods = [\"all\", \"any\", \"argmax\", \"argmin\", \"argpartition\", \"argsort\",\n_diff_methods = [\"clip\", \"compress\", \"conj\", \"conjugate\", \"cumprod\", \"cumsum\",\n\"diagonal\", \"dot\", \"max\", \"mean\", \"min\", \"prod\", \"ptp\",\n\"ravel\", \"repeat\", \"sort\", \"squeeze\", \"std\", \"sum\",\n- \"swapaxes\", \"take\", \"trace\", \"transpose\", \"var\"]\n+ \"swapaxes\", \"take\", \"tile\", \"trace\", \"transpose\", \"var\"]\n# Set up operator, method, and property forwarding on Tracer instances containing\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -599,6 +599,23 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(onp_fun, lnp_fun, args_maker, check_dtypes=True)\nself._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape=[{}]_reps={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), reps),\n+ \"shape\": shape, \"dtype\": dtype, \"reps\": reps,\n+ \"rng\": jtu.rand_default()}\n+ for reps in [(), (2,), (3, 4), (2, 3, 4)]\n+ for dtype in default_dtypes\n+ for shape in all_shapes\n+ ))\n+ def testTile(self, shape, dtype, reps, rng):\n+ onp_fun = lambda arg: onp.tile(arg, reps)\n+ lnp_fun = lambda arg: lnp.tile(arg, reps)\n+\n+ args_maker = lambda: [rng(shape, dtype)]\n+\n+ self._CheckAgainstNumpy(onp_fun, lnp_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(lnp_fun, args_maker, check_dtypes=True)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_axis={}_baseshape=[{}]_dtypes=[{}]\".format(\n"
}
] | Python | Apache License 2.0 | google/jax | add lax numpy.tile implementation |
260,335 | 24.04.2019 10:26:29 | 25,200 | 2f9ebf5ef5d54c549d9b60377109f08d351550d0 | add docstring to xla.device_put | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -84,6 +84,21 @@ def execute_compiled_primitive(compiled, result_handler, *args):\nreturn result_handler(compiled.Execute(input_bufs, not core.skip_checks))\ndef device_put(x, device_num=0):\n+ \"\"\"Place a Python value `x` on device number `device_num`.\n+\n+ This is a wrapper around jax.lib.xla_bridge.device_put to handle\n+ additional Python array types, namely DeviceArray (which is already backed by\n+ device memory, though may be on the wrong device) and DeviceConstant. In\n+ particular, it avoids transferring data already placed on the correct device,\n+ and handles instantiating DeviceConstants.\n+\n+ Args:\n+ x: an ndarray, DeviceArray, DeviceConstant, or JaxTuple to be transferred.\n+ device_num: an int representing the target physical device number.\n+\n+ Returns:\n+ A buffer representing the input `x` placed on the appropriate device.\n+ \"\"\"\nx = canonicalize_pyval_dtype(x)\nif type(x) is DeviceArray:\nif x.device_buffer.device() == device_num:\n"
}
] | Python | Apache License 2.0 | google/jax | add docstring to xla.device_put |
260,335 | 24.04.2019 18:16:31 | 25,200 | ee9d148fc16e2b0e695ab2891ebfbcacc301b70d | avoid super-linear recursive behavior in batching | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -284,12 +284,14 @@ def move_dim_to_front(x, dim):\nreturn moveaxis(None, 0, dim, x)\ndef dimsize(dim, x):\n- aval = get_aval(x)\n+ return _dimsize(dim, get_aval(x), x)\n+\n+def _dimsize(dim, aval, x):\nif type(aval) is AbstractTuple:\nif type(dim) is tuple:\n- return reduce(set.union, map(dimsize, dim, x))\n+ return reduce(set.union, map(_dimsize, dim, aval, x))\nelif type(dim) is int:\n- return reduce(set.union, map(partial(dimsize, dim), x))\n+ return reduce(set.union, map(partial(_dimsize, dim), aval, x))\nelif dim is None:\nreturn set()\nelse:\n@@ -303,17 +305,20 @@ def dimsize(dim, x):\nraise TypeError(type(dim))\ndef moveaxis(sz, dst, src, x, force_broadcast=True):\n- aval = get_aval(x)\n+ return _moveaxis(sz, dst, src, get_aval(x), x, force_broadcast)\n+\n+# TODO(mattjj): not passing forece_broadcast recursively... intentional?\n+def _moveaxis(sz, dst, src, aval, x, force_broadcast=True):\nif type(aval) is AbstractTuple:\nif type(src) is tuple and type(dst) is tuple:\n- return pack(map(partial(moveaxis, sz), dst, src, x))\n+ return pack(map(partial(_moveaxis, sz), dst, src, aval, x))\nelif type(src) is tuple:\n- return pack(map(partial(moveaxis, sz, dst), src, x))\n+ return pack(map(partial(_moveaxis, sz, dst), src, aval, x))\nelif type(dst) is tuple:\nsrcs = (src,) * len(dst)\n- return pack(map(partial(moveaxis, sz), dst, srcs, x))\n+ return pack(map(partial(_moveaxis, sz), dst, srcs, aval, x))\nelse:\n- return pack(map(partial(moveaxis, sz, dst, src), x))\n+ return pack(map(partial(_moveaxis, sz, dst, src), aval, x))\nelif isinstance(aval, ShapedArray):\ndst_ = (dst % aval.ndim) if dst is not None and aval.ndim else dst\nif src == dst_:\n@@ -333,9 +338,12 @@ def moveaxis(sz, dst, src, x, force_broadcast=True):\nraise TypeError(type(aval))\ndef broadcast(x, sz, force_broadcast=False):\n- aval = get_aval(x)\n+ return _broadcast(sz, get_aval(x), x, force_broadcast)\n+\n+# TODO(mattjj): not passing forece_broadcast recursively... intentional?\n+def _broadcast(sz, aval, x, force_broadcast=False):\nif type(aval) is AbstractTuple:\n- return pack(map(partial(broadcast, sz=sz), x))\n+ return pack(map(partial(_broadcast, sz), aval, x))\nelif isinstance(aval, ShapedArray):\n# for scalars, maybe don't actually broadcast\nif not onp.ndim(x) and not force_broadcast:\n"
}
] | Python | Apache License 2.0 | google/jax | avoid super-linear recursive behavior in batching |
260,335 | 24.04.2019 21:31:15 | 25,200 | 055521fa8e349b55d8044ef7d3b53a40ef93d929 | add DeviceTuples for device-persistent tuples | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -418,11 +418,7 @@ def lattice_join(x, y):\ndef valid_jaxtype(x):\n- try:\n- concrete_aval(x)\n- except TypeError:\n- return False\n- return True\n+ return type(x) in pytype_aval_mappings\ndef concrete_aval(x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -31,6 +31,7 @@ from ..ad_util import add_jaxvals_p, zeros_like_p, zeros_like_jaxval\nfrom ..linear_util import transformation, transformation_with_aux, wrap_init\nfrom ..tree_util import register_pytree_node\nfrom ..util import unzip2, partial, safe_map\n+from . import xla\nmap = safe_map\n@@ -200,8 +201,9 @@ def shaped_jaxtuple(xs):\nreturn AbstractTuple(map(shaped_aval, xs))\npytype_aval_mappings[JaxTuple] = shaped_jaxtuple\n+pytype_aval_mappings[xla.DeviceTuple] = xla.abstractify_device_tuple\n-for t in array_types:\n+for t in it.chain(array_types, [xla.DeviceArray]):\npytype_aval_mappings[t] = make_shaped_array\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -43,53 +43,94 @@ from . import ad\n### util\n-def shard_arg(device_ordinals, arg):\n+# TODO(mattjj, phawkins): improve re-distribution not to copy to host\n+def shard_arg(device_ordinals, axis_size, arg):\n\"\"\"Shard an argument data array arg along its leading axis.\nArgs:\ndevice_ordinals: list of integers of length num_replicas mapping a logical\nreplica index to a physical device number.\n- arg: an array type representing an argument value to be sharded along its\n- leading axis and placed on the devices/replicas.\n+ axis_size: int, size of the axis to be sharded.\n+ arg: a JaxType representing an argument to be sharded along its leading axis\n+ (or the leading axis of its leaves in the tuple case) and placed on the\n+ devices indicated by `device_ordinals`.\nReturns:\n- A list of length num_replicas of device buffers indexed by replica number,\n- where the nth element is the argument to be passed to the nth replica.\n+ A list of device buffers with the same length as `device_ordinals` indexed\n+ by replica number, so that the nth element is the argument to be passed to\n+ the nth replica.\n\"\"\"\nnrep = len(device_ordinals)\n- assignments = assign_shards_to_replicas(nrep, arg.shape[0])\n- if type(arg) is ShardedDeviceArray and nrep == len(arg.device_buffers):\n- # TODO(mattjj, phawkins): improve re-distribution not to copy to host\n+ assignments = assign_shards_to_replicas(nrep, axis_size)\n+ if (type(arg) in (ShardedDeviceArray, ShardedDeviceTuple)\n+ and nrep == len(arg.device_buffers)):\n_, ids = onp.unique(assignments, return_index=True)\nget_shard = memoize_unary(lambda i: arg.device_buffers[i].to_py())\nreturn [buf if buf.device() == device_ordinals[r]\nelse xla.device_put(get_shard(i), device_ordinals[r])\nfor r, (i, buf) in enumerate(zip(assignments, arg.device_buffers))]\nelse:\n- shards = [(arg[assignments[i]], device_ordinals[i])\n+ shards = [(_slice(arg, assignments[i]), device_ordinals[i])\nfor i in range(len(assignments))]\nreturn xla.device_put_many(shards)\n+def _slice(x, i):\n+ \"\"\"Return the ith slice of a JaxType (tuple or array).\"\"\"\n+ t = type(x)\n+ if t is core.JaxTuple or t is xla.DeviceTuple:\n+ return core.pack(_slice(elt, i) for elt in x)\n+ else:\n+ return x[i]\n+\n+\ndef unshard_output(axis_size, replica_results):\n\"\"\"Collect together replica results into a result value.\nArgs:\naxis_size: size of the sharded output data axis.\n- replica_results: list of either ndarrays or DeviceArrays indexed by replica\n- number.\n+ replica_results: list of JaxTypes of length equal to the number of replicas\n+ representing their respective results and which together represent the\n+ value to be unsharded.\nReturns:\n- Either an ndarray or a ShardedDeviceArray representing the result of the\n- computation, stacking together the results from the replicas.\n+ A JaxType representing the single stacked logical result of the computation,\n+ possibly maintained as a lazy sharded type.\n\"\"\"\n- nrep = len(replica_results)\n- if all(type(res) is xla.DeviceArray for res in replica_results):\n- return ShardedDeviceArray(axis_size, replica_results)\n+ types = {type(result) for result in replica_results}\n+ assert len(types) == 1\n+ t = types.pop()\n+ if t is xla.DeviceArray:\n+ bufs = [r.device_buffer for r in replica_results]\n+ return ShardedDeviceArray(axis_size, bufs)\n+ elif t is xla.DeviceTuple:\n+ bufs = [r.device_buffer for r in replica_results]\n+ return ShardedDeviceTuple(axis_size, bufs)\n+ elif t is core.JaxTuple:\n+ # A JaxTuple can result from merging pvals, for example\n+ # pmap(lambda x: pack((3, x)))(...)\n+ # To avoid the complexity of DeviceTuples having mixed host/device elements,\n+ # we instead pull everything back to the host.\n+ # TODO(mattjj): can improve this policy to enable more device-persistence\n+ return _stack(axis_size, replica_results)\nelse:\n- assignments = assign_shards_to_replicas(nrep, axis_size)\n+ # This case can obtain if t is a host-backed type like an onp.ndarray or\n+ # Python int, e.g. from pmap(lambda x: 3)(...). Just stack in host memory.\n+ return _stack(axis_size, replica_results)\n+\n+def _stack(axis_size, replica_results):\n+ \"\"\"Stack replica_results to produce a result in host memory.\"\"\"\n+ types = {type(result) for result in replica_results}\n+ assert len(types) == 1\n+ t = types.pop()\n+ if t is core.JaxTuple or t is xla.DeviceTuple:\n+ results = zip(*replica_results)\n+ return core.pack(map(partial(_stack, axis_size), results))\n+ else:\n+ assignments = assign_shards_to_replicas(len(replica_results), axis_size)\n_, ids = onp.unique(assignments, return_index=True)\nreturn onp.stack([replica_results[i] for i in ids])\n+\ndef assign_shards_to_replicas(nrep, size):\n\"\"\"Produce a mapping from replica id to shard index.\n@@ -266,23 +307,53 @@ def _map(f, *xs):\nreturn tuple(map(f, *xs))\n+class ShardedDeviceTuple(xla.DeviceTuple):\n+ __slots__ = [\"axis_size\", \"device_buffers\"]\n+\n+ def __init__(self, axis_size, device_buffers):\n+ self.axis_size = axis_size\n+ self.device_buffers = device_buffers\n+\n+ def __iter__(self):\n+ all_bufs = zip(*[buf.destructure() for buf in self.device_buffers])\n+ elts = [_tuple_elt_handler(self.axis_size, bufs) for bufs in all_bufs]\n+ return iter(elts)\n+\n+def _tuple_elt_handler(axis_size, bufs):\n+ is_tuple = {buf.shape().is_tuple() for buf in bufs}\n+ assert len(is_tuple) == 1\n+ if is_tuple.pop():\n+ return ShardedDeviceTuple(axis_size, bufs)\n+ else:\n+ return ShardedDeviceArray(axis_size, bufs)\n+\n+core.pytype_aval_mappings[ShardedDeviceTuple] = core.AbstractTuple\n+xla.pytype_aval_mappings[ShardedDeviceTuple] = \\\n+ xla.pytype_aval_mappings[xla.DeviceTuple]\n+xla.canonicalize_dtype_handlers[ShardedDeviceTuple] = \\\n+ xla.canonicalize_dtype_handlers[xla.DeviceTuple]\n+\n+\nclass ShardedDeviceArray(xla.DeviceArray):\n__slots__ = [\"device_buffers\"]\n- def __init__(self, axis_size, replica_results):\n- self.device_buffers = [res.device_buffer for res in replica_results]\n- r = replica_results[0]\n- self.shape = (axis_size,) + r.shape\n- self.dtype = r.dtype\n- self.ndim = 1 + r.ndim\n- self.size = axis_size * r.size\n+ def __init__(self, axis_size, device_buffers):\n+ self.device_buffers = device_buffers\n+\n+ xla_shape = device_buffers[0].shape()\n+ self.shape = (axis_size,) + tuple(xla_shape.dimensions())\n+ self.dtype = xla_shape.element_type()\n+ self.ndim = 1 + len(self.shape)\n+ self.size = axis_size * prod(self.shape)\nself._npy_value = None\n@property\ndef _value(self):\nif self._npy_value is None:\nnpy_shards = [buf.to_py() for buf in self.device_buffers]\n- self._npy_value = unshard_output(self.shape[0], npy_shards)\n+ assignments = assign_shards_to_replicas(len(npy_shards), self.shape[0])\n+ _, ids = onp.unique(assignments, return_index=True)\n+ self._npy_value = onp.stack([npy_shards[i] for i in ids])\nreturn self._npy_value\ncore.pytype_aval_mappings[ShardedDeviceArray] = ConcreteArray\n@@ -299,26 +370,16 @@ def xla_pmap_impl(fun, *args, **params):\naxis_name = params.pop('axis_name')\naxis_size = params.pop('axis_size')\nassert not params\n-\n- flat_args, in_trees = unzip2(map(xla.tree_flatten, args))\n- flat_args = concatenate(flat_args)\n- fun, out_tree = xla.flatten_fun(fun, in_trees)\n-\n- abstract_args = map(partial(abstractify, axis_size), flat_args)\n+ abstract_args = map(partial(abstractify, axis_size), args)\ncompiled_fun = parallel_callable(fun, axis_name, axis_size, *abstract_args)\n- flat_ans = compiled_fun(out_tree(), *flat_args)\n-\n- if out_tree() is xla.leaf:\n- return flat_ans\n- else:\n- return xla.build_tree(iter(flat_ans), out_tree())\n+ return compiled_fun(*args)\ndef abstractify(axis_size, x):\nreturn _shard_aval(axis_size, xla.abstractify(x))\ndef _shard_aval(axis_size, aval):\nif type(aval) is core.AbstractTuple:\n- return AbstractTuple(map(partial(_shard_aval, axis_size), aval))\n+ return core.AbstractTuple(map(partial(_shard_aval, axis_size), aval))\nelif type(aval) is ShapedArray:\nassert aval.shape[0] == axis_size\nreturn ShapedArray(aval.shape[1:], aval.dtype)\n@@ -334,20 +395,17 @@ def parallel_callable(fun, axis_name, axis_size, *avals):\nout = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\ncompiled, nrep, result_shape = out\ndel master, consts, jaxpr, env\n- handle_arg = partial(shard_arg, compiled._device_ordinals)\n+ handle_arg = partial(shard_arg, compiled._device_ordinals, axis_size)\nhandle_result = xla.result_handler(result_shape)\nreturn partial(execute_replicated, compiled, pval, axis_size, nrep,\nhandle_arg, handle_result)\ndef execute_replicated(compiled, pval, axis_size, nrep, handle_in, handle_out,\n- out_tree, *args):\n+ *args):\ninput_bufs = zip(*map(handle_in, args)) if args else [[]] * nrep\nout_bufs = compiled.ExecutePerReplica(input_bufs)\nreplica_results = [merge_pvals(handle_out(buf), pval) for buf in out_bufs]\n- if out_tree is xla.leaf:\nreturn unshard_output(axis_size, replica_results)\n- else:\n- return tuple(map(partial(unshard_output, axis_size), zip(*replica_results)))\nxla_pmap_p = core.Primitive('xla_pmap')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -59,7 +59,7 @@ def xla_primitive_callable(prim, *abstract_args, **kwargs):\nhandle_result = result_handler(result_shape)\ncompiled = built_c.Compile(shapes, xb.get_compile_options(),\nbackend=xb.get_backend())\n- return partial(execute_compiled_primitive, compiled, handle_result)\n+ return partial(execute_compiled_primitive, prim.name, compiled, handle_result)\n@memoize\ndef primitive_computation(prim, *shapes, **kwargs):\n@@ -79,28 +79,52 @@ def aval_from_xla_shape(shape):\nelse:\nreturn ShapedArray(shape.dimensions(), shape.element_type())\n-def execute_compiled_primitive(compiled, result_handler, *args):\n+def execute_compiled_primitive(name, compiled, result_handler, *args):\ninput_bufs = [device_put(x) for x in args]\n- return result_handler(compiled.Execute(input_bufs, not core.skip_checks))\n+ out_buf = compiled.Execute(input_bufs, not core.skip_checks)\n+ check_nans(name, out_buf)\n+ return result_handler(out_buf)\n+\n+def check_nans(name, buf):\n+ FLAGS.jax_debug_nans and _check_nans(name, buf.shape(), buf)\n+\n+def _check_nans(name, xla_shape, buf):\n+ if xla_shape.is_tuple():\n+ _map(partial(_check_nans, name), xla_shape.tuple_shapes(), buf.destructure())\n+ else:\n+ if onp.issubdtype(xla_shape.element_type(), onp.floating):\n+ pyval = buf.to_py()\n+ if onp.any(onp.isnan(pyval)):\n+ msg = \"invalid value (nan) encountered in {}\"\n+ raise FloatingPointError(msg.format(name))\ndef device_put(x, device_num=0):\n\"\"\"Place a Python value `x` on device number `device_num`.\nThis is a wrapper around jax.lib.xla_bridge.device_put to handle\n- additional Python array types, namely DeviceArray (which is already backed by\n- device memory, though may be on the wrong device) and DeviceConstant. In\n- particular, it avoids transferring data already placed on the correct device,\n- and handles instantiating DeviceConstants.\n+ additional Python types, namely\n+ 1. the array-like types DeviceArray (which is already backed by device\n+ memory, though may be on the wrong device) and its subclass DeviceConstant\n+ (which represents a lazy value to be instantiated), and\n+ 2. the tuple-like types DeviceTuple (which is already backed by device\n+ memory, though may be on the wrong device) and JaxTuple (which may have some\n+ elements that are backed by device memory on the correct device).\n+ In particular, this function avoids transferring data already placed on the\n+ correct device, and handles instantiating DeviceConstants.\nArgs:\n- x: an ndarray, DeviceArray, DeviceConstant, or JaxTuple to be transferred.\n+ x: a tuplelike-tree with arraylike leaves representing the value to be\n+ transferred to the device, where tuplelike means a JaxTuple or\n+ DeviceTuple, and arraylike includes DeviceArray, DeviceConstant, and\n+ anything that has an '__array__' attr.\ndevice_num: an int representing the target physical device number.\nReturns:\nA buffer representing the input `x` placed on the appropriate device.\n\"\"\"\nx = canonicalize_pyval_dtype(x)\n- if type(x) is DeviceArray:\n+ t = type(x)\n+ if t is DeviceArray or t is DeviceTuple:\nif x.device_buffer.device() == device_num:\nreturn x.device_buffer\nelse:\n@@ -109,22 +133,26 @@ def device_put(x, device_num=0):\nreturn device_put(x.device_buffer.to_py(), device_num)\nelif isinstance(x, DeviceConstant):\nreturn instantiate_device_constant(x, device_num=device_num)\n+ elif hasattr(x, '__array__'):\n+ return xb.device_put(x, device_num) # handle arraylikes\n+ elif t is JaxTuple:\n+ # TODO(mattjj, phawkins): for the JaxTuple case, this implementation can\n+ # round-trip tuple elements already on the correct device; consider revising\n+ return xb.device_put(x, device_num)\nelse:\n- return xb.device_put(x, device_num) # round-trips tuple elements\n+ raise TypeError(t)\ndef device_put_many(xs_and_devices):\n\"\"\"Place multiple Python values on multiple devices in parallel.\nThis is a wrapper around jax.lib.xla_bridge.device_put_many to handle\n- additional Python array types, namely DeviceArray (which is already backed by\n- device memory, though may be on the wrong device) and DeviceConstant. In\n- particular, it avoids transferring data already placed on the correct device,\n- and handles instantiating DeviceConstants.\n+ additional Python types. See the docstring for jax.interpreters.xla.device_put\n+ for more information.\nArgs:\n- xs_and_devices: a sequence of (pyval, device_num) pairs where pyval is an\n- ndarray, DeviceArray, DeviceConstant, or JaxTuple and device_num is an int\n- representing the physical device number on which pyval should be placed.\n+ xs_and_devices: a sequence of (pyval, device_num) pairs in which device_num\n+ is an int representing the target physical device number and pyval is a\n+ tuple-like tree with arraylike leaves (see the device_put docstring).\nReturns:\nA sequence of buffers representing the inputs placed on the corresponding\n@@ -135,7 +163,8 @@ def device_put_many(xs_and_devices):\noutputs = [None] * len(xs_and_devices)\nfor i, (x, device_num) in enumerate(xs_and_devices):\nx = canonicalize_pyval_dtype(x)\n- if type(x) is DeviceArray:\n+ t = type(x)\n+ if t is DeviceArray or t is DeviceTuple:\nif x.device_buffer.device() == device_num:\noutputs[i] = x.device_buffer\nelse:\n@@ -145,9 +174,13 @@ def device_put_many(xs_and_devices):\ntransfers.append((x.device_buffer.to_py(), device_num))\nelif isinstance(x, DeviceConstant):\noutputs[i] = instantiate_device_constant(x, device_num=device_num)\n- else:\n+ elif t is onp.ndarray or t is JaxTuple:\n+ # TODO(mattjj, phawkins): for the JaxTuple case, this implementation can\n+ # round-trip tuple elements already on the correct device, revise?\ntransfer_indices.append(i)\ntransfers.append((x, device_num))\n+ else:\n+ raise TypeError(t)\ntransfer_results = xb.device_put_many(transfers)\nfor i, result in zip(transfer_indices, transfer_results):\n@@ -155,28 +188,30 @@ def device_put_many(xs_and_devices):\nreturn outputs\ndef result_handler(result_shape):\n- if type(result_shape) is ResultArray and FLAGS.jax_device_values:\n- if FLAGS.jax_debug_nans and onp.issubdtype(result_shape[1], onp.floating):\n- def handle_result(device_buffer):\n- py_val = device_buffer.to_py()\n- if onp.any(onp.isnan(py_val)):\n- raise FloatingPointError(\"invalid value\")\n+ if FLAGS.jax_device_values:\n+ return device_persistent_result_handler(result_shape)\nelse:\n- return DeviceArray(device_buffer, *result_shape)\n+ return pyval_result_handler(result_shape)\n+\n+def device_persistent_result_handler(result_shape):\n+ t = type(result_shape)\n+ if t is ResultArray:\n+ return lambda buf: DeviceArray(buf, *result_shape)\n+ elif t is ResultTuple:\n+ return DeviceTuple\nelse:\n- def handle_result(device_buffer):\n- return DeviceArray(device_buffer, *result_shape)\n- elif type(result_shape) is ResultArray:\n- def handle_result(device_buffer):\n- return onp.asarray(DeviceArray(device_buffer, *result_shape))\n- elif type(result_shape) is ResultTuple:\n+ raise TypeError(t)\n+\n+def pyval_result_handler(result_shape):\n+ t = type(result_shape)\n+ if t is ResultArray:\n+ return lambda buf: buf.to_py()\n+ elif t is ResultTuple:\nhandlers = list(map(result_handler, result_shape))\n- def handle_result(device_buffer):\n- bufs = device_buffer.destructure()\n- return JaxTuple(handler(buf) for handler, buf in zip(handlers, bufs))\n+ return lambda buf: JaxTuple(h(b) for h, b in zip(handlers, buf.destructure()))\nelse:\n- raise TypeError(type(result_shape))\n- return handle_result\n+ raise TypeError(t)\n+\ndef xla_shape_to_result_shape(xla_shape):\nif xla_shape.is_tuple():\n@@ -275,7 +310,6 @@ translations[core.call_p] = lambda c, subc_a1, *a2: c.Call(subc_a1[0],\nsubc_a1[1] + a2)\ntranslations[core.identity_p] = lambda c, x: x\n-# TODO(mattjj): add_jaxvals should handle any jaxval\ndef zeros_like_translation_rule(c, x):\ndef _zeros_like(shape):\nif shape.is_tuple():\n@@ -284,8 +318,9 @@ def zeros_like_translation_rule(c, x):\nreturn c.Broadcast(c.Constant(onp.array(0, shape.element_type())),\nshape.dimensions())\nreturn _zeros_like(c.GetShape(x))\n-\ntranslations[ad_util.zeros_like_p] = zeros_like_translation_rule\n+\n+# TODO(mattjj): add_jaxvals should handle any jaxval\ntranslations[ad_util.add_jaxvals_p] = lambda c, x, y: c.Add(x, y)\n@@ -333,6 +368,37 @@ class DeviceValue(object):\ndef __init__(self, device_buffer):\nself.device_buffer = device_buffer\n+\n+class DeviceTuple(DeviceValue):\n+ __slots__ = [\"elt_xla_shapes\", \"elt_handlers\"]\n+ def __init__(self, device_buffer):\n+ self.device_buffer = device_buffer\n+ self.elt_xla_shapes = device_buffer.shape().tuple_shapes()\n+ self.elt_handlers = list(map(_tuple_elt_handler, self.elt_xla_shapes))\n+\n+ def __iter__(self):\n+ bufs = self.device_buffer.destructure()\n+ elts = [handler(buf) for handler, buf in zip(self.elt_handlers, bufs)]\n+ return iter(elts)\n+\n+ def __len__(self):\n+ return len(self.elt_xla_shapes)\n+\n+def _tuple_elt_handler(xla_shape):\n+ if xla_shape.is_tuple():\n+ return DeviceTuple\n+ else:\n+ result_shape = xla_shape_to_result_shape(xla_shape)\n+ return lambda buf: DeviceArray(buf, *result_shape)\n+\n+def abstractify_device_tuple(tup):\n+ return AbstractTuple(map(aval_from_xla_shape, tup.elt_xla_shapes))\n+\n+core.pytype_aval_mappings[DeviceTuple] = AbstractTuple\n+pytype_aval_mappings[DeviceTuple] = abstractify_device_tuple\n+canonicalize_dtype_handlers[DeviceTuple] = identity\n+\n+\ndef forward_method(attrname, self, fun, *args):\nreturn fun(getattr(self, attrname), *args)\nforward_to_value = partial(forward_method, \"_value\")\n@@ -423,7 +489,7 @@ def _device_array_constant_handler(c, val, canonicalize_types=True):\nxb.register_constant_handler(DeviceArray, _device_array_constant_handler)\npytype_aval_mappings[ConcreteArray] = make_shaped_array\n-pytype_aval_mappings[ShapedArray] = lambda x: x\n+pytype_aval_mappings[ShapedArray] = identity\nclass DeviceConstant(DeviceArray):\n@@ -456,76 +522,15 @@ def xla_shape(x):\nraise TypeError(type(x))\n-# For callable XLA Computations (as opposed to, e.g., Computations used in the\n-# body of a While) we flatten functions to take multiple array arguments (no\n-# tuple arguments) and return either an array output or a flat tuple output that\n-# is immediately destructured. This flattening avoids the need for the runtime\n-# to manage multiple references to DeviceValues caused by tuple membership\n-# (since the XLA runtime depends on single-ownership, rather than e.g.\n-# refcounting). In particular, we don't have a DeviceTuple representation, and\n-# instead, for values returned to the user, always destructure tuples.\n-# The code here is similar to that in tree_util, but is meant to flatten\n-# JaxTuple trees only.\n-\n-@lu.transformation_with_aux\n-def flatten_fun(in_trees, *flat_args):\n- jtuple_trees = tuple(map(partial(build_tree, iter(flat_args)), in_trees))\n- ans = yield jtuple_trees, {}\n- aval = core.get_aval(ans)\n- if type(aval) is AbstractTuple:\n- ans_flat, out_tree = tree_flatten(ans)\n- yield pack(ans_flat), out_tree\n- else:\n- yield ans, leaf\n-\n-def tree_flatten(maybe_tree):\n- aval = core.get_aval(maybe_tree)\n- return _tree_flatten(aval, maybe_tree)\n-\n-def _tree_flatten(aval, maybe_tree):\n- if type(aval) is AbstractTuple:\n- flat_children, child_specs = unzip2(map(_tree_flatten, aval, maybe_tree))\n- return it.chain.from_iterable(flat_children), JTupleTreeDef(child_specs)\n- elif core.skip_checks or valid_jaxtype(maybe_tree):\n- return [maybe_tree], leaf\n- else:\n- raise TypeError(type(maybe_tree))\n-\n-JTupleTreeDef = namedtuple(\"JTupleTreeDef\", [\"child_specs\"])\n-\n-class Leaf(object):\n- def __repr__(self):\n- return '*'\n-leaf = Leaf()\n-\n-def build_tree(xs, tree_spec):\n- if tree_spec is leaf:\n- return next(xs)\n- elif type(tree_spec) is JTupleTreeDef:\n- return pack(map(partial(build_tree, xs), tree_spec.child_specs))\n- else:\n- raise TypeError(type(tree_spec))\n-\n-\ndef xla_call_impl(fun, *args):\n- flat_args, in_trees = unzip2(map(tree_flatten, args))\n- flat_args = concatenate(flat_args)\n- fun, out_tree = flatten_fun(fun, in_trees)\n-\n- compiled_fun = xla_callable(fun, *map(abstractify, flat_args))\n+ compiled_fun = xla_callable(fun, *map(abstractify, args))\ntry:\n- flat_ans = compiled_fun(*flat_args)\n+ return compiled_fun(*args)\nexcept FloatingPointError:\n- msg = (\"Invalid value encountered in the output of a jit function. \"\n+ print(\"Invalid value encountered in the output of a jit function. \"\n\"Calling the de-optimized version.\")\n- print(msg)\nreturn fun.call_wrapped(*args) # probably won't return\n- if out_tree() is leaf:\n- return flat_ans\n- else:\n- return build_tree(iter(flat_ans), out_tree())\n-\n@lu.memoize\ndef xla_callable(fun, *abstract_args):\n@@ -541,6 +546,7 @@ def xla_callable(fun, *abstract_args):\ndef execute_compiled(compiled, pval, handle_result, *args):\ninput_bufs = [device_put(x) for x in args]\nout_buf = compiled.Execute(input_bufs, not core.skip_checks)\n+ check_nans(\"jit-compiled computation\", out_buf)\nreturn pe.merge_pvals(handle_result(out_buf), pval)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1265,8 +1265,6 @@ for t in itertools.chain(array_types, [xla.DeviceArray]):\nad_util.jaxval_adders[t] = add\nad_util.jaxval_zeros_likers[xla.DeviceArray] = zeros_like_array\n-batching.pytype_aval_mappings[xla.DeviceArray] = make_shaped_array\n-\n### primitives\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -58,6 +58,14 @@ RTOL = 1e-4\n_dtype = lambda x: getattr(x, 'dtype', None) or onp.asarray(x).dtype\n+def is_sequence(x):\n+ try:\n+ iter(x)\n+ except TypeError:\n+ return False\n+ else:\n+ return True\n+\ndef numpy_eq(x, y):\ntesting_tpu = FLAGS.jax_test_dut and FLAGS.jax_test_dut.startswith(\"tpu\")\ntesting_x32 = not FLAGS.jax_enable_x64\n@@ -437,23 +445,23 @@ class JaxTestCase(parameterized.TestCase):\ndef assertAllClose(self, x, y, check_dtypes, atol=None, rtol=None):\n\"\"\"Assert that x and y, either arrays or nested tuples/lists, are close.\"\"\"\n- if isinstance(x, (tuple, list)):\n- self.assertIsInstance(y, (tuple, list))\n- self.assertEqual(len(x), len(y))\n- for x_elt, y_elt in zip(x, y):\n- self.assertAllClose(x_elt, y_elt, check_dtypes, atol=atol, rtol=rtol)\n- elif isinstance(x, dict):\n+ if isinstance(x, dict):\nself.assertIsInstance(y, dict)\nself.assertEqual(set(x.keys()), set(y.keys()))\nfor k in x.keys():\nself.assertAllClose(x[k], y[k], check_dtypes, atol=atol, rtol=rtol)\n- else:\n- is_array = lambda x: hasattr(x, '__array__') or onp.isscalar(x)\n- self.assertTrue(is_array(x))\n- self.assertTrue(is_array(y))\n+ elif is_sequence(x) and not hasattr(x, '__array__'):\n+ self.assertTrue(is_sequence(y) and not hasattr(y, '__array__'))\n+ self.assertEqual(len(x), len(y))\n+ for x_elt, y_elt in zip(x, y):\n+ self.assertAllClose(x_elt, y_elt, check_dtypes, atol=atol, rtol=rtol)\n+ elif hasattr(x, '__array__') or onp.isscalar(x):\n+ self.assertTrue(hasattr(y, '__array__') or onp.isscalar(y))\nx = onp.asarray(x)\ny = onp.asarray(y)\nself.assertArraysAllClose(x, y, check_dtypes, atol=atol, rtol=rtol)\n+ else:\n+ raise TypeError((type(x), type(y)))\ndef _CompileAndCheck(self, fun, args_maker, check_dtypes,\nrtol=None, atol=None):\n"
}
] | Python | Apache License 2.0 | google/jax | add DeviceTuples for device-persistent tuples |
260,335 | 01.05.2019 14:17:25 | 25,200 | a8d4db071e827a9bcd06387d0728fb30105d7e72 | improve xla.device_put on JaxTuples | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -136,9 +136,8 @@ def device_put(x, device_num=0):\nelif hasattr(x, '__array__'):\nreturn xb.device_put(x, device_num) # handle arraylikes\nelif t is JaxTuple:\n- # TODO(mattjj, phawkins): for the JaxTuple case, this implementation can\n- # round-trip tuple elements already on the correct device; consider revising\n- return xb.device_put(x, device_num)\n+ element_bufs = tuple(map(partial(device_put, device_num=device_num), x))\n+ return xb.make_tuple(element_bufs, device_num)\nelse:\nraise TypeError(t)\n@@ -207,7 +206,7 @@ def pyval_result_handler(result_shape):\nif t is ResultArray:\nreturn lambda buf: buf.to_py()\nelif t is ResultTuple:\n- handlers = list(map(result_handler, result_shape))\n+ handlers = list(map(pyval_result_handler, result_shape))\nreturn lambda buf: JaxTuple(h(b) for h, b in zip(handlers, buf.destructure()))\nelse:\nraise TypeError(t)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -186,6 +186,9 @@ def device_put_many(pyvals_and_devices):\nelse:\nreturn [device_put(pyval, device) for (pyval, device) in pyvals_and_devices]\n+def make_tuple(bufs, device_num=0):\n+ return xla_client.Buffer.make_tuple(bufs, device=device_num)\n+\nShape = xla_client.Shape # pylint: disable=invalid-name\n"
}
] | Python | Apache License 2.0 | google/jax | improve xla.device_put on JaxTuples |
260,335 | 01.05.2019 14:30:08 | 25,200 | 1275370c9e0349e07e564c778f97ad9d6e1901a3 | fix JaxTuple branch of xla.device_put_many | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -173,11 +173,13 @@ def device_put_many(xs_and_devices):\ntransfers.append((x.device_buffer.to_py(), device_num))\nelif isinstance(x, DeviceConstant):\noutputs[i] = instantiate_device_constant(x, device_num=device_num)\n- elif t is onp.ndarray or t is JaxTuple:\n- # TODO(mattjj, phawkins): for the JaxTuple case, this implementation can\n- # round-trip tuple elements already on the correct device, revise?\n+ elif hasattr(t, '__array__'):\ntransfer_indices.append(i)\n- transfers.append((x, device_num))\n+ transfers.append((x, device_num)) # handle arraylikes\n+ elif t is JaxTuple:\n+ # TODO(mattjj,phawkins): improve this to avoid device_put call\n+ element_bufs = tuple(map(partial(device_put, device_num=device_num), x))\n+ outputs[i] = xb.make_tuple(element_bufs, device_num)\nelse:\nraise TypeError(t)\n"
}
] | Python | Apache License 2.0 | google/jax | fix JaxTuple branch of xla.device_put_many |
260,335 | 01.05.2019 15:00:45 | 25,200 | cfb5345fd0c3e3d0c060260a30592965e5b82d2b | fix bugs in ShardedDeviceArray.__init__ | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -343,8 +343,8 @@ class ShardedDeviceArray(xla.DeviceArray):\nxla_shape = device_buffers[0].shape()\nself.shape = (axis_size,) + tuple(xla_shape.dimensions())\nself.dtype = xla_shape.element_type()\n- self.ndim = 1 + len(self.shape)\n- self.size = axis_size * prod(self.shape)\n+ self.ndim = len(self.shape)\n+ self.size = prod(self.shape)\nself._npy_value = None\n@property\n"
}
] | Python | Apache License 2.0 | google/jax | fix bugs in ShardedDeviceArray.__init__ |
260,335 | 01.05.2019 19:32:48 | 25,200 | 3f638d3a40d0e1768ce004608017898164bdc32e | make JaxTuple not subclass tuple, add docstrings | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -440,18 +440,34 @@ pytype_aval_mappings = {}\n# ------------------- Products -------------------\n-class JaxTuple(tuple):\n- def __new__(cls, xs):\n+# We set up a registry of tuple types so that we can control the behavior of\n+# isinstance(val, JaxTuple) without subclassing JaxTuple, which can be difficult\n+# when slots are defined and multiple inheritance is necessary.\n+class _TupleMeta(type(tuple)):\n+ def __instancecheck__(self, instance):\n+ return type(instance) in tuple_types\n+tuple_types = set()\n+\n+class JaxTuple(six.with_metaclass(_TupleMeta)):\n+ __slots__ = ['xs']\n+\n+ def __init__(self, xs):\n+ self.xs = xs = tuple(xs)\nif not skip_checks:\n- xs = list(xs)\nassert all(map(valid_jaxtype, xs)), xs\n- return tuple.__new__(cls, xs)\n+\n+ def __iter__(self):\n+ return iter(self.xs)\n+\n+ def __len__(self):\n+ return len(self.xs)\ndef __repr__(self):\nif self is unit:\nreturn unitvar\nelse:\nreturn 'JaxTuple({})'.format(','.join(map(repr, self)))\n+tuple_types.add(JaxTuple)\nclass AbstractTuple(AbstractValue, tuple):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -309,7 +309,7 @@ def _dimsize(dim, aval, x):\ndef moveaxis(sz, dst, src, x, force_broadcast=True):\nreturn _moveaxis(sz, dst, src, get_aval(x), x, force_broadcast)\n-# TODO(mattjj): not passing forece_broadcast recursively... intentional?\n+# TODO(mattjj): not passing force_broadcast recursively... intentional?\ndef _moveaxis(sz, dst, src, aval, x, force_broadcast=True):\nif type(aval) is AbstractTuple:\nif type(src) is tuple and type(dst) is tuple:\n@@ -342,7 +342,7 @@ def _moveaxis(sz, dst, src, aval, x, force_broadcast=True):\ndef broadcast(x, sz, force_broadcast=False):\nreturn _broadcast(sz, get_aval(x), x, force_broadcast)\n-# TODO(mattjj): not passing forece_broadcast recursively... intentional?\n+# TODO(mattjj): not passing force_broadcast recursively... intentional?\ndef _broadcast(sz, aval, x, force_broadcast=False):\nif type(aval) is AbstractTuple:\nreturn pack(map(partial(_broadcast, sz), aval, x))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -308,6 +308,26 @@ def _map(f, *xs):\nclass ShardedDeviceTuple(xla.DeviceTuple):\n+ \"\"\"A ShardedDeviceTuple is a JaxTuple sharded across devices.\n+\n+ The purpose of a ShardedDeviceTuple is to reduce the number of transfers when\n+ executing replicated computations, by allowing results to persist on the\n+ devices that produced them. That way dispatching a similarly replicated\n+ computation that consumes the same sharded memory layout does not incur any\n+ transfers.\n+\n+ A ShardedDeviceTuple represents one logical JaxTuple value, and simulates the\n+ behavior of a JaxTuple so that it can be treated by user code as a JaxTuple;\n+ that is, it is only an optimization to reduce transfers.\n+\n+ The number of device buffers underlying a ShardedDeviceTuple instance is equal\n+ to the number of replicas of the computation that produced it. Each buffer\n+ represents a shard of the logical tuple value represented by the\n+ ShardedDeviceTuple, where a shard of an array is a slice along its leading\n+ axis, and a shard of a tuple is a tuple of corresponding shards of its\n+ elements. These component buffers reside on distinct devices, but need not\n+ represent distinct logical shards.\n+ \"\"\"\n__slots__ = [\"axis_size\", \"device_buffers\"]\ndef __init__(self, axis_size, device_buffers):\n@@ -315,6 +335,9 @@ class ShardedDeviceTuple(xla.DeviceTuple):\nself.device_buffers = device_buffers\ndef __iter__(self):\n+ # To destructure, we destructure the constituent buffers on each device,\n+ # then logically concatenate those shards across devices producing one\n+ # logically concatenated result per element.\nall_bufs = zip(*[buf.destructure() for buf in self.device_buffers])\nelts = [_tuple_elt_handler(self.axis_size, bufs) for bufs in all_bufs]\nreturn iter(elts)\n@@ -335,6 +358,25 @@ xla.canonicalize_dtype_handlers[ShardedDeviceTuple] = \\\nclass ShardedDeviceArray(xla.DeviceArray):\n+ \"\"\"A ShardedDeviceArray is an ndarray sharded across devices.\n+\n+ The purposes of a ShardedDeviceArray is to reduce the number of transfers when\n+ executing replicated computations, by allowing results to persist on the\n+ devices that produced them. That way dispatching a similarly replicated\n+ computation that consumes the same sharded memory layout does not incur any\n+ transfers.\n+\n+ A ShardedDeviceArray represents one logical ndarray value, and simulates the\n+ behavior of an ndarray so that it can be treated by user code as an ndarray;\n+ that is, it is only an optimizatoin to reduce transfers.\n+\n+ The number of device buffers underlying a ShardedDeviceArray instance is equal\n+ to the number of replicas of the computation that produced it. Each buffer\n+ represents a shard of the original array, meaning a slice along its leading\n+ axis. These component buffers reside on distinct devices, but need not\n+ represent distinct logical shards. The correspondence can be computed with\n+ the assign_shards_to_replicas function.\n+ \"\"\"\n__slots__ = [\"device_buffers\"]\ndef __init__(self, axis_size, device_buffers):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -365,13 +365,15 @@ for t in array_types:\nclass DeviceValue(object):\n+ \"\"\"A DeviceValue represents a value backed by device memory.\"\"\"\n__slots__ = [\"device_buffer\"]\ndef __init__(self, device_buffer):\nself.device_buffer = device_buffer\n-\nclass DeviceTuple(DeviceValue):\n+ \"\"\"A DeviceTuple is a JaxTuple backed by a single device memory buffer.\"\"\"\n__slots__ = [\"elt_xla_shapes\", \"elt_handlers\"]\n+\ndef __init__(self, device_buffer):\nself.device_buffer = device_buffer\nself.elt_xla_shapes = device_buffer.shape().tuple_shapes()\n@@ -385,6 +387,10 @@ class DeviceTuple(DeviceValue):\ndef __len__(self):\nreturn len(self.elt_xla_shapes)\n+ def __repr__(self):\n+ return 'DeviceTuple[{}]'.format(len(self.elt_xla_shapes))\n+core.tuple_types.add(DeviceTuple)\n+\ndef _tuple_elt_handler(xla_shape):\nif xla_shape.is_tuple():\nreturn DeviceTuple\n@@ -405,6 +411,9 @@ def forward_method(attrname, self, fun, *args):\nforward_to_value = partial(forward_method, \"_value\")\nclass DeviceArray(DeviceValue):\n+ \"\"\"A DeviceArray is an ndarray backed by a single device memory buffer.\"\"\"\n+ # We don't subclass ndarray because that would open up a host of issues,\n+ # but lax_numpy.py overrides isinstance behavior and attaches ndarray methods.\n__slots__ = [\"shape\", \"dtype\", \"ndim\", \"size\", \"_npy_value\"]\n__array_priority__ = 100.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -25,9 +25,9 @@ from jax import test_util as jtu\nimport jax.numpy as np\nfrom jax import jit, grad, device_get, device_put, jacfwd, jacrev, hessian\nfrom jax import api\n-from jax.core import Primitive\n+from jax.core import Primitive, pack, JaxTuple\nfrom jax.interpreters.ad import defjvp, defvjp, defvjp2, defvjp_all\n-from jax.interpreters.xla import DeviceArray\n+from jax.interpreters.xla import DeviceArray, DeviceTuple\nfrom jax.abstract_arrays import concretization_err_msg\nfrom jax.config import config\n@@ -537,6 +537,16 @@ class APITest(jtu.JaxTestCase):\nself.assertAllClose(grad_ans, 3. * 4. + onp.cos(onp.sin(3. * 4)),\ncheck_dtypes=False)\n+ def test_devicetuple_iteration(self):\n+ tup = device_put(pack((1, 2)))\n+ self.assertIsInstance(tup, DeviceTuple)\n+ self.assertEqual(tuple(tup), (1, 2))\n+\n+ def test_devicetuple_isinstance(self):\n+ tup = device_put(pack((1, 2)))\n+ self.assertIsInstance(tup, DeviceTuple)\n+ self.assertIsInstance(tup, JaxTuple)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | make JaxTuple not subclass tuple, add docstrings |
260,335 | 01.05.2019 19:36:32 | 25,200 | 00a43e721af1ce64ec9705e190a3a704ebca1bcb | comment that DeviceValues don't get canonicalized | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -403,6 +403,8 @@ def abstractify_device_tuple(tup):\ncore.pytype_aval_mappings[DeviceTuple] = AbstractTuple\npytype_aval_mappings[DeviceTuple] = abstractify_device_tuple\n+# DeviceValues don't need to be canonicalized because we assume values on the\n+# device have already been canonicalized.\ncanonicalize_dtype_handlers[DeviceTuple] = identity\n@@ -492,6 +494,8 @@ class DeviceArray(DeviceValue):\ncore.pytype_aval_mappings[DeviceArray] = ConcreteArray\npytype_aval_mappings[DeviceArray] = make_shaped_array\n+# DeviceValues don't need to be canonicalized because we assume values on the\n+# device have already been canonicalized.\ncanonicalize_dtype_handlers[DeviceArray] = identity\ndef _device_array_constant_handler(c, val, canonicalize_types=True):\n"
}
] | Python | Apache License 2.0 | google/jax | comment that DeviceValues don't get canonicalized |
260,335 | 01.05.2019 19:45:17 | 25,200 | 21118d0dff9b8b51c6333cd34e43a2b0a1f75e12 | make isinstance(sharded_device_tup, JaxTuple) true | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -341,6 +341,7 @@ class ShardedDeviceTuple(xla.DeviceTuple):\nall_bufs = zip(*[buf.destructure() for buf in self.device_buffers])\nelts = [_tuple_elt_handler(self.axis_size, bufs) for bufs in all_bufs]\nreturn iter(elts)\n+core.tuple_types.add(ShardedDeviceTuple)\ndef _tuple_elt_handler(axis_size, bufs):\nis_tuple = {buf.shape().is_tuple() for buf in bufs}\n"
}
] | Python | Apache License 2.0 | google/jax | make isinstance(sharded_device_tup, JaxTuple) true |
260,335 | 02.05.2019 08:02:01 | 25,200 | 87a150e567a4c6e6ced207278cd72b3ee2d3d1c2 | add a tree_util.py module-level docstring | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "# limitations under the License.\n\"\"\"\n-User-facing transformations.\n+JAX user-facing transformations and utilities.\n-These mostly wrap internal transformations, providing convenience flags to\n-control behavior and handling Python containers (tuples/lists/dicts) of\n-arguments and outputs.\n+The transformations here mostly wrap internal transformations, providing\n+convenience flags to control behavior and handling Python containers of\n+arguments and outputs. The Python containers handled are pytrees (see\n+tree_util.py), which include nested tuples/lists/dicts, where the leaves are\n+arrays or JaxTuples.\n\"\"\"\nfrom __future__ import absolute_import\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/tree_util.py",
"new_path": "jax/tree_util.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+\"\"\"Utilities for working with tree-like container data structures.\n+\n+The code here is independent of JAX. The only dependence is on jax.util, which\n+itself has no JAX-specific code.\n+\n+This module provides a small set of utility functions for working with tree-like\n+data structures, such as nested tuples, lists, and dicts. We call these\n+structures pytrees. They are trees in that they are defined recursively (any\n+non-pytree is a pytree, i.e. a leaf, and any pytree of pytrees is a pytree) and\n+can be operated on recursively (object identity equivalence is not preserved by\n+mapping operations, and the structures cannot contain reference cycles).\n+\n+The set of Python types that are considered pytree nodes (e.g. that can be\n+mapped over, rather than treated as leaves) is extensible. There is a single\n+module-level registry of types, and class hierarchy is ignored. By registering a\n+new pytree node type, that type in effect becomes transparent to the utility\n+functions in this file.\n+\"\"\"\n+\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n"
}
] | Python | Apache License 2.0 | google/jax | add a tree_util.py module-level docstring |
260,335 | 02.05.2019 19:27:22 | 25,200 | ddd29e724eef6920a0e0c629f5e4cf916ca6c3a3 | fix DeviceArray.__repr__ for complex dtypes, test
c.f. | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2333,6 +2333,8 @@ for method_name in _nondiff_methods + _diff_methods:\nsetattr(ShapedArray, \"reshape\", core.aval_method(_reshape))\nsetattr(ShapedArray, \"flatten\", core.aval_method(ravel))\nsetattr(ShapedArray, \"T\", core.aval_property(transpose))\n+setattr(ShapedArray, \"real\", core.aval_property(real))\n+setattr(ShapedArray, \"imag\", core.aval_property(imag))\nsetattr(ShapedArray, \"astype\", core.aval_method(lax.convert_element_type))\n@@ -2345,6 +2347,8 @@ for method_name in _nondiff_methods + _diff_methods:\nsetattr(DeviceArray, \"reshape\", _reshape)\nsetattr(DeviceArray, \"flatten\", ravel)\nsetattr(DeviceArray, \"T\", property(transpose))\n+setattr(DeviceArray, \"real\", property(real))\n+setattr(DeviceArray, \"imag\", property(imag))\nsetattr(DeviceArray, \"astype\", lax.convert_element_type)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -537,6 +537,15 @@ class APITest(jtu.JaxTestCase):\nself.assertAllClose(grad_ans, 3. * 4. + onp.cos(onp.sin(3. * 4)),\ncheck_dtypes=False)\n+ def test_devicearray_repr(self):\n+ x = device_put(np.zeros(3))\n+ self.assertIsInstance(x, DeviceArray)\n+ repr(x) # doesn't crash\n+\n+ x = device_put(np.ones(3) + 1j * np.ones(3))\n+ self.assertIsInstance(x, DeviceArray)\n+ repr(x) # doesn't crash\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix DeviceArray.__repr__ for complex dtypes, test
c.f. #666 |
260,335 | 02.05.2019 22:13:49 | 25,200 | 7c5d683915b6ca531776cbabc10b58c26a7c83e2 | revise sharded result handling, misc cleanup | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -496,13 +496,7 @@ def pmap(fun, axis_name=None):\n@wraps(fun)\ndef f_jitted(*args, **kwargs):\n- leaves, _ = tree_flatten(args)\n- axis_sizes = set(onp.shape(leaf)[0] for leaf in leaves)\n- if len(axis_sizes) != 1:\n- msg = \"pmap requires all leading axes to have equal length, got {}.\"\n- raise TypeError(msg.format(axis_sizes))\n- axis_size = axis_sizes.pop()\n-\n+ axis_size = _pmap_axis_size(args)\nf = lu.wrap_init(fun)\njaxtuple_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\njaxtuple_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))\n@@ -516,6 +510,26 @@ def pmap(fun, axis_name=None):\nf_jitted.__name__ = namestr(f_jitted.__name__, axis_name)\nreturn f_jitted\n+def _pmap_axis_size(args):\n+ leaves, _ = tree_flatten(args)\n+ axis_sizes = reduce(set.union, map(_jaxtype_axis_size, leaves), set())\n+ if len(axis_sizes) == 0:\n+ raise TypeError(\"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 TypeError(msg.format(axis_sizes))\n+ return axis_sizes.pop()\n+\n+def _jaxtype_axis_size(x):\n+ return _aval_axis_size(core.get_aval(x))\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+ return {aval.shape[0]}\n+\n+\ndef _serial_pmap(fun, axis_name=None, in_axes=0, out_axes=0):\n\"\"\"Vectorizing pseudo-map for single-program multiple-data (SPMD) functions.\"\"\"\naxis_name = _TempAxisName() if axis_name is None else axis_name\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -445,8 +445,7 @@ pytype_aval_mappings = {}\n# when slots are defined and multiple inheritance is necessary.\nclass _TupleMeta(type(tuple)):\ndef __instancecheck__(self, instance):\n- return type(instance) in tuple_types\n-tuple_types = set()\n+ return type(get_aval(instance)) is AbstractTuple\nclass JaxTuple(six.with_metaclass(_TupleMeta)):\n__slots__ = ['xs']\n@@ -467,7 +466,6 @@ class JaxTuple(six.with_metaclass(_TupleMeta)):\nreturn unitvar\nelse:\nreturn 'JaxTuple({})'.format(','.join(map(repr, self)))\n-tuple_types.add(JaxTuple)\nclass AbstractTuple(AbstractValue, tuple):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -201,7 +201,7 @@ def shaped_jaxtuple(xs):\nreturn AbstractTuple(map(shaped_aval, xs))\npytype_aval_mappings[JaxTuple] = shaped_jaxtuple\n-pytype_aval_mappings[xla.DeviceTuple] = xla.abstractify_device_tuple\n+pytype_aval_mappings[xla.DeviceTuple] = xla.pytype_aval_mappings[xla.DeviceTuple]\nfor t in it.chain(array_types, [xla.DeviceArray]):\npytype_aval_mappings[t] = make_shaped_array\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -18,6 +18,7 @@ from __future__ import print_function\nfrom collections import namedtuple\nimport itertools as it\n+import operator as op\nimport numpy as onp\nimport six\n@@ -83,52 +84,60 @@ def _slice(x, i):\nreturn x[i]\n-def unshard_output(axis_size, replica_results):\n- \"\"\"Collect together replica results into a result value.\n-\n- Args:\n- axis_size: size of the sharded output data axis.\n- replica_results: list of JaxTypes of length equal to the number of replicas\n- representing their respective results and which together represent the\n- value to be unsharded.\n+def sharded_result_handler(axis_size, aval):\n+ full_aval = add_axis_to_aval(axis_size, aval)\n+ t = type(aval)\n+ if t is ShapedArray:\n+ return partial(sharded_array_result_handler, full_aval)\n+ elif t is core.AbstractTuple:\n+ return partial(sharded_tuple_result_handler, axis_size, full_aval)\n+ else:\n+ raise TypeError(t)\n- Returns:\n- A JaxType representing the single stacked logical result of the computation,\n- possibly maintained as a lazy sharded type.\n- \"\"\"\n- types = {type(result) for result in replica_results}\n- assert len(types) == 1\n- t = types.pop()\n+def sharded_array_result_handler(aval, replica_results):\n+ t, = set(map(type, replica_results))\nif t is xla.DeviceArray:\nbufs = [r.device_buffer for r in replica_results]\n- return ShardedDeviceArray(axis_size, bufs)\n- elif t is xla.DeviceTuple:\n+ return ShardedDeviceArray(aval, bufs)\n+ elif issubclass(t, (onp.ndarray, xla.DeviceConstant, ShardedDeviceArray)):\n+ assignments = assign_shards_to_replicas(len(replica_results), aval.shape[0])\n+ _, ids = onp.unique(assignments, return_index=True)\n+ return onp.stack([replica_results[i] for i in ids])\n+ else:\n+ raise TypeError(t)\n+\n+def sharded_tuple_result_handler(axis_size, aval, replica_results):\n+ t, = set(map(type, replica_results))\n+ if t is xla.DeviceTuple:\nbufs = [r.device_buffer for r in replica_results]\n- return ShardedDeviceTuple(axis_size, bufs)\n+ return ShardedDeviceTuple(axis_size, aval, bufs)\nelif t is core.JaxTuple:\n- # A JaxTuple can result from merging pvals, for example\n- # pmap(lambda x: pack((3, x)))(...)\n- # To avoid the complexity of DeviceTuples having mixed host/device elements,\n- # we instead pull everything back to the host.\n- # TODO(mattjj): can improve this policy to enable more device-persistence\n- return _stack(axis_size, replica_results)\n+ # e.g. pmap(lambda x: core.pack((3, x)))(...)\n+ reduced_aval = remove_axis_from_aval(aval)\n+ all_results = zip(*replica_results)\n+ return core.pack([sharded_result_handler(axis_size, elt_aval)(results)\n+ for elt_aval, results in zip(reduced_aval, all_results)])\nelse:\n- # This case can obtain if t is a host-backed type like an onp.ndarray or\n- # Python int, e.g. from pmap(lambda x: 3)(...). Just stack in host memory.\n- return _stack(axis_size, replica_results)\n-\n-def _stack(axis_size, replica_results):\n- \"\"\"Stack replica_results to produce a result in host memory.\"\"\"\n- types = {type(result) for result in replica_results}\n- assert len(types) == 1\n- t = types.pop()\n- if t is core.JaxTuple or t is xla.DeviceTuple:\n- results = zip(*replica_results)\n- return core.pack(map(partial(_stack, axis_size), results))\n+ raise TypeError(t)\n+\n+\n+def add_axis_to_aval(n, aval):\n+ t = type(aval)\n+ if t is core.AbstractTuple:\n+ return core.AbstractTuple(map(partial(add_axis_to_aval, n), aval))\n+ elif t is ShapedArray:\n+ return ShapedArray((n,) + aval.shape, aval.dtype)\nelse:\n- assignments = assign_shards_to_replicas(len(replica_results), axis_size)\n- _, ids = onp.unique(assignments, return_index=True)\n- return onp.stack([replica_results[i] for i in ids])\n+ raise TypeError(t)\n+\n+def remove_axis_from_aval(aval):\n+ t = type(aval)\n+ if t is core.AbstractTuple:\n+ return core.AbstractTuple(map(remove_axis_from_aval, aval))\n+ elif t is ShapedArray:\n+ return ShapedArray(aval.shape[1:], aval.dtype)\n+ else:\n+ raise TypeError(t)\ndef assign_shards_to_replicas(nrep, size):\n@@ -328,32 +337,42 @@ class ShardedDeviceTuple(xla.DeviceTuple):\nelements. These component buffers reside on distinct devices, but need not\nrepresent distinct logical shards.\n\"\"\"\n- __slots__ = [\"axis_size\", \"device_buffers\"]\n+ __slots__ = [\"device_buffers\", \"axis_size\", \"aval\"]\n- def __init__(self, axis_size, device_buffers):\n- self.axis_size = axis_size\n+ def __init__(self, axis_size, aval, device_buffers):\n+ assert device_buffers\nself.device_buffers = device_buffers\n+ self.axis_size = axis_size\n+ self.aval = aval\n+ # To destructure, we destructure the constituent buffers on each device, then\n+ # logically concatenate those shards across devices producing one logically\n+ # concatenated result per element. The logical concatenation is performed with\n+ # the result handler logic applied to the elements.\ndef __iter__(self):\n- # To destructure, we destructure the constituent buffers on each device,\n- # then logically concatenate those shards across devices producing one\n- # logically concatenated result per element.\nall_bufs = zip(*[buf.destructure() for buf in self.device_buffers])\n- elts = [_tuple_elt_handler(self.axis_size, bufs) for bufs in all_bufs]\n+ handlers = map(partial(tuple_element_handler, self.axis_size), self.aval)\n+ elts = [handler(bufs) for handler, bufs in zip(handlers, all_bufs)]\nreturn iter(elts)\n-core.tuple_types.add(ShardedDeviceTuple)\n-def _tuple_elt_handler(axis_size, bufs):\n- is_tuple = {buf.shape().is_tuple() for buf in bufs}\n- assert len(is_tuple) == 1\n- if is_tuple.pop():\n- return ShardedDeviceTuple(axis_size, bufs)\n+ def __len__(self):\n+ return len(self.device_buffers[0].destructure())\n+\n+ def __repr__(self):\n+ return 'ShardedDeviceTuple(len={length})'.format(length=len(self))\n+\n+def tuple_element_handler(axis_size, aval):\n+ t = type(aval)\n+ if t is core.AbstractTuple:\n+ return partial(ShardedDeviceTuple, axis_size, aval)\n+ elif t is ShapedArray:\n+ return partial(ShardedDeviceArray, aval)\nelse:\n- return ShardedDeviceArray(axis_size, bufs)\n+ raise TypeError(t)\n+\ncore.pytype_aval_mappings[ShardedDeviceTuple] = core.AbstractTuple\n-xla.pytype_aval_mappings[ShardedDeviceTuple] = \\\n- xla.pytype_aval_mappings[xla.DeviceTuple]\n+xla.pytype_aval_mappings[ShardedDeviceTuple] = op.attrgetter('aval')\nxla.canonicalize_dtype_handlers[ShardedDeviceTuple] = \\\nxla.canonicalize_dtype_handlers[xla.DeviceTuple]\n@@ -380,14 +399,10 @@ class ShardedDeviceArray(xla.DeviceArray):\n\"\"\"\n__slots__ = [\"device_buffers\"]\n- def __init__(self, axis_size, device_buffers):\n+ def __init__(self, aval, device_buffers):\nself.device_buffers = device_buffers\n-\n- xla_shape = device_buffers[0].shape()\n- self.shape = (axis_size,) + tuple(xla_shape.dimensions())\n- self.dtype = xla_shape.element_type()\n- self.ndim = len(self.shape)\n- self.size = prod(self.shape)\n+ self.shape, self.dtype = aval.shape, aval.dtype\n+ self.ndim, self.size = len(aval.shape), prod(aval.shape)\nself._npy_value = None\n@property\n@@ -436,19 +451,31 @@ def parallel_callable(fun, axis_name, axis_size, *avals):\njaxpr, (pval, consts, env) = trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)\nassert not env\nout = compile_replicated(jaxpr, axis_name, axis_size, consts, *avals)\n- compiled, nrep, result_shape = out\n+ compiled, nrep, shard_result_shape = out\ndel master, consts, jaxpr, env\nhandle_arg = partial(shard_arg, compiled._device_ordinals, axis_size)\n- handle_result = xla.result_handler(result_shape)\n- return partial(execute_replicated, compiled, pval, axis_size, nrep,\n- handle_arg, handle_result)\n+ handle_replica_result = xla.result_handler(shard_result_shape)\n+ handle_full_result = sharded_result_handler(axis_size, merged_aval(pval))\n+ return partial(execute_replicated, compiled, pval, nrep,\n+ handle_arg, handle_replica_result, handle_full_result)\n+\n+def merged_aval(pval):\n+ pv, const = pval\n+ if isinstance(pv, core.AbstractValue):\n+ return pv\n+ elif isinstance(pv, pe.JaxprTracerTuple):\n+ return core.AbstractTuple(map(merged_aval, zip(pv, const)))\n+ elif pv is None:\n+ return xla.abstractify(const)\n+ else:\n+ raise TypeError(type(pv))\n-def execute_replicated(compiled, pval, axis_size, nrep, handle_in, handle_out,\n- *args):\n+def execute_replicated(compiled, pval, nrep, handle_in,\n+ handle_replica_result, handle_full_result, *args):\ninput_bufs = zip(*map(handle_in, args)) if args else [[]] * nrep\nout_bufs = compiled.ExecutePerReplica(input_bufs)\n- replica_results = [merge_pvals(handle_out(buf), pval) for buf in out_bufs]\n- return unshard_output(axis_size, replica_results)\n+ results = [merge_pvals(handle_replica_result(buf), pval) for buf in out_bufs]\n+ return handle_full_result(results)\nxla_pmap_p = core.Primitive('xla_pmap')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -133,9 +133,9 @@ def device_put(x, device_num=0):\nreturn device_put(x.device_buffer.to_py(), device_num)\nelif isinstance(x, DeviceConstant):\nreturn instantiate_device_constant(x, device_num=device_num)\n- elif hasattr(x, '__array__'):\n+ elif isinstance(x, (DeviceArray, onp.ndarray)):\nreturn xb.device_put(x, device_num) # handle arraylikes\n- elif t is JaxTuple:\n+ elif isinstance(x, JaxTuple):\nelement_bufs = tuple(map(partial(device_put, device_num=device_num), x))\nreturn xb.make_tuple(element_bufs, device_num)\nelse:\n@@ -188,6 +188,30 @@ def device_put_many(xs_and_devices):\noutputs[i] = result\nreturn outputs\n+\n+# When we execute an XLA computation, we get a raw device buffer back and need\n+# to package it into a suitable Python object to return to the user. To avoid\n+# unnecessary device-to-host transfers, we typically return a DeviceValue that\n+# acts just like a familiar Python type (e.g. an ndarray or JaxTuple) but is\n+# lazy in that it only copies data back to the host as required. Since the same\n+# DeviceValue type is formed on every execution of a compiled computation, at\n+# compile time we set up result handler functions and thus avoid redoing some of\n+# the Python bookkeeping work on every execution. Since XLA shapes are slower to\n+# manipulate than simple Python builtins, we store the metadata required for\n+# forming the DeviceValue result in special ResultArray / ResultTuple classes.\n+\n+def xla_shape_to_result_shape(xla_shape):\n+ if xla_shape.is_tuple():\n+ aval = aval_from_xla_shape(xla_shape)\n+ result_shapes = tuple(map(xla_shape_to_result_shape, xla_shape.tuple_shapes()))\n+ return ResultTuple((aval, result_shapes))\n+ else:\n+ shape, dtype = xla_shape.dimensions(), xla_shape.element_type()\n+ ndim, size = len(shape), prod(shape)\n+ return ResultArray((shape, dtype, ndim, size))\n+class ResultTuple(tuple): pass\n+class ResultArray(tuple): pass\n+\ndef result_handler(result_shape):\nif FLAGS.jax_device_values:\nreturn device_persistent_result_handler(result_shape)\n@@ -197,9 +221,9 @@ def result_handler(result_shape):\ndef device_persistent_result_handler(result_shape):\nt = type(result_shape)\nif t is ResultArray:\n- return lambda buf: DeviceArray(buf, *result_shape)\n+ return partial(DeviceArray, result_shape)\nelif t is ResultTuple:\n- return DeviceTuple\n+ return partial(DeviceTuple, result_shape)\nelse:\nraise TypeError(t)\n@@ -214,17 +238,6 @@ def pyval_result_handler(result_shape):\nraise TypeError(t)\n-def xla_shape_to_result_shape(xla_shape):\n- if xla_shape.is_tuple():\n- return ResultTuple(map(xla_shape_to_result_shape, xla_shape.tuple_shapes()))\n- else:\n- shape, dtype = xla_shape.dimensions(), xla_shape.element_type()\n- ndim, size = len(shape), prod(shape)\n- return ResultArray((shape, dtype, ndim, size))\n-class ResultTuple(tuple): pass\n-class ResultArray(tuple): pass\n-\n-\ndef compile_jaxpr(jaxpr, const_vals, *abstract_args):\narg_shapes = list(map(xla_shape, abstract_args))\nbuilt_c = jaxpr_computation(jaxpr, const_vals, (), *arg_shapes)\n@@ -372,39 +385,29 @@ class DeviceValue(object):\nclass DeviceTuple(DeviceValue):\n\"\"\"A DeviceTuple is a JaxTuple backed by a single device memory buffer.\"\"\"\n- __slots__ = [\"elt_xla_shapes\", \"elt_handlers\"]\n+ __slots__ = [\"aval\", \"result_shapes\"]\n- def __init__(self, device_buffer):\n+ def __init__(self, result_shape, device_buffer):\nself.device_buffer = device_buffer\n- self.elt_xla_shapes = device_buffer.shape().tuple_shapes()\n- self.elt_handlers = list(map(_tuple_elt_handler, self.elt_xla_shapes))\n+ self.aval, self.result_shapes = result_shape\ndef __iter__(self):\nbufs = self.device_buffer.destructure()\n- elts = [handler(buf) for handler, buf in zip(self.elt_handlers, bufs)]\n+ handlers = map(device_persistent_result_handler, self.result_shapes)\n+ elts = [handler(buf) for handler, buf in zip(handlers, bufs)]\nreturn iter(elts)\ndef __len__(self):\n- return len(self.elt_xla_shapes)\n+ return len(self.aval)\ndef __repr__(self):\n- return 'DeviceTuple[{}]'.format(len(self.elt_xla_shapes))\n-core.tuple_types.add(DeviceTuple)\n-\n-def _tuple_elt_handler(xla_shape):\n- if xla_shape.is_tuple():\n- return DeviceTuple\n- else:\n- result_shape = xla_shape_to_result_shape(xla_shape)\n- return lambda buf: DeviceArray(buf, *result_shape)\n+ return 'DeviceTuple(len={length})'.format(length=len(self))\n-def abstractify_device_tuple(tup):\n- return AbstractTuple(map(aval_from_xla_shape, tup.elt_xla_shapes))\n+# DeviceValues don't need to be dtype-canonicalized because we assume values on\n+# the device have already been canonicalized.\ncore.pytype_aval_mappings[DeviceTuple] = AbstractTuple\n-pytype_aval_mappings[DeviceTuple] = abstractify_device_tuple\n-# DeviceValues don't need to be canonicalized because we assume values on the\n-# device have already been canonicalized.\n+pytype_aval_mappings[DeviceTuple] = op.attrgetter('aval')\ncanonicalize_dtype_handlers[DeviceTuple] = identity\n@@ -419,12 +422,9 @@ class DeviceArray(DeviceValue):\n__slots__ = [\"shape\", \"dtype\", \"ndim\", \"size\", \"_npy_value\"]\n__array_priority__ = 100.\n- def __init__(self, device_buffer, shape, dtype, ndim, size):\n+ def __init__(self, result_shape, device_buffer):\nself.device_buffer = device_buffer\n- self.shape = shape\n- self.dtype = dtype\n- self.ndim = ndim\n- self.size = size\n+ self.shape, self.dtype, self.ndim, self.size = result_shape\nself._npy_value = None\n# TODO make device_buffer a property, make the _npy_value writeable, invalidate\n@@ -492,10 +492,10 @@ class DeviceArray(DeviceValue):\nreturn id(self)\n-core.pytype_aval_mappings[DeviceArray] = ConcreteArray\n-pytype_aval_mappings[DeviceArray] = make_shaped_array\n# DeviceValues don't need to be canonicalized because we assume values on the\n# device have already been canonicalized.\n+core.pytype_aval_mappings[DeviceArray] = ConcreteArray\n+pytype_aval_mappings[DeviceArray] = make_shaped_array\ncanonicalize_dtype_handlers[DeviceArray] = identity\ndef _device_array_constant_handler(c, val, canonicalize_types=True):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -542,11 +542,19 @@ class APITest(jtu.JaxTestCase):\nself.assertIsInstance(tup, DeviceTuple)\nself.assertEqual(tuple(tup), (1, 2))\n+ tup = device_put(pack((1, pack((2, 3)))))\n+ self.assertIsInstance(tup, DeviceTuple)\n+ self.assertAllClose(tup, (1, (2, 3)), check_dtypes=False)\n+\ndef test_devicetuple_isinstance(self):\ntup = device_put(pack((1, 2)))\nself.assertIsInstance(tup, DeviceTuple)\nself.assertIsInstance(tup, JaxTuple)\n+ def test_devicetuple_repr(self):\n+ tup = device_put(pack((1, 2)))\n+ self.assertEqual(repr(tup), 'DeviceTuple(len=2)')\n+\nif __name__ == '__main__':\nabsltest.main()\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -25,8 +25,9 @@ from absl.testing import parameterized\nimport jax.numpy as np\nfrom jax import test_util as jtu\n+from jax import core\nfrom jax import lax\n-from jax.api import pmap, vmap, jvp, grad, make_jaxpr, linearize, device_put\n+from jax.api import pmap, jit, vmap, jvp, grad, make_jaxpr, linearize, device_put\nfrom jax.lib import xla_bridge\nfrom jax.util import prod\nfrom jax.interpreters import pxla\n@@ -192,7 +193,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = grad(lambda x: np.sum(baseline_fun(x)))(x)\nself.assertAllClose(ans, expected, check_dtypes=True)\n- def testShardedDeviceValues(self):\n+ def testShardedDeviceArrays(self):\nf = lambda x: 2 * x\nf = pmap(f, axis_name='i')\n@@ -201,15 +202,16 @@ class PmapTest(jtu.JaxTestCase):\n# test that we can pass in and out ShardedDeviceArrays\ny = f(x)\n- assert type(y) is pxla.ShardedDeviceArray # pylint: disable=unidiomatic-typecheck\n+ self.assertIsInstance(y, np.ndarray)\n+ self.assertIsInstance(y, pxla.ShardedDeviceArray)\nself.assertAllClose(y, 2 * x, check_dtypes=False)\nz = f(y)\n- assert type(z) is pxla.ShardedDeviceArray # pylint: disable=unidiomatic-typecheck\n+ self.assertIsInstance(z, pxla.ShardedDeviceArray)\nself.assertAllClose(z, 2 * 2 * x, check_dtypes=False)\n# test that we can pass in a regular DeviceArray\ny = f(device_put(x))\n- assert type(y) is pxla.ShardedDeviceArray # pylint: disable=unidiomatic-typecheck\n+ self.assertIsInstance(y, pxla.ShardedDeviceArray)\nself.assertAllClose(y, 2 * x, check_dtypes=False)\n# test that we can pass a ShardedDeviceArray to a regular jit computation\n@@ -221,6 +223,9 @@ class PmapTest(jtu.JaxTestCase):\nz = f(y)\nself.assertAllClose(z, 2 * 2 * x[::-1], check_dtypes=False)\n+ # test that the repr doesn't crash\n+ repr(z)\n+\ndef testPsumMultiple(self):\nf = lambda x: lax.psum(x, ('i', 'j'))\nf = pmap(pmap(f, 'i'), 'j')\n@@ -255,6 +260,26 @@ class PmapTest(jtu.JaxTestCase):\nself.assertEqual((tuple(sorted(groups[0])),),\n((0, 1, 2, 3, 4, 5, 6, 7,),)) # order doesn't matter\n+ def testShardedDeviceTuple(self):\n+ f = lambda x: core.pack((x, x))\n+ f = pmap(f)\n+\n+ shape = (xla_bridge.device_count(), 4)\n+ x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)\n+\n+ # test that we can pass in and out ShardedDeviceTuples (and unpack them)\n+ y = f(x)\n+ self.assertIsInstance(y, pxla.ShardedDeviceTuple)\n+ self.assertIsInstance(y, core.JaxTuple)\n+ self.assertAllClose(y, (x, x), check_dtypes=False)\n+ z = f(y)\n+ self.assertIsInstance(z, pxla.ShardedDeviceTuple)\n+ self.assertAllClose(z, (y, y), check_dtypes=True)\n+\n+ # test that we can pass a ShardedDeviceTuple to a regular jit computation\n+ w = jit(lambda x: list(x)[0])(y)\n+ self.assertAllClose(w, x, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | revise sharded result handling, misc cleanup |
260,335 | 03.05.2019 08:14:03 | 25,200 | 7fc3f3f7047029cc76bf2260047ad53138844e5e | fix legacy numpy issue with DeviceArray.__repr__ | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -442,6 +442,18 @@ class DeviceArray(DeviceValue):\ndef __repr__(self):\nreturn onp.array_repr(self)\n+ def item(self):\n+ if onp.issubdtype(self.dtype, onp.complexfloating):\n+ return complex(self)\n+ elif onp.issubdtype(self.dtype, onp.floating):\n+ return float(self)\n+ elif onp.issubdtype(self.dtype, onp.integer):\n+ return int(self)\n+ elif onp.issubdtype(self.dtype, onp.bool_):\n+ return bool(self)\n+ else:\n+ raise TypeError(self.dtype)\n+\ndef __len__(self):\ntry:\nreturn self.shape[0]\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -555,6 +555,10 @@ class APITest(jtu.JaxTestCase):\ntup = device_put(pack((1, 2)))\nself.assertEqual(repr(tup), 'DeviceTuple(len=2)')\n+ def test_legacy_devicearray_repr(self):\n+ dx = device_put(3.)\n+ str(dx.item()) # doesn't crash\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix legacy numpy issue with DeviceArray.__repr__ |
260,335 | 03.05.2019 08:24:24 | 25,200 | 8e96e2f6df8e687a5ba4c56b3c531b1be9e3fe46 | revert incorrect change to core.valid_jaxtype | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -418,7 +418,11 @@ def lattice_join(x, y):\ndef valid_jaxtype(x):\n- return type(x) in pytype_aval_mappings\n+ try:\n+ concrete_aval(x)\n+ except TypeError:\n+ return False\n+ return True\ndef concrete_aval(x):\n@@ -440,9 +444,10 @@ pytype_aval_mappings = {}\n# ------------------- Products -------------------\n-# We set up a registry of tuple types so that we can control the behavior of\n-# isinstance(val, JaxTuple) without subclassing JaxTuple, which can be difficult\n-# when slots are defined and multiple inheritance is necessary.\n+# We override isinstance(x, JaxTuple) behavior (using a metaclass) because\n+# defining __slots__ (for performance) is incompatible with multiple\n+# inheritance, and both isinstance(x, JaxTuple) and isinstance(x, DeviceValue)\n+# can be true.\nclass _TupleMeta(type(tuple)):\ndef __instancecheck__(self, instance):\nreturn type(get_aval(instance)) is AbstractTuple\n"
}
] | Python | Apache License 2.0 | google/jax | revert incorrect change to core.valid_jaxtype |
260,335 | 03.05.2019 08:46:21 | 25,200 | 3d6d678c79eb538170399a6ced87599d516f9551 | xla_client.make_tuple gets backend | [
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -187,7 +187,8 @@ def device_put_many(pyvals_and_devices):\nreturn [device_put(pyval, device) for (pyval, device) in pyvals_and_devices]\ndef make_tuple(bufs, device_num=0):\n- return xla_client.Buffer.make_tuple(bufs, device=device_num)\n+ return xla_client.Buffer.make_tuple(bufs, device=device_num,\n+ backend=get_backend())\nShape = xla_client.Shape # pylint: disable=invalid-name\n"
}
] | Python | Apache License 2.0 | google/jax | xla_client.make_tuple gets backend |
260,335 | 03.05.2019 11:39:37 | 25,200 | 15a4554ffb0c00ca95df307ff32c9acad0c81a4e | flatten out pytrees in jit at the api.py level | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -41,7 +41,7 @@ from . import linear_util as lu\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)\n+ pytree_fun_to_jaxtupletree_fun2, flatten_fun)\nfrom .tree_util import (process_pytree, node_types, build_tree, PyTreeDef,\ntree_map, tree_flatten, tree_unflatten, tree_structure,\ntree_transpose, leaf)\n@@ -109,23 +109,14 @@ def jit(fun, static_argnums=()):\nmsg = (\"Jitted function has static_argnums={} but was called with only {}\"\n\" positional arguments.\")\nraise TypeError(msg.format(static_argnums, len(args)))\n- if kwargs:\n- # TODO(mattjj, dougalm): remove warning by May 1 2019\n- msg = (\"Until recently jitted functions called with keyword arguments \"\n- \"treated those arguments as if they were part of static_argnums, \"\n- \"but now they are treated just like other arguments. If you were \"\n- \"relying on the previous behavior, you may need to update your \"\n- \"code to use static_argnums. See the jit docstring.\")\n- warn(msg)\nf = lu.wrap_init(fun)\ndyn_argnums = [i for i in range(len(args)) if i not in static_argnums]\nf, dyn_args = _argnums_partial(f, dyn_argnums, args)\n- jaxtuple_args, in_trees = unzip2(map(pytree_to_jaxtupletree, dyn_args))\n- jaxtuple_kwargs, kwargs_tree = pytree_to_jaxtupletree(kwargs)\n- _check_args(jaxtuple_args)\n- jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun2(f, kwargs_tree, in_trees)\n- out = xla.xla_call(jaxtree_fun, jaxtuple_kwargs, *jaxtuple_args)\n- return build_tree(out_tree(), out)\n+ args_flat, in_tree = tree_flatten((dyn_args, kwargs))\n+ _check_args(args_flat)\n+ flat_fun, out_tree = flatten_fun(f, in_tree)\n+ out = xla.xla_call(flat_fun, *args_flat)\n+ return tree_unflatten(out_tree(), out)\njitted_name = \"jit({}, static_argnums={})\"\nf_jitted.__name__ = jitted_name.format(f_jitted.__name__, static_argnums)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/api_util.py",
"new_path": "jax/api_util.py",
"diff": "@@ -74,3 +74,10 @@ def pytree_fun_to_flatjaxtuple_fun(in_trees, *args):\ndef pytree_to_flatjaxtuple(pytree):\nflat_ans, out_tree = tree_flatten(pytree)\nreturn pack(flat_ans), out_tree\n+\n+\n+@transformation_with_aux\n+def flatten_fun(in_tree, *args_flat):\n+ py_args, py_kwargs = tree_unflatten(in_tree, args_flat)\n+ ans = yield py_args, py_kwargs\n+ yield pytree_to_flatjaxtuple(ans)\n"
}
] | Python | Apache License 2.0 | google/jax | flatten out pytrees in jit at the api.py level |
260,335 | 03.05.2019 12:01:12 | 25,200 | f95f1c8dda9f4eeabb64744e1d6be51a2f4c91cc | fix bugs, make tests pass with skip_checks = False | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -474,6 +474,12 @@ class JaxTuple(six.with_metaclass(_TupleMeta)):\nclass AbstractTuple(AbstractValue, tuple):\n+ def __new__(cls, xs=()):\n+ if not skip_checks:\n+ xs = tuple(xs)\n+ assert all(isinstance(x, AbstractValue) for x in xs), xs\n+ return tuple.__new__(cls, xs)\n+\n@staticmethod\ndef _iter(tracer):\nreturn map(full_lower, tracer.unpack())\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -301,9 +301,9 @@ def join_pvals(pval1, pval2):\npvals1, pvals2 = zip(pv1, const1), zip(pv2, const2)\njoin_pvs, join_consts = unzip2(map(join_pvals, pvals1, pvals2))\nif all(isinstance(pv, AbstractValue) for pv in join_pvs):\n- return PartialVal((AbstractTuple(join_pvs), tuple(join_consts)))\n+ return PartialVal((AbstractTuple(join_pvs), pack(join_consts)))\nelse:\n- return PartialVal((JaxprTracerTuple(join_pvs), tuple(join_consts)))\n+ return PartialVal((JaxprTracerTuple(join_pvs), pack(join_consts)))\ndef as_abstract_val(pv):\nif isinstance(pv, AbstractValue):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -371,7 +371,7 @@ def tuple_element_handler(axis_size, aval):\nraise TypeError(t)\n-core.pytype_aval_mappings[ShardedDeviceTuple] = core.AbstractTuple\n+core.pytype_aval_mappings[ShardedDeviceTuple] = core.pytype_aval_mappings[core.JaxTuple]\nxla.pytype_aval_mappings[ShardedDeviceTuple] = op.attrgetter('aval')\nxla.canonicalize_dtype_handlers[ShardedDeviceTuple] = \\\nxla.canonicalize_dtype_handlers[xla.DeviceTuple]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -406,7 +406,7 @@ class DeviceTuple(DeviceValue):\n# DeviceValues don't need to be dtype-canonicalized because we assume values on\n# the device have already been canonicalized.\n-core.pytype_aval_mappings[DeviceTuple] = AbstractTuple\n+core.pytype_aval_mappings[DeviceTuple] = core.pytype_aval_mappings[JaxTuple]\npytype_aval_mappings[DeviceTuple] = op.attrgetter('aval')\ncanonicalize_dtype_handlers[DeviceTuple] = identity\n"
}
] | Python | Apache License 2.0 | google/jax | fix bugs, make tests pass with skip_checks = False |
260,335 | 03.05.2019 13:23:12 | 25,200 | f4a25cd61f408f17bfb92215028e5557e3d0913c | add some documentation to optimizers.py | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optimizers.py",
"new_path": "jax/experimental/optimizers.py",
"diff": "This short module contains some convenient optimizer definitions, specifically\ninitialization and update functions, which can be used with ndarrays or\narbitrarily-nested tuple/list/dicts of ndarrays.\n+\n+An optimizer is modeled as an ``(init_fun, update_fun, get_params)`` triple of\n+functions, where the component functions have these signatures:\n+\n+::\n+\n+ init_fun(params)\n+\n+ Args:\n+ params: pytree representing the initial parameters.\n+\n+ Returns:\n+ A pytree representing the initial optimizer state, which includes the\n+ initial parameters and may also include auxiliary values like initial\n+ momentum. The optimizer state pytree structure generally differs from that\n+ of `params`.\n+\n+::\n+\n+ get_params(opt_state)\n+\n+ Args:\n+ opt_state: pytree representing an optimizer state.\n+\n+ Returns:\n+ A pytree representing the parameters extracted from `opt_state`, such that\n+ the invariant `params == get_params(init_params(params))` holds true.\n+\n+::\n+\n+ update_fun(step, grads, opt_state)\n+\n+ Args:\n+ step: integer representing the step index.\n+ grads: a pytree with the same structure as `get_params(opt_state)` representing\n+ the gradients to be used in updating the optimizer state.\n+ opt_state: a pytree representing the optimizer state to be updated.\n+\n+ Returns:\n+ A pytree with the same structure as the `opt_state` argument representing the\n+ updated optimizer state.\n+\n+\n+Notice that an optimizer implementation has a lot of flexibility in the form of\n+opt_state: it just has to be a pytree of JaxTypes (so that it can be passed to\n+the JAX transforms defined in api.py) and it has to be consumable by update_fun\n+and get_params.\n\"\"\"\n+\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n@@ -35,6 +83,18 @@ from jax.tree_util import tree_flatten, tree_unflatten, register_pytree_node\nmap = safe_map\nzip = safe_zip\n+\n+# The implementation here basically works by flattening pytrees. There are two\n+# levels of pytrees to think about: the pytree of params, which we can think of\n+# as defining an \"outer pytree\", and a pytree produced by applying init_fun to\n+# each leaf of the params pytree, which we can think of as the \"inner pytrees\".\n+# Since pytrees can be flattened, that structure is isomorphic to a list of\n+# lists (with no further nesting). This implementation represents that structure\n+# as a JaxTuple-of-JaxTuples so that we can maintain the entire optimizer state\n+# as a single DeviceTuple, and thus pay no pytree traversal overhead when we\n+# dispatch to a `jit`-compiled `update_fun`. That JaxTuple-of-JaxTuples is\n+# stored together with the tree structure data in an OptimizerState instance.\n+\nOptimizerState = collections.namedtuple(\"OptimizerState\",\n[\"packed_state\", \"tree\", \"subtrees\"])\nregister_pytree_node(OptimizerState,\n@@ -42,7 +102,33 @@ register_pytree_node(OptimizerState,\nlambda data, xs: OptimizerState(xs[0], data[0], data[1]))\ndef optimizer(opt_maker):\n- \"\"\"Decorator to make an optimizer map over tuple/list/dict containers.\"\"\"\n+ \"\"\"Decorator to make an optimizer defined for arrays generalize to containers.\n+\n+ Args:\n+ opt_maker: a function that returns an ``(init_fun, update_fun, get_params)``\n+ triple of functions that might only work with ndarrays, as per\n+\n+ .. code-block:: haskell\n+\n+ init_fun :: ndarray -> OptStatePytree ndarray\n+ update_fun :: OptStatePytree ndarray -> OptStatePytree ndarray\n+ get_params :: OptStatePytree ndarray -> ndarray\n+\n+ Returns:\n+ An ``(init_fun, update_fun, get_params)`` triple of functions that work on\n+ arbitrary pytrees, as per\n+\n+ .. code-block:: haskell\n+\n+ init_fun :: ParameterPytree ndarray -> OptimizerState\n+ update_fun :: OptimizerState -> OptimizerState\n+ get_params :: OptimizerState -> ParameterPytree ndarray\n+\n+ The OptimizerState pytree type used by the returned functions is isomorphic\n+ to ``ParameterPytree (OptStatePytree ndarray)`` but has an implementation\n+ based on JaxTuples to avoid pytree structuring/destructuring overheads.\n+ \"\"\"\n+\n@functools.wraps(opt_maker)\ndef tree_opt_maker(*args, **kwargs):\ninit, update, get_params = opt_maker(*args, **kwargs)\n"
}
] | Python | Apache License 2.0 | google/jax | add some documentation to optimizers.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.