author int64 658 755k | date stringlengths 19 19 | timezone int64 -46,800 43.2k | hash stringlengths 40 40 | message stringlengths 5 490 | mods list | language stringclasses 20 values | license stringclasses 3 values | repo stringlengths 5 68 | original_message stringlengths 12 491 |
|---|---|---|---|---|---|---|---|---|---|
260,335 | 26.05.2020 20:01:36 | 25,200 | 9f8a4ad341acc8bab52c0746102193cb7a4da2ee | remove stray print statement from | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -775,7 +775,6 @@ def frexp(x):\nint_type = _INT_DTYPES[info.bits]\nx1, x2 = _normalize_float(x)\n- print(x1, x2)\nx1 = lax.bitcast_convert_type(x1, int_type)\nx2 += ((x1 >> info.nmant) & mask) - bias + 1\nx1 &= ~(mask << info.nmant)\n"
}
] | Python | Apache License 2.0 | google/jax | remove stray print statement from #1529 |
260,424 | 27.05.2020 08:59:31 | -3,600 | 1cc471928b0e677149a72518dc95fa2daa47f76e | Remove pe from name_stack and test. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -167,8 +167,6 @@ class JaxprTrace(Trace):\nif (self.master.trace_type is StagingJaxprTrace\nand call_primitive in staged_out_calls):\ntracers = map(self.instantiate_const_abstracted, tracers)\n- else:\n- name = wrap_name(name, 'pe')\nparams = dict(params, name=name)\nif call_primitive in call_partial_eval_rules:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/metadata_test.py",
"new_path": "tests/metadata_test.py",
"diff": "@@ -67,10 +67,10 @@ class MetadataTest(jtu.JaxTestCase):\nself.assertRegex(hlo, 'op_type=\"sin\"')\nself.assertRegex(hlo, 'op_type=\"cos\"')\nself.assertRegex(hlo, 'op_type=\"mul\"')\n- self.assertRegex(hlo, 'op_name=\".*jit\\\\(pe\\\\(jvp\\\\(foo\\\\)\\\\)\\\\)/sin\"')\n- self.assertRegex(hlo, 'op_name=\".*jit\\\\(pe\\\\(jvp\\\\(foo\\\\)\\\\)\\\\)/cos\"')\n+ self.assertRegex(hlo, 'op_name=\".*jit\\\\(jvp\\\\(foo\\\\)\\\\)/sin\"')\n+ self.assertRegex(hlo, 'op_name=\".*jit\\\\(jvp\\\\(foo\\\\)\\\\)/cos\"')\nself.assertRegex(hlo, 'op_name=\".*jit\\\\(transpose\\\\('\n- 'pe\\\\(jvp\\\\(foo\\\\)\\\\)\\\\)\\\\)/mul\"')\n+ 'jvp\\\\(foo\\\\)\\\\)\\\\)/mul\"')\ndef test_cond_metadata(self):\ndef true_fun(x):\n"
}
] | Python | Apache License 2.0 | google/jax | Remove pe from name_stack and test. (#3209) |
260,485 | 27.05.2020 12:37:55 | 14,400 | ec3b593ca85d6f5c3b538b6615dfbd8c8ffe8148 | Added geometric distribution to scipy stats | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/stats/__init__.py",
"new_path": "jax/scipy/stats/__init__.py",
"diff": "@@ -26,3 +26,4 @@ from . import pareto\nfrom . import t\nfrom . import uniform\nfrom . import logistic\n+from . import geom\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/scipy/stats/geom.py",
"diff": "+# Copyright 2020 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+import scipy.stats as osp_stats\n+\n+from ... import lax\n+from ...numpy import lax_numpy as jnp\n+from ...numpy._util import _wraps\n+from ..special import xlogy, xlog1py\n+\n+@_wraps(osp_stats.geom.logpmf, update_doc=False)\n+def logpmf(k, p, loc=0):\n+ k, p, loc = jnp._promote_args_inexact(\"geom.logpmf\", k, p, loc)\n+ zero = jnp._constant_like(k, 0)\n+ one = jnp._constant_like(k, 1)\n+ x = lax.sub(k, loc)\n+ log_probs = xlog1py(lax.sub(x, one), -p) + lax.log(p)\n+ return jnp.where(lax.le(x, zero), -jnp.inf, log_probs)\n+\n+@_wraps(osp_stats.geom.pmf, update_doc=False)\n+def pmf(k, p, loc=0):\n+ return jnp.exp(logpmf(k, p, loc))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -102,6 +102,23 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\ntol=1e-4)\nself._CompileAndCheck(lax_fun, args_maker, check_dtypes=True)\n+ @genNamedParametersNArgs(3, jtu.rand_default)\n+ def testGeomLogPmf(self, rng_factory, shapes, dtypes):\n+ rng = rng_factory(self.rng())\n+ scipy_fun = osp_stats.geom.logpmf\n+ lax_fun = lsp_stats.geom.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=False,\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_factory, shapes, dtypes):\nrng = rng_factory(self.rng())\n"
}
] | Python | Apache License 2.0 | google/jax | Added geometric distribution to scipy stats (#3205) |
260,287 | 28.05.2020 17:39:13 | -7,200 | c1ccbdf1a7d6738bd23971aa6d2718e8ba013f86 | Small cleanup for partial_eval
`partial_eval` uses some pretty tricky conventions for return values
(see `partial_eval_wrapper`), but it forces all call sites to deal with
untangling them. This commit inlines the postprocessing into
`partial_eval`, greatly simplifying its usage. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -27,7 +27,7 @@ from .. import linear_util as lu\nfrom ..abstract_arrays import ShapedArray, ConcreteArray, raise_to_shaped\nfrom ..ad_util import zero\nfrom ..util import (unzip2, safe_zip, safe_map, toposort, partial, split_list,\n- wrap_name, cache)\n+ wrap_name, cache, curry)\nfrom ..core import (Trace, Tracer, new_master, Jaxpr, Literal, get_aval,\nAbstractValue, unit, unitvar, abstract_unit,\nTypedJaxpr, new_jaxpr_eqn)\n@@ -171,22 +171,21 @@ class JaxprTrace(Trace):\nif call_primitive in call_partial_eval_rules:\nreturn call_partial_eval_rules[call_primitive](self, call_primitive, f, tracers, params)\n- in_pvs, in_consts = unzip2([t.pval for t in tracers])\n- fun, aux = partial_eval(f, self, in_pvs)\n- out_flat = call_primitive.bind(fun, *in_consts, **params)\n- out_pvs, jaxpr, env = aux()\n- env_tracers = map(self.full_raise, env)\n- out_pv_consts, consts = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])\n+\n+ jaxpr, out_pvals, consts, env_tracers = self.partial_eval(\n+ f, [t.pval for t in tracers], partial(call_primitive.bind, **params))\nif not jaxpr.eqns:\nenv = {core.unitvar: core.unit}\nmap(env.setdefault, jaxpr.invars, (*env_tracers, *tracers))\nmap(env.setdefault, jaxpr.constvars, consts)\n- return [pv_const if pv is None else v.val if type(v) is Literal else env[v]\n- for v, pv, pv_const in zip(jaxpr.outvars, out_pvs, out_pv_consts)]\n+ return [v.val if type(v) is Literal\n+ else pval.get_known() if pval.is_known()\n+ else env[v]\n+ for v, pval in zip(jaxpr.outvars, out_pvals)]\n+\nconst_tracers = map(self.new_instantiated_const, consts)\nlifted_jaxpr = convert_constvars_jaxpr(jaxpr)\n- out_tracers = [JaxprTracer(self, PartialVal((out_pv, out_pv_const)), None)\n- for out_pv, out_pv_const in zip(out_pvs, out_pv_consts)]\n+ out_tracers = [JaxprTracer(self, pval, None) for pval in out_pvals]\nnew_params = dict(params, call_jaxpr=lifted_jaxpr)\n# The `jaxpr` already contains the env_vars at start of invars\neqn = new_eqn_recipe(tuple(it.chain(const_tracers, env_tracers, tracers)),\n@@ -225,23 +224,25 @@ class JaxprTrace(Trace):\ntracers = map(self.instantiate_const_abstracted, tracers)\nelse:\nname = wrap_name(name, 'pe')\n-\nparams = dict(params, name=name)\n- in_pvs, in_consts = unzip2([t.pval for t in tracers])\n- reduced_pvs = [None if pv is None else\n- core.mapped_aval(params['axis_size'], pv) if m else pv\n- for pv, m in zip(in_pvs, params['mapped_invars'])]\n- fun, aux = partial_eval(f, self, reduced_pvs)\n- out_flat = map_primitive.bind(fun, *in_consts, **params)\n- out_pvs_reduced, jaxpr, env = aux()\n- out_pv_consts, consts = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])\n- out_pvs = [None if pv is None else core.unmapped_aval(params['axis_size'], pv)\n- for pv in out_pvs_reduced]\n+\n+ @curry\n+ def modify_aval(modify, args):\n+ pval, is_mapped = args\n+ if pval.is_known() or not is_mapped:\n+ return pval\n+ return PartialVal((modify(params['axis_size'], pval[0]), pval[1]))\n+\n+ reduced_in_pvals = map(modify_aval(core.mapped_aval),\n+ zip([t.pval for t in tracers], params['mapped_invars']))\n+ jaxpr, reduced_out_pvals, consts, env_tracers = self.partial_eval(\n+ f, reduced_in_pvals, partial(map_primitive.bind, **params))\n+ out_pvals = map(modify_aval(core.unmapped_aval),\n+ [(pval, True) for pval in reduced_out_pvals])\n+\nconst_tracers = map(self.new_instantiated_const, consts)\n- env_tracers = map(self.full_raise, env)\nlifted_jaxpr = convert_constvars_jaxpr(jaxpr)\n- out_tracers = [JaxprTracer(self, PartialVal((out_pv, out_pv_const)), None)\n- for out_pv, out_pv_const in zip(out_pvs, out_pv_consts)]\n+ out_tracers = [JaxprTracer(self, pval, None) for pval in out_pvals]\n# The `jaxpr` already contains the env_vars at start of invars\nnew_params = dict(params,\nmapped_invars=((True,) * len(const_tracers) +\n@@ -298,20 +299,17 @@ class JaxprTrace(Trace):\nassert self.master.trace_type is StagingJaxprTrace\nreturn fun.call_wrapped(*tracers)\n-# This subclass is used just for its type tag (see comment for `JaxprTrace`)\n-# This switches the behavior of process_call to stage out into the jaxpr any\n-# call primitives encountered (rather than doing partial evaluation into the call).\n-class StagingJaxprTrace(JaxprTrace):\n- pass\n-\n-custom_partial_eval_rules: Dict[core.Primitive, Callable] = {}\n-call_partial_eval_rules: Dict[core.Primitive, Callable] = {}\n-staged_out_calls: Set[core.Primitive] = set()\n-\n-\n-def partial_eval(f, trace, pvs: Sequence[Optional[AbstractValue]], instantiate=False):\n- f = trace_to_subjaxpr(f, trace.master, instantiate)\n- return partial_eval_wrapper(f, tuple(pvs))\n+ def partial_eval(self, f: lu.WrappedFun, pvals: Sequence[PartialVal],\n+ app: Callable[[lu.WrappedFun, Tuple[core.Value, ...]], Tuple[core.Value]]):\n+ \"\"\"Partially evaluate f on a sequence of PartialVals.\"\"\"\n+ in_avals, in_consts = unzip2(pvals)\n+ f = trace_to_subjaxpr(f, self.master, False)\n+ f, aux = partial_eval_wrapper(f, tuple(in_avals))\n+ out_flat, (out_avals, jaxpr, env) = app(f, *in_consts), aux()\n+ out_consts, consts = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])\n+ out_pvs = map(PartialVal, zip(out_avals, out_consts))\n+ env_tracers = map(self.full_raise, env)\n+ return jaxpr, out_pvs, consts, env_tracers\n@lu.transformation_with_aux\n@@ -323,6 +321,17 @@ def partial_eval_wrapper(avals: Sequence[Optional[AbstractValue]], *consts):\nyield out, (out_pvs, jaxpr, env)\n+# This subclass is used just for its type tag (see comment for `JaxprTrace`)\n+# This switches the behavior of process_call to stage out into the jaxpr any\n+# call primitives encountered (rather than doing partial evaluation into the call).\n+class StagingJaxprTrace(JaxprTrace):\n+ pass\n+\n+custom_partial_eval_rules: Dict[core.Primitive, Callable] = {}\n+call_partial_eval_rules: Dict[core.Primitive, Callable] = {}\n+staged_out_calls: Set[core.Primitive] = set()\n+\n+\ndef abstract_eval_fun(fun, *avals, **params):\npvals_in = [PartialVal.unknown(a) for a in avals]\n_, pvals_out, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvals_in,\n@@ -660,27 +669,22 @@ def _remat_partial_eval(trace, _, f, tracers, params):\ninstantiated_tracers = map(trace.instantiate_const_abstracted, tracers)\n# Using the instantiated tracers, run call_bind like JaxprTrace.process_call.\n- in_pvs, in_consts = unzip2(t.pval for t in instantiated_tracers)\n- fun, aux = partial_eval(f, trace, in_pvs)\n+ in_pvals = [t.pval for t in instantiated_tracers]\nwith core.initial_style_staging():\n- out_flat = remat_call_p.bind(fun, *in_consts, **params)\n- out_pvs, jaxpr, env = aux()\n- env = map(trace.full_raise, env)\n- out_pval_consts1, consts = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])\n- out_pvals1 = [PartialVal((pv, const)) for pv, const in zip(out_pvs, out_pval_consts1)]\n+ jaxpr, out_pvals1, consts, env_tracers = trace.partial_eval(\n+ f, in_pvals, partial(remat_call_p.bind, **params))\n# Since we traced with everything marked as unknown, but we need to know which\n# outputs are known/unknown, we use partial_eval_jaxpr to get out_unknowns.\n- in_avals = ([raise_to_shaped(t.pval.get_aval()) for t in env]\n- + [raise_to_shaped(pv) for pv in in_pvs])\n- out_avals = [raise_to_shaped(pv if pv is not None\n- else abstract_unit if var is unitvar\n+ in_avals = ([raise_to_shaped(t.pval.get_aval()) for t in env_tracers]\n+ + [raise_to_shaped(pval.get_aval()) for pval in in_pvals])\n+ out_avals = [raise_to_shaped(abstract_unit if var is unitvar\nelse get_aval(var.val) if type(var) is Literal\n- else get_aval(const))\n- for var, pv, const in zip(jaxpr.outvars, out_pvs, out_pval_consts1)]\n+ else pval.get_aval())\n+ for var, pval in zip(jaxpr.outvars, out_pvals1)]\ntyped_jaxpr = core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)\n- in_unknowns = [t.pval[0] is not None for t in it.chain(env, tracers)]\n+ in_unknowns = [t.pval[0] is not None for t in it.chain(env_tracers, tracers)]\njaxpr_1, jaxpr_2, out_unknowns = partial_eval_jaxpr(typed_jaxpr, in_unknowns,\ninstantiate=False,\ntrace_type=trace.master.trace_type)\n@@ -696,15 +700,15 @@ def _remat_partial_eval(trace, _, f, tracers, params):\n# produced concrete avals at the output, simply by using those as computed\n# values. For the use case of reverse-mode ad in op-by-op (\"eager mode\")\n# evaluation, all the primal outputs should be concrete (thus not recomputed).\n- to_compute = [not uk and type(pv) is not ConcreteArray\n- for uk, pv in zip(out_unknowns, out_pvs)]\n+ to_compute = [not uk and type(pval[0]) is not ConcreteArray\n+ for uk, pval in zip(out_unknowns, out_pvals1)]\njaxpr_1_primals = _dce_jaxpr(jaxpr_1, to_compute + [False] * num_res)\n- _, in_consts = unzip2(t.pval for t in it.chain(env, tracers))\n+ _, in_consts = unzip2(t.pval for t in it.chain(env_tracers, tracers))\nout_pval_consts2 = core.jaxpr_as_fun(jaxpr_1_primals)(*in_consts)[:-num_res or None]\nout_pvals = map(_reconstruct_pval, out_pvals1, out_pval_consts2, out_unknowns)\n# Now that we have out_pvals, the rest is just like JaxprTrace.process_call.\n- instantiated_tracers = env + instantiated_tracers\n+ instantiated_tracers = env_tracers + instantiated_tracers\nconst_tracers = map(trace.new_instantiated_const, consts)\nlifted_jaxpr = convert_constvars_jaxpr(typed_jaxpr.jaxpr)\nout_tracers = [JaxprTracer(trace, out_pval, None) for out_pval in out_pvals]\n"
}
] | Python | Apache License 2.0 | google/jax | Small cleanup for partial_eval (#3210)
`partial_eval` uses some pretty tricky conventions for return values
(see `partial_eval_wrapper`), but it forces all call sites to deal with
untangling them. This commit inlines the postprocessing into
`partial_eval`, greatly simplifying its usage. |
260,335 | 28.05.2020 10:20:36 | 25,200 | 572928dfa309e625e221fd084bd25ee010afa2eb | fix custom_jvp_call_jaxpr transpose function
* make custom_jvp_call_jaxpr handle multilinear funs
see
* remove old comment | [
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -343,15 +343,11 @@ xla.initial_style_translations[custom_jvp_call_jaxpr_p] = \\\nxla.lower_fun_initial_style(_custom_jvp_call_jaxpr_impl)\n# If a (multi)linear function is defined with a custom jvp, then\n-# custom_jvp_call_jaxpr can appear in jaxprs to be transposed. We transpose it\n-# like a core.call.\n-def _custom_jvp_call_jaxpr_transpose(cts, *args, fun_jaxpr, jvp_jaxpr_thunk,\n- avals):\n+# custom_jvp_call_jaxpr can appear in jaxprs to be transposed. Since it's\n+# already been linearized, we can drop the jvp rule.\n+def _custom_jvp_call_jaxpr_transpose(cts, *args, fun_jaxpr, jvp_jaxpr_thunk):\ndel jvp_jaxpr_thunk\n- name = 'custom_jvp_call_jaxpr_linear'\n- avals = [core.get_aval(l) for l in fun_jaxpr.literals] + avals\n- return ad.call_transpose(core.call_p, dict(name=name), fun_jaxpr.jaxpr,\n- tuple(fun_jaxpr.literals) + args, cts, avals)\n+ return ad.backward_pass(fun_jaxpr.jaxpr, fun_jaxpr.literals, args, cts)\nad.primitive_transposes[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_transpose\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2457,6 +2457,25 @@ class CustomJVPTest(jtu.JaxTestCase):\ngrad(experiment)(1.) # doesn't crash\n+ def test_linear_in_scan(self):\n+ @api.custom_jvp\n+ def f(x):\n+ return -x\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ x_dot, = tangents\n+ return f(x), f(x_dot)\n+\n+ def foo(x):\n+ out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n+ return out\n+\n+ ans = api.grad(foo)(3.)\n+ expected = -1.\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nclass CustomVJPTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | fix custom_jvp_call_jaxpr transpose function (#3231)
* make custom_jvp_call_jaxpr handle multilinear funs
see #3226
* remove old comment |
260,366 | 28.05.2020 13:21:39 | 14,400 | 7c90023ddbbb598a2f34a805ac8c4b19f69b82e1 | Fix sign error in custom_jvp / custom_vjp.
f(x, y) = sin(x) * y.
df/dy should be sin(x) instead of -sin(x). | [
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -118,7 +118,7 @@ class custom_jvp:\nx, y = primals\nx_dot, y_dot = tangents\nprimal_out = f(x, y)\n- tangent_out = jnp.cos(x) * x_dot * y - jnp.sin(x) * y_dot\n+ tangent_out = jnp.cos(x) * x_dot * y + jnp.sin(x) * y_dot\nreturn primal_out, tangent_out\nFor a more detailed introduction, see the tutorial_.\n@@ -161,7 +161,7 @@ class custom_jvp:\nx, y = primals\nx_dot, y_dot = tangents\nprimal_out = f(x, y)\n- tangent_out = jnp.cos(x) * x_dot * y - jnp.sin(x) * y_dot\n+ tangent_out = jnp.cos(x) * x_dot * y + jnp.sin(x) * y_dot\nreturn primal_out, tangent_out\n\"\"\"\nself.jvp = jvp\n@@ -187,7 +187,7 @@ class custom_jvp:\nreturn jnp.sin(x) * y\nf.defjvps(lambda x_dot, primal_out, x, y: jnp.cos(x) * x_dot * y,\n- lambda y_dot, primal_out, x, y: -jnp.sin(x) * y_dot)\n+ lambda y_dot, primal_out, x, y: jnp.sin(x) * y_dot)\n\"\"\"\nif self.nondiff_argnums:\nraise TypeError(\"Can't use ``defjvps`` with ``nondiff_argnums``.\")\n@@ -379,7 +379,7 @@ class custom_vjp:\ndef f_bwd(res, g):\ncos_x, sin_x, y = res\n- return (cos_x * g * y, -sin_x * g)\n+ return (cos_x * g * y, sin_x * g)\nf.defvjp(f_fwd, f_bwd)\n@@ -433,7 +433,7 @@ class custom_vjp:\ndef f_bwd(res, g):\ncos_x, sin_x, y = res\n- return (cos_x * g * y, -sin_x * g)\n+ return (cos_x * g * y, sin_x * g)\nf.defvjp(f_fwd, f_bwd)\n\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | Fix sign error in custom_jvp / custom_vjp. (#3213) (#3219)
f(x, y) = sin(x) * y.
df/dy should be sin(x) instead of -sin(x). |
260,280 | 28.05.2020 17:16:56 | 10,800 | e48a4e012bd253428e3bb0dd4ac5b163439a5270 | uses np.prod instead of jnp.prod for shapes | [
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -554,7 +554,7 @@ where: 10\nif jtu.device_under_test() == \"tpu\":\nif dtype in (jnp.int16,):\nraise SkipTest(f\"transfering {dtype} not supported on TPU\")\n- args = [jnp.arange(jnp.prod(shape), dtype=dtype).reshape(shape)]\n+ args = [jnp.arange(np.prod(shape), dtype=dtype).reshape(shape)]\nif nr_args > 1:\nargs = args * nr_args\njit_fun1 = api.jit(lambda xs: hcb.id_print(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -238,7 +238,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nfor shape in [100, (10, 10), (10, 5, 2)]))\ndef testPermutationArray(self, dtype, shape):\nkey = random.PRNGKey(0)\n- x = jnp.arange(jnp.prod(shape)).reshape(shape).astype(dtype)\n+ x = jnp.arange(np.prod(shape)).reshape(shape).astype(dtype)\nrand = lambda key: random.permutation(key, x)\ncrand = api.jit(rand)\n@@ -249,7 +249,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertFalse(np.all(perm1 == x)) # seems unlikely!\nself.assertAllClose(np.sort(perm1.ravel()), x.ravel(), check_dtypes=False)\nself.assertArraysAllClose(\n- x, jnp.arange(jnp.prod(shape)).reshape(shape).astype(dtype),\n+ x, jnp.arange(np.prod(shape)).reshape(shape).astype(dtype),\ncheck_dtypes=True)\ndef testPermutationInteger(self):\n"
}
] | Python | Apache License 2.0 | google/jax | uses np.prod instead of jnp.prod for shapes (#3236) |
260,411 | 29.05.2020 12:54:09 | -10,800 | 5b684fc695258c03ea5e04230e08f82ae4540ffc | Attempt to fix error in google3 import
See | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1152,8 +1152,11 @@ def squeeze(a, axis: Union[int, Tuple[int, ...]] = None):\n@_wraps(np.expand_dims)\ndef expand_dims(a, axis: Union[int, Tuple[int, ...]]):\n- if isinstance(axis, int):\n- axis = (axis,)\n+ # TODO(https://github.com/google/jax/issues/3243)\n+ try:\n+ axis = (int(axis),)\n+ except TypeError:\n+ pass\nreturn lax.expand_dims(a, axis)\n"
}
] | Python | Apache License 2.0 | google/jax | Attempt to fix error in google3 import (#3244)
See #3243 |
260,411 | 29.05.2020 13:06:50 | -10,800 | 9691f9b065f6400c3e13fc7f3a68cb31a3fc3058 | Fix travis; yaml parser does not like comments inside shell commands | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -44,8 +44,8 @@ install:\nconda install --yes sphinx sphinx_rtd_theme nbsphinx sphinx-autodoc-typehints jupyter_client matplotlib;\npip install sklearn;\nfi\n- - if [ \"$JAX_TO_TF\" = true ] ;then\n# jax_to_tf needs some fixes that are not in tensorflow==2.2.0\n+ - if [ \"$JAX_TO_TF\" = true ] ;then\npip install tf-nightly==2.3.0.dev20200525 ;\nfi\nscript:\n"
}
] | Python | Apache License 2.0 | google/jax | Fix travis; yaml parser does not like comments inside shell commands (#3245) |
260,505 | 29.05.2020 20:58:10 | 14,400 | 0031075bb2d30c95ae4fb29d3457767d65ae07f6 | Replaced jnp.sum by sum when the argument is a list | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optix.py",
"new_path": "jax/experimental/optix.py",
"diff": "@@ -96,7 +96,7 @@ def clip(max_delta) -> InitUpdate:\ndef global_norm(updates: Updates) -> Updates:\nreturn jnp.sqrt(\n- jnp.sum([jnp.sum(jnp.square(x)) for x in tree_leaves(updates)]))\n+ sum([jnp.sum(jnp.square(x)) for x in tree_leaves(updates)]))\nclass ClipByGlobalNormState(OptState):\n"
}
] | Python | Apache License 2.0 | google/jax | Replaced jnp.sum by sum when the argument is a list (#3253) |
260,411 | 30.05.2020 08:48:44 | -10,800 | d34debafe6b266fbc2482fd9f2dae0805d4fcc18 | Implementation of jax_to_tf.while | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/jax_to_tf.py",
"new_path": "jax/experimental/jax_to_tf/jax_to_tf.py",
"diff": "@@ -782,6 +782,68 @@ def _cond(pred: TfVal, *operands: TfVal,\ntf_impl[lax.cond_p] = _cond\n+\n+def _while(*args, cond_nconsts: int, cond_jaxpr: core.TypedJaxpr,\n+ body_nconsts: int, body_jaxpr: core.TypedJaxpr):\n+ cond_consts, body_consts, init_carry = util.split_list(args, [cond_nconsts,\n+ body_nconsts])\n+ if cond_jaxpr.out_avals[0].shape: # type: ignore[attr-defined]\n+ # The conditional is not a scalar, this must be a batched while\n+ return _batched_while(*args,\n+ cond_nconsts=cond_nconsts, cond_jaxpr=cond_jaxpr,\n+ body_nconsts=body_nconsts, body_jaxpr=body_jaxpr)\n+\n+ # The conditional must return a single value to TF\n+ def cond_tf_func(*args):\n+ pred, = _interpret_jaxpr(cond_jaxpr, *cond_consts, *args)\n+ return pred\n+ body_tf_func = functools.partial(_interpret_jaxpr, body_jaxpr, *body_consts)\n+ return tf.while_loop(cond_tf_func, body_tf_func, init_carry)\n+\n+\n+def _batched_while(*args, cond_nconsts: int, cond_jaxpr: core.TypedJaxpr,\n+ body_nconsts: int, body_jaxpr: core.TypedJaxpr):\n+ \"\"\"Interprets a batched while.\n+\n+ A batched while has a conditional that returns a tensor of booleans, and\n+ a body that returns a list of tensors whose leading dimensions match those\n+ of the conditional tensor.\n+\n+ We need to turn it into a while with scalar boolean conditional. We will\n+ expand the loop carry to include a prefix with the current tensor boolean\n+ condition. We prepend to the loop the first calculation of the tensor boolean\n+ condition. The loop condition will use a \"reduce_any\" to calculate a scalar\n+ boolean from the tensor boolean condition. The end of the loop body will\n+ compute the new carry using a \"tf.where\", and we compute the new tensor\n+ boolean condition.\n+ \"\"\"\n+ cond_consts, body_consts, init_carry = util.split_list(args, [cond_nconsts,\n+ body_nconsts])\n+ # Initial computation of batched condition\n+ init_pred_b, = _interpret_jaxpr(cond_jaxpr, *cond_consts, *init_carry)\n+\n+ def new_cond_tf_func(pred_b: TfVal, *carry: TfVal) -> TfVal:\n+ pred = tf.reduce_any(pred_b, axis=list(range(len(pred_b.shape))))\n+ return pred\n+\n+ def new_body_tf_func(pred_b: TfVal, *carry: TfVal) -> Sequence[TfVal]:\n+ new_carry = _interpret_jaxpr(body_jaxpr, *body_consts, *carry)\n+\n+ def select_one_carry(new_c, c):\n+ pred_b_bcast = _broadcast_in_dim(pred_b, new_c.shape,\n+ list(range(len(pred_b.shape))))\n+ return tf.where(pred_b_bcast, new_c, c)\n+\n+ selected_carry = list(util.safe_map(select_one_carry, new_carry, carry))\n+ next_pred_b, = _interpret_jaxpr(cond_jaxpr, *cond_consts, *selected_carry)\n+ return (next_pred_b, *selected_carry)\n+\n+ _, *res_carry = tf.while_loop(new_cond_tf_func, new_body_tf_func,\n+ (init_pred_b, *init_carry))\n+ return res_carry\n+\n+tf_impl[lax.while_p] = _while\n+\n# TODO: add_any\n# TODO: after_all\n# TODO: all_to_all\n@@ -817,7 +879,6 @@ tf_impl[lax.cond_p] = _cond\n# TODO: svd\n# TODO: top_k\n# TODO: triangular_solve\n-# TODO: while\ndef _register_checkpoint_pytrees():\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"new_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"diff": "@@ -344,6 +344,7 @@ class TfOpsTest(jtu.JaxTestCase):\nself.assertLen(jax.tree_leaves(m.c), 2)\n+# TODO(necula): move this to a separate file\nclass ControlFlowOpsTest(parameterized.TestCase):\n@parameterized.parameters(False, True)\n@@ -372,6 +373,103 @@ class ControlFlowOpsTest(parameterized.TestCase):\nnp.testing.assert_allclose(f_tf(True, 1.), f_jax(True, 1.))\nnp.testing.assert_allclose(f_tf(False, 1.), f_jax(False, 1.))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"_function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\n+ def test_while_single_carry(self, with_function=False):\n+ \"\"\"A while with a single carry\"\"\"\n+ with jax_to_tf.enable_jit():\n+ def func(x):\n+ # Equivalent to:\n+ # for(i=x; i < 4; i++);\n+ return lax.while_loop(lambda c: c < 4, lambda c: c + 1, x)\n+\n+ f_jax = func\n+ f_tf = jax_to_tf.convert(f_jax)\n+ if with_function:\n+ f_tf = tf.function(f_tf)\n+ res_jax = f_jax(0)\n+ res_tf = f_tf(0)\n+ np.testing.assert_allclose(res_jax, res_tf)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"_function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\n+ def test_while(self, with_function=False):\n+ with jax_to_tf.enable_jit():\n+ # Some constants to capture in the conditional branches\n+ cond_const = np.ones(3, dtype=np.float32)\n+ body_const1 = np.full_like(cond_const, 1.)\n+ body_const2 = np.full_like(cond_const, 2.)\n+\n+ def func(x):\n+ # Equivalent to:\n+ # c = [1, 1, 1]\n+ # for(i=0; i < 3; i++)\n+ # c += [1, 1, 1] + [2, 2, 2]\n+ #\n+ # The function is set-up so that it captures constants in the\n+ # body of the functionals. This covers some cases in the representation\n+ # of the lax.while primitive.\n+ def cond(idx_carry):\n+ i, c = idx_carry\n+ return i < jnp.sum(lax.tie_in(i, cond_const)) # Capture cond_const\n+\n+ def body(idx_carry):\n+ i, c = idx_carry\n+ return (i + 1, c + body_const1 + body_const2)\n+\n+ return lax.while_loop(cond, body, (0, x))\n+\n+ f_jax = func\n+ f_tf = jax_to_tf.convert(f_jax)\n+ if with_function:\n+ f_tf = tf.function(f_tf)\n+ input = cond_const\n+ res_jax = f_jax(input)\n+ res_tf = f_tf(input)\n+ for r_jax, r_tf in zip(res_jax, res_tf):\n+ np.testing.assert_allclose(r_jax, r_tf)\n+\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"_function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\n+ def test_while_batched(self, with_function=True):\n+ \"\"\"A while with a single carry\"\"\"\n+ with jax_to_tf.enable_jit():\n+ def product(x, y):\n+ # Equivalent to \"x * y\" implemented as:\n+ # res = 0.\n+ # for(i=0; i < y; i++)\n+ # res += x\n+ return lax.while_loop(lambda idx_carry: idx_carry[0] < y,\n+ lambda idx_carry: (idx_carry[0] + 1,\n+ idx_carry[1] + x),\n+ (0, 0.))\n+\n+ # We use vmap to compute result[i, j] = i * j\n+ xs = np.arange(4, dtype=np.int32)\n+ ys = np.arange(5, dtype=np.int32)\n+\n+ def product_xs_y(xs, y):\n+ return jax.vmap(product, in_axes=(0, None))(xs, y)\n+ def product_xs_ys(xs, ys):\n+ return jax.vmap(product_xs_y, in_axes=(None, 0))(xs, ys)\n+\n+ f_jax = product_xs_ys\n+ f_tf = jax_to_tf.convert(f_jax)\n+ if with_function:\n+ f_tf = tf.function(f_tf)\n+ res_jax = f_jax(xs, ys)\n+ res_tf = f_tf(xs, ys)\n+ for r_tf, r_jax in zip(res_tf, res_jax):\n+ np.testing.assert_allclose(r_tf, r_jax)\n+\n@parameterized.parameters(False, True)\ndef test_scan(self, with_function=False):\ndef f_jax(xs, ys):\n"
}
] | Python | Apache License 2.0 | google/jax | Implementation of jax_to_tf.while (#3241) |
260,485 | 01.06.2020 23:43:43 | 14,400 | 7a4b222387abb549b8629ac6815c093a456a5b9d | Added support for np.diagflat | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -28,7 +28,7 @@ from .lax_numpy import (\ncomplex128, complex64, complex_, complexfloating, compress, concatenate,\nconj, conjugate, convolve, copysign, corrcoef, correlate, cos, cosh,\ncount_nonzero, cov, cross, csingle, cumprod, cumproduct, cumsum, deg2rad,\n- degrees, diag, diag_indices, diagonal, diff, digitize, divide, divmod, dot,\n+ degrees, diag, diagflat, diag_indices, diagonal, diff, digitize, divide, divmod, dot,\ndouble, dsplit, dstack, dtype, e, ediff1d, einsum, einsum_path, empty,\nempty_like, equal, euler_gamma, exp, exp2, expand_dims, expm1, extract, eye,\nfabs, finfo, fix, flatnonzero, flexible, flip, fliplr, flipud, float16, float32,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2575,6 +2575,27 @@ def diag(v, k=0):\nelse:\nraise ValueError(\"diag input must be 1d or 2d\")\n+_SCALAR_VALUE_DOC=\"\"\"\\\n+This differs from np.diagflat for some scalar values of v,\n+jax always returns a two-dimensional array, whereas numpy may\n+return a scalar depending on the type of v.\n+\"\"\"\n+\n+@_wraps(np.diagflat, lax_description=_SCALAR_VALUE_DOC)\n+def diagflat(v, k=0):\n+ v = ravel(v)\n+ v_length = len(v)\n+ adj_length = v_length + _abs(k)\n+ res = zeros(adj_length*adj_length, dtype=v.dtype)\n+ i = arange(0, adj_length-_abs(k))\n+ if (k >= 0):\n+ fi = i+k+i*adj_length\n+ else:\n+ fi = i+(i-k)*adj_length\n+ res = ops.index_update(res, ops.index[fi], v)\n+ res = res.reshape(adj_length,adj_length)\n+ return res\n+\n@_wraps(np.polyval)\ndef polyval(p, x):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1455,6 +1455,24 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_k={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), k),\n+ \"dtype\": dtype, \"shape\": shape, \"k\": k}\n+ for dtype in default_dtypes\n+ for shape in all_shapes\n+ for k in range(-4, 4)))\n+ def testDiagFlat(self, shape, dtype, k):\n+ rng = jtu.rand_default(self.rng())\n+ # numpy has inconsistencies for scalar values\n+ # https://github.com/numpy/numpy/issues/16477\n+ # jax differs in that it treats scalars values as length-1 arrays\n+ np_fun = lambda arg: np.diagflat(np.atleast_1d(arg), k)\n+ jnp_fun = lambda arg: jnp.diagflat(arg, k)\n+ args_maker = lambda: [rng(shape, dtype)]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_offset={}_axis1={}_axis2={}\".format(\njtu.format_shape_dtype_string(shape, dtype), offset, axis1, axis2),\n"
}
] | Python | Apache License 2.0 | google/jax | Added support for np.diagflat (#3259) |
260,411 | 02.06.2020 12:35:28 | -10,800 | d36429b5fd992cb16081f44dfd787f28c296e0a8 | Implement jax_to_tf.scan
Also removed the enable_jit, which was needed only
to work around the lack of control flow primitive support. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/__init__.py",
"new_path": "jax/experimental/jax_to_tf/__init__.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-from .jax_to_tf import enable_jit, convert\n+from .jax_to_tf import convert\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/jax_to_tf.py",
"new_path": "jax/experimental/jax_to_tf/jax_to_tf.py",
"diff": "@@ -29,6 +29,7 @@ from jax import numpy as jnp\nfrom jax import tree_util\nfrom jax import util\nfrom jax.api_util import flatten_fun\n+from jax.lax import lax_control_flow\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n@@ -46,27 +47,6 @@ from tensorflow.compiler.xla import xla_data_pb2 # type: ignore[import]\nTfVal = Any\n-# TODO(necula): used for tests, until we handle all control-flow primitives\n-class _JitState(threading.local):\n-\n- def __init__(self):\n- super().__init__()\n- self.disable_jit = True\n-\n-_jit_state = _JitState()\n-\n-\n-@contextlib.contextmanager\n-def enable_jit():\n- \"\"\"Temporarily allow JAX jit.\"\"\"\n- old_state = _jit_state.disable_jit\n- _jit_state.disable_jit = False\n- try:\n- yield\n- finally:\n- _jit_state.disable_jit = old_state\n-\n-\ndef disable_gradient(fun):\n\"\"\"Prevents the wrapped function from being differentiated.\"\"\"\n@@ -111,22 +91,12 @@ def convert(fun):\n\"\"\"\n@disable_gradient\ndef wrapped_fun(*args):\n- # TODO(necula): remove the jit disabling once we handle all control-flow.\n- # Disabling the jit helps to avoid some unsupported jax primitives.\n- # E.g. scan will be statically unrolled.\n- def doit():\nf = lu.wrap_init(fun)\nargs_flat, in_tree = tree_util.tree_flatten((args, {}))\nflat_fun, out_tree = flatten_fun(f, in_tree)\nout_flat = _interpret_fun(flat_fun, args_flat)\nreturn tree_util.tree_unflatten(out_tree(), out_flat)\n- if _jit_state.disable_jit:\n- with jax.disable_jit():\n- return doit()\n- else:\n- return doit()\n-\nreturn wrapped_fun\n# Internals\n@@ -844,6 +814,17 @@ def _batched_while(*args, cond_nconsts: int, cond_jaxpr: core.TypedJaxpr,\ntf_impl[lax.while_p] = _while\n+\n+def _scan(*tf_args : TfVal, **kwargs):\n+ # We use the scan impl rule to rewrite in terms of while. We wrap it under\n+ # _interpret_fun to abstract the TF values from scan_impl.\n+ def func1(*jax_args):\n+ return lax_control_flow._scan_impl(*jax_args, **kwargs)\n+\n+ return _interpret_fun(lu.wrap_init(func1), tf_args)\n+\n+tf_impl[lax.scan_p] = _scan\n+\n# TODO: add_any\n# TODO: after_all\n# TODO: all_to_all\n@@ -870,7 +851,6 @@ tf_impl[lax.while_p] = _while\n# TODO: reduce\n# TODO: reduce_window\n# TODO: rng_uniform\n-# TODO: scan\n# TODO: select_and_gather_add\n# TODO: select_and_scatter\n# TODO: sort\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"new_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"diff": "@@ -122,6 +122,11 @@ class TfOpsTest(jtu.JaxTestCase):\nf_tf = jax_to_tf.convert(f_jax)\nnp.testing.assert_allclose(f_jax(0.7), f_tf(0.7))\n+ def test_nested_jit(self):\n+ f_jax = jax.jit(lambda x: jnp.sin(jax.jit(jnp.cos)(x)))\n+ f_tf = jax_to_tf.convert(f_jax)\n+ np.testing.assert_allclose(f_jax(0.7), f_tf(0.7))\n+\ndef test_converts_jax_arrays(self):\nf_tf = tf.function(lambda x: x)\nself.assertEqual(f_tf(jnp.zeros([])).numpy(), 0.)\n@@ -349,8 +354,6 @@ class ControlFlowOpsTest(parameterized.TestCase):\n@parameterized.parameters(False, True)\ndef test_cond(self, with_function=False):\n- with jax_to_tf.enable_jit():\n-\ndef f_jax(pred, x):\nreturn lax.cond(pred, lambda t: t + 1., lambda f: f, x)\n@@ -362,8 +365,6 @@ class ControlFlowOpsTest(parameterized.TestCase):\n@parameterized.parameters(False, True)\ndef test_cond_multiple_results(self, with_function=False):\n- with jax_to_tf.enable_jit():\n-\ndef f_jax(pred, x):\nreturn lax.cond(pred, lambda t: (t + 1., 1.), lambda f: (f + 2., 2.), x)\n@@ -380,7 +381,6 @@ class ControlFlowOpsTest(parameterized.TestCase):\nfor with_function in [False, True]))\ndef test_while_single_carry(self, with_function=False):\n\"\"\"A while with a single carry\"\"\"\n- with jax_to_tf.enable_jit():\ndef func(x):\n# Equivalent to:\n# for(i=x; i < 4; i++);\n@@ -399,7 +399,6 @@ class ControlFlowOpsTest(parameterized.TestCase):\nwith_function=with_function)\nfor with_function in [False, True]))\ndef test_while(self, with_function=False):\n- with jax_to_tf.enable_jit():\n# Some constants to capture in the conditional branches\ncond_const = np.ones(3, dtype=np.float32)\nbody_const1 = np.full_like(cond_const, 1.)\n@@ -441,7 +440,6 @@ class ControlFlowOpsTest(parameterized.TestCase):\nfor with_function in [False, True]))\ndef test_while_batched(self, with_function=True):\n\"\"\"A while with a single carry\"\"\"\n- with jax_to_tf.enable_jit():\ndef product(x, y):\n# Equivalent to \"x * y\" implemented as:\n# res = 0.\n@@ -473,13 +471,10 @@ class ControlFlowOpsTest(parameterized.TestCase):\n@parameterized.parameters(False, True)\ndef test_scan(self, with_function=False):\ndef f_jax(xs, ys):\n- # Equivalent to:\n- # res = 0.\n- # for x, y in zip(xs, ys):\n- # res += x * y\n- def body(carry, inputs):\n+ body_const = np.ones((2, ), dtype=np.float32) # Test constant capture\n+ def body(res0, inputs):\nx, y = inputs\n- return carry + x * y, carry\n+ return res0 + x * y, body_const\nreturn lax.scan(body, 0., (xs, ys))\nf_tf = jax_to_tf.convert(f_jax)\n"
}
] | Python | Apache License 2.0 | google/jax | Implement jax_to_tf.scan (#3260)
Also removed the enable_jit, which was needed only
to work around the lack of control flow primitive support. |
260,335 | 02.06.2020 17:37:20 | 25,200 | c42a7f7890205bbeacd5511161b7af04eb512417 | remove some trailing whitespace | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/linalg.py",
"new_path": "jax/numpy/linalg.py",
"diff": "@@ -170,7 +170,7 @@ def _cofactor_solve(a, b):\nIf a is rank n-1, then the lower right corner of u will be zero and the\ntriangular_solve will fail.\nLet x = solve(p @ l, b) and y = det(a)*solve(a, b).\n- Then y_{n} =\n+ Then y_{n}\nx_{n} / u_{nn} * prod_{i=1...n}(u_{ii}) =\nx_{n} * prod_{i=1...n-1}(u_{ii})\nSo by replacing the lower-right corner of u with prod_{i=1...n-1}(u_{ii})^-1\n"
}
] | Python | Apache License 2.0 | google/jax | remove some trailing whitespace (#3287) |
260,335 | 02.06.2020 20:28:21 | 25,200 | 538691b9f4b4edc4457b50e19a56d0cbd3bbc68d | remove `pack` from optimizers.py
It is vestigial, from a time when JaxTuples roamed free. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optimizers.py",
"new_path": "jax/experimental/optimizers.py",
"diff": "@@ -88,12 +88,11 @@ zip = safe_zip\n# Since pytrees can be flattened, that structure is isomorphic to a list of\n# lists (with no further nesting).\n-pack = tuple\nOptimizerState = namedtuple(\"OptimizerState\",\n- [\"packed_state\", \"tree_def\", \"subtree_defs\"])\n+ [\"states_flat\", \"tree_def\", \"subtree_defs\"])\nregister_pytree_node(\nOptimizerState,\n- lambda xs: ((xs.packed_state,), (xs.tree_def, xs.subtree_defs)),\n+ lambda xs: ((xs.states_flat,), (xs.tree_def, xs.subtree_defs)),\nlambda data, xs: OptimizerState(xs[0], data[0], data[1]))\ndef optimizer(opt_maker):\n@@ -138,19 +137,18 @@ def optimizer(opt_maker):\nx0_flat, tree = tree_flatten(x0_tree)\ninitial_states = [init(x0) for x0 in x0_flat]\nstates_flat, subtrees = unzip2(map(tree_flatten, initial_states))\n- packed_state = pack(map(pack, states_flat))\n- return OptimizerState(packed_state, tree, subtrees)\n+ return OptimizerState(states_flat, tree, subtrees)\n@functools.wraps(update)\ndef tree_update(i, grad_tree, opt_state):\n- packed_state, tree, subtrees = opt_state\n+ states_flat, tree, subtrees = opt_state\ngrad_flat, tree2 = tree_flatten(grad_tree)\nif tree2 != tree:\nmsg = (\"optimizer update function was passed a gradient tree that did \"\n\"not match the parameter tree structure with which it was \"\n\"initialized: parameter tree {} and grad tree {}.\")\nraise TypeError(msg.format(tree, tree2))\n- states = map(tree_unflatten, subtrees, packed_state)\n+ states = map(tree_unflatten, subtrees, states_flat)\nnew_states = map(partial(update, i), grad_flat, states)\nnew_states_flat, subtrees2 = unzip2(map(tree_flatten, new_states))\nfor subtree, subtree2 in zip(subtrees, subtrees2):\n@@ -158,13 +156,12 @@ def optimizer(opt_maker):\nmsg = (\"optimizer update function produced an output structure that \"\n\"did not match its input structure: input {} and output {}.\")\nraise TypeError(msg.format(subtree, subtree2))\n- new_packed_state = pack(map(pack, new_states_flat))\n- return OptimizerState(new_packed_state, tree, subtrees)\n+ return OptimizerState(new_states_flat, tree, subtrees)\n@functools.wraps(get_params)\ndef tree_get_params(opt_state):\n- packed_state, tree, subtrees = opt_state\n- states = map(tree_unflatten, subtrees, packed_state)\n+ states_flat, tree, subtrees = opt_state\n+ states = map(tree_unflatten, subtrees, states_flat)\nparams = map(get_params, states)\nreturn tree_unflatten(tree, params)\n@@ -551,8 +548,8 @@ def unpack_optimizer_state(opt_state):\nReturns:\nA pytree with JoinPoint leaves that contain a second level of pytrees.\n\"\"\"\n- packed_state, tree_def, subtree_defs = opt_state\n- subtrees = map(tree_unflatten, subtree_defs, packed_state)\n+ states_flat, tree_def, subtree_defs = opt_state\n+ subtrees = map(tree_unflatten, subtree_defs, states_flat)\nsentinels = [JoinPoint(subtree) for subtree in subtrees]\nreturn tree_util.tree_unflatten(tree_def, sentinels)\n@@ -573,5 +570,4 @@ def pack_optimizer_state(marked_pytree):\nassert all(isinstance(s, JoinPoint) for s in sentinels)\nsubtrees = [s.subtree for s in sentinels]\nstates_flat, subtree_defs = unzip2(map(tree_flatten, subtrees))\n- packed_state = pack(map(pack, states_flat))\n- return OptimizerState(packed_state, tree_def, subtree_defs)\n+ return OptimizerState(states_flat, tree_def, subtree_defs)\n"
}
] | Python | Apache License 2.0 | google/jax | remove `pack` from optimizers.py (#3305)
It is vestigial, from a time when JaxTuples roamed free. |
260,335 | 02.06.2020 20:28:59 | 25,200 | b58eec51ac28fcf49093adf8092726597ef6cfb8 | make pmap axis checking an exception, hoist | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1116,6 +1116,9 @@ def pmap(fun: Callable, axis_name: Optional[AxisName] = None, *, in_axes=0,\ndonate_tuple = rebase_donate_argnums(_ensure_tuple(donate_argnums),\nstatic_broadcasted_tuple)\n+ if any(axis != 0 for axis in tree_leaves(in_axes)):\n+ raise ValueError(f\"pmap in_axes leaves must be 0 or None, got {in_axes}\")\n+\n# axis_size is an optional integer representing the global axis size.\n# The aggregate size (across all hosts) size of the mapped axis must match\n# the given value. This argument is mutually exclusive with ``devices``.\n@@ -1145,8 +1148,6 @@ def pmap(fun: Callable, axis_name: Optional[AxisName] = None, *, in_axes=0,\nargs, in_tree = tree_flatten((dyn_args, kwargs))\ndonated_invars = donation_vector(donate_tuple, dyn_args, kwargs)\nin_axes_flat = flatten_axes(in_tree, (dyn_in_axes, 0))\n- assert all(axis in (0, None) for axis in in_axes_flat), \\\n- \"pmap currently only supports mapping over the leading axis\"\nlocal_axis_size = _mapped_axis_size(in_tree, args, in_axes_flat, \"pmap\")\nfor arg in args: _check_arg(arg)\nflat_fun, out_tree = flatten_fun(f, in_tree)\n@@ -1184,13 +1185,14 @@ def soft_pmap(fun: Callable, axis_name: Optional[AxisName] = None, *,\n_check_callable(fun)\naxis_name = _TempAxisName(fun) if axis_name is None else axis_name\n+ if any(axis != 0 for axis in tree_leaves(in_axes)):\n+ raise ValueError(f\"soft_pmap in_axes leaves must be 0 or None, got {in_axes}\")\n+\n@wraps(fun)\ndef f_pmapped(*args, **kwargs):\nf = lu.wrap_init(fun)\nargs_flat, in_tree = tree_flatten((args, kwargs))\nin_axes_flat = flatten_axes(in_tree, (in_axes, 0))\n- assert all(axis in (0, None) for axis in in_axes_flat), \\\n- \"soft_pmap currently only supports mapping over the leading axis\"\nmapped_invars = tuple(axis is not None for axis in in_axes_flat)\naxis_size = _mapped_axis_size(in_tree, args_flat, in_axes_flat, \"soft_pmap\")\nfor arg in args_flat: _check_arg(arg)\n"
}
] | Python | Apache License 2.0 | google/jax | make pmap axis checking an exception, hoist (#3239) |
260,335 | 03.06.2020 07:32:44 | 25,200 | 0e229e4ea8c7361e1a72c2b15b9f18d9829c0a03 | keep old name 'packed_state' of OptimizerState | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optimizers.py",
"new_path": "jax/experimental/optimizers.py",
"diff": "@@ -89,10 +89,10 @@ zip = safe_zip\n# lists (with no further nesting).\nOptimizerState = namedtuple(\"OptimizerState\",\n- [\"states_flat\", \"tree_def\", \"subtree_defs\"])\n+ [\"packed_state\", \"tree_def\", \"subtree_defs\"])\nregister_pytree_node(\nOptimizerState,\n- lambda xs: ((xs.states_flat,), (xs.tree_def, xs.subtree_defs)),\n+ lambda xs: ((xs.packed_state,), (xs.tree_def, xs.subtree_defs)),\nlambda data, xs: OptimizerState(xs[0], data[0], data[1]))\ndef optimizer(opt_maker):\n"
}
] | Python | Apache License 2.0 | google/jax | keep old name 'packed_state' of OptimizerState |
260,519 | 04.06.2020 03:26:35 | -36,000 | b998044ffed2f36f683c9dce4fbd2914d5b7de44 | Add np.polyadd | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -211,6 +211,7 @@ Not every function in NumPy is implemented; contributions are welcome!\npackbits\npad\npercentile\n+ polyadd\npolyval\npower\npositive\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -47,7 +47,7 @@ from .lax_numpy import (\nnanmax, nanmean, nanmin, nanprod, nanstd, nansum, nanvar, ndarray, ndim,\nnegative, newaxis, nextafter, nonzero, not_equal, number, numpy_version,\nobject_, ones, ones_like, operator_name, outer, packbits, pad, percentile,\n- pi, polyval, positive, power, prod, product, promote_types, ptp, quantile,\n+ pi, polyadd, polyval, positive, power, prod, product, promote_types, ptp, quantile,\nrad2deg, radians, ravel, real, reciprocal, remainder, repeat, reshape,\nresult_type, right_shift, rint, roll, rollaxis, rot90, round, row_stack,\nsave, savez, searchsorted, select, set_printoptions, shape, sign, signbit,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2609,6 +2609,19 @@ def polyval(p, x):\ny = y * x + p[i]\nreturn y\n+@_wraps(np.polyadd)\n+def polyadd(a, b):\n+ a = asarray(a)\n+ b = asarray(b)\n+\n+ shape_diff = a.shape[0] - b.shape[0]\n+ if shape_diff > 0:\n+ b = concatenate((np.zeros(shape_diff, dtype=b.dtype), b))\n+ else:\n+ a = concatenate((np.zeros(shape_diff, dtype=b.dtype), a))\n+\n+ return lax.add(a,b)\n+\n@_wraps(np.append)\ndef append(arr, values, axis=None):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1117,6 +1117,22 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape, jnp.float32), rng(shape, dtype)]\nself._CheckAgainstNumpy(np.extract, jnp.extract, args_maker)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype)),\n+ \"dtype\": dtype, \"shape\": shape}\n+ for dtype in default_dtypes\n+ for shape in one_dim_array_shapes))\n+ def testPolyAdd(self, shape, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ np_fun = lambda arg1, arg2: np.polyadd(arg1, arg2)\n+ jnp_fun = lambda arg1, arg2: jnp.polyadd(arg1, arg2)\n+ args_maker = lambda: [rng(shape, dtype), rng(shape, dtype)]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_axis={}\".format(\njtu.format_shape_dtype_string(shape, dtype), axis),\n"
}
] | Python | Apache License 2.0 | google/jax | Add np.polyadd (#3261) |
260,411 | 04.06.2020 09:41:45 | -10,800 | afa9276f0869305afe12cbaec88fe3fb535de807 | Implement jax_to_tf.scan | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/jax_to_tf.py",
"new_path": "jax/experimental/jax_to_tf/jax_to_tf.py",
"diff": "@@ -29,6 +29,7 @@ from jax import numpy as jnp\nfrom jax import tree_util\nfrom jax import util\nfrom jax.api_util import flatten_fun\n+from jax.lax import lax_control_flow\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n@@ -844,6 +845,17 @@ def _batched_while(*args, cond_nconsts: int, cond_jaxpr: core.TypedJaxpr,\ntf_impl[lax.while_p] = _while\n+\n+def _scan(*tf_args : TfVal, **kwargs):\n+ # We use the scan impl rule to rewrite in terms of while. We wrap it under\n+ # _interpret_fun to abstract the TF values from scan_impl.\n+ def func1(*jax_args):\n+ return lax_control_flow._scan_impl(*jax_args, **kwargs)\n+\n+ return _interpret_fun(lu.wrap_init(func1), tf_args)\n+\n+tf_impl[lax.scan_p] = _scan\n+\n# TODO: add_any\n# TODO: after_all\n# TODO: all_to_all\n@@ -870,7 +882,6 @@ tf_impl[lax.while_p] = _while\n# TODO: reduce\n# TODO: reduce_window\n# TODO: rng_uniform\n-# TODO: scan\n# TODO: select_and_gather_add\n# TODO: select_and_scatter\n# TODO: sort\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"new_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"diff": "@@ -122,6 +122,11 @@ class TfOpsTest(jtu.JaxTestCase):\nf_tf = jax_to_tf.convert(f_jax)\nnp.testing.assert_allclose(f_jax(0.7), f_tf(0.7))\n+ def test_nested_jit(self):\n+ f_jax = jax.jit(lambda x: jnp.sin(jax.jit(jnp.cos)(x)))\n+ f_tf = jax_to_tf.convert(f_jax)\n+ np.testing.assert_allclose(f_jax(0.7), f_tf(0.7))\n+\ndef test_converts_jax_arrays(self):\nf_tf = tf.function(lambda x: x)\nself.assertEqual(f_tf(jnp.zeros([])).numpy(), 0.)\n@@ -473,15 +478,13 @@ class ControlFlowOpsTest(parameterized.TestCase):\n@parameterized.parameters(False, True)\ndef test_scan(self, with_function=False):\ndef f_jax(xs, ys):\n- # Equivalent to:\n- # res = 0.\n- # for x, y in zip(xs, ys):\n- # res += x * y\n- def body(carry, inputs):\n+ body_const = np.ones((2, ), dtype=np.float32) # Test constant capture\n+ def body(res0, inputs):\nx, y = inputs\n- return carry + x * y, carry\n+ return res0 + x * y, body_const\nreturn lax.scan(body, 0., (xs, ys))\n+ with jax_to_tf.enable_jit():\nf_tf = jax_to_tf.convert(f_jax)\nif with_function:\nf_tf = tf.function(f_tf)\n"
}
] | Python | Apache License 2.0 | google/jax | Implement jax_to_tf.scan (#3307) |
260,299 | 04.06.2020 11:25:30 | -3,600 | c04dea1c84b657d014412a04a5312e7e525b7501 | Begin implementing mask(jit) | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -26,7 +26,7 @@ from .. import abstract_arrays\nfrom .. import core\nfrom ..tree_util import tree_unflatten\nfrom ..core import Trace, Tracer\n-from ..util import safe_map, safe_zip, unzip2, prod\n+from ..util import safe_map, safe_zip, unzip2, prod, wrap_name\nfrom ..abstract_arrays import ShapedArray\nfrom .. import linear_util as lu\n@@ -77,22 +77,29 @@ def padded_shape_as_value(shape):\nreturn eval_polymorphic_shape(shape, shape_envs.padded)\ndef mask_fun(fun, logical_env, padded_env, in_vals, polymorphic_shapes):\n+ env_keys, padded_env_vals = unzip2(sorted(padded_env.items()))\n+ logical_env_vals = [logical_env[k] for k in env_keys]\n+ # Make padded_env hashable\n+ padded_env = (env_keys, padded_env_vals)\nwith core.new_master(MaskTrace) as master:\n- fun, out_shapes = mask_subtrace(fun, master, polymorphic_shapes)\n- with extend_shape_envs(logical_env, padded_env):\n- out_vals = fun.call_wrapped(*in_vals)\n+ fun, out_shapes = mask_subtrace(fun, master, polymorphic_shapes, padded_env)\n+ out_vals = fun.call_wrapped(*(logical_env_vals + in_vals))\ndel master\nreturn out_vals, out_shapes()\n@lu.transformation_with_aux\n-def mask_subtrace(master, polymorphic_shapes, *in_vals):\n+def mask_subtrace(master, shapes, padded_env, *in_vals):\n+ env_keys, _ = padded_env\n+ logical_env_vals, in_vals = in_vals[:len(env_keys)], in_vals[len(env_keys):]\n+ logical_env = dict(zip(env_keys, logical_env_vals))\n+ padded_env = dict(zip(*padded_env))\ntrace = MaskTrace(master, core.cur_sublevel())\nin_tracers = [MaskTracer(trace, x, s).full_lower()\n- for x, s in zip(in_vals, polymorphic_shapes)]\n+ for x, s in zip(in_vals, shapes)]\n+ with extend_shape_envs(logical_env, padded_env):\nouts = yield in_tracers, {}\nout_tracers = map(trace.full_raise, outs)\n- out_vals, out_shapes = unzip2((t.val, t.polymorphic_shape)\n- for t in out_tracers)\n+ out_vals, out_shapes = unzip2((t.val, t.polymorphic_shape) for t in out_tracers)\nyield out_vals, out_shapes\ndef eval_polymorphic_shape(shape, values_dict):\n@@ -378,7 +385,8 @@ class MaskTrace(Trace):\nlogical_shapes = map(shape_as_value, polymorphic_shapes)\nmasking_rule = masking_rules.get(primitive)\nif masking_rule is None:\n- raise NotImplementedError('Masking rule for {} not implemented yet.'.format(primitive))\n+ raise NotImplementedError(\n+ 'Masking rule for {} not implemented yet.'.format(primitive))\nout = masking_rule(vals, logical_shapes, **params)\nif not primitive.multiple_results:\nreturn MaskTracer(self, out, out_shape)\n@@ -386,7 +394,20 @@ class MaskTrace(Trace):\nreturn map(partial(MaskTracer, self), out, out_shape)\ndef process_call(self, call_primitive, f, tracers, params):\n- raise NotImplementedError\n+ assert call_primitive.multiple_results\n+ params = dict(params, name=wrap_name(params.get('name', f.__name__), 'mask'))\n+ vals, shapes = unzip2((t.val, t.polymorphic_shape) for t in tracers)\n+ if not any(is_polymorphic(s) for s in shapes):\n+ return call_primitive.bind(f, *vals, **params)\n+ else:\n+ logical_env, padded_env = shape_envs\n+ env_keys, padded_env_vals = unzip2(sorted(padded_env.items()))\n+ logical_env_vals = tuple(logical_env[k] for k in env_keys)\n+ # Make padded_env hashable\n+ padded_env = (env_keys, padded_env_vals)\n+ f, shapes_out = mask_subtrace(f, self.master, shapes, padded_env)\n+ vals_out = call_primitive.bind(f, *(logical_env_vals + vals), **params)\n+ return [MaskTracer(self, v, s) for v, s in zip(vals_out, shapes_out())]\ndef post_process_call(self, call_primitive, out_tracers, params):\nraise NotImplementedError\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -393,7 +393,6 @@ class MaskingTest(jtu.JaxTestCase):\n['float_', 'float_'], rand_default(self.rng()))\ndef test_jit(self):\n- raise SkipTest\n@partial(mask, in_shapes=['n'], out_shape='2*n')\n@jit\ndef duplicate(x):\n"
}
] | Python | Apache License 2.0 | google/jax | Begin implementing mask(jit) |
260,299 | 04.06.2020 12:28:38 | -3,600 | dfe3462746d701b08f3d1ee814534f228d2fa199 | Add device_put_p abstract_eval rule | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1202,6 +1202,7 @@ device_put_p = core.Primitive('device_put')\ndevice_put_p.def_impl(_device_put_impl)\npe.custom_partial_eval_rules[device_put_p] = lambda trace, x, **params: x\nad.deflinear(device_put_p, lambda cotangent, **kwargs: [cotangent])\n+device_put_p.def_abstract_eval(lambda x, **params: x)\nmasking.defvectorized(device_put_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -437,8 +437,6 @@ class MaskingTest(jtu.JaxTestCase):\ndef test_numpy_pad(self):\n- # TODO (j-towns) requires mask(jit)\n- raise SkipTest\ndef numpy_pad(x):\nreturn jnp.pad(x, (0, 1), constant_values=5.)\n@@ -609,8 +607,6 @@ class MaskingTest(jtu.JaxTestCase):\nself.check(d, ['2'], '', {}, [(2,)], ['int_'], rand_int(self.rng(), 0, 10))\ndef test_where(self):\n- # Requires mask(jit)\n- raise SkipTest\nself.check(lambda x: jnp.where(x < 0, x, 0. * x), ['n'], 'n',\n{'n': 2}, [(3,)], ['float_'], rand_default(self.rng()))\n"
}
] | Python | Apache License 2.0 | google/jax | Add device_put_p abstract_eval rule |
260,299 | 04.06.2020 12:50:47 | -3,600 | 0f0032727b68e3fc07164c3505ad5c80c9c08503 | Implement MaskTrace.post_process_call | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -410,7 +410,12 @@ class MaskTrace(Trace):\nreturn [MaskTracer(self, v, s) for v, s in zip(vals_out, shapes_out())]\ndef post_process_call(self, call_primitive, out_tracers, params):\n- raise NotImplementedError\n+ vals, shapes = unzip2((t.val, t.polymorphic_shape) for t in out_tracers)\n+ master = self.master\n+ def todo(vals):\n+ trace = MaskTrace(master, core.cur_sublevel())\n+ return map(partial(MaskTracer, trace), vals, shapes)\n+ return vals, todo\nclass UniqueId:\ndef __init__(self, name):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -407,6 +407,17 @@ class MaskingTest(jtu.JaxTestCase):\nout = duplicate([jnp.arange(3)], dict(n=2))\nassert np.all(np.array([0, 1, 0, 1]) == out[:4])\n+ def test_jit2(self):\n+ # Trigger MaskTrace.post_process_call\n+ def fun(x):\n+ @jit\n+ def concat(y):\n+ return lax.concatenate([x, y], 0)\n+ return concat(jnp.array([1., 2., 3.]))\n+\n+ self.check(fun, ['n'], '(n+3,)', {'n': 2}, [(3,)], ['float_'],\n+ rand_default(self.rng()))\n+\n@parameterized.named_parameters({\n'testcase_name': \"padding_config={}_shapes={}\".format(padding_config,\nshape),\n"
}
] | Python | Apache License 2.0 | google/jax | Implement MaskTrace.post_process_call |
260,299 | 04.06.2020 15:05:14 | -3,600 | 38d483737d0e35f77ed79fc279574b4b2dc46937 | Fix x64 test | [
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -413,9 +413,9 @@ class MaskingTest(jtu.JaxTestCase):\n@jit\ndef concat(y):\nreturn lax.concatenate([x, y], 0)\n- return concat(jnp.array([1., 2., 3.]))\n+ return concat(jnp.array([1., 2., 3.], dtype='float32'))\n- self.check(fun, ['n'], '(n+3,)', {'n': 2}, [(3,)], ['float_'],\n+ self.check(fun, ['n'], '(n+3,)', {'n': 2}, [(3,)], ['float32'],\nrand_default(self.rng()))\n@parameterized.named_parameters({\n"
}
] | Python | Apache License 2.0 | google/jax | Fix x64 test |
260,335 | 04.06.2020 10:13:15 | 25,200 | 9c0a58a8e774171e5e465bd81d2fad481c5264fc | add float dtype checks to random.py
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -359,6 +359,9 @@ def uniform(key: jnp.ndarray,\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `uniform` must be a float dtype, \"\n+ f\"got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\nreturn _uniform(key, shape, dtype, minval, maxval)\n@@ -543,6 +546,9 @@ def normal(key: jnp.ndarray,\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `normal` must be a float dtype, \"\n+ f\"got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\nreturn _normal(key, shape, dtype)\n@@ -581,6 +587,9 @@ def multivariate_normal(key: jnp.ndarray,\n``shape + mean.shape[-1:]`` if ``shape`` is not None, or else\n``broadcast_shapes(mean.shape[:-1], cov.shape[:-2]) + mean.shape[-1:]``.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `multivariate_normal` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nif shape is not None:\nshape = abstract_arrays.canonicalize_shape(shape)\n@@ -634,6 +643,9 @@ def truncated_normal(key: jnp.ndarray,\nA random array with the specified dtype and shape given by ``shape`` if\n``shape`` is not None, or else by broadcasting ``lower`` and ``upper``.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `truncated_normal` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nif shape is not None:\nshape = abstract_arrays.canonicalize_shape(shape)\n@@ -714,6 +726,9 @@ def beta(key: jnp.ndarray,\nA random array with the specified dtype and shape given by ``shape`` if\n``shape`` is not None, or else by broadcasting ``a`` and ``b``.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `beta` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nif shape is not None:\nshape = abstract_arrays.canonicalize_shape(shape)\n@@ -748,6 +763,9 @@ def cauchy(key, shape=(), dtype=np.float64):\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `cauchy` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\nreturn _cauchy(key, shape, dtype)\n@@ -780,6 +798,9 @@ def dirichlet(key, alpha, shape=None, dtype=np.float64):\n``shape + (alpha.shape[-1],)`` if ``shape`` is not None, or else\n``alpha.shape``.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `dirichlet` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nif shape is not None:\nshape = abstract_arrays.canonicalize_shape(shape)\n@@ -814,6 +835,9 @@ def exponential(key, shape=(), dtype=np.float64):\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `exponential` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\nreturn _exponential(key, shape, dtype)\n@@ -1039,6 +1063,9 @@ def gamma(key, a, shape=None, dtype=np.float64):\nA random array with the specified dtype and with shape given by ``shape`` if\n``shape`` is not None, or else by ``a.shape``.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `gamma` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nif shape is not None:\nshape = abstract_arrays.canonicalize_shape(shape)\n@@ -1178,6 +1205,9 @@ def gumbel(key, shape=(), dtype=np.float64):\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `gumbel` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\nreturn _gumbel(key, shape, dtype)\n@@ -1232,6 +1262,9 @@ def laplace(key, shape=(), dtype=np.float64):\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `laplace` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\nreturn _laplace(key, shape, dtype)\n@@ -1257,6 +1290,9 @@ def logistic(key, shape=(), dtype=np.float64):\nReturns:\nA random array with the specified shape and dtype.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `logistic` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\nreturn _logistic(key, shape, dtype)\n@@ -1297,6 +1333,9 @@ def pareto(key, b, shape=None, dtype=np.float64):\nA random array with the specified dtype and with shape given by ``shape`` if\n``shape`` is not None, or else by ``b.shape``.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `pareto` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nif shape is not None:\nshape = abstract_arrays.canonicalize_shape(shape)\n@@ -1331,6 +1370,9 @@ def t(key, df, shape=(), dtype=np.float64):\nA random array with the specified dtype and with shape given by ``shape`` if\n``shape`` is not None, or else by ``df.shape``.\n\"\"\"\n+ if not dtypes.issubdtype(dtype, np.floating):\n+ raise ValueError(f\"dtype argument to `t` must be a float \"\n+ f\"dtype, got {dtype}\")\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = abstract_arrays.canonicalize_shape(shape)\nreturn _t(key, df, shape, dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -687,6 +687,10 @@ class LaxRandomTest(jtu.JaxTestCase):\nrandom.fold_in(k, 4),\nnp.array([2285895361, 433833334], dtype='uint32'))\n+ def testDtypeErrorMessage(self):\n+ with self.assertRaisesRegex(ValueError, r\"dtype argument to.*\"):\n+ random.normal(random.PRNGKey(0), (), dtype=jnp.int32)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | add float dtype checks to random.py (#3320)
fixes #3317 |
260,485 | 04.06.2020 23:27:29 | 14,400 | 969ed6d162e6d92ec691cb5e07edee85d4aa0b03 | Initial implementation of polymul function | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -212,6 +212,7 @@ Not every function in NumPy is implemented; contributions are welcome!\npad\npercentile\npolyadd\n+ polymul\npolyval\npower\npositive\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -48,7 +48,7 @@ from .lax_numpy import (\nnanmax, nanmean, nanmin, nanprod, nanstd, nansum, nanvar, ndarray, ndim,\nnegative, newaxis, nextafter, nonzero, not_equal, number, numpy_version,\nobject_, ones, ones_like, operator_name, outer, packbits, pad, percentile,\n- pi, polyadd, polyval, positive, power, prod, product, promote_types, ptp, quantile,\n+ pi, polyadd, polymul, polyval, positive, power, prod, product, promote_types, ptp, quantile,\nrad2deg, radians, ravel, real, reciprocal, remainder, repeat, reshape,\nresult_type, right_shift, rint, roll, rollaxis, rot90, round, row_stack,\nsave, savez, searchsorted, select, set_printoptions, shape, sign, signbit,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2617,6 +2617,31 @@ def polyadd(a, b):\nreturn lax.add(a,b)\n+def _trim_zeros(a):\n+ for i, v in enumerate(a):\n+ if v != 0:\n+ return a[i:]\n+ return a[:0]\n+\n+_LEADING_ZEROS_DOC=\"\"\"\\\n+Setting trim_leading_zeros=True makes the output match that of numpy.\n+But prevents the function from being able to be used in compiled code.\n+\"\"\"\n+\n+@_wraps(np.polymul, lax_description=_LEADING_ZEROS_DOC)\n+def polymul(a1, a2, *, trim_leading_zeros=False):\n+ if isinstance(a1, np.poly1d):\n+ a1 = asarray(a1)\n+ if isinstance(a2, np.poly1d):\n+ a2 = asarray(a2)\n+ if trim_leading_zeros and (len(a1) > 1 or len(a2) > 1):\n+ a1, a2 = _trim_zeros(a1), _trim_zeros(a2)\n+ if len(a1) == 0:\n+ a1 = asarray([0.])\n+ if len(a2) == 0:\n+ a2 = asarray([0.])\n+ val = convolve(a1, a2, mode='full')\n+ return val\n@_wraps(np.append)\ndef append(arr, values, axis=None):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1505,6 +1505,24 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=True)\nself._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_a1_shape={}_a2_shape2={}\".format(\n+ jtu.format_shape_dtype_string(a1_shape, dtype),\n+ jtu.format_shape_dtype_string(a2_shape, dtype)),\n+ \"dtype\": dtype, \"a1_shape\": a1_shape, \"a2_shape\": a2_shape}\n+ for dtype in default_dtypes\n+ for a1_shape in one_dim_array_shapes\n+ for a2_shape in one_dim_array_shapes))\n+ def testPolyMul(self, a1_shape, a2_shape, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ np_fun = lambda arg1, arg2: np.polymul(arg1, arg2)\n+ jnp_fun_np = lambda arg1, arg2: jnp.polymul(arg1, arg2, trim_leading_zeros=True)\n+ jnp_fun_co = lambda arg1, arg2: jnp.polymul(arg1, arg2)\n+ args_maker = lambda: [rng(a1_shape, dtype), rng(a2_shape, dtype)]\n+ tol = {np.float16: 2e-1, np.float32: 5e-2, np.float64: 1e-14}\n+ self._CheckAgainstNumpy(np_fun, jnp_fun_np, args_maker, check_dtypes=False, tol=tol)\n+ self._CompileAndCheck(jnp_fun_co, args_maker, check_dtypes=False)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_offset={}_axis1={}_axis2={}\".format(\njtu.format_shape_dtype_string(shape, dtype), offset, axis1, axis2),\n"
}
] | Python | Apache License 2.0 | google/jax | Initial implementation of polymul function (#3303) |
260,285 | 05.06.2020 09:04:22 | -7,200 | ea782220c4a95f85933b37955d597ab73783ab22 | Allow mask(split) | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1353,17 +1353,19 @@ def broadcast_to(arr, shape):\n@_wraps(np.split)\ndef split(ary, indices_or_sections, axis=0):\n- dummy_val = np.broadcast_to(0, ary.shape) # zero strides\n+ axis = core.concrete_or_error(int, axis, \"in jax.numpy.split argument `axis`\")\n+ size = ary.shape[axis]\nif isinstance(indices_or_sections, (tuple, list) + _arraylike_types):\nindices_or_sections = [core.concrete_or_error(int, i_s, \"in jax.numpy.split argument 1\")\nfor i_s in indices_or_sections]\n+ split_indices = np.concatenate([[0], indices_or_sections, [size]])\nelse:\nindices_or_sections = core.concrete_or_error(int, indices_or_sections,\n\"in jax.numpy.split argument 1\")\n- axis = core.concrete_or_error(int, axis, \"in jax.numpy.split argument `axis`\")\n-\n- subarrays = np.split(dummy_val, indices_or_sections, axis) # shapes\n- split_indices = np.cumsum([0] + [np.shape(sub)[axis] for sub in subarrays])\n+ part_size, r = _divmod(size, indices_or_sections)\n+ if r != 0:\n+ raise ValueError(\"array split does not result in an equal division\")\n+ split_indices = np.arange(indices_or_sections + 1) * part_size\nstarts, ends = [0] * ndim(ary), shape(ary)\n_subval = lambda x, i, v: subvals(x, [(i, v)])\nreturn [lax.slice(ary, _subval(starts, axis, start), _subval(ends, axis, end))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -616,7 +616,10 @@ class MaskingTest(jtu.JaxTestCase):\n{'n': 2}, [(3,)], ['float_'], rand_default(self.rng()))\ndef test_split(self):\n- raise SkipTest\n+ self.check(lambda x: jnp.split(x, 2), ['2*n'], ['n', 'n'], dict(n=4),\n+ [(8,)], ['float_'], rand_default(self.rng()))\n+ self.check(lambda x: jnp.split(x, [10]), ['n'], ['10', 'n+-10'], dict(n=12),\n+ [(12,)], ['float_'], rand_default(self.rng()))\n@parameterized.named_parameters(jtu.cases_from_list([{\n'testcase_name': \"operator={}\".format(operator.__name__), 'operator': operator}\n"
}
] | Python | Apache License 2.0 | google/jax | Allow mask(split) |
260,287 | 05.06.2020 17:22:55 | -7,200 | 74d160f5e0772b05c249ed6a7d71a846719c394c | Don't keep primal arguments and results in the linearized jaxpr
Linearized functions are supposed to take tangent types to tangent
types, and so all primal arguments are unused and primal results get
replaced by units. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1476,9 +1476,7 @@ def _lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args):\nmsg = (\"linearized function called on tangent values inconsistent with \"\n\"the original primal values.\")\nraise ValueError(msg) from e\n- dummy = (core.unit,) * len(tangents)\n- out = eval_jaxpr(jaxpr, consts, *(dummy + tangents))\n- tangents_out = out[len(out)//2:]\n+ tangents_out = eval_jaxpr(jaxpr, consts, *tangents)\nreturn tuple(map(lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),\nout_pvals, tangents_out))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -96,6 +96,8 @@ def linearize(traceable, *primals, **kwargs):\nout_primals_pvals, out_tangents_pvals = tree_unflatten(out_tree(), out_pvals)\nassert all(out_primal_pval.is_known() for out_primal_pval in out_primals_pvals)\n_, out_primals_consts = unzip2(out_primals_pvals)\n+ jaxpr.invars = jaxpr.invars[len(primals):]\n+ jaxpr.outvars = jaxpr.outvars[len(out_primals_pvals):]\nif not has_aux:\nreturn out_primals_consts, out_tangents_pvals, jaxpr, consts\nelse:\n@@ -108,10 +110,8 @@ def vjp(traceable, primals, has_aux=False):\nout_primals, pvals, jaxpr, consts, aux = linearize(traceable, *primals, has_aux=True)\ndef vjp_(*cts):\ncts = tuple(map(ignore_consts, cts, pvals))\n- dummy_primals_and_cts = (core.unit,) * len(cts) + cts\ndummy_args = [UndefinedPrimal(v.aval) for v in jaxpr.invars]\n- arg_cts = backward_pass(jaxpr, consts, dummy_args, dummy_primals_and_cts)\n- arg_cts = arg_cts[len(primals):]\n+ arg_cts = backward_pass(jaxpr, consts, dummy_args, cts)\nreturn map(instantiate_zeros, primals, arg_cts)\nif not has_aux:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -116,7 +116,11 @@ class JaxprTrace(Trace):\nreturn JaxprTracer(self, PartialVal.unknown(get_aval(val)), ConstVar(val))\ndef new_arg(self, pval: PartialVal) -> 'JaxprTracer':\n+ const = pval.get_known()\n+ if const is None:\nreturn JaxprTracer(self, pval, LambdaBinding())\n+ else:\n+ return self.new_const(const)\ndef instantiate_const(self, tracer) -> Tracer:\nconst = tracer.pval.get_known()\n"
}
] | Python | Apache License 2.0 | google/jax | Don't keep primal arguments and results in the linearized jaxpr (#3233)
Linearized functions are supposed to take tangent types to tangent
types, and so all primal arguments are unused and primal results get
replaced by units. |
260,287 | 27.05.2020 13:57:47 | 0 | adb442eb8ab7e126f34abf6571477a882d7d7a9a | Make ad_util.zero a class that carries avals (similar to UndefinedPrimal)
This is useful for remat transpose rule submitted in and e.g.
allowed me to catch a slight overuse of defjvp2 for `random_gamma_p` (it
was unnecessarily declared as having multiple outputs). | [
{
"change_type": "MODIFY",
"old_path": "jax/ad_util.py",
"new_path": "jax/ad_util.py",
"diff": "from .core import (lattice_join, Primitive, Unit, unit, AbstractUnit,\n- valid_jaxtype)\n+ valid_jaxtype, raise_to_shaped, get_aval)\nfrom .tree_util import register_pytree_node\nfrom typing import Any, Dict\nfrom .util import safe_map\n@@ -58,13 +58,17 @@ def zeros_like_impl(example):\nzeros_like_p.def_abstract_eval(lambda x: x)\n-class Zero(object):\n+class Zero:\n+ __slots__ = ['aval']\n+ def __init__(self, aval):\n+ self.aval = aval\ndef __repr__(self):\n- return \"Zero\"\n+ return 'Zero({})'.format(self.aval)\n+ @staticmethod\n+ def from_value(val):\n+ return Zero(raise_to_shaped(get_aval(val)))\n-zero = Zero()\n-\n-register_pytree_node(Zero, lambda z: ((), None), lambda _, xs: zero)\n+register_pytree_node(Zero, lambda z: ((), z.aval), lambda aval, _: Zero(aval))\ndef _stop_gradient_impl(x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1877,7 +1877,7 @@ def defjvp_all(fun, custom_jvp):\nnum_consts, in_tree = params['num_consts'], params['in_tree']\n_, args_flat = split_list(primals, [num_consts])\nconsts_dot, args_dot_flat = split_list(tangents, [num_consts])\n- if not all(t is ad_util.zero for t in consts_dot):\n+ if not all(type(t) is ad_util.Zero for t in consts_dot):\nmsg = (\"Detected differentiation with respect to closed-over values with \"\n\"custom JVP rule, which isn't supported.\")\nraise ValueError(msg)\n@@ -1901,7 +1901,7 @@ def defjvp(fun, *jvprules):\ndef custom_jvp(primals, tangents):\nans = fun(*primals)\ntangents_out = [rule(t, ans, *primals) for rule, t in zip(jvprules, tangents)\n- if rule is not None and t is not ad_util.zero]\n+ if rule is not None and type(t) is not ad_util.Zero]\nreturn ans, functools.reduce(ad.add_tangents, tangents_out, ad_util.zero)\ndefjvp_all(fun, custom_jvp)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -24,7 +24,7 @@ from .tree_util import tree_flatten, tree_unflatten, tree_map, tree_multimap\nfrom .util import safe_zip, safe_map, unzip2, split_list, curry\nfrom .api_util import flatten_fun_nokwargs, argnums_partial, wrap_hashably\nfrom .abstract_arrays import raise_to_shaped\n-from .ad_util import zero, stop_gradient_p\n+from .ad_util import Zero, stop_gradient_p\nfrom .interpreters import partial_eval as pe\nfrom .interpreters import ad\nfrom .interpreters import batching\n@@ -80,7 +80,7 @@ def sum_tangents(x, *xs):\nreturn reduce(ad.add_tangents, xs, x)\ndef zeros_like_pytree(x):\n- return tree_map(lambda _: zero, x)\n+ return tree_map(Zero.from_value, x)\ndef stop_gradient(x):\nreturn tree_map(_stop_gradient, x)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "import functools\nimport itertools as it\n-from typing import Any, Callable, Dict, Set, List\n+from typing import Any, Callable, Dict, Set, List, Sequence, Optional\nfrom . import partial_eval as pe\nfrom .. import core as core\nfrom ..core import Trace, Tracer, new_master, get_aval, call_p, Primitive, Literal\nfrom ..ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval, zeros_like_aval,\n- zeros_like_p, zero)\n+ zeros_like_p, Zero)\nfrom ..abstract_arrays import raise_to_shaped\nfrom ..util import unzip2, safe_map, safe_zip, partial, split_list, wrap_name\nfrom ..tree_util import register_pytree_node\n@@ -59,7 +59,7 @@ def jvp_subtrace(master, primals, tangents):\nfor x in list(primals) + list(tangents):\nif isinstance(x, Tracer):\nassert x._trace.level < trace.level\n- in_tracers = [JVPTracer(trace, x, t) if t is not zero else x\n+ in_tracers = [JVPTracer(trace, x, t) if type(t) is not Zero else x\nfor x, t in zip(primals, tangents)]\nans = yield in_tracers, {}\nout_tracers = map(trace.full_raise, ans)\n@@ -139,19 +139,19 @@ def unpair_pval(pval):\n# NOTE: The FIXMEs below are caused by primal/tangent mixups (type errors if you will)\ndef backward_pass(jaxpr: core.Jaxpr, consts, primals_in, cotangents_in):\n- if all(ct is zero for ct in cotangents_in):\n- return [zero] * len(jaxpr.invars)\n+ if all(type(ct) is Zero for ct in cotangents_in):\n+ return map(lambda v: Zero(v.aval), jaxpr.invars)\ndef write_cotangent(v, ct):\n# assert v not in primal_env\n- if ct is not None and type(v) is not Literal and ct is not zero:\n+ if ct is not None and type(v) is not Literal and type(ct) is not Zero:\nct_env[v] = add_tangents(ct_env[v], ct) if v in ct_env else ct\nif not core.skip_checks:\nct_aval = core.get_aval(ct_env[v])\nassert v.aval == core.lattice_join(v.aval, ct_aval), (v.aval, ct_aval)\ndef read_cotangent(v):\n- return ct_env.get(v, zero)\n+ return ct_env.get(v, Zero(v.aval))\ndef read_primal(v):\nif type(v) is Literal:\n@@ -195,7 +195,7 @@ def backward_pass(jaxpr: core.Jaxpr, consts, primals_in, cotangents_in):\nparams, call_jaxpr, invals, cts_in, cts_in_avals)\nelse:\ncts_out = get_primitive_transpose(eqn.primitive)(cts_in, *invals, **eqn.params)\n- cts_out = [zero] * len(eqn.invars) if cts_out is zero else cts_out\n+ cts_out = map(lambda v: Zero(v.aval), eqn.invars) if cts_out is Zero else cts_out\n# FIXME: Some invars correspond to primals!\nmap(write_cotangent, eqn.invars, cts_out)\nfor var in to_drop:\n@@ -229,10 +229,10 @@ def get_primitive_transpose(p):\nclass JVPTrace(Trace):\ndef pure(self, val):\n- return JVPTracer(self, val, zero)\n+ return JVPTracer(self, val, Zero.from_value(val))\ndef lift(self, val):\n- return JVPTracer(self, val, zero)\n+ return JVPTracer(self, val, Zero.from_value(val))\ndef sublift(self, val):\nreturn JVPTracer(self, val.primal, val.tangent)\n@@ -291,10 +291,10 @@ class JVPTrace(Trace):\nnew_name = wrap_name(params.get('name', f.__name__), 'jvp')\nnew_mapped_invars = (*params['mapped_invars'],\n*[m for m, t in zip(params['mapped_invars'], tangents)\n- if t is not zero])\n+ if type(t) is not Zero])\nnew_donated_invars = (*params['donated_invars'],\n*[m for m, t in zip(params['donated_invars'], tangents)\n- if t is not zero])\n+ if type(t) is not Zero])\nnew_params = dict(params, name=new_name, mapped_invars=new_mapped_invars,\ndonated_invars=new_donated_invars)\nresult = map_primitive.bind(f_jvp, *primals, *nonzero_tangents, **new_params)\n@@ -323,7 +323,7 @@ class JVPTrace(Trace):\nreturn map(partial(JVPTracer, self), primals_out, tangents_out)\ndef join(self, xt, yt):\n- xz, yz = xt is zero, yt is zero\n+ xz, yz = type(xt) is Zero, type(yt) is Zero\nif xz == yz:\nreturn xt, yt\nelif yz and not xz:\n@@ -350,13 +350,13 @@ class JVPTracer(Tracer):\nreturn get_aval(self.primal)\ndef full_lower(self):\n- if self.tangent is zero:\n+ if type(self.tangent) is Zero:\nreturn core.full_lower(self.primal)\nelse:\nreturn self\ndef _primal_tangent_shapes_match(primal, tangent):\n- if tangent is not zero:\n+ if type(tangent) is not Zero:\nprimal_aval = raise_to_shaped(get_aval(primal))\ntangent_aval = raise_to_shaped(get_aval(tangent))\nassert primal_aval == tangent_aval\n@@ -375,14 +375,14 @@ def deflinear(primitive, transpose_rule):\ndef linear_jvp(primitive, primals, tangents, **params):\nval_out = primitive.bind(*primals, **params)\n- if all(tangent is zero for tangent in tangents):\n- return val_out, zero\n+ if all(type(tangent) is Zero for tangent in tangents):\n+ return val_out, Zero.from_value(val_out)\nelse:\ntangents = map(instantiate_zeros, primals, tangents)\nreturn val_out, primitive.bind(*tangents, **params)\ndef linear_transpose(transpose_rule, cotangent, *args, **kwargs):\n- return zero if cotangent is zero else transpose_rule(cotangent, **kwargs)\n+ return Zero if type(cotangent) is Zero else transpose_rule(cotangent, **kwargs)\ndef deflinear2(primitive, transpose_rule):\n@@ -390,34 +390,37 @@ def deflinear2(primitive, transpose_rule):\nprimitive_transposes[primitive] = partial(linear_transpose2, transpose_rule)\ndef linear_transpose2(transpose_rule, cotangent, *args, **kwargs):\n- return zero if cotangent is zero else transpose_rule(cotangent, *args, **kwargs)\n+ return Zero if type(cotangent) is Zero else transpose_rule(cotangent, *args, **kwargs)\ndef defjvp(primitive, *jvprules):\nassert isinstance(primitive, Primitive)\n+ assert not primitive.multiple_results\nprimitive_jvps[primitive] = partial(standard_jvp, jvprules, primitive)\ndef standard_jvp(jvprules, primitive, primals, tangents, **params):\nval_out = primitive.bind(*primals, **params)\ntangents_out = [rule(t, *primals, **params) for rule, t in zip(jvprules, tangents)\n- if rule is not None and t is not zero]\n- return val_out, functools.reduce(add_tangents, tangents_out, zero)\n+ if rule is not None and type(t) is not Zero]\n+ return val_out, functools.reduce(add_tangents, tangents_out, Zero.from_value(val_out))\ndef defjvp2(primitive, *jvprules):\nassert isinstance(primitive, Primitive)\n+ assert not primitive.multiple_results\nprimitive_jvps[primitive] = partial(standard_jvp2, jvprules, primitive)\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)\n- if rule is not None and t is not zero)\n- return val_out, functools.reduce(add_tangents, tangents_out, zero)\n+ if rule is not None and type(t) is not Zero)\n+ tangents_out = list(tangents_out)\n+ return val_out, functools.reduce(add_tangents, tangents_out, Zero.from_value(val_out))\ndef add_tangents(x, y):\n- if x is zero:\n+ if type(x) is Zero:\nreturn y\n- elif y is zero:\n+ elif type(y) is Zero:\nreturn x\nelse:\nreturn add_jaxvals(x, y)\n@@ -433,12 +436,14 @@ defbilinear = partial(defbilinear_broadcasting, lambda g, x: g)\ndef bilinear_transpose(lhs_rule, rhs_rule, cotangent, x, y, **kwargs):\nassert is_undefined_primal(x) ^ is_undefined_primal(y)\n+ if type(cotangent) is Zero:\n+ return Zero\nif is_undefined_primal(x):\n- out = zero if cotangent is zero else lhs_rule(cotangent, y, **kwargs)\n- return out, None\n+ out = lhs_rule(cotangent, y, **kwargs)\n+ return Zero if out is Zero else (out, None)\nelse:\n- out = zero if cotangent is zero else rhs_rule(cotangent, x, **kwargs)\n- return None, out\n+ out = rhs_rule(cotangent, x, **kwargs)\n+ return Zero if out is Zero else (None, out)\ndef defjvp_zero(primitive):\n@@ -446,21 +451,22 @@ def defjvp_zero(primitive):\nprimitive_jvps[primitive] = partial(zero_jvp, primitive)\ndef zero_jvp(primitive, primals, tangents, **params):\n- return primitive.bind(*primals, **params), zero\n+ r = primitive.bind(*primals, **params)\n+ return r, Zero.from_value(r)\n-deflinear(zeros_like_p, lambda t: [zero])\n+deflinear(zeros_like_p, lambda t: [Zero.from_value(t)])\ndeflinear(core.identity_p, lambda t: (t,))\ndeflinear(add_jaxvals_p, lambda t: (t, t))\ndef instantiate_zeros(example, tangent):\n- if tangent is zero:\n+ if type(tangent) is Zero:\nreturn zeros_like_jaxval(example)\nelse:\nreturn tangent\ndef instantiate_zeros_aval(aval, tangent):\n- if tangent is zero:\n+ if type(tangent) is Zero:\nreturn zeros_like_aval(aval)\nelse:\nreturn tangent\n@@ -527,10 +533,10 @@ def map_transpose(primitive, params, call_jaxpr, args, ct, _):\nfun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\nnew_mapped_invars = (*[m for m, x in zip(params['mapped_invars'], args)\nif not is_undefined_primal(x)],\n- *[True for x in ct if x is not zero])\n+ *[True for x in ct if type(x) is not zero])\nnew_donated_invars = (*[d for d, x in zip(params['donated_invars'], args)\nif not is_undefined_primal(x)],\n- *[False for x in ct if x is not zero])\n+ *[False for x in ct if type(x) is not zero])\nnew_params = dict(params, name=wrap_name(params['name'], 'transpose'),\nmapped_invars=tuple(new_mapped_invars),\ndonated_invars=tuple(new_donated_invars))\n@@ -541,7 +547,7 @@ def map_transpose(primitive, params, call_jaxpr, args, ct, _):\n# The freevars are being fanned out (not mapped). During transpose the\n# dual of fan-out is fan-in-sum. We apply it to the unmapped invars.\nassert len(mapped_invars) == len(arg_cts)\n- arg_cts = (arg_ct if arg_mapped or arg_ct is zero else arg_ct.sum(0)\n+ arg_cts = (arg_ct if arg_mapped or type(arg_ct) is Zero else arg_ct.sum(0)\nfor arg_ct, arg_mapped in zip(arg_cts, mapped_invars))\nreturn arg_cts\n@@ -564,10 +570,11 @@ def f_jvp_traceable(nonzeros, *primals_and_nztangents):\nnum_primals = len(nonzeros)\nprimals = list(primals_and_nztangents[:num_primals])\nnonzero_tangents = iter(primals_and_nztangents[num_primals:])\n- tangents = [next(nonzero_tangents) if nz else zero for nz in nonzeros]\n+ tangents = [next(nonzero_tangents) if nz else Zero.from_value(p)\n+ for p, nz in zip(primals, nonzeros)]\nprimals_out, tangents_out = yield (primals, tangents), {}\n- out_nonzeros = [t is not zero for t in tangents_out]\n- nonzero_tangents_out = [t for t in tangents_out if t is not zero]\n+ out_nonzeros = [type(t) is not Zero for t in tangents_out]\n+ nonzero_tangents_out = [t for t in tangents_out if type(t) is not Zero]\nyield list(primals_out) + nonzero_tangents_out, out_nonzeros\ndef rearrange_binders(jaxpr: core.TypedJaxpr, primals_in, tangents_in, primals_out, tangents_out):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -25,7 +25,7 @@ import numpy as onp\nfrom .. import core\nfrom .. import linear_util as lu\nfrom ..abstract_arrays import ConcreteArray, raise_to_shaped\n-from ..ad_util import zero\n+from ..ad_util import Zero\nfrom ..util import (unzip2, safe_zip, safe_map, toposort, partial, split_list,\nwrap_name, cache, curry)\nfrom ..core import (Trace, Tracer, new_master, Jaxpr, Literal, get_aval,\n@@ -50,7 +50,7 @@ class PartialVal(tuple):\nif not core.skip_checks:\n# type checks\nassert isinstance(pv, (AbstractValue, type(None))), xs\n- assert isinstance(const, core.Tracer) or const is zero or core.valid_jaxtype(const), xs\n+ assert isinstance(const, core.Tracer) or type(const) is Zero or core.valid_jaxtype(const), xs\n# invariant checks\nif isinstance(pv, AbstractValue):\nassert const == core.unit, xs\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2131,7 +2131,7 @@ def _sub_transpose(t, x, y):\n# The following linearity assertion is morally true, but because in some cases\n# we instantiate zeros for convenience, it doesn't always hold.\n# assert ad.is_undefined_primal(x) and ad.is_undefined_primal(y)\n- return [t, neg(t) if t is not ad_util.zero else ad_util.zero]\n+ return [t, neg(t) if type(t) is not ad_util.Zero else ad_util.Zero]\nsub_p = standard_naryop([_num, _num], 'sub')\nad.defjvp(sub_p,\n@@ -2145,7 +2145,7 @@ ad.defbilinear_broadcasting(_brcast, mul_p, mul, mul)\ndef _div_transpose_rule(cotangent, x, y):\nassert ad.is_undefined_primal(x) and not ad.is_undefined_primal(y)\n- res = ad_util.zero if cotangent is ad_util.zero else div(cotangent, y)\n+ res = ad_util.Zero if type(cotangent) is ad_util.Zero else div(cotangent, y)\nreturn res, None\ndiv_p = standard_naryop([_num, _num], 'div')\nad.defjvp(div_p,\n@@ -2401,7 +2401,7 @@ def _conv_general_dilated_transpose_rhs(\nassert type(dimension_numbers) is ConvDimensionNumbers\nif onp.size(g) == 0:\n# Avoids forming degenerate convolutions where the RHS has spatial size 0.\n- return ad_util.zero\n+ return ad_util.Zero\nlhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\nlhs_trans, rhs_trans, out_trans = map(_conv_spec_transpose, dimension_numbers)\nassert batch_group_count == 1 or feature_group_count == 1\n@@ -2871,8 +2871,8 @@ def _concatenate_translation_rule(c, *operands, **kwargs):\ndef _concatenate_transpose_rule(t, *operands, dimension):\noperand_shapes = [o.aval.shape if ad.is_undefined_primal(o) else o.shape\nfor o in operands]\n- if t is ad_util.zero:\n- return [ad_util.zero if ad.is_undefined_primal(o) else None for o in operands]\n+ if t is ad_util.Zero:\n+ return ad_util.Zero\nelse:\nlimit_points = onp.cumsum([shape[dimension] for shape in operand_shapes])\nstarts = onp.zeros((len(operands), t.ndim), dtype=int)\n@@ -2916,9 +2916,8 @@ def _pad_shape_rule(operand, padding_value, *, padding_config):\nreturn tuple(out_shape)\ndef _pad_transpose(t, operand, padding_value, *, padding_config):\n- if t is ad_util.zero:\n- return [ad_util.zero if ad.is_undefined_primal(operand) else None,\n- ad_util.zero if ad.is_undefined_primal(padding_value) else None]\n+ if t is ad_util.Zero:\n+ return ad_util.Zero\nlo, hi, interior = zip(*padding_config)\ntotal = lambda x: _reduce_sum(x, list(range(t.ndim)))\n@@ -3250,10 +3249,8 @@ def _select_dtype_rule(pred, on_true, on_false):\ndef _select_transpose_rule(t, pred, on_true, on_false):\nassert not ad.is_undefined_primal(pred)\n- if t is ad_util.zero:\n- return [None,\n- ad_util.zero if ad.is_undefined_primal(on_true) else None,\n- ad_util.zero if ad.is_undefined_primal(on_false) else None]\n+ if type(t) is ad_util.Zero:\n+ return ad_util.Zero\nelse:\nzeros = full_like(t, 0)\nreturn [None,\n@@ -3442,9 +3439,9 @@ def _dynamic_slice_translation_rule(c, operand, *start_indices, slice_sizes):\nreturn xops.DynamicSlice(operand, start_indices, slice_sizes)\ndef _dynamic_slice_jvp(primals, tangents, *, slice_sizes):\n- tangent_out = ad_util.zero\n- if tangents[0] is not ad_util.zero:\n- tangent_out = dynamic_slice(tangents[0], primals[1:], slice_sizes)\n+ tangent_out = tangents[0]\n+ if type(tangent_out) is not ad_util.Zero:\n+ tangent_out = dynamic_slice(tangent_out, primals[1:], slice_sizes)\nreturn dynamic_slice(primals[0], primals[1:], slice_sizes), tangent_out\ndef _dynamic_slice_transpose_rule(t, operand, *start_indices, slice_sizes):\n@@ -3521,8 +3518,8 @@ def _dynamic_update_slice_jvp(primals, tangents):\nstart_indices = primals[2:]\ng_operand, g_update = tangents[:2]\nval_out = dynamic_update_slice(operand, update, start_indices)\n- if g_operand is ad_util.zero and g_update is ad_util.zero:\n- tangent_out = ad_util.zero\n+ if type(g_operand) is ad_util.Zero and type(g_update) is ad_util.Zero:\n+ tangent_out = ad_util.Zero.from_value(val_out)\nelse:\ng_operand = ad.instantiate_zeros(operand, g_operand)\ng_update = ad.instantiate_zeros(update, g_update)\n@@ -3617,14 +3614,14 @@ def _gather_transpose_rule(t, operand, start_indices, *, dimension_numbers,\nslice_sizes):\nassert ad.is_undefined_primal(operand)\noperand_shape = operand.aval.shape\n- if t is ad_util.zero:\n- return [ad_util.zero, ad_util.zero]\n+ if type(t) is ad_util.Zero:\n+ return ad_util.Zero\nzeros = full(operand_shape, tie_in(t, _zero(t)))\nscatter_dnums = ScatterDimensionNumbers(\nupdate_window_dims=dimension_numbers.offset_dims,\ninserted_window_dims=dimension_numbers.collapsed_slice_dims,\nscatter_dims_to_operand_dims=dimension_numbers.start_index_map)\n- return [scatter_add(zeros, start_indices, t, scatter_dnums), ad_util.zero]\n+ return [scatter_add(zeros, start_indices, t, scatter_dnums), ad_util.Zero.from_value(start_indices)]\ndef _gather_batching_rule(batched_args, batch_dims, *, dimension_numbers,\nslice_sizes):\n@@ -3727,8 +3724,8 @@ def _scatter_add_jvp(primals, tangents, *, update_jaxpr, update_consts,\nval_out = scatter_add_p.bind(\noperand, scatter_indices, updates, update_jaxpr=update_jaxpr,\nupdate_consts=update_consts, dimension_numbers=dimension_numbers)\n- if g_operand is ad_util.zero and g_updates is ad_util.zero:\n- tangent_out = ad_util.zero\n+ if type(g_operand) is ad_util.Zero and type(g_updates) is ad_util.Zero:\n+ tangent_out = ad_util.Zero.from_value(val_out)\nelse:\ng_operand = ad.instantiate_zeros(operand, g_operand)\ng_updates = ad.instantiate_zeros(updates, g_updates)\n@@ -3744,8 +3741,8 @@ def _scatter_add_transpose_rule(t, operand, scatter_indices, updates, *,\nupdates_shape = updates.aval.shape\nelse:\nupdates_shape = updates.shape\n- if t is ad_util.zero:\n- return [ad_util.zero, None, ad_util.zero]\n+ if type(t) is ad_util.Zero:\n+ return ad_util.Zero\noperand_t = update_t = None\nif ad.is_undefined_primal(operand):\n@@ -3775,8 +3772,8 @@ def _scatter_mul_transpose_rule(t, operand, scatter_indices, updates, *,\nupdates_shape = updates.aval.shape\nelse:\nupdates_shape = updates.shape\n- if t is ad_util.zero:\n- return [ad_util.zero, None, ad_util.zero]\n+ if type(t) is ad_util.Zero:\n+ return ad_util.Zero\noperand_t = update_t = None\nif ad.is_undefined_primal(operand):\n@@ -3884,8 +3881,8 @@ def _scatter_extremal_jvp(scatter_op, primals, tangents, update_jaxpr,\noperand, scatter_indices, updates, update_jaxpr=update_jaxpr,\nupdate_consts=update_consts, dimension_numbers=scatter_dnums)\n- if g_operand is ad_util.zero and g_updates is ad_util.zero:\n- tangent_out = ad_util.zero\n+ if type(g_operand) is ad_util.Zero and type(g_updates) is ad_util.Zero:\n+ tangent_out = ad_util.Zero.from_value(val_out)\nelse:\ng_operand = ad.instantiate_zeros(operand, g_operand)\ng_updates = ad.instantiate_zeros(updates, g_updates)\n@@ -3986,12 +3983,11 @@ def _scatter_jvp(primals, tangents, *, update_jaxpr, update_consts,\ng_operand, g_scatter_indices, g_updates = tangents\ndnums = dimension_numbers\n- if g_operand is ad_util.zero and g_updates is ad_util.zero:\n+ if type(g_operand) is ad_util.Zero and type(g_updates) is ad_util.Zero:\nval_out = scatter_p.bind(\noperand, scatter_indices, updates, update_jaxpr=update_jaxpr,\nupdate_consts=update_consts, dimension_numbers=dnums)\n- tangent_out = ad_util.zero\n- return val_out, tangent_out\n+ return val_out, ad_util.Zero.from_value(val_out)\ng_operand = ad.instantiate_zeros(operand, g_operand)\ng_updates = ad.instantiate_zeros(updates, g_updates)\n@@ -4507,8 +4503,8 @@ def _select_and_scatter_add_jvp(\nsource, operand, select_prim, window_dimensions, window_strides,\npadding)\ndel g_operand\n- if g_source is ad_util.zero:\n- tangent_out = ad_util.zero\n+ if type(g_source) is ad_util.Zero:\n+ tangent_out = ad_util.Zero.from_value(val_out)\nelse:\ntangent_out = _select_and_scatter_add(\ng_source, operand, select_prim, window_dimensions,\n@@ -4693,8 +4689,8 @@ def _select_and_gather_add_jvp(\nsource, operand, select_prim, window_dimensions, window_strides,\npadding)\ndel g_operand\n- if g_source is ad_util.zero:\n- tangent_out = ad_util.zero\n+ if type(g_source) is ad_util.Zero:\n+ tangent_out = ad_util.Zero.from_value(val_out)\nelse:\ntangent_out = _select_and_gather_add(\ng_source, operand, select_prim, window_dimensions,\n@@ -4932,8 +4928,7 @@ def _sort_jvp(primals, tangents, *, dimension):\nprimals = sort_p.bind(*(primals + (iotas[dimension],)), dimension=dimension)\nidx = tuple(primals[-1] if i == dimension else iotas[i]\nfor i in range(len(shape)))\n- tangents_out = tuple(ad_util.zero if t is ad_util.zero else t[idx]\n- for t in tangents)\n+ tangents_out = tuple(t if type(t) is ad_util.Zero else t[idx] for t in tangents)\nreturn tuple(primals[:-1]), tangents_out\ndef _sort_batch_rule(batched_args, batch_dims, *, dimension):\n@@ -4978,8 +4973,8 @@ def _top_k_jvp(primals, tangents, *, k):\noperand, = primals\ntangent, = tangents\nprimals_out = top_k(operand, k)\n- if tangent is ad_util.zero:\n- tangents_out = (ad_util.zero, ad_util.zero)\n+ if type(tangent) is ad_util.Zero:\n+ tangent_out = ad_util.Zero.from_value(primals_out[0])\nelse:\n_, k_idxs = primals_out\nidx_shape = k_idxs.shape\n@@ -4998,9 +4993,8 @@ def _top_k_jvp(primals, tangents, *, k):\noffset_dims=(),\ncollapsed_slice_dims=tuple(range(rank)),\nstart_index_map=tuple(range(rank)))\n- tangents_out = (gather(tangent, gather_indices, dnums, slice_sizes),\n- ad_util.zero)\n- return primals_out, tangents_out\n+ tangent_out = gather(tangent, gather_indices, dnums, slice_sizes)\n+ return primals_out, (tangent_out, ad_util.Zero.from_value(primals_out[1]))\ndef _top_k_batch_rule(batched_args, batch_dims, *, k):\noperand, = batched_args\n@@ -5022,8 +5016,12 @@ xla.translations[top_k_p] = partial(standard_translate, 'top_k')\nad.primitive_jvps[top_k_p] = _top_k_jvp\nbatching.primitive_batchers[top_k_p] = _top_k_batch_rule\n-def _tie_in_transpose_rule(t):\n- return [ad_util.zero, t]\n+def _tie_in_transpose_rule(t, x, y):\n+ # TODO(apaszke): What to do about this?\n+ if ad.is_undefined_primal(x):\n+ return [ad_util.Zero(x.aval), t]\n+ else:\n+ return [ad_util.Zero.from_value(x), t]\ndef _tie_in_batch_rule(batched_args, batch_dims):\ny = tie_in(*batched_args)\n@@ -5039,7 +5037,7 @@ tie_in_p = Primitive('tie_in')\ntie_in_p.def_impl(_tie_in_impl)\ntie_in_p.def_abstract_eval(lambda x, y: raise_to_shaped(y))\nxla.translations[tie_in_p] = lambda c, x, y: y\n-ad.deflinear(tie_in_p, _tie_in_transpose_rule)\n+ad.deflinear2(tie_in_p, _tie_in_transpose_rule)\nbatching.primitive_batchers[tie_in_p] = _tie_in_batch_rule\nmasking.masking_rules[tie_in_p] = lambda vals, logical_shapes: vals[1]\n@@ -5047,7 +5045,7 @@ masking.masking_rules[tie_in_p] = lambda vals, logical_shapes: vals[1]\ndef _stop_gradient_jvp_rule(primals, tangents):\n# if we don't call stop_gradient here, we'd only peel off one autodiff tracer\nx, = primals\n- return stop_gradient(x), ad_util.zero\n+ return stop_gradient(x), ad_util.Zero.from_value(x)\ndef _stop_gradient_batch_rule(batched_args, batch_dims):\nx, = batched_args\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax_linalg.py",
"new_path": "jax/lax_linalg.py",
"diff": "@@ -368,8 +368,8 @@ def triangular_solve_transpose_rule(\n# Triangular solve is nonlinear in its first argument and linear in its second\n# argument, analogous to `div` but swapped.\nassert not ad.is_undefined_primal(a) and ad.is_undefined_primal(b)\n- if cotangent is ad_util.zero:\n- cotangent_b = ad_util.zero\n+ if type(cotangent) is ad_util.Zero:\n+ cotangent_b = ad_util.Zero(b.aval)\nelse:\ncotangent_b = triangular_solve(a, cotangent, left_side, lower,\nnot transpose_a, conjugate_a, unit_diagonal)\n@@ -622,7 +622,7 @@ def _lu_jvp_rule(primals, tangents):\nl_dot = jnp.matmul(l, jnp.tril(lau, -1))\nu_dot = jnp.matmul(jnp.triu(lau), u)\nlu_dot = l_dot + u_dot\n- return (lu, pivots), (lu_dot, ad_util.zero)\n+ return (lu, pivots), (lu_dot, ad_util.Zero.from_value(pivots))\ndef _lu_batching_rule(batched_args, batch_dims):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -1028,7 +1028,7 @@ def _gamma_impl(key, a):\nsamples = lax.map(lambda args: _gamma_one(*args), (keys, alphas))\nelse:\nsamples = vmap(_gamma_one)(keys, alphas)\n- return jnp.reshape(samples, a_shape),\n+ return jnp.reshape(samples, a_shape)\ndef _gamma_batching_rule(batched_args, batch_dims):\nk, a = batched_args\n@@ -1036,14 +1036,13 @@ def _gamma_batching_rule(batched_args, batch_dims):\nsize = next(t.shape[i] for t, i in zip(batched_args, batch_dims) if i is not None)\nk = batching.bdim_at_front(k, bk, size)\na = batching.bdim_at_front(a, ba, size)\n- return random_gamma_p.bind(k, a), (0,)\n+ return random_gamma_p.bind(k, a), 0\nrandom_gamma_p = core.Primitive('random_gamma')\n-random_gamma_p.multiple_results = True\nrandom_gamma_p.def_impl(_gamma_impl)\n-random_gamma_p.def_abstract_eval(lambda key, a: (abstract_arrays.raise_to_shaped(a),))\n-ad.defjvp2(random_gamma_p, None, lambda tangent, ans, key, a: (tangent * _gamma_grad(ans[0], a),))\n-xla.translations[random_gamma_p] = xla.lower_fun(_gamma_impl)\n+random_gamma_p.def_abstract_eval(lambda key, a: abstract_arrays.raise_to_shaped(a))\n+ad.defjvp2(random_gamma_p, None, lambda tangent, ans, key, a: tangent * _gamma_grad(ans, a))\n+xla.translations[random_gamma_p] = xla.lower_fun(_gamma_impl, multiple_results=False)\nbatching.primitive_batchers[random_gamma_p] = _gamma_batching_rule\ndef gamma(key, a, shape=None, dtype=np.float64):\n@@ -1081,7 +1080,7 @@ def _gamma(key, a, shape, dtype):\na = lax.convert_element_type(a, dtype)\nif np.shape(a) != shape:\na = jnp.broadcast_to(a, shape)\n- return random_gamma_p.bind(key, a)[0]\n+ return random_gamma_p.bind(key, a)\n@partial(jit, static_argnums=(2, 3, 4))\n"
}
] | Python | Apache License 2.0 | google/jax | Make ad_util.zero a class that carries avals (similar to UndefinedPrimal)
This is useful for remat transpose rule submitted in #3162 and e.g.
allowed me to catch a slight overuse of defjvp2 for `random_gamma_p` (it
was unnecessarily declared as having multiple outputs). |
260,287 | 27.05.2020 18:09:35 | 0 | c5d870738c571d75eacd92b14540b2705147b346 | Fix host_callback | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -389,7 +389,7 @@ id_tap_p.def_abstract_eval(_id_tap_abstract_eval)\n# The AttributeError is for regular values, the KeyError is for ConcreteArray\ndef _instantiate_zeros(arg, tan):\n\"\"\"Turn special ad.zero tangents into arrays of 0s.\"\"\"\n- if tan is not ad.zero:\n+ if type(tan) is not ad.Zero:\nreturn tan\ntry:\n"
}
] | Python | Apache License 2.0 | google/jax | Fix host_callback |
260,287 | 28.05.2020 13:20:56 | 0 | 3f1d3a73ace426540f81167fbda9f2068898075a | Remove example from ad.instantiate_zeros, fix vmap bug | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1881,7 +1881,7 @@ def defjvp_all(fun, custom_jvp):\nmsg = (\"Detected differentiation with respect to closed-over values with \"\n\"custom JVP rule, which isn't supported.\")\nraise ValueError(msg)\n- args_dot_flat = map(ad.instantiate_zeros, args_flat, args_dot_flat)\n+ args_dot_flat = map(ad.instantiate_zeros, args_dot_flat)\nargs = tree_unflatten(in_tree, args_flat)\nargs_dot = tree_unflatten(in_tree, args_dot_flat)\nout, out_dot = custom_jvp(args, args_dot)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -306,7 +306,7 @@ custom_jvp_call_jaxpr_p.def_abstract_eval(_custom_jvp_call_jaxpr_abstract_eval)\ndef _custom_jvp_call_jaxpr_jvp(primals, tangents, *, fun_jaxpr, jvp_jaxpr_thunk):\njvp_jaxpr = jvp_jaxpr_thunk()\n- tangents = map(ad.instantiate_zeros, primals, tangents)\n+ tangents = map(ad.instantiate_zeros, tangents)\nouts = core.jaxpr_as_fun(jvp_jaxpr)(*primals, *tangents)\nreturn split_list(outs, [len(outs) // 2])\nad.primitive_jvps[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_jvp\n@@ -550,7 +550,7 @@ custom_vjp_call_jaxpr_p.def_abstract_eval(_custom_vjp_call_jaxpr_abstract_eval)\ndef _custom_vjp_call_jaxpr_jvp(primals, tangents, *, fun_jaxpr, fwd_jaxpr_thunk,\nbwd, out_trees):\n- tangents = map(ad.instantiate_zeros, primals, tangents)\n+ tangents = map(ad.instantiate_zeros, tangents)\nfwd_jaxpr = fwd_jaxpr_thunk()\nout_tree, res_tree = out_trees()\nres_and_primals_out = core.jaxpr_as_fun(fwd_jaxpr)(*primals)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -49,8 +49,8 @@ def jvpfun(instantiate, primals, tangents):\ndel master\nif type(instantiate) is bool:\ninstantiate = [instantiate] * len(out_tangents)\n- out_tangents = [instantiate_zeros(x, t) if inst else t for x, t, inst\n- in zip(out_primals, out_tangents, instantiate)]\n+ out_tangents = [instantiate_zeros(t) if inst else t for t, inst\n+ in zip(out_tangents, instantiate)]\nyield out_primals, out_tangents\n@lu.transformation\n@@ -112,7 +112,7 @@ def vjp(traceable, primals, has_aux=False):\ncts = tuple(map(ignore_consts, cts, pvals))\ndummy_args = [UndefinedPrimal(v.aval) for v in jaxpr.invars]\narg_cts = backward_pass(jaxpr, consts, dummy_args, cts)\n- return map(instantiate_zeros, primals, arg_cts)\n+ return map(instantiate_zeros, arg_cts)\nif not has_aux:\nreturn out_primals, vjp_\n@@ -305,14 +305,14 @@ class JVPTrace(Trace):\ndef process_custom_jvp_call(self, _, __, f_jvp, tracers):\nprimals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers)\nprimals_in = map(core.full_lower, primals_in)\n- tangents_in = map(instantiate_zeros, primals_in, tangents_in)\n+ tangents_in = map(instantiate_zeros, tangents_in)\nouts = f_jvp.call_wrapped(*it.chain(primals_in, tangents_in))\nprimals_out, tangents_out = split_list(outs, [len(outs) // 2])\nreturn map(partial(JVPTracer, self), primals_out, tangents_out)\ndef process_custom_vjp_call(self, _, __, fwd, bwd, tracers, *, out_trees):\nprimals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers)\n- tangents_in = map(instantiate_zeros, primals_in, tangents_in)\n+ tangents_in = map(instantiate_zeros, tangents_in)\nres_and_primals_out = fwd.call_wrapped(*map(core.full_lower, primals_in))\nout_tree, res_tree = out_trees()\nres, primals_out = split_list(res_and_primals_out, [res_tree.num_leaves])\n@@ -378,7 +378,7 @@ def linear_jvp(primitive, primals, tangents, **params):\nif all(type(tangent) is Zero for tangent in tangents):\nreturn val_out, Zero.from_value(val_out)\nelse:\n- tangents = map(instantiate_zeros, primals, tangents)\n+ tangents = map(instantiate_zeros, tangents)\nreturn val_out, primitive.bind(*tangents, **params)\ndef linear_transpose(transpose_rule, cotangent, *args, **kwargs):\n@@ -459,14 +459,17 @@ deflinear(zeros_like_p, lambda t: [Zero.from_value(t)])\ndeflinear(core.identity_p, lambda t: (t,))\ndeflinear(add_jaxvals_p, lambda t: (t, t))\n-def instantiate_zeros(example, tangent):\n+def instantiate_zeros(tangent):\nif type(tangent) is Zero:\n- return zeros_like_jaxval(example)\n+ return zeros_like_aval(tangent.aval)\nelse:\nreturn tangent\n+# This function seems similar to instantaite_zeros, but it is sometimes used\n+# to instantiate zero abstract units with a different aval\ndef instantiate_zeros_aval(aval, tangent):\nif type(tangent) is Zero:\n+ assert type(tangent.aval) is core.AbstractUnit or tangent.aval == aval\nreturn zeros_like_aval(aval)\nelse:\nreturn tangent\n@@ -625,7 +628,7 @@ def defvjp_all(prim, custom_vjp):\nname = prim.name\ndef fun_jvp(xs, ts, **params):\n- ts = map(instantiate_zeros, xs, ts)\n+ ts = map(instantiate_zeros, ts)\nprimals_and_tangents = fun_jvp_p.bind(*it.chain(xs, ts), **params)\nprimals, tangents = split_list(primals_and_tangents, [len(primals_and_tangents) // 2])\nif prim.multiple_results:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -24,6 +24,7 @@ from .. import linear_util as lu\nfrom ..util import unzip2, partial, safe_map, wrap_name, split_list\nfrom . import xla\nfrom . import partial_eval as pe\n+from .. import lax_reference\nmap = safe_map\n@@ -62,6 +63,7 @@ def _batch_fun(sum_match, in_dims, out_dims_thunk, out_dim_dests, *in_vals, **pa\nif od is not None and not isinstance(od_dest, int) and not od_dest is last and not sum_match:\nmsg = f\"vmap has mapped output but out_axes is {od_dest}\"\nraise ValueError(msg)\n+ print(out_vals, out_dims, out_dim_dests, size, sum_match)\nout_vals = map(partial(matchaxis, size, sum_match=sum_match), out_dims, out_dim_dests, out_vals)\nyield out_vals\n@@ -125,6 +127,7 @@ class BatchTrace(Trace):\nreturn BatchTracer(self, val.val, val.batch_dim)\ndef process_primitive(self, primitive, tracers, params):\n+ print(primitive)\nvals_in, dims_in = unzip2((t.val, t.batch_dim) for t in tracers)\nif all(bdim is not_mapped for bdim in dims_in):\nreturn primitive.bind(*vals_in, **params)\n@@ -311,10 +314,10 @@ def broadcast(x, sz, axis):\naxis = onp.ndim(x)\nshape = list(onp.shape(x))\nshape.insert(axis, sz)\n+ broadcast_dims = tuple(onp.delete(onp.arange(len(shape)), axis))\nif isinstance(x, onp.ndarray) or onp.isscalar(x):\n- return onp.broadcast_to(dtypes.coerce_to_array(x), shape)\n+ return lax_reference.broadcast_in_dim(x, shape, broadcast_dims)\nelse:\n- broadcast_dims = tuple(onp.delete(onp.arange(len(shape)), axis))\nreturn x.broadcast_in_dim(shape, broadcast_dims)\ndef moveaxis(x, src, dst):\n@@ -328,6 +331,7 @@ def moveaxis(x, src, dst):\nreturn x.transpose(perm)\ndef matchaxis(sz, src, dst, x, sum_match=False):\n+ print('>', src, dst)\nif core.get_aval(x) is core.abstract_unit:\nreturn core.unit\nif src == dst:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -3521,8 +3521,8 @@ def _dynamic_update_slice_jvp(primals, tangents):\nif type(g_operand) is ad_util.Zero and type(g_update) is ad_util.Zero:\ntangent_out = ad_util.Zero.from_value(val_out)\nelse:\n- g_operand = ad.instantiate_zeros(operand, g_operand)\n- g_update = ad.instantiate_zeros(update, g_update)\n+ g_operand = ad.instantiate_zeros(g_operand)\n+ g_update = ad.instantiate_zeros(g_update)\ntangent_out = dynamic_update_slice(g_operand, g_update, start_indices)\nreturn val_out, tangent_out\n@@ -3727,8 +3727,8 @@ def _scatter_add_jvp(primals, tangents, *, update_jaxpr, update_consts,\nif type(g_operand) is ad_util.Zero and type(g_updates) is ad_util.Zero:\ntangent_out = ad_util.Zero.from_value(val_out)\nelse:\n- g_operand = ad.instantiate_zeros(operand, g_operand)\n- g_updates = ad.instantiate_zeros(updates, g_updates)\n+ g_operand = ad.instantiate_zeros(g_operand)\n+ g_updates = ad.instantiate_zeros(g_updates)\ntangent_out = scatter_add_p.bind(\ng_operand, scatter_indices, g_updates, update_jaxpr=update_jaxpr,\nupdate_consts=update_consts, dimension_numbers=dimension_numbers)\n@@ -3884,8 +3884,8 @@ def _scatter_extremal_jvp(scatter_op, primals, tangents, update_jaxpr,\nif type(g_operand) is ad_util.Zero and type(g_updates) is ad_util.Zero:\ntangent_out = ad_util.Zero.from_value(val_out)\nelse:\n- g_operand = ad.instantiate_zeros(operand, g_operand)\n- g_updates = ad.instantiate_zeros(updates, g_updates)\n+ g_operand = ad.instantiate_zeros(g_operand)\n+ g_updates = ad.instantiate_zeros(g_updates)\n# gather_dnums and slice_sizes define the gather op that is the inverse of\n# the scatter op specified by scatter_dnums\n@@ -3989,8 +3989,8 @@ def _scatter_jvp(primals, tangents, *, update_jaxpr, update_consts,\nupdate_consts=update_consts, dimension_numbers=dnums)\nreturn val_out, ad_util.Zero.from_value(val_out)\n- g_operand = ad.instantiate_zeros(operand, g_operand)\n- g_updates = ad.instantiate_zeros(updates, g_updates)\n+ g_operand = ad.instantiate_zeros(g_operand)\n+ g_updates = ad.instantiate_zeros(g_updates)\n# If there are overlapping indices in the scatter, it is unspecified which\n# update \"wins\". So we use the following perhaps surprising scheme:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -409,8 +409,8 @@ def _while_loop_jvp(primals, tangents, cond_nconsts, cond_jaxpr, body_nconsts,\nassert False, \"Fixpoint not reached\"\nnonzeros = cconst_nz + body_nonzeros\n- tangents = [ad.instantiate_zeros(x, t) if type(t) is ad_util.Zero and nz else t\n- for x, t, nz in zip(primals, tangents, nonzeros)]\n+ tangents = [ad.instantiate_zeros(t) if nz else t\n+ for t, nz in zip(tangents, nonzeros)]\ncconst, bconst, init = split_list(primals, [cond_nconsts, body_nconsts])\n_, bconst_dot, init_dot = split_list(tangents, [cond_nconsts, body_nconsts])\n@@ -1225,8 +1225,8 @@ def _scan_jvp(primals, tangents, reverse, length, jaxpr, num_consts, num_carry,\nelse:\nassert False, \"Fixpoint not reached\"\n- tangents = [ad.instantiate_zeros(x, t) if type(t) is ad_util.Zero and nz else t\n- for x, t, nz in zip(primals, tangents, nonzeros)]\n+ tangents = [ad.instantiate_zeros(t) if nz else t\n+ for t, nz in zip(tangents, nonzeros)]\nconsts, init, xs = split_list(primals, [num_consts, num_carry])\nall_tangents = split_list(tangents, [num_consts, num_carry])\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1763,6 +1763,12 @@ class APITest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, msg):\ng(jnp.ones((1, 1)), b=1)\n+ def test_vmap_unmapped_last(self):\n+ @partial(jax.vmap, out_axes=jax.interpreters.batching.last)\n+ def f(x):\n+ return np.zeros((2,))\n+ f(np.zeros((5,)))\n+\nclass JaxprTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Remove example from ad.instantiate_zeros, fix vmap bug |
260,287 | 29.05.2020 09:43:08 | 0 | 17472b97ab2d6953f953d1f339ed9ee8d4ad5424 | Optimize zeros_like_shaped_array
This function is used a lot more now, because `ad.instantiate_zeros` now
goes through that and not `zeros_like_array`. | [
{
"change_type": "MODIFY",
"old_path": "jax/abstract_arrays.py",
"new_path": "jax/abstract_arrays.py",
"diff": "@@ -37,7 +37,7 @@ def make_shaped_array(x):\ndef zeros_like_array(x):\ndtype = dtypes.canonicalize_dtype(dtypes.result_type(x))\n- return np.broadcast_to(np.array(0, dtype), np.shape(x))\n+ return zeros_like_shaped_array(ShapedArray(np.shape(x), dtype))\narray_types = {np.ndarray, np.bool_,\nnp.int8, np.int16, np.int32, np.int64,\n@@ -53,7 +53,7 @@ for t in array_types:\ndef zeros_like_shaped_array(aval):\nassert isinstance(aval, ShapedArray)\n- return np.zeros(aval.shape, dtype=aval.dtype)\n+ return np.broadcast_to(np.array(0, aval.dtype), aval.shape)\nad_util.aval_zeros_likers[ShapedArray] = zeros_like_shaped_array\n"
}
] | Python | Apache License 2.0 | google/jax | Optimize zeros_like_shaped_array
This function is used a lot more now, because `ad.instantiate_zeros` now
goes through that and not `zeros_like_array`. |
260,519 | 06.06.2020 02:44:10 | -36,000 | 29740de63ecd35073e66f3502f1d7dfe79d990e7 | Add np.polysub | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -213,6 +213,7 @@ Not every function in NumPy is implemented; contributions are welcome!\npercentile\npolyadd\npolymul\n+ polysub\npolyval\npower\npositive\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -48,7 +48,7 @@ from .lax_numpy import (\nnanmax, nanmean, nanmin, nanprod, nanstd, nansum, nanvar, ndarray, ndim,\nnegative, newaxis, nextafter, nonzero, not_equal, number, numpy_version,\nobject_, ones, ones_like, operator_name, outer, packbits, pad, percentile,\n- pi, polyadd, polymul, polyval, positive, power, prod, product, promote_types, ptp, quantile,\n+ pi, polyadd, polymul, polysub, polyval, positive, power, prod, product, promote_types, ptp, quantile,\nrad2deg, radians, ravel, real, reciprocal, remainder, repeat, reshape,\nresult_type, right_shift, rint, roll, rollaxis, rot90, round, row_stack,\nsave, savez, searchsorted, select, set_printoptions, shape, sign, signbit,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2645,6 +2645,17 @@ def polymul(a1, a2, *, trim_leading_zeros=False):\nval = convolve(a1, a2, mode='full')\nreturn val\n+@_wraps(np.polysub)\n+def polysub(a, b):\n+ a = asarray(a)\n+ b = asarray(b)\n+\n+ if b.shape[0] <= a.shape[0]:\n+ return a.at[-b.shape[0]:].add(-b)\n+ else:\n+ return -b.at[-a.shape[0]:].add(-a)\n+\n+\n@_wraps(np.append)\ndef append(arr, values, axis=None):\nif axis is None:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1133,6 +1133,23 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"a_shape={} , b_shape={}\".format(\n+ jtu.format_shape_dtype_string(a_shape, dtype),\n+ jtu.format_shape_dtype_string(b_shape, dtype)),\n+ \"dtype\": dtype, \"a_shape\": a_shape, \"b_shape\" : b_shape}\n+ for dtype in default_dtypes\n+ for a_shape in one_dim_array_shapes\n+ for b_shape in one_dim_array_shapes))\n+ def testPolySub(self, a_shape, b_shape, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ np_fun = lambda arg1, arg2: np.polysub(arg1, arg2)\n+ jnp_fun = lambda arg1, arg2: jnp.polysub(arg1, arg2)\n+ args_maker = lambda: [rng(a_shape, dtype), rng(b_shape, dtype)]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=True)\n+ self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_axis={}\".format(\njtu.format_shape_dtype_string(shape, dtype), axis),\n"
}
] | Python | Apache License 2.0 | google/jax | Add np.polysub (#3319) |
260,335 | 06.06.2020 21:44:14 | 25,200 | fd886b17a48f23637f3fcae810117721f155e16c | make jnp.array faster
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -35,20 +35,21 @@ import warnings\nimport numpy as np\nimport opt_einsum\n-from jax import jit, device_put, custom_jvp\n+from jax import jit, custom_jvp\nfrom .vectorize import vectorize\nfrom ._util import _wraps\nfrom .. import core\nfrom .. import dtypes\nfrom ..abstract_arrays import UnshapedArray, ShapedArray, ConcreteArray, canonicalize_shape\nfrom ..config import flags\n-from ..interpreters.xla import DeviceArray\n+from ..interpreters.xla import (DeviceArray, device_put, array_result_handler,\n+ DeviceValue)\nfrom ..interpreters.masking import Poly\nfrom .. import lax\nfrom .. import ops\nfrom ..util import (partial, unzip2, prod as _prod,\nsubvals, safe_zip)\n-from ..lib import pytree\n+from ..tree_util import tree_leaves, tree_flatten\nFLAGS = flags.FLAGS\nflags.DEFINE_enum(\n@@ -2107,19 +2108,24 @@ def array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nif order is not None and order != \"K\":\nraise NotImplementedError(\"Only implemented for order='K'\")\nlax._check_user_dtype_supported(dtype, \"array\")\n-\n- if isinstance(object, ndarray) or isscalar(object):\n- out = device_put(object)\n- if dtype and _dtype(out) != dtypes.canonicalize_dtype(dtype):\n+ dtype = dtype and dtypes.canonicalize_dtype(dtype)\n+\n+ if _can_call_numpy_array(object):\n+ object = np.array(object, dtype=dtype, ndmin=ndmin)\n+ assert type(object) not in dtypes.python_scalar_dtypes\n+\n+ if type(object) is np.ndarray:\n+ out = _device_put_raw(object)\n+ if dtype: assert _dtype(out) == dtype\n+ elif isinstance(object, (DeviceValue, core.Tracer)):\n+ out = object\n+ if dtype and _dtype(out) != dtype:\nout = lax.convert_element_type(out, dtype)\n- elif hasattr(object, '__array__'):\n- # this case is for duck-typed handling of objects that implement `__array__`\n- out = array(object.__array__(), dtype and dtypes.canonicalize_dtype(dtype))\nelif isinstance(object, (list, tuple)):\nif object:\nout = stack([array(elt, dtype=dtype) for elt in object])\nelse:\n- out = array(np.array([], dtype or float_))\n+ out = _device_put_raw(np.array([], dtype or float_))\nelse:\ntry:\nview = memoryview(object)\n@@ -2134,6 +2140,15 @@ def array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nout = lax.broadcast(out, (1,) * (ndmin - ndim(out)))\nreturn out\n+def _can_call_numpy_array(x):\n+ return _all(not isinstance(l, (core.Tracer, DeviceValue))\n+ for l in tree_leaves(x))\n+\n+def _device_put_raw(x):\n+ aval = core.raise_to_shaped(core.get_aval(x))\n+ return array_result_handler(None, aval)(device_put(x))\n+\n+\n@_wraps(np.asarray)\ndef asarray(a, dtype=None, order=None):\nlax._check_user_dtype_supported(dtype, \"asarray\")\n@@ -3431,7 +3446,7 @@ def _split_index_for_jit(idx):\n# indexing logic to handle them.\nidx = _expand_bool_indices(idx)\n- leaves, treedef = pytree.flatten(idx)\n+ leaves, treedef = tree_flatten(idx)\ndynamic = [None] * len(leaves)\nstatic = [None] * len(leaves)\nfor i, x in enumerate(leaves):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -2134,16 +2134,17 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nreturn np.array([], dtype=dtype)\nassert type(jnp.array(NDArrayLike())) == jax.interpreters.xla.DeviceArray\n- class DeviceArrayLike:\n- def __array__(self, dtype=None):\n- return jnp.array([], dtype=dtype)\n- assert type(jnp.array(DeviceArrayLike())) == jax.interpreters.xla.DeviceArray\n+ # NOTE(mattjj): disabled b/c __array__ must produce ndarrays\n+ # class DeviceArrayLike:\n+ # def __array__(self, dtype=None):\n+ # return jnp.array([], dtype=dtype)\n+ # assert type(jnp.array(DeviceArrayLike())) == jax.interpreters.xla.DeviceArray\ndef testArrayMethod(self):\nclass arraylike(object):\ndtype = np.float32\ndef __array__(self, dtype=None):\n- return 3.\n+ return np.array(3., dtype=dtype)\na = arraylike()\nans = jnp.array(a)\nassert ans == 3.\n"
}
] | Python | Apache License 2.0 | google/jax | make jnp.array faster (#3350)
fixes #2919 |
260,411 | 07.06.2020 14:45:15 | -10,800 | 7863f817c7a853b4968f1f2635aab01d89aa2321 | Commented-out the literal jaxpr checks in host_callback
* Commented-out the literal jaxpr checks in host_callback
Will re-enable when we change the host_callback, or when we have better
tools for updating goldens | [
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -132,20 +132,8 @@ class HostCallbackTest(jtu.JaxTestCase):\nxla_bridge.get_backend.cache_clear()\ndef test_eval(self):\n- assertMultiLineStrippedEqual(self, \"\"\"\n-{ lambda ; a.\n- let b = mul a 2.00\n- c = id_tap[ arg_treedef=*\n- func=_print\n- what=a * 2 ] b\n- d = mul c 3.00\n- e f = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=1\n- what=y * 3 ] d c\n- g = integer_pow[ y=2 ] f\n- in (g,) }\"\"\", str(api.make_jaxpr(fun1)(5.)))\n- self.assertEqual(\"\", testing_stream.output)\n+ # TODO: renable jaxpr golden tests when changing host_callback\n+ #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(fun1)(5.)))\nwith hcb.outfeed_receiver():\nself.assertAllClose((5. * 2.) ** 2, fun1(5.))\n@@ -161,15 +149,7 @@ what: y * 3\nx1, y1 = hcb.id_print((x * 2., x * 3.), output_stream=testing_stream)\nreturn x1 + y1\n- assertMultiLineStrippedEqual(self, \"\"\"\n-{ lambda ; a.\n- let b = mul a 2.00\n- c = mul a 3.00\n- d e = id_tap[ arg_treedef=PyTreeDef(tuple, [*,*])\n- func=_print\n- ] b c\n- f = add d e\n- in (f,) }\"\"\", str(api.make_jaxpr(func2)(3.)))\n+ #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(func2)(3.)))\nwith hcb.outfeed_receiver():\nself.assertEqual(3. * (2. + 3.), func2(3.))\nassertMultiLineStrippedEqual(self, \"\"\"\n@@ -242,20 +222,7 @@ what: here\ndef func(x):\nreturn hcb.id_print(42, result=x, output_stream=testing_stream)\n- assertMultiLineStrippedEqual(self, \"\"\"\n-{ lambda ; a.\n- let b = xla_call[ backend=None\n- call_jaxpr={ lambda ; a.\n- let b c = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=1\n- ] 42 a\n- in (c,) }\n- device=None\n- donated_invars=(False,)\n- name=func ] a\n- in (b,) }\"\"\", str(api.make_jaxpr(api.jit(func))(5)))\n- self.assertEqual(\"\", testing_stream.output)\n+ #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(api.jit(func))(5)))\nwith hcb.outfeed_receiver():\nself.assertAllClose(5, api.jit(func)(5))\n@@ -665,21 +632,6 @@ what: x3\nwith self.assertRaisesRegex(ValueError, \"outfeed_receiver is not started\"):\napi.jit(lambda x: hcb.id_print(x))(0)\n- def test_jit_nested_cond_no_print(self):\n- \"\"\"A nested conditional, without any prints\"\"\"\n- raise SkipTest(\"skip this\")\n- @api.jit\n- def cfun(x):\n- return lax.cond(\n- lax.lt(x, 2),\n- lambda x: x,\n- lambda x: lax.cond(x < 5,\n- 3, lambda x: x,\n- 4, lambda y: y),\n- x)\n- print(self._testMethodName, api.xla_computation(cfun)(1).as_hlo_text())\n- cfun(1)\n-\ndef test_while(self):\n\"\"\"Executing while, even without JIT uses compiled code\"\"\"\ny = jnp.ones(5) # captured const\n@@ -713,35 +665,8 @@ what: x3\ndef test_jvp(self):\njvp_fun1 = lambda x, xt: api.jvp(fun1, (x,), (xt,))\n- assertMultiLineStrippedEqual(self, \"\"\"\n-{ lambda ; a b.\n- let c = mul a 2.00\n- d = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=0\n- what=a * 2 ] c\n- e = mul d 3.00\n- f g = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=1\n- what=y * 3 ] e d\n- h = integer_pow[ y=2 ] g\n- i = mul b 2.00\n- j k = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=1\n- transforms=(('jvp',),)\n- what=a * 2 ] i d\n- l = mul j 3.00\n- m n o = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=2\n- transforms=(('jvp',),)\n- what=y * 3 ] l j f\n- p = mul 2.00 g\n- q = mul n p\n- in (h, q) }\"\"\",\n- str(api.make_jaxpr(jvp_fun1)(jnp.float32(5.), jnp.float32(0.1))))\n+ #assertMultiLineStrippedEqual(self, \"\",\n+ # str(api.make_jaxpr(jvp_fun1)(jnp.float32(5.), jnp.float32(0.1))))\nwith hcb.outfeed_receiver():\nres_primals, res_tangents = jvp_fun1(jnp.float32(5.), jnp.float32(0.1))\nself.assertAllClose(100., res_primals, check_dtypes=False)\n@@ -791,34 +716,7 @@ transforms: ({'name': 'jvp'}, {'name': 'transpose'}) what: x * 3\ny = hcb.id_print(x * 2., what=\"x * 2\", output_stream=testing_stream)\nreturn x * hcb.id_print(y * 3., what=\"y * 3\", output_stream=testing_stream)\ngrad_func = api.grad(func)\n- assertMultiLineStrippedEqual(self, \"\"\"\n-{ lambda ; a.\n- let b = mul 1.00 a\n- c d = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=1\n- transforms=(('jvp',), ('transpose',))\n- what=y * 3 ] b 0.00\n- e = mul c 3.00\n- f g = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=1\n- transforms=(('jvp',), ('transpose',))\n- what=x * 2 ] e 0.00\n- h = mul f 2.00\n- i = mul a 2.00\n- j = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=0\n- what=x * 2 ] i\n- k = mul j 3.00\n- l = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=0\n- what=y * 3 ] k\n- m = mul 1.00 l\n- n = add_any h m\n- in (n,) }\"\"\", str(api.make_jaxpr(grad_func)(5.)))\n+ #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(grad_func)(5.)))\nwith hcb.outfeed_receiver():\nres_grad = grad_func(jnp.float32(5.))\n@@ -841,10 +739,7 @@ transforms: ({'name': 'jvp'}, {'name': 'transpose'}) what: x * 2\ngrad_func = api.grad(api.grad(func))\nwith hcb.outfeed_receiver():\n- assertMultiLineStrippedEqual(self, \"\"\"\n-{ lambda ; a.\n- let\n- in (12.00,) }\"\"\", str(api.make_jaxpr(grad_func)(5.)))\n+ _ = api.make_jaxpr(grad_func)(5.)\n# Just making the Jaxpr invokes the id_print twiceonce\nassertMultiLineStrippedEqual(self, \"\"\"\ntransforms: ({'name': 'jvp'}, {'name': 'transpose'}) what: x * 2\n@@ -869,21 +764,7 @@ transforms: ({'name': 'jvp'}, {'name': 'transpose'}) what: x * 2\ndef test_vmap(self):\nvmap_fun1 = api.vmap(fun1)\nvargs = jnp.array([jnp.float32(4.), jnp.float32(5.)])\n- assertMultiLineStrippedEqual(self, \"\"\"\n-{ lambda ; a.\n- let b = mul a 2.00\n- c = id_tap[ arg_treedef=*\n- func=_print\n- transforms=(('batch', (0,)),)\n- what=a * 2 ] b\n- d = mul c 3.00\n- e f = id_tap[ arg_treedef=*\n- func=_print\n- nr_untapped=1\n- transforms=(('batch', (0, 0)),)\n- what=y * 3 ] d c\n- g = integer_pow[ y=2 ] f\n- in (g,) }\"\"\", str(api.make_jaxpr(vmap_fun1)(vargs)))\n+ #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(vmap_fun1)(vargs)))\nwith hcb.outfeed_receiver():\n_ = vmap_fun1(vargs)\nassertMultiLineStrippedEqual(self, \"\"\"\n@@ -902,13 +783,7 @@ transforms: ({'name': 'batch', 'batch_dims': (0, 0)},) what: y * 3\nvmap_func = api.vmap(func)\nvargs = jnp.array([jnp.float32(4.), jnp.float32(5.)])\n- assertMultiLineStrippedEqual(self, \"\"\"\n-{ lambda ; a.\n- let b c = id_tap[ arg_treedef=PyTreeDef(tuple, [*,*])\n- func=_print\n- transforms=(('batch', (None, 0)),) ] 3.00 a\n- d = add c 3.00\n- in (d,) }\"\"\", str(api.make_jaxpr(vmap_func)(vargs)))\n+ #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(vmap_func)(vargs)))\nwith hcb.outfeed_receiver():\n_ = vmap_func(vargs)\nassertMultiLineStrippedEqual(self, \"\"\"\n@@ -928,17 +803,7 @@ transforms: ({'name': 'batch', 'batch_dims': (None, 0)},)\nxv = jnp.arange(5, dtype=np.int32)\nyv = jnp.arange(3, dtype=np.int32)\n- assertMultiLineStrippedEqual(self, \"\"\"\n-{ lambda ; a b.\n- let c = broadcast_in_dim[ broadcast_dimensions=(1,)\n- shape=(3, 5) ] a\n- d = reshape[ dimensions=None\n- new_sizes=(3, 1) ] b\n- e = add c d\n- f = id_tap[ arg_treedef=*\n- func=_print\n- transforms=(('batch', (0,)), ('batch', (0,))) ] e\n- in (f,) }\"\"\", str(api.make_jaxpr(sum_all)(xv, yv)))\n+ #assertMultiLineStrippedEqual(self, \"\", str(api.make_jaxpr(sum_all)(xv, yv)))\nwith hcb.outfeed_receiver():\n_ = sum_all(xv, yv)\nassertMultiLineStrippedEqual(self, \"\"\"\n@@ -1055,9 +920,10 @@ class OutfeedRewriterTest(jtu.JaxTestCase):\ndef assertRewrite(self, expected: str, func: Callable, args: Sequence,\nhas_input_token=True, has_output_token=True):\n\"\"\"Check that the rewrite of func(*args) matches expected.\"\"\"\n- jaxpr = api.make_jaxpr(func)(*args)\n- assertMultiLineStrippedEqual(self, expected,\n- str(hcb._rewrite_typed_jaxpr(jaxpr, has_input_token, has_output_token)[0]))\n+ _ = api.make_jaxpr(func)(*args)\n+ # TODO: re-enable when we change the host_callback rewriter\n+ #assertMultiLineStrippedEqual(self, expected,\n+ # str(hcb._rewrite_typed_jaxpr(jaxpr, has_input_token, has_output_token)[0]))\ndef test_no_outfeed(self):\nself.assertRewrite(\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | Commented-out the literal jaxpr checks in host_callback (#3351)
* Commented-out the literal jaxpr checks in host_callback
Will re-enable when we change the host_callback, or when we have better
tools for updating goldens |
260,335 | 08.06.2020 09:47:32 | 25,200 | 508821cc184155b86c10850dcbb61c81daeee3e4 | fix a one-character issue from a bad merge
cf. | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -776,7 +776,7 @@ def _cond_batching_rule(args, dims, branches, linear):\nreturn out, out_dims\ndef _cond_jvp(primals, tangents, branches, linear):\n- nonzeros = [type(t) is not ad_util.zero for t in tangents]\n+ nonzeros = [type(t) is not ad_util.Zero for t in tangents]\nindex_nz, *ops_nz = nonzeros\nassert index_nz is False\n"
}
] | Python | Apache License 2.0 | google/jax | fix a one-character issue from a bad merge (#3362)
cf. #3222 |
260,411 | 08.06.2020 19:59:25 | -10,800 | 65d95f10eaea6f29910e77bee87b5b84c4d6f277 | A couple of ad_util.zero were missed in | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1905,7 +1905,7 @@ def defjvp(fun, *jvprules):\nans = fun(*primals)\ntangents_out = [rule(t, ans, *primals) for rule, t in zip(jvprules, tangents)\nif rule is not None and type(t) is not ad_util.Zero]\n- return ans, functools.reduce(ad.add_tangents, tangents_out, ad_util.zero)\n+ return ans, functools.reduce(ad.add_tangents, tangents_out, ad_util.Zero.from_value(ans))\ndefjvp_all(fun, custom_jvp)\ndef defvjp_all(fun, custom_vjp):\n"
}
] | Python | Apache License 2.0 | google/jax | A couple of ad_util.zero were missed in #3222 (#3363) |
260,519 | 09.06.2020 03:06:20 | -36,000 | b1adef40d49d4c8e995f2468af2e07fa13fb0690 | Fix polyadd and test | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2626,13 +2626,11 @@ def polyadd(a, b):\na = asarray(a)\nb = asarray(b)\n- shape_diff = a.shape[0] - b.shape[0]\n- if shape_diff > 0:\n- b = concatenate((np.zeros(shape_diff, dtype=b.dtype), b))\n+ if b.shape[0] <= a.shape[0]:\n+ return a.at[-b.shape[0]:].add(b)\nelse:\n- a = concatenate((np.zeros(shape_diff, dtype=b.dtype), a))\n+ return b.at[-a.shape[0]:].add(a)\n- return lax.add(a,b)\ndef _trim_zeros(a):\nfor i, v in enumerate(a):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1119,16 +1119,18 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_shape={}\".format(\n- jtu.format_shape_dtype_string(shape, dtype)),\n- \"dtype\": dtype, \"shape\": shape}\n+ {\"testcase_name\": \"a_shape={} , b_shape={}\".format(\n+ jtu.format_shape_dtype_string(a_shape, dtype),\n+ jtu.format_shape_dtype_string(b_shape, dtype)),\n+ \"dtype\": dtype, \"a_shape\": a_shape, \"b_shape\" : b_shape}\nfor dtype in default_dtypes\n- for shape in one_dim_array_shapes))\n- def testPolyAdd(self, shape, dtype):\n+ for a_shape in one_dim_array_shapes\n+ for b_shape in one_dim_array_shapes))\n+ def testPolyAdd(self, a_shape, b_shape, dtype):\nrng = jtu.rand_default(self.rng())\nnp_fun = lambda arg1, arg2: np.polyadd(arg1, arg2)\njnp_fun = lambda arg1, arg2: jnp.polyadd(arg1, arg2)\n- args_maker = lambda: [rng(shape, dtype), rng(shape, dtype)]\n+ args_maker = lambda: [rng(a_shape, dtype), rng(b_shape, dtype)]\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=True)\nself._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n"
}
] | Python | Apache License 2.0 | google/jax | Fix polyadd and test (#3344) |
260,335 | 08.06.2020 11:48:58 | 25,200 | 982f86702e55c33e063e02285dad77376ceebfda | clean up handling of aux data in jvp_subtrace_aux
related to indirectly, in that we now won't try to do something
crazy like `JVPTracer(trace, object(), zero)`, which didn't like | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -74,10 +74,10 @@ def jvp_subtrace_aux(master, primals, tangents):\nassert x._trace.level < trace.level\nans, aux = yield map(partial(JVPTracer, trace), primals, tangents), {}\nans_tracers = map(trace.full_raise, ans)\n- aux_tracers = map(trace.full_raise, aux)\nout_primals, out_tangents = unzip2((t.primal, t.tangent) for t in ans_tracers)\n- aux_primals, _ = unzip2((t.primal, t.tangent) for t in aux_tracers)\n- aux_primals = map(core.full_lower, aux_primals)\n+ aux_primals = [core.full_lower(x.primal)\n+ if isinstance(x, JVPTracer) and x._trace.level == trace.level\n+ else x for x in aux]\nyield (out_primals, out_tangents), aux_primals\ndef linearize(traceable, *primals, **kwargs):\n"
}
] | Python | Apache License 2.0 | google/jax | clean up handling of aux data in jvp_subtrace_aux
related to #3222 indirectly, in that we now won't try to do something
crazy like `JVPTracer(trace, object(), zero)`, which #3222 didn't like |
260,335 | 08.06.2020 13:16:19 | 25,200 | fb8b3a4df9c2746fb1768d1175511f59eef0c802 | symbolic zeros tweak to work with div rule | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -144,7 +144,8 @@ def backward_pass(jaxpr: core.Jaxpr, consts, primals_in, cotangents_in):\ndef write_cotangent(v, ct):\n# assert v not in primal_env\n- if ct is not None and type(v) is not Literal and type(ct) is not Zero:\n+ if (ct is not None and type(v) is not Literal and\n+ type(ct) is not Zero and ct is not Zero):\nct_env[v] = add_tangents(ct_env[v], ct) if v in ct_env else ct\nif not core.skip_checks:\nct_aval = core.get_aval(ct_env[v])\n@@ -195,7 +196,7 @@ def backward_pass(jaxpr: core.Jaxpr, consts, primals_in, cotangents_in):\nparams, call_jaxpr, invals, cts_in, cts_in_avals)\nelse:\ncts_out = get_primitive_transpose(eqn.primitive)(cts_in, *invals, **eqn.params)\n- cts_out = map(lambda v: Zero(v.aval), eqn.invars) if cts_out is Zero else cts_out\n+ cts_out = [Zero(v.aval) for v in eqn.invars] if cts_out is Zero else cts_out\n# FIXME: Some invars correspond to primals!\nmap(write_cotangent, eqn.invars, cts_out)\nfor var in to_drop:\n"
}
] | Python | Apache License 2.0 | google/jax | symbolic zeros tweak to work with div rule |
260,335 | 08.06.2020 13:22:13 | 25,200 | 866c17c32ec10d46c79ccaf3069189e776b3536f | fix a couple ad_util.Zero type checks | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2871,7 +2871,7 @@ def _concatenate_translation_rule(c, *operands, **kwargs):\ndef _concatenate_transpose_rule(t, *operands, dimension):\noperand_shapes = [o.aval.shape if ad.is_undefined_primal(o) else o.shape\nfor o in operands]\n- if t is ad_util.Zero:\n+ if type(t) is ad_util.Zero:\nreturn ad_util.Zero\nelse:\nlimit_points = onp.cumsum([shape[dimension] for shape in operand_shapes])\n@@ -2916,7 +2916,7 @@ def _pad_shape_rule(operand, padding_value, *, padding_config):\nreturn tuple(out_shape)\ndef _pad_transpose(t, operand, padding_value, *, padding_config):\n- if t is ad_util.Zero:\n+ if type(t) is ad_util.Zero:\nreturn ad_util.Zero\nlo, hi, interior = zip(*padding_config)\n"
}
] | Python | Apache License 2.0 | google/jax | fix a couple ad_util.Zero type checks |
260,335 | 08.06.2020 13:30:00 | 25,200 | 0a716978adb67194a7ce5c4f373e1f60f14c9b9a | fix a docs bug | [
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/How_JAX_primitives_work.ipynb",
"new_path": "docs/notebooks/How_JAX_primitives_work.ipynb",
"diff": "\" else:\\n\",\n\" # This use of multiply_add is with a constant \\\"y\\\"\\n\",\n\" assert ad.is_undefined_primal(x)\\n\",\n- \" ct_x = ad.zero if ct is ad.zero else multiply_add_prim(ct, y, lax.zeros_like_array(y))\\n\",\n+ \" ct_x = ad.Zero(x.aval) if type(ct) is ad.Zero else multiply_add_prim(ct, y, lax.zeros_like_array(y))\\n\",\n\" res = ct_x, None, ct\\n\",\n\" return res\\n\",\n\"\\n\",\n"
}
] | Python | Apache License 2.0 | google/jax | fix a docs bug |
260,335 | 08.06.2020 13:46:10 | 25,200 | 04191ab9de7ed262e4b2b3fd885435e272ae157e | improve broadcast handling in batching.py
We can avoid a circular import just by `import jax`! | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "import numpy as onp\nfrom typing import Any, Callable, Dict, Optional, Tuple, Union\n+import jax\nfrom .. import core\nfrom ..core import Trace, Tracer, new_master\nfrom ..abstract_arrays import ShapedArray, raise_to_shaped\n@@ -23,7 +24,6 @@ from .. import linear_util as lu\nfrom ..util import unzip2, partial, safe_map, wrap_name, split_list\nfrom . import xla\nfrom . import partial_eval as pe\n-from .. import lax_reference\nmap = safe_map\n@@ -294,13 +294,6 @@ defvectorized(xla.device_put_p)\n### util\n-# These utilities depend on primitives for things like broadcasting, reshaping,\n-# and transposition on arrays. To avoid a circular import from depending on\n-# lax.py, these functions use method dispatch on their arguments, which could be\n-# DeviceArrays, numpy.ndarrays, or traced versions of those. This strategy\n-# almost works, except for broadcast, for which raw numpy.ndarrays don't have a\n-# method. To handle that case, the `broadcast` function uses a try/except.\n-\nclass _Last(object): pass\nlast = _Last()\n@@ -312,10 +305,7 @@ def broadcast(x, sz, axis):\nshape = list(onp.shape(x))\nshape.insert(axis, sz)\nbroadcast_dims = tuple(onp.delete(onp.arange(len(shape)), axis))\n- if isinstance(x, onp.ndarray) or onp.isscalar(x):\n- return lax_reference.broadcast_in_dim(x, shape, broadcast_dims)\n- else:\n- return x.broadcast_in_dim(shape, broadcast_dims)\n+ return jax.lax.broadcast_in_dim(x, shape, broadcast_dims)\ndef moveaxis(x, src, dst):\nif core.get_aval(x) is core.abstract_unit:\n"
}
] | Python | Apache License 2.0 | google/jax | improve broadcast handling in batching.py
We can avoid a circular import just by `import jax`! |
260,335 | 08.06.2020 14:13:01 | 25,200 | 2a6d3f417c8fba37e109099d1618378b50c7c7b8 | fix another docs bug | [
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/How_JAX_primitives_work.ipynb",
"new_path": "docs/notebooks/How_JAX_primitives_work.ipynb",
"diff": "\"\\n\",\n\" In our case, multiply_add is not a linear primitive. However, it is used linearly \\n\",\n\" w.r.t. tangents in multiply_add_value_and_jvp:\\n\",\n- \" output_tangent(xt, yt, zt) = multiply_add_prim(xt, y, multiply_add_prim(x, yt, zt)\\n\",\n+ \" output_tangent(xt, yt, zt) = multiply_add_prim(xt, y, multiply_add_prim(x, yt, zt))\\n\",\n\" \\n\",\n\" Always one of the first two multiplicative arguments are constants.\\n\",\n\"\\n\",\n\" if not ad.is_undefined_primal(x):\\n\",\n\" # This use of multiply_add is with a constant \\\"x\\\"\\n\",\n\" assert ad.is_undefined_primal(y)\\n\",\n- \" ct_y = ad.zero if ct is ad.zero else multiply_add_prim(x, ct, lax.zeros_like_array(x))\\n\",\n+ \" ct_y = ad.Zero(y.aval) if type(ct) is ad.Zero else multiply_add_prim(x, ct, lax.zeros_like_array(x))\n\" res = None, ct_y, ct\\n\",\n\" else:\\n\",\n\" # This use of multiply_add is with a constant \\\"y\\\"\\n\",\n"
}
] | Python | Apache License 2.0 | google/jax | fix another docs bug |
260,335 | 08.06.2020 15:06:00 | 25,200 | ee428008c4bdc271a5c962a5b315a2f45056a290 | yet another doc fix | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -830,7 +830,7 @@ def vmap(fun: Callable, in_axes=0, out_axes=0) -> Callable:\nacross the mapped axis:\n>>> print(vmap(lambda x, y: (x + y, y * 2.), in_axes=(0, None), out_axes=0)(np.arange(2.), 4.))\n- (DeviceArray([4., 5.], dtype=float32), array([8., 8.]))\n+ (DeviceArray([4., 5.], dtype=float32), DeviceArray([8., 8.], dtype=float32))\nIf the ``out_axes`` is specified for a mapped result, the result is\ntransposed accordingly.\n"
}
] | Python | Apache License 2.0 | google/jax | yet another doc fix |
260,411 | 09.06.2020 12:28:03 | -10,800 | 67927b071e1c6c0ded453761ca8ebd0e043df731 | Fix imports for jax_to_tf tests | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"new_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"diff": "@@ -27,13 +27,14 @@ import numpy as np\nimport tensorflow as tf # type: ignore[import]\nfrom jax.experimental import jax_to_tf\n-from . import tf_test_util\n-from . import primitive_harness\n-\n+from jax.experimental.jax_to_tf.tests import tf_test_util\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n+# Import after parsing flags\n+from jax.experimental.jax_to_tf.tests import primitive_harness\n+\n# TODO(tomhennigan) Increase coverage here.\nLAX_ELEMENTWISE_UNARY = (\nlax.abs,\n"
}
] | Python | Apache License 2.0 | google/jax | Fix imports for jax_to_tf tests (#3377) |
260,335 | 09.06.2020 15:19:53 | 25,200 | 0011fd5e9429fc463e585737c0d69ca0b03cb08f | fix defjvps with None as first rule
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -75,7 +75,7 @@ def _initial_style_jaxpr(fun, in_avals):\ntyped_jaxpr = core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)\nreturn typed_jaxpr\n-def sum_tangents(x, *xs):\n+def sum_tangents(_, x, *xs):\nreturn reduce(ad.add_tangents, xs, x)\ndef zeros_like_pytree(x):\n@@ -196,7 +196,7 @@ class custom_jvp:\nzeros = zeros_like_pytree(primal_out)\nall_tangents_out = [jvp(t, primal_out, *primals) if jvp else zeros\nfor t, jvp in zip(tangents, jvps)]\n- tangent_out = tree_multimap(sum_tangents, *all_tangents_out)\n+ tangent_out = tree_multimap(sum_tangents, primal_out, *all_tangents_out)\nreturn primal_out, tangent_out\nself.defjvp(jvp)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2476,6 +2476,17 @@ class CustomJVPTest(jtu.JaxTestCase):\nexpected = -1.\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_custom_jvps_first_rule_is_none(self):\n+ # https://github.com/google/jax/issues/3389\n+ @api.custom_jvp\n+ def f(x, y):\n+ return x ** 2 * y\n+\n+ f.defjvps(None, lambda x_dot, primal_out, x, y: 2 * x * y * x_dot)\n+ ans = grad(f, 1)(2., 3.) # doesn't crash\n+ expected = 12.\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nclass CustomVJPTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | fix defjvps with None as first rule
fixes #3389 |
260,335 | 09.06.2020 19:20:15 | 25,200 | 650fb494ad9f955ac8ddc979b1bdd8e64faf57fd | tweak t logpdf tolerance for float64 | [
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -373,7 +373,8 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\ntol=1e-3)\n- self._CompileAndCheck(lax_fun, args_maker)\n+ self._CompileAndCheck(lax_fun, args_maker,\n+ rtol={onp.float64: 1e-14}, atol={onp.float64: 1e-14})\n@genNamedParametersNArgs(3, jtu.rand_default)\n"
}
] | Python | Apache License 2.0 | google/jax | tweak t logpdf tolerance for float64 |
260,411 | 10.06.2020 08:13:40 | -10,800 | b3c348cc07ec31b560532a48c0c759263341b003 | Moved shift_right implementation from tfxla to jax_to_tf
* Implemented shift_right without tfxla
These ops don't actually need XLA, they should not depend on tfxla.
* Small fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/jax_to_tf.py",
"new_path": "jax/experimental/jax_to_tf/jax_to_tf.py",
"diff": "@@ -175,7 +175,7 @@ class TensorFlowTracer(core.Tracer):\nself._trace = trace\nif not isinstance(val, (tf.Tensor, tf.Variable)):\naval = xla.abstractify(val)\n- val = tf.convert_to_tensor(np.array(val, aval.dtype), dtype=aval.dtype)\n+ val = tf.convert_to_tensor(np.array(val, aval.dtype), dtype=aval.dtype) # type: ignore[attribute-error]\nself.val = val\n@property\n@@ -321,12 +321,45 @@ tf_impl[lax.rem_p] = wrap_binary_op(_rem)\ntf_impl[lax.max_p] = wrap_binary_op(tf.math.maximum)\ntf_impl[lax.min_p] = wrap_binary_op(tf.math.minimum)\n+# Map from TF signed types to TF unsigned types.\n+_SIGNED_TO_UNSIGNED_TABLE = {\n+ tf.int8: tf.uint8,\n+ tf.int16: tf.uint16,\n+ tf.int32: tf.uint32,\n+ tf.int64: tf.uint64,\n+}\n+\n+# Map from TF unsigned types to TF signed types.\n+_UNSIGNED_TO_SIGNED_TABLE = {u: s for s, u in _SIGNED_TO_UNSIGNED_TABLE.items()}\n# Note: Bitwise operations only yield identical results on unsigned integers!\n-tf_impl[lax.shift_left_p] = tf.bitwise.left_shift\n# pylint: disable=protected-access\n-tf_impl[lax.shift_right_arithmetic_p] = tfxla._shift_right_arithmetic_helper\n-tf_impl[lax.shift_right_logical_p] = tfxla._shift_right_logical_helper\n+def _shift_right_arithmetic(x, y):\n+ if x.dtype.is_unsigned:\n+ assert x.dtype == y.dtype\n+ orig_dtype = x.dtype\n+ signed_dtype = _UNSIGNED_TO_SIGNED_TABLE[orig_dtype]\n+ x = tf.cast(x, signed_dtype)\n+ y = tf.cast(y, signed_dtype)\n+ res = tf.bitwise.right_shift(x, y)\n+ return tf.cast(res, orig_dtype)\n+ else:\n+ return tf.bitwise.right_shift(x, y)\n+tf_impl[lax.shift_right_arithmetic_p] = _shift_right_arithmetic\n+\n+def _shift_right_logical(x, y):\n+ if x.dtype.is_unsigned:\n+ return tf.bitwise.right_shift(x, y)\n+ else:\n+ assert x.dtype == y.dtype\n+ orig_dtype = x.dtype\n+ unsigned_dtype = _SIGNED_TO_UNSIGNED_TABLE[orig_dtype]\n+ x = tf.cast(x, unsigned_dtype)\n+ y = tf.cast(y, unsigned_dtype)\n+ res = tf.bitwise.right_shift(x, y)\n+ return tf.cast(res, orig_dtype)\n+tf_impl[lax.shift_right_logical_p] = _shift_right_logical\n+\ntf_impl[lax.shift_left_p] = tf.bitwise.left_shift\ntf_impl[lax.not_p] = tf.bitwise.invert\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax_to_tf/tests/primitive_harness.py",
"diff": "@@ -21,23 +21,30 @@ NumPy (lax_reference) or TensorFlow.\nfrom typing import Any, Callable, Dict, Iterable, Optional, NamedTuple, Sequence, Tuple, Union\nfrom absl import testing\n+from jax import config\nfrom jax import test_util as jtu\nfrom jax import dtypes\nfrom jax import lax\nimport numpy as np\n+FLAGS = config.FLAGS\n+\n# TODO: these are copied from tests/lax_test.py (make this source of truth)\n+# Do not run int64 tests unless FLAGS.jax_enable_x64, otherwise we get a\n+# mix of int32 and int64 operations.\ndef supported_dtypes(dtypes):\n- return [t for t in dtypes if t in jtu.supported_dtypes()]\n+ return [t for t in dtypes if\n+ t in jtu.supported_dtypes() and\n+ (FLAGS.jax_enable_x64 or np.dtype(t).itemsize != 8)]\nfloat_dtypes = supported_dtypes([dtypes.bfloat16, np.float16, np.float32,\nnp.float64])\ncomplex_elem_dtypes = supported_dtypes([np.float32, np.float64])\ncomplex_dtypes = supported_dtypes([np.complex64, np.complex128])\ninexact_dtypes = float_dtypes + complex_dtypes\n-int_dtypes = supported_dtypes([np.int32, np.int64])\n-uint_dtypes = supported_dtypes([np.uint32, np.uint64])\n+int_dtypes = supported_dtypes([np.int8, np.int16, np.int32, np.int64])\n+uint_dtypes = supported_dtypes([np.uint8, np.uint16, np.uint32, np.uint64])\nbool_dtypes = [np.bool_]\ndefault_dtypes = float_dtypes + int_dtypes\nall_dtypes = float_dtypes + complex_dtypes + int_dtypes + bool_dtypes\n@@ -168,3 +175,33 @@ lax_squeeze = jtu.cases_from_list(\n]\nfor dtype in [np.float32]\n)\n+\n+shift_inputs = [\n+ (arg, dtype, shift_amount)\n+ for dtype in supported_dtypes(uint_dtypes + int_dtypes)\n+ for arg in [\n+ np.array([-250, -1, 0, 1, 250], dtype=dtype),\n+ ]\n+ for shift_amount in [0, 1, 2, 3, 7]\n+]\n+\n+lax_shift_left = jtu.cases_from_list(\n+ Harness(f\"_dtype={dtype.__name__}_shift_amount={shift_amount}\", # type: ignore\n+ lax.shift_left,\n+ [arg, StaticArg(np.array([shift_amount], dtype=dtype))])\n+ for arg, dtype, shift_amount in shift_inputs\n+)\n+\n+lax_shift_right_logical = jtu.cases_from_list(\n+ Harness(f\"_dtype={dtype.__name__}_shift_amount={shift_amount}\", # type: ignore\n+ lax.shift_right_logical,\n+ [arg, StaticArg(np.array([shift_amount], dtype=dtype))])\n+ for arg, dtype, shift_amount in shift_inputs\n+)\n+\n+lax_shift_right_arithmetic = jtu.cases_from_list(\n+ Harness(f\"_dtype={dtype.__name__}_shift_amount={shift_amount}\", # type: ignore\n+ lax.shift_right_arithmetic,\n+ [arg, StaticArg(np.array([shift_amount], dtype=dtype))])\n+ for arg, dtype, shift_amount in shift_inputs\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"new_path": "jax/experimental/jax_to_tf/tests/tf_ops_test.py",
"diff": "@@ -86,8 +86,6 @@ LAX_LOGICAL_ELEMENTWISE_BINARY = (\nlax.bitwise_or,\nlax.bitwise_xor,\nlax.shift_left,\n- lax.shift_right_arithmetic,\n- lax.shift_right_logical,\n)\nREDUCE = (\n@@ -245,6 +243,23 @@ class TfOpsTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(r_jax[np.isfinite(r_jax)],\nr_tf[np.isfinite(r_tf)], atol=1e-4)\n+ # TODO(necula): combine tests that are identical except for the harness\n+ # wait until we get more experience with using harnesses.\n+ @primitive_harness.parameterized(primitive_harness.lax_shift_left)\n+ def test_shift_left(self, harness):\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ with_function=True)\n+\n+ @primitive_harness.parameterized(primitive_harness.lax_shift_right_logical)\n+ def test_shift_right_logical(self, harness):\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ with_function=True)\n+\n+ @primitive_harness.parameterized(primitive_harness.lax_shift_right_arithmetic)\n+ def test_shift_right_arithmetic(self, harness):\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ with_function=True)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_{f_jax.__name__}\",\nf_jax=f_jax)\n"
}
] | Python | Apache License 2.0 | google/jax | Moved shift_right implementation from tfxla to jax_to_tf (#3378)
* Implemented shift_right without tfxla
These ops don't actually need XLA, they should not depend on tfxla.
* Small fixes |
260,285 | 10.06.2020 11:47:47 | -7,200 | 98a32f2c5999c69d9367bf2bd9dcaacaaab114c2 | Remove special case for scan masking
The scan masking rule is now simplified to a standard masking rule, and the special case handling in masking.py has been removed. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -33,7 +33,6 @@ from .. import linear_util as lu\nmap = safe_map\nzip = safe_zip\n-shape_parameterized_primitive_rules: Dict[core.Primitive, Callable] = {}\nmasking_rules: Dict[core.Primitive, Callable] = {}\ndef defvectorized(prim):\n@@ -369,7 +368,7 @@ class MaskTracer(Tracer):\n@property\ndef dtype(self):\n- return self.val.dtype\n+ return self.val.dtype if hasattr(self.val, 'dtype') else type(self.val)\ndef is_pure(self):\nreturn all(type(poly) is not Poly or poly.is_constant\n@@ -393,24 +392,18 @@ class MaskTrace(Trace):\nreturn MaskTracer(self, val.val, val.polymorphic_shape)\ndef process_primitive(self, primitive, tracers, params):\n- vals, polymorphic_shapes = unzip2((t.val, t.polymorphic_shape) for t in tracers)\n- if primitive in shape_parameterized_primitive_rules:\n- rule = shape_parameterized_primitive_rules[primitive]\n- out, out_shape = rule(shape_envs, vals, polymorphic_shapes, **params)\n- else:\n- avals = [t.aval for t in tracers]\n- out = primitive.abstract_eval(*avals, **params)\n- out_shape = [o.shape for o in out] if primitive.multiple_results else out.shape\n- logical_shapes = map(shape_as_value, polymorphic_shapes)\nmasking_rule = masking_rules.get(primitive)\nif masking_rule is None:\nraise NotImplementedError(\n- 'Masking rule for {} not implemented yet.'.format(primitive))\n+ f'Masking rule for {primitive} not implemented yet.')\n+ aout = primitive.abstract_eval(*(t.aval for t in tracers), **params)\n+ vals, polymorphic_shapes = unzip2((t.val, t.polymorphic_shape) for t in tracers)\n+ logical_shapes = map(shape_as_value, polymorphic_shapes)\nout = masking_rule(vals, logical_shapes, **params)\n- if not primitive.multiple_results:\n- return MaskTracer(self, out, out_shape)\n+ if primitive.multiple_results:\n+ return map(partial(MaskTracer, self), out, (o.shape for o in aout))\nelse:\n- return map(partial(MaskTracer, self), out, out_shape)\n+ return MaskTracer(self, out, aout.shape)\ndef process_call(self, call_primitive, f, tracers, params):\nassert call_primitive.multiple_results\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -1481,11 +1481,9 @@ def _scan_shape_rule(shapes, reverse, length, jaxpr,\nys_shapes = [(length,) + tuple(y_aval.shape) for y_aval in y_avals]\nreturn init_shexprs + ys_shapes\n-def _scan_masking_rule(shape_envs, padded_vals, shape_exprs, reverse, length,\n+def _scan_masking_rule(padded_vals, logical_shapes, reverse, length,\njaxpr, num_consts, num_carry, linear):\n- out_shape = _scan_shape_rule(shape_exprs, reverse, length, jaxpr,\n- num_consts, num_carry, linear)\n- dynamic_length = length.evaluate(shape_envs.logical)\n+ dynamic_length, = masking.shape_as_value((length,))\nmasked_jaxpr = _masked_scan_jaxpr(jaxpr, num_consts, num_carry)\nconsts, init, xs = split_list(padded_vals, [num_consts, num_carry])\nmax_length, = {x.shape[0] for x in xs}\n@@ -1495,7 +1493,7 @@ def _scan_masking_rule(shape_envs, padded_vals, shape_exprs, reverse, length,\nreverse=reverse, length=max_length, jaxpr=masked_jaxpr,\nnum_consts=1 + num_consts, num_carry=1 + num_carry,\nlinear=tuple([False] + const_linear + [False] + init_linear + xs_linear))\n- return out_vals[1:], out_shape\n+ return out_vals[1:]\ndef _masked_scan_jaxpr(jaxpr, num_consts, num_carry):\nfun = core.jaxpr_as_fun(jaxpr)\n@@ -1540,7 +1538,7 @@ pe.custom_partial_eval_rules[scan_p] = _scan_partial_eval\nxla.initial_style_translations[scan_p] = \\\nxla.lower_fun_initial_style(_scan_impl)\nbatching.primitive_batchers[scan_p] = _scan_batching_rule\n-masking.shape_parameterized_primitive_rules[scan_p] = _scan_masking_rule\n+masking.masking_rules[scan_p] = _scan_masking_rule\ndef map(f, xs):\n"
}
] | Python | Apache License 2.0 | google/jax | Remove special case for scan masking
The scan masking rule is now simplified to a standard masking rule, and the special case handling in masking.py has been removed. |
260,285 | 10.06.2020 12:56:26 | -7,200 | c39b6a40652218fbd67923ea57499a6cfc2d75fa | Remove unused scan shape rule | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax_control_flow.py",
"new_path": "jax/lax/lax_control_flow.py",
"diff": "@@ -1474,13 +1474,6 @@ def _scan_batching_rule(args, dims, reverse, length, jaxpr, num_consts,\nys_bdims = [1 if b else batching.not_mapped for b in ys_batched]\nreturn outs, carry_bdims + ys_bdims\n-def _scan_shape_rule(shapes, reverse, length, jaxpr,\n- num_consts, num_carry, linear):\n- const_shexprs, init_shexprs, xs_shexprs = split_list(shapes, [num_consts, num_carry])\n- _, y_avals = split_list(jaxpr.out_avals, [num_carry])\n- ys_shapes = [(length,) + tuple(y_aval.shape) for y_aval in y_avals]\n- return init_shexprs + ys_shapes\n-\ndef _scan_masking_rule(padded_vals, logical_shapes, reverse, length,\njaxpr, num_consts, num_carry, linear):\ndynamic_length, = masking.shape_as_value((length,))\n"
}
] | Python | Apache License 2.0 | google/jax | Remove unused scan shape rule |
260,519 | 11.06.2020 02:57:35 | -36,000 | 832431db9eea95f2212370b47bdd0e6e891fcd0a | Add np.triu_indices_from function | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -268,8 +268,10 @@ Not every function in NumPy is implemented; contributions are welcome!\ntri\ntril\ntril_indices\n+ tril_indices_from\ntriu\ntriu_indices\n+ triu_indices_from\ntrue_divide\ntrunc\nunique\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -54,8 +54,8 @@ from .lax_numpy import (\nsave, savez, searchsorted, select, set_printoptions, shape, sign, signbit,\nsignedinteger, sin, sinc, single, sinh, size, sometrue, sort, split, sqrt,\nsquare, squeeze, stack, std, subtract, sum, swapaxes, take, take_along_axis,\n- tan, tanh, tensordot, tile, trace, trapz, transpose, tri, tril, tril_indices,\n- triu, triu_indices, true_divide, trunc, uint16, uint32, uint64, uint8, unique,\n+ tan, tanh, tensordot, tile, trace, trapz, transpose, tri, tril, tril_indices, tril_indices_from,\n+ triu, triu_indices, triu_indices_from, true_divide, trunc, uint16, uint32, uint64, uint8, unique,\nunpackbits, unravel_index, unsignedinteger, vander, var, vdot, vsplit,\nvstack, where, zeros, zeros_like)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2542,6 +2542,17 @@ tril_indices = _wrap_indices_function(np.tril_indices)\ntriu_indices = _wrap_indices_function(np.triu_indices)\nmask_indices = _wrap_indices_function(np.mask_indices)\n+\n+@_wraps(np.triu_indices_from)\n+def triu_indices_from(arr, k=0):\n+ return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1])\n+\n+\n+@_wraps(np.tril_indices_from)\n+def tril_indices_from(arr, k=0):\n+ return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1])\n+\n+\n@_wraps(np.diag_indices)\ndef diag_indices(n, ndim=2):\nif n < 0:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1481,6 +1481,58 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"n={}_k={}_m={}\".format(n, k, m),\n+ \"n\": n, \"k\": k, \"m\": m}\n+ for n in range(1, 5)\n+ for k in [-1, 0, 1]\n+ for m in range(1, 5)))\n+ def testTrilIndices(self, n, k, m):\n+ np_fun = lambda n, k, m: np.tril_indices(n, k=k, m=m)\n+ jnp_fun = lambda n, k, m: jnp.tril_indices(n, k=k, m=m)\n+ args_maker = lambda: [n, k, m]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"n={}_k={}_m={}\".format(n, k, m),\n+ \"n\": n, \"k\": k, \"m\": m}\n+ for n in range(1, 5)\n+ for k in [-1, 0, 1]\n+ for m in range(1, 5)))\n+ def testTriuIndices(self, n, k, m):\n+ np_fun = lambda n, k, m: np.triu_indices(n, k=k, m=m)\n+ jnp_fun = lambda n, k, m: jnp.triu_indices(n, k=k, m=m)\n+ args_maker = lambda: [n, k, m]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_k={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), k),\n+ \"dtype\": dtype, \"shape\": shape, \"k\": k, \"rng_factory\": jtu.rand_default}\n+ for dtype in default_dtypes\n+ for shape in [(1,1), (1,2), (2,2), (2,3), (3,2), (3,3), (4,4)]\n+ for k in [-1, 0, 1]))\n+ def testTriuIndicesFrom(self, shape, dtype, k, rng_factory):\n+ rng = rng_factory(self.rng())\n+ np_fun = lambda arr, k: np.triu_indices_from(arr, k=k)\n+ jnp_fun = lambda arr, k: jnp.triu_indices_from(arr, k=k)\n+ args_maker = lambda: [rng(shape, dtype), k]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_k={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), k),\n+ \"dtype\": dtype, \"shape\": shape, \"k\": k, \"rng_factory\": jtu.rand_default}\n+ for dtype in default_dtypes\n+ for shape in [(1,1), (1,2), (2,2), (2,3), (3,2), (3,3), (4,4)]\n+ for k in [-1, 0, 1]))\n+ def testTrilIndicesFrom(self, shape, dtype, k, rng_factory):\n+ rng = rng_factory(self.rng())\n+ np_fun = lambda arr, k: np.tril_indices_from(arr, k=k)\n+ jnp_fun = lambda arr, k: jnp.tril_indices_from(arr, k=k)\n+ args_maker = lambda: [rng(shape, dtype), k]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_ndim={}_n={}\".format(ndim, n),\n\"ndim\": ndim, \"n\": n}\n"
}
] | Python | Apache License 2.0 | google/jax | Add np.triu_indices_from function (#3346) |
260,285 | 11.06.2020 07:08:12 | -7,200 | dfd2d8c564b304343090b85643c1f2abcf2515fa | Fix dtype, minor | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -23,7 +23,7 @@ from typing import Callable, Dict, Sequence, Union\nimport numpy as onp\nfrom .. import abstract_arrays\n-from .. import core\n+from .. import core, dtypes\nfrom ..tree_util import tree_unflatten\nfrom ..core import Trace, Tracer\nfrom ..util import safe_map, safe_zip, unzip2, prod, wrap_name\n@@ -368,7 +368,7 @@ class MaskTracer(Tracer):\n@property\ndef dtype(self):\n- return getattr(self.val, 'dtype', type(self.val))\n+ return dtypes.dtype(self.val)\ndef is_pure(self):\nreturn all(type(poly) is not Poly or poly.is_constant\n@@ -396,14 +396,14 @@ class MaskTrace(Trace):\nif masking_rule is None:\nraise NotImplementedError(\nf'Masking rule for {primitive} not implemented yet.')\n- aout = primitive.abstract_eval(*(t.aval for t in tracers), **params)\n+ out_aval = primitive.abstract_eval(*(t.aval for t in tracers), **params)\nvals, polymorphic_shapes = unzip2((t.val, t.polymorphic_shape) for t in tracers)\nlogical_shapes = map(shape_as_value, polymorphic_shapes)\nout = masking_rule(vals, logical_shapes, **params)\nif primitive.multiple_results:\n- return map(partial(MaskTracer, self), out, (o.shape for o in aout))\n+ return map(partial(MaskTracer, self), out, (o.shape for o in out_aval))\nelse:\n- return MaskTracer(self, out, aout.shape)\n+ return MaskTracer(self, out, out_aval.shape)\ndef process_call(self, call_primitive, f, tracers, params):\nassert call_primitive.multiple_results\n"
}
] | Python | Apache License 2.0 | google/jax | Fix dtype, minor |
260,335 | 11.06.2020 14:21:02 | 25,200 | 1a433620a3c98ec6f49a9f39eb71730987b9003e | make jnp.array(x, copy=True) copies device buffers
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -43,7 +43,7 @@ from .. import dtypes\nfrom ..abstract_arrays import UnshapedArray, ShapedArray, ConcreteArray, canonicalize_shape\nfrom ..config import flags\nfrom ..interpreters.xla import (DeviceArray, device_put, array_result_handler,\n- DeviceValue)\n+ DeviceValue, abstractify)\nfrom ..interpreters.masking import Poly\nfrom .. import lax\nfrom .. import ops\n@@ -2120,9 +2120,12 @@ def array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nout = _device_put_raw(object)\nif dtype: assert _dtype(out) == dtype\nelif isinstance(object, (DeviceValue, core.Tracer)):\n+ if isinstance(object, DeviceArray) and copy:\n+ # We perform a copy by bouncing back to the host\n+ # TODO(phawkins): add a device runtime function to copy a buffer\n+ out = _device_put_raw(np.asarray(object))\n+ else:\nout = object\n- if dtype and _dtype(out) != dtype:\n- out = lax.convert_element_type(out, dtype)\nelif isinstance(object, (list, tuple)):\nif object:\nout = stack([array(elt, dtype=dtype) for elt in object])\n@@ -2138,6 +2141,9 @@ def array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nraise TypeError(\"Unexpected input type for array: {}\".format(type(object)))\n+ if dtype and _dtype(out) != dtype:\n+ out = lax.convert_element_type(out, dtype)\n+\nif ndmin > ndim(out):\nout = lax.broadcast(out, (1,) * (ndmin - ndim(out)))\nreturn out\n@@ -2146,9 +2152,9 @@ def _can_call_numpy_array(x):\nreturn _all(not isinstance(l, (core.Tracer, DeviceValue))\nfor l in tree_leaves(x))\n+# TODO(mattjj): maybe move these two functions into xla.py\ndef _device_put_raw(x):\n- aval = core.raise_to_shaped(core.get_aval(x))\n- return array_result_handler(None, aval)(device_put(x))\n+ return array_result_handler(None, abstractify(x))(device_put(x))\n@_wraps(np.asarray)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -3114,6 +3114,21 @@ class BufferDonationTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, \"nested.*not supported\"):\njit_fun(a)\n+ def test_jnp_array_copy(self):\n+ # https://github.com/google/jax/issues/3412\n+\n+ @partial(api.jit, donate_argnums=(0,))\n+ def _test(array):\n+ return array.at[0].set(77)\n+\n+ x = jnp.asarray([0, 1])\n+ x_copy = jnp.array(x, copy=True)\n+ new_x = _test(x)\n+\n+ # Gives: RuntimeError: Invalid argument: CopyToHostAsync() called on invalid buffer.\n+ print(x_copy) # doesn't crash\n+\n+\n# === pmap ===\n@jtu.skip_on_devices(\"cpu\", \"gpu\") # In/out aliasing only supported on TPU.\n"
}
] | Python | Apache License 2.0 | google/jax | make jnp.array(x, copy=True) copies device buffers
fixes #3412 |
260,314 | 12.06.2020 01:42:25 | 14,400 | b680c994ae0f07f4fdfb482177ef82857ee97a49 | allow scalar input in poisson sampler | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -1186,7 +1186,7 @@ def poisson(key, lam, shape=(), dtype=np.int64):\nshape = abstract_arrays.canonicalize_shape(shape)\nif np.shape(lam) != shape:\nlam = jnp.broadcast_to(lam, shape)\n- lam = lam.astype(np.float32)\n+ lam = lax.convert_element_type(lam, np.float32)\nreturn _poisson(key, lam, shape, dtype)\n"
}
] | Python | Apache License 2.0 | google/jax | allow scalar input in poisson sampler |
260,287 | 12.06.2020 15:03:26 | -7,200 | 2dac55a0bfca6911237b43bd8882c9a4bf4ed258 | Skip known invars and outvars in JaxprTrace.process_call | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/masking.py",
"new_path": "jax/interpreters/masking.py",
"diff": "@@ -425,6 +425,9 @@ class MaskTrace(Trace):\n# Make padded_env hashable\npadded_env = (env_keys, padded_env_vals)\nf, shapes_out = mask_subtrace(f, self.master, shapes, padded_env)\n+ if 'donated_invars' in params:\n+ params = dict(params, donated_invars=((False,) * len(logical_env_vals) +\n+ params['donated_invars']))\nvals_out = call_primitive.bind(f, *(logical_env_vals + vals), **params)\nreturn [MaskTracer(self, v, s) for v, s in zip(vals_out, shapes_out())]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -27,7 +27,7 @@ from .. import linear_util as lu\nfrom ..abstract_arrays import ConcreteArray, raise_to_shaped\nfrom ..ad_util import Zero\nfrom ..util import (unzip2, safe_zip, safe_map, toposort, partial, split_list,\n- wrap_name, cache, curry)\n+ cache, curry)\nfrom ..core import (Trace, Tracer, new_master, Jaxpr, Literal, get_aval,\nAbstractValue, unit, unitvar, abstract_unit,\nTypedJaxpr, new_jaxpr_eqn)\n@@ -166,19 +166,36 @@ class JaxprTrace(Trace):\nout_tracer.recipe = new_eqn_recipe(tracers, [out_tracer], primitive, params)\nreturn out_tracer\n- def process_call(self, call_primitive, f: lu.WrappedFun, tracers, params):\n+ def process_call(self, primitive, f: lu.WrappedFun, tracers, params):\nname = params.get('name', f.__name__)\nif (self.master.trace_type is StagingJaxprTrace\n- and call_primitive in staged_out_calls):\n+ and primitive in staged_out_calls):\ntracers = map(self.instantiate_const_abstracted, tracers)\nparams = dict(params, name=name)\n- if call_primitive in call_partial_eval_rules:\n- return call_partial_eval_rules[call_primitive](self, call_primitive, f, tracers, params)\n+ if primitive in call_partial_eval_rules:\n+ return call_partial_eval_rules[primitive](self, primitive, f, tracers, params)\n+ @curry\n+ def modify_aval(modify, args):\n+ pval, is_mapped = args\n+ if pval.is_known() or not is_mapped:\n+ return pval\n+ return PartialVal((modify(params['axis_size'], pval[0]), pval[1]))\n+\n+ in_pvals = [t.pval for t in tracers]\n+ if primitive.map_primitive:\n+ in_pvals = map(modify_aval(core.mapped_aval), zip(in_pvals, params['mapped_invars']))\njaxpr, out_pvals, consts, env_tracers = self.partial_eval(\n- f, [t.pval for t in tracers], partial(call_primitive.bind, **params))\n- if not jaxpr.eqns:\n+ f, in_pvals, partial(primitive.bind, **params))\n+ if primitive.map_primitive:\n+ out_pvals = map(modify_aval(core.unmapped_aval),\n+ [(pval, True) for pval in out_pvals])\n+\n+ # Don't bother if the traced jaxpr is trivial. Simply evaluate it in here.\n+ # XXX: We don't allow this fast path for map primitives, because this simplification might\n+ # e.g. reduce the number of required devices if someone pmaps an identity function.\n+ if not primitive.map_primitive and not jaxpr.eqns:\nenv = {core.unitvar: core.unit}\nmap(env.setdefault, jaxpr.invars, (*env_tracers, *tracers))\nmap(env.setdefault, jaxpr.constvars, consts)\n@@ -187,21 +204,37 @@ class JaxprTrace(Trace):\nelse env[v]\nfor v, pval in zip(jaxpr.outvars, out_pvals)]\n- const_tracers = map(self.new_instantiated_const, consts)\n+ # Skip known invars and outvars, and lift constants as regular invars\n+ in_knowns = tuple(t.pval.is_known() for t in it.chain(env_tracers, tracers))\n+ out_unknowns = tuple(not pval.is_known() for pval in out_pvals)\n+ jaxpr = _drop_invars(jaxpr, in_knowns)\n+ jaxpr = _dce_untyped_jaxpr(jaxpr, out_unknowns, drop_outputs=True)\nlifted_jaxpr = convert_constvars_jaxpr(jaxpr)\n- out_tracers = [JaxprTracer(self, pval, None) for pval in out_pvals]\n+\n+ # Known tracers get propagated as if they were constants\n+ known_tracers_out = [self.new_const(pval.get_known()) for pval in out_pvals if pval.is_known()]\n+\n+ # Unknown tracers need to have the jaxpr set up as their recipe\n+ unknown_tracers_out = [JaxprTracer(self, pval, None) for pval in out_pvals if not pval.is_known()]\n+ unknown_tracers_in = [t for t in tracers if not t.pval.is_known()]\n+ const_tracers = map(self.new_instantiated_const, consts)\nnew_params = dict(params, call_jaxpr=lifted_jaxpr)\n- invars = tuple(it.chain(const_tracers, env_tracers, tracers))\nif 'donated_invars' in params:\nnew_donated_invars = ((False,) * len(const_tracers) +\n(False,) * len(env_tracers) +\n- params['donated_invars'])\n- new_params['donated_invars'] = tuple(new_donated_invars)\n- # The `jaxpr` already contains the env_vars at start of invars\n- eqn = new_eqn_recipe(invars, out_tracers, call_primitive, new_params)\n- for t in out_tracers:\n+ tuple(v for v, t in zip(params['donated_invars'], tracers) if not t.pval.is_known()))\n+ new_params['donated_invars'] = new_donated_invars\n+ if primitive.map_primitive:\n+ new_mapped_invars = ((True,) * len(const_tracers) +\n+ (False,) * len(env_tracers) +\n+ tuple(v for v, t in zip(params['mapped_invars'], tracers) if not t.pval.is_known()))\n+ new_params['mapped_invars'] = new_mapped_invars\n+ eqn = new_eqn_recipe(tuple(it.chain(const_tracers, env_tracers, unknown_tracers_in)),\n+ unknown_tracers_out, primitive, new_params)\n+ for t in unknown_tracers_out:\nt.recipe = eqn\n- return out_tracers\n+\n+ return _zip_knowns(known_tracers_out, unknown_tracers_out, out_unknowns)\ndef post_process_call(self, call_primitive, out_tracers, params):\njaxpr, consts, env = tracers_to_jaxpr([], out_tracers)\n@@ -229,48 +262,7 @@ class JaxprTrace(Trace):\nreturn out_tracers\nreturn out, todo\n- def process_map(self, map_primitive, f: lu.WrappedFun, tracers, params):\n- name = params.get('name', f.__name__)\n- if self.master.trace_type is StagingJaxprTrace:\n- tracers = map(self.instantiate_const_abstracted, tracers)\n- else:\n- name = wrap_name(name, 'pe')\n- params = dict(params, name=name)\n-\n- @curry\n- def modify_aval(modify, args):\n- pval, is_mapped = args\n- if pval.is_known() or not is_mapped:\n- return pval\n- return PartialVal((modify(params['axis_size'], pval[0]), pval[1]))\n-\n- reduced_in_pvals = map(modify_aval(core.mapped_aval),\n- zip([t.pval for t in tracers], params['mapped_invars']))\n- jaxpr, reduced_out_pvals, consts, env_tracers = self.partial_eval(\n- f, reduced_in_pvals, partial(map_primitive.bind, **params))\n- out_pvals = map(modify_aval(core.unmapped_aval),\n- [(pval, True) for pval in reduced_out_pvals])\n-\n- const_tracers = map(self.new_instantiated_const, consts)\n- lifted_jaxpr = convert_constvars_jaxpr(jaxpr)\n- out_tracers = [JaxprTracer(self, pval, None) for pval in out_pvals]\n- # The `jaxpr` already contains the env_vars at start of invars\n- new_donated_invars = ((False,) * len(const_tracers) +\n- (False,) * len(env_tracers) +\n- params['donated_invars'])\n- new_mapped_invars = ((True,) * len(const_tracers) +\n- (False,) * len(env_tracers) +\n- params['mapped_invars'])\n- new_params = dict(params, donated_invars=tuple(new_donated_invars),\n- mapped_invars=tuple(new_mapped_invars),\n- call_jaxpr=lifted_jaxpr)\n- assert (len(new_params['mapped_invars'])\n- == len(const_tracers) + len(env_tracers) + len(tracers))\n- eqn = new_eqn_recipe(tuple(it.chain(const_tracers, env_tracers, tracers)),\n- out_tracers, map_primitive, new_params)\n- for t in out_tracers:\n- t.recipe = eqn\n- return out_tracers\n+ process_map = process_call\ndef post_process_map(self, map_primitive, out_tracers, params):\njaxpr, consts, env = tracers_to_jaxpr([], out_tracers)\n@@ -327,6 +319,12 @@ class JaxprTrace(Trace):\nenv_tracers = map(self.full_raise, env)\nreturn jaxpr, out_pvs, consts, env_tracers\n+# This subclass is used just for its type tag (see comment for `JaxprTrace`)\n+# This switches the behavior of process_call to stage out into the jaxpr any\n+# call primitives encountered (rather than doing partial evaluation into the call).\n+class StagingJaxprTrace(JaxprTrace):\n+ pass\n+\n@lu.transformation_with_aux\ndef partial_eval_wrapper(avals: Sequence[Optional[AbstractValue]], *consts):\n@@ -337,12 +335,6 @@ def partial_eval_wrapper(avals: Sequence[Optional[AbstractValue]], *consts):\nyield out, (out_pvs, jaxpr, env)\n-# This subclass is used just for its type tag (see comment for `JaxprTrace`)\n-# This switches the behavior of process_call to stage out into the jaxpr any\n-# call primitives encountered (rather than doing partial evaluation into the call).\n-class StagingJaxprTrace(JaxprTrace):\n- pass\n-\ncustom_partial_eval_rules: Dict[core.Primitive, Callable] = {}\ncall_partial_eval_rules: Dict[core.Primitive, Callable] = {}\nstaged_out_calls: Set[core.Primitive] = set()\n@@ -396,6 +388,9 @@ class JaxprTracer(Tracer):\nelse:\nreturn self\n+ def is_known(self):\n+ return self.pval.is_known()\n+\n# TODO(necula): this should return a TypedJaxpr\n# TODO(necula): remove stage_out, replace trace_type=pe.StagingJaxprTrace\ndef trace_to_jaxpr(fun: lu.WrappedFun, pvals: Sequence[PartialVal],\n@@ -705,7 +700,7 @@ def _remat_partial_eval(trace, _, f, tracers, params):\n# Using the instantiated tracers, run call_bind like JaxprTrace.process_call.\nin_pvals = [t.pval for t in instantiated_tracers]\nwith core.initial_style_staging():\n- jaxpr, out_pvals1, consts, env_tracers = trace.partial_eval(\n+ jaxpr, eval_out_pvals, consts, env_tracers = trace.partial_eval(\nf, in_pvals, partial(remat_call_p.bind, **params))\n# Since we traced with everything marked as unknown, but we need to know which\n@@ -716,53 +711,86 @@ def _remat_partial_eval(trace, _, f, tracers, params):\nout_avals = [raise_to_shaped(abstract_unit if var is unitvar\nelse get_aval(var.val) if type(var) is Literal\nelse pval.get_aval())\n- for var, pval in zip(jaxpr.outvars, out_pvals1)]\n+ for var, pval in zip(jaxpr.outvars, eval_out_pvals)]\ntyped_jaxpr = core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)\n- in_unknowns = [t.pval[0] is not None for t in it.chain(env_tracers, tracers)]\n- jaxpr_1, jaxpr_2, out_unknowns = partial_eval_jaxpr(typed_jaxpr, in_unknowns,\n+ in_unknowns = [not t.is_known() for t in it.chain(env_tracers, tracers)]\n+ jaxpr_known, jaxpr_unknown, out_unknowns = partial_eval_jaxpr(typed_jaxpr, in_unknowns,\ninstantiate=False,\ntrace_type=trace.master.trace_type)\n- num_res = len(jaxpr_1.out_avals) - len(jaxpr_2.out_avals)\n+ out_knowns = [not b for b in out_unknowns]\n# First, we prune the jaxpr to be staged out not to have too many outputs.\n- typed_jaxpr = _dce_jaxpr(typed_jaxpr, out_unknowns)\n+ typed_jaxpr = _dce_jaxpr(typed_jaxpr, out_unknowns, drop_outputs=True)\n+\n+ out_known_pvals, out_unknown_pvals = _partition_knowns(eval_out_pvals, out_unknowns)\n# Next, we need values for the outputs that should be known. Since consts\n- # weren't passed through Python for evaluation, we need to evaluate jaxpr_1,\n+ # weren't passed through Python for evaluation, we need to evaluate jaxpr_known,\n# minus the residual outputs that we don't need. When `concrete=True`, as an\n# optimization we can avoid redoing *some* redundant FLOPs, namely those that\n# produced concrete avals at the output, simply by using those as computed\n- # values. For the use case of reverse-mode ad in op-by-op (\"eager mode\")\n+ # values. For the use case of inverse-mode ad in op-by-op (\"eager mode\")\n# evaluation, all the primal outputs should be concrete (thus not recomputed).\n- to_compute = [not uk and type(pval[0]) is not ConcreteArray\n- for uk, pval in zip(out_unknowns, out_pvals1)]\n- jaxpr_1_primals = _dce_jaxpr(jaxpr_1, to_compute + [False] * num_res)\n+ to_compute = [type(pval[0]) is not ConcreteArray\n+ for uk, pval in zip(out_unknowns, eval_out_pvals)\n+ if not uk]\n+ num_outputs = len(jaxpr_unknown.out_avals)\n+ num_res = len(jaxpr_known.out_avals) - num_outputs\n+ jaxpr_known_nores = _dce_jaxpr(jaxpr_known, out_knowns + [False] * num_res, drop_outputs=True)\n+ jaxpr_known_comp = _dce_jaxpr(jaxpr_known_nores, to_compute)\n_, in_consts = unzip2(t.pval for t in it.chain(env_tracers, tracers))\n- out_pval_consts2 = core.jaxpr_as_fun(jaxpr_1_primals)(*in_consts)[:-num_res or None]\n- out_pvals = map(_reconstruct_pval, out_pvals1, out_pval_consts2, out_unknowns)\n+ reconstructed_consts = core.jaxpr_as_fun(jaxpr_known_comp)(*in_consts)\n+ out_known_pvals = map(_reconstruct_pval, out_known_pvals, reconstructed_consts)\n+\n+ # Now that we have out_pvals, the rest is similar to JaxprTrace.process_call.\n+ # Known outputs should keep propagating as constants\n+ assert all(pv.is_known() for pv in out_known_pvals)\n+ known_output_tracers = [trace.new_const(pval.get_known()) for pval in out_known_pvals]\n- # Now that we have out_pvals, the rest is just like JaxprTrace.process_call.\n- instantiated_tracers = env_tracers + instantiated_tracers\n+ # Unknown outputs get wrapped in tracers with the appropriate recipe, as in JaxprTrace.process_call\nconst_tracers = map(trace.new_instantiated_const, consts)\n+ unknown_output_tracers = [JaxprTracer(trace, out_pval, None) for out_pval in out_unknown_pvals]\nlifted_jaxpr = convert_constvars_jaxpr(typed_jaxpr.jaxpr)\n- out_tracers = [JaxprTracer(trace, out_pval, None) for out_pval in out_pvals]\nnew_params = dict(params, call_jaxpr=lifted_jaxpr)\n- eqn = new_eqn_recipe(tuple(it.chain(const_tracers, instantiated_tracers)),\n- out_tracers, remat_call_p, new_params)\n- for t in out_tracers: t.recipe = eqn\n- return out_tracers\n+ eqn = new_eqn_recipe(tuple(it.chain(const_tracers, env_tracers, instantiated_tracers)),\n+ unknown_output_tracers,\n+ remat_call_p,\n+ new_params)\n+ for t in unknown_output_tracers: t.recipe = eqn\n+\n+ return _zip_knowns(known_output_tracers, unknown_output_tracers, out_unknowns)\ncall_partial_eval_rules[remat_call_p] = _remat_partial_eval\n-def _dce_jaxpr(typed_jaxpr: core.TypedJaxpr,\n- outputs: Sequence[bool]) -> core.TypedJaxpr:\n+def _partition_knowns(l, unknowns):\n+ return ([e for e, unknown in zip(l, unknowns) if not unknown],\n+ [e for e, unknown in zip(l, unknowns) if unknown])\n+\n+def _zip_knowns(kl, ul, unknowns):\n+ ul_it = iter(ul)\n+ kl_it = iter(kl)\n+ return [next(ul_it) if unknown else next(kl_it) for unknown in unknowns]\n+\n+\n+def _dce_jaxpr(typed_jaxpr: TypedJaxpr, outputs: Sequence[bool], drop_outputs=False) -> TypedJaxpr:\n+ if drop_outputs:\n+ new_out_avals = [aval for aval, output in zip(typed_jaxpr.out_avals, outputs) if output]\n+ else:\n+ new_out_avals = [aval if output else core.abstract_unit\n+ for aval, output in zip(typed_jaxpr.out_avals, outputs)]\n+ new_jaxpr = _dce_untyped_jaxpr(typed_jaxpr.jaxpr, tuple(outputs), drop_outputs)\n+ return core.TypedJaxpr(new_jaxpr, typed_jaxpr.literals, typed_jaxpr.in_avals,\n+ new_out_avals)\n+\n+@cache()\n+def _dce_untyped_jaxpr(jaxpr: Jaxpr, outputs: Tuple[bool, ...], drop_outputs=False) -> Jaxpr:\n# This dead-code elimination is pretty rudimentary, and in particular doesn't\n# nontrivially DCE through scan, call, or other higher-order primitives.\n# TODO(mattjj): better DCE\n- jaxpr = typed_jaxpr.jaxpr\n- outvars, out_avals = jaxpr.outvars, typed_jaxpr.out_avals\n- out_pairs = [(var, aval) if output else (unitvar, core.abstract_unit)\n- for var, aval, output in zip(outvars, out_avals, outputs)]\n- new_outvars, new_out_avals = unzip2(out_pairs)\n+ if drop_outputs:\n+ new_outvars = [var for var, output in zip(jaxpr.outvars, outputs) if output]\n+ else:\n+ new_outvars = [var if output else unitvar\n+ for var, output in zip(jaxpr.outvars, outputs)]\nneeded_vars = {v for v in new_outvars if type(v) is not Literal}\nnew_eqns = []\n@@ -771,14 +799,18 @@ def _dce_jaxpr(typed_jaxpr: core.TypedJaxpr,\nnew_eqns.append(eqn)\nneeded_vars.update(v for v in eqn.invars if type(v) is not Literal)\nnew_eqns = new_eqns[::-1]\n- new_jaxpr = core.Jaxpr(jaxpr.constvars, jaxpr.invars,\n+ return core.Jaxpr(jaxpr.constvars, jaxpr.invars,\nnew_outvars, new_eqns)\n- return core.TypedJaxpr(new_jaxpr, typed_jaxpr.literals, typed_jaxpr.in_avals,\n- new_out_avals)\n-def _reconstruct_pval(pval1: PartialVal, const2: core.Value, unknown: bool):\n+@cache()\n+def _drop_invars(jaxpr: Jaxpr, drop: Tuple[bool, ...]):\n+ return core.Jaxpr(jaxpr.constvars, [v for v, d in zip(jaxpr.invars, drop) if not d],\n+ jaxpr.outvars, jaxpr.eqns)\n+\n+\n+def _reconstruct_pval(pval1: PartialVal, const2: core.Value):\npv1, _ = pval1\n- if unknown or pval1.is_known():\n+ if pval1.is_known():\nreturn pval1\nelse:\nif type(pv1) is ConcreteArray:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1099,6 +1099,7 @@ xla_pmap_p.multiple_results = True\nxla_pmap = partial(core.map_bind, xla_pmap_p)\nxla_pmap_p.def_custom_bind(xla_pmap)\nxla_pmap_p.def_impl(xla_pmap_impl)\n+pe.staged_out_calls.add(xla_pmap_p)\ndef _pmap_translation_rule(c, axis_env,\nin_nodes, name_stack, axis_name, axis_size,\n"
}
] | Python | Apache License 2.0 | google/jax | Skip known invars and outvars in JaxprTrace.process_call (#3242) |
260,335 | 12.06.2020 15:41:07 | 25,200 | ae9df752de75344d231c7ec973fdd562a91d8913 | add docstring to ravel_pytree | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.rst",
"new_path": "docs/jax.rst",
"diff": "@@ -17,6 +17,7 @@ Subpackages\njax.ops\njax.random\njax.tree_util\n+ jax.flatten_util\njax.dlpack\njax.profiler\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/flatten_util.py",
"new_path": "jax/flatten_util.py",
"diff": "@@ -24,17 +24,21 @@ zip = safe_zip\ndef ravel_pytree(pytree):\n+ \"\"\"Ravel (i.e. flatten) a pytree of arrays down to a 1D array.\n+\n+ Args:\n+ pytree: a pytree to ravel.\n+\n+ Returns:\n+ A pair where the first element is a 1D array representing the flattened and\n+ concatenated leaf values, and the second element is a callable for\n+ unflattening a 1D vector of the same length back to a pytree of of the same\n+ structure as the input ``pytree``.\n+ \"\"\"\nleaves, treedef = tree_flatten(pytree)\n- flat, unravel_list = vjp(ravel_list, *leaves)\n+ flat, unravel_list = vjp(_ravel_list, *leaves)\nunravel_pytree = lambda flat: tree_unflatten(treedef, unravel_list(flat))\nreturn flat, unravel_pytree\n-def ravel_list(*lst):\n+def _ravel_list(*lst):\nreturn jnp.concatenate([jnp.ravel(elt) for elt in lst]) if lst else jnp.array([])\n-\n-\n-@lu.transformation_with_aux\n-def ravel_fun(unravel_inputs, flat_in, **kwargs):\n- pytree_args = unravel_inputs(flat_in)\n- ans = yield pytree_args, {}\n- yield ravel_pytree(ans)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/tree_util.py",
"new_path": "jax/tree_util.py",
"diff": "@@ -49,23 +49,26 @@ def tree_flatten(tree):\nArgs:\ntree: a pytree to flatten.\n+\nReturns:\n- a pair with a list of leaves and the corresponding treedef.\n+ A pair where the first element is a list of leaf values and the second\n+ element is a treedef representing the structure of the flattened tree.\n\"\"\"\nreturn pytree.flatten(tree)\ndef tree_unflatten(treedef, leaves):\n\"\"\"Reconstructs a pytree from the treedef and the leaves.\n- The inverse of `tree_flatten`.\n+ The inverse of :func:`tree_flatten`.\nArgs:\ntreedef: the treedef to reconstruct\n- leaves: the list of leaves to use for reconstruction. The list must\n- match the leaves of the treedef.\n+ leaves: the list of leaves to use for reconstruction. The list must match\n+ the leaves of the treedef.\n+\nReturns:\n- The reconstructed pytree, containing the `leaves` placed in the\n- structure described by `treedef`.\n+ The reconstructed pytree, containing the ``leaves`` placed in the structure\n+ described by ``treedef``.\n\"\"\"\nreturn treedef.unflatten(leaves)\n@@ -102,7 +105,7 @@ def all_leaves(iterable):\niterable: Iterable of leaves.\nReturns:\n- True if all elements in the input are leaves false if not.\n+ A boolean indicating if all elements in the input are leaves.\n\"\"\"\nreturn pytree.all_leaves(iterable)\n@@ -113,14 +116,14 @@ def register_pytree_node(nodetype, flatten_func, unflatten_func):\nArgs:\nnodetype: a Python type to treat as an internal pytree node.\n- flatten_func: a function to be used during flattening, taking a value\n- of type `nodetype` and returning a pair, with (1) an iterable for\n- the children to be flattened recursively, and (2) some auxiliary data\n- to be stored in the treedef and to be passed to the `unflatten_func`.\n- unflatten_func: a function taking two arguments: the auxiliary data that\n- was returned by `flatten_func` and stored in the treedef, and the\n+ flatten_func: a function to be used during flattening, taking a value of\n+ type ``nodetype`` and returning a pair, with (1) an iterable for the\n+ children to be flattened recursively, and (2) some auxiliary data to be\n+ stored in the treedef and to be passed to the ``unflatten_func``.\n+ unflatten_func: a function taking two arguments: the auxiliary data that was\n+ returned by ``flatten_func`` and stored in the treedef, and the\nunflattened children. The function should return an instance of\n- `nodetype`.\n+ ``nodetype``.\n\"\"\"\npytree.register_node(nodetype, flatten_func, unflatten_func)\n_registry[nodetype] = _RegistryEntry(flatten_func, unflatten_func)\n@@ -149,13 +152,13 @@ def tree_map(f, tree):\n\"\"\"Maps a function over a pytree to produce a new pytree.\nArgs:\n- f: function to be applied at each leaf.\n+ f: unary function to be applied at each leaf.\ntree: a pytree to be mapped over.\nReturns:\nA new pytree with the same structure as `tree` but with the value at each\n- leaf given by `f(x)` where `x` is the value at the corresponding leaf in\n- `tree`.\n+ leaf given by ``f(x)`` where ``x`` is the value at the corresponding leaf in\n+ the input ``tree``.\n\"\"\"\nleaves, treedef = pytree.flatten(tree)\nreturn treedef.unflatten(map(f, leaves))\n@@ -164,17 +167,18 @@ def tree_multimap(f, tree, *rest):\n\"\"\"Maps a multi-input function over pytree args to produce a new pytree.\nArgs:\n- f: function that takes `1 + len(rest)` arguments, to be applied at the\n+ f: function that takes ``1 + len(rest)`` arguments, to be applied at the\ncorresponding leaves of the pytrees.\ntree: a pytree to be mapped over, with each leaf providing the first\n- positional argument to `f`.\n+ positional argument to ``f``.\n*rest: a tuple of pytrees, each of which has the same structure as tree or\nor has tree as a prefix.\n+\nReturns:\n- A new pytree with the same structure as `tree` but with the value at each\n- leaf given by `f(x, *xs)` where `x` is the value at the corresponding leaf\n- in `tree` and `xs` is the tuple of values at corresponding nodes in\n- `rest`.\n+ A new pytree with the same structure as ``tree`` but with the value at each\n+ leaf given by ``f(x, *xs)`` where ``x`` is the value at the corresponding\n+ leaf in ``tree`` and ``xs`` is the tuple of values at corresponding nodes in\n+ ``rest``.\n\"\"\"\nleaves, treedef = pytree.flatten(tree)\nall_leaves = [leaves] + [treedef.flatten_up_to(r) for r in rest]\n@@ -214,7 +218,7 @@ _registry = {\ntype(None): _RegistryEntry(lambda z: ((), None), lambda _, xs: None),\n}\ndef _replace_nones(sentinel, tree):\n- \"\"\"Replaces `None` in `tree` with `sentinel`.\"\"\"\n+ \"\"\"Replaces ``None`` in ``tree`` with ``sentinel``.\"\"\"\nif tree is None:\nreturn sentinel\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | add docstring to ravel_pytree |
260,335 | 14.06.2020 13:56:53 | 25,200 | 482067640578a40f088e5556a702090d12c26d5a | add jax.numpy.concatenate(..., axis=None) support
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1995,6 +1995,8 @@ def concatenate(arrays, axis=0):\nraise ValueError(\"Need at least one array to concatenate.\")\nif ndim(arrays[0]) == 0:\nraise ValueError(\"Zero-dimensional arrays cannot be concatenated.\")\n+ if axis is None:\n+ return concatenate([ravel(a) for a in arrays], axis=0)\naxis = _canonicalize_axis(axis, ndim(arrays[0]))\narrays = _promote_dtypes(*arrays)\n# lax.concatenate can be slow to compile for wide concatenations, so form a\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1218,6 +1218,12 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ def testConcatenateAxisNone(self):\n+ # https://github.com/google/jax/issues/3419\n+ a = jnp.array([[1, 2], [3, 4]])\n+ b = jnp.array([[5]])\n+ jnp.concatenate((a, b), axis=None)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_axis={}_baseshape=[{}]_dtypes=[{}]\".format(\naxis, \",\".join(str(d) for d in base_shape),\n"
}
] | Python | Apache License 2.0 | google/jax | add jax.numpy.concatenate(..., axis=None) support
fixes #3419 |
260,335 | 14.06.2020 14:45:29 | 25,200 | 29fa935ca56dd6aa8fc688a30f860c300fe93bd6 | fix vmap-of-pmap mapped_invars logic bug
fixes
This crept in via but more importantly it shows we don't have
good test coverage here! | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -161,10 +161,12 @@ class BatchTrace(Trace):\nif all(dim is not_mapped for dim in dims):\nreturn map_primitive.bind(f, *vals, **params)\nelse:\n+ mapped_invars = params['mapped_invars']\nsize, = {x.shape[d] for x, d in zip(vals, dims) if d is not not_mapped}\n- vals = [moveaxis(x, d, 1) if d is not not_mapped and d != 1 else x\n- for x, d in zip(vals, dims)]\n- dims = tuple(not_mapped if d is not_mapped else 0 for d in dims)\n+ vals = [moveaxis(x, d, 1) if d == 0 and mapped_invar else x\n+ for x, d, mapped_invar in zip(vals, dims, mapped_invars)]\n+ dims = tuple(not_mapped if d is not_mapped else max(0, d - mapped_invar)\n+ for d, mapped_invar in zip(dims, mapped_invars))\nf, dims_out = batch_subtrace(f, self.master, dims)\nvals_out = map_primitive.bind(f, *vals, **params)\ndims_out = tuple(d + 1 if d is not not_mapped else d for d in dims_out())\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -854,6 +854,29 @@ class PmapTest(jtu.JaxTestCase):\nans = s(keys) # doesn't crash\nself.assertEqual(ans.shape, (13, N_DEVICES))\n+ def testVmapOfPmap3(self):\n+ # https://github.com/google/jax/issues/3399\n+ device_count = xla_bridge.device_count()\n+ if device_count < 2:\n+ raise SkipTest(\"test requires at least two devices\")\n+\n+ def map_version(qs, pts):\n+ return jax.lax.map(lambda x: func(x, pts), qs)\n+\n+ def vmap_version(qs, pts):\n+ return jax.vmap(func, in_axes=(0, None))(qs, pts)\n+\n+ def func(q, pts):\n+ q_from_pmap = jax.pmap(lambda x, y: y, in_axes=(0, None))(pts, q)\n+ return q, q_from_pmap\n+\n+ pts = jnp.ones(device_count)\n+ qs = jnp.asarray(((0,0), (3,3), (2,2)))\n+\n+ _, expected = map_version(qs, pts)\n+ _, ans = vmap_version(qs, pts)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef testVmapOfPmapNonLeadingAxis(self):\ndevice_count = xla_bridge.device_count()\nf0 = lambda x: x\n@@ -1210,7 +1233,6 @@ class PmapTest(jtu.JaxTestCase):\nout = pmap(lambda x: jax.lax.pmean(x, 'i'), 'i')(x)\nself.assertEqual(list(out), [1])\n-\nclass PmapWithDevicesTest(jtu.JaxTestCase):\ndef testAllDevices(self):\n"
}
] | Python | Apache License 2.0 | google/jax | fix vmap-of-pmap mapped_invars logic bug
fixes #3399
This crept in via #1959, but more importantly it shows we don't have
good test coverage here! |
260,411 | 15.06.2020 10:05:23 | -10,800 | 0e804296766384763bfbb8cd6e2758b623d919ef | Added jax2tf test about primitive coverage | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -23,15 +23,21 @@ import jax\nfrom jax import abstract_arrays\nfrom jax import ad_util\nfrom jax import core\n+from jax import custom_derivatives\nfrom jax import lax\nfrom jax import linear_util as lu\nfrom jax import numpy as jnp\n+from jax import random\nfrom jax import tree_util\nfrom jax import util\nfrom jax.api_util import flatten_fun\nfrom jax.lax import lax_control_flow\n+from jax.lax import lax_fft\n+from jax import lax_linalg\n+from jax.interpreters import ad\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n+from jax.interpreters import pxla\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n@@ -243,10 +249,42 @@ def wrap_binary_op(func):\nreturn func(*promote_types(lhs, rhs), *args, **kwargs)\nreturn wrapped_func\n+def _unexpected_primitive(p: core.Primitive, *args, **kwargs):\n+ assert False, f\"Encountered unexpected primitive {p}\"\ntf_impl: Dict[core.Primitive, Callable[..., Any]] = {}\n+for unexpected in [\n+ xla.xla_call_p]: # Not part of the public API\n+\n+ tf_impl[unexpected] = functools.partial(_unexpected_primitive, unexpected)\n+\n+# Primitives that are not yet implemented must be explicitly declared here.\n+tf_not_yet_impl = [\n+ ad_util.add_jaxvals_p, ad.custom_lin_p,\n+\n+ lax.after_all_p, lax.all_to_all_p, lax.create_token_p, lax_fft.fft_p,\n+ lax.igamma_grad_a_p, lax.infeed_p, lax.linear_solve_p, lax.outfeed_p,\n+ lax.sort_p, lax.pmax_p, lax.pmin_p, lax.ppermute_p, lax.psum_p,\n+ lax.population_count_p, lax.reduce_p, lax.reduce_window_p, lax.rng_uniform_p,\n+ lax.select_and_gather_add_p, lax.select_and_scatter_p,\n+ lax.top_k_p,\n+\n+ core.call_p,\n+ lax_linalg.cholesky_p, lax_linalg.eig_p, lax_linalg.eigh_p,\n+ lax_linalg.lu_p, lax_linalg.qr_p, lax_linalg.svd_p,\n+ lax_linalg.triangular_solve_p,\n+\n+ custom_derivatives.custom_jvp_call_jaxpr_p,\n+ custom_derivatives.custom_vjp_call_jaxpr_p,\n+\n+ random.random_gamma_p,\n+ pe.remat_call_p,\n+ pxla.xla_pmap_p, pxla.axis_index_p,\n+]\n+\ntf_impl[lax.tie_in_p] = lambda x, y: y\n+tf_impl[core.identity_p] = lambda x: x\ntf_impl[ad_util.stop_gradient_p] = tf.stop_gradient\ntf_impl[ad_util.zeros_like_p] = tf.zeros_like\ntf_impl[xla.device_put_p] = lambda x, device=None: x\n@@ -888,41 +926,6 @@ def _scan(*tf_args : TfVal, **kwargs):\ntf_impl[lax.scan_p] = _scan\n-# TODO: add_any\n-# TODO: after_all\n-# TODO: all_to_all\n-# TODO: axis_index\n-# TODO: cholesky_p\n-# TODO: create_token\n-# TODO: custom_jvp_call_jaxpr\n-# TODO: custom_lin\n-# TODO: custom_linear_solve\n-# TODO: custom_vjp_call_jaxpr\n-# TODO: eig\n-# TODO: eigh\n-# TODO: fft\n-# TODO: id\n-# TODO: infeed\n-# TODO: lu\n-# TODO: outfeed\n-# TODO: pmax\n-# TODO: pmin\n-# TODO: ppermute\n-# TODO: psum\n-# TODO: qr\n-# TODO: random_gamma\n-# TODO: reduce\n-# TODO: reduce_window\n-# TODO: rng_uniform\n-# TODO: select_and_gather_add\n-# TODO: select_and_scatter\n-# TODO: sort\n-# TODO: sort_key_val\n-# TODO: stop_gradient\n-# TODO: svd\n-# TODO: top_k\n-# TODO: triangular_solve\n-\ndef _register_checkpoint_pytrees():\n\"\"\"Registers TF custom container types as pytrees.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_ops_test.py",
"new_path": "jax/experimental/jax2tf/tests/tf_ops_test.py",
"diff": "@@ -20,16 +20,16 @@ from absl.testing import parameterized\nimport jax\nfrom jax import dtypes\n-import jax.lax as lax\n-import jax.numpy as jnp\n+from jax import lax\n+from jax import numpy as jnp\nfrom jax import test_util as jtu\n-import numpy as np\n-import tensorflow as tf # type: ignore[import]\n-\n+from jax.config import config\nfrom jax.experimental import jax2tf\nfrom jax.experimental.jax2tf.tests import tf_test_util\n+from jax.interpreters import xla\n+import numpy as np\n+import tensorflow as tf # type: ignore[import]\n-from jax.config import config\nconfig.parse_flags_with_absl()\n# Import after parsing flags\n@@ -108,6 +108,26 @@ INDEX = (\nclass TfOpsTest(tf_test_util.JaxToTfTestCase):\n+ def test_primitive_coverage(self):\n+ \"\"\"Fail if there are JAX primitives that are not implemented.\"\"\"\n+ # Harvest primitives from XLA translation tables\n+ all_primitives = (set(xla.translations)\n+ | set(xla.backend_specific_translations['cpu'])\n+ | set(xla.backend_specific_translations['gpu'])\n+ | set(xla.backend_specific_translations['tpu'])\n+ | set(xla.initial_style_translations)\n+ | set(xla.parallel_translations))\n+\n+ tf_impl = set(jax.experimental.jax2tf.jax2tf.tf_impl)\n+ tf_not_yet_impl = set(jax.experimental.jax2tf.jax2tf.tf_not_yet_impl)\n+\n+ all_primitives = tuple(sorted(all_primitives, key=str))\n+ for p in all_primitives:\n+ if p in tf_not_yet_impl:\n+ self.assertNotIn(p, tf_impl) # Should not be in both tf_impl and tf_not_yet_impl\n+ else:\n+ self.assertIn(p, tf_impl)\n+\ndef test_basics(self):\nf_jax = lambda x: jnp.sin(jnp.cos(x))\n_, res_tf = self.ConvertAndCompare(f_jax, 0.7)\n"
}
] | Python | Apache License 2.0 | google/jax | Added jax2tf test about primitive coverage (#3420) |
260,411 | 15.06.2020 10:59:46 | -10,800 | 1440ccf4f9ecd9a487d0ce55e5aa725ecaf0e961 | Fixed bug in argument type promotion for dynamic_update_slice
Also added tests for lax.slice, lax.dynamic_slice and
lax.dynamic_update_slice. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -292,8 +292,8 @@ def promote_types(*values):\ndef wrap_binary_op(func):\n- def wrapped_func(lhs, rhs, *args, **kwargs):\n- return func(*promote_types(lhs, rhs), *args, **kwargs)\n+ def wrapped_func(lhs, rhs, **kwargs):\n+ return func(*promote_types(lhs, rhs), **kwargs)\nreturn wrapped_func\ndef _unexpected_primitive(p: core.Primitive, *args, **kwargs):\n@@ -657,7 +657,8 @@ tf_impl[lax.dynamic_slice_p] = _dynamic_slice\ndef _dynamic_update_slice(operand, update, *start_indices):\n- return tfxla.dynamic_update_slice(operand, update, tf.stack(start_indices))\n+ return tfxla.dynamic_update_slice(*promote_types(operand, update),\n+ tf.stack(start_indices))\ntf_impl[lax.dynamic_update_slice_p] = _dynamic_update_slice\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -17,7 +17,7 @@ Used to test various implementations of JAX primitives, e.g., against\nNumPy (lax_reference) or TensorFlow.\n\"\"\"\n-\n+import operator\nfrom typing import Any, Callable, Dict, Iterable, Optional, NamedTuple, Sequence, Tuple, Union\nfrom absl import testing\n@@ -158,6 +158,59 @@ lax_pad = jtu.cases_from_list(\n]\n)\n+lax_slice = jtu.cases_from_list(\n+ Harness(f\"_shape={shape}_start_indices={start_indices}_limit_indices={limit_indices}_strides={strides}\", # type: ignore\n+ lax.slice,\n+ [RandArg(shape, dtype), # type: ignore\n+ StaticArg(start_indices), # type: ignore\n+ StaticArg(limit_indices), # type: ignore\n+ StaticArg(strides)], # type: ignore\n+ start_indices=start_indices, # type: ignore\n+ limit_indices=limit_indices) # type: ignore\n+ for shape, start_indices, limit_indices, strides in [\n+ [(3,), (1,), (2,), None],\n+ [(7,), (4,), (7,), None],\n+ [(5,), (1,), (5,), (2,)],\n+ [(8,), (1,), (6,), (2,)],\n+ [(5, 3), (1, 1), (3, 2), None],\n+ [(5, 3), (1, 1), (3, 1), None],\n+ [(7, 5, 3), (4, 0, 1), (7, 1, 3), None],\n+ [(5, 3), (1, 1), (2, 1), (1, 1)],\n+ [(5, 3), (1, 1), (5, 3), (2, 1)],\n+ ]\n+ for dtype in [np.float32]\n+)\n+\n+# Like lax_slice, but (a) make the start_indices dynamic arg, and no strides.\n+lax_dynamic_slice = [\n+ Harness(harness.name,\n+ lax.dynamic_slice,\n+ [harness.arg_descriptors[0],\n+ np.array(list(start_indices)),\n+ StaticArg(tuple(map(operator.sub, limit_indices, start_indices)))])\n+ for harness in lax_slice\n+ for start_indices in [harness.params[\"start_indices\"]]\n+ for limit_indices in [harness.params[\"limit_indices\"]]\n+]\n+\n+lax_dynamic_update_slice = jtu.cases_from_list(\n+ Harness((f\"_operand={jtu.format_shape_dtype_string(shape, dtype)}\" # type: ignore\n+ f\"_update={jtu.format_shape_dtype_string(update_shape, update_dtype)}\"\n+ f\"_start_indices={start_indices}\"),\n+ lax.dynamic_update_slice,\n+ [RandArg(shape, dtype), # type: ignore\n+ RandArg(update_shape, update_dtype), # type: ignore\n+ np.array(start_indices)]) # type: ignore\n+ for shape, start_indices, update_shape in [\n+ [(3,), (1,), (1,)],\n+ [(5, 3), (1, 1), (3, 1)],\n+ [(7, 5, 3), (4, 1, 0), (2, 0, 1)],\n+ ]\n+ for dtype, update_dtype in [\n+ (np.float32, np.float32),\n+ (np.float64, np.float32)\n+ ])\n+\nlax_squeeze = jtu.cases_from_list(\nHarness(f\"_inshape={jtu.format_shape_dtype_string(arg_shape, dtype)}_dimensions={dimensions}\", # type: ignore\nlax.squeeze,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_ops_test.py",
"new_path": "jax/experimental/jax2tf/tests/tf_ops_test.py",
"diff": "@@ -280,6 +280,21 @@ class TfOpsTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\nwith_function=True)\n+ @primitive_harness.parameterized(primitive_harness.lax_slice)\n+ def test_slice(self, harness):\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ with_function=True)\n+\n+ @primitive_harness.parameterized(primitive_harness.lax_dynamic_slice)\n+ def test_dynamic_slice(self, harness):\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ with_function=True)\n+\n+ @primitive_harness.parameterized(primitive_harness.lax_dynamic_update_slice)\n+ def test_dynamic_update_slice(self, harness):\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ with_function=True)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_{f_jax.__name__}\",\nf_jax=f_jax)\n"
}
] | Python | Apache License 2.0 | google/jax | Fixed bug in argument type promotion for dynamic_update_slice (#3427)
Also added tests for lax.slice, lax.dynamic_slice and
lax.dynamic_update_slice. |
260,411 | 15.06.2020 12:14:09 | -10,800 | 2e3d4393c218a5cd51e88e9e1fca0b47e587ddaa | [jax2tf] fix the too-early use of tf.constant
If I leave it at top-level, I get test failures about missing platform Host | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -57,14 +57,13 @@ TfVal = Any\n# Whenever we are in a JAX tracing context we must use `core.unit` values\n# in those places. However, when we move to TF we have to turn them into\n# some small TFVal; it does not matter which value since it will never be used\n-# in an actual operation.\n+# in an actual operation. We will use `tf.constant(np.nan, float32)`.\nTfValOrUnit = Union[TfVal, core.Unit]\n-_unit_tfval = tf.constant(np.nan, tf.float32)\n-\ndef _tfval_remove_unit(args: Sequence[TfValOrUnit]) -> Sequence[TfVal]:\n\"\"\"Replace core.unit with regular TF values.\"\"\"\n- return [_unit_tfval if a is core.unit else a for a in args]\n+ return [tf.constant(np.nan, tf.float32) if a is core.unit else a\n+ for a in args]\ndef _tfval_add_unit(vals: Sequence[TfVal],\navals: Sequence[core.AbstractValue]) -> Sequence[TfValOrUnit]:\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] fix the too-early use of tf.constant (#3446)
If I leave it at top-level, I get test failures about missing platform Host |
260,422 | 13.06.2020 11:39:01 | -3,600 | 3c78605bb8c1133bba6b59bb6a973b046018717a | Propagate raw __name__ and __doc__ of functions wrapped by jit and sharded_jit. | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -166,9 +166,6 @@ def jit(fun: Callable, static_argnums: Union[int, Iterable[int]] = (),\nout = xla.xla_call(flat_fun, *args_flat, device=device, backend=backend,\nname=flat_fun.__name__, donated_invars=donated_invars)\nreturn tree_unflatten(out_tree(), out)\n-\n- jitted_name = \"jit({}, static_argnums={})\"\n- f_jitted.__name__ = jitted_name.format(f_jitted.__name__, static_argnums)\nreturn f_jitted\n@contextmanager\n@@ -1164,9 +1161,6 @@ def pmap(fun: Callable, axis_name: Optional[AxisName] = None, *, in_axes=0,\nmapped_invars=tuple(axis is not None for axis in in_axes_flat),\ndonated_invars=tuple(donated_invars))\nreturn tree_unflatten(out_tree(), out)\n-\n- namestr = \"pmap({}, axis_name={})\".format\n- f_pmapped.__name__ = namestr(f_pmapped.__name__, axis_name)\nreturn f_pmapped\nclass _TempAxisName:\n@@ -1221,9 +1215,6 @@ def soft_pmap(fun: Callable, axis_name: Optional[AxisName] = None, *,\ndonated_invars=donated_invars)\nouts = [_reshape_merge(out) for out in reshaped_outs]\nreturn tree_unflatten(out_tree(), outs)\n-\n- namestr = \"soft_pmap({}, axis_name={})\".format\n- f_pmapped.__name__ = namestr(f_pmapped.__name__, axis_name)\nreturn f_pmapped\ndef _reshape_split(num_chunks, x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/sharded_jit.py",
"new_path": "jax/interpreters/sharded_jit.py",
"diff": "@@ -26,7 +26,7 @@ from . import xla\nfrom .. import linear_util as lu\nfrom ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\n-from ..api_util import flatten_axes, flatten_fun\n+from ..api_util import flatten_axes, flatten_fun, wraps\nfrom ..tree_util import tree_flatten, tree_unflatten\nfrom ..util import extend_name_stack, wrap_name, safe_zip\n@@ -264,6 +264,7 @@ def sharded_jit(fun: Callable, in_parts, out_parts, num_partitions: int = None):\nelse:\nnum_parts = pxla.get_num_partitions(in_parts, out_parts)\n+ @wraps(fun)\ndef wrapped(*args, **kwargs):\nif kwargs:\nraise NotImplementedError(\"sharded_jit over kwargs not yet supported\")\n"
}
] | Python | Apache License 2.0 | google/jax | Propagate raw __name__ and __doc__ of functions wrapped by jit and sharded_jit. |
260,335 | 15.06.2020 07:32:42 | 25,200 | 12ce6e376872d6e1bdacc0e88984f21f92dc0cc8 | roll back of while we debug internal fails | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -161,12 +161,10 @@ class BatchTrace(Trace):\nif all(dim is not_mapped for dim in dims):\nreturn map_primitive.bind(f, *vals, **params)\nelse:\n- mapped_invars = params['mapped_invars']\nsize, = {x.shape[d] for x, d in zip(vals, dims) if d is not not_mapped}\n- vals = [moveaxis(x, d, 1) if d == 0 and mapped_invar else x\n- for x, d, mapped_invar in zip(vals, dims, mapped_invars)]\n- dims = tuple(not_mapped if d is not_mapped else max(0, d - mapped_invar)\n- for d, mapped_invar in zip(dims, mapped_invars))\n+ vals = [moveaxis(x, d, 1) if d is not not_mapped and d != 1 else x\n+ for x, d in zip(vals, dims)]\n+ dims = tuple(not_mapped if d is not_mapped else 0 for d in dims)\nf, dims_out = batch_subtrace(f, self.master, dims)\nvals_out = map_primitive.bind(f, *vals, **params)\ndims_out = tuple(d + 1 if d is not not_mapped else d for d in dims_out())\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -856,6 +856,10 @@ class PmapTest(jtu.JaxTestCase):\ndef testVmapOfPmap3(self):\n# https://github.com/google/jax/issues/3399\n+\n+ # TODO(mattjj): re-enable\n+ raise SkipTest(\"temporarily skipping test while debugging others\")\n+\ndevice_count = xla_bridge.device_count()\nif device_count < 2:\nraise SkipTest(\"test requires at least two devices\")\n@@ -1233,6 +1237,7 @@ class PmapTest(jtu.JaxTestCase):\nout = pmap(lambda x: jax.lax.pmean(x, 'i'), 'i')(x)\nself.assertEqual(list(out), [1])\n+\nclass PmapWithDevicesTest(jtu.JaxTestCase):\ndef testAllDevices(self):\n"
}
] | Python | Apache License 2.0 | google/jax | roll back of #3439 while we debug internal fails |
260,335 | 15.06.2020 09:10:40 | 25,200 | fcfcffe334351d8e79670c48e2aa08cc86426341 | add systematic tests for vmap-of-pmap
fixes
Also re-applies the fix in (i.e it rolls-back the rollback PR because we're now confident it's correct (and some internal tests are buggy). | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -161,10 +161,12 @@ class BatchTrace(Trace):\nif all(dim is not_mapped for dim in dims):\nreturn map_primitive.bind(f, *vals, **params)\nelse:\n+ mapped_invars = params['mapped_invars']\nsize, = {x.shape[d] for x, d in zip(vals, dims) if d is not not_mapped}\n- vals = [moveaxis(x, d, 1) if d is not not_mapped and d != 1 else x\n- for x, d in zip(vals, dims)]\n- dims = tuple(not_mapped if d is not_mapped else 0 for d in dims)\n+ vals = [moveaxis(x, d, 1) if d == 0 and mapped_invar else x\n+ for x, d, mapped_invar in zip(vals, dims, mapped_invars)]\n+ dims = tuple(not_mapped if d is not_mapped else max(0, d - mapped_invar)\n+ for d, mapped_invar in zip(dims, mapped_invars))\nf, dims_out = batch_subtrace(f, self.master, dims)\nvals_out = map_primitive.bind(f, *vals, **params)\ndims_out = tuple(d + 1 if d is not not_mapped else d for d in dims_out())\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_vmap_test.py",
"new_path": "tests/lax_vmap_test.py",
"diff": "@@ -29,6 +29,7 @@ from jax import dtypes\nfrom jax import lax\nfrom jax import test_util as jtu\nfrom jax.lib import xla_client\n+from jax.util import safe_map, safe_zip\nfrom tests.lax_test import (all_dtypes, CombosWithReplacement,\ncompatible_shapes, default_dtypes, float_dtypes,\n@@ -38,6 +39,10 @@ from jax.config import config\nconfig.parse_flags_with_absl()\nFLAGS = config.FLAGS\n+map, unsafe_map = safe_map, map\n+zip, unsafe_zip = safe_zip, zip\n+\n+\ndef all_bdims(*shapes):\nbdims = (itertools.chain([cast(Optional[int], None)],\nrange(len(shape) + 1)) for shape in shapes)\n@@ -56,17 +61,15 @@ def slicer(x, bdim):\nreturn lambda i: lax.index_in_dim(x, i, bdim, keepdims=False)\ndef args_slicer(args, bdims):\n- slicers = list(map(slicer, args, bdims))\n+ slicers = map(slicer, args, bdims)\nreturn lambda i: [sl(i) for sl in slicers]\nclass LaxVmapTest(jtu.JaxTestCase):\ndef _CheckBatching(self, op, bdim_size, bdims, shapes, dtypes, rng,\nrtol=None, atol=None):\n- batched_shapes = list(jax.util.safe_map(partial(add_bdim, bdim_size),\n- bdims, shapes))\n- args = [rng(shape, dtype)\n- for shape, dtype in jax.util.safe_zip(batched_shapes, dtypes)]\n+ batched_shapes = map(partial(add_bdim, bdim_size), bdims, shapes)\n+ args = [rng(shape, dtype) for shape, dtype in zip(batched_shapes, dtypes)]\nargs_slice = args_slicer(args, bdims)\nans = api.vmap(op, bdims)(*args)\nexpected = onp.stack([op(*args_slice(i)) for i in range(bdim_size)])\n@@ -642,7 +645,7 @@ class LaxVmapTest(jtu.JaxTestCase):\n# Note also that we chose 3 * 5 * 3 * 5 such that it fits in the range of\n# values a bfloat16 can represent exactly to avoid ties.\nfor dtype, rng_factory in itertools.chain(\n- zip(float_dtypes + int_dtypes, itertools.repeat(jtu.rand_unique_int)))))\n+ unsafe_zip(float_dtypes + int_dtypes, itertools.repeat(jtu.rand_unique_int)))))\ndef testTopK(self, shape, dtype, k, bdims, rng_factory):\nrng = rng_factory(self.rng())\n# _CheckBatching doesn't work with tuple outputs, so test outputs separately.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "from concurrent.futures import ThreadPoolExecutor\nfrom functools import partial\n+import itertools as it\nimport os\nfrom random import shuffle\nfrom unittest import SkipTest\n@@ -37,6 +38,9 @@ from jax.util import prod\nfrom jax.interpreters import pxla\nfrom jax.interpreters import xla\n+from tests.lax_test import compatible_shapes\n+from tests.lax_vmap_test import all_bdims, add_bdim, args_slicer\n+\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -856,10 +860,6 @@ class PmapTest(jtu.JaxTestCase):\ndef testVmapOfPmap3(self):\n# https://github.com/google/jax/issues/3399\n-\n- # TODO(mattjj): re-enable\n- raise SkipTest(\"temporarily skipping test while debugging others\")\n-\ndevice_count = xla_bridge.device_count()\nif device_count < 2:\nraise SkipTest(\"test requires at least two devices\")\n@@ -1237,6 +1237,36 @@ class PmapTest(jtu.JaxTestCase):\nout = pmap(lambda x: jax.lax.pmean(x, 'i'), 'i')(x)\nself.assertEqual(list(out), [1])\n+class VmapOfPmapTest(jtu.JaxTestCase):\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": f\"{shapes}_{vmap_bdims}_{pmap_bdims}\",\n+ \"shapes\": shapes, \"vmap_bdims\": vmap_bdims, \"pmap_bdims\": pmap_bdims}\n+ for shape_group in compatible_shapes\n+ for num_args in range(1, 4)\n+ for shapes in it.combinations_with_replacement(shape_group, num_args)\n+ for vmap_bdims in all_bdims(*shapes)\n+ for pmap_bdims in it.product([0, None], repeat=num_args)\n+ if not all(bd is None for bd in pmap_bdims)\n+ ))\n+ def testVmapOfPmap(self, shapes, vmap_bdims, pmap_bdims):\n+ vmapped_size = 3\n+ pmapped_size = xla_bridge.device_count()\n+\n+ rng = jtu.rand_default(self.rng())\n+\n+ def fun(*args):\n+ return sum(args)\n+\n+ final_shapes = map(partial(add_bdim, vmapped_size), vmap_bdims,\n+ map(partial(add_bdim, pmapped_size), pmap_bdims, shapes))\n+\n+ args = [rng(shape, jnp.float32) for shape in final_shapes]\n+ args_slice = args_slicer(args, vmap_bdims)\n+ ans = vmap(pmap(fun, in_axes=pmap_bdims), vmap_bdims)(*args)\n+ expected = np.stack([fun(*args_slice(i)) for i in range(vmapped_size)])\n+ self.assertAllClose(ans, expected)\n+\nclass PmapWithDevicesTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | add systematic tests for vmap-of-pmap
fixes #3440
Also re-applies the fix in #3439 (i.e it rolls-back the rollback PR #3448) because we're now confident it's correct (and some internal tests are buggy). |
260,700 | 11.05.2020 23:44:32 | 14,400 | 3cf6b1de542bb2b8770af99f236af698eae3db96 | add erf inv rule
erf_inv rule not working
works up to order 2
erf inv rule
use np for now
actually use np for now | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -249,6 +249,49 @@ def def_comp(prim, comp):\ndef_comp(lax.erfc_p, lambda x: 1 - lax.erf(x))\n+\n+def _erf_inv_rule(primals_in, series_in):\n+ x, = primals_in\n+ series, = series_in\n+\n+ u = [x] + series\n+ primal_out = lax.erf_inv(x)\n+ v = [primal_out] + [None] * len(series)\n+\n+ # derivative on co-domain for caching purposes\n+ deriv_const = np.sqrt(np.pi) / 2.\n+ deriv_y = lambda y: lax.mul(deriv_const, lax.exp(lax.square(y)))\n+\n+ # manually propagate through deriv_y since we don't have lazy evaluation of sensitivities\n+\n+ c = [deriv_y(primal_out)] + [None] * (len(series) - 1)\n+ tmp_sq = [lax.square(v[0])] + [None] * (len(series) - 1)\n+ tmp_exp = [lax.exp(tmp_sq[0])] + [None] * (len(series) - 1)\n+ for k in range(1, len(series)):\n+ # we know c[:k], we compute c[k]\n+\n+ # propagate c to get v\n+ v[k] = fact(k-1) * sum(_scale(k, j) * c[k-j] * u[j] for j in range(1, k + 1))\n+\n+ # propagate v to get next c\n+\n+ # square\n+ tmp_sq[k] = fact(k) * sum(_scale2(k, j) * v[k-j] * v[j] for j in range(k + 1))\n+\n+ # exp\n+ tmp_exp[k] = fact(k-1) * sum(_scale(k, j) * tmp_exp[k-j] * tmp_sq[j] for j in range(1, k + 1))\n+\n+ # const\n+ c[k] = deriv_const * tmp_exp[k]\n+\n+ # we can't, and don't need, to compute c[k+1], just need to get the last v[k]\n+ k = len(series)\n+ v[k] = fact(k-1) * sum(_scale(k, j) * c[k-j] * u[j] for j in range(1, k + 1))\n+\n+ primal_out, *series_out = v\n+ return primal_out, series_out\n+jet_rules[lax.erf_inv_p] = _erf_inv_rule\n+\n### More complicated rules\ndef fact(n):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/jet_test.py",
"new_path": "tests/jet_test.py",
"diff": "@@ -226,6 +226,8 @@ class JetTest(jtu.JaxTestCase):\ndef test_erf(self): self.unary_check(lax.erf)\n@jtu.skip_on_devices(\"tpu\")\ndef test_erfc(self): self.unary_check(lax.erfc)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_erf_inv(self): self.unary_check(lax.erf_inv, lims=[-1, 1])\n@jtu.skip_on_devices(\"tpu\")\ndef test_div(self): self.binary_check(lambda x, y: x / y, lims=[0.8, 4.0])\n"
}
] | Python | Apache License 2.0 | google/jax | add erf inv rule
erf_inv rule not working
works up to order 2
erf inv rule
use np for now
actually use np for now |
260,700 | 15.06.2020 17:23:57 | 14,400 | f463598f19549cd37386e8d7e7fe9036f52d6f02 | add int pow rule | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -298,10 +298,18 @@ jet_rules[lax.pow_p] = _pow_taylor\ndef _integer_pow_taylor(primals_in, series_in, *, y):\nif y == 2:\n- fn = lambda x: x * x\n- else:\n- fn = lambda x: lax.pow(x, np.array(y, dtype=x.dtype))\n- return jet(fn, primals_in, series_in)\n+ return jet(lambda x: x * x, primals_in, series_in)\n+ x, = primals_in\n+ series, = series_in\n+ u = [x] + series\n+ v = [lax.integer_pow(x, y)] + [None] * len(series)\n+ for k in range(1, len(v)):\n+ vu = sum(_scale(k, j) * v[k-j] * u[j] for j in range(1, k + 1))\n+ uv = sum(_scale(k, j) * u[k-j] * v[j] for j in range(1, k))\n+ v[k] = np.where(x == 0, 0, fact(k-1) * (y * vu - uv) / x)\n+ primal_out, *series_out = v\n+\n+ return primal_out, series_out\njet_rules[lax.integer_pow_p] = _integer_pow_taylor\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/jet_test.py",
"new_path": "tests/jet_test.py",
"diff": "@@ -163,6 +163,12 @@ class JetTest(jtu.JaxTestCase):\nself.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_int_pow(self):\n+ for p in range(2, 6):\n+ self.unary_check(lambda x: x ** p, lims=[-2, 2])\n+ self.unary_check(lambda x: x ** 10, lims=[0, 0])\n+\n@jtu.skip_on_devices(\"tpu\")\ndef test_exp(self): self.unary_check(jnp.exp)\n"
}
] | Python | Apache License 2.0 | google/jax | add int pow rule |
260,335 | 12.06.2020 16:10:45 | 25,200 | d4c6cb62abce5b7b5a28a4297ccda27d0a8405d8 | print warning when doing jit-of-pmap | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -169,8 +169,6 @@ def jit(fun: Callable, static_argnums: Union[int, Iterable[int]] = (),\nname=flat_fun.__name__, donated_invars=donated_invars)\nreturn tree_unflatten(out_tree(), out)\n- jitted_name = \"jit({}, static_argnums={})\"\n- f_jitted.__name__ = jitted_name.format(f_jitted.__name__, static_argnums)\nreturn f_jitted\n@contextmanager\n@@ -1167,8 +1165,6 @@ def pmap(fun: Callable, axis_name: Optional[AxisName] = None, *, in_axes=0,\ndonated_invars=tuple(donated_invars))\nreturn tree_unflatten(out_tree(), out)\n- namestr = \"pmap({}, axis_name={})\".format\n- f_pmapped.__name__ = namestr(f_pmapped.__name__, axis_name)\nreturn f_pmapped\nclass _TempAxisName:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -249,6 +249,7 @@ def xla_primitive_callable(prim, *arg_specs: Tuple[core.AbstractValue,\nnreps = initial_style_primitive_replicas(params)\nelse:\nnreps = 1\n+\nif nreps > xb.device_count(backend):\nraise ValueError(\nf\"compiling a primitive computation `{prim}` that requires {nreps} \"\n@@ -609,6 +610,14 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\nlog_priority = logging.WARNING if FLAGS.jax_log_compiles else logging.DEBUG\nlogging.log(log_priority, \"Compiling %s for args %s.\", fun.__name__, abstract_args)\n+ if nreps > 1:\n+ warn(f\"The jitted function {fun.__name__} includes a pmap. Using \"\n+ \"jit-of-pmap can lead to inefficient data movement, as the outer jit \"\n+ \"does not preserve sharded data representations and instead collects \"\n+ \"input and output arrays onto a single device. \"\n+ \"Consider removing the outer jit unless you know what you're doing. \"\n+ \"See https://github.com/google/jax/issues/2926.\")\n+\nif nreps > xb.device_count(backend):\nraise ValueError(\nf\"compiling computation that requires {nreps} replicas, but only \"\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -19,6 +19,7 @@ import itertools as it\nimport os\nfrom random import shuffle\nfrom unittest import SkipTest\n+import warnings\nimport numpy as np\nfrom absl.testing import absltest\n@@ -1237,6 +1238,23 @@ class PmapTest(jtu.JaxTestCase):\nout = pmap(lambda x: jax.lax.pmean(x, 'i'), 'i')(x)\nself.assertEqual(list(out), [1])\n+ def testJitOfPmapWarningMessage(self):\n+ device_count = xla_bridge.device_count()\n+\n+ if device_count == 1:\n+ raise SkipTest(\"test requires at least two devices\")\n+\n+ def foo(x): return x\n+\n+ with warnings.catch_warnings(record=True) as w:\n+ warnings.simplefilter(\"always\")\n+ jit(pmap(foo))(jnp.arange(device_count))\n+\n+ self.assertGreaterEqual(len(w), 1)\n+ self.assertIn(\"The jitted function foo includes a pmap\",\n+ str(w[-1].message))\n+\n+\nclass VmapOfPmapTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n"
}
] | Python | Apache License 2.0 | google/jax | print warning when doing jit-of-pmap |
260,335 | 16.06.2020 11:46:37 | 25,200 | 005958e13ec0d30cd45192673e761e886622db6e | added reviewer suggestion | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/invertible_ad.py",
"new_path": "jax/interpreters/invertible_ad.py",
"diff": "@@ -54,7 +54,7 @@ def _invertible_call_make_output_tracers(trace, in_tracers, out_tracers, params)\nnew_in_tracers = (*in_tracers, *out_consts)\n# Append dummy outputs that correspond to known outputs left in the call_jaxpr\n- dummy_outputs = [JaxprTracer(trace, t.pval, core.unit) for t in out_tracers_known]\n+ dummy_outputs = [trace.new_const(t.pval.get_known()) for t in out_tracers_known]\nnew_out_tracers = (*dummy_outputs, *out_tracers_unknown)\neqn = new_eqn_recipe(new_in_tracers, new_out_tracers, invertible_call_p,\n"
}
] | Python | Apache License 2.0 | google/jax | added reviewer suggestion |
260,335 | 16.06.2020 15:46:51 | 25,200 | 20f4ec649c9cccdac6822302a4c4695192fa9473 | fix a bug from | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -704,6 +704,7 @@ def _remat_partial_eval(process_out, trace, _, f, tracers, params):\n# Using the instantiated tracers, run call_bind like JaxprTrace.process_call.\nin_pvals = [t.pval for t in instantiated_tracers]\n+ with core.initial_style_staging():\njaxpr, eval_out_pvals, consts, env_tracers = trace.partial_eval(\nf, in_pvals, partial(remat_call_p.bind, **params))\n"
}
] | Python | Apache License 2.0 | google/jax | fix a bug from #3459 (#3466) |
260,700 | 16.06.2020 22:48:25 | 14,400 | 575216e094ac55866320ae09dff4b05ef47fb7ea | add jet primitives, refactor tests | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -18,6 +18,7 @@ from functools import partial\nimport numpy as np\nimport jax\n+import jax.numpy as jnp\nfrom jax import core\nfrom jax.util import unzip2\nfrom jax import ad_util\n@@ -180,6 +181,7 @@ defzero(lax.gt_p)\ndefzero(lax.ge_p)\ndefzero(lax.eq_p)\ndefzero(lax.ne_p)\n+defzero(lax.not_p)\ndefzero(lax.and_p)\ndefzero(lax.or_p)\ndefzero(lax.xor_p)\n@@ -188,6 +190,11 @@ defzero(lax.ceil_p)\ndefzero(lax.round_p)\ndefzero(lax.sign_p)\ndefzero(ad_util.stop_gradient_p)\n+defzero(lax.is_finite_p)\n+defzero(lax.shift_left_p)\n+defzero(lax.shift_right_arithmetic_p)\n+defzero(lax.shift_right_logical_p)\n+defzero(lax.bitcast_convert_type_p)\ndef deflinear(prim):\n@@ -201,6 +208,8 @@ def linear_prop(prim, primals_in, series_in, **params):\ndeflinear(lax.neg_p)\ndeflinear(lax.real_p)\ndeflinear(lax.complex_p)\n+deflinear(lax.conj_p)\n+deflinear(lax.imag_p)\ndeflinear(lax.add_p)\ndeflinear(lax.sub_p)\ndeflinear(lax.convert_element_type_p)\n@@ -218,12 +227,14 @@ deflinear(lax.tie_in_p)\ndeflinear(lax_fft.fft_p)\ndeflinear(xla.device_put_p)\n+\ndef def_deriv(prim, deriv):\n\"\"\"\nDefine the jet rule for a primitive in terms of its first derivative.\n\"\"\"\njet_rules[prim] = partial(deriv_prop, prim, deriv)\n+\ndef deriv_prop(prim, deriv, primals_in, series_in):\nx, = primals_in\nseries, = series_in\n@@ -240,6 +251,7 @@ def deriv_prop(prim, deriv, primals_in, series_in):\ndef_deriv(lax.erf_p, lambda x: lax.mul(lax._const(x, 2. / np.sqrt(np.pi)), lax.exp(lax.neg(lax.square(x)))))\n+\ndef def_comp(prim, comp):\n\"\"\"\nDefine the jet rule for a primitive in terms of a composition of simpler primitives.\n@@ -247,7 +259,16 @@ def def_comp(prim, comp):\njet_rules[prim] = partial(jet, comp)\n+def_comp(lax.expm1_p, lambda x: lax.exp(x) - 1)\n+def_comp(lax.log1p_p, lambda x: lax.log(1 + x))\n+def_comp(lax.sqrt_p, lambda x: x ** 0.5)\n+def_comp(lax.rsqrt_p, lambda x: x ** -0.5)\n+def_comp(lax.asinh_p, lambda x: lax.log(x + lax.sqrt(lax.square(x) + 1)))\n+def_comp(lax.acosh_p, lambda x: lax.log(x + lax.sqrt(lax.square(x) - 1)))\n+def_comp(lax.atanh_p, lambda x: 0.5 * lax.log(lax.div(1 + x, 1 - x)))\ndef_comp(lax.erfc_p, lambda x: 1 - lax.erf(x))\n+def_comp(lax.rem_p, lambda x, y: x - y * lax.floor(x / y))\n+def_comp(lax.clamp_p, lambda a, x, b: lax.min(lax.max(a, x), b))\ndef _erf_inv_rule(primals_in, series_in):\n@@ -314,17 +335,6 @@ def _exp_taylor(primals_in, series_in):\nreturn primal_out, series_out\njet_rules[lax.exp_p] = _exp_taylor\n-def _expm1_taylor(primals_in, series_in):\n- x, = primals_in\n- series, = series_in\n- u = [x] + series\n- v = [lax.exp(x)] + [None] * len(series)\n- for k in range(1,len(v)):\n- v[k] = fact(k-1) * sum([_scale(k, j)* v[k-j] * u[j] for j in range(1, k+1)])\n- primal_out, *series_out = v\n- return lax.expm1(x), series_out\n-jet_rules[lax.expm1_p] = _expm1_taylor\n-\ndef _pow_taylor(primals_in, series_in):\nu_, r_ = primals_in\n@@ -340,7 +350,11 @@ def _pow_taylor(primals_in, series_in):\njet_rules[lax.pow_p] = _pow_taylor\ndef _integer_pow_taylor(primals_in, series_in, *, y):\n- if y == 2:\n+ if y == 0:\n+ return jet(jnp.ones_like, primals_in, series_in)\n+ elif y == 1:\n+ return jet(lambda x: x, primals_in, series_in)\n+ elif y == 2:\nreturn jet(lambda x: x * x, primals_in, series_in)\nx, = primals_in\nseries, = series_in\n@@ -391,26 +405,6 @@ def _log_taylor(primals_in, series_in):\nreturn primal_out, series_out\njet_rules[lax.log_p] = _log_taylor\n-def _sqrt_taylor(primals_in, series_in):\n- return jet(lambda x: x ** 0.5, primals_in, series_in)\n-jet_rules[lax.sqrt_p] = _sqrt_taylor\n-\n-def _rsqrt_taylor(primals_in, series_in):\n- return jet(lambda x: x ** -0.5, primals_in, series_in)\n-jet_rules[lax.rsqrt_p] = _rsqrt_taylor\n-\n-def _asinh_taylor(primals_in, series_in):\n- return jet(lambda x: lax.log(x + lax.sqrt(lax.square(x) + 1)), primals_in, series_in)\n-jet_rules[lax.asinh_p] = _asinh_taylor\n-\n-def _acosh_taylor(primals_in, series_in):\n- return jet(lambda x: lax.log(x + lax.sqrt(lax.square(x) - 1)), primals_in, series_in)\n-jet_rules[lax.acosh_p] = _acosh_taylor\n-\n-def _atanh_taylor(primals_in, series_in):\n- return jet(lambda x: 0.5 * lax.log(lax.div(1 + x, 1 - x)), primals_in, series_in)\n-jet_rules[lax.atanh_p] = _atanh_taylor\n-\ndef _atan2_taylor(primals_in, series_in):\nx, y = primals_in\nprimal_out = lax.atan2(x, y)\n@@ -426,19 +420,7 @@ def _atan2_taylor(primals_in, series_in):\nreturn primal_out, series_out\njet_rules[lax.atan2_p] = _atan2_taylor\n-def _log1p_taylor(primals_in, series_in):\n- x, = primals_in\n- series, = series_in\n- u = [x + 1] + series\n- v = [lax.log(x + 1)] + [None] * len(series)\n- for k in range(1, len(v)):\n- conv = sum([_scale(k, j) * v[j] * u[k-j] for j in range(1, k)])\n- v[k] = (u[k] - fact(k - 1) * conv) / u[0]\n- primal_out, *series_out = v\n- return primal_out, series_out\n-jet_rules[lax.log1p_p] = _log1p_taylor\n-\n-def _div_taylor_rule(primals_in, series_in, **params):\n+def _div_taylor_rule(primals_in, series_in):\nx, y = primals_in\nx_terms, y_terms = series_in\nu = [x] + x_terms\n@@ -531,3 +513,37 @@ def _select_taylor_rule(primal_in, series_in, **params):\nseries_out = [sel(*terms_in, **params) for terms_in in zip(*series_in)]\nreturn primal_out, series_out\njet_rules[lax.select_p] = _select_taylor_rule\n+\n+\n+def _lax_max_taylor_rule(primal_in, series_in):\n+ x, y = primal_in\n+\n+ xgy = x > y # greater than mask\n+ xey = x == y # equal to mask\n+ primal_out = lax.select(xgy, x, y)\n+\n+ def select_max_and_avg_eq(x_i, y_i):\n+ \"\"\"Select x where x>y or average when x==y\"\"\"\n+ max_i = lax.select(xgy, x_i, y_i)\n+ max_i = lax.select(xey, (x_i + y_i)/2, max_i)\n+ return max_i\n+\n+ series_out = [select_max_and_avg_eq(*terms_in) for terms_in in zip(*series_in)]\n+ return primal_out, series_out\n+jet_rules[lax.max_p] = _lax_max_taylor_rule\n+\n+def _lax_min_taylor_rule(primal_in, series_in):\n+ x, y = primal_in\n+ xgy = x < y # less than mask\n+ xey = x == y # equal to mask\n+ primal_out = lax.select(xgy, x, y)\n+\n+ def select_min_and_avg_eq(x_i, y_i):\n+ \"\"\"Select x where x>y or average when x==y\"\"\"\n+ min_i = lax.select(xgy, x_i, y_i)\n+ min_i = lax.select(xey, (x_i + y_i)/2, min_i)\n+ return min_i\n+\n+ series_out = [select_min_and_avg_eq(*terms_in) for terms_in in zip(*series_in)]\n+ return primal_out, series_out\n+jet_rules[lax.min_p] = _lax_min_taylor_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2116,6 +2116,7 @@ ad.defjvp(integer_pow_p, _integer_pow_jvp)\n_replace_zero = lambda x: select(eq(x, _const(x, 0)), _ones(x), x)\nnot_p = standard_unop(_bool_or_int, 'not')\n+ad.defjvp_zero(not_p)\nand_p = standard_naryop([_bool_or_int, _bool_or_int], 'and')\nad.defjvp_zero(and_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/jet_test.py",
"new_path": "tests/jet_test.py",
"diff": "@@ -36,7 +36,7 @@ def jvp_taylor(fun, primals, series):\ndef composition(eps):\ntaylor_terms = [sum([eps ** (i+1) * terms[i] / fact(i + 1)\nfor i in range(len(terms))]) for terms in series]\n- nudged_args = [x + t for x, t in zip(primals, taylor_terms)]\n+ nudged_args = [(x + t).astype(x.dtype) for x, t in zip(primals, taylor_terms)]\nreturn fun(*nudged_args)\nprimal_out = fun(*primals)\nterms_out = [repeated(jacfwd, i+1)(composition)(0.) for i in range(order)]\n@@ -122,24 +122,36 @@ class JetTest(jtu.JaxTestCase):\nself.check_jet(f, primals, series_in, check_dtypes=False)\n- def unary_check(self, fun, lims=[-2, 2], order=3):\n+ def unary_check(self, fun, lims=[-2, 2], order=3, dtype=None):\ndims = 2, 3\nrng = np.random.RandomState(0)\n+ if dtype is None:\nprimal_in = transform(lims, rng.rand(*dims))\nterms_in = [rng.randn(*dims) for _ in range(order)]\n+ else:\n+ rng = jtu.rand_uniform(rng, *lims)\n+ primal_in = rng(dims, dtype)\n+ terms_in = [rng(dims, dtype) for _ in range(order)]\nself.check_jet(fun, (primal_in,), (terms_in,), atol=1e-4, rtol=1e-4)\n- def binary_check(self, fun, lims=[-2, 2], order=3, finite=True):\n+ def binary_check(self, fun, lims=[-2, 2], order=3, finite=True, dtype=None):\ndims = 2, 3\nrng = np.random.RandomState(0)\nif isinstance(lims, tuple):\nx_lims, y_lims = lims\nelse:\nx_lims, y_lims = lims, lims\n+ if dtype is None:\nprimal_in = (transform(x_lims, rng.rand(*dims)),\ntransform(y_lims, rng.rand(*dims)))\nseries_in = ([rng.randn(*dims) for _ in range(order)],\n[rng.randn(*dims) for _ in range(order)])\n+ else:\n+ rng = jtu.rand_uniform(rng, *lims)\n+ primal_in = (rng(dims, dtype),\n+ rng(dims, dtype))\n+ series_in = ([rng(dims, dtype) for _ in range(order)],\n+ [rng(dims, dtype) for _ in range(order)])\nif finite:\nself.check_jet(fun, primal_in, series_in, atol=1e-4, rtol=1e-4)\nelse:\n@@ -165,7 +177,7 @@ class JetTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_int_pow(self):\n- for p in range(2, 6):\n+ for p in range(6):\nself.unary_check(lambda x: x ** p, lims=[-2, 2])\nself.unary_check(lambda x: x ** 10, lims=[0, 0])\n@@ -179,9 +191,19 @@ class JetTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_ceil(self): self.unary_check(jnp.ceil)\n@jtu.skip_on_devices(\"tpu\")\n- def test_round(self): self.unary_check(jnp.round)\n+ def test_round(self): self.unary_check(lax.round)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_sign(self): self.unary_check(lax.sign)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_real(self): self.unary_check(lax.real, dtype=np.complex64)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_conj(self): self.unary_check(lax.conj, dtype=np.complex64)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_imag(self): self.unary_check(lax.imag, dtype=np.complex64)\n@jtu.skip_on_devices(\"tpu\")\n- def test_sign(self): self.unary_check(jnp.sign)\n+ def test_not(self): self.unary_check(lax.bitwise_not, dtype=np.bool_)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_is_finite(self): self.unary_check(lax.is_finite)\n@jtu.skip_on_devices(\"tpu\")\ndef test_log(self): self.unary_check(jnp.log, lims=[0.8, 4.0])\n@jtu.skip_on_devices(\"tpu\")\n@@ -238,6 +260,10 @@ class JetTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_div(self): self.binary_check(lambda x, y: x / y, lims=[0.8, 4.0])\n@jtu.skip_on_devices(\"tpu\")\n+ def test_rem(self): self.binary_check(lax.rem, lims=[0.8, 4.0])\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_complex(self): self.binary_check(lax.complex)\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_sub(self): self.binary_check(lambda x, y: x - y)\n@jtu.skip_on_devices(\"tpu\")\ndef test_add(self): self.binary_check(lambda x, y: x + y)\n@@ -256,17 +282,42 @@ class JetTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_ne(self): self.binary_check(lambda x, y: x != y)\n@jtu.skip_on_devices(\"tpu\")\n- def test_and(self): self.binary_check(lambda x, y: jnp.logical_and(x, y))\n+ def test_max(self): self.binary_check(lax.max)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_min(self): self.binary_check(lax.min)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_and(self): self.binary_check(lax.bitwise_and, dtype=np.bool_)\n@jtu.skip_on_devices(\"tpu\")\n- def test_or(self): self.binary_check(lambda x, y: jnp.logical_or(x, y))\n+ def test_or(self): self.binary_check(lax.bitwise_or, dtype=np.bool_)\n@jtu.skip_on_devices(\"tpu\")\n- def test_xor(self): self.binary_check(lambda x, y: jnp.logical_xor(x, y))\n+ def test_xor(self): self.binary_check(jnp.bitwise_xor, dtype=np.bool_)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_shift_left(self): self.binary_check(lax.shift_left, dtype=np.int32)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_shift_right_a(self): self.binary_check(lax.shift_right_arithmetic, dtype=np.int32)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_shift_right_l(self): self.binary_check(lax.shift_right_logical, dtype=np.int32)\n@jtu.skip_on_devices(\"tpu\")\n@jtu.ignore_warning(message=\"overflow encountered in power\")\ndef test_pow(self): self.binary_check(lambda x, y: x ** y, lims=([0.2, 500], [-500, 500]), finite=False)\n@jtu.skip_on_devices(\"tpu\")\ndef test_atan2(self): self.binary_check(lax.atan2, lims=[-40, 40])\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_clamp(self):\n+ lims = [-2, 2]\n+ order = 3\n+ dims = 2, 3\n+ rng = np.random.RandomState(0)\n+ primal_in = (transform(lims, rng.rand(*dims)),\n+ transform(lims, rng.rand(*dims)),\n+ transform(lims, rng.rand(*dims)))\n+ series_in = ([rng.randn(*dims) for _ in range(order)],\n+ [rng.randn(*dims) for _ in range(order)],\n+ [rng.randn(*dims) for _ in range(order)])\n+\n+ self.check_jet(lax.clamp, primal_in, series_in, atol=1e-4, rtol=1e-4)\n+\ndef test_process_call(self):\ndef f(x):\nreturn jit(lambda x: x * x)(x)\n"
}
] | Python | Apache License 2.0 | google/jax | add jet primitives, refactor tests (#3468)
Co-authored-by: Jesse Bettencourt <jessebett@cs.toronto.edu> |
260,411 | 17.06.2020 11:57:21 | -10,800 | 4f21b9351cd6f4be6d192ddda45c260db38b4380 | [jax2tf] Added special case for tf.pad.
Fixed lax_reference.pad to handle lax.pad with negative edge padding. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -677,6 +677,10 @@ def _pad_shape(operand, padding_value, padding_config):\ndef _pad(operand, padding_value, padding_config):\nlow, high, interior = util.unzip3(padding_config)\n+ if all(lo >= 0 and hi >= 0 and i == 0 for lo, hi, i in padding_config):\n+ return tf.pad(operand, util.safe_zip(low, high),\n+ mode=\"CONSTANT\", constant_values=padding_value)\n+ # TODO(necula): implement shape inference for XlaPad\nout_shape = _pad_shape(operand, padding_value, padding_config)\nout = tfxla.pad(operand, padding_value, low, high, interior)\nout.set_shape(out_shape)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -150,7 +150,7 @@ lax_pad = jtu.cases_from_list(\nfor dtype in default_dtypes\nfor pads in [\n[(0, 0, 0), (0, 0, 0)], # no padding\n- [(1, 1, 0), (2, 2, 0)], # edge padding\n+ [(1, 1, 0), (2, 2, 0)], # only positive edge padding\n[(1, 2, 1), (0, 1, 0)], # edge padding and interior padding\n[(0, 0, 0), (-1, -1, 0)], # negative padding\n[(0, 0, 0), (-2, -2, 4)], # add big dilation then remove from edges\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -154,13 +154,14 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(primitive_harness.lax_pad)\ndef test_pad(self, harness: primitive_harness.Harness):\n+ # TODO: figure out the bfloat16 story\nif harness.params[\"dtype\"] is dtypes.bfloat16:\nraise unittest.SkipTest(\"bfloat16 not implemented\")\n- # TODO: implement (or decide not to) pads with negative edge padding\n+ # TODO: fix pad with negative padding in XLA (fixed on 06/16/2020)\nif any([lo < 0 or hi < 0 for lo, hi, mid in harness.params[\"pads\"]]):\nraise unittest.SkipTest(\"pad with negative pad not supported\")\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n- with_function=True)\n+ with_function=False)\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_{f_jax.__name__}\",\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax_reference.py",
"new_path": "jax/lax_reference.py",
"diff": "@@ -232,16 +232,19 @@ def reshape(operand, new_sizes, dimensions=None):\nreturn np.reshape(np.transpose(operand, dimensions), new_sizes)\ndef pad(operand, padding_value, padding_config):\n+ # https://www.tensorflow.org/xla/operation_semantics#pad\nlo, hi, interior = zip(*padding_config)\n- outshape = np.add(np.add(np.add(lo, hi), operand.shape),\n+ # Handle first the positive edge padding and interior\n+ lo_pos, hi_pos = np.clip(lo, 0, None), np.clip(hi, 0, None)\n+ outshape = np.add(np.add(np.add(lo_pos, hi_pos), operand.shape),\nnp.multiply(interior, np.subtract(operand.shape, 1)))\nout = np.full(outshape, padding_value, operand.dtype)\nlhs_slices = tuple(_slice(l if l > 0 else 0, -h if h > 0 else None, step)\n- for l, h, step in zip(lo, hi, np.add(1, interior)))\n- rhs_slices = tuple(_slice(l if l < 0 else 0, -h if h < 0 else None)\n+ for l, h, step in zip(lo_pos, hi_pos, np.add(1, interior)))\n+ out[lhs_slices] = operand\n+ trim_slices = tuple(_slice(-l if l < 0 else 0, h if h < 0 else None)\nfor l, h in zip(lo, hi))\n- out[lhs_slices] = operand[rhs_slices]\n- return out\n+ return out[trim_slices]\ndef rev(operand, dimensions):\ndimensions = frozenset(dimensions)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -976,7 +976,14 @@ class LaxTest(jtu.JaxTestCase):\n\"shape\": shape, \"dtype\": dtype, \"pads\": pads, \"rng_factory\": jtu.rand_small}\nfor shape in [(2, 3)]\nfor dtype in default_dtypes\n- for pads in [[(1, 2, 1), (0, 1, 0)]]))\n+ for pads in [\n+ [(0, 0, 0), (0, 0, 0)], # no padding\n+ [(1, 1, 0), (2, 2, 0)], # only positive edge padding\n+ [(1, 2, 1), (0, 1, 0)], # edge padding and interior padding\n+ [(0, 0, 0), (-1, -1, 0)], # negative padding\n+ [(0, 0, 0), (-2, -2, 4)], # add big dilation then remove from edges\n+ [(0, 0, 0), (-2, -3, 1)], # remove everything in one dimension\n+ ]))\ndef testPadAgainstNumpy(self, shape, dtype, pads, rng_factory):\nrng = rng_factory(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Added special case for tf.pad. (#3462)
Fixed lax_reference.pad to handle lax.pad with negative edge padding. |
260,519 | 18.06.2020 02:43:50 | -36,000 | 5ee936fdcf44711a2fcd8b1f448a6134c14294a4 | Add polyder numpy function | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -212,6 +212,7 @@ Not every function in NumPy is implemented; contributions are welcome!\npad\npercentile\npolyadd\n+ polyder\npolymul\npolysub\npolyval\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -48,7 +48,7 @@ from .lax_numpy import (\nnanmax, nanmean, nanmin, nanprod, nanstd, nansum, nanvar, ndarray, ndim,\nnegative, newaxis, nextafter, nonzero, not_equal, number, numpy_version,\nobject_, ones, ones_like, operator_name, outer, packbits, pad, percentile,\n- pi, polyadd, polymul, polysub, polyval, positive, power, prod, product, promote_types, ptp, quantile,\n+ pi, polyadd, polyder, polymul, polysub, polyval, positive, power, prod, product, promote_types, ptp, quantile,\nrad2deg, radians, ravel, real, reciprocal, remainder, repeat, reshape,\nresult_type, right_shift, rint, roll, rollaxis, rot90, round, row_stack,\nsave, savez, searchsorted, select, set_printoptions, shape, sign, signbit,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2655,6 +2655,18 @@ def polyadd(a, b):\nreturn b.at[-a.shape[0]:].add(a)\n+@_wraps(np.polyder)\n+def polyder(a, m=1):\n+ a = asarray(a)\n+ if m < 0:\n+ raise ValueError(\"Order of derivative must be positive\")\n+ if m == 0:\n+ return a\n+ if m % 1:\n+ raise ValueError(\"m must be an integer\")\n+ coeff = (arange(len(a), m, -1) - 1 - arange(m)[:, newaxis]).prod(0)\n+ return a[:-m] * coeff\n+\ndef _trim_zeros(a):\nfor i, v in enumerate(a):\nif v != 0:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1152,6 +1152,23 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_order={}\".format(\n+ jtu.format_shape_dtype_string(a_shape, dtype),\n+ order),\n+ \"dtype\": dtype, \"a_shape\": a_shape, \"order\" : order}\n+ for dtype in default_dtypes\n+ for a_shape in one_dim_array_shapes\n+ for order in range(5)))\n+ def testPolyDer(self, a_shape, order, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ np_fun = lambda arg1: np.polyder(arg1, m=order)\n+ jnp_fun = lambda arg1: jnp.polyder(arg1, m=order)\n+ args_maker = lambda: [rng(a_shape, dtype)]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)\n+ self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_axis={}\".format(\njtu.format_shape_dtype_string(shape, dtype), axis),\n"
}
] | Python | Apache License 2.0 | google/jax | Add polyder numpy function (#3403) |
260,335 | 17.06.2020 10:05:28 | 25,200 | 5344ec5364bbe6b08bfe4f9e4c0f581b807f0cfe | use original numpy for shape calculations
cf. | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2253,7 +2253,7 @@ def arange(start, stop=None, step=None, dtype=None):\nlax._check_user_dtype_supported(dtype, \"arange\")\nif stop is None and step is None:\ndtype = dtype or _dtype(start)\n- return lax.iota(dtype, ceil(start)) # avoids materializing\n+ return lax.iota(dtype, np.ceil(start)) # avoids materializing\nelse:\nreturn array(np.arange(start, stop=stop, step=step, dtype=dtype))\n"
}
] | Python | Apache License 2.0 | google/jax | use original numpy for shape calculations (#3474)
cf. #3453 |
260,335 | 22.06.2020 08:12:41 | 25,200 | 3fff83790742a1b0a468032ecff6f8809fde57d9 | pin numpy version in setup.py to avoid warnings | [
{
"change_type": "MODIFY",
"old_path": "setup.py",
"new_path": "setup.py",
"diff": "@@ -29,7 +29,7 @@ setup(\npackages=find_packages(exclude=[\"examples\"]),\npython_requires='>=3.6',\ninstall_requires=[\n- 'numpy>=1.12', 'absl-py', 'opt_einsum'\n+ 'numpy >=1.12, <1.19', 'absl-py', 'opt_einsum'\n],\nurl='https://github.com/google/jax',\nlicense='Apache-2.0',\n"
}
] | Python | Apache License 2.0 | google/jax | pin numpy version in setup.py to avoid warnings (#3509) |
260,335 | 22.06.2020 10:27:44 | 25,200 | a81e732d3d5398ef5cd74eaf518b6cb2d58877db | fix jet typo: jnp not np | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -363,7 +363,7 @@ def _integer_pow_taylor(primals_in, series_in, *, y):\nfor k in range(1, len(v)):\nvu = sum(_scale(k, j) * v[k-j] * u[j] for j in range(1, k + 1))\nuv = sum(_scale(k, j) * u[k-j] * v[j] for j in range(1, k))\n- v[k] = np.where(x == 0, 0, fact(k-1) * (y * vu - uv) / x)\n+ v[k] = jnp.where(x == 0, 0, fact(k-1) * (y * vu - uv) / x)\nprimal_out, *series_out = v\nreturn primal_out, series_out\n"
}
] | Python | Apache License 2.0 | google/jax | fix jet typo: jnp not np (#3507) |
260,705 | 22.06.2020 16:31:08 | 10,800 | e5d4ca31a8b59fb93229d3629035007e5aa329cc | Fix typo understanding jaxprs page on readthedocs | [
{
"change_type": "MODIFY",
"old_path": "docs/jaxpr.rst",
"new_path": "docs/jaxpr.rst",
"diff": "@@ -169,7 +169,7 @@ before (with two input vars, one for each element of the input tuple)\nConstant Vars\n--------------\n-ConstVars arise when the computation ontains array constants, either\n+ConstVars arise when the computation contains array constants, either\nfrom the Python program, or from constant-folding. For example, the function\n``func6`` below\n"
}
] | Python | Apache License 2.0 | google/jax | Fix typo understanding jaxprs page on readthedocs (#3513) |
260,335 | 22.06.2020 17:50:33 | 25,200 | 2f7108f78ba4d7fd12a8ad6232685d0d10b28c01 | remove the lower_fun default multiple_results=True | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1853,7 +1853,7 @@ def custom_transforms(fun):\nfun_p.def_abstract_eval(fun_abstract_eval)\ndef fun_translation(c, *xla_args, **params):\n- return xla.lower_fun(fun_impl)(c, *xla_args, **params)\n+ return xla.lower_fun(fun_impl, multiple_results=True)(c, *xla_args, **params)\nxla.translations[fun_p] = fun_translation\nreturn CustomTransformsFunction(fun, fun_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -857,7 +857,7 @@ def _tuple_output(*args, **kwargs):\nyield (ans,)\n-def lower_fun(fun, multiple_results=True):\n+def lower_fun(fun, multiple_results):\n# This function can only be used to lower functions that take JAX array types\n# as arguments (and e.g. don't accept unit values), because it assumes it can\n# map from XLA types to JAX types. In general that mapping is not possible (as\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax_linalg.py",
"new_path": "jax/lax_linalg.py",
"diff": "@@ -645,7 +645,7 @@ lu_p = Primitive('lu')\nlu_p.multiple_results = True\nlu_p.def_impl(_lu_impl)\nlu_p.def_abstract_eval(_lu_abstract_eval)\n-xla.translations[lu_p] = xla.lower_fun(_lu_python)\n+xla.translations[lu_p] = xla.lower_fun(_lu_python, multiple_results=True)\nad.primitive_jvps[lu_p] = _lu_jvp_rule\nbatching.primitive_batchers[lu_p] = _lu_batching_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -216,9 +216,11 @@ threefry2x32_p.def_impl(partial(xla.apply_primitive, threefry2x32_p))\nthreefry2x32_p.def_abstract_eval(_threefry2x32_abstract_eval)\nbatching.defbroadcasting(threefry2x32_p)\nxla.translations[threefry2x32_p] = xla.lower_fun(\n- partial(_threefry2x32_lowering, use_rolled_loops=False))\n+ partial(_threefry2x32_lowering, use_rolled_loops=False),\n+ multiple_results=True)\nxla.backend_specific_translations['cpu'][threefry2x32_p] = xla.lower_fun(\n- partial(_threefry2x32_lowering, use_rolled_loops=True))\n+ partial(_threefry2x32_lowering, use_rolled_loops=True),\n+ multiple_results=True)\nif cuda_prng:\nxla.backend_specific_translations['gpu'][threefry2x32_p] = \\\n_threefry2x32_gpu_translation_rule\n"
}
] | Python | Apache License 2.0 | google/jax | remove the lower_fun default multiple_results=True (#3524) |
260,452 | 22.06.2020 22:43:25 | 14,400 | 046006e047543d5c24f75a930ab87ef56c247032 | Fix typo: np.bool -> np.bool_
Replaced np.bool (which is just bool) with np.bool_, which is numpy's
Boolean type. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -729,7 +729,7 @@ _CODE_TO_DTYPE = {\n5: np.dtype(np.uint16),\n6: np.dtype(np.uint32),\n7: np.dtype(np.uint64),\n- 8: np.dtype(np.bool),\n+ 8: np.dtype(np.bool_),\n9: np.dtype(np.float16),\n10: np.dtype(np.float32),\n11: np.dtype(np.float64),\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -286,7 +286,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ndef test_boolean_gather(self):\nvalues = np.array([[True, True], [False, True], [False, False]],\n- dtype=np.bool)\n+ dtype=np.bool_)\nindices = np.array([0, 1], dtype=np.int32)\nfor axis in [0, 1]:\nf_jax = jax.jit(lambda v, i: jnp.take(v, i, axis=axis)) # pylint: disable=cell-var-from-loop\n@@ -323,7 +323,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nf_jax=f_jax)\nfor f_jax in REDUCE))\ndef test_reduce_ops_with_boolean_input(self, f_jax):\n- values = [np.array([True, False, True], dtype=np.bool)]\n+ values = [np.array([True, False, True], dtype=np.bool_)]\nself.ConvertAndCompare(f_jax, values, with_function=True)\ndef test_gather_rank_change(self):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -628,7 +628,7 @@ def signbit(x):\n\"jax.numpy.signbit only supports 16, 32, and 64-bit types.\")\nx = lax.bitcast_convert_type(x, int_type)\n- return lax.convert_element_type(x >> (info.nexp + info.nmant), np.bool)\n+ return lax.convert_element_type(x >> (info.nexp + info.nmant), np.bool_)\n"
}
] | Python | Apache License 2.0 | google/jax | Fix typo: np.bool -> np.bool_ (#3525)
Replaced np.bool (which is just bool) with np.bool_, which is numpy's
Boolean type. |
260,335 | 22.06.2020 20:04:07 | 25,200 | 02494924f9554fb2b4317043319b3731a13fccdd | fix an issue with newer versions of pytype | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -838,7 +838,7 @@ def _reconstruct_pval(pval1: PartialVal, const2: core.Value):\nreturn pval1\nelse:\nif type(pv1) is ConcreteArray:\n- return PartialVal.known(pv1.val)\n+ return PartialVal.known(pv1.val) # pytype: disable=attribute-error\nelse:\nreturn PartialVal.known(const2)\n"
}
] | Python | Apache License 2.0 | google/jax | fix an issue with newer versions of pytype (#3526) |
260,597 | 23.06.2020 05:46:41 | -7,200 | 5ee6bc00340e07d1b4fd705bddc2b496cd21f25a | Remove unnecessary static_argnum in np.gradient | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1006,7 +1006,7 @@ def ediff1d(ary, to_end=None, to_begin=None):\nreturn result\n-@partial(jit, static_argnums=(1, 2))\n+@partial(jit, static_argnums=2)\ndef _gradient(a, varargs, axis):\ndef gradient_along_axis(a, h, axis):\nsliced = partial(lax.slice_in_dim, a, axis=axis)\n"
}
] | Python | Apache License 2.0 | google/jax | Remove unnecessary static_argnum in np.gradient (#3512) |
260,322 | 23.06.2020 14:25:53 | -3,600 | 490c8533c889127200a9d4a7ed283cfbacc96586 | Adds boolean support for bitwise not and unittests for boolean support on logical operations. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -496,6 +496,24 @@ tf_impl[lax.shift_right_logical_p] = _shift_right_logical\ntf_impl[lax.shift_left_p] = tf.bitwise.left_shift\n+def _not(x):\n+ \"\"\"Computes bitwise not with support for booleans.\n+\n+ Numpy and JAX support bitwise not for booleans by applying a logical not!\n+ This means that applying bitwise_not yields an unexected result:\n+ jnp.bitwise_not(jnp.array([True, False]))\n+ >> DeviceArray([False, True], dtype=bool)\n+\n+ if you assume that booleans are simply casted to integers.\n+ jnp.bitwise_not(jnp.array([True, False]).astype(np.int32)).astype(bool)\n+ >> DeviceArray([True, True], dtype=bool)\n+ \"\"\"\n+ if x.dtype == tf.bool:\n+ return tf.logical_not(x)\n+ else:\n+ return tf.bitwise.invert(x)\n+\n+tf_impl[lax.not_p] = _not\ndef bool_to_int8(f, argnums):\n\"\"\"Computes bool valued functions using int8.\"\"\"\n@@ -513,7 +531,6 @@ def bool_to_int8(f, argnums):\ntf_impl[lax.or_p] = bool_to_int8(tf.bitwise.bitwise_or, argnums=(0, 1))\ntf_impl[lax.and_p] = bool_to_int8(tf.bitwise.bitwise_and, argnums=(0, 1))\ntf_impl[lax.xor_p] = bool_to_int8(tf.bitwise.bitwise_xor, argnums=(0, 1))\n-tf_impl[lax.not_p] = bool_to_int8(tf.bitwise.invert, argnums=(0,))\ntf_impl[lax.eq_p] = wrap_binary_op(tf.math.equal)\ntf_impl[lax.ne_p] = wrap_binary_op(tf.math.not_equal)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -81,6 +81,10 @@ LAX_ELEMENTWISE_BINARY = (\nlax.sub,\n)\n+LAX_LOGICAL_ELEMENTWISE_UNARY = (\n+ lax.bitwise_not,\n+)\n+\nLAX_LOGICAL_ELEMENTWISE_BINARY = (\nlax.bitwise_and,\nlax.bitwise_or,\n@@ -222,6 +226,32 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nr_tf = f_tf(a, b)\nself.assertAllClose(r_jax[np.isfinite(r_jax)],\nr_tf[np.isfinite(r_tf)], atol=1e-4)\n+ # Checks support for bools.\n+ if f_jax in (lax.bitwise_and, lax.bitwise_or, lax.bitwise_xor):\n+ a = np.array([True, True, False, False])\n+ b = np.array([True, False, True, False])\n+ f_tf = tf.function(jax2tf.convert(f_jax))\n+ r_jax = f_jax(a, b)\n+ r_tf = f_tf(a, b)\n+ self.assertArraysEqual(r_jax, np.asarray(r_tf))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"_{f_jax.__name__}\",\n+ f_jax=f_jax)\n+ for f_jax in LAX_LOGICAL_ELEMENTWISE_UNARY))\n+ def test_unary_logical_elementwise(self, f_jax):\n+ a = np.array([1, 3, 2, 0, 0, 2, 1, 3], dtype=np.uint32)\n+ f_tf = tf.function(jax2tf.convert(f_jax))\n+ r_jax = f_jax(a)\n+ r_tf = f_tf(a)\n+ self.assertAllClose(r_jax[np.isfinite(r_jax)],\n+ r_tf[np.isfinite(r_tf)], atol=1e-4)\n+ # Checks support for bools.\n+ a = np.array([True, False])\n+ f_tf = tf.function(jax2tf.convert(f_jax))\n+ r_jax = f_jax(a)\n+ r_tf = f_tf(a)\n+ self.assertArraysEqual(r_jax, np.asarray(r_tf))\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_{f_jax.__name__}\",\n"
}
] | Python | Apache License 2.0 | google/jax | Adds boolean support for bitwise not and unittests for boolean support on logical operations. (#3483)
Co-authored-by: Thomas Keck <thomaskeck@google.com> |
260,335 | 23.06.2020 12:08:12 | 25,200 | a45e28377f54c5bd3033b989f8eb9fe516a7583d | add back a full_lower, dropped in | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -36,7 +36,7 @@ from . import source_info_util\nfrom .util import safe_zip, safe_map, partial, curry, prod, partialmethod\nfrom .pprint_util import pp, vcat, PrettyPrint\n-# TODO(dougalm): the trace cache breaks the leak detector. Consisder solving.\n+# TODO(dougalm): compilation cache breaks the leak detector. Consisder solving.\ncheck_leaks = False\n\"\"\"Disables internal invariant checks.\"\"\"\n@@ -1101,7 +1101,7 @@ def call_bind(primitive: Union['CallPrimitive', 'MapPrimitive'],\nelse:\ntracers = map(top_trace.full_raise, args)\nouts = primitive.process(top_trace, fun, tracers, params)\n- return apply_todos(env_trace_todo(), outs)\n+ return apply_todos(env_trace_todo(), map(full_lower, outs))\nclass CallPrimitive(Primitive):\nmultiple_results = True\n@@ -1220,11 +1220,6 @@ def _check_jaxpr(jaxpr: Jaxpr, in_avals: Sequence[AbstractValue]):\nmap(write, jaxpr.invars, in_avals)\nfor eqn in jaxpr.eqns:\n-\n- if eqn.primitive in skip_check_primitives:\n- map(write, eqn.outvars, [v.aval for v in eqn.outvars]) # skip checking\n- continue\n-\nin_avals = map(read, eqn.invars)\nif eqn.primitive.call_primitive:\nout_avals = check_call(eqn.primitive, in_avals, eqn.params)\n@@ -1240,8 +1235,6 @@ def _check_jaxpr(jaxpr: Jaxpr, in_avals: Sequence[AbstractValue]):\nmap(read, jaxpr.outvars)\n-skip_check_primitives: Set[Primitive] = set()\n-\ndef check_eqn(prim, in_avals, params):\nfor jaxpr in jaxprs_in_params(params):\ncheck_jaxpr(jaxpr)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/invertible_ad.py",
"new_path": "jax/interpreters/invertible_ad.py",
"diff": "@@ -64,9 +64,6 @@ def _invertible_call_make_output_tracers(trace, in_tracers, out_tracers, params)\npe.call_partial_eval_rules[invertible_call_p] = partial(\npe._remat_partial_eval, _invertible_call_make_output_tracers)\n-# TODO(mattjj): remove this when #3370 lands\n-core.skip_check_primitives.add(invertible_call_p)\n-\n@cache()\ndef _append_invars(jaxpr, avals):\nnewvar = core.gensym([jaxpr])\n"
}
] | Python | Apache License 2.0 | google/jax | add back a full_lower, dropped in #3491 (#3530) |
260,335 | 23.06.2020 14:03:36 | 25,200 | 74ee2ef6eb522f3de93feacc6b15e2f9a93fb8a7 | avoid value-based error check in random.choice | [
{
"change_type": "MODIFY",
"old_path": "jax/random.py",
"new_path": "jax/random.py",
"diff": "@@ -574,8 +574,6 @@ def choice(key, a, shape=(), replace=True, p=None):\np = jnp.asarray(p)\nif p.shape != (n_inputs,):\nraise ValueError(\"p must be None or match the shape of a\")\n- if jnp.any(p < 0):\n- raise ValueError(\"entries of p must be non-negative.\")\nif replace:\np_cuml = jnp.cumsum(p)\nr = p_cuml[-1] * (1 - uniform(key, shape))\n"
}
] | Python | Apache License 2.0 | google/jax | avoid value-based error check in random.choice (#3531) |
260,677 | 23.06.2020 23:36:45 | -3,600 | 9d173c622555898b3825a296f82d166da67b6f46 | Support `b` and `return_sign` in scipy.special.logsumexp | [
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -101,15 +101,27 @@ expit.defjvps(lambda g, ans, x: g * ans * (lax._const(ans, 1) - ans))\n@_wraps(osp_special.logsumexp)\ndef logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):\n- if b is not None or return_sign:\n- raise NotImplementedError(\"Only implemented for b=None, return_sign=False\")\n+ if b is not None:\n+ a, b = jnp.broadcast_arrays(a, b)\ndims = _reduction_dims(a, axis)\ndimadd = lambda x: lax.expand_dims(x, dims)\namax = lax.reduce(a, _constant_like(a, -np.inf), lax.max, dims)\namax = lax.stop_gradient(lax.select(lax.is_finite(amax), amax, lax.full_like(amax, 0)))\namax_singletons = dimadd(amax)\n+ if b is None:\nout = lax.add(lax.log(lax.reduce(lax.exp(lax.sub(a, amax_singletons)),\n_constant_like(a, 0), lax.add, dims)), amax)\n+ sign = jnp.where(jnp.isnan(out), np.nan, 1.0).astype(out.dtype)\n+ sign = jnp.where(out == -np.inf, 0.0, sign)\n+ else:\n+ sumexp = lax.reduce(lax.mul(lax.exp(lax.sub(a, amax_singletons)), b),\n+ _constant_like(a, 0), lax.add, dims)\n+ sign = lax.stop_gradient(lax.sign(sumexp))\n+ out = lax.add(lax.log(lax.abs(sumexp)), amax)\n+ if return_sign:\n+ return (dimadd(out), dimadd(sign)) if keepdims else (out, sign)\n+ if b is not None:\n+ out = jnp.where(sign < 0, np.nan, out)\nreturn dimadd(out) if keepdims else out\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_scipy_test.py",
"new_path": "tests/lax_scipy_test.py",
"diff": "@@ -33,6 +33,10 @@ config.parse_flags_with_absl()\nFLAGS = config.FLAGS\nall_shapes = [(), (4,), (3, 4), (3, 1), (1, 4), (2, 1, 4)]\n+compatible_shapes = [[(), ()],\n+ [(4,), (3, 4)],\n+ [(3, 1), (1, 4)],\n+ [(2, 3, 4), (2, 1, 4)]]\nfloat_dtypes = [onp.float32, onp.float64]\ncomplex_dtypes = [onp.complex64]\n@@ -90,28 +94,51 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nreturn lambda: [rng(shape, dtype) for shape, dtype in zip(shapes, dtypes)]\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_inshape={}_axis={}_keepdims={}\".format(\n- jtu.format_shape_dtype_string(shape, dtype), axis, keepdims),\n+ {\"testcase_name\":\n+ \"_shapes={}_axis={}_keepdims={}_return_sign={}_use_b_{}\".format(\n+ jtu.format_shape_dtype_string(shapes, dtype),\n+ axis, keepdims, return_sign, use_b),\n# TODO(b/133842870): re-enable when exp(nan) returns NaN on CPU.\n- \"rng_factory\": jtu.rand_some_inf_and_nan\n- if jtu.device_under_test() != \"cpu\"\n- else jtu.rand_default,\n- \"shape\": shape, \"dtype\": dtype,\n- \"axis\": axis, \"keepdims\": keepdims}\n- for shape in all_shapes for dtype in float_dtypes\n- for axis in range(-len(shape), len(shape))\n- for keepdims in [False, True]))\n+ \"shapes\": shapes, \"dtype\": dtype,\n+ \"axis\": axis, \"keepdims\": keepdims,\n+ \"return_sign\": return_sign, \"use_b\": use_b}\n+ for shape_group in compatible_shapes for dtype in float_dtypes\n+ for shapes in itertools.product(shape_group, shape_group)\n+ for axis in range(-max(len(shape) for shape in shapes),\n+ max(len(shape) for shape in shapes))\n+ for keepdims in [False, True]\n+ for return_sign in [False, True]\n+ for use_b in [False, True]))\n@jtu.skip_on_flag(\"jax_xla_backend\", \"xrt\")\n- def testLogSumExp(self, rng_factory, shape, dtype, axis, keepdims):\n- rng = rng_factory(self.rng())\n+ @jtu.ignore_warning(category=RuntimeWarning,\n+ message=\"invalid value encountered in log.*\")\n+ def testLogSumExp(self, shapes, dtype, axis,\n+ keepdims, return_sign, use_b):\n+ if jtu.device_under_test() != \"cpu\":\n+ rng = jtu.rand_some_inf_and_nan(self.rng())\n+ else:\n+ rng = jtu.rand_default(self.rng())\n# TODO(mattjj): test autodiff\n+ if use_b:\n+ def scipy_fun(array_to_reduce, scale_array):\n+ return osp_special.logsumexp(array_to_reduce, axis, keepdims=keepdims,\n+ return_sign=return_sign, b=scale_array)\n+\n+ def lax_fun(array_to_reduce, scale_array):\n+ return lsp_special.logsumexp(array_to_reduce, axis, keepdims=keepdims,\n+ return_sign=return_sign, b=scale_array)\n+\n+ args_maker = lambda: [rng(shapes[0], dtype), rng(shapes[1], dtype)]\n+ else:\ndef scipy_fun(array_to_reduce):\n- return osp_special.logsumexp(array_to_reduce, axis, keepdims=keepdims)\n+ return osp_special.logsumexp(array_to_reduce, axis, keepdims=keepdims,\n+ return_sign=return_sign)\ndef lax_fun(array_to_reduce):\n- return lsp_special.logsumexp(array_to_reduce, axis, keepdims=keepdims)\n+ return lsp_special.logsumexp(array_to_reduce, axis, keepdims=keepdims,\n+ return_sign=return_sign)\n- args_maker = lambda: [rng(shape, dtype)]\n+ args_maker = lambda: [rng(shapes[0], dtype)]\nself._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker)\nself._CompileAndCheck(lax_fun, args_maker)\n"
}
] | Python | Apache License 2.0 | google/jax | Support `b` and `return_sign` in scipy.special.logsumexp (#3488) |
260,597 | 24.06.2020 15:22:35 | -7,200 | a6e3f992a70775ef16c285e024cd2ac62ea32077 | Add np.unwrap | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -56,7 +56,7 @@ from .lax_numpy import (\nsquare, squeeze, stack, std, subtract, sum, swapaxes, take, take_along_axis,\ntan, tanh, tensordot, tile, trace, trapz, transpose, tri, tril, tril_indices, tril_indices_from,\ntriu, triu_indices, triu_indices_from, true_divide, trunc, uint16, uint32, uint64, uint8, unique,\n- unpackbits, unravel_index, unsignedinteger, vander, var, vdot, vsplit,\n+ unpackbits, unravel_index, unsignedinteger, unwrap, vander, var, vdot, vsplit,\nvstack, where, zeros, zeros_like)\nfrom .polynomial import roots\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1844,6 +1844,22 @@ nancumprod = _make_cumulative_reduction(np.nancumprod, lax.cumprod,\nfill_nan=True, fill_value=1)\n+@_wraps(np.unwrap)\n+def unwrap(p, discont=pi, axis=-1):\n+ dd = diff(p, axis=axis)\n+ ddmod = mod(dd + pi, 2 * pi) - pi\n+ ddmod = where((ddmod == -pi) & (dd > 0), pi, ddmod)\n+\n+ ph_correct = where(abs(dd) < discont, 0, ddmod - dd)\n+\n+ up = concatenate((\n+ lax.slice_in_dim(p, 0, 1, axis=axis),\n+ lax.slice_in_dim(p, 1, None, axis=axis) + cumsum(ph_correct, axis=axis)\n+ ), axis=axis)\n+\n+ return up\n+\n+\n### Array-creation functions\ndef _check_no_padding(axis_padding, mode):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -260,6 +260,12 @@ JAX_COMPOUND_OP_RECORDS = [\n[\"rev\"], inexact=True),\nop_record(\"diff\", 1, number_dtypes, nonzerodim_shapes, jtu.rand_default, [\"rev\"]),\nop_record(\"ediff1d\", 3, [np.int32], all_shapes, jtu.rand_default, []),\n+ op_record(\"unwrap\", 1, float_dtypes, nonempty_nonscalar_array_shapes,\n+ jtu.rand_default, [\"rev\"],\n+ # numpy.unwrap always returns float64\n+ check_dtypes=False,\n+ # numpy cumsum is inaccurate, see issue #3517\n+ tolerance={dtypes.bfloat16: 1e-1, np.float16: 1e-1})\n]\nJAX_BITWISE_OP_RECORDS = [\n"
}
] | Python | Apache License 2.0 | google/jax | Add np.unwrap (#3527) |
260,280 | 24.06.2020 11:54:06 | 10,800 | 319eeaf5c97b076cbdc70fb9fa60260cb32416c0 | Future warning about lists and tuples | [
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -1521,6 +1521,10 @@ def _make_reduction(np_fun, op, init_val, preproc=None, bool_op=None,\nif out is not None:\nraise ValueError(\"reduction does not support the `out` argument.\")\n+ if isinstance(a, (list, tuple)):\n+ msg = \"Reductions won't accept lists and tuples\" + \\\n+ \"in future versions, only scalars and ndarrays\"\n+ warnings.warn(msg, category=FutureWarning)\na = a if isinstance(a, ndarray) else asarray(a)\na = preproc(a) if preproc else a\ndims = _reduction_dims(a, axis)\n"
},
{
"change_type": "MODIFY",
"old_path": "pytest.ini",
"new_path": "pytest.ini",
"diff": "@@ -4,7 +4,8 @@ filterwarnings =\nignore:No GPU/TPU found, falling back to CPU.:UserWarning\nignore:Explicitly requested dtype.*is not available.*:UserWarning\nignore:jax.experimental.vectorize is deprecated.*:FutureWarning\n- # The rest are for experimental/jax2tf\n+ ignore:Reductions won't accept lists and tuples*:FutureWarning\n+ # The rest are for experimental/jax_to_tf\nignore:the imp module is deprecated in favour of importlib.*:DeprecationWarning\nignore:can't resolve package from __spec__ or __package__:ImportWarning\nignore:Using or importing the ABCs.*:DeprecationWarning\n"
}
] | Python | Apache License 2.0 | google/jax | Future warning about lists and tuples (#3369) |
260,519 | 24.06.2020 21:49:16 | -19,080 | a44bc0c2c05aa4a079eda3995379dab4a63182dc | Add np.diag_indices_from | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.numpy.rst",
"new_path": "docs/jax.numpy.rst",
"diff": "@@ -97,6 +97,7 @@ Not every function in NumPy is implemented; contributions are welcome!\ndegrees\ndiag\ndiag_indices\n+ diag_indices_from\ndiagflat\ndiagonal\ndigitize\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -29,7 +29,7 @@ from .lax_numpy import (\ncomplex128, complex64, complex_, complexfloating, compress, concatenate,\nconj, conjugate, convolve, copysign, corrcoef, correlate, cos, cosh,\ncount_nonzero, cov, cross, csingle, cumprod, cumproduct, cumsum, deg2rad,\n- degrees, diag, diagflat, diag_indices, diagonal, diff, digitize, divide, divmod, dot,\n+ degrees, diag, diagflat, diag_indices, diag_indices_from, diagonal, diff, digitize, divide, divmod, dot,\ndouble, dsplit, dstack, dtype, e, ediff1d, einsum, einsum_path, empty,\nempty_like, equal, euler_gamma, exp, exp2, expand_dims, expm1, extract, eye,\nfabs, finfo, fix, flatnonzero, flexible, flip, fliplr, flipud, float16, float32,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/lax_numpy.py",
"new_path": "jax/numpy/lax_numpy.py",
"diff": "@@ -2593,6 +2593,16 @@ def diag_indices(n, ndim=2):\n.format(ndim))\nreturn (lax.iota(int_, n),) * ndim\n+@_wraps(np.diag_indices_from)\n+def diag_indices_from(arr):\n+ if not arr.ndim >= 2:\n+ raise ValueError(\"input array must be at least 2-d\")\n+\n+ if len(set(arr.shape)) != 1:\n+ raise ValueError(\"All dimensions of input must be of equal length\")\n+\n+ return diag_indices(arr.shape[0], ndim=arr.ndim)\n+\n@_wraps(np.diagonal)\ndef diagonal(a, offset=0, axis1=0, axis2=1):\na_shape = shape(a)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -1593,6 +1593,20 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nnp.testing.assert_equal(np.diag_indices(n, ndim),\njnp.diag_indices(n, ndim))\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"arr_shape={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype)\n+ ),\n+ \"dtype\": dtype, \"shape\": shape}\n+ for dtype in default_dtypes\n+ for shape in [(1,1), (2,2), (3,3), (4,4), (5,5)]))\n+ def testDiagIndicesFrom(self, dtype, shape):\n+ rng = jtu.rand_default(self.rng())\n+ np_fun = np.diag_indices_from\n+ jnp_fun = jnp.diag_indices_from\n+ args_maker = lambda : [rng(shape, dtype)]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n+ self._CompileAndCheck(jnp_fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_k={}\".format(\n"
}
] | Python | Apache License 2.0 | google/jax | Add np.diag_indices_from (#3500) |
260,705 | 24.06.2020 19:00:24 | 10,800 | 7e5407c734b22aaa73da2bfe9c75edff3d87d37e | Fix typos pytrees page on readthedocs | [
{
"change_type": "MODIFY",
"old_path": "docs/pytrees.rst",
"new_path": "docs/pytrees.rst",
"diff": "@@ -55,8 +55,8 @@ to only map over the dictionary argument, we can use::\n(None, 0) # equivalent to (None, {\"k1\": 0, \"k2\": 0})\n-Or, if want every argument to be mapped, we can simply write a single leaf value\n-that is applied over the entire argument tuple pytree::\n+Or, if we want every argument to be mapped, we can simply write a single leaf\n+value that is applied over the entire argument tuple pytree::\n0\n@@ -103,7 +103,7 @@ Here is a simple example::\nvalue_flat, value_tree = tree_flatten(value_structured)\nprint(\"value_flat={}\\nvalue_tree={}\".format(value_flat, value_tree))\n- # Transform the flt value list using an element-wise numeric transformer\n+ # Transform the flat value list using an element-wise numeric transformer\ntransformed_flat = list(map(lambda v: v * 2., value_flat))\nprint(\"transformed_flat={}\".format(transformed_flat))\n"
}
] | Python | Apache License 2.0 | google/jax | Fix typos pytrees page on readthedocs (#3548) |
260,335 | 24.06.2020 16:11:26 | 25,200 | 696958d2bd97ecfb83feafc5d70bc9fc32cc8b6d | add remat docstring
* add remat docstring
first part of addressing | [
{
"change_type": "MODIFY",
"old_path": "jax/api.py",
"new_path": "jax/api.py",
"diff": "@@ -1792,6 +1792,87 @@ def eval_shape(fun: Callable, *args, **kwargs):\ndef checkpoint(fun: Callable, concrete: bool = False) -> Callable:\n+ \"\"\"Make ``fun`` recompute internal linearization points when differentiated.\n+\n+ The :func:`jax.checkpoint` decorator, aliased to ``jax.remat``, provides a\n+ way to trade off computation time and memory cost in the context of automatic\n+ differentiation, especially with reverse-mode autodiff like :func:`jax.grad`\n+ and :func:`jax.vjp` but also with :func:`jax.linearize`.\n+\n+ When differentiating a function in reverse-mode, by default all the\n+ linearization points (e.g. inputs to elementwise nonlinear primitive\n+ operations) are stored when evaluating the forward pass so that they can be\n+ reused on the backward pass. This evaluation strategy can lead to a high\n+ memory cost, or even to poor performance on hardware acceleartors where memory\n+ access is much more expensive than FLOPs.\n+\n+ An alternative evaluation strategy is for some of the linearization points to\n+ be recomputed (i.e. rematerialized) rather than stored. This approach can\n+ reduce memory usage at the cost of increased computation.\n+\n+ This function decorator produces a new version of ``fun`` which follows\n+ the rematerialization strategy rather than the default store-everything\n+ strategy. That is, it returns a new version of ``fun`` which, when\n+ differentiated, doesn't store any of its intermediate linearization points.\n+ Instead, these linearization points are recomputed from the function's saved\n+ inputs.\n+\n+ See the examples below.\n+\n+ Args:\n+ fun: Function for which the autodiff evaluation strategy is to be changed\n+ from the default of storing all intermediate linearization points to\n+ recomputing them. Its arguments and return value should be arrays,\n+ scalars, or (nested) standard Python containers (tuple/list/dict) thereof.\n+ concrete: Optional, boolean indicating whether ``fun`` may involve\n+ value-dependent Python control flow (default False). Support for such\n+ control flow is optional, and disabled by default, because in some\n+ edge-case compositions with :func:`jax.jit` it can lead to some extra\n+ computation.\n+\n+ Returns:\n+ A function (callable) with the same input/output behavior as ``fun`` but\n+ which, when differentiated using e.g. :func:`jax.grad`, :func:`jax.vjp`, or\n+ :func:`jax.linearize`, recomputes rather than stores intermediate\n+ linearization points, thus potentially saving memory at the cost of extra\n+ computation.\n+\n+ Here is a simple example:\n+\n+ >>> import jax\n+ >>> import jax.numpy as jnp\n+\n+ >>> @jax.checkpoint\n+ ... def g(x):\n+ ... y = jnp.sin(x)\n+ ... z = jnp.sin(y)\n+ ... return z\n+ ...\n+ >>> jax.grad(g)(2.0)\n+ DeviceArray(-0.25563914, dtype=float32)\n+\n+ Here, the same value is produced whether or not the :func:`jax.checkpoint`\n+ decorator is present. But when using :func:`jax.checkpoint`, the value\n+ ``jnp.sin(2.0)`` is computed twice: once on the forward pass, and once on the\n+ backward pass. The values ``jnp.cos(2.0)`` and ``jnp.cos(jnp.sin(2.0))`` are\n+ also computed twice. Without using the decorator, both ``jnp.cos(2.0)`` and\n+ ``jnp.cos(jnp.sin(2.0))`` would be stored and reused.\n+\n+ The :func:`jax.checkpoint` decorator can be applied recursively to express\n+ sophisticated autodiff rematerialization strategies. For example:\n+\n+ >>> def recursive_checkpoint(funs):\n+ ... if len(funs) == 1:\n+ ... return funs[0]\n+ ... elif len(funs) == 2:\n+ ... f1, f2 = funs\n+ ... return lambda x: f1(f2(x))\n+ ... else:\n+ ... f1 = recursive_checkpoint(funs[:len(funs)//2])\n+ ... f2 = recursive_checkpoint(funs[len(funs)//2:])\n+ ... return lambda x: f1(jax.checkpoint(f2)(x))\n+ ...\n+ \"\"\"\n@wraps(fun)\ndef fun_remat(*args, **kwargs):\nargs_flat, in_tree = tree_flatten((args, kwargs))\n@@ -1828,7 +1909,7 @@ class CustomTransformsFunction(object):\nreturn tree_unflatten(out_tree(), outs)\ndef custom_transforms(fun):\n- \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n+ \"\"\"Deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp`.\"\"\"\nname = getattr(fun, '__name__', '<unnamed custom_transforms primitive>')\nfun_p = core.Primitive(name)\n"
}
] | Python | Apache License 2.0 | google/jax | add remat docstring (#3542)
* add remat docstring
first part of addressing #3314 |
260,299 | 25.06.2020 15:50:11 | -3,600 | c9670d50c5015f36d7569bdf204b0651c64e55fb | Fix lazy broadcast issue | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -2776,7 +2776,8 @@ ad.deflinear(broadcast_p, lambda t, sizes: [_reduce_sum(t, range(len(sizes)))])\nbatching.primitive_batchers[broadcast_p] = _broadcast_batch_rule\ndef _broadcast_in_dim_impl(operand, *, shape, broadcast_dimensions):\n- if type(operand) is xla.DeviceArray:\n+ if type(operand) is xla.DeviceArray and onp.all(\n+ onp.equal(operand.shape, onp.take(shape, broadcast_dimensions))):\nshape = _broadcast_in_dim_shape_rule(\noperand, shape=shape, broadcast_dimensions=broadcast_dimensions)\naval = ShapedArray(shape, _dtype(operand))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1787,6 +1787,13 @@ class LazyConstantTest(jtu.JaxTestCase):\nexpected = onp.asarray(make_const())\nself._Check(make_const, expected)\n+ def testBroadcastInDim(self):\n+ arr = lax.full((2, 1), 1.) + 1.\n+ arr_onp = onp.full((2, 1), 1.) + 1.\n+ expected = lax_reference.broadcast_in_dim(arr_onp, (2, 1, 3), (0, 2))\n+ make_const = lambda: lax.broadcast_in_dim(arr, (2, 1, 3), (0, 2))\n+ self._Check(make_const, expected)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | Fix lazy broadcast issue (#3536) |
260,335 | 25.06.2020 17:36:17 | 25,200 | db80ca5dd87d27e1800834c2828298aa3f6d8992 | allow closures for odeint dynamics functions
* allow closures for odeint dynamics functions
fixes
* add tests for odeint dynamics closing over tracers | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/ode.py",
"new_path": "jax/experimental/ode.py",
"diff": "@@ -31,15 +31,39 @@ import jax.numpy as jnp\nfrom jax import core\nfrom jax import lax\nfrom jax import ops\n-from jax.util import safe_map, safe_zip\n+from jax.util import safe_map, safe_zip, cache, split_list\n+from jax.api_util import flatten_fun_nokwargs\nfrom jax.flatten_util import ravel_pytree\n-from jax.tree_util import tree_map\n+from jax.tree_util import tree_map, tree_flatten, tree_unflatten\n+from jax.interpreters import partial_eval as pe\nfrom jax import linear_util as lu\nmap = safe_map\nzip = safe_zip\n+@cache()\n+def closure_convert(fun, in_tree, in_avals):\n+ in_pvals = [pe.PartialVal.unknown(aval) for aval in in_avals]\n+ wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\n+ with core.initial_style_staging():\n+ jaxpr, out_pvals, consts = pe.trace_to_jaxpr(\n+ wrapped_fun, in_pvals, instantiate=True, stage_out=False)\n+ out_tree = out_tree()\n+ num_consts = len(consts)\n+\n+ def converted_fun(y, t, *consts_args):\n+ consts, args = split_list(consts_args, [num_consts])\n+ all_args, in_tree2 = tree_flatten((y, t, *args))\n+ assert in_tree == in_tree2\n+ out_flat = core.eval_jaxpr(jaxpr, consts, *all_args)\n+ return tree_unflatten(out_tree, out_flat)\n+\n+ return converted_fun, consts\n+\n+def abstractify(x):\n+ return core.raise_to_shaped(core.get_aval(x))\n+\ndef ravel_first_arg(f, unravel):\nreturn ravel_first_arg_(lu.wrap_init(f), unravel).call_wrapped\n@@ -159,8 +183,12 @@ def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf):\nmsg = (\"The contents of odeint *args must be arrays or scalars, but got \"\n\"\\n{}.\")\nraise TypeError(msg.format(arg))\n- tree_map(_check_arg, args)\n- return _odeint_wrapper(func, rtol, atol, mxstep, y0, t, *args)\n+\n+ flat_args, in_tree = tree_flatten((y0, t[0], *args))\n+ in_avals = tuple(map(abstractify, flat_args))\n+ converted, consts = closure_convert(func, in_tree, in_avals)\n+\n+ return _odeint_wrapper(converted, rtol, atol, mxstep, y0, t, *consts, *args)\n@partial(jax.jit, static_argnums=(0, 1, 2, 3))\ndef _odeint_wrapper(func, rtol, atol, mxstep, y0, ts, *args):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/ode_test.py",
"new_path": "tests/ode_test.py",
"diff": "@@ -181,6 +181,37 @@ class ODETest(jtu.JaxTestCase):\nf = lambda x0: odeint(lambda x, _t: x, x0, t)\njax.vmap(f)(x0_eval) # doesn't crash\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_grad_closure(self):\n+ # simplification of https://github.com/google/jax/issues/2718\n+ def experiment(x):\n+ def model(y, t):\n+ return -x * y\n+ history = odeint(model, 1., np.arange(0, 10, 0.1))\n+ return history[-1]\n+ jtu.check_grads(experiment, (0.01,), modes=[\"rev\"], order=1)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_grad_closure_with_vmap(self):\n+ # https://github.com/google/jax/issues/2718\n+ @jax.jit\n+ def experiment(x):\n+ def model(y, t):\n+ return -x * y\n+ history = odeint(model, 1., np.arange(0, 10, 0.1))\n+ return history[-1]\n+\n+ gradfun = jax.value_and_grad(experiment)\n+ t = np.arange(0., 1., 0.01)\n+ h, g = jax.vmap(gradfun)(t) # doesn't crash\n+ ans = h[11], g[11]\n+\n+ expected_h = experiment(t[11])\n+ expected_g = (experiment(t[11] + 1e-5) - expected_h) / 1e-5\n+ expected = expected_h, expected_g\n+\n+ self.assertAllClose(ans, expected, check_dtypes=False, atol=1e-2, rtol=1e-2)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | allow closures for odeint dynamics functions (#3562)
* allow closures for odeint dynamics functions
fixes #2718, #3557
* add tests for odeint dynamics closing over tracers |
260,335 | 25.06.2020 19:17:24 | 25,200 | 062ce297ddf9056ca7743a2d262b0db070eb4553 | removed stale faq entries | [
{
"change_type": "MODIFY",
"old_path": "docs/faq.rst",
"new_path": "docs/faq.rst",
"diff": "-JAX Frequently Asked Questions\n-==============================\n+JAX Frequently Asked Questions (FAQ)\n+====================================\n.. comment RST primer for Sphinx: https://thomas-cokelaer.info/tutorials/sphinx/rest_syntax.html\n.. comment Some links referenced here. Use JAX_sharp_bits_ (underscore at the end) to reference\n@@ -11,25 +11,6 @@ JAX Frequently Asked Questions\nWe are collecting here answers to frequently asked questions.\nContributions welcome!\n-Creating arrays with `jax.numpy.array` is slower than with `numpy.array`\n-------------------------------------------------------------------------\n-\n-The following code is relatively fast when using NumPy, and slow when using\n-JAX's NumPy::\n-\n- import numpy as np\n- np.array([0] * int(1e6))\n-\n-The reason is that in NumPy the ``numpy.array`` function is implemented in C, while\n-the :func:`jax.numpy.array` is implemented in Python, and it needs to iterate over a long\n-list to convert each list element to an array element.\n-\n-An alternative would be to create the array with original NumPy and then convert\n-it to a JAX array::\n-\n- from jax import numpy as jnp\n- jnp.array(np.array([0] * int(1e6)))\n-\n`jit` changes the behavior of my function\n-----------------------------------------\n@@ -293,20 +274,3 @@ Additional reading:\n* `Issue: gradients through np.where when one of branches is nan <https://github.com/google/jax/issues/1052#issuecomment-514083352>`_.\n* `How to avoid NaN gradients when using where <https://github.com/tensorflow/probability/blob/master/discussion/where-nan.pdf>`_.\n-\n-Why do I get forward-mode differentiation error when I am trying to do reverse-mode differentiation?\n------------------------------------------------------------------------------------------------------\n-\n-JAX implements reverse-mode differentiation as a composition of two operations:\n-linearization and transposition. The linearization step (see :func:`jax.linearize`)\n-uses the JVP rules to form the forward-computation of tangents along with the intermediate\n-forward computations of intermediate values on which the tangents depend.\n-The transposition step will turn the forward-computation of tangents\n-into a reverse-mode computation.\n-\n-If the JVP rule is not implemented for a primitive, then neither the forward-mode\n-nor the reverse-mode differentiation will work, but the error given will refer\n-to the forward-mode because that is the one that fails.\n-\n-You can read more details at How_JAX_primitives_work_.\n-\n"
}
] | Python | Apache License 2.0 | google/jax | removed stale faq entries (#3565) |
260,335 | 25.06.2020 20:57:34 | 25,200 | 26c6c3a457414577f7232699095877d6c86d032d | fix error when doing forward-mode of odeint
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -590,3 +590,5 @@ batching.primitive_batchers[custom_vjp_call_jaxpr_p] = _custom_vjp_call_jaxpr_vm\nxla.initial_style_translations[custom_vjp_call_jaxpr_p] = \\\nxla.lower_fun_initial_style(_custom_vjp_call_jaxpr_impl)\n+\n+batching.primitive_batchers[ad.custom_lin_p] = ad._raise_custom_vjp_error_on_jvp\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/ode_test.py",
"new_path": "tests/ode_test.py",
"diff": "@@ -212,6 +212,15 @@ class ODETest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False, atol=1e-2, rtol=1e-2)\n+ def test_forward_mode_error(self):\n+ # https://github.com/google/jax/issues/3558\n+\n+ def f(k):\n+ return odeint(lambda x, t: k*x, 1., jnp.linspace(0, 1., 50)).sum()\n+\n+ with self.assertRaisesRegex(TypeError, \"can't apply forward-mode.*\"):\n+ jax.jacfwd(f)(3.)\n+\nif __name__ == '__main__':\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | fix error when doing forward-mode of odeint (#3566)
fixes #3558 |
260,676 | 26.06.2020 18:40:00 | -3,600 | 99a43f20db0c35f6da5d2dfc636bd57bd5bfad6e | Added missing is_stable argument to lax.sort | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1196,8 +1196,8 @@ def cumprod(operand: Array, axis: int) -> Array:\n\"\"\"Computes a cumulative product along `axis`.\"\"\"\nreturn cumprod_p.bind(operand, axis=int(axis))\n-def sort(operand: Union[Array, Sequence[Array]], dimension: int = -1\n- ) -> Union[Array, Tuple[Array, ...]]:\n+def sort(operand: Union[Array, Sequence[Array]], dimension: int = -1,\n+ is_stable: bool = False) -> Union[Array, Tuple[Array, ...]]:\n\"\"\"Wraps XLA's `Sort\n<https://www.tensorflow.org/xla/operation_semantics#sort>`_\noperator.\n@@ -1206,16 +1206,17 @@ def sort(operand: Union[Array, Sequence[Array]], dimension: int = -1\nif len(operand) == 0:\nraise TypeError(\"Sort requires at least one operand\")\ndimension = _canonicalize_axis(dimension, len(operand[0].shape))\n- return tuple(sort_p.bind(*operand, dimension=dimension))\n+ return tuple(sort_p.bind(*operand, dimension=dimension,\n+ is_stable=is_stable))\nelse:\ndimension = _canonicalize_axis(dimension, len(operand.shape))\n- return sort_p.bind(operand, dimension=dimension)[0]\n+ return sort_p.bind(operand, dimension=dimension, is_stable=is_stable)[0]\n-def sort_key_val(keys: Array, values: Array,\n- dimension: int = -1) -> Tuple[Array, Array]:\n+def sort_key_val(keys: Array, values: Array, dimension: int = -1,\n+ is_stable: bool = False) -> Tuple[Array, Array]:\n\"\"\"Sorts ``keys`` along ``dimension`` and applies same permutation to ``values``.\"\"\"\ndimension = _canonicalize_axis(dimension, len(keys.shape))\n- k, v = sort_p.bind(keys, values, dimension=dimension)\n+ k, v = sort_p.bind(keys, values, dimension=dimension, is_stable=is_stable)\nreturn k, v\ndef top_k(operand: Array, k: int) -> Tuple[Array, Array]:\n@@ -4937,7 +4938,7 @@ def _sort_lt_comparator(*operands):\nelse lt(xk, yk))\nreturn p\n-def _sort_translation_rule(c, *operands, dimension):\n+def _sort_translation_rule(c, *operands, dimension, is_stable):\ntypes = [c.get_shape(x).xla_element_type() for x in operands]\nsubc = xla_bridge.make_computation_builder(\"sort_lt_comparator\")\nparams = [xb.parameter(subc, 2 * i + j, xc.Shape.array_shape(typ, ()))\n@@ -4945,23 +4946,24 @@ def _sort_translation_rule(c, *operands, dimension):\nresult = xla.lower_fun(_sort_lt_comparator,\nmultiple_results=False)(subc, *params)\ncomparator = subc.build(result)\n- out = xops.Sort(c, operands, dimension=dimension, is_stable=True,\n+ out = xops.Sort(c, operands, dimension=dimension, is_stable=is_stable,\ncomparator=comparator)\nreturn out if len(operands) != 1 else xops.Tuple(c, [out])\n-def _sort_jvp(primals, tangents, *, dimension):\n+def _sort_jvp(primals, tangents, *, dimension, is_stable):\nshape = primals[0].shape\niotas = []\nfor dim, size in enumerate(shape):\ndtype = onp.int32 if size < onp.iinfo(onp.int32).max else onp.int64\niotas.append(broadcasted_iota(dtype, shape, dim))\n- primals = sort_p.bind(*(primals + (iotas[dimension],)), dimension=dimension)\n+ primals = sort_p.bind(*(primals + (iotas[dimension],)), dimension=dimension,\n+ is_stable=is_stable)\nidx = tuple(primals[-1] if i == dimension else iotas[i]\nfor i in range(len(shape)))\ntangents_out = tuple(t if type(t) is ad_util.Zero else t[idx] for t in tangents)\nreturn tuple(primals[:-1]), tangents_out\n-def _sort_batch_rule(batched_args, batch_dims, *, dimension):\n+def _sort_batch_rule(batched_args, batch_dims, *, dimension, is_stable):\nprototype_arg, new_bdim = next(\n(a, b) for a, b in zip(batched_args, batch_dims) if b is not None)\nnew_args = []\n@@ -4973,7 +4975,8 @@ def _sort_batch_rule(batched_args, batch_dims, *, dimension):\nnew_args.append(batching.moveaxis(arg, bdim, new_bdim))\nnew_dimension = dimension + (new_bdim <= dimension)\nbdims = (new_bdim,) * len(new_args)\n- return sort_p.bind(*new_args, dimension=new_dimension), bdims\n+ return (sort_p.bind(*new_args, dimension=new_dimension, is_stable=is_stable),\n+ bdims)\nsort_p = Primitive('sort')\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_autodiff_test.py",
"new_path": "tests/lax_autodiff_test.py",
"diff": "@@ -749,33 +749,38 @@ class LaxAutodiffTest(jtu.JaxTestCase):\n# TODO(b/205052657): enable more tests when supported\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_shape={}_axis={}\".format(\n- jtu.format_shape_dtype_string(shape, dtype), axis),\n- \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype, \"axis\": axis}\n+ {\"testcase_name\": \"_shape={}_axis={}_isstable={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), axis, is_stable),\n+ \"rng_factory\": rng_factory, \"shape\": shape, \"dtype\": dtype, \"axis\": axis,\n+ \"is_stable\": is_stable}\nfor dtype in [onp.float32]\nfor shape in [(5,), (5, 7)]\nfor axis in [len(shape) - 1]\n+ for is_stable in [False, True]\nfor rng_factory in [jtu.rand_default]))\n- def testSortGrad(self, shape, dtype, axis, rng_factory):\n+ def testSortGrad(self, shape, dtype, axis, is_stable, rng_factory):\nrng = rng_factory(self.rng())\noperand = rng(shape, dtype)\n- sort = lambda x: lax.sort(x, dimension=axis)\n+ sort = lambda x: lax.sort(x, dimension=axis, is_stable=is_stable)\ncheck_grads(sort, (operand,), 2, [\"fwd\", \"rev\"], eps=1e-2)\n# TODO(b/205052657): enable more tests when supported\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_keyshape={}_valshape={}_axis={}\".format(\n+ {\"testcase_name\": \"_keyshape={}_valshape={}_axis={}_isstable={}\".format(\njtu.format_shape_dtype_string(shape, key_dtype),\njtu.format_shape_dtype_string(shape, val_dtype),\n- axis),\n+ axis, is_stable),\n\"rng_factory\": rng_factory, \"shape\": shape,\n- \"key_dtype\": key_dtype, \"val_dtype\": val_dtype, \"axis\": axis}\n+ \"key_dtype\": key_dtype, \"val_dtype\": val_dtype, \"axis\": axis,\n+ \"is_stable\": is_stable}\nfor key_dtype in [onp.float32]\nfor val_dtype in [onp.float32]\nfor shape in [(3,), (5, 3)]\nfor axis in [len(shape) - 1]\n+ for is_stable in [False, True]\nfor rng_factory in [jtu.rand_default]))\n- def testSortKeyValGrad(self, shape, key_dtype, val_dtype, axis, rng_factory):\n+ def testSortKeyValGrad(self, shape, key_dtype, val_dtype, axis, is_stable,\n+ rng_factory):\nrng = rng_factory(self.rng())\n# This test relies on the property that wherever keys are tied, values are\n# too, since we don't guarantee the same ordering of values with equal keys.\n@@ -787,7 +792,7 @@ class LaxAutodiffTest(jtu.JaxTestCase):\nreturn keys, values\nkeys, values = args_maker()\n- fun = lambda keys, values: lax.sort_key_val(keys, values, axis)\n+ fun = lambda keys, values: lax.sort_key_val(keys, values, axis, is_stable)\ncheck_grads(fun, (keys, values), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, 1e-2)\n@parameterized.named_parameters(jtu.cases_from_list(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -1338,13 +1338,14 @@ class LaxTest(jtu.JaxTestCase):\nself._CheckAgainstNumpy(fun, onp_fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_shape={}_axis={}\".format(\n- jtu.format_shape_dtype_string(shape, dtype), axis),\n- \"shape\": shape, \"dtype\": dtype, \"axis\": axis}\n+ {\"testcase_name\": \"_shape={}_axis={}_isstable={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), axis, is_stable),\n+ \"shape\": shape, \"dtype\": dtype, \"axis\": axis, \"is_stable\": is_stable}\nfor dtype in all_dtypes\nfor shape in [(5,), (5, 7)]\n- for axis in [-1, len(shape) - 1]))\n- def testSort(self, shape, dtype, axis):\n+ for axis in [-1, len(shape) - 1]\n+ for is_stable in [False, True]))\n+ def testSort(self, shape, dtype, axis, is_stable):\n# TODO(b/141131288): enable complex-valued sorts on TPU.\nif (onp.issubdtype(dtype, onp.complexfloating) and (\n(jtu.device_under_test() == \"cpu\" and jax.lib.version <= (0, 1, 47)) or\n@@ -1352,17 +1353,18 @@ class LaxTest(jtu.JaxTestCase):\nraise SkipTest(\"Complex-valued sort not implemented\")\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\n- fun = lambda x: lax.sort(x, dimension=axis)\n+ fun = lambda x: lax.sort(x, dimension=axis, is_stable=is_stable)\nself._CompileAndCheck(fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_shape={}_axis={}\".format(\n- jtu.format_shape_dtype_string(shape, dtype), axis),\n- \"shape\": shape, \"dtype\": dtype, \"axis\": axis}\n+ {\"testcase_name\": \"_shape={}_axis={}_isstable={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype), axis, is_stable),\n+ \"shape\": shape, \"dtype\": dtype, \"axis\": axis, \"is_stable\": is_stable}\nfor dtype in all_dtypes\nfor shape in [(5,), (5, 7)]\n- for axis in [-1, len(shape) - 1]))\n- def testSortAgainstNumpy(self, shape, dtype, axis):\n+ for axis in [-1, len(shape) - 1]\n+ for is_stable in [False, True]))\n+ def testSortAgainstNumpy(self, shape, dtype, axis, is_stable):\n# TODO(b/141131288): enable complex-valued sorts on TPU.\nif (onp.issubdtype(dtype, onp.complexfloating) and (\n(jtu.device_under_test() == \"cpu\" and jax.lib.version <= (0, 1, 47)) or\n@@ -1370,22 +1372,27 @@ class LaxTest(jtu.JaxTestCase):\nraise SkipTest(\"Complex-valued sort not implemented\")\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: [rng(shape, dtype)]\n- op = lambda x: lax.sort(x, dimension=axis)\n- numpy_op = lambda x: lax_reference.sort(x, axis)\n+ op = lambda x: lax.sort(x, dimension=axis, is_stable=is_stable)\n+ def numpy_op(x):\n+ if is_stable:\n+ return lax_reference.sort(x, axis, kind='stable')\n+ else:\n+ return lax_reference.sort(x, axis)\nself._CheckAgainstNumpy(op, numpy_op, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_keyshape={}_valshape={}_axis={}\".format(\n+ {\"testcase_name\": \"_keyshape={}_valshape={}_axis={}_isstable={}\".format(\njtu.format_shape_dtype_string(shape, key_dtype),\njtu.format_shape_dtype_string(shape, val_dtype),\n- axis),\n+ axis, is_stable),\n\"shape\": shape, \"key_dtype\": key_dtype, \"val_dtype\": val_dtype,\n- \"axis\": axis}\n+ \"axis\": axis, \"is_stable\": is_stable}\nfor key_dtype in float_dtypes + complex_dtypes + int_dtypes + uint_dtypes\nfor val_dtype in [onp.float32, onp.int32, onp.uint32]\nfor shape in [(3,), (5, 3)]\n- for axis in [-1, len(shape) - 1]))\n- def testSortKeyVal(self, shape, key_dtype, val_dtype, axis):\n+ for axis in [-1, len(shape) - 1]\n+ for is_stable in [False, True]))\n+ def testSortKeyVal(self, shape, key_dtype, val_dtype, axis, is_stable):\n# TODO(b/141131288): enable complex-valued sorts on TPU.\nif (onp.issubdtype(key_dtype, onp.complexfloating) and (\n(jtu.device_under_test() == \"cpu\" and jax.lib.version <= (0, 1, 47)) or\n@@ -1401,7 +1408,7 @@ class LaxTest(jtu.JaxTestCase):\nvalues = rng(shape, val_dtype)\nreturn keys, values\n- fun = lambda keys, values: lax.sort_key_val(keys, values, axis)\n+ fun = lambda keys, values: lax.sort_key_val(keys, values, axis, is_stable)\nself._CompileAndCheck(fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_vmap_test.py",
"new_path": "tests/lax_vmap_test.py",
"diff": "@@ -655,15 +655,17 @@ class LaxVmapTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_shape={}_dimension={}_arity={}_bdims={}\"\n+ {\"testcase_name\": \"_shape={}_dimension={}_arity={}_bdims={}_isstable={}\"\n.format(jtu.format_shape_dtype_string(shape, onp.float32), dimension,\n- arity, bdims),\n- \"shape\": shape, \"dimension\": dimension, \"arity\": arity, \"bdims\": bdims}\n+ arity, bdims, is_stable),\n+ \"shape\": shape, \"dimension\": dimension, \"arity\": arity, \"bdims\": bdims,\n+ \"is_stable\": is_stable}\nfor shape in [(2, 3)]\nfor dimension in [0, 1]\nfor arity in range(3)\n- for bdims in all_bdims(*((shape,) * arity))))\n- def testSort(self, shape, dimension, arity, bdims):\n+ for bdims in all_bdims(*((shape,) * arity))\n+ for is_stable in [False, True]))\n+ def testSort(self, shape, dimension, arity, bdims, is_stable):\nrng = jtu.rand_default(self.rng())\nif arity == 1:\nfun = partial(lax.sort, dimension=dimension)\n@@ -671,7 +673,9 @@ class LaxVmapTest(jtu.JaxTestCase):\nrng)\nelse:\nfor i in range(arity):\n- fun = lambda *args, i=i: lax.sort(args, dimension=dimension)[i]\n+ fun = lambda *args, i=i: lax.sort(args,\n+ dimension=dimension,\n+ is_stable=is_stable)[i]\nself._CheckBatching(fun, 5, bdims, (shape,) * arity,\n(onp.float32,) * arity, rng)\n"
}
] | Python | Apache License 2.0 | google/jax | Added missing is_stable argument to lax.sort (#3553) |
260,335 | 26.06.2020 11:44:16 | 25,200 | 11caa21eca1634a6c4cd7cd1b94a25110c7929aa | ensure lax.reduce monoid test uses original numpy | [
{
"change_type": "MODIFY",
"old_path": "jax/lax/lax.py",
"new_path": "jax/lax/lax.py",
"diff": "@@ -1054,17 +1054,17 @@ def _get_monoid_reducer(monoid_op: Callable, x: Array) -> Optional[Callable]:\ndtype = _dtype(x)\nif (type(aval) is ConcreteArray) and aval.shape == ():\nif monoid_op is add:\n- return aval.val == 0 and _reduce_sum\n+ return onp.equal(aval.val, 0) and _reduce_sum\nif monoid_op is mul:\n- return aval.val == 1 and _reduce_prod\n+ return onp.equal(aval.val, 1) and _reduce_prod\nelif monoid_op is bitwise_or and dtype == onp.bool_:\n- return aval.val == _get_max_identity(dtype) and _reduce_or\n+ return onp.equal(aval.val, _get_max_identity(dtype)) and _reduce_or\nelif monoid_op is bitwise_and and dtype == onp.bool_:\n- return aval.val == _get_min_identity(dtype) and _reduce_and\n+ return onp.equal(aval.val, _get_min_identity(dtype)) and _reduce_and\nelif monoid_op is max:\n- return aval.val == _get_max_identity(dtype) and _reduce_max\n+ return onp.equal(aval.val, _get_max_identity(dtype)) and _reduce_max\nelif monoid_op is min:\n- return aval.val == _get_min_identity(dtype) and _reduce_min\n+ return onp.equal(aval.val, _get_min_identity(dtype)) and _reduce_min\nreturn None\ndef _get_max_identity(dtype: DType) -> Array:\n"
}
] | Python | Apache License 2.0 | google/jax | ensure lax.reduce monoid test uses original numpy (#3573) |
260,444 | 27.06.2020 00:19:57 | -7,200 | 42cbe49ce648f909eea9b69e2f70ae33a59ea570 | Correction a typo of the period of the PRNG. | [
{
"change_type": "MODIFY",
"old_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb",
"new_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb",
"diff": "\"id\": \"ORMVVGZJgSVi\"\n},\n\"source\": [\n- \"Underneath the hood, numpy uses the [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) PRNG to power its pseudorandom functions. The PRNG has a period of $2^{19937-1}$ and at any point can be described by __624 32bit unsigned ints__ and a __position__ indicating how much of this \\\"entropy\\\" has been used up.\"\n+ \"Underneath the hood, numpy uses the [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) PRNG to power its pseudorandom functions. The PRNG has a period of $2^{19937}-1$ and at any point can be described by __624 32bit unsigned ints__ and a __position__ indicating how much of this \\\"entropy\\\" has been used up.\"\n]\n},\n{\n"
}
] | Python | Apache License 2.0 | google/jax | Correction a typo of the period of the PRNG. (#3578) |
260,411 | 27.06.2020 14:55:28 | -10,800 | 496cde6ebcce844f6b9321ce7d73c8fbdd96532d | [jax2tf] Add special case for translation of lax.gather to tf.gather.
Also adds more tests for conversion for gather. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -902,19 +902,58 @@ def _gather_shape(operand, start_indices, dimension_numbers, slice_sizes):\nreturn out.shape\n+def _try_tf_gather(operand, start_indices, dimension_numbers, slice_sizes):\n+ # Handle only the case when batch_dims=0.\n+\n+ # Find axis to match the tf.gather semantics\n+ # Let I = len(indices_shape)\n+ # let O = len(op_shape)\n+ # slice_sizes == op_shape[:axis] + (1,) + op_shape[axis+1:]\n+ # collapsed_slice_dims == (axis,)\n+ # start_index_map == (axis,)\n+ # offset_dims == (0, 1, ..., axis - 1, axis + I, ..., O + I - 1)\n+ op_shape = np.shape(operand)\n+ assert len(op_shape) == len(slice_sizes)\n+ if not (len(op_shape) >= 1 and\n+ len(dimension_numbers.start_index_map) == 1 and\n+ len(dimension_numbers.collapsed_slice_dims) == 1 and\n+ dimension_numbers.collapsed_slice_dims[0] == dimension_numbers.start_index_map[0] and\n+ len(dimension_numbers.offset_dims) == len(op_shape) - 1):\n+ return None\n+ # We added a trailing dimension of size 1\n+ if start_indices.shape[-1] != 1:\n+ return None\n+ # Guess the axis\n+ axis = dimension_numbers.collapsed_slice_dims[0]\n+ index_dims = len(np.shape(start_indices)) - 1\n+ expected_offset_dims = tuple(\n+ list(range(axis)) +\n+ list(range(axis + index_dims, len(op_shape) + index_dims - 1)))\n+ if dimension_numbers.offset_dims != expected_offset_dims:\n+ return None\n+ expected_slice_sizes = op_shape[:axis] + (1,) + op_shape[axis + 1:]\n+ if slice_sizes != expected_slice_sizes:\n+ return None\n+ # TODO: should we allow ourselves to add a reshape, or should we strictly\n+ # convert 1:1, or go to TFXLA when not possible?\n+ start_indices = tf.reshape(start_indices, start_indices.shape[0:-1])\n+ return tf.gather(operand, start_indices, axis=axis, batch_dims=0)\n+\n+\n@functools.partial(bool_to_int8, argnums=0)\n-def _gather(operand, start_indices, dimension_numbers, slice_sizes,\n- indices_are_sorted=False):\n+def _gather(operand, start_indices, dimension_numbers, slice_sizes):\n\"\"\"Tensorflow implementation of gather.\"\"\"\n+ res = _try_tf_gather(operand, start_indices, dimension_numbers, slice_sizes)\n+ if res is not None:\n+ return res\nout_shape = _gather_shape(\noperand, start_indices, dimension_numbers, slice_sizes)\nproto = _gather_dimensions_proto(start_indices.shape, dimension_numbers)\nout, = tf.xla.experimental.compile(\n- lambda o, s: tfxla.gather(o, s, proto, slice_sizes, indices_are_sorted),\n+ lambda o, s: tfxla.gather(o, s, proto, slice_sizes, False),\n[operand, start_indices])\nout.set_shape(out_shape)\nreturn out\n-\ntf_impl[lax.gather_p] = _gather\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -25,6 +25,7 @@ from jax import config\nfrom jax import test_util as jtu\nfrom jax import dtypes\nfrom jax import lax\n+from jax import numpy as jnp\nimport numpy as np\n@@ -136,10 +137,54 @@ def parameterized(harness_group: Iterable[Harness],\nfor harness in harness_group\nif one_containing is None or one_containing in harness.name)\nif one_containing is not None:\n+ if not cases:\n+ raise ValueError(f\"Cannot find test case with name containing {one_containing}.\"\n+ \"Names are:\"\n+ \"\\n\".join([harness.name for harness in harness_group]))\ncases = cases[0:1]\nreturn testing.parameterized.named_parameters(*cases)\n+_gather_input = np.arange(1000, dtype=np.float32).reshape((10, 10, 10))\n+lax_gather = jtu.cases_from_list(\n+ # Construct gather harnesses using take\n+ [Harness(f\"from_take_indices_shape={indices.shape}_axis={axis}\",\n+ lambda a, i, axis: jnp.take(a, i, axis=axis),\n+ [_gather_input,\n+ indices,\n+ StaticArg(axis)])\n+ for indices in [\n+ np.array(2, dtype=np.int32),\n+ np.array([2], dtype=np.int32),\n+ np.array([2, 4], dtype=np.int32),\n+ np.array([[2, 4], [5, 6]], dtype=np.int32)\n+ ]\n+ for axis in [0, 1, 2]] +\n+\n+ # Directly from lax.gather in lax_test.py.\n+ [Harness(\n+ f\"_shape={shape}_idxs_shape={idxs.shape}_dnums={dnums}_slice_sizes={slice_sizes}\",\n+ lambda op, idxs, dnums, slice_sizes: lax.gather(op, idxs, dimension_numbers=dnums, slice_sizes=slice_sizes),\n+ [RandArg(shape, np.float32),\n+ idxs, StaticArg(dnums), StaticArg(slice_sizes)])\n+ for shape, idxs, dnums, slice_sizes in [\n+ ((5,), np.array([[0], [2]]), lax.GatherDimensionNumbers(\n+ offset_dims=(), collapsed_slice_dims=(0,), start_index_map=(0,)),\n+ (1,)),\n+ ((10,), np.array([[0], [0], [0]]), lax.GatherDimensionNumbers(\n+ offset_dims=(1,), collapsed_slice_dims=(), start_index_map=(0,)),\n+ (2,)),\n+ ((10, 5,), np.array([[0], [2], [1]]), lax.GatherDimensionNumbers(\n+ offset_dims=(1,), collapsed_slice_dims=(0,), start_index_map=(0,)),\n+ (1, 3)),\n+ ((10, 5), np.array([[0, 2], [1, 0]]), lax.GatherDimensionNumbers(\n+ offset_dims=(1,), collapsed_slice_dims=(0,), start_index_map=(0, 1)),\n+ (1, 3)),\n+ ]\n+ ]\n+)\n+\n+\nlax_pad = jtu.cases_from_list(\nHarness(f\"_inshape={jtu.format_shape_dtype_string(arg_shape, dtype)}_pads={pads}\",\nlax.pad,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -321,12 +321,10 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\nwith_function=True)\n- def test_gather(self):\n- values = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32)\n- indices = np.array([0, 1], dtype=np.int32)\n- for axis in (0, 1):\n- f_jax = jax.jit(lambda v, i: jnp.take(v, i, axis=axis)) # pylint: disable=cell-var-from-loop\n- self.ConvertAndCompare(f_jax, values, indices, with_function=True)\n+ @primitive_harness.parameterized(primitive_harness.lax_gather)\n+ def test_gather(self, harness: primitive_harness.Harness):\n+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()),\n+ with_function=False)\ndef test_boolean_gather(self):\nvalues = np.array([[True, True], [False, True], [False, False]],\n@@ -336,6 +334,12 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nf_jax = jax.jit(lambda v, i: jnp.take(v, i, axis=axis)) # pylint: disable=cell-var-from-loop\nself.ConvertAndCompare(f_jax, values, indices, with_function=True)\n+ def test_gather_rank_change(self):\n+ params = jnp.array([[1.0, 1.5, 2.0], [2.0, 2.5, 3.0], [3.0, 3.5, 4.0]])\n+ indices = jnp.array([[1, 1, 2], [0, 1, 0]])\n+ f_jax = jax.jit(lambda i: params[i])\n+ self.ConvertAndCompare(f_jax, indices, with_function=True)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_{f_jax.__name__}\",\nf_jax=f_jax)\n@@ -370,11 +374,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nvalues = np.array([True, False, True], dtype=np.bool_)\nself.ConvertAndCompare(f_jax, values, with_function=True)\n- def test_gather_rank_change(self):\n- params = jnp.array([[1.0, 1.5, 2.0], [2.0, 2.5, 3.0], [3.0, 3.5, 4.0]])\n- indices = jnp.array([[1, 1, 2], [0, 1, 0]])\n- f_jax = jax.jit(lambda i: params[i])\n- self.ConvertAndCompare(f_jax, indices, with_function=True)\ndef test_prngsplit(self):\nf_jax = jax.jit(lambda key: jax.random.split(key, 2))\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Add special case for translation of lax.gather to tf.gather. (#3486)
Also adds more tests for conversion for gather. |
260,530 | 28.06.2020 12:11:12 | 14,400 | 7b57dc8c8043163a5e649ba66143ccef880d7d58 | Issue1635 expm frechet
* Implement Frechet derivatives for expm.
* Update expm to use the current custom gradients API.
Make some stylistic fixes. | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.scipy.rst",
"new_path": "docs/jax.scipy.rst",
"diff": "@@ -16,6 +16,7 @@ jax.scipy.linalg\ndet\neigh\nexpm\n+ expm_frechet\ninv\nlu\nlu_factor\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/linalg.py",
"new_path": "jax/scipy/linalg.py",
"diff": "@@ -19,6 +19,7 @@ import scipy.linalg\nimport textwrap\nfrom jax import jit, vmap\n+from .. import api\nfrom .. import lax\nfrom .. import lax_linalg\nfrom ..numpy._util import _wraps\n@@ -232,15 +233,18 @@ def tril(m, k=0):\ndef triu(m, k=0):\nreturn jnp.triu(m, k)\n-@_wraps(scipy.linalg.expm, lax_description=textwrap.dedent(\"\"\"\\\n+_expm_description = textwrap.dedent(\"\"\"\nIn addition to the original NumPy argument(s) listed below,\nalso supports the optional boolean argument ``upper_triangular``\nto specify whether the ``A`` matrix is upper triangular.\n- \"\"\"))\n+\"\"\")\n+\n+@_wraps(scipy.linalg.expm, lax_description=_expm_description)\ndef expm(A, *, upper_triangular=False):\nreturn _expm(A, upper_triangular)\n-def _expm(A, upper_triangular=False):\n+@partial(api.custom_jvp, nondiff_argnums=(1,))\n+def _expm(A, upper_triangular):\nP, Q, n_squarings = _calc_P_Q(A)\nR = _solve_P_Q(P, Q, upper_triangular)\nR = _squaring(R, n_squarings)\n@@ -262,7 +266,8 @@ def _calc_P_Q(A):\nn_squarings = jnp.maximum(0, jnp.floor(jnp.log2(A_L1 / maxnorm)))\nA = A / 2**n_squarings\nU13, V13 = _pade13(A)\n- conds=jnp.array([1.495585217958292e-002, 2.539398330063230e-001, 9.504178996162932e-001, 2.097847961257068e+000])\n+ conds=jnp.array([1.495585217958292e-002, 2.539398330063230e-001,\n+ 9.504178996162932e-001, 2.097847961257068e+000])\nU = jnp.select((maxnorm<conds), (U3, U5, U7, U9), U13)\nV = jnp.select((maxnorm<conds), (V3, V5, V7, V9), V13)\nelif A.dtype == 'float32' or A.dtype == 'complex64':\n@@ -348,6 +353,220 @@ def _pade13(A):\nreturn U,V\n+_expm_frechet_description = textwrap.dedent(\"\"\"\n+Does not currently support the Scipy argument ``jax.numpy.asarray_chkfinite``,\n+because `jax.numpy.asarray_chkfinite` does not exist at the moment. Does not\n+support the ``method='blockEnlarge'`` argument.\n+\"\"\")\n+\n+@_wraps(scipy.linalg.expm_frechet, lax_description=_expm_frechet_description)\n+def expm_frechet(A, E, *, method=None, compute_expm=True):\n+ return _expm_frechet(A, E, method, compute_expm)\n+\n+def _expm_frechet(A, E, method=None, compute_expm=True):\n+ A = jnp.asarray(A)\n+ E = jnp.asarray(E)\n+ if A.ndim != 2 or A.shape[0] != A.shape[1]:\n+ raise ValueError('expected A to be a square matrix')\n+ if E.ndim != 2 or E.shape[0] != E.shape[1]:\n+ raise ValueError('expected E to be a square matrix')\n+ if A.shape != E.shape:\n+ raise ValueError('expected A and E to be the same shape')\n+ if method is None:\n+ method = 'SPS'\n+ if method == 'SPS':\n+ expm_A, expm_frechet_AE = expm_frechet_algo_64(A, E)\n+ else:\n+ raise ValueError('only method=\\'SPS\\' is supported')\n+ expm_A, expm_frechet_AE = expm_frechet_algo_64(A, E)\n+ if compute_expm:\n+ return expm_A, expm_frechet_AE\n+ else:\n+ return expm_frechet_AE\n+\n+\"\"\"\n+Maximal values ell_m of ||2**-s A|| such that the backward error bound\n+does not exceed 2**-53.\n+\"\"\"\n+ell_table_61 = (\n+ None,\n+ # 1\n+ 2.11e-8,\n+ 3.56e-4,\n+ 1.08e-2,\n+ 6.49e-2,\n+ 2.00e-1,\n+ 4.37e-1,\n+ 7.83e-1,\n+ 1.23e0,\n+ 1.78e0,\n+ 2.42e0,\n+ # 11\n+ 3.13e0,\n+ 3.90e0,\n+ 4.74e0,\n+ 5.63e0,\n+ 6.56e0,\n+ 7.52e0,\n+ 8.53e0,\n+ 9.56e0,\n+ 1.06e1,\n+ 1.17e1,\n+)\n+\n+@jit\n+def expm_frechet_algo_64(A, E):\n+ ident = jnp.eye(*A.shape, dtype=A.dtype)\n+ A_norm_1 = np_linalg.norm(A, 1)\n+ \"\"\"\n+ Subset of the Maximal values ell_m of ||2**-s A||\n+ such that the backward error bound does not exceed 2**-53.\n+ \"\"\"\n+ args = (A, E, ident, A_norm_1)\n+ U3579, V3579, Lu3579, Lv3579, s3579 = lax.cond(A_norm_1 <= ell_table_61[3],\n+ args, lambda args: _diff_pade3(args),\n+ args, lambda args: lax.cond(A_norm_1 <= ell_table_61[5],\n+ args, lambda args: _diff_pade5(args),\n+ args, lambda args: lax.cond(A_norm_1 <= ell_table_61[7],\n+ args, lambda args: _diff_pade7(args),\n+ args, lambda args: _diff_pade9(args))))\n+ U13, V13, Lu13, Lv13, s13 = _diff_pade13(args)\n+\n+ # Must be of minimum length 2 for np.select to be used\n+ ell_table_61_local99 = jnp.array([ell_table_61[9], ell_table_61[9]])\n+ U = jnp.select((A_norm_1<=ell_table_61_local99), (U3579, U3579), U13)\n+ V = jnp.select((A_norm_1<=ell_table_61_local99), (V3579, V3579), V13)\n+ Lu = jnp.select((A_norm_1<=ell_table_61_local99), (Lu3579, Lu3579), Lu13)\n+ Lv = jnp.select((A_norm_1<=ell_table_61_local99), (Lv3579, Lv3579), Lv13)\n+ s = jnp.select((A_norm_1<=ell_table_61_local99), (s3579, s3579), s13)\n+\n+ lu_piv = lu_factor(-U + V)\n+ R = lu_solve(lu_piv, U + V)\n+ L = lu_solve(lu_piv, Lu + Lv + jnp.dot((Lu - Lv), R))\n+ # squaring\n+ def my_body_fun(i,my_arg):\n+ R, L = my_arg\n+ L = jnp.dot(R, L) + jnp.dot(L, R)\n+ R = jnp.dot(R, R)\n+ return R, L\n+ lower = jnp.zeros(1, dtype=s.dtype)\n+ R, L = lax.fori_loop(lower[0], s, my_body_fun, (R, L))\n+ return R, L\n+\n+\"\"\"\n+# The b vectors and U and V are those from\n+# scipy.sparse.linalg.matfuncs.py.\n+# M, Lu, Lv follow (6.11), (6.12), (6.13), (3.3)\n+\"\"\"\n+@jit\n+def _diff_pade3(args):\n+ A,E,ident,_ = args\n+ s = 0\n+ b = (120., 60., 12., 1.)\n+ A2 = A.dot(A)\n+ M2 = jnp.dot(A, E) + jnp.dot(E, A)\n+ U = A.dot(b[3]*A2 + b[1]*ident)\n+ V = b[2]*A2 + b[0]*ident\n+ Lu = A.dot(b[3]*M2) + E.dot(b[3]*A2 + b[1]*ident)\n+ Lv = b[2]*M2\n+ return U, V, Lu, Lv, s\n+\n+@jit\n+def _diff_pade5(args):\n+ A,E,ident,_ = args\n+ s = 0\n+ b = (30240., 15120., 3360., 420., 30., 1.)\n+ A2 = A.dot(A)\n+ M2 = jnp.dot(A, E) + jnp.dot(E, A)\n+ A4 = jnp.dot(A2, A2)\n+ M4 = jnp.dot(A2, M2) + jnp.dot(M2, A2)\n+ U = A.dot(b[5]*A4 + b[3]*A2 + b[1]*ident)\n+ V = b[4]*A4 + b[2]*A2 + b[0]*ident\n+ Lu = (A.dot(b[5]*M4 + b[3]*M2) +\n+ E.dot(b[5]*A4 + b[3]*A2 + b[1]*ident))\n+ Lv = b[4]*M4 + b[2]*M2\n+ return U, V, Lu, Lv, s\n+\n+@jit\n+def _diff_pade7(args):\n+ A, E, ident, _ = args\n+ s = 0\n+ b = (17297280., 8648640., 1995840., 277200., 25200., 1512., 56., 1.)\n+ A2 = A.dot(A)\n+ M2 = jnp.dot(A, E) + jnp.dot(E, A)\n+ A4 = jnp.dot(A2, A2)\n+ M4 = jnp.dot(A2, M2) + jnp.dot(M2, A2)\n+ A6 = jnp.dot(A2, A4)\n+ M6 = jnp.dot(A4, M2) + jnp.dot(M4, A2)\n+ U = A.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)\n+ V = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident\n+ Lu = (A.dot(b[7]*M6 + b[5]*M4 + b[3]*M2) +\n+ E.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))\n+ Lv = b[6]*M6 + b[4]*M4 + b[2]*M2\n+ return U, V, Lu, Lv, s\n+\n+@jit\n+def _diff_pade9(args):\n+ A,E,ident,_ = args\n+ s = 0\n+ b = (17643225600., 8821612800., 2075673600., 302702400., 30270240., 2162160.,\n+ 110880., 3960., 90., 1.)\n+ A2 = A.dot(A)\n+ M2 = jnp.dot(A, E) + jnp.dot(E, A)\n+ A4 = jnp.dot(A2, A2)\n+ M4 = jnp.dot(A2, M2) + jnp.dot(M2, A2)\n+ A6 = jnp.dot(A2, A4)\n+ M6 = jnp.dot(A4, M2) + jnp.dot(M4, A2)\n+ A8 = jnp.dot(A4, A4)\n+ M8 = jnp.dot(A4, M4) + jnp.dot(M4, A4)\n+ U = A.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)\n+ V = b[8]*A8 + b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident\n+ Lu = (A.dot(b[9]*M8 + b[7]*M6 + b[5]*M4 + b[3]*M2) +\n+ E.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))\n+ Lv = b[8]*M8 + b[6]*M6 + b[4]*M4 + b[2]*M2\n+ return U, V, Lu, Lv, s\n+\n+@jit\n+def _diff_pade13(args):\n+ A,E,ident,A_norm_1 = args\n+ s = jnp.maximum(0, jnp.floor_divide(lax.ceil(jnp.log2(A_norm_1 / ell_table_61[13])), 1))\n+ two = jnp.array([2.0],A.dtype)\n+ A = A * two[0]**-s\n+ E = E * two[0]**-s\n+ # pade order 13\n+ A2 = jnp.dot(A, A)\n+ M2 = jnp.dot(A, E) + jnp.dot(E, A)\n+ A4 = jnp.dot(A2, A2)\n+ M4 = jnp.dot(A2, M2) + jnp.dot(M2, A2)\n+ A6 = jnp.dot(A2, A4)\n+ M6 = jnp.dot(A4, M2) + jnp.dot(M4, A2)\n+ b = (64764752532480000., 32382376266240000., 7771770303897600.,\n+ 1187353796428800., 129060195264000., 10559470521600.,\n+ 670442572800., 33522128640., 1323241920., 40840800., 960960.,\n+ 16380., 182., 1.)\n+ W1 = b[13]*A6 + b[11]*A4 + b[9]*A2\n+ W2 = b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident\n+ Z1 = b[12]*A6 + b[10]*A4 + b[8]*A2\n+ Z2 = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident\n+ W = jnp.dot(A6, W1) + W2\n+ U = jnp.dot(A, W)\n+ V = jnp.dot(A6, Z1) + Z2\n+ Lw1 = b[13]*M6 + b[11]*M4 + b[9]*M2\n+ Lw2 = b[7]*M6 + b[5]*M4 + b[3]*M2\n+ Lz1 = b[12]*M6 + b[10]*M4 + b[8]*M2\n+ Lz2 = b[6]*M6 + b[4]*M4 + b[2]*M2\n+ Lw = jnp.dot(A6, Lw1) + jnp.dot(M6, W1) + Lw2\n+ Lu = jnp.dot(A, Lw) + jnp.dot(E, W)\n+ Lv = jnp.dot(A6, Lz1) + jnp.dot(M6, Z1) + Lz2\n+ return U, V, Lu, Lv, s\n+\n+@_expm.defjvp\n+def _expm_jvp(upper_triangular, primals, tangents):\n+ matrix, = primals\n+ g, = tangents\n+ return expm_frechet(matrix, g, compute_expm=True)\n+\n+\n@_wraps(scipy.linalg.block_diag)\n@jit\ndef block_diag(*arrs):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -1282,5 +1282,43 @@ class ScipyLinalgTest(jtu.JaxTestCase):\nargs_maker, tol=1e-3)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_n={}\".format(jtu.format_shape_dtype_string((n,n), dtype)),\n+ \"n\": n, \"dtype\": dtype, \"rng_factory\": rng_factory}\n+ for n in [1, 4, 5, 20, 50, 100]\n+ for dtype in float_types + complex_types\n+ for rng_factory in [jtu.rand_small]))\n+ def testExpmFrechet(self, n, dtype, rng_factory):\n+ rng = rng_factory(self.rng())\n+ _skip_if_unsupported_type(dtype)\n+ args_maker = lambda: [rng((n, n), dtype), rng((n, n), dtype),]\n+\n+ #compute_expm is True\n+ osp_fun = lambda a,e: osp.linalg.expm_frechet(a,e,compute_expm=True)\n+ jsp_fun = lambda a,e: jsp.linalg.expm_frechet(a,e,compute_expm=True)\n+ self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker,\n+ check_dtypes=False)\n+ self._CompileAndCheck(jsp_fun, args_maker, check_dtypes=False)\n+ #compute_expm is False\n+ osp_fun = lambda a,e: osp.linalg.expm_frechet(a,e,compute_expm=False)\n+ jsp_fun = lambda a,e: jsp.linalg.expm_frechet(a,e,compute_expm=False)\n+ self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker,\n+ check_dtypes=False)\n+ self._CompileAndCheck(jsp_fun, args_maker, check_dtypes=False)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_n={}\".format(jtu.format_shape_dtype_string((n,n), dtype)),\n+ \"n\": n, \"dtype\": dtype, \"rng_factory\": rng_factory}\n+ for n in [1, 4, 5, 20, 50]\n+ for dtype in float_types + complex_types\n+ for rng_factory in [jtu.rand_small]))\n+ def testExpmGrad(self, n, dtype, rng_factory):\n+ rng = rng_factory(self.rng())\n+ _skip_if_unsupported_type(dtype)\n+ a = rng((n, n), dtype)\n+ jtu.check_grads(jsp.linalg.expm, (a,), modes=[\"fwd\"], order=1)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
}
] | Python | Apache License 2.0 | google/jax | Issue1635 expm frechet (#2062)
* Implement Frechet derivatives for expm.
* Update expm to use the current custom gradients API.
Make some stylistic fixes.
Co-authored-by: Peter Hawkins <phawkins@google.com> |
260,411 | 29.06.2020 12:48:27 | -10,800 | 6147026b81bc1a2754cc40bd1de58961a8929c4a | [jax2tf] Add support for custom JVP/VJP
* [jax2tf] Add support for custom JVP/VJP
The custom VJP/JVP in initial style control-flow primitives make
use of special custom_jvp_call_jaxpr primitives
* Fix flake | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -80,13 +80,20 @@ def _tfval_remove_unit(args: Sequence[TfValOrUnit]) -> Sequence[TfVal]:\ndef _tfval_add_unit(vals: Sequence[TfValOrUnit],\navals: Sequence[core.AbstractValue]) -> Sequence[TfValOrUnit]:\n\"\"\"Turn regular TfVals into TfValOrUnit, based on expected abstract values.\n- This function is sometimes called with a mix of core.unit and tf.nan in places\n- of units.\n+ When the aval is a unit, the corresponding value is either core.unit,\n+ or an EagerTensor with the value NaN (we use tf.nan as a concrete TF value\n+ for units, see _tfval_remove_unit) or may even be a Tensor if we are building\n+ graphs and the NaN value is abstracted.\n\"\"\"\ndef add_unit(v: TfValOrUnit, aval: core.AbstractValue):\nif not core.skip_checks:\n- assert ((v is core.unit or tf.math.is_nan(v))\n- if aval is core.abstract_unit else _is_tfval(v))\n+ if aval is core.abstract_unit:\n+ if v is not core.unit:\n+ assert isinstance(v, tf.Tensor)\n+ if v.device: # Only for EagerTensor\n+ assert tf.math.is_nan(v)\n+ else:\n+ assert _is_tfval(v)\nreturn core.unit if aval is core.abstract_unit else v\nreturn util.safe_map(add_unit, vals, avals)\n@@ -124,7 +131,7 @@ def disable_gradient(fun):\ndef grad_disabled(*dy, variables=None):\nraise ValueError(\"jax2tf currently does not support gradients. Please \"\n- \"reach out to tomhennigan@ if this feature is a blocker \"\n+ \"reach out to jax-core@ if this feature is a blocker \"\n\"for you, we are working on it!\")\nis_tensor = lambda t: isinstance(t, (tf.Tensor, tf.Variable))\n@@ -355,8 +362,6 @@ for unexpected in [\n# Primitives that are not yet implemented must be explicitly declared here.\ntf_not_yet_impl = [\n- ad.custom_lin_p,\n-\nlax.after_all_p, lax.all_to_all_p, lax.create_token_p, lax_fft.fft_p,\nlax.igamma_grad_a_p, lax.infeed_p, lax.linear_solve_p, lax.outfeed_p,\nlax.sort_p, lax.pmax_p, lax.pmin_p, lax.ppermute_p, lax.psum_p,\n@@ -369,9 +374,6 @@ tf_not_yet_impl = [\nlax_linalg.lu_p, lax_linalg.qr_p, lax_linalg.svd_p,\nlax_linalg.triangular_solve_p,\n- custom_derivatives.custom_jvp_call_jaxpr_p,\n- custom_derivatives.custom_vjp_call_jaxpr_p,\n-\nrandom.random_gamma_p,\nlax.random_gamma_grad_p,\npe.remat_call_p,\n@@ -1090,6 +1092,30 @@ def _scan(*tf_args : TfValOrUnit, **kwargs) -> Sequence[TfValOrUnit]:\ntf_impl[lax.scan_p] = _scan\n+def _custom_jvp_call_jaxpr(*args: TfValOrUnit,\n+ fun_jaxpr: core.TypedJaxpr,\n+ jvp_jaxpr_thunk: Callable) -> Sequence[TfValOrUnit]:\n+ # TODO(necula): ensure that there is no AD transformation in scope\n+ res = _interpret_jaxpr(fun_jaxpr, *args)\n+ return _tfval_add_unit(res, fun_jaxpr.out_avals)\n+\n+tf_impl[custom_derivatives.custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr\n+\n+\n+def _custom_vjp_call_jaxpr(*args: TfValOrUnit,\n+ fun_jaxpr: core.TypedJaxpr,\n+ **_) -> Sequence[TfValOrUnit]:\n+ # TODO(necula): ensure that there is no AD transformation in scope\n+ res = _interpret_jaxpr(fun_jaxpr, *args)\n+ return _tfval_add_unit(res, fun_jaxpr.out_avals)\n+\n+tf_impl[custom_derivatives.custom_vjp_call_jaxpr_p] = _custom_vjp_call_jaxpr\n+\n+def _custom_lin(*args: TfValOrUnit, **_) -> Sequence[TfValOrUnit]:\n+ raise TypeError(\"can't apply forward-mode autodiff (jvp) to a custom_vjp \"\n+ \"function.\")\n+\n+tf_impl[ad.custom_lin_p] = _custom_lin\ndef _register_checkpoint_pytrees():\n\"\"\"Registers TF custom container types as pytrees.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"new_path": "jax/experimental/jax2tf/tests/control_flow_ops_test.py",
"diff": "@@ -62,6 +62,72 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\nwith jax2tf.enable_jit():\nself.ConvertAndCompare(jax.grad(f), 1.)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"_function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\n+ def test_cond_units(self, with_function=True):\n+ def g(x):\n+ return lax.cond(True, lambda x: x, lambda y: y, x)\n+\n+ with jax2tf.enable_jit():\n+ self.ConvertAndCompare(g, 0.7, with_function=with_function)\n+ self.ConvertAndCompare(jax.grad(g), 0.7, with_function=with_function)\n+\n+\n+ def test_cond_custom_jvp(self):\n+ \"\"\"Conversion of function with custom JVP, inside cond.\n+ This exercises the custom_jvp_call_jaxpr primitives.\"\"\"\n+ @jax.custom_jvp\n+ def f(x):\n+ return x * x\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ x_dot, = tangents\n+ primal_out = f(x)\n+ tangent_out = 3. * x * x_dot\n+ return primal_out, tangent_out\n+\n+ def g(x):\n+ return lax.cond(True, f, lambda y: y, x)\n+\n+ with jax2tf.enable_jit():\n+ arg = 0.7\n+ self.TransformConvertAndCompare(g, arg, None)\n+ self.TransformConvertAndCompare(g, arg, \"jvp\")\n+ self.TransformConvertAndCompare(g, arg, \"vmap\")\n+ self.TransformConvertAndCompare(g, arg, \"jvp_vmap\")\n+ self.TransformConvertAndCompare(g, arg, \"grad\")\n+ self.TransformConvertAndCompare(g, arg, \"grad_vmap\")\n+\n+\n+ def test_cond_custom_vjp(self):\n+ \"\"\"Conversion of function with custom VJP, inside cond.\n+ This exercises the custom_vjp_call_jaxpr primitives.\"\"\"\n+ @jax.custom_vjp\n+ def f(x):\n+ return x * x\n+\n+ # f_fwd: a -> (b, residual)\n+ def f_fwd(x):\n+ return f(x), 3. * x\n+ # f_bwd: (residual, CT b) -> [CT a]\n+ def f_bwd(residual, ct_b):\n+ return residual * ct_b,\n+\n+ f.defvjp(f_fwd, f_bwd)\n+\n+ def g(x):\n+ return lax.cond(True, f, lambda y: y, x)\n+\n+ with jax2tf.enable_jit():\n+ arg = 0.7\n+ self.TransformConvertAndCompare(g, arg, None)\n+ self.TransformConvertAndCompare(g, arg, \"vmap\")\n+ self.TransformConvertAndCompare(g, arg, \"grad_vmap\")\n+\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_function={with_function}\",\nwith_function=with_function)\n@@ -136,6 +202,34 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\nwith jax2tf.enable_jit():\nself.ConvertAndCompare(product_xs_ys, xs, ys, with_function=with_function)\n+ def test_while_custom_jvp(self):\n+ \"\"\"Conversion of function with custom JVP, inside while.\n+ This exercises the custom_jvp_call_jaxpr primitives.\"\"\"\n+ @jax.custom_jvp\n+ def f(x):\n+ return x * x\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ x_dot, = tangents\n+ primal_out = f(x)\n+ tangent_out = 3. * x * x_dot\n+ return primal_out, tangent_out\n+\n+ def g(x):\n+ return lax.while_loop(lambda carry: carry[0] < 10,\n+ lambda carry: (carry[0] + 1, f(carry[1])),\n+ (0, x))\n+\n+ with jax2tf.enable_jit():\n+ arg = 0.7\n+ self.TransformConvertAndCompare(g, arg, None)\n+ self.TransformConvertAndCompare(g, arg, \"jvp\")\n+ self.TransformConvertAndCompare(g, arg, \"vmap\")\n+ self.TransformConvertAndCompare(g, arg, \"jvp_vmap\")\n+\n+\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_function={with_function}\",\nwith_function=with_function)\n@@ -167,5 +261,63 @@ class ControlFlowOpsTest(tf_test_util.JaxToTfTestCase):\nself.ConvertAndCompare(jax.grad(f_jax), arg, arg, with_function=with_function)\n+ def test_scan_custom_jvp(self):\n+ \"\"\"Conversion of function with custom JVP, inside scan.\n+ This exercises the custom_jvp_call_jaxpr primitives.\"\"\"\n+ @jax.custom_jvp\n+ def f(x):\n+ return x * x\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ x_dot, = tangents\n+ primal_out = f(x)\n+ tangent_out = 3. * x * x_dot\n+ return primal_out, tangent_out\n+\n+ def g(x):\n+ return lax.scan(lambda carry, inp: (carry + f(inp), 0.),\n+ np.full(x.shape[1:], 0.), # Like x w/o leading dim\n+ x)[0]\n+\n+ with jax2tf.enable_jit():\n+ arg = np.full((5,), 0.7)\n+ self.TransformConvertAndCompare(g, arg, None)\n+ self.TransformConvertAndCompare(g, arg, \"jvp\")\n+ self.TransformConvertAndCompare(g, arg, \"vmap\")\n+ self.TransformConvertAndCompare(g, arg, \"jvp_vmap\")\n+ self.TransformConvertAndCompare(g, arg, \"grad\")\n+ self.TransformConvertAndCompare(g, arg, \"grad_vmap\")\n+\n+ def test_scan_custom_vjp(self):\n+ \"\"\"Conversion of function with custom VJP, inside scan.\n+ This exercises the custom_vjp_call_jaxpr primitives.\"\"\"\n+ @jax.custom_vjp\n+ def f(x):\n+ return x * x\n+\n+ # f_fwd: a -> (b, residual)\n+ def f_fwd(x):\n+ return f(x), 3. * x\n+ # f_bwd: (residual, CT b) -> [CT a]\n+ def f_bwd(residual, ct_b):\n+ return residual * ct_b,\n+\n+ f.defvjp(f_fwd, f_bwd)\n+\n+ def g(x):\n+ return lax.scan(lambda carry, inp: (carry + f(inp), 0.),\n+ np.full(x.shape[1:], 0.), # Like x w/o leading dim\n+ x)[0]\n+\n+ with jax2tf.enable_jit():\n+ arg = np.full((5,), 0.7)\n+ self.TransformConvertAndCompare(g, arg, None)\n+ self.TransformConvertAndCompare(g, arg, \"vmap\")\n+ self.TransformConvertAndCompare(g, arg, \"grad\")\n+ self.TransformConvertAndCompare(g, arg, \"grad_vmap\")\n+\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -127,6 +127,48 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.assertLen(jax.tree_leaves(m.b), 2)\nself.assertLen(jax.tree_leaves(m.c), 2)\n+ def test_custom_jvp(self):\n+ \"\"\"Conversion of function with custom JVP\"\"\"\n+ @jax.custom_jvp\n+ def f(x):\n+ return x * x\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ x_dot, = tangents\n+ primal_out = f(x)\n+ tangent_out = 3. * x * x_dot\n+ return primal_out, tangent_out\n+\n+ arg = 0.7\n+ self.TransformConvertAndCompare(f, arg, None, with_function=True)\n+ self.TransformConvertAndCompare(f, arg, \"jvp\", with_function=True)\n+ self.TransformConvertAndCompare(f, arg, \"vmap\", with_function=True)\n+ self.TransformConvertAndCompare(f, arg, \"jvp_vmap\", with_function=True)\n+ self.TransformConvertAndCompare(f, arg, \"grad\", with_function=True)\n+ self.TransformConvertAndCompare(f, arg, \"grad_vmap\", with_function=True)\n+\n+ def test_custom_vjp(self):\n+ \"\"\"Conversion of function with custom VJP\"\"\"\n+ @jax.custom_vjp\n+ def f(x):\n+ return x * x\n+\n+ # f_fwd: a -> (b, residual)\n+ def f_fwd(x):\n+ return f(x), 3. * x\n+ # f_bwd: (residual, CT b) -> [CT a]\n+ def f_bwd(residual, ct_b):\n+ return residual * ct_b,\n+\n+ f.defvjp(f_fwd, f_bwd)\n+ arg = 0.7\n+ self.TransformConvertAndCompare(f, arg, None, with_function=True)\n+ self.TransformConvertAndCompare(f, arg, \"vmap\", with_function=True)\n+ self.TransformConvertAndCompare(f, arg, \"grad\", with_function=True)\n+ self.TransformConvertAndCompare(f, arg, \"grad_vmap\", with_function=True)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"new_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"diff": "import contextlib\nimport logging\nimport numpy as np\n-from typing import Any, Callable, Tuple\n+from typing import Any, Callable, Optional, Tuple\nimport tensorflow as tf # type: ignore[import]\n+import jax\nfrom jax.config import config\nfrom jax import dtypes\nfrom jax.experimental import jax2tf\nfrom jax import test_util as jtu\n+from jax import numpy as jnp\nclass JaxToTfTestCase(jtu.JaxTestCase):\n@@ -64,10 +66,47 @@ class JaxToTfTestCase(jtu.JaxTestCase):\n\"\"\"Compares jax_func(*args) with convert(jax_func)(*args).\"\"\"\nfunc_tf = jax2tf.convert(func_jax)\nif with_function:\n- func_tf = tf.function(func_tf)\n+ func_tf = tf.function(func_tf, autograph=False)\nres_jax = func_jax(*args)\n#logging.info(f\"res_jax is {res_jax} on {res_jax.device_buffer.device()}\")\nres_tf = func_tf(*args)\n#logging.info(f\"res_tf is {res_tf} on {res_tf.backing_device}\")\nself.assertAllClose(res_jax, res_tf, atol=atol, rtol=rtol)\nreturn (res_jax, res_tf)\n+\n+ def TransformConvertAndCompare(self, func: Callable,\n+ arg,\n+ transform: Optional[str],\n+ with_function: bool = False):\n+ \"\"\"Like ConvertAndCompare but first applies a transformation.\n+\n+ `func` must be a function from one argument to one result. `arg` is\n+ the argument before the transformation.\n+\n+ `transform` can be None, \"jvp\", \"grad\", \"vmap\", \"jvp_vmap\", \"grad_vmap\"\n+ \"\"\"\n+ if transform is None:\n+ return self.ConvertAndCompare(func, arg, with_function=with_function)\n+ if transform == \"jvp\":\n+ t_func = lambda x, xt: jax.jvp(func, (x,), (xt,))\n+ return self.ConvertAndCompare(t_func, arg, np.full_like(arg, 0.1),\n+ with_function=with_function)\n+ if transform == \"grad\":\n+ return self.ConvertAndCompare(jax.grad(func), arg,\n+ with_function=with_function)\n+ if transform == \"vmap\":\n+ t_arg = np.stack([arg] * 4)\n+ return self.ConvertAndCompare(jax.vmap(func),\n+ t_arg, with_function=with_function)\n+ if transform == \"jvp_vmap\":\n+ jvp_func = lambda x, xt: jax.jvp(jax.vmap(func), (x,), (xt,))\n+ t_arg = np.stack([arg] * 4)\n+ return self.ConvertAndCompare(jvp_func, t_arg,\n+ np.full_like(t_arg, 0.1),\n+ with_function=with_function)\n+ if transform == \"grad_vmap\":\n+ grad_func = jax.grad(lambda x: jnp.sum(jax.vmap(func)(x)))\n+ t_arg = np.stack([arg] * 4)\n+ return self.ConvertAndCompare(grad_func, t_arg,\n+ with_function=with_function)\n+ assert False, transform\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Add support for custom JVP/VJP (#3581)
* [jax2tf] Add support for custom JVP/VJP
The custom VJP/JVP in initial style control-flow primitives make
use of special custom_jvp_call_jaxpr primitives
* Fix flake |
260,411 | 30.06.2020 10:12:22 | -10,800 | 59344028c85ed0c8fad20b052275b572c2d60785 | [jax2tf] Fix tf.gather handling of out-of-bounds indices
JAX and XLA clamp out-of-bounds indices, while tf.gather aborts. We
ensure that when we rewrite lax.gather to tf.gather, we use XLA. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -938,9 +938,14 @@ def _try_tf_gather(operand, start_indices, dimension_numbers, slice_sizes):\nreturn None\n# TODO: should we allow ourselves to add a reshape, or should we strictly\n# convert 1:1, or go to TFXLA when not possible?\n- start_indices = tf.reshape(start_indices, start_indices.shape[0:-1])\n- return tf.gather(operand, start_indices, axis=axis, batch_dims=0)\n-\n+ start_indices_reshaped = tf.reshape(start_indices, start_indices.shape[0:-1])\n+ # We do not use tf.gather directly because in the non-compiled version it\n+ # rejects indices that are out of bounds, while JAX and XLA clamps them.\n+ # We fix this by ensuring that we always compile tf.gather, to use XLA.\n+ out, = tf.xla.experimental.compile(\n+ lambda o, s: tf.gather(o, s, axis=axis, batch_dims=0),\n+ [operand, start_indices_reshaped])\n+ return out\n@functools.partial(bool_to_int8, argnums=0)\ndef _gather(operand, start_indices, dimension_numbers, slice_sizes):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -154,10 +154,13 @@ lax_gather = jtu.cases_from_list(\nindices,\nStaticArg(axis)])\nfor indices in [\n+ # Ensure each set of indices has a distinct shape\nnp.array(2, dtype=np.int32),\nnp.array([2], dtype=np.int32),\nnp.array([2, 4], dtype=np.int32),\n- np.array([[2, 4], [5, 6]], dtype=np.int32)\n+ np.array([[2, 4], [5, 6]], dtype=np.int32),\n+ np.array([0, 1, 10], dtype=np.int32), # Index out of bounds\n+ np.array([0, 1, 2, -1], dtype=np.int32), # Index out of bounds\n]\nfor axis in [0, 1, 2]] +\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix tf.gather handling of out-of-bounds indices (#3604)
JAX and XLA clamp out-of-bounds indices, while tf.gather aborts. We
ensure that when we rewrite lax.gather to tf.gather, we use XLA. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.