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
27.02.2020 08:00:34
28,800
7adf9fe84f5b522ee9120a7ff7763ea0708fc394
add more jet rules!
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1870,20 +1870,6 @@ ad.primitive_transposes[sub_p] = _sub_transpose\nmul_p = standard_naryop([_num, _num], 'mul')\nad.defbilinear_broadcasting(_brcast, mul_p, mul, mul)\n-def _mul_taylor(primals_in, series_in):\n- x, y = primals_in\n- x_terms, y_terms = series_in\n- u = [x] + x_terms\n- w = [y] + y_terms\n- v = [None] * len(u)\n- def scale(k, j): return 1. / (fact(k - j) * fact(j))\n- for k in range(0, len(v)):\n- v[k] = fact(k) * sum([scale(k, j) * u[j] * w[k-j] for j in range(0, k+1)])\n- primal_out, *series_out = v\n- return primal_out, series_out\n-taylor.prop_rules[mul_p] = _mul_taylor\n-\n-\ndef _safe_mul_translation_rule(c, x, y):\ndtype = c.GetShape(x).numpy_dtype()\nzero = c.Constant(onp.array(0, dtype=dtype))\n@@ -2355,20 +2341,21 @@ ad.defbilinear(dot_general_p,\nbatching.primitive_batchers[dot_general_p] = _dot_general_batch_rule\nmasking.masking_rules[dot_general_p] = _dot_general_masking_rule\n-# TODO factor out a bilinear rule (mul, dot, conv, ...)\n-def _dot_general_taylor(primals_in, series_in, **params):\n+def _bilinear_taylor_rule(prim, primals_in, series_in, **params):\nx, y = primals_in\nx_terms, y_terms = series_in\nu = [x] + x_terms\nw = [y] + y_terms\nv = [None] * len(u)\n- dot = partial(dot_general_p.bind, **params)\n+ op = partial(prim.bind, **params)\ndef scale(k, j): return 1. / (fact(k - j) * fact(j))\nfor k in range(0, len(v)):\n- v[k] = fact(k) * sum([scale(k, j) * dot(u[j], w[k-j]) for j in range(0, k+1)])\n+ v[k] = fact(k) * sum([scale(k, j) * op(u[j], w[k-j]) for j in range(0, k+1)])\nprimal_out, *series_out = v\nreturn primal_out, series_out\n-taylor.prop_rules[dot_general_p] = _dot_general_taylor\n+taylor.prop_rules[dot_general_p] = partial(_bilinear_taylor_rule, dot_general_p)\n+taylor.prop_rules[mul_p] = partial(_bilinear_taylor_rule, mul_p)\n+taylor.prop_rules[conv_general_dilated_p] = partial(_bilinear_taylor_rule, conv_general_dilated_p)\ndef _broadcast_shape_rule(operand, sizes):\n@@ -2662,6 +2649,7 @@ reshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,\nreshape_p.def_impl(_reshape_impl)\nad.deflinear2(reshape_p, _reshape_transpose_rule)\nbatching.primitive_batchers[reshape_p] = _reshape_batch_rule\n+taylor.deflinear(reshape_p)\ndef _rev_shape_rule(operand, dimensions):\n" }, { "change_type": "MODIFY", "old_path": "mac.py", "new_path": "mac.py", "diff": "+import time\n+\nimport jax.numpy as np\nfrom jax import jet, jvp\n@@ -40,9 +42,14 @@ def repeated(f, n):\nreturn rfun\ndef jvp_test_jet(f, primals, series, atol=1e-5):\n+ tic = time.time()\ny, terms = jet(f, primals, series)\n+ print(\"jet done in {} sec\".format(time.time() - tic))\n+\n+ tic = time.time()\ny_jvp, terms_jvp = jvp_taylor(f, primals, series)\n- # import ipdb; ipdb.set_trace()\n+ print(\"jvp done in {} sec\".format(time.time() - tic))\n+\nassert np.allclose(y, y_jvp)\nassert np.allclose(terms, terms_jvp, atol=atol)\n@@ -56,18 +63,17 @@ def test_exp():\ndef test_dot():\n- D = 6\n- N = 4\n- x1 = npr.randn(D)\n- x2 = npr.randn(D)\n+ M, K, N = 5, 6, 7\n+ order = 4\n+ x1 = npr.randn(M, K)\n+ x2 = npr.randn(K, N)\nprimals = (x1, x2)\n- terms_in1 = list(npr.randn(N,D))\n- terms_in2 = list(npr.randn(N,D))\n+ terms_in1 = [npr.randn(*x1.shape) for _ in range(order)]\n+ terms_in2 = [npr.randn(*x2.shape) for _ in range(order)]\nseries_in = (terms_in1, terms_in2)\njvp_test_jet(np.dot, primals, series_in)\n-\ndef test_mlp():\nsigm = lambda x: 1. / (1. + np.exp(-x))\ndef mlp(M1,M2,x):\n@@ -78,6 +84,45 @@ def test_mlp():\nterms_in = [np.ones_like(x), np.zeros_like(x), np.zeros_like(x), np.zeros_like(x)]\njvp_test_jet(f_mlp,(x,),[terms_in])\n+def test_mul():\n+ D = 3\n+ N = 4\n+ x1 = npr.randn(D)\n+ x2 = npr.randn(D)\n+ f = lambda a, b: a * b\n+ primals = (x1, x2)\n+ terms_in1 = list(npr.randn(N,D))\n+ terms_in2 = list(npr.randn(N,D))\n+ series_in = (terms_in1, terms_in2)\n+ jvp_test_jet(f, primals, series_in)\n+\n+from jax.experimental import stax\n+from jax import random\n+from jax.tree_util import tree_map\n+\n+def test_conv():\n+ order = 4\n+ input_shape = (1, 5, 5, 1)\n+ key = random.PRNGKey(0)\n+ init_fun, apply_fun = stax.Conv(3, (2, 2), padding='VALID')\n+ _, (W, b) = init_fun(key, input_shape)\n+\n+ x = npr.randn(*input_shape)\n+ primals = (W, b, x)\n+\n+ series_in1 = [npr.randn(*W.shape) for _ in range(order)]\n+ series_in2 = [npr.randn(*b.shape) for _ in range(order)]\n+ series_in3 = [npr.randn(*x.shape) for _ in range(order)]\n+\n+ series_in = (series_in1, series_in2, series_in3)\n+\n+ def f(W, b, x):\n+ return apply_fun((W, b), x)\n+ jvp_test_jet(f, primals, series_in)\n+\n+\ntest_exp()\ntest_dot()\n-test_mlp() # TODO add div rule!\n+test_conv()\n+test_mul()\n+# test_mlp() # TODO add div rule!\n" } ]
Python
Apache License 2.0
google/jax
add more jet rules! Co-authored-by: Jesse Bettencourt <jessebett@cs.toronto.edu> Co-authored-by: Jacob Kelly <jacob.jin.kelly@gmail.com> Co-authored-by: David Duvenaud <duvenaud@cs.toronto.edu>
260,700
28.02.2020 13:18:11
18,000
ddd52c47301d48cb65b6c7098a164b99362efa3a
adding div and linear prims
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -37,6 +37,7 @@ from ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\nfrom . import partial_eval as pe\nfrom . import ad\n+from . import taylor\nfrom . import masking\nFLAGS = flags.FLAGS\n@@ -982,6 +983,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+taylor.deflinear(device_put_p)\nmasking.shape_rules[device_put_p] = lambda x, **_: x.shape\nmasking.defvectorized(device_put_p)\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1779,6 +1779,7 @@ ad.defjvp2(erf_inv_p, lambda g, ans, x: mul(_const(x, onp.sqrt(onp.pi) / 2.),\nreal_p = unop(_complex_basetype, _complex, 'real')\nad.deflinear(real_p, lambda t: [complex(t, onp.zeros((), _dtype(t)))])\n+taylor.deflinear(real_p)\nimag_p = unop(_complex_basetype, _complex, 'imag')\nad.defjvp(imag_p, lambda g, _: real(mul(_const(g, -1j), g)))\n@@ -1787,6 +1788,7 @@ _complex_dtype = lambda dtype, *args: (onp.zeros((), dtype) + onp.zeros((), onp.\ncomplex_p = naryop(_complex_dtype, [_complex_elem_types, _complex_elem_types],\n'complex')\nad.deflinear(complex_p, lambda t: [real(t), imag(neg(t))])\n+taylor.deflinear(complex_p)\nconj_p = unop(_complex_dtype, _complex_elem_types | _complex, 'conj')\n@@ -1892,7 +1894,21 @@ div_p = standard_naryop([_num, _num], 'div')\nad.defjvp(div_p,\nlambda g, x, y: div(_brcast(g, y), y),\nlambda g, x, y: div(mul(neg(_brcast(g, x)), x), square(y)))\n+\n+def _div_taylor_rule(primals_in, series_in, **params):\n+ x, y = primals_in\n+ x_terms, y_terms = series_in\n+ u = [x] + x_terms\n+ w = [y] + y_terms\n+ v = [None] * len(u)\n+ def scale(k, j): return 1. / (fact(k - j) * fact(j))\n+ for k in range(0, len(v)):\n+ conv = sum([scale(k, j) * v[j] * w[k-j] for j in range(0, k)])\n+ v[k] = (u[k] - fact(k) * conv) / w[0]\n+ primal_out, *series_out = v\n+ return primal_out, series_out\nad.primitive_transposes[div_p] = _div_transpose_rule\n+taylor.prop_rules[div_p] = _div_taylor_rule\nrem_p = standard_naryop([_num, _num], 'rem')\nad.defjvp(rem_p,\n@@ -1982,6 +1998,7 @@ convert_element_type_p = standard_primitive(\nad.deflinear(\nconvert_element_type_p,\nlambda t, new_dtype, old_dtype: [convert_element_type(t, old_dtype)])\n+taylor.deflinear(convert_element_type_p)\nbatching.defvectorized(convert_element_type_p)\nmasking.defvectorized(convert_element_type_p)\n@@ -2371,6 +2388,7 @@ def _broadcast_batch_rule(batched_args, batch_dims, sizes):\nbroadcast_p = standard_primitive(\n_broadcast_shape_rule, _input_dtype, 'broadcast')\nad.deflinear(broadcast_p, lambda t, sizes: [_reduce_sum(t, range(len(sizes)))])\n+taylor.deflinear(broadcast_p)\nbatching.primitive_batchers[broadcast_p] = _broadcast_batch_rule\ndef _broadcast_in_dim_impl(operand, shape, broadcast_dimensions):\n@@ -2418,6 +2436,7 @@ broadcast_in_dim_p = standard_primitive(\n_broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')\nbroadcast_in_dim_p.def_impl(_broadcast_in_dim_impl)\nad.deflinear(broadcast_in_dim_p, _broadcast_in_dim_transpose_rule)\n+taylor.deflinear(broadcast_in_dim_p)\nbatching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule\n@@ -2508,6 +2527,7 @@ concatenate_p = standard_primitive(\n_concatenate_shape_rule, _concatenate_dtype_rule, 'concatenate',\n_concatenate_translation_rule)\nad.deflinear(concatenate_p, _concatenate_transpose_rule)\n+taylor.deflinear(concatenate_p)\nad.primitive_transposes[concatenate_p] = _concatenate_transpose_rule\nbatching.primitive_batchers[concatenate_p] = _concatenate_batch_rule\n@@ -2556,6 +2576,7 @@ def _pad_batch_rule(batched_args, batch_dims, padding_config):\npad_p = standard_primitive(_pad_shape_rule, _pad_dtype_rule, 'pad')\nad.deflinear(pad_p, _pad_transpose)\n+taylor.deflinear(pad_p)\nad.primitive_transposes[pad_p] = _pad_transpose\nbatching.primitive_batchers[pad_p] = _pad_batch_rule\n@@ -2648,6 +2669,7 @@ reshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,\n'reshape', _reshape_translation_rule)\nreshape_p.def_impl(_reshape_impl)\nad.deflinear2(reshape_p, _reshape_transpose_rule)\n+taylor.deflinear(reshape_p)\nbatching.primitive_batchers[reshape_p] = _reshape_batch_rule\ntaylor.deflinear(reshape_p)\n@@ -2671,6 +2693,7 @@ def _rev_batch_rule(batched_args, batch_dims, dimensions):\nrev_p = standard_primitive(_rev_shape_rule, _input_dtype, 'rev')\nad.deflinear(rev_p, lambda t, dimensions: [rev(t, dimensions)])\n+taylor.deflinear(rev_p)\nbatching.primitive_batchers[rev_p] = _rev_batch_rule\n@@ -2703,6 +2726,7 @@ transpose_p = standard_primitive(_transpose_shape_rule, _input_dtype,\ntranspose_p.def_impl(_transpose_impl)\nad.deflinear(transpose_p,\nlambda t, permutation: [transpose(t, onp.argsort(permutation))])\n+taylor.deflinear(transpose_p)\nbatching.primitive_batchers[transpose_p] = _transpose_batch_rule\n@@ -2861,6 +2885,7 @@ def _slice_batching_rule(batched_args, batch_dims, start_indices, limit_indices,\nslice_p = standard_primitive(_slice_shape_rule, _input_dtype, 'slice',\n_slice_translation_rule)\nad.deflinear2(slice_p, _slice_transpose_rule)\n+taylor.deflinear(slice_p)\nbatching.primitive_batchers[slice_p] = _slice_batching_rule\n@@ -3509,6 +3534,7 @@ reduce_sum_p = standard_primitive(\n_reduce_sum_shape_rule, partial(_reduce_number_dtype_rule, 'reduce_sum'),\n'reduce_sum', _reduce_sum_translation_rule)\nad.deflinear2(reduce_sum_p, _reduce_sum_transpose_rule)\n+taylor.deflinear(reduce_sum_p)\nbatching.defreducer(reduce_sum_p)\n_masking_defreducer(reduce_sum_p,\nlambda shape, dtype: onp.broadcast_to(onp.array(0, dtype), shape))\n@@ -3710,6 +3736,7 @@ reduce_window_sum_p = standard_primitive(\n_reduce_window_sum_shape_rule, _input_dtype, 'reduce_window_sum',\n_reduce_window_sum_translation_rule)\nad.deflinear2(reduce_window_sum_p, _reduce_window_sum_transpose_rule)\n+taylor.deflinear(reduce_window_sum_p)\nbatching.primitive_batchers[reduce_window_sum_p] = partial(\n_reduce_window_batch_rule, _reduce_window_sum)\n@@ -4167,6 +4194,7 @@ tie_in_p.def_impl(lambda x, y: y)\ntie_in_p.def_abstract_eval(lambda x, y: raise_to_shaped(y))\nxla.translations[tie_in_p] = lambda c, x, y: y\nad.deflinear(tie_in_p, _tie_in_transpose_rule)\n+taylor.deflinear(tie_in_p)\nbatching.primitive_batchers[tie_in_p] = _tie_in_batch_rule\nmasking.shape_rules[tie_in_p] = lambda x, y: y.shape\nmasking.masking_rules[tie_in_p] = lambda vals, logical_shapes: vals[1]\n" } ]
Python
Apache License 2.0
google/jax
adding div and linear prims Co-authored-by: Jesse Bettencourt <jessebett@cs.toronto.edu>
260,700
28.02.2020 20:50:03
18,000
3bcf02a191fdb3239cdd8125b4617efc4420d8e0
Add gather rule
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -3185,6 +3185,14 @@ gather_p = standard_primitive(\n_gather_translation_rule)\nad.defjvp(gather_p, _gather_jvp_rule, None)\n+def _gather_taylor_rule(primals_in, series_in, **params):\n+ operand, start_indices = primals_in\n+ gs, _ = series_in\n+ primal_out = gather_p.bind(operand, start_indices, **params)\n+ series_out = [gather_p.bind(g, start_indices, **params) for g in gs]\n+ return primal_out, series_out\n+taylor.prop_rules[gather_p] = _gather_taylor_rule\n+\nad.primitive_transposes[gather_p] = _gather_transpose_rule\nbatching.primitive_batchers[gather_p] = _gather_batching_rule\n" } ]
Python
Apache License 2.0
google/jax
Add gather rule Co-authored-by: Matthew Johnson <mattjj@csail.mit.edu> Co-authored-by: Jesse Bettencourt <jessebett@cs.toronto.edu> Co-authored-by: David Duvenaud <duvenaud@cs.toronto.edu>
260,700
29.02.2020 13:23:38
18,000
dcebe5056215c9de8527ce5ec1e54ae4154c34d6
jet for reduce_max
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -3619,6 +3619,22 @@ _reduce_max_translation_rule = partial(_reduce_chooser_translation_rule, max_p,\nreduce_max_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n'reduce_max', _reduce_max_translation_rule)\nad.defjvp2(reduce_max_p, _reduce_chooser_jvp_rule)\n+\n+def _reduce_max_taylor_rule(primals_in, series_in, **params):\n+ operand, = primals_in\n+ gs, = series_in\n+ primal_out = reduce_max_p.bind(operand, **params)\n+ def _reduce_chooser_taylor_rule(g, ans, operand, axes):\n+ # TODO: everything except the return statement can be factored out of the function\n+ shape = [1 if i in axes else d for i, d in enumerate(operand.shape)]\n+ location_indicators = convert_element_type(\n+ _eq_meet(operand, reshape(ans, shape)), g.dtype)\n+ counts = _reduce_sum(location_indicators, axes)\n+ return div(_reduce_sum(mul(g, location_indicators), axes), counts)\n+ series_out = [_reduce_chooser_taylor_rule(g, primal_out, operand, **params) for g in gs]\n+ return primal_out, series_out\n+taylor.prop_rules[reduce_max_p] = _reduce_max_taylor_rule\n+\nbatching.defreducer(reduce_max_p)\n" } ]
Python
Apache License 2.0
google/jax
jet for reduce_max Co-authored-by: Matthew Johnson <mattjj@csail.mit.edu> Co-authored-by: Jesse Bettencourt <jessebett@cs.toronto.edu> Co-authored-by: David Duvenaud <duvenaud@cs.toronto.edu>
260,700
29.02.2020 13:30:14
18,000
30830dfc251a1d55e7bd48f2894fe3b03084d69f
linear rule for sub
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1867,6 +1867,7 @@ sub_p = standard_naryop([_num, _num], 'sub')\nad.defjvp(sub_p,\nlambda g, x, y: _brcast(g, y),\nlambda g, x, y: _brcast(neg(g), x))\n+taylor.deflinear(sub_p)\nad.primitive_transposes[sub_p] = _sub_transpose\nmul_p = standard_naryop([_num, _num], 'mul')\n" } ]
Python
Apache License 2.0
google/jax
linear rule for sub Co-authored-by: Jesse Bettencourt <jessebett@cs.toronto.edu>
260,700
29.02.2020 14:02:16
18,000
b4d003d460ee512821ee7a6bc8b64a04d6aee6f9
jet rule for log
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1689,6 +1689,19 @@ taylor.prop_rules[exp_p] = _exp_taylor\nlog_p = standard_unop(_float | _complex, 'log')\nad.defjvp(log_p, lambda g, x: div(g, x))\n+def _log_taylor(primals_in, series_in):\n+ x, = primals_in\n+ series, = series_in\n+ u = [x] + series\n+ v = [log(x)] + [None] * len(series)\n+ def scale(k, j): return 1. / (fact(k-j) * fact(j-1))\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+taylor.prop_rules[log_p] = _log_taylor\n+\nexpm1_p = standard_unop(_float | _complex, 'expm1')\nad.defjvp2(expm1_p, lambda g, ans, x: mul(g, add(ans, _one(ans))))\n" } ]
Python
Apache License 2.0
google/jax
jet rule for log Co-authored-by: Jesse Bettencourt <jessebett@cs.toronto.edu> Co-authored-by: Matthew Johnson <mattjj@csail.mit.edu> Co-authored-by: David Duvenaud <duvenaud@cs.toronto.edu>
260,700
29.02.2020 14:37:20
18,000
840797d4a17f6870a076f6173b5ecadd5c07277e
refactor reduce_max jet rule
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -3638,14 +3638,15 @@ def _reduce_max_taylor_rule(primals_in, series_in, **params):\noperand, = primals_in\ngs, = series_in\nprimal_out = reduce_max_p.bind(operand, **params)\n- def _reduce_chooser_taylor_rule(g, ans, operand, axes):\n- # TODO: everything except the return statement can be factored out of the function\n+ axes = params.pop(\"axes\", None)\n+ primal_dtype = gs[0].dtype\nshape = [1 if i in axes else d for i, d in enumerate(operand.shape)]\nlocation_indicators = convert_element_type(\n- _eq_meet(operand, reshape(ans, shape)), g.dtype)\n+ _eq_meet(operand, reshape(primal_out, shape)), primal_dtype)\ncounts = _reduce_sum(location_indicators, axes)\n+ def _reduce_chooser_taylor_rule(g):\nreturn div(_reduce_sum(mul(g, location_indicators), axes), counts)\n- series_out = [_reduce_chooser_taylor_rule(g, primal_out, operand, **params) for g in gs]\n+ series_out = [_reduce_chooser_taylor_rule(g) for g in gs]\nreturn primal_out, series_out\ntaylor.prop_rules[reduce_max_p] = _reduce_max_taylor_rule\n" } ]
Python
Apache License 2.0
google/jax
refactor reduce_max jet rule
260,335
14.03.2020 21:21:27
25,200
668a1703bc8e4a4f289b25ab9867bcbe1a6167fe
add jet tests, remove top-level files
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/taylor.py", "new_path": "jax/interpreters/taylor.py", "diff": "@@ -55,18 +55,18 @@ class JetTrace(core.Trace):\nseries_in = [[onp.zeros(onp.shape(x), dtype=onp.result_type(x))\nif t is zero_term else t for t in series]\nfor x, series in zip(primals_in, series_in)]\n- rule = prop_rules[primitive]\n+ rule = jet_rules[primitive]\nprimal_out, terms_out = rule(primals_in, series_in, **params)\nreturn JetTracer(self, primal_out, terms_out)\ndef process_call(self, call_primitive, f, tracers, params):\n- assert False\n+ assert False # TODO\ndef post_process_call(self, call_primitive, out_tracer, params):\n- assert False\n+ assert False # TODO\ndef join(self, xt, yt):\n- assert False\n+ assert False # TODO?\nclass ZeroTerm(object): pass\n@@ -76,27 +76,10 @@ class ZeroSeries(object): pass\nzero_series = ZeroSeries()\n-prop_rules = {}\n-\n-def tay_to_deriv_coeff(u_tay):\n- u_deriv = [ui * fact(i) for (i, ui) in enumerate(u_tay)]\n- return u_deriv\n-\n-def deriv_to_tay_coeff(u_deriv):\n- u_tay = [ui / fact(i) for (i, ui) in enumerate(u_deriv)]\n- return u_tay\n-\n-def taylor_tilde(u_tay):\n- u_tilde = [i * ui for (i, ui) in enumerate(u_tay)]\n- return u_tilde\n-\n-def taylor_untilde(u_tilde):\n- u_tay = [i * ui for (i, ui) in enumerate(u_tilde)]\n- return u_tay\n-\n+jet_rules = {}\ndef deflinear(prim):\n- prop_rules[prim] = partial(linear_prop, prim)\n+ jet_rules[prim] = partial(linear_prop, prim)\ndef linear_prop(prim, primals_in, series_in, **params):\nprimal_out = prim.bind(*primals_in, **params)\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1684,7 +1684,7 @@ def _exp_taylor(primals_in, series_in):\nv[k] = fact(k-1) * sum([scale(k, j)* v[k-j] * u[j] for j in range(1, k+1)])\nprimal_out, *series_out = v\nreturn primal_out, series_out\n-taylor.prop_rules[exp_p] = _exp_taylor\n+taylor.jet_rules[exp_p] = _exp_taylor\nlog_p = standard_unop(_float | _complex, 'log')\nad.defjvp(log_p, lambda g, x: div(g, x))\n@@ -1700,7 +1700,7 @@ def _log_taylor(primals_in, series_in):\nv[k] = (u[k] - fact(k - 1) * conv) / u[0]\nprimal_out, *series_out = v\nreturn primal_out, series_out\n-taylor.prop_rules[log_p] = _log_taylor\n+taylor.jet_rules[log_p] = _log_taylor\nexpm1_p = standard_unop(_float | _complex, 'expm1')\nad.defjvp2(expm1_p, lambda g, ans, x: mul(g, add(ans, _one(ans))))\n@@ -1922,7 +1922,7 @@ def _div_taylor_rule(primals_in, series_in, **params):\nprimal_out, *series_out = v\nreturn primal_out, series_out\nad.primitive_transposes[div_p] = _div_transpose_rule\n-taylor.prop_rules[div_p] = _div_taylor_rule\n+taylor.jet_rules[div_p] = _div_taylor_rule\nrem_p = standard_naryop([_num, _num], 'rem')\nad.defjvp(rem_p,\n@@ -2384,9 +2384,9 @@ def _bilinear_taylor_rule(prim, primals_in, series_in, **params):\nv[k] = fact(k) * sum([scale(k, j) * op(u[j], w[k-j]) for j in range(0, k+1)])\nprimal_out, *series_out = v\nreturn primal_out, series_out\n-taylor.prop_rules[dot_general_p] = partial(_bilinear_taylor_rule, dot_general_p)\n-taylor.prop_rules[mul_p] = partial(_bilinear_taylor_rule, mul_p)\n-taylor.prop_rules[conv_general_dilated_p] = partial(_bilinear_taylor_rule, conv_general_dilated_p)\n+taylor.jet_rules[dot_general_p] = partial(_bilinear_taylor_rule, dot_general_p)\n+taylor.jet_rules[mul_p] = partial(_bilinear_taylor_rule, mul_p)\n+taylor.jet_rules[conv_general_dilated_p] = partial(_bilinear_taylor_rule, conv_general_dilated_p)\ndef _broadcast_shape_rule(operand, sizes):\n@@ -3205,7 +3205,7 @@ def _gather_taylor_rule(primals_in, series_in, **params):\nprimal_out = gather_p.bind(operand, start_indices, **params)\nseries_out = [gather_p.bind(g, start_indices, **params) for g in gs]\nreturn primal_out, series_out\n-taylor.prop_rules[gather_p] = _gather_taylor_rule\n+taylor.jet_rules[gather_p] = _gather_taylor_rule\nad.primitive_transposes[gather_p] = _gather_transpose_rule\nbatching.primitive_batchers[gather_p] = _gather_batching_rule\n@@ -3648,7 +3648,7 @@ def _reduce_max_taylor_rule(primals_in, series_in, **params):\nreturn div(_reduce_sum(mul(g, location_indicators), axes), counts)\nseries_out = [_reduce_chooser_taylor_rule(g) for g in gs]\nreturn primal_out, series_out\n-taylor.prop_rules[reduce_max_p] = _reduce_max_taylor_rule\n+taylor.jet_rules[reduce_max_p] = _reduce_max_taylor_rule\nbatching.defreducer(reduce_max_p)\n" }, { "change_type": "DELETE", "old_path": "jet_nn.py", "new_path": null, "diff": "-\"\"\"\n-Create some pared down examples to see if we can take jets through them.\n-\"\"\"\n-import time\n-\n-import haiku as hk\n-import jax\n-import jax.numpy as jnp\n-import numpy.random as npr\n-\n-from jax.flatten_util import ravel_pytree\n-\n-import tensorflow_datasets as tfds\n-from functools import reduce\n-\n-from scipy.special import factorial as fact\n-\n-\n-def sigmoid(z):\n- \"\"\"\n- Defined using only numpy primitives (but probably less numerically stable).\n- \"\"\"\n- return 1./(1. + jnp.exp(-z))\n-\n-def repeated(f, n):\n- def rfun(p):\n- return reduce(lambda x, _: f(x), range(n), p)\n- return rfun\n-\n-\n-def jvp_taylor(f, primals, series):\n- def expansion(eps):\n- tayterms = [\n- sum([eps**(i + 1) * terms[i] / fact(i + 1) for i in range(len(terms))])\n- for terms in series\n- ]\n- return f(*map(sum, zip(primals, tayterms)))\n-\n- n_derivs = []\n- N = len(series[0]) + 1\n- for i in range(1, N):\n- d = repeated(jax.jacobian, i)(expansion)(0.)\n- n_derivs.append(d)\n- return f(*primals), n_derivs\n-\n-\n-def jvp_test_jet(f, primals, series, atol=1e-5):\n- tic = time.time()\n- y, terms = jax.jet(f, primals, series)\n- print(\"jet done in {} sec\".format(time.time() - tic))\n-\n- tic = time.time()\n- y_jvp, terms_jvp = jvp_taylor(f, primals, series)\n- print(\"jvp done in {} sec\".format(time.time() - tic))\n-\n- assert jnp.allclose(y, y_jvp)\n- assert jnp.allclose(terms, terms_jvp, atol=atol)\n-\n-\n-def softmax_cross_entropy(logits, labels):\n- one_hot = hk.one_hot(labels, logits.shape[-1])\n- return -jnp.sum(jax.nn.log_softmax(logits) * one_hot, axis=-1)\n- # return -logits[labels]\n-\n-\n-rng = jax.random.PRNGKey(42)\n-\n-order = 4\n-\n-batch_size = 2\n-train_ds = tfds.load('mnist', split=tfds.Split.TRAIN)\n-train_ds = train_ds.cache().shuffle(1000).batch(batch_size)\n-batch = next(tfds.as_numpy(train_ds))\n-\n-\n-def test_mlp_x():\n- \"\"\"\n- Test jet through a linear layer built with Haiku wrt x.\n- \"\"\"\n-\n- def loss_fn(images, labels):\n- model = hk.Sequential([\n- lambda x: x.astype(jnp.float32) / 255.,\n- hk.Linear(10)\n- ])\n- logits = model(images)\n- return jnp.mean(softmax_cross_entropy(logits, labels))\n-\n- loss_obj = hk.transform(loss_fn)\n-\n- # flatten for MLP\n- batch['image'] = jnp.reshape(batch['image'], (batch_size, -1))\n- images, labels = jnp.array(batch['image'], dtype=jnp.float32), jnp.array(batch['label'])\n-\n- params = loss_obj.init(rng, images, labels)\n-\n- flat_params, unravel = ravel_pytree(params)\n-\n- loss = loss_obj.apply(unravel(flat_params), images, labels)\n- print(\"forward pass works\")\n-\n- f = lambda images: loss_obj.apply(unravel(flat_params), images, labels)\n- _ = jax.grad(f)(images)\n- terms_in = [npr.randn(*images.shape) for _ in range(order)]\n- jvp_test_jet(f, (images,), (terms_in,))\n-\n-\n-def test_mlp1():\n- \"\"\"\n- Test jet through a linear layer built with Haiku.\n- \"\"\"\n-\n- def loss_fn(images, labels):\n- model = hk.Sequential([\n- lambda x: x.astype(jnp.float32) / 255.,\n- hk.Linear(10)\n- ])\n- logits = model(images)\n- return jnp.mean(softmax_cross_entropy(logits, labels))\n-\n- loss_obj = hk.transform(loss_fn)\n-\n- # flatten for MLP\n- batch['image'] = jnp.reshape(batch['image'], (batch_size, -1))\n- images, labels = jnp.array(batch['image'], dtype=jnp.float32), jnp.array(batch['label'])\n-\n- params = loss_obj.init(rng, images, labels)\n-\n- flat_params, unravel = ravel_pytree(params)\n-\n- loss = loss_obj.apply(unravel(flat_params), images, labels)\n- print(\"forward pass works\")\n-\n- f = lambda flat_params: loss_obj.apply(unravel(flat_params), images, labels)\n- terms_in = [npr.randn(*flat_params.shape) for _ in range(order)]\n- jvp_test_jet(f, (flat_params,), (terms_in,))\n-\n-\n-def test_mlp2():\n- \"\"\"\n- Test jet through a MLP with sigmoid activations.\n- \"\"\"\n-\n- def loss_fn(images, labels):\n- model = hk.Sequential([\n- lambda x: x.astype(jnp.float32) / 255.,\n- hk.Linear(100),\n- sigmoid,\n- hk.Linear(10)\n- ])\n- logits = model(images)\n- return jnp.mean(softmax_cross_entropy(logits, labels))\n-\n- loss_obj = hk.transform(loss_fn)\n-\n- # flatten for MLP\n- batch['image'] = jnp.reshape(batch['image'], (batch_size, -1))\n- images, labels = jnp.array(batch['image'], dtype=jnp.float32), jnp.array(batch['label'])\n-\n- params = loss_obj.init(rng, images, labels)\n-\n- flat_params, unravel = ravel_pytree(params)\n-\n- loss = loss_obj.apply(unravel(flat_params), images, labels)\n- print(\"forward pass works\")\n-\n- f = lambda flat_params: loss_obj.apply(unravel(flat_params), images, labels)\n- terms_in = [npr.randn(*flat_params.shape) for _ in range(order)]\n- jvp_test_jet(f, (flat_params,), (terms_in,), atol=1e-4)\n-\n-\n-def test_res1():\n- \"\"\"\n- Test jet through a simple convnet with sigmoid activations.\n- \"\"\"\n-\n- def loss_fn(images, labels):\n- model = hk.Sequential([\n- lambda x: x.astype(jnp.float32) / 255.,\n- hk.Conv2D(output_channels=10,\n- kernel_shape=3,\n- stride=2,\n- padding=\"VALID\"),\n- sigmoid,\n- hk.Reshape(output_shape=(batch_size, -1)),\n- hk.Linear(10)\n- ])\n- logits = model(images)\n- return jnp.mean(softmax_cross_entropy(logits, labels))\n-\n- loss_obj = hk.transform(loss_fn)\n-\n- images, labels = batch['image'], batch['label']\n-\n- params = loss_obj.init(rng, images, labels)\n-\n- flat_params, unravel = ravel_pytree(params)\n-\n- loss = loss_obj.apply(unravel(flat_params), images, labels)\n- print(\"forward pass works\")\n-\n- f = lambda flat_params: loss_obj.apply(unravel(flat_params), images, labels)\n- terms_in = [npr.randn(*flat_params.shape) for _ in range(order)]\n- jvp_test_jet(f, (flat_params,), (terms_in,))\n-\n-\n-def test_div():\n- x = 1.\n- y = 5.\n- primals = (x, y)\n- order = 4\n- series_in = ([npr.randn() for _ in range(order)], [npr.randn() for _ in range(order)])\n- jvp_test_jet(lambda a, b: a / b, primals, series_in)\n-\n-\n-def test_gather():\n- npr.seed(0)\n- D = 3 # dimensionality\n- N = 6 # differentiation order\n- x = npr.randn(D)\n- terms_in = list(npr.randn(N, D))\n- jvp_test_jet(lambda x: x[1:], (x,), (terms_in,))\n-\n-def test_reduce_max():\n- npr.seed(0)\n- D1, D2 = 3, 5 # dimensionality\n- N = 6 # differentiation order\n- x = npr.randn(D1, D2)\n- terms_in = [npr.randn(D1, D2) for _ in range(N)]\n- jvp_test_jet(lambda x: x.max(axis=1), (x,), (terms_in,))\n-\n-def test_sub():\n- x = 1.\n- y = 5.\n- primals = (x, y)\n- order = 4\n- series_in = ([npr.randn() for _ in range(order)], [npr.randn() for _ in range(order)])\n- jvp_test_jet(lambda a, b: a - b, primals, series_in)\n-\n-def test_exp():\n- npr.seed(0)\n- D1, D2 = 3, 5 # dimensionality\n- N = 6 # differentiation order\n- x = npr.randn(D1, D2)\n- terms_in = [npr.randn(D1, D2) for _ in range(N)]\n- jvp_test_jet(lambda x: jnp.exp(x), (x,), (terms_in,))\n-\n-def test_log():\n- npr.seed(0)\n- D1, D2 = 3, 5 # dimensionality\n- N = 4 # differentiation order\n- x = jnp.exp(npr.randn(D1, D2))\n- terms_in = [jnp.exp(npr.randn(D1, D2)) for _ in range(N)]\n- jvp_test_jet(lambda x: jnp.log(x), (x,), (terms_in,))\n-\n-\n-# test_div()\n-# test_gather()\n-# test_reduce_max()\n-# test_sub()\n-# test_exp()\n-# test_log()\n-\n-# test_mlp_x()\n-# test_mlp1()\n-# test_mlp2()\n-# test_res1()\n" }, { "change_type": "DELETE", "old_path": "mac.py", "new_path": null, "diff": "-import time\n-\n-import jax.numpy as np\n-from jax import jet, jvp\n-\n-def f(x, y):\n- return x + 2 * np.exp(y)\n-\n-out = jet(f, (1., 2.), [(1., 0.), (1., 0.)])\n-print(out)\n-\n-out = jvp(f, (1., 2.), (1., 1.))\n-print(out)\n-\n-\n-###\n-\n-from functools import reduce\n-import numpy.random as npr\n-from jax import jacobian\n-\n-from scipy.special import factorial as fact\n-\n-def jvp_taylor(f, primals, series):\n- def expansion(eps):\n- tayterms = [\n- sum([eps**(i + 1) * terms[i] / fact(i + 1) for i in range(len(terms))])\n- for terms in series\n- ]\n- return f(*map(sum, zip(primals, tayterms)))\n-\n- n_derivs = []\n- N = len(series[0]) + 1\n- for i in range(1, N):\n- d = repeated(jacobian, i)(expansion)(0.)\n- n_derivs.append(d)\n- return f(*primals), n_derivs\n-\n-def repeated(f, n):\n- def rfun(p):\n- return reduce(lambda x, _: f(x), range(n), p)\n- return rfun\n-\n-def jvp_test_jet(f, primals, series, atol=1e-5):\n- tic = time.time()\n- y, terms = jet(f, primals, series)\n- print(\"jet done in {} sec\".format(time.time() - tic))\n-\n- tic = time.time()\n- y_jvp, terms_jvp = jvp_taylor(f, primals, series)\n- print(\"jvp done in {} sec\".format(time.time() - tic))\n-\n- assert np.allclose(y, y_jvp)\n- assert np.allclose(terms, terms_jvp, atol=atol)\n-\n-def test_exp():\n- npr.seed(0)\n- D = 3 # dimensionality\n- N = 6 # differentiation order\n- x = npr.randn(D)\n- terms_in = list(npr.randn(N,D))\n- jvp_test_jet(np.exp, (x,), (terms_in,), atol=1e-4)\n-\n-\n-def test_dot():\n- M, K, N = 5, 6, 7\n- order = 4\n- x1 = npr.randn(M, K)\n- x2 = npr.randn(K, N)\n- primals = (x1, x2)\n- terms_in1 = [npr.randn(*x1.shape) for _ in range(order)]\n- terms_in2 = [npr.randn(*x2.shape) for _ in range(order)]\n- series_in = (terms_in1, terms_in2)\n- jvp_test_jet(np.dot, primals, series_in)\n-\n-\n-def test_mlp():\n- sigm = lambda x: 1. / (1. + np.exp(-x))\n- def mlp(M1,M2,x):\n- return np.dot(sigm(np.dot(x,M1)),M2)\n- f_mlp = lambda x: mlp(M1,M2,x)\n- M1,M2 = (npr.randn(10,10), npr.randn(10,5))\n- x= npr.randn(2,10)\n- terms_in = [np.ones_like(x), np.zeros_like(x), np.zeros_like(x), np.zeros_like(x)]\n- jvp_test_jet(f_mlp,(x,),[terms_in])\n-\n-def test_mul():\n- D = 3\n- N = 4\n- x1 = npr.randn(D)\n- x2 = npr.randn(D)\n- f = lambda a, b: a * b\n- primals = (x1, x2)\n- terms_in1 = list(npr.randn(N,D))\n- terms_in2 = list(npr.randn(N,D))\n- series_in = (terms_in1, terms_in2)\n- jvp_test_jet(f, primals, series_in)\n-\n-from jax.experimental import stax\n-from jax import random\n-from jax.tree_util import tree_map\n-\n-def test_conv():\n- order = 4\n- input_shape = (1, 5, 5, 1)\n- key = random.PRNGKey(0)\n- init_fun, apply_fun = stax.Conv(3, (2, 2), padding='VALID')\n- _, (W, b) = init_fun(key, input_shape)\n-\n- x = npr.randn(*input_shape)\n- primals = (W, b, x)\n-\n- series_in1 = [npr.randn(*W.shape) for _ in range(order)]\n- series_in2 = [npr.randn(*b.shape) for _ in range(order)]\n- series_in3 = [npr.randn(*x.shape) for _ in range(order)]\n-\n- series_in = (series_in1, series_in2, series_in3)\n-\n- def f(W, b, x):\n- return apply_fun((W, b), x)\n- jvp_test_jet(f, primals, series_in)\n-\n-\n-test_exp()\n-test_dot()\n-test_conv()\n-test_mul()\n-# test_mlp() # TODO add div rule!\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/jet_test.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+\n+from functools import partial, reduce\n+import operator as op\n+from unittest import SkipTest\n+\n+from absl.testing import absltest\n+from absl.testing import parameterized\n+import numpy as onp\n+from scipy.special import factorial as fact\n+\n+from jax import core\n+from jax import test_util as jtu\n+\n+import jax.numpy as np\n+from jax import random\n+from jax import jet, jacobian, jit\n+from jax.experimental import stax\n+\n+from jax.config import config\n+config.parse_flags_with_absl()\n+\n+\n+def jvp_taylor(fun, primals, series):\n+ order, = set(map(len, series))\n+ def composition(eps):\n+ taylor_terms = [sum([eps ** (i+1) * terms[i] / fact(i + 1)\n+ for i in range(len(terms))]) for terms in series]\n+ nudged_args = [x + t for x, t in zip(primals, taylor_terms)]\n+ return fun(*nudged_args)\n+ primal_out = fun(*primals)\n+ terms_out = [repeated(jacobian, i+1)(composition)(0.) for i in range(order)]\n+ return primal_out, terms_out\n+\n+def repeated(f, n):\n+ def rfun(p):\n+ return reduce(lambda x, _: f(x), range(n), p)\n+ return rfun\n+\n+class JetTest(jtu.JaxTestCase):\n+\n+ def check_jet(self, fun, primals, series, atol=1e-5, rtol=1e-5):\n+ y, terms = jet(fun, primals, series)\n+ expected_y, expected_terms = jvp_taylor(fun, primals, series)\n+ self.assertAllClose(y, expected_y, atol=atol, rtol=rtol, check_dtypes=True)\n+ self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol,\n+ check_dtypes=True)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_exp(self):\n+ order, dim = 4, 3\n+ rng = onp.random.RandomState(0)\n+ primal_in = rng.randn(dim)\n+ terms_in = [rng.randn(dim) for _ in range(order)]\n+ self.check_jet(np.exp, (primal_in,), (terms_in,), atol=1e-4, rtol=1e-4)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_log(self):\n+ order, dim = 4, 3\n+ rng = onp.random.RandomState(0)\n+ primal_in = np.exp(rng.randn(dim))\n+ terms_in = [rng.randn(dim) for _ in range(order)]\n+ self.check_jet(np.log, (primal_in,), (terms_in,), atol=1e-4, rtol=1e-4)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_dot(self):\n+ M, K, N = 2, 3, 4\n+ order = 3\n+ rng = onp.random.RandomState(0)\n+ x1 = rng.randn(M, K)\n+ x2 = rng.randn(K, N)\n+ primals = (x1, x2)\n+ terms_in1 = [rng.randn(*x1.shape) for _ in range(order)]\n+ terms_in2 = [rng.randn(*x2.shape) for _ in range(order)]\n+ series_in = (terms_in1, terms_in2)\n+ self.check_jet(np.dot, primals, series_in)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_conv(self):\n+ order = 3\n+ input_shape = (1, 5, 5, 1)\n+ key = random.PRNGKey(0)\n+ init_fun, apply_fun = stax.Conv(3, (2, 2), padding='VALID')\n+ _, (W, b) = init_fun(key, input_shape)\n+\n+ rng = onp.random.RandomState(0)\n+\n+ x = rng.randn(*input_shape)\n+ primals = (W, b, x)\n+\n+ series_in1 = [rng.randn(*W.shape) for _ in range(order)]\n+ series_in2 = [rng.randn(*b.shape) for _ in range(order)]\n+ series_in3 = [rng.randn(*x.shape) for _ in range(order)]\n+\n+ series_in = (series_in1, series_in2, series_in3)\n+\n+ def f(W, b, x):\n+ return apply_fun((W, b), x)\n+\n+ self.check_jet(f, primals, series_in)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_div(self):\n+ primals = 1., 5.\n+ order = 4\n+ rng = onp.random.RandomState(0)\n+ series_in = ([rng.randn() for _ in range(order)], [rng.randn() for _ in range(order)])\n+ self.check_jet(op.truediv, primals, series_in)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_sub(self):\n+ primals = 1., 5.\n+ order = 4\n+ rng = onp.random.RandomState(0)\n+ series_in = ([rng.randn() for _ in range(order)], [rng.randn() for _ in range(order)])\n+ self.check_jet(op.sub, primals, series_in)\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_gather(self):\n+ order, dim = 4, 3\n+ rng = onp.random.RandomState(0)\n+ x = rng.randn(dim)\n+ terms_in = [rng.randn(dim) for _ in range(order)]\n+ self.check_jet(lambda x: x[1:], (x,), (terms_in,))\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_reduce_max(self):\n+ dim1, dim2 = 3, 5\n+ order = 6\n+ rng = onp.random.RandomState(0)\n+ x = rng.randn(dim1, dim2)\n+ terms_in = [rng.randn(dim1, dim2) for _ in range(order)]\n+ self.check_jet(lambda x: x.max(axis=1), (x,), (terms_in,))\n+\n+\n+if __name__ == '__main__':\n+ absltest.main()\n" } ]
Python
Apache License 2.0
google/jax
add jet tests, remove top-level files
260,335
15.03.2020 09:58:54
25,200
92a0b3d40a271f931626865a5a0d90a34698d48a
add basic pytree support to jet
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -43,7 +43,7 @@ from .api_util import (wraps, flatten_fun, apply_flat_fun, flatten_fun_nokwargs,\nflatten_fun_nokwargs2)\nfrom .tree_util import (tree_map, tree_flatten, tree_unflatten, tree_structure,\ntree_transpose, tree_leaves, tree_multimap,\n- _replace_nones)\n+ treedef_is_leaf, _replace_nones)\nfrom .util import (unzip2, curry, partial, safe_map, safe_zip,\nWrapHashably, Hashable, prod, split_list, extend_name_stack, wrap_name)\nfrom .lib import xla_bridge as xb\n@@ -2110,6 +2110,27 @@ def checkpoint(fun: Callable, concrete: bool = False):\nremat = checkpoint\ndef jet(fun, primals, series):\n- f = lu.wrap_init(fun)\n- out_primal, out_terms = taylor.jet(f).call_wrapped(primals, series)\n- return out_primal, out_terms\n+ try:\n+ order, = set(map(len, series))\n+ except ValueError:\n+ msg = \"jet terms have inconsistent lengths for different arguments\"\n+ raise ValueError(msg) from None\n+\n+ # TODO(mattjj): consider supporting pytree inputs\n+ for i, (x, terms) in enumerate(zip(primals, series)):\n+ treedef = tree_structure(x)\n+ if not treedef_is_leaf(treedef):\n+ raise ValueError(\"primal value at position {} is not an array\".format(i))\n+ for j, t in enumerate(terms):\n+ treedef = tree_structure(t)\n+ if not treedef_is_leaf(treedef):\n+ raise ValueError(\"term {} for argument {} is not an array\".format(j, i))\n+\n+ @lu.transformation_with_aux\n+ def flatten_fun_output(*args):\n+ ans = yield args, {}\n+ yield tree_flatten(ans)\n+\n+ f, out_tree = flatten_fun_output(lu.wrap_init(fun))\n+ out_primals, out_terms = taylor.jet(f).call_wrapped(primals, series)\n+ return tree_unflatten(out_tree(), out_primals), tree_unflatten(out_tree(), out_terms)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/taylor.py", "new_path": "jax/interpreters/taylor.py", "diff": "@@ -15,9 +15,9 @@ def jet(primals, series):\ntrace = JetTrace(master, core.cur_sublevel())\nin_tracers = map(partial(JetTracer, trace), primals, series)\nans = yield in_tracers, {}\n- out_tracer = trace.full_raise(ans) # TODO multiple outputs\n- out_primal, series_out = out_tracer.primal, out_tracer.terms\n- yield out_primal, series_out\n+ out_tracers = map(trace.full_raise, ans)\n+ out_primals, out_terms = unzip2((t.primal, t.terms) for t in out_tracers)\n+ yield out_primals, out_terms\nclass JetTracer(core.Tracer):\n@@ -34,7 +34,10 @@ class JetTracer(core.Tracer):\nreturn core.get_aval(self.primal)\ndef full_lower(self):\n- return self # TODO symbolic zeros\n+ if self.terms is zero_series or all(t is zero_term for t in self.terms):\n+ return core.full_lower(self.primal)\n+ else:\n+ return self\nclass JetTrace(core.Trace):\n@@ -52,6 +55,7 @@ class JetTrace(core.Trace):\norder, = {len(terms) for terms in series_in if terms is not zero_series}\nseries_in = [[zero_term] * order if s is zero_series else s\nfor s in series_in]\n+ # TODO(mattjj): avoid always instantiating zeros\nseries_in = [[onp.zeros(onp.shape(x), dtype=onp.result_type(x))\nif t is zero_term else t for t in series]\nfor x, series in zip(primals_in, series_in)]\n" } ]
Python
Apache License 2.0
google/jax
add basic pytree support to jet
260,335
15.03.2020 10:49:48
25,200
a7b3be71e89e1c49efb91e9f3fe5ce42b2ae18a1
move jet into jax.experimental
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -57,7 +57,6 @@ from .interpreters import ad\nfrom .interpreters import batching\nfrom .interpreters import parallel\nfrom .interpreters import masking\n-from .interpreters import taylor\nfrom .interpreters.masking import shapecheck, ensure_poly\nfrom .config import flags, config, bool_env\n@@ -2108,29 +2107,3 @@ def checkpoint(fun: Callable, concrete: bool = False):\nreturn tree_unflatten(out_tree(), out_flat)\nreturn fun_remat\nremat = checkpoint\n-\n-def jet(fun, primals, series):\n- try:\n- order, = set(map(len, series))\n- except ValueError:\n- msg = \"jet terms have inconsistent lengths for different arguments\"\n- raise ValueError(msg) from None\n-\n- # TODO(mattjj): consider supporting pytree inputs\n- for i, (x, terms) in enumerate(zip(primals, series)):\n- treedef = tree_structure(x)\n- if not treedef_is_leaf(treedef):\n- raise ValueError(\"primal value at position {} is not an array\".format(i))\n- for j, t in enumerate(terms):\n- treedef = tree_structure(t)\n- if not treedef_is_leaf(treedef):\n- raise ValueError(\"term {} for argument {} is not an array\".format(j, i))\n-\n- @lu.transformation_with_aux\n- def flatten_fun_output(*args):\n- ans = yield args, {}\n- yield tree_flatten(ans)\n-\n- f, out_tree = flatten_fun_output(lu.wrap_init(fun))\n- out_primals, out_terms = taylor.jet(f).call_wrapped(primals, series)\n- return tree_unflatten(out_tree(), out_primals), tree_unflatten(out_tree(), out_terms)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/jet.py", "diff": "+from functools import partial\n+from collections import Counter\n+\n+import numpy as onp\n+from scipy.special import factorial as fact\n+\n+from jax import core\n+from jax.util import unzip2, prod\n+from jax.tree_util import (register_pytree_node, tree_structure,\n+ treedef_is_leaf, tree_flatten, tree_unflatten)\n+import jax.linear_util as lu\n+\n+\n+def jet(fun, primals, series):\n+ try:\n+ order, = set(map(len, series))\n+ except ValueError:\n+ msg = \"jet terms have inconsistent lengths for different arguments\"\n+ raise ValueError(msg) from None\n+\n+ # TODO(mattjj): consider supporting pytree inputs\n+ for i, (x, terms) in enumerate(zip(primals, series)):\n+ treedef = tree_structure(x)\n+ if not treedef_is_leaf(treedef):\n+ raise ValueError(\"primal value at position {} is not an array\".format(i))\n+ for j, t in enumerate(terms):\n+ treedef = tree_structure(t)\n+ if not treedef_is_leaf(treedef):\n+ raise ValueError(\"term {} for argument {} is not an array\".format(j, i))\n+\n+ @lu.transformation_with_aux\n+ def flatten_fun_output(*args):\n+ ans = yield args, {}\n+ yield tree_flatten(ans)\n+\n+ f, out_tree = flatten_fun_output(lu.wrap_init(fun))\n+ out_primals, out_terms = jet_transform(f).call_wrapped(primals, series)\n+ return tree_unflatten(out_tree(), out_primals), tree_unflatten(out_tree(), out_terms)\n+\n+@lu.transformation\n+def jet_transform(primals, series):\n+ with core.new_master(JetTrace) as master:\n+ trace = JetTrace(master, core.cur_sublevel())\n+ in_tracers = map(partial(JetTracer, trace), primals, series)\n+ ans = yield in_tracers, {}\n+ out_tracers = map(trace.full_raise, ans)\n+ out_primals, out_terms = unzip2((t.primal, t.terms) for t in out_tracers)\n+ yield out_primals, out_terms\n+\n+\n+class JetTracer(core.Tracer):\n+ __slots__ = [\"primal\", \"terms\"]\n+\n+ def __init__(self, trace, primal, terms):\n+ assert type(terms) in (ZeroSeries, list, tuple)\n+ self._trace = trace\n+ self.primal = primal\n+ self.terms = terms\n+\n+ @property\n+ def aval(self):\n+ return core.get_aval(self.primal)\n+\n+ def full_lower(self):\n+ if self.terms is zero_series or all(t is zero_term for t in self.terms):\n+ return core.full_lower(self.primal)\n+ else:\n+ return self\n+\n+class JetTrace(core.Trace):\n+\n+ def pure(self, val):\n+ return JetTracer(self, val, zero_series)\n+\n+ def lift(self, val):\n+ return JetTracer(self, val, zero_series)\n+\n+ def sublift(self, val):\n+ return JetTracer(self, val.primal, val.terms)\n+\n+ def process_primitive(self, primitive, tracers, params):\n+ primals_in, series_in = unzip2((t.primal, t.terms) for t in tracers)\n+ order, = {len(terms) for terms in series_in if terms is not zero_series}\n+ series_in = [[zero_term] * order if s is zero_series else s\n+ for s in series_in]\n+ # TODO(mattjj): avoid always instantiating zeros\n+ series_in = [[onp.zeros(onp.shape(x), dtype=onp.result_type(x))\n+ if t is zero_term else t for t in series]\n+ for x, series in zip(primals_in, series_in)]\n+ rule = jet_rules[primitive]\n+ primal_out, terms_out = rule(primals_in, series_in, **params)\n+ return JetTracer(self, primal_out, terms_out)\n+\n+ def process_call(self, call_primitive, f, tracers, params):\n+ assert False # TODO\n+\n+ def post_process_call(self, call_primitive, out_tracer, params):\n+ assert False # TODO\n+\n+ def join(self, xt, yt):\n+ assert False # TODO?\n+\n+\n+class ZeroTerm(object): pass\n+zero_term = ZeroTerm()\n+register_pytree_node(ZeroTerm, lambda z: ((), None), lambda _, xs: zero_term)\n+\n+class ZeroSeries(object): pass\n+zero_series = ZeroSeries()\n+register_pytree_node(ZeroSeries, lambda z: ((), None), lambda _, xs: zero_series)\n+\n+\n+jet_rules = {}\n+\n+def deflinear(prim):\n+ jet_rules[prim] = partial(linear_prop, prim)\n+\n+def linear_prop(prim, primals_in, series_in, **params):\n+ primal_out = prim.bind(*primals_in, **params)\n+ series_out = [prim.bind(*terms_in, **params) for terms_in in zip(*series_in)]\n+ return primal_out, series_out\n+\n+\n+### rule definitions\n+\n+from jax.lax import lax\n+\n+deflinear(lax.neg_p)\n+deflinear(lax.real_p)\n+deflinear(lax.complex_p)\n+deflinear(lax.add_p)\n+deflinear(lax.sub_p)\n+deflinear(lax.convert_element_type_p)\n+deflinear(lax.broadcast_p)\n+deflinear(lax.broadcast_in_dim_p)\n+deflinear(lax.concatenate_p)\n+deflinear(lax.pad_p)\n+deflinear(lax.reshape_p)\n+deflinear(lax.rev_p)\n+deflinear(lax.transpose_p)\n+deflinear(lax.slice_p)\n+deflinear(lax.reduce_sum_p)\n+deflinear(lax.reduce_window_sum_p)\n+deflinear(lax.tie_in_p)\n+\n+def _exp_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+ def scale(k, j): return 1. / (fact(k-j) * fact(j-1))\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 primal_out, series_out\n+jet_rules[lax.exp_p] = _exp_taylor\n+\n+def _log_taylor(primals_in, series_in):\n+ x, = primals_in\n+ series, = series_in\n+ u = [x] + series\n+ v = [lax.log(x)] + [None] * len(series)\n+ def scale(k, j): return 1. / (fact(k-j) * fact(j-1))\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.log_p] = _log_taylor\n+\n+def _div_taylor_rule(primals_in, series_in, **params):\n+ x, y = primals_in\n+ x_terms, y_terms = series_in\n+ u = [x] + x_terms\n+ w = [y] + y_terms\n+ v = [None] * len(u)\n+ def scale(k, j): return 1. / (fact(k - j) * fact(j))\n+ for k in range(0, len(v)):\n+ conv = sum([scale(k, j) * v[j] * w[k-j] for j in range(0, k)])\n+ v[k] = (u[k] - fact(k) * conv) / w[0]\n+ primal_out, *series_out = v\n+ return primal_out, series_out\n+jet_rules[lax.div_p] = _div_taylor_rule\n+\n+def _bilinear_taylor_rule(prim, primals_in, series_in, **params):\n+ x, y = primals_in\n+ x_terms, y_terms = series_in\n+ u = [x] + x_terms\n+ w = [y] + y_terms\n+ v = [None] * len(u)\n+ op = partial(prim.bind, **params)\n+ def scale(k, j): return 1. / (fact(k - j) * fact(j))\n+ for k in range(0, len(v)):\n+ v[k] = fact(k) * sum([scale(k, j) * op(u[j], w[k-j]) for j in range(0, k+1)])\n+ primal_out, *series_out = v\n+ return primal_out, series_out\n+jet_rules[lax.dot_general_p] = partial(_bilinear_taylor_rule, lax.dot_general_p)\n+jet_rules[lax.mul_p] = partial(_bilinear_taylor_rule, lax.mul_p)\n+jet_rules[lax.conv_general_dilated_p] = partial(_bilinear_taylor_rule, lax.conv_general_dilated_p)\n+\n+def _gather_taylor_rule(primals_in, series_in, **params):\n+ operand, start_indices = primals_in\n+ gs, _ = series_in\n+ primal_out = lax.gather_p.bind(operand, start_indices, **params)\n+ series_out = [lax.gather_p.bind(g, start_indices, **params) for g in gs]\n+ return primal_out, series_out\n+jet_rules[lax.gather_p] = _gather_taylor_rule\n+\n+def _reduce_max_taylor_rule(primals_in, series_in, **params):\n+ operand, = primals_in\n+ gs, = series_in\n+ primal_out = lax.reduce_max_p.bind(operand, **params)\n+ axes = params.pop(\"axes\", None)\n+ primal_dtype = gs[0].dtype\n+ shape = [1 if i in axes else d for i, d in enumerate(operand.shape)]\n+ location_indicators = lax.convert_element_type(\n+ lax._eq_meet(operand, lax.reshape(primal_out, shape)), primal_dtype)\n+ counts = lax._reduce_sum(location_indicators, axes)\n+ def _reduce_chooser_taylor_rule(g):\n+ return lax.div(lax._reduce_sum(lax.mul(g, location_indicators), axes), counts)\n+ series_out = [_reduce_chooser_taylor_rule(g) for g in gs]\n+ return primal_out, series_out\n+jet_rules[lax.reduce_max_p] = _reduce_max_taylor_rule\n+\n+\n+from jax.interpreters import xla\n+deflinear(xla.device_put_p)\n" }, { "change_type": "DELETE", "old_path": "jax/interpreters/taylor.py", "new_path": null, "diff": "-from functools import partial\n-from collections import Counter\n-\n-import numpy as onp\n-from scipy.special import factorial as fact\n-\n-from jax import core\n-from jax.util import unzip2, prod\n-import jax.linear_util as lu\n-\n-\n-@lu.transformation\n-def jet(primals, series):\n- with core.new_master(JetTrace) as master:\n- trace = JetTrace(master, core.cur_sublevel())\n- in_tracers = map(partial(JetTracer, trace), primals, series)\n- ans = yield in_tracers, {}\n- out_tracers = map(trace.full_raise, ans)\n- out_primals, out_terms = unzip2((t.primal, t.terms) for t in out_tracers)\n- yield out_primals, out_terms\n-\n-\n-class JetTracer(core.Tracer):\n- __slots__ = [\"primal\", \"terms\"]\n-\n- def __init__(self, trace, primal, terms):\n- assert type(terms) in (ZeroSeries, list, tuple)\n- self._trace = trace\n- self.primal = primal\n- self.terms = terms\n-\n- @property\n- def aval(self):\n- return core.get_aval(self.primal)\n-\n- def full_lower(self):\n- if self.terms is zero_series or all(t is zero_term for t in self.terms):\n- return core.full_lower(self.primal)\n- else:\n- return self\n-\n-class JetTrace(core.Trace):\n-\n- def pure(self, val):\n- return JetTracer(self, val, zero_series)\n-\n- def lift(self, val):\n- return JetTracer(self, val, zero_series)\n-\n- def sublift(self, val):\n- return JetTracer(self, val.primal, val.terms)\n-\n- def process_primitive(self, primitive, tracers, params):\n- primals_in, series_in = unzip2((t.primal, t.terms) for t in tracers)\n- order, = {len(terms) for terms in series_in if terms is not zero_series}\n- series_in = [[zero_term] * order if s is zero_series else s\n- for s in series_in]\n- # TODO(mattjj): avoid always instantiating zeros\n- series_in = [[onp.zeros(onp.shape(x), dtype=onp.result_type(x))\n- if t is zero_term else t for t in series]\n- for x, series in zip(primals_in, series_in)]\n- rule = jet_rules[primitive]\n- primal_out, terms_out = rule(primals_in, series_in, **params)\n- return JetTracer(self, primal_out, terms_out)\n-\n- def process_call(self, call_primitive, f, tracers, params):\n- assert False # TODO\n-\n- def post_process_call(self, call_primitive, out_tracer, params):\n- assert False # TODO\n-\n- def join(self, xt, yt):\n- assert False # TODO?\n-\n-\n-class ZeroTerm(object): pass\n-zero_term = ZeroTerm()\n-\n-class ZeroSeries(object): pass\n-zero_series = ZeroSeries()\n-\n-\n-jet_rules = {}\n-\n-def deflinear(prim):\n- jet_rules[prim] = partial(linear_prop, prim)\n-\n-def linear_prop(prim, primals_in, series_in, **params):\n- primal_out = prim.bind(*primals_in, **params)\n- series_out = [prim.bind(*terms_in, **params) for terms_in in zip(*series_in)]\n- return primal_out, series_out\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -37,7 +37,6 @@ from ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\nfrom . import partial_eval as pe\nfrom . import ad\n-from . import taylor\nfrom . import masking\nFLAGS = flags.FLAGS\n@@ -983,7 +982,6 @@ 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-taylor.deflinear(device_put_p)\nmasking.shape_rules[device_put_p] = lambda x, **_: x.shape\nmasking.defvectorized(device_put_p)\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -24,7 +24,6 @@ from typing import Any\nimport warnings\nimport numpy as onp\n-from scipy.special import factorial as fact # TODO scipy dep?\nfrom ..util import partial, prod\n@@ -44,7 +43,6 @@ from ..interpreters import xla\nfrom ..interpreters import pxla\nfrom ..interpreters import ad\nfrom ..interpreters import batching\n-from ..interpreters import taylor\nfrom ..interpreters import masking\nfrom ..util import curry, cache, safe_zip, unzip2, prod\nfrom ..tree_util import build_tree, tree_unflatten, tree_map\n@@ -1640,7 +1638,6 @@ _bool_or_int = _int | _bool\nneg_p = standard_unop(_num, 'neg')\nad.deflinear(neg_p, lambda t: [neg(t)])\n-taylor.deflinear(neg_p)\ndef _sign_translation_rule(c, x):\nshape = c.GetShape(x)\n@@ -1674,34 +1671,9 @@ ad.defjvp_zero(is_finite_p)\nexp_p = standard_unop(_float | _complex, 'exp')\nad.defjvp2(exp_p, lambda g, ans, x: _safe_mul(g, ans))\n-def _exp_taylor(primals_in, series_in):\n- x, = primals_in\n- series, = series_in\n- u = [x] + series\n- v = [exp(x)] + [None] * len(series)\n- def scale(k, j): return 1. / (fact(k-j) * fact(j-1))\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 primal_out, series_out\n-taylor.jet_rules[exp_p] = _exp_taylor\n-\nlog_p = standard_unop(_float | _complex, 'log')\nad.defjvp(log_p, lambda g, x: div(g, x))\n-def _log_taylor(primals_in, series_in):\n- x, = primals_in\n- series, = series_in\n- u = [x] + series\n- v = [log(x)] + [None] * len(series)\n- def scale(k, j): return 1. / (fact(k-j) * fact(j-1))\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-taylor.jet_rules[log_p] = _log_taylor\n-\nexpm1_p = standard_unop(_float | _complex, 'expm1')\nad.defjvp2(expm1_p, lambda g, ans, x: mul(g, add(ans, _one(ans))))\n@@ -1792,7 +1764,6 @@ ad.defjvp2(erf_inv_p, lambda g, ans, x: mul(_const(x, onp.sqrt(onp.pi) / 2.),\nreal_p = unop(_complex_basetype, _complex, 'real')\nad.deflinear(real_p, lambda t: [complex(t, onp.zeros((), _dtype(t)))])\n-taylor.deflinear(real_p)\nimag_p = unop(_complex_basetype, _complex, 'imag')\nad.defjvp(imag_p, lambda g, _: real(mul(_const(g, -1j), g)))\n@@ -1801,7 +1772,6 @@ _complex_dtype = lambda dtype, *args: (onp.zeros((), dtype) + onp.zeros((), onp.\ncomplex_p = naryop(_complex_dtype, [_complex_elem_types, _complex_elem_types],\n'complex')\nad.deflinear(complex_p, lambda t: [real(t), imag(neg(t))])\n-taylor.deflinear(complex_p)\nconj_p = unop(_complex_dtype, _complex_elem_types | _complex, 'conj')\n@@ -1869,7 +1839,6 @@ def _add_transpose(t, x, y):\nadd_p = standard_naryop([_num, _num], 'add')\nad.defjvp(add_p, lambda g, x, y: _brcast(g, y), lambda g, x, y: _brcast(g, x))\nad.primitive_transposes[add_p] = _add_transpose\n-taylor.deflinear(add_p)\ndef _sub_transpose(t, x, y):\n@@ -1880,7 +1849,6 @@ sub_p = standard_naryop([_num, _num], 'sub')\nad.defjvp(sub_p,\nlambda g, x, y: _brcast(g, y),\nlambda g, x, y: _brcast(neg(g), x))\n-taylor.deflinear(sub_p)\nad.primitive_transposes[sub_p] = _sub_transpose\nmul_p = standard_naryop([_num, _num], 'mul')\n@@ -1908,21 +1876,7 @@ div_p = standard_naryop([_num, _num], 'div')\nad.defjvp(div_p,\nlambda g, x, y: div(_brcast(g, y), y),\nlambda g, x, y: div(mul(neg(_brcast(g, x)), x), square(y)))\n-\n-def _div_taylor_rule(primals_in, series_in, **params):\n- x, y = primals_in\n- x_terms, y_terms = series_in\n- u = [x] + x_terms\n- w = [y] + y_terms\n- v = [None] * len(u)\n- def scale(k, j): return 1. / (fact(k - j) * fact(j))\n- for k in range(0, len(v)):\n- conv = sum([scale(k, j) * v[j] * w[k-j] for j in range(0, k)])\n- v[k] = (u[k] - fact(k) * conv) / w[0]\n- primal_out, *series_out = v\n- return primal_out, series_out\nad.primitive_transposes[div_p] = _div_transpose_rule\n-taylor.jet_rules[div_p] = _div_taylor_rule\nrem_p = standard_naryop([_num, _num], 'rem')\nad.defjvp(rem_p,\n@@ -2012,7 +1966,6 @@ convert_element_type_p = standard_primitive(\nad.deflinear(\nconvert_element_type_p,\nlambda t, new_dtype, old_dtype: [convert_element_type(t, old_dtype)])\n-taylor.deflinear(convert_element_type_p)\nbatching.defvectorized(convert_element_type_p)\nmasking.defvectorized(convert_element_type_p)\n@@ -2372,22 +2325,6 @@ ad.defbilinear(dot_general_p,\nbatching.primitive_batchers[dot_general_p] = _dot_general_batch_rule\nmasking.masking_rules[dot_general_p] = _dot_general_masking_rule\n-def _bilinear_taylor_rule(prim, primals_in, series_in, **params):\n- x, y = primals_in\n- x_terms, y_terms = series_in\n- u = [x] + x_terms\n- w = [y] + y_terms\n- v = [None] * len(u)\n- op = partial(prim.bind, **params)\n- def scale(k, j): return 1. / (fact(k - j) * fact(j))\n- for k in range(0, len(v)):\n- v[k] = fact(k) * sum([scale(k, j) * op(u[j], w[k-j]) for j in range(0, k+1)])\n- primal_out, *series_out = v\n- return primal_out, series_out\n-taylor.jet_rules[dot_general_p] = partial(_bilinear_taylor_rule, dot_general_p)\n-taylor.jet_rules[mul_p] = partial(_bilinear_taylor_rule, mul_p)\n-taylor.jet_rules[conv_general_dilated_p] = partial(_bilinear_taylor_rule, conv_general_dilated_p)\n-\ndef _broadcast_shape_rule(operand, sizes):\n_check_shapelike('broadcast', 'sizes', sizes)\n@@ -2402,7 +2339,6 @@ def _broadcast_batch_rule(batched_args, batch_dims, sizes):\nbroadcast_p = standard_primitive(\n_broadcast_shape_rule, _input_dtype, 'broadcast')\nad.deflinear(broadcast_p, lambda t, sizes: [_reduce_sum(t, range(len(sizes)))])\n-taylor.deflinear(broadcast_p)\nbatching.primitive_batchers[broadcast_p] = _broadcast_batch_rule\ndef _broadcast_in_dim_impl(operand, shape, broadcast_dimensions):\n@@ -2450,7 +2386,6 @@ broadcast_in_dim_p = standard_primitive(\n_broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')\nbroadcast_in_dim_p.def_impl(_broadcast_in_dim_impl)\nad.deflinear(broadcast_in_dim_p, _broadcast_in_dim_transpose_rule)\n-taylor.deflinear(broadcast_in_dim_p)\nbatching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule\n@@ -2541,7 +2476,6 @@ concatenate_p = standard_primitive(\n_concatenate_shape_rule, _concatenate_dtype_rule, 'concatenate',\n_concatenate_translation_rule)\nad.deflinear(concatenate_p, _concatenate_transpose_rule)\n-taylor.deflinear(concatenate_p)\nad.primitive_transposes[concatenate_p] = _concatenate_transpose_rule\nbatching.primitive_batchers[concatenate_p] = _concatenate_batch_rule\n@@ -2590,7 +2524,6 @@ def _pad_batch_rule(batched_args, batch_dims, padding_config):\npad_p = standard_primitive(_pad_shape_rule, _pad_dtype_rule, 'pad')\nad.deflinear(pad_p, _pad_transpose)\n-taylor.deflinear(pad_p)\nad.primitive_transposes[pad_p] = _pad_transpose\nbatching.primitive_batchers[pad_p] = _pad_batch_rule\n@@ -2683,9 +2616,7 @@ reshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,\n'reshape', _reshape_translation_rule)\nreshape_p.def_impl(_reshape_impl)\nad.deflinear2(reshape_p, _reshape_transpose_rule)\n-taylor.deflinear(reshape_p)\nbatching.primitive_batchers[reshape_p] = _reshape_batch_rule\n-taylor.deflinear(reshape_p)\ndef _rev_shape_rule(operand, dimensions):\n@@ -2707,7 +2638,6 @@ def _rev_batch_rule(batched_args, batch_dims, dimensions):\nrev_p = standard_primitive(_rev_shape_rule, _input_dtype, 'rev')\nad.deflinear(rev_p, lambda t, dimensions: [rev(t, dimensions)])\n-taylor.deflinear(rev_p)\nbatching.primitive_batchers[rev_p] = _rev_batch_rule\n@@ -2740,7 +2670,6 @@ transpose_p = standard_primitive(_transpose_shape_rule, _input_dtype,\ntranspose_p.def_impl(_transpose_impl)\nad.deflinear(transpose_p,\nlambda t, permutation: [transpose(t, onp.argsort(permutation))])\n-taylor.deflinear(transpose_p)\nbatching.primitive_batchers[transpose_p] = _transpose_batch_rule\n@@ -2899,7 +2828,6 @@ def _slice_batching_rule(batched_args, batch_dims, start_indices, limit_indices,\nslice_p = standard_primitive(_slice_shape_rule, _input_dtype, 'slice',\n_slice_translation_rule)\nad.deflinear2(slice_p, _slice_transpose_rule)\n-taylor.deflinear(slice_p)\nbatching.primitive_batchers[slice_p] = _slice_batching_rule\n@@ -3199,14 +3127,6 @@ gather_p = standard_primitive(\n_gather_translation_rule)\nad.defjvp(gather_p, _gather_jvp_rule, None)\n-def _gather_taylor_rule(primals_in, series_in, **params):\n- operand, start_indices = primals_in\n- gs, _ = series_in\n- primal_out = gather_p.bind(operand, start_indices, **params)\n- series_out = [gather_p.bind(g, start_indices, **params) for g in gs]\n- return primal_out, series_out\n-taylor.jet_rules[gather_p] = _gather_taylor_rule\n-\nad.primitive_transposes[gather_p] = _gather_transpose_rule\nbatching.primitive_batchers[gather_p] = _gather_batching_rule\n@@ -3557,7 +3477,6 @@ reduce_sum_p = standard_primitive(\n_reduce_sum_shape_rule, partial(_reduce_number_dtype_rule, 'reduce_sum'),\n'reduce_sum', _reduce_sum_translation_rule)\nad.deflinear2(reduce_sum_p, _reduce_sum_transpose_rule)\n-taylor.deflinear(reduce_sum_p)\nbatching.defreducer(reduce_sum_p)\n_masking_defreducer(reduce_sum_p,\nlambda shape, dtype: onp.broadcast_to(onp.array(0, dtype), shape))\n@@ -3633,23 +3552,6 @@ _reduce_max_translation_rule = partial(_reduce_chooser_translation_rule, max_p,\nreduce_max_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n'reduce_max', _reduce_max_translation_rule)\nad.defjvp2(reduce_max_p, _reduce_chooser_jvp_rule)\n-\n-def _reduce_max_taylor_rule(primals_in, series_in, **params):\n- operand, = primals_in\n- gs, = series_in\n- primal_out = reduce_max_p.bind(operand, **params)\n- axes = params.pop(\"axes\", None)\n- primal_dtype = gs[0].dtype\n- shape = [1 if i in axes else d for i, d in enumerate(operand.shape)]\n- location_indicators = convert_element_type(\n- _eq_meet(operand, reshape(primal_out, shape)), primal_dtype)\n- counts = _reduce_sum(location_indicators, axes)\n- def _reduce_chooser_taylor_rule(g):\n- return div(_reduce_sum(mul(g, location_indicators), axes), counts)\n- series_out = [_reduce_chooser_taylor_rule(g) for g in gs]\n- return primal_out, series_out\n-taylor.jet_rules[reduce_max_p] = _reduce_max_taylor_rule\n-\nbatching.defreducer(reduce_max_p)\n@@ -3776,7 +3678,6 @@ reduce_window_sum_p = standard_primitive(\n_reduce_window_sum_shape_rule, _input_dtype, 'reduce_window_sum',\n_reduce_window_sum_translation_rule)\nad.deflinear2(reduce_window_sum_p, _reduce_window_sum_transpose_rule)\n-taylor.deflinear(reduce_window_sum_p)\nbatching.primitive_batchers[reduce_window_sum_p] = partial(\n_reduce_window_batch_rule, _reduce_window_sum)\n@@ -4234,7 +4135,6 @@ tie_in_p.def_impl(lambda x, y: y)\ntie_in_p.def_abstract_eval(lambda x, y: raise_to_shaped(y))\nxla.translations[tie_in_p] = lambda c, x, y: y\nad.deflinear(tie_in_p, _tie_in_transpose_rule)\n-taylor.deflinear(tie_in_p)\nbatching.primitive_batchers[tie_in_p] = _tie_in_batch_rule\nmasking.shape_rules[tie_in_p] = lambda x, y: y.shape\nmasking.masking_rules[tie_in_p] = lambda vals, logical_shapes: vals[1]\n" }, { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -27,8 +27,9 @@ from jax import test_util as jtu\nimport jax.numpy as np\nfrom jax import random\n-from jax import jet, jacobian, jit\n+from jax import jacobian, jit\nfrom jax.experimental import stax\n+from jax.experimental.jet import jet\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n" } ]
Python
Apache License 2.0
google/jax
move jet into jax.experimental
260,335
15.03.2020 11:39:44
25,200
8d402d83da8ca68d7937ee01726fec74d5abb4f7
add copyright notice to jet.py
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.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+\nfrom functools import partial\nfrom collections import Counter\n" } ]
Python
Apache License 2.0
google/jax
add copyright notice to jet.py
260,335
15.03.2020 12:00:44
25,200
a00e3986d4c2c73e49f4517a8518cf1b7b424535
remove scipy dep, fix dtype issue
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -17,7 +17,6 @@ from functools import partial\nfrom collections import Counter\nimport numpy as onp\n-from scipy.special import factorial as fact\nfrom jax import core\nfrom jax.util import unzip2, prod\n@@ -140,6 +139,9 @@ def linear_prop(prim, primals_in, series_in, **params):\nfrom jax.lax import lax\n+def fact(n):\n+ return lax.exp(lax.lgamma(n+1.))\n+\ndeflinear(lax.neg_p)\ndeflinear(lax.real_p)\ndeflinear(lax.complex_p)\n" }, { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -20,7 +20,6 @@ from unittest import SkipTest\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport numpy as onp\n-from scipy.special import factorial as fact\nfrom jax import core\nfrom jax import test_util as jtu\n@@ -29,7 +28,7 @@ import jax.numpy as np\nfrom jax import random\nfrom jax import jacobian, jit\nfrom jax.experimental import stax\n-from jax.experimental.jet import jet\n+from jax.experimental.jet import jet, fact\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -53,12 +52,14 @@ def repeated(f, n):\nclass JetTest(jtu.JaxTestCase):\n- def check_jet(self, fun, primals, series, atol=1e-5, rtol=1e-5):\n+ def check_jet(self, fun, primals, series, atol=1e-5, rtol=1e-5,\n+ check_dtypes=True):\ny, terms = jet(fun, primals, series)\nexpected_y, expected_terms = jvp_taylor(fun, primals, series)\n- self.assertAllClose(y, expected_y, atol=atol, rtol=rtol, check_dtypes=True)\n+ self.assertAllClose(y, expected_y, atol=atol, rtol=rtol,\n+ check_dtypes=check_dtypes)\nself.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol,\n- check_dtypes=True)\n+ check_dtypes=check_dtypes)\n@jtu.skip_on_devices(\"tpu\")\ndef test_exp(self):\n@@ -99,19 +100,19 @@ class JetTest(jtu.JaxTestCase):\nrng = onp.random.RandomState(0)\n- x = rng.randn(*input_shape)\n+ x = rng.randn(*input_shape).astype(\"float32\")\nprimals = (W, b, x)\n- series_in1 = [rng.randn(*W.shape) for _ in range(order)]\n- series_in2 = [rng.randn(*b.shape) for _ in range(order)]\n- series_in3 = [rng.randn(*x.shape) for _ in range(order)]\n+ series_in1 = [rng.randn(*W.shape).astype(\"float32\") for _ in range(order)]\n+ series_in2 = [rng.randn(*b.shape).astype(\"float32\") for _ in range(order)]\n+ series_in3 = [rng.randn(*x.shape).astype(\"float32\") for _ in range(order)]\nseries_in = (series_in1, series_in2, series_in3)\ndef f(W, b, x):\nreturn apply_fun((W, b), x)\n- self.check_jet(f, primals, series_in)\n+ self.check_jet(f, primals, series_in, check_dtypes=False)\n@jtu.skip_on_devices(\"tpu\")\ndef test_div(self):\n" } ]
Python
Apache License 2.0
google/jax
remove scipy dep, fix dtype issue
260,335
15.03.2020 21:32:56
25,200
7666c254f99717081283d3c9d0859f5ed451f127
fix buggy broadcast_in_dim shapecheck test
[ { "change_type": "MODIFY", "old_path": "tests/masking_test.py", "new_path": "tests/masking_test.py", "diff": "@@ -149,11 +149,17 @@ class MaskingTest(jtu.JaxTestCase):\nreturn api.device_put(x)\ndef test_shapecheck_broadcast_in_dim(self):\n+ x = np.zeros(7)\n+\n+ @shapecheck(['(n,)'], '(3, n, 4)')\n+ def broadcast_in_dim(x):\n+ return lax.broadcast_in_dim(x, shape=(3, x.shape[0], 4), broadcast_dimensions=(1,))\n+\nx = np.zeros((7, 1))\n- lax.broadcast_in_dim(x, shape=(3, x.shape[0], 4), broadcast_dimensions=(1, 2))\n- @shapecheck(['(n, 1)'], '(3, n, 4)')\n+\n+ @shapecheck(['(n, 1)'], '(3, n, 4, 1)')\ndef broadcast_in_dim(x):\n- return lax.broadcast_in_dim(x, shape=(3, x.shape[0], 4), broadcast_dimensions=(1, 2))\n+ return lax.broadcast_in_dim(x, shape=(3, x.shape[0], 4, x.shape[1]), broadcast_dimensions=(1, 3))\ndef test_shapecheck_jit(self):\n@shapecheck(['n'], '2*n')\n" } ]
Python
Apache License 2.0
google/jax
fix buggy broadcast_in_dim shapecheck test
260,335
16.03.2020 09:20:34
25,200
1c202ac3c4d83b889c54765752470a5589278f19
fix typo, unbreak pmap (from
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -55,7 +55,7 @@ def identity(x): return x\ndef _make_unit(c): return c.Constant(onp.zeros((), dtype=onp.dtype('bool')))\ndef _make_abstract_unit(_): return xc.Shape.array_shape(onp.dtype('bool'), ())\ndef _device_put_unit(_, device):\n- return xc.Buffer.from_pyval(onp.zeros((), dtype=onp.dtype('bool')),\n+ return xc.Buffer.from_pyval(onp.zeros((), dtype=onp.dtype('bool')), device,\nbackend=xb.get_device_backend(device))\n" } ]
Python
Apache License 2.0
google/jax
fix typo, unbreak pmap (from #2416)
260,335
16.03.2020 10:23:24
25,200
5280793191f391bfb3f97617796ddfda4a3d4e48
fix custom_transforms + jit bug from
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1559,8 +1559,8 @@ 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- xla.translations[fun_p] = fun_translation\n+ return xla.lower_fun(fun_impl, translation_with_avals=True)(c, *xla_args, **params)\n+ xla.translations_with_avals[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": "@@ -225,8 +225,9 @@ def primitive_computation(prim, axis_env, backend, tuple_args, *avals, **params)\nrule = backend_specific_translations[platform][prim]\nrule(c, *xla_args, **params)\nelif prim in translations:\n- rule = translations[prim]\n- rule(c, *xla_args, **params)\n+ translations[prim](c, *xla_args, **params)\n+ elif prim in translations_with_avals:\n+ translations_with_avals[prim](c, avals, *xla_args, **params)\nelif prim in initial_style_translations:\nrule = initial_style_translations[prim]\nrule(c, axis_env, extend_name_stack(prim.name), avals, backend,\n@@ -332,6 +333,9 @@ def jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, name_stack, *args):\nans = rule(c, *in_nodes, **eqn.params)\nelif eqn.primitive in translations:\nans = translations[eqn.primitive](c, *in_nodes, **eqn.params)\n+ elif eqn.primitive in translations_with_avals:\n+ ans = translations_with_avals[eqn.primitive](c, map(aval, eqn.invars),\n+ *in_nodes, **eqn.params)\nelif eqn.primitive in initial_style_translations:\nnew_params = check_backend_params(eqn.params, backend)\nrule = initial_style_translations[eqn.primitive]\n@@ -629,6 +633,7 @@ ad.primitive_transposes[xla_call_p] = partial(ad.call_transpose, xla_call_p)\n### translation tables\ntranslations = {}\n+translations_with_avals = {} # TODO(mattjj): unify with above table\nparallel_translations = {}\ninitial_style_translations = {}\ncall_translations = {}\n@@ -650,7 +655,7 @@ def add_jaxvals_translation_rule(c, x, y):\nreturn c.Add(x, y)\ntranslations[ad_util.add_jaxvals_p] = add_jaxvals_translation_rule\n-def lower_fun(fun):\n+def lower_fun(fun, translation_with_avals=False):\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@@ -658,8 +663,12 @@ def lower_fun(fun):\n# least we assume that the mapping from JAX *array* types to XLA array types\n# is invertible. This assumption is unchecked!\n# TODO(mattjj): remove assumption can map XLA array types to JAX array types\n- def f(c, *xla_args, **params):\n+ def f(c, *args, **params):\n# TODO(mattjj): revise this 'calling convention'\n+ if translation_with_avals:\n+ avals, *xla_args = args\n+ else:\n+ xla_args = args\navals = [_array_aval_from_xla_shape(c.GetShape(x)) for x in xla_args]\npvals = [pe.PartialVal((a, core.unit)) for a in avals]\njaxpr, _, consts = pe.trace_to_jaxpr(\n" } ]
Python
Apache License 2.0
google/jax
fix custom_transforms + jit bug from #2416
260,335
16.03.2020 12:17:09
25,200
ed8dbd254deee8f11f77e50ad6e70e2696fead51
temporarily switch off changes
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax_control_flow.py", "new_path": "jax/lax/lax_control_flow.py", "diff": "@@ -154,7 +154,7 @@ def fori_loop(lower, upper, body_fun, init_val):\nexcept TypeError:\nuse_scan = False\nelse:\n- use_scan = True\n+ use_scan = False # TODO(mattjj): re-enable this\nif use_scan:\n(_, _, result), _ = scan(_fori_scan_body_fun(body_fun),\n@@ -1209,7 +1209,8 @@ def scan_bind(*args, forward, length, num_consts, num_carry, jaxpr, linear):\nscan_p = core.Primitive(\"scan\")\nscan_p.multiple_results = True\nscan_p.def_custom_bind(scan_bind)\n-scan_p.def_impl(partial(xla.apply_primitive, scan_p))\n+scan_p.def_impl(_scan_impl)\n+# scan_p.def_impl(partial(xla.apply_primitive, scan_p)) # TODO(mattjj): re-enable\nscan_p.def_abstract_eval(_scan_abstract_eval)\nad.primitive_jvps[scan_p] = _scan_jvp\nad.primitive_transposes[scan_p] = _scan_transpose\n" } ]
Python
Apache License 2.0
google/jax
temporarily switch off #2414 changes
260,411
17.03.2020 09:07:14
-3,600
e66e5699474bd1fbffe1f7ded1a95a78d2727d6a
Minor update to docsl trigger readthedocs
[ { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.rst", "new_path": "docs/CHANGELOG.rst", "diff": "@@ -26,10 +26,10 @@ jax 0.1.60 (unreleased)\nhigher-order automatic differentiation.\n* Added more sanity checking to arguments of :py:func:`jax.lax.broadcast_in_dim`.\n-* The minimum jaxlib version is now 0.1.40.\n+* The minimum jaxlib version is now 0.1.41.\njaxlib 0.1.40 (March 4, 2020)\n---------------------------------\n+------------------------------\n* Adds experimental support in Jaxlib for TensorFlow profiler, which allows\ntracing of CPU and GPU computations from TensorBoard.\n" } ]
Python
Apache License 2.0
google/jax
Minor update to docsl trigger readthedocs (#2433)
260,411
17.03.2020 09:24:17
-3,600
c4c770b7fc3b8d8f199e2b037d02a5b79e944175
Minor update to docs; trigger readthedocs
[ { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.rst", "new_path": "docs/CHANGELOG.rst", "diff": "@@ -29,7 +29,7 @@ jax 0.1.60 (unreleased)\n* The minimum jaxlib version is now 0.1.41.\njaxlib 0.1.40 (March 4, 2020)\n-------------------------------\n+-------------------------------\n* Adds experimental support in Jaxlib for TensorFlow profiler, which allows\ntracing of CPU and GPU computations from TensorBoard.\n" } ]
Python
Apache License 2.0
google/jax
Minor update to docs; trigger readthedocs (#2434)
260,335
17.03.2020 22:07:53
25,200
f1d9130f2511be29b8c53a0b5f4f685009771af7
remove safe_mul (undo also cf.
[ { "change_type": "MODIFY", "old_path": "jax/lax/__init__.py", "new_path": "jax/lax/__init__.py", "diff": "@@ -16,11 +16,11 @@ from .lax import *\nfrom .lax import (_reduce_sum, _reduce_max, _reduce_min, _reduce_or,\n_reduce_and, _reduce_window_sum, _reduce_window_max,\n_reduce_window_min, _reduce_window_prod,\n- _select_and_gather_add, _float, _complex,\n- _input_dtype, _const, _eq_meet, _safe_mul,\n- _broadcasting_select, _check_user_dtype_supported,\n- _one, _const, _upcast_fp16_for_computation,\n- _broadcasting_shape_rule, _eye, _tri, _delta)\n+ _select_and_gather_add, _float, _complex, _input_dtype,\n+ _const, _eq_meet, _broadcasting_select,\n+ _check_user_dtype_supported, _one, _const,\n+ _upcast_fp16_for_computation, _broadcasting_shape_rule,\n+ _eye, _tri, _delta)\nfrom .lax_control_flow import *\nfrom .lax_fft import *\nfrom .lax_parallel import *\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1145,9 +1145,6 @@ def stop_gradient(x):\nreturn tree_map(stop_gradient_p.bind, x)\n-def _safe_mul(x, y): return safe_mul_p.bind(x, y)\n-\n-\n### convenience wrappers around traceables\n@@ -1674,7 +1671,7 @@ is_finite_p = unop(_fixed_dtype(onp.bool_), _float, 'is_finite')\nad.defjvp_zero(is_finite_p)\nexp_p = standard_unop(_float | _complex, 'exp')\n-ad.defjvp2(exp_p, lambda g, ans, x: _safe_mul(g, ans))\n+ad.defjvp2(exp_p, lambda g, ans, x: mul(g, ans))\nlog_p = standard_unop(_float | _complex, 'log')\nad.defjvp(log_p, lambda g, x: div(g, x))\n@@ -1804,21 +1801,18 @@ _maybe_conj = lambda x: conj(x) if _iscomplex(x) else x\n_maybe_real = lambda x: real(x) if _iscomplex(x) else x\nsqrt_p = standard_unop(_float | _complex, 'sqrt')\n-ad.defjvp2(sqrt_p, lambda g, ans, x: _safe_mul(g, div(_const(x, 0.5), ans)))\n+ad.defjvp2(sqrt_p, lambda g, ans, x: mul(g, div(_const(x, 0.5), ans)))\nrsqrt_p = standard_unop(_float | _complex, 'rsqrt')\nad.defjvp2(rsqrt_p,\nlambda g, ans, x:\n- _safe_mul(g, mul(_const(x, -0.5), pow(x, _const(x, -1.5)))))\n+ mul(g, mul(_const(x, -0.5), pow(x, _const(x, -1.5)))))\npow_p = standard_naryop([_float | _complex, _float | _complex], 'pow')\ndef _pow_jvp_lhs(g, ans, x, y):\n- # we call _safe_mul here so that we get the behavior 0*inf = 0, since when a\n- # coefficient in `g` is zero we want to keep it at zero, not produce a nan.\n- # see https://github.com/google/jax/pull/383\njac = mul(y, pow(x, select(eq(y, _zeros(y)), _ones(y), sub(y, _ones(y)))))\n- return _safe_mul(_brcast(g, y), jac)\n+ return mul(_brcast(g, y), jac)\ndef _pow_jvp_rhs(g, ans, x, y):\nreturn mul(_brcast(g, x), mul(log(_replace_zero(x)), ans))\n@@ -1859,19 +1853,6 @@ ad.primitive_transposes[sub_p] = _sub_transpose\nmul_p = standard_naryop([_num, _num], 'mul')\nad.defbilinear_broadcasting(_brcast, mul_p, mul, mul)\n-def _safe_mul_translation_rule(c, x, y):\n- dtype = c.GetShape(x).numpy_dtype()\n- zero = c.Constant(onp.array(0, dtype=dtype))\n- out_shape = broadcast_shapes(c.GetShape(x).dimensions(),\n- c.GetShape(y).dimensions())\n- return c.Select(c.Or(c.Eq(x, zero), c.Eq(y, zero)),\n- c.Broadcast(zero, out_shape),\n- c.Mul(x, y))\n-\n-safe_mul_p = standard_naryop([_num, _num], 'safe_mul',\n- translation_rule=_safe_mul_translation_rule)\n-ad.defbilinear_broadcasting(_brcast, safe_mul_p, _safe_mul, _safe_mul)\n-\ndef _div_transpose_rule(cotangent, x, y):\nassert ad.is_undefined_primal(x) and not ad.is_undefined_primal(y)\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax_parallel.py", "new_path": "jax/lax/lax_parallel.py", "diff": "@@ -519,7 +519,6 @@ _defbroadcasting(lax.xor_p)\n_defbroadcasting(lax.add_p)\n_defbroadcasting(lax.sub_p)\n_defbroadcasting(lax.mul_p)\n-_defbroadcasting(lax.safe_mul_p)\n_defbroadcasting(lax.div_p)\n_defbroadcasting(lax.rem_p)\n_defbroadcasting(lax.max_p)\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/special.py", "new_path": "jax/scipy/special.py", "diff": "@@ -113,13 +113,13 @@ def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):\n@_wraps(osp_special.xlogy)\ndef xlogy(x, y):\nx, y = _promote_args_inexact(\"xlogy\", x, y)\n- return lax._safe_mul(x, lax.log(y))\n+ return lax.mul(x, lax.log(y))\n@_wraps(osp_special.xlog1py, update_doc=False)\ndef xlog1py(x, y):\nx, y = _promote_args_inexact(\"xlog1py\", x, y)\n- return lax._safe_mul(x, lax.log1p(y))\n+ return lax.mul(x, lax.log1p(y))\n@_wraps(osp_special.entr)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -2113,17 +2113,20 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\njax_numpy_result = ((x + x.T) / 2).dtype\nself.assertEqual(orig_numpy_result, jax_numpy_result)\n- def testIssue347(self):\n- # https://github.com/google/jax/issues/347\n- def test_fail(x):\n- x = jnp.sqrt(jnp.sum(x ** 2, axis=1))\n- ones = jnp.ones_like(x)\n- x = jnp.where(x > 0.5, x, ones)\n- return jnp.sum(x)\n-\n- x = jnp.array([[1, 2], [3, 4], [0, 0]], dtype=jnp.float64)\n- result = api.grad(test_fail)(x)\n- assert not onp.any(onp.isnan(result))\n+ # NOTE(mattjj): I disabled this test when removing lax._safe_mul because\n+ # introducing the convention 0 * inf = 0 leads to silently wrong results in\n+ # some cases. See this comment for details:\n+ # https://github.com/google/jax/issues/1052#issuecomment-514083352\n+ # def testIssue347(self):\n+ # # https://github.com/google/jax/issues/347\n+ # def test_fail(x):\n+ # x = jnp.sqrt(jnp.sum(x ** 2, axis=1))\n+ # ones = jnp.ones_like(x)\n+ # x = jnp.where(x > 0.5, x, ones)\n+ # return jnp.sum(x)\n+ # x = jnp.array([[1, 2], [3, 4], [0, 0]], dtype=jnp.float64)\n+ # result = api.grad(test_fail)(x)\n+ # assert not onp.any(onp.isnan(result))\ndef testIssue453(self):\n# https://github.com/google/jax/issues/453\n@@ -2240,11 +2243,14 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself.assertAllClose(onp.zeros(3,), api.grad(f)(onp.ones(3,)),\ncheck_dtypes=True)\n- def testIssue777(self):\n- x = jnp.linspace(-200, 0, 4, dtype=onp.float32)\n- f = api.grad(lambda x: jnp.sum(1 / (1 + jnp.exp(-x))))\n- self.assertAllClose(f(x), onp.array([0., 0., 0., 0.25], dtype=onp.float32),\n- check_dtypes=True)\n+ # NOTE(mattjj): I disabled this test when removing lax._safe_mul because this\n+ # is a numerical stability issue that should be solved with a custom jvp rule\n+ # of the sigmoid function being differentiated here, not by safe_mul.\n+ # def testIssue777(self):\n+ # x = jnp.linspace(-200, 0, 4, dtype=onp.float32)\n+ # f = api.grad(lambda x: jnp.sum(1 / (1 + jnp.exp(-x))))\n+ # self.assertAllClose(f(x), onp.array([0., 0., 0., 0.25], dtype=onp.float32),\n+ # check_dtypes=True)\n@parameterized.named_parameters(\njtu.cases_from_list(\n" } ]
Python
Apache License 2.0
google/jax
remove safe_mul (undo #383, also cf. #1052)
260,411
19.03.2020 06:56:59
-3,600
cd7ab0a9e0476043f1a3f4a029d6e088a63c3e29
Changed to pmap_benchmark to make it runnable in Google
[ { "change_type": "MODIFY", "old_path": "benchmarks/pmap_benchmark.py", "new_path": "benchmarks/pmap_benchmark.py", "diff": "@@ -18,12 +18,15 @@ python3 pmap_benchmark.py\nTo make it run faster, set env var TARGET_TOTAL_SECS to a low number (e.g. 2).\n\"\"\"\n-import numpy as onp\n+from absl import app\n-from benchmark import benchmark_suite\nimport jax\n-import jax.numpy as np\n+from jax import numpy as np\nfrom jax import pmap\n+from jax.benchmarks import benchmark\n+from jax.config import config\n+\n+import numpy as onp\ndef pmap_shard_args_benchmark():\n@@ -38,7 +41,8 @@ def pmap_shard_args_benchmark():\nshape = (nshards, 4)\nargs = [onp.random.random(shape) for _ in range(nargs)]\nsharded_args = pmap(lambda x: x)(args)\n- assert all(type(arg) == jax.pxla.ShardedDeviceArray for arg in sharded_args)\n+ assert all(isinstance(arg, jax.pxla.ShardedDeviceArray)\n+ for arg in sharded_args)\ndef benchmark_fn():\nfor _ in range(100):\npmap_fn(*sharded_args)\n@@ -51,7 +55,7 @@ def pmap_shard_args_benchmark():\nfor nshards in (2, 4, 8, 100, 500):\nif nshards > jax.local_device_count(): continue\nparams.append({\"nargs\": 10, \"nshards\": nshards})\n- benchmark_suite(get_benchmark_fn, params, \"pmap_shard_args\")\n+ benchmark.benchmark_suite(get_benchmark_fn, params, \"pmap_shard_args\")\ndef pmap_shard_outputs_benchmark():\n@@ -76,7 +80,7 @@ def pmap_shard_outputs_benchmark():\nfor nshards in (2, 4, 8, 100, 500):\nif nshards > jax.local_device_count(): continue\nparams.append({\"nouts\": 10, \"nshards\": nshards})\n- benchmark_suite(get_benchmark_fn, params, \"pmap_shard_outputs\")\n+ benchmark.benchmark_suite(get_benchmark_fn, params, \"pmap_shard_outputs\")\ndef run_all_benchmarks():\n@@ -84,5 +88,10 @@ def run_all_benchmarks():\npmap_shard_outputs_benchmark()\n-if __name__ == \"__main__\":\n+def main(unused_argv):\nrun_all_benchmarks()\n+\n+\n+if __name__ == \"__main__\":\n+ config.config_with_absl()\n+ app.run(main)\n" } ]
Python
Apache License 2.0
google/jax
Changed to pmap_benchmark to make it runnable in Google (#2448)
260,411
19.03.2020 08:54:37
-3,600
78c1f6b08d60f3f6c8252a2b6dd05fcef5ad8afb
Increased tolerance for testScipySpecialFun Prevent failures on TPU
[ { "change_type": "MODIFY", "old_path": "jax/test_util.py", "new_path": "jax/test_util.py", "diff": "@@ -18,7 +18,7 @@ import functools\nimport re\nimport itertools as it\nimport os\n-from typing import Dict, Sequence\n+from typing import Dict, Sequence, Union\nfrom unittest import SkipTest\nfrom absl.testing import absltest\n@@ -295,6 +295,15 @@ def count_jit_and_pmap_compiles():\ndef device_under_test():\nreturn FLAGS.jax_test_dut or xla_bridge.get_backend().platform\n+def if_device_under_test(device_type: Union[str, Sequence[str]],\n+ if_true, if_false):\n+ \"\"\"Chooses `if_true` of `if_false` based on device_under_test.\"\"\"\n+ if device_under_test() in ([device_type] if isinstance(device_type, str)\n+ else device_type):\n+ return if_true\n+ else:\n+ return if_false\n+\ndef supported_dtypes():\nif device_under_test() == \"tpu\":\nreturn {onp.bool_, onp.int32, onp.uint32, dtypes.bfloat16, onp.float32,\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -136,7 +136,8 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nself._CompileAndCheck(lax_op, args_maker, check_dtypes=True, rtol=1e-5)\nif test_autodiff:\n- jtu.check_grads(lax_op, args, order=1, atol=1e-3, rtol=3e-3, eps=1e-3)\n+ jtu.check_grads(lax_op, args, order=1,\n+ atol=jtu.if_device_under_test(\"tpu\", 2e-3, 1e-3), rtol=3e-3, eps=1e-3)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_inshape={}_d={}\".format(\n" } ]
Python
Apache License 2.0
google/jax
Increased tolerance for testScipySpecialFun (#2454) Prevent failures on TPU
260,335
19.03.2020 11:26:29
25,200
1d0b7e2b5c7c4fc1c46a8065f12ce1e56378d9a8
make jaxpr pretty-print show multiple outputs
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -968,11 +968,7 @@ def pp_eqn(eqn):\n>> pp(' ') >> pp(pp_vars(eqn.invars))) + pp_subexpr\ndef pp_jaxpr(jaxpr):\n- if len(jaxpr.outvars) > 1:\npp_outvars = str(tuple(jaxpr.outvars))\n- else:\n- pp_outvars = str(jaxpr.outvars[0])\n-\nreturn (pp('{{ lambda {} ; {}.'.format(pp_vars(jaxpr.constvars),\npp_vars(jaxpr.invars))) +\n((pp('let ') >>\n" } ]
Python
Apache License 2.0
google/jax
make jaxpr pretty-print show multiple outputs
260,335
19.03.2020 11:28:35
25,200
7f8ce8ff3c927d4d2a251af71c2ee4388cf6da26
fix test errors from previous commit
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "new_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "diff": "\"\\n\",\n\"jaxpr: { lambda ; ; a.\\n\",\n\" let b = add a 1\\n\",\n- \" in [b] }\\n\",\n+ \" in (b,) }\\n\",\n\"\\n\",\n\"\\n\",\n\"bar\\n\",\n\" precision=None ] a c\\n\",\n\" e = add d b\\n\",\n\" g = add e f\\n\",\n- \" in [g, c] }\\n\",\n+ \" in (g, c) }\\n\",\n\"\\n\"\n]\n}\n\"{ lambda ; ; a.\\n\",\n\" let b = tanh a\\n\",\n\" c = exp b\\n\",\n- \" in [c] }\\n\",\n+ \" in (c,) }\\n\",\n\"\\n\",\n\"()\\n\"\n]\n\" j = tie_in b nan\\n\",\n\" k = broadcast[ sizes=() ] j\\n\",\n\" l = select d i k\\n\",\n- \" in [l] }\"\n+ \" in (l,) }\"\n]\n},\n\"execution_count\": 14,\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1861,12 +1861,12 @@ class JaxprTest(jtu.JaxTestCase):\nd = add a 2.0\ne = cond[ false_jaxpr={ lambda ; b a.\nlet c = sub a b\n- in c }\n+ in (c,) }\nlinear=(False, False, False, False)\ntrue_jaxpr={ lambda ; b a.\nlet c = add a b\n- in c } ] b a c a d\n- in e }\n+ in (c,) } ] b a c a d\n+ in (e,) }\n\"\"\", str(jaxpr))\ndef testExamplesJaxprDoc(self):\n@@ -1883,7 +1883,7 @@ class JaxprTest(jtu.JaxTestCase):\nd = mul c 3.0\ne = add a d\nf = reduce_sum[ axes=(0,) ] e\n- in f }\n+ in (f,) }\n\"\"\", str(jaxpr))\ndef func5(first, second):\n@@ -1898,7 +1898,7 @@ class JaxprTest(jtu.JaxTestCase):\n{ lambda b d ; a.\nlet c = add a b\ne = sub c d\n- in e }\n+ in (e,) }\n\"\"\", str(jaxpr))\ndef func7(arg):\n@@ -1914,12 +1914,12 @@ class JaxprTest(jtu.JaxTestCase):\nlet b = ge a 0.0\nc = cond[ false_jaxpr={ lambda ; a.\nlet b = sub a 3.0\n- in b }\n+ in (b,) }\nlinear=(False, False)\ntrue_jaxpr={ lambda ; a.\nlet b = add a 3.0\n- in b } ] b a a\n- in c }\n+ in (b,) } ] b a a\n+ in (c,) }\n\"\"\", str(jaxpr))\ndef func8(arg1, arg2): # arg2 is a pair\n@@ -1935,12 +1935,12 @@ class JaxprTest(jtu.JaxTestCase):\nlet d = ge a 0.0\nf = cond[ false_jaxpr={ lambda ; c a b.\nlet d = add c b\n- in d }\n+ in (d,) }\nlinear=(False, False, False, False, False)\ntrue_jaxpr={ lambda ; a b.\nlet\n- in a } ] d b c e b c\n- in f }\n+ in (a,) } ] d b c e b c\n+ in (f,) }\n\"\"\", str(jaxpr))\ndef func10(arg, n):\n@@ -1961,9 +1961,9 @@ class JaxprTest(jtu.JaxTestCase):\nbody_nconsts=2\ncond_jaxpr={ lambda ; a b c.\nlet d = lt a b\n- in d }\n+ in (d,) }\ncond_nconsts=0 ] c a 0 b e\n- in h }\n+ in (h,) }\n\"\"\", str(jaxpr))\ndef func11(arr, extra):\n@@ -2008,11 +2008,11 @@ class JaxprTest(jtu.JaxTestCase):\ncall_jaxpr={ lambda ; c b a.\nlet d = mul b c\ne = add a d\n- in e }\n+ in (e,) }\ndevice=None\nname=inner ] b a c\ne = add a d\n- in e }\n+ in (e,) }\n\"\"\", str(jaxpr))\ndef func13(arr, extra):\n@@ -2033,12 +2033,12 @@ class JaxprTest(jtu.JaxTestCase):\ne = add c d\nf = psum[ axis_name=rows ] a\ng = div e f\n- in g }\n+ in (g,) }\ndevices=None\nglobal_axis_size=None\nmapped_invars=(True, False, True)\nname=inner ] c b a\n- in d }\n+ in (d,) }\n\"\"\", str(jaxpr))\nclass LazyTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
fix test errors from previous commit
260,411
21.03.2020 13:53:35
-3,600
9331fc5b428c573461c070d81b6582904462b932
Added pytype checking to Travis
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -6,7 +6,7 @@ language: python\nmatrix:\ninclude:\n- python: \"3.6\"\n- env: JAX_CHECK_TYPES=true\n+ env: JAX_ONLY_CHECK_TYPES=true\n- python: \"3.6\"\nenv: JAX_ENABLE_X64=0 JAX_NUM_GENERATED_CASES=25\n- python: \"3.6\"\n@@ -25,7 +25,7 @@ before_install:\n- conda config --add channels conda-forge\n- conda update -q conda\ninstall:\n- - conda install --yes python=$TRAVIS_PYTHON_VERSION pip absl-py opt_einsum numpy scipy pytest-xdist pytest-benchmark mypy\n+ - conda install --yes python=$TRAVIS_PYTHON_VERSION pip absl-py opt_einsum numpy scipy pytest-xdist pytest-benchmark mypy pytype\n# The jaxlib version should match the minimum jaxlib version in\n# jax/lib/__init__.py. This tests JAX PRs against the oldest permitted\n# jaxlib.\n@@ -40,8 +40,9 @@ install:\nscript:\n- if [ \"$JAX_ONLY_DOCUMENTATION\" = true ]; then\nsphinx-build -b html -D nbsphinx_execute=always docs docs/build/html ;\n- elif [ \"$JAX_CHECK_TYPES\" = true ]; then\n+ elif [ \"$JAX_ONLY_CHECK_TYPES\" = true ]; then\nmypy --config-file=mypy.ini jax ;\n+ pytype jax ;\nelse\npytest -n 1 tests examples -W ignore ;\nfi\n" } ]
Python
Apache License 2.0
google/jax
Added pytype checking to Travis (#2475)
260,335
21.03.2020 10:46:07
25,200
93d3e347211405d3b8cf10fd1e671cdc7bf6b835
make lax_linalg.solve_triangular allow vector rhs also add tests for jax.scipy.linalg.cho_solve
[ { "change_type": "MODIFY", "old_path": "jax/lax_linalg.py", "new_path": "jax/lax_linalg.py", "diff": "@@ -70,9 +70,15 @@ def svd(x, full_matrices=True, compute_uv=True):\ndef triangular_solve(a, b, left_side=False, lower=False, transpose_a=False,\nconjugate_a=False, unit_diagonal=False):\nconjugate_a = conjugate_a and np.issubdtype(lax.dtype(a), np.complexfloating)\n- return triangular_solve_p.bind(\n+ singleton = np.ndim(b) == np.ndim(a) - 1\n+ if singleton:\n+ b = np.expand_dims(b, -1 if left_side else -2)\n+ out = triangular_solve_p.bind(\na, b, left_side=left_side, lower=lower, transpose_a=transpose_a,\nconjugate_a=conjugate_a, unit_diagonal=unit_diagonal)\n+ if singleton:\n+ out = out[..., 0] if left_side else out[..., 0, :]\n+ return out\n# utilities\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/linalg.py", "new_path": "jax/scipy/linalg.py", "diff": "@@ -46,15 +46,11 @@ def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):\ndef _cho_solve(c, b, lower):\nc, b = np_linalg._promote_arg_dtypes(np.asarray(c), np.asarray(b))\nnp_linalg._check_solve_shapes(c, b)\n- # TODO(phawkins): triangular_solve only supports matrices on the RHS, so we\n- # add a dummy dimension. Extend it to support vectors and simplify this.\n- rhs_vector = c.ndim == b.ndim + 1\n- b = b[..., np.newaxis] if rhs_vector else b\nb = lax_linalg.triangular_solve(c, b, left_side=True, lower=lower,\ntranspose_a=not lower, conjugate_a=not lower)\nb = lax_linalg.triangular_solve(c, b, left_side=True, lower=lower,\ntranspose_a=lower, conjugate_a=lower)\n- return b[..., 0] if rhs_vector else b\n+ return b\n@_wraps(scipy.linalg.cho_solve, update_doc=False)\ndef cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -1037,8 +1037,10 @@ class ScipyLinalgTest(jtu.JaxTestCase):\nfor conjugate_a in (\n[False] if np.issubdtype(dtype, np.floating) else [False, True])\nfor left_side, a_shape, b_shape in [\n+ (False, (4, 4), (4,)),\n(False, (4, 4), (1, 4,)),\n(False, (3, 3), (4, 3)),\n+ (True, (4, 4), (4,)),\n(True, (4, 4), (4, 1)),\n(True, (4, 4), (4, 3)),\n(True, (2, 8, 8), (2, 8, 10)),\n@@ -1139,5 +1141,35 @@ class ScipyLinalgTest(jtu.JaxTestCase):\ncheck_dtypes=True)\nself._CompileAndCheck(jsp_fun, args_maker_zeros, check_dtypes=True)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_lhs={}_rhs={}_lower={}\".format(\n+ jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype),\n+ lower),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"rng_factory\": rng_factory, \"lower\": lower}\n+ for lhs_shape, rhs_shape in [\n+ [(1, 1), (1,)],\n+ [(4, 4), (4,)],\n+ [(4, 4), (4, 4)],\n+ ]\n+ for dtype in float_types\n+ for lower in [True, False]\n+ for rng_factory in [jtu.rand_default]))\n+ def testChoSolve(self, lhs_shape, rhs_shape, dtype, lower, rng_factory):\n+ rng = rng_factory()\n+ _skip_if_unsupported_type(dtype)\n+ def args_maker():\n+ b = rng(rhs_shape, dtype)\n+ if lower:\n+ L = onp.tril(rng(lhs_shape, dtype))\n+ return [(L, lower), b]\n+ else:\n+ U = onp.triu(rng(lhs_shape, dtype))\n+ return [(U, lower), b]\n+ self._CheckAgainstNumpy(osp.linalg.cho_solve, jsp.linalg.cho_solve,\n+ args_maker, check_dtypes=True, tol=1e-3)\n+\n+\nif __name__ == \"__main__\":\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
make lax_linalg.solve_triangular allow vector rhs also add tests for jax.scipy.linalg.cho_solve
260,335
21.03.2020 21:20:12
25,200
6876271bac7d4ce68118190f06e003e004b070a9
bump tolerance for mvn logpdf x64 test
[ { "change_type": "MODIFY", "old_path": "tests/scipy_stats_test.py", "new_path": "tests/scipy_stats_test.py", "diff": "@@ -441,7 +441,7 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nlsp_stats.multivariate_normal.logpdf,\nargs_maker, check_dtypes=True, tol=1e-3)\nself._CompileAndCheck(lsp_stats.multivariate_normal.logpdf, args_maker,\n- check_dtypes=True)\n+ check_dtypes=True, rtol=1e-4, atol=1e-4)\nif __name__ == \"__main__\":\n" } ]
Python
Apache License 2.0
google/jax
bump tolerance for mvn logpdf x64 test
260,335
23.03.2020 12:18:59
25,200
c76f32b1be7a6e22a23948fc8265a5351b54007f
remove jarrett and _make_graphviz, bitrot might want to revive jarrett later!
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1906,94 +1906,6 @@ def custom_gradient(fun):\nreturn primal_fun\n-def jarrett(fun):\n- new_fun = custom_transforms(fun)\n-\n- def elementwise_jvp(primals, tangents):\n- pushfwd = partial(jvp, fun, primals)\n- y, jacs = vmap(pushfwd, out_axes=(None, 0))(_elementwise_std_basis(tangents))\n- flat_tangents, _ = tree_flatten(tangents)\n- out_tangent = sum([t * jac for t, jac in zip(flat_tangents, jacs)])\n- return y, out_tangent\n- defjvp_all(new_fun, elementwise_jvp)\n-\n- return new_fun\n-\n-def _elementwise_std_basis(pytree):\n- leaves, _ = tree_flatten(pytree)\n- arity = len(leaves)\n- dims = map(onp.size, leaves)\n- # TODO(mattjj): use symbolic constants\n- dtype = dtypes.result_type(*leaves)\n- if not dtypes.issubdtype(dtype, onp.floating):\n- msg = (\"Jacobian only defined for functions with floating input and output \"\n- \"dtypes (i.e. dtypes that model real numbers), got {}.\")\n- raise TypeError(msg.format(dtype)) # TODO(mattjj, dougalm): handle complex\n- basis_array = onp.stack([onp.concatenate(\n- [onp.ones(dims[j], dtype) if i == j else onp.zeros(dims[j], dtype)\n- for j in range(arity)]) for i in range(arity)])\n- return _unravel_array_into_pytree(pytree, 1, basis_array)\n-\n-\n-# This function mostly exists for making slides about JAX.\n-def _make_graphviz(fun):\n- \"\"\"Adapts `fun` to return a graphviz dot string of its program representation.\n-\n- Args:\n- fun: The function whose `jaxpr` is to be rendered into graphviz dot. Its\n- positional arguments and return value should be arrays, scalars, or\n- standard Python containers (tuple/list/dict) thereof.\n-\n- Returns:\n- A wrapped version of `fun`, set up to return a graphviz dot string.\n-\n- See make_jaxpr for a related function.\n- \"\"\"\n- # TODO(mattjj): handle eqn.restructure\n- # TODO(mattjj): handle subjaxprs\n-\n- def pv_like(x):\n- aval = xla.abstractify(x)\n- return pe.PartialVal((aval, core.unit))\n-\n- id_names = (\"id{}\".format(i) for i in it.count())\n-\n- def jaxpr_to_graphviz(jaxpr, consts):\n- fragment = []\n-\n- fragment.extend(map(invar_node, jaxpr.invars, jaxpr.invars))\n- fragment.extend(map(constant_node, jaxpr.constvars, consts))\n-\n- for eqn in jaxpr.eqns:\n- id_name = next(id_names)\n- fragment.append(function_node(id_name, eqn.primitive.name))\n- fragment.extend(edge(invar, id_name) for invar in eqn.invars)\n- fragment.extend(edge(id_name, outvar) for outvar in eqn.outvars)\n- for ov in jaxpr.outvars:\n- fragment.append(outvar_node(ov, \"out\"))\n- return graph(''.join(fragment))\n-\n- edge = '{} -> {} [color=gray30];\\n'.format\n- function_node = '{} [label=\"{}\", shape=box, color=lightskyblue, style=filled];\\n'.format\n- invar_node = '{} [rank=2, label=\"{}\", color=mediumspringgreen, style=filled];\\n'.format\n- outvar_node = '{} [label=\"{}\", fillcolor=indianred1, style=\"filled,dashed\", color=black];\\n'.format\n- constant_node = '{} [rank=2, label=\"{}\", color=goldenrod1, style=filled];\\n'.format\n- freevar_node = '{} [rank=2, label=\"{}\", color=palegreen, style=filled];\\n'.format\n- graph = 'digraph G {{{}}}'.format\n-\n- @wraps(fun)\n- def graphviz_maker(*args, **kwargs):\n- wrapped = lu.wrap_init(fun, kwargs)\n- jax_args, in_tree = tree_flatten((args, kwargs))\n- jaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)\n- pvals = map(pv_like, jax_args)\n- jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals)\n- return jaxpr_to_graphviz(jaxpr, consts)\n-\n- graphviz_maker.__name__ = \"make_graphviz({})\".format(graphviz_maker.__name__)\n- return graphviz_maker\n-\n-\nclass ShapeDtypeStruct(object):\n__slots__ = [\"shape\", \"dtype\"]\ndef __init__(self, shape, dtype):\n" } ]
Python
Apache License 2.0
google/jax
remove jarrett and _make_graphviz, bitrot might want to revive jarrett later!
260,335
23.03.2020 18:43:02
25,200
0cf84f925b049264ca2f18d95d87b7305ab36bac
fix custom_transforms bug
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1609,7 +1609,8 @@ def custom_transforms(fun):\nad.primitive_jvps[fun_p] = fun_jvp\ndef fun_batch(args, dims, **params):\n- return batching.batch_fun(lu.wrap_init(fun_impl, params), args, dims)\n+ batched, out_dims = batching.batch_fun2(lu.wrap_init(fun_impl, params), dims)\n+ return batched.call_wrapped(*args), out_dims()\nbatching.primitive_batchers[fun_p] = fun_batch\ndef fun_abstract_eval(*avals, **params):\n" } ]
Python
Apache License 2.0
google/jax
fix custom_transforms bug
260,499
25.03.2020 02:10:06
0
b05ac57938e942b9b011ebe9991126bf7245dbca
Making isclose handle correctly infinite and NaN values.
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -974,7 +974,7 @@ def moveaxis(a, source, destination):\n@_wraps(onp.isclose)\n-def isclose(a, b, rtol=1e-05, atol=1e-08):\n+def isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):\na, b = _promote_args(\"isclose\", asarray(a), asarray(b))\ndtype = _dtype(a)\nif issubdtype(dtype, inexact):\n@@ -985,6 +985,27 @@ def isclose(a, b, rtol=1e-05, atol=1e-08):\nout = lax.le(\nlax.abs(lax.sub(a, b)),\nlax.add(atol, lax.mul(rtol, lax.abs(b))))\n+ # This corrects the comparisons for infinite and nan values\n+ a_inf = isinf(a)\n+ b_inf = isinf(b)\n+ any_inf = logical_or(a_inf, b_inf)\n+ both_inf = logical_and(a_inf, b_inf)\n+ # Make all elements where either a or b are infinite to False\n+ out = logical_and(out, logical_not(any_inf))\n+ # Make all elements where both a or b are the same inf to True\n+ same_value = lax.eq(a, b)\n+ same_inf = logical_and(both_inf, same_value)\n+ out = logical_or(out, same_inf)\n+\n+ # Make all elements where either a or b is NaN to False\n+ a_nan = isnan(a)\n+ b_nan = isnan(b)\n+ any_nan = logical_or(a_nan, b_nan)\n+ out = logical_and(out, logical_not(any_nan))\n+ if equal_nan:\n+ # Make all elements where both a and b is NaN to True\n+ both_nan = logical_and(a_nan, b_nan)\n+ out = logical_or(out, both_nan)\nreturn _maybe_numpy_1_13_isclose_behavior(a, out)\nelse:\nreturn lax.eq(a, b)\n" } ]
Python
Apache License 2.0
google/jax
Making isclose handle correctly infinite and NaN values.
260,335
24.03.2020 20:43:33
25,200
74c20509ebcf9d467fafbcb5e655475a0e4bdc77
improve custom_jvp error messages, fixes
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -708,6 +708,13 @@ class UnshapedArray(AbstractValue):\n\"\"\"Returns a copy of the aval with weak_type=False.\"\"\"\nreturn UnshapedArray(self.dtype) if self.weak_type else self\n+ @property\n+ def shape(self):\n+ msg = (\"UnshapedArray has no shape. Please open an issue at \"\n+ \"https://github.com/google/jax/issues because it's unexpected for \"\n+ \"UnshapedArray instances to ever be produced.\")\n+ raise TypeError(msg)\n+\nclass ShapedArray(UnshapedArray):\n__slots__ = ['shape']\narray_abstraction_level = 1\n" }, { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -186,8 +186,23 @@ def _flatten_jvp(in_tree, *args):\ntangents_out, out_tree2 = tree_flatten(py_tangents_out)\nif out_tree != out_tree2:\nmsg = (\"Custom JVP rule must produce primal and tangent outputs with equal \"\n- \"container (pytree) structures, but got {} and {}.\")\n+ \"container (pytree) structures, but got {} and {} respectively.\")\nraise TypeError(msg.format(out_tree, out_tree2)) from None\n+ primal_avals_out = [raise_to_shaped(core.get_aval(x)) for x in primals_out]\n+ tangent_avals_out = [raise_to_shaped(core.get_aval(t)) for t in tangents_out]\n+ if primal_avals_out != tangent_avals_out:\n+ if len(primal_avals_out) == 1:\n+ (av1,), (av2,) = primal_avals_out, tangent_avals_out\n+ msg = (\"Custom JVP rule must produce primal and tangent outputs with \"\n+ \"equal shapes and dtypes, but got {} and {} respectively.\")\n+ raise TypeError(msg.format(av1.str_short(), av2.str_short()))\n+ else:\n+ msg = (\"Custom JVP rule must produce primal and tangent outputs with \"\n+ \"equal shapes and dtypes, but got:\\n{}\")\n+ disagreements = (\n+ \" primal {} for tangent {}\".format(av1.str_short(), av2.str_short())\n+ for av1, av2 in zip(primal_avals_out, tangent_avals_out) if av1 != av2)\n+ raise TypeError(msg.format('\\n'.join(disagreements)))\nyield primals_out + tangents_out, out_tree\ndef _custom_deriv_call_bind(primitive, f, *args, **params):\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax_control_flow.py", "new_path": "jax/lax/lax_control_flow.py", "diff": "@@ -1309,9 +1309,9 @@ def _check_tree(func_name, expected_name, actual_tree, expected_tree):\ndef _check_tree_and_avals(what, tree1, avals1, tree2, avals2):\n\"\"\"Raises TypeError if (tree1, avals1) does not match (tree2, avals2).\n- Corresponding `tree` and `avals` must match in the sense that the number of leaves in\n- `tree` must be equal to the length of `avals`.\n- `what` will be prepended to details of the mismatch in TypeError.\n+ Corresponding `tree` and `avals` must match in the sense that the number of\n+ leaves in `tree` must be equal to the length of `avals`. `what` will be\n+ prepended to details of the mismatch in TypeError.\n\"\"\"\nif tree1 != tree2:\nmsg = (\"{} must have same type structure, got {} and {}.\")\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2228,7 +2228,7 @@ class CustomJVPTest(jtu.JaxTestCase):\ndef test_pmap(self):\nraise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n- def test_missing_jvp_rule_error(self):\n+ def test_missing_jvp_rule_error_message(self):\n@api.custom_jvp\ndef foo(x):\nreturn x ** 2\n@@ -2246,7 +2246,7 @@ class CustomJVPTest(jtu.JaxTestCase):\nr\"No JVP defined for custom_jvp function foo using defjvp.\",\nlambda: api.grad(foo)(2.))\n- def test_jvp_rule_inconsistent_pytree_structures_error(self):\n+ def test_jvp_rule_inconsistent_pytree_structures_error_message(self):\n@api.custom_jvp\ndef f(x):\nreturn (x**2,)\n@@ -2263,12 +2263,32 @@ class CustomJVPTest(jtu.JaxTestCase):\nre.escape(\n\"Custom JVP rule must produce primal and tangent outputs \"\n\"with equal container (pytree) structures, but got \"\n- \"{} and {}.\".format(\n+ \"{} and {} respectively.\".format(\ntree_util.tree_structure((1,)),\ntree_util.tree_structure([1, 2]))\n),\nlambda: api.jvp(f, (2.,), (1.,)))\n+ def test_primal_tangent_aval_disagreement_error_message(self):\n+ @api.custom_jvp\n+ def f(x):\n+ return x ** 2\n+\n+ @f.defjvp\n+ def foo_jvp(primals, tangents):\n+ x, = primals\n+ t, = tangents\n+ return f(x), np.reshape(t, (1,))\n+\n+ f(2.) # doesn't crash\n+ self.assertRaisesRegex(\n+ TypeError,\n+ re.escape(\n+ \"Custom JVP rule must produce primal and tangent outputs \"\n+ \"with equal shapes and dtypes, but got float32[] and float32[1] \"\n+ \"respectively.\"),\n+ lambda: api.jvp(f, (np.float32(2.),), (np.float32(1.),)))\n+\nclass CustomVJPTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
improve custom_jvp error messages, fixes #2502
260,411
25.03.2020 11:07:50
-7,200
d1e8f43abe5c369ee5405e423c5ba601d2cc631c
Better error message for indexing with floats Now the error message is 'Indexer must have integer or boolean type'. Before it was 'len() of unsized object'
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -3032,8 +3032,8 @@ def _index_to_gather(x_shape, idx):\ny_axis += 1\nx_axis += 1\nelse:\n- if abstract_i and not (issubdtype(abstract_i.dtype, integer) or\n- issubdtype(abstract_i.dtype, bool_)):\n+ if (abstract_i is not None and\n+ not (issubdtype(abstract_i.dtype, integer) or issubdtype(abstract_i.dtype, bool_))):\nmsg = (\"Indexer must have integer or boolean type, got indexer \"\n\"with type {} at position {}, indexer value {}\")\nraise TypeError(msg.format(abstract_i.dtype.name, idx_pos, i))\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_indexing_test.py", "new_path": "tests/lax_numpy_indexing_test.py", "diff": "@@ -754,8 +754,20 @@ class IndexingTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef testFloatIndexingError(self):\n- x = jnp.array([1, 2, 3])\n- self.assertRaises(TypeError, lambda: x[3.5])\n+ BAD_INDEX_TYPE_ERROR = \"Indexer must have integer or boolean type, got indexer with type\"\n+ with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n+ jnp.zeros(2)[0.]\n+ with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n+ jnp.zeros((2, 2))[(0, 0.)]\n+ with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n+ jnp.zeros((2, 2))[(0, 0.)]\n+ with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n+ api.jit(lambda idx: jnp.zeros((2, 2))[idx])((0, 0.))\n+ with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n+ ops.index_add(jnp.zeros(2), 0., 1.)\n+ with self.assertRaisesRegex(TypeError, BAD_INDEX_TYPE_ERROR):\n+ ops.index_update(jnp.zeros(2), 0., 1.)\n+\ndef testIndexOutOfBounds(self): # https://github.com/google/jax/issues/2245\narray = jnp.ones(5)\n" } ]
Python
Apache License 2.0
google/jax
Better error message for indexing with floats (#2496) Now the error message is 'Indexer must have integer or boolean type'. Before it was 'len() of unsized object'
260,411
19.03.2020 14:55:16
-3,600
6f2f779a3d0ab831e1715347324a1810551c9aca
Started a FAQ for JAX
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/faq.rst", "diff": "+JAX Frequently Asked Questions\n+==============================\n+\n+We are collecting here answers to frequently asked questions.\n+Contributions welcome!\n+\n+Gradients contain `NaN` where using ``where``\n+------------------------------------------------\n+\n+If you define a function using ``where`` to avoid an undefined value, if you\n+are not careful you may obtain a `NaN` for reverse differentiation::\n+\n+ def my_log(x):\n+ return np.where(x > 0., np.log(x), 0.)\n+\n+ my_log(0.) ==> 0. # Ok\n+ jax.grad(my_log)(0.) ==> NaN\n+\n+A short explanation is that during ``grad`` computation the adjoint corresponding\n+to the undefined ``np.log(x)`` is a ``NaN`` and when it gets accumulated to the\n+adjoint of the ``np.where``. The correct way to write such functions is to ensure\n+that there is a ``np.where`` *inside* the partially-defined function, to ensure\n+that the adjoint is always finite::\n+\n+ def safe_for_grad_log(x):\n+ return np.log(np.where(x > 0., x, 1.)\n+\n+ safe_for_grad_log(0.) ==> 0. # Ok\n+ jax.grad(safe_for_grad_log)(0.) ==> 0. # Ok\n+\n+The inner ``np.where`` may be needed in addition to the original one, e.g.:\n+\n+ def my_log_or_y(x, y):\n+ \"\"\"Return log(x) if x > 0 or y\"\"\"\n+ return np.where(x > 0., np.log(np.where(x > 0., x, 1.), y)\n+\n+\n+Additional reading:\n+\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\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "docs/index.rst", "new_path": "docs/index.rst", "diff": "@@ -33,6 +33,7 @@ For an introduction to JAX, start at the\n:caption: Notes\nCHANGELOG\n+ faq\njaxpr\nasync_dispatch\nconcurrency\n" } ]
Python
Apache License 2.0
google/jax
Started a FAQ for JAX
260,411
22.03.2020 06:47:14
-3,600
86e3046e21d0b5374824656e4e8eeca1e20fea2a
Added a FAQ for impure functions
[ { "change_type": "MODIFY", "old_path": "docs/faq.rst", "new_path": "docs/faq.rst", "diff": "@@ -4,6 +4,48 @@ JAX Frequently Asked Questions\nWe are collecting here answers to frequently asked questions.\nContributions welcome!\n+`jit` changes the behavior of my function\n+-----------------------------------------\n+\n+If you have a Python function that changes behavior after using `jit`, perhaps\n+your function uses global state, or has side-effects. In the following code, the\n+`impure_func` uses the global `y` and has a side-effect due to `print`::\n+\n+ y = 0\n+\n+ # @jit # Different behavior with jit\n+ def impure_func(x):\n+ print(\"Inside:\", y)\n+ return x + y\n+\n+ for y in range(3):\n+ print(\"Result:\", impure_func(y))\n+\n+Without `jit` the output is::\n+\n+ Inside: 0\n+ Result: 0\n+ Inside: 1\n+ Result: 2\n+ Inside: 2\n+ Result: 4\n+\n+and with `jit` it is:\n+\n+ Inside: 0\n+ Result: 0\n+ Result: 1\n+ Result: 2\n+\n+For `jit` the function is executed once using the Python interpreter, at which time the\n+`Inside` printing happens, and the first value of `y` is observed. Then the function\n+is compiled and cached, and executed multiple times with different values of `x`, but\n+with the same first value of `y`.\n+\n+Additional reading:\n+\n+ * [JAX - The Sharp Bits: Pure Functions](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#%F0%9F%94%AA-Pure-functions)\n+\nGradients contain `NaN` where using ``where``\n------------------------------------------------\n" } ]
Python
Apache License 2.0
google/jax
Added a FAQ for impure functions
260,411
24.03.2020 10:22:49
-3,600
f88d49b43ce2a111cacbeb8028741005cea34b57
Added FAQ entry about creating JAX arrays
[ { "change_type": "MODIFY", "old_path": "docs/faq.rst", "new_path": "docs/faq.rst", "diff": "@@ -4,6 +4,26 @@ 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 `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+\n`jit` changes the behavior of my function\n-----------------------------------------\n" } ]
Python
Apache License 2.0
google/jax
Added FAQ entry about creating JAX arrays
260,499
25.03.2020 09:59:43
0
9ec0ac6e20ff83d9bb7807bc0b3017a3714039e5
Added test for isclose.
[ { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1579,6 +1579,31 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nonp.array([0x2a], dtype=onp.uint8),\ncheck_dtypes=True)\n+ def testIsClose(self):\n+ c_isclose = api.jit(jnp.isclose)\n+ c_isclose_nan = api.jit(partial(jnp.isclose, equal_nan=True))\n+ n = 2\n+\n+ rng = onp.random.RandomState(0)\n+ x = rng.randn(n, 1)\n+ y = rng.randn(n, 1)\n+ inf = onp.asarray(n * [onp.inf]).reshape([n, 1])\n+ nan = onp.asarray(n * [onp.nan]).reshape([n, 1])\n+ args = [x, y, inf, -inf, nan]\n+\n+ for arg0 in args:\n+ for arg1 in args:\n+ result_np = onp.isclose(arg0, arg1)\n+ result_jax = jnp.isclose(arg0, arg1)\n+ result_jit = c_isclose(arg0, arg1)\n+ self.assertTrue(jnp.all(jnp.equal(result_np, result_jax)))\n+ self.assertTrue(jnp.all(jnp.equal(result_np, result_jit)))\n+ result_np = onp.isclose(arg0, arg1, equal_nan=True)\n+ result_jax = jnp.isclose(arg0, arg1, equal_nan=True)\n+ result_jit = c_isclose_nan(arg0, arg1)\n+ self.assertTrue(jnp.all(jnp.equal(result_np, result_jax)))\n+ self.assertTrue(jnp.all(jnp.equal(result_np, result_jit)))\n+\ndef testAllClose(self):\nrng = onp.random.RandomState(0)\nx = rng.randn(2, 2)\n" } ]
Python
Apache License 2.0
google/jax
Added test for isclose.
260,335
25.03.2020 14:53:23
25,200
da9b52324af6c73b94cf7fe70d301cccf9c85c7e
remove incorrect sentence in notebook
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/How_JAX_primitives_work.ipynb", "new_path": "docs/notebooks/How_JAX_primitives_work.ipynb", "diff": "\"\\n\",\n\"\\n\",\n\"For example, the abstraction of a vector with 3 elements may be `ShapedArray(float32[3])`, or `ConcreteArray([1., 2., 3.])`. \\n\",\n- \"In the latter case, JAX uses the actual concrete value wrapped as an abstract value. Nevertheless, the abstract evaluation is not supposed to look at the concrete values, but only at the shapes and types.\\n\"\n+ \"In the latter case, JAX uses the actual concrete value wrapped as an abstract value.\\n\"\n]\n},\n{\n" } ]
Python
Apache License 2.0
google/jax
remove incorrect sentence in notebook
260,335
25.03.2020 17:05:57
25,200
fc0f875b02edc0f48edbe2f2b91158f415ae5fe8
improve ref to Tao's 3rd edition of Analysis I
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "new_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"But mathematically if we think of $f$ as a function on $\\\\mathbb{R}_+$ then it is differentiable at 0 [Rudin Definition 5.1, or Tao Definition 10.1.1]. Alternatively, we might say as a convention we want to consider the directional derivative from the right. So there is a sensible value for the Python function `grad(f)` to return at `0.0`, namely `1.0`, even though JAX's machinery for differentiation over reals doesn't produce it.\\n\",\n+ \"But mathematically if we think of $f$ as a function on $\\\\mathbb{R}_+$ then it is differentiable at 0 [Rudin's Real and Complex Analysis Definition 5.1, or Tao's Analysis I 3rd ed. Definition 10.1.1 and Example 10.1.6]. Alternatively, we might say as a convention we want to consider the directional derivative from the right. So there is a sensible value for the Python function `grad(f)` to return at `0.0`, namely `1.0`, even though JAX's machinery for differentiation over reals doesn't produce it.\\n\",\n\"\\n\",\n\"We can use a custom JVP rule! In particular, we can define the JVP rule in terms of the derivative function $x \\\\mapsto \\\\frac{\\\\sqrt{x} + 2}{2(\\\\sqrt{x} + 1)^2}$ on $\\\\mathbb{R}_+$,\"\n]\n" } ]
Python
Apache License 2.0
google/jax
improve ref to Tao's 3rd edition of Analysis I
260,335
25.03.2020 18:17:55
25,200
32747476874fcd32f6feaa42128369b2973220bb
fix derivatives reference (wrong Rudin!)
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "new_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"But mathematically if we think of $f$ as a function on $\\\\mathbb{R}_+$ then it is differentiable at 0 [Rudin's Real and Complex Analysis Definition 5.1, or Tao's Analysis I 3rd ed. Definition 10.1.1 and Example 10.1.6]. Alternatively, we might say as a convention we want to consider the directional derivative from the right. So there is a sensible value for the Python function `grad(f)` to return at `0.0`, namely `1.0`, even though JAX's machinery for differentiation over reals doesn't produce it.\\n\",\n+ \"But mathematically if we think of $f$ as a function on $\\\\mathbb{R}_+$ then it is differentiable at 0 [Rudin's Principles of Mathematical Analysis Definition 5.1, or Tao's Analysis I 3rd ed. Definition 10.1.1 and Example 10.1.6]. Alternatively, we might say as a convention we want to consider the directional derivative from the right. So there is a sensible value for the Python function `grad(f)` to return at `0.0`, namely `1.0`, even though JAX's machinery for differentiation over reals doesn't produce it.\\n\",\n\"\\n\",\n\"We can use a custom JVP rule! In particular, we can define the JVP rule in terms of the derivative function $x \\\\mapsto \\\\frac{\\\\sqrt{x} + 2}{2(\\\\sqrt{x} + 1)^2}$ on $\\\\mathbb{R}_+$,\"\n]\n" } ]
Python
Apache License 2.0
google/jax
fix derivatives reference (wrong Rudin!)
260,335
25.03.2020 20:19:49
25,200
c3e3d4807edc0dac4ba9ac71ff4c0397d8f44770
temporarily revert parts of pending bug fix
[ { "change_type": "MODIFY", "old_path": "jax/nn/functions.py", "new_path": "jax/nn/functions.py", "diff": "import numpy as onp\n-from jax import custom_jvp\n+from jax import custom_transforms, defjvp\nfrom jax import dtypes\nfrom jax import lax\nfrom jax.scipy.special import expit\n@@ -25,7 +25,7 @@ import jax.numpy as np\n# activations\n-@custom_jvp\n+@custom_transforms\ndef relu(x):\nr\"\"\"Rectified linear unit activation function.\n@@ -35,11 +35,7 @@ def relu(x):\n\\mathrm{relu}(x) = \\max(x, 0)\n\"\"\"\nreturn np.maximum(x, 0)\n-def _relu_jvp(primals, tangents):\n- x, = primals\n- t, = tangents\n- return relu(x), lax.select(x > 0, t, lax.full_like(t, 0))\n-relu.defjvp(_relu_jvp)\n+defjvp(relu, lambda g, ans, x: lax.select(x > 0, g, lax.full_like(g, 0)))\ndef softplus(x):\nr\"\"\"Softplus activation function.\n" }, { "change_type": "MODIFY", "old_path": "jax/numpy/linalg.py", "new_path": "jax/numpy/linalg.py", "diff": "@@ -20,7 +20,7 @@ import textwrap\nimport operator\nfrom typing import Tuple, Union, cast\n-from jax import jit, vmap, custom_jvp\n+from jax import jit, vmap\nfrom .. import lax\nfrom .. import ops\nfrom .. import lax_linalg\n@@ -29,6 +29,7 @@ from .lax_numpy import _not_implemented\nfrom .lax_numpy import _wraps\nfrom .vectorize import vectorize\nfrom . import lax_numpy as np\n+from ..api import custom_transforms, defjvp\nfrom ..util import get_module_functions\nfrom ..third_party.numpy.linalg import cond, tensorinv, tensorsolve\n@@ -110,8 +111,8 @@ def matrix_rank(M, tol=None):\nreturn np.sum(S > tol)\n-@custom_jvp\n@_wraps(onp.linalg.slogdet)\n+@custom_transforms\n@jit\ndef slogdet(a):\na = _promote_arg_dtypes(np.asarray(a))\n@@ -136,15 +137,11 @@ def slogdet(a):\nis_zero, np.array(-np.inf, dtype=dtype),\nnp.sum(np.log(np.abs(diag)), axis=-1))\nreturn sign, np.real(logdet)\n-def _slogdet_jvp(primals, tangents):\n- x, = primals\n- g, = tangents\n- if np.issubdtype(np._dtype(x), np.complexfloating):\n- raise NotImplementedError # TODO(pfau): make this work for complex types\n- sign, ans = slogdet(x)\n- sign_dot, ans_dot = np.zeros_like(sign), np.trace(solve(x, g), axis1=-1, axis2=-2)\n- return (sign, ans), (sign_dot, ans_dot)\n-slogdet.defjvp(_slogdet_jvp)\n+def _jvp_slogdet(g, ans, x):\n+ jvp_sign = np.zeros(x.shape[:-2])\n+ jvp_logdet = np.trace(solve(x, g), axis1=-1, axis2=-2)\n+ return jvp_sign, jvp_logdet\n+defjvp(slogdet, _jvp_slogdet)\n@_wraps(onp.linalg.det)\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/special.py", "new_path": "jax/scipy/special.py", "diff": "@@ -20,6 +20,7 @@ import scipy.special as osp_special\nfrom .. import util\nfrom .. import lax\nfrom .. import api\n+from ..api import custom_transforms, defjvp\nfrom ..numpy import lax_numpy as jnp\nfrom ..numpy.lax_numpy import (_wraps, asarray, _reduction_dims, _constant_like,\n_promote_args_inexact)\n@@ -79,26 +80,21 @@ def erfinv(x):\nreturn lax.erf_inv(x)\n-@api.custom_jvp\n+@_wraps(osp_special.logit, update_doc=False)\n+@custom_transforms\ndef logit(x):\n+ x = asarray(x)\nreturn lax.log(lax.div(x, lax.sub(lax._const(x, 1), x)))\n-def _logit_jvp(primals, tangents):\n- (x,), (t,) = primals, tangents\n- ans = logit(x)\n- t_out = lax.div(lax.mul(x, lax.sub(lax._const(x, 1), x)))\n- return ans, t_out\n-logit.defjvp(_logit_jvp)\n+defjvp(logit, lambda g, ans, x: g / (x * (1 - x)))\n-@api.custom_jvp\n+@_wraps(osp_special.expit, update_doc=False)\n+@custom_transforms\ndef expit(x):\n- return 1 / (1 + lax.exp(-x))\n-def _expit_jvp(primals, tangents):\n- (x,), (t,) = primals, tangents\n- ans = expit(x)\n- t_out = t * ans * (1 - ans)\n- return ans, t_out\n-expit.defjvp(_expit_jvp)\n+ x = asarray(x)\n+ one = lax._const(x, 1)\n+ return lax.div(one, lax.add(one, lax.exp(lax.neg(x))))\n+defjvp(expit, lambda g, ans, x: g * ans * (lax._const(ans, 1) - ans))\n@_wraps(osp_special.logsumexp)\n@@ -411,7 +407,7 @@ def _ndtri(p):\nreturn x_nan_replaced\n-@partial(api.custom_jvp, nondiff_argnums=(1,))\n+@custom_transforms\ndef log_ndtr(x, series_order=3):\nr\"\"\"Log Normal distribution function.\n@@ -512,13 +508,7 @@ def log_ndtr(x, series_order=3):\nlax.log(_ndtr(lax.max(x, lower_segment))),\n_log_ndtr_lower(lax.min(x, lower_segment),\nseries_order)))\n-\n-def _log_ndtr_jvp(series_order, primals, tangents):\n- (x,), (t,) = primals, tangents\n- ans = log_ndtr(x, series_order=series_order)\n- t_out = lax.mul(t, lax.exp(lax.sub(_norm_logpdf(x), ans)))\n- return ans, t_out\n-log_ndtr.defjvp(_log_ndtr_jvp)\n+defjvp(log_ndtr, lambda g, ans, x: lax.mul(g, lax.exp(lax.sub(_norm_logpdf(x), ans))))\ndef _log_ndtr_lower(x, series_order):\n\"\"\"Asymptotic expansion version of `Log[cdf(x)]`, appropriate for `x<<-1`.\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
temporarily revert parts of #2026 pending bug fix
260,335
26.03.2020 16:52:29
25,200
42dbfd43d4b219dd31a102d63b6fb241acbb2426
attempt to fix link formatting with nbsphinx
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "new_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "diff": "\"\\n\",\n\"This notebook is about #1. To read instead about #2, see the [notebook on adding primitives](https://jax.readthedocs.io/en/latest/notebooks/How_JAX_primitives_work.html).\\n\",\n\"\\n\",\n- \"For an introduction to JAX's automatic differentiation API, see [The Autodiff Cookbook](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html). This notebook assumes some familiarity with [`jax.jvp`](https://jax.readthedocs.io/en/latest/jax.html#jax.jvp) and [`jax.grad`](https://jax.readthedocs.io/en/latest/jax.html#jax.vjp), and the mathematical meaning of JVPs and VJPs.\"\n+ \"For an introduction to JAX's automatic differentiation API, see [The Autodiff Cookbook](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html). This notebook assumes some familiarity with [jax.jvp](https://jax.readthedocs.io/en/latest/jax.html#jax.jvp) and [jax.grad](https://jax.readthedocs.io/en/latest/jax.html#jax.grad), and the mathematical meaning of JVPs and VJPs.\"\n]\n},\n{\n" } ]
Python
Apache License 2.0
google/jax
attempt to fix link formatting with nbsphinx
260,510
26.03.2020 19:07:48
25,200
0499b8457fce77dbb773c8e8ea599ba544650878
Instantiate zeros in _custom_vjp_call_jaxpr_jvp
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -518,6 +518,7 @@ def _custom_vjp_call_jaxpr_jvp(primals, tangents, jaxpr, fwd, bwd, out_trees,\n_, primals = split_list(primals, [num_consts])\nzero_tangents, tangents = split_list(tangents, [num_consts])\nassert all(t is zero for t in zero_tangents)\n+ tangents = map(ad.instantiate_zeros, primals, tangents)\nres_and_primals_out = fwd.call_wrapped(*primals)\nout_tree, res_tree = out_trees()\nres, primals_out = split_list(res_and_primals_out, [res_tree.num_leaves])\n" } ]
Python
Apache License 2.0
google/jax
Instantiate zeros in _custom_vjp_call_jaxpr_jvp
260,346
28.03.2020 12:32:44
-3,600
415cde5b18299aa8aa7dd35908c42dcaf4ea121e
Make it more explicit that default JVP assumes |R It's just an attempt to make this implicit assumption, as it only became clear to me after our discussion in chat, not after reading this.
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "new_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"But mathematically if we think of $f$ as a function on $\\\\mathbb{R}_+$ then it is differentiable at 0 [Rudin's Principles of Mathematical Analysis Definition 5.1, or Tao's Analysis I 3rd ed. Definition 10.1.1 and Example 10.1.6]. Alternatively, we might say as a convention we want to consider the directional derivative from the right. So there is a sensible value for the Python function `grad(f)` to return at `0.0`, namely `1.0`, even though JAX's machinery for differentiation over reals doesn't produce it.\\n\",\n+ \"But mathematically if we think of $f$ as a function on $\\\\mathbb{R}_+$ then it is differentiable at 0 [Rudin's Principles of Mathematical Analysis Definition 5.1, or Tao's Analysis I 3rd ed. Definition 10.1.1 and Example 10.1.6]. Alternatively, we might say as a convention we want to consider the directional derivative from the right. So there is a sensible value for the Python function `grad(f)` to return at `0.0`, namely `1.0`. By default, JAX's machinery for differentiation assumes all functions are defined over $\\\\mathbb{R}$ and thus doesn't produce `1.0` here.\\n\",\n\"\\n\",\n\"We can use a custom JVP rule! In particular, we can define the JVP rule in terms of the derivative function $x \\\\mapsto \\\\frac{\\\\sqrt{x} + 2}{2(\\\\sqrt{x} + 1)^2}$ on $\\\\mathbb{R}_+$,\"\n]\n" } ]
Python
Apache License 2.0
google/jax
Make it more explicit that default JVP assumes |R It's just an attempt to make this implicit assumption, as it only became clear to me after our discussion in chat, not after reading this.
260,335
28.03.2020 11:56:12
25,200
1b5978953b01d34f07f252e193a963f9b9a1ebf5
add ShardedDeviceArray to ad vspace op handlers fixes (thanks, !)
[ { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1498,9 +1498,10 @@ def zeros_like_array(x):\nreturn full_like(x, 0)\nfor t in itertools.chain(dtypes.python_scalar_dtypes.keys(), array_types,\n- [xla.DeviceArray]):\n+ [xla.DeviceArray, pxla.ShardedDeviceArray]):\nad_util.jaxval_adders[t] = add\nad_util.jaxval_zeros_likers[xla.DeviceArray] = zeros_like_array\n+ad_util.jaxval_zeros_likers[pxla.ShardedDeviceArray] = zeros_like_array\n### primitives\n" } ]
Python
Apache License 2.0
google/jax
add ShardedDeviceArray to ad vspace op handlers fixes #2529 (thanks, @dpfau !)
260,335
28.03.2020 14:55:58
25,200
f99720b70ab615c966ba321fb1a35503be33fca6
add type annotations to core.py tracing machinery also add .copy() method to core.trace_state global trace state
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -274,33 +274,20 @@ def eval_jaxpr(jaxpr, consts, *args):\nreturn map(read, jaxpr.outvars)\n-def full_lower(val):\n- if isinstance(val, Tracer):\n- return val.full_lower()\n- else:\n- return val\n-\n-\n-def find_top_trace(xs):\n- try:\n- top_trace = max((x._trace for x in xs if isinstance(x, Tracer)),\n- key=attrgetter('level'))\n- except ValueError:\n- return None\n- else:\n- return type(top_trace)(top_trace.master, cur_sublevel())\n-\n-\n# -------------------- tracing --------------------\n-class Trace(object):\n- def __init__(self, master, sublevel):\n+class Trace:\n+ master: 'MasterTrace'\n+ level: int\n+ sublevel: 'Sublevel'\n+\n+ def __init__(self, master: 'MasterTrace', sublevel: 'Sublevel') -> None:\nself.master = master\nself.level = master.level\nself.sublevel = sublevel\n- def full_raise(self, val):\n+ def full_raise(self, val) -> 'Tracer':\nif not isinstance(val, Tracer):\nreturn self.pure(val)\nlevel = self.level\n@@ -311,18 +298,19 @@ class Trace(object):\nelif val._trace.sublevel < sublevel:\nreturn self.sublift(val)\nelse:\n- escaped_tracer_error(\n- \"Can't lift sublevels {} to {}\".format(val._trace.sublevel, sublevel))\n+ raise escaped_tracer_error(\"Can't lift sublevels {} to {}\"\n+ .format(val._trace.sublevel, sublevel))\nelif val._trace.level < level:\nif val._trace.sublevel > sublevel:\n- escaped_tracer_error(\n- \"Incompatible sublevel: {}, {}\".format(val._trace, (level, sublevel)))\n+ raise escaped_tracer_error(\"Incompatible sublevel: {}, {}\"\n+ .format(val._trace, (level, sublevel)))\nreturn self.lift(val)\nelif val._trace.level > level:\n- escaped_tracer_error(\n- \"Can't lift level {} to {}\".format(val, self))\n+ raise escaped_tracer_error(\"Can't lift level {} to {}\"\n+ .format(val, self))\nelse: # val._trace.level == self.level:\n- escaped_tracer_error(\"Different traces at same level: {}, {}\".format(val, self))\n+ raise escaped_tracer_error(\"Different traces at same level: {}, {}\"\n+ .format(val, self))\ndef pure(self, val):\nraise NotImplementedError(\"must override\")\n@@ -345,10 +333,11 @@ def escaped_tracer_error(detail):\n\"through global state from a previously traced function.\\n\"\n\"The functions being transformed should not save traced values to \"\n\"global state.\\nDetails: {}.\")\n- raise UnexpectedTracerError(msg.format(detail))\n+ return UnexpectedTracerError(msg.format(detail))\nclass UnexpectedTracerError(Exception): pass\n+\nclass Tracer(object):\n__array_priority__ = 1000\n__slots__ = ['_trace', '__weakref__']\n@@ -452,74 +441,91 @@ class Tracer(object):\ndef __deepcopy__(self, unused_memo):\nreturn self\n-\n# these can be used to set up forwarding of properties and instance methods from\n# Tracer instances to the underlying avals\naval_property = namedtuple(\"aval_property\", [\"fget\"])\naval_method = namedtuple(\"aval_method\", [\"fun\"])\n-class MasterTrace(object):\n- def __init__(self, level, trace_type):\n+class MasterTrace:\n+ level: int\n+ trace_type: Type[Trace]\n+\n+ def __init__(self, level, trace_type) -> None:\nself.level = level\nself.trace_type = trace_type\n- def __repr__(self):\n+ def __repr__(self) -> str:\nreturn \"MasterTrace({},{})\".format(self.level, self.trace_type.__name__)\n- def __hash__(self):\n+ def __hash__(self) -> int:\nreturn hash((self.level, self.trace_type))\n- def __eq__(self, other):\n- return self.level == other.level and self.trace_type == other.trace_type\n+ def __eq__(self, other: object) -> bool:\n+ return (isinstance(other, MasterTrace) and\n+ self.level == other.level and self.trace_type == other.trace_type)\n+class TraceStack:\n+ upward: List[MasterTrace]\n+ downward: List[MasterTrace]\n-class TraceStack(object):\ndef __init__(self):\nself.upward = []\nself.downward = []\n- def next_level(self, bottom):\n+ def next_level(self, bottom: bool) -> int:\nif bottom:\nreturn - (len(self.downward) + 1)\nelse:\nreturn len(self.upward)\n- def push(self, val, bottom):\n+ def push(self, master_trace: MasterTrace, bottom: bool) -> None:\nif bottom:\n- self.downward.append(val)\n+ self.downward.append(master_trace)\nelse:\n- self.upward.append(val)\n+ self.upward.append(master_trace)\n- def pop(self, bottom):\n+ def pop(self, bottom: bool) -> None:\nif bottom:\nself.downward.pop()\nelse:\nself.upward.pop()\n- def __repr__(self):\n+ def __repr__(self) -> str:\nreturn 'Trace stack\\n{} ---\\n{}'.format(\nmap(' {}\\n'.format, self.upward[::-1]),\nmap(' {}\\n'.format, self.downward))\n+ def copy(self):\n+ new = TraceStack()\n+ new.upward = self.upward[:]\n+ new.downward = self.downward[:]\n+ return new\nclass Sublevel(int): pass\n+\n# The global state of the tracer is accessed by a thread-local object.\n# This allows concurrent tracing in separate threads; passing traced objects\n# between threads is forbidden.\nclass TraceState(threading.local):\n- def __init__(self):\n+ trace_stack: TraceStack\n+ substack: List[Sublevel]\n+\n+ def __init__(self) -> None:\nself.trace_stack = TraceStack()\nself.substack = [Sublevel(0)]\n+ def copy(self):\n+ new = TraceState()\n+ new.trace_stack = self.trace_stack.copy()\n+ new.substack = self.substack[:]\n+ return new\ntrace_state = TraceState()\n-\n-def cur_sublevel():\n+def cur_sublevel() -> Sublevel:\nreturn trace_state.substack[-1]\n-\n@contextmanager\ndef new_master(trace_type: Type[Trace], bottom=False) -> Generator[MasterTrace, None, None]:\nlevel = trace_state.trace_stack.next_level(bottom)\n@@ -538,9 +544,8 @@ def new_master(trace_type: Type[Trace], bottom=False) -> Generator[MasterTrace,\nprint(trace_state.trace_stack)\nraise Exception('Leaked trace {}'.format(t()))\n-\n@contextmanager\n-def new_sublevel():\n+def new_sublevel() -> Generator[None, None, None]:\nsublevel = Sublevel(len(trace_state.substack))\ntrace_state.substack.append(sublevel)\ntry:\n@@ -554,6 +559,22 @@ def new_sublevel():\nif t() is not None:\nraise Exception('Leaked sublevel {}'.format(t()))\n+def full_lower(val):\n+ if isinstance(val, Tracer):\n+ return val.full_lower()\n+ else:\n+ return val\n+\n+def find_top_trace(xs):\n+ try:\n+ top_trace = max((x._trace for x in xs if isinstance(x, Tracer)),\n+ key=attrgetter('level'))\n+ except ValueError:\n+ return None\n+ else:\n+ return type(top_trace)(top_trace.master, cur_sublevel())\n+\n+\n# -------------------- abstract values --------------------\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -285,7 +285,7 @@ class JaxprTracer(Tracer):\nassert isinstance(pval, PartialVal)\npv, const = pval\nif isinstance(const, Tracer) and const._trace.level >= trace.level:\n- core.escaped_tracer_error(\n+ raise core.escaped_tracer_error(\n\"Tracer from a higher level: {} in trace {}\".format(const, trace))\nself._trace = trace\nself.pval = pval\n@@ -452,7 +452,8 @@ def tracers_to_jaxpr(in_tracers, out_tracers):\nprocessed_eqn_ids.add(recipe.eqn_id)\nelif isinstance(recipe, LambdaBinding):\nif not any(t is in_tracer for in_tracer in in_tracers):\n- core.escaped_tracer_error(\"Tracer not among input tracers {}\".format(t))\n+ raise core.escaped_tracer_error(\n+ \"Tracer not among input tracers {}\".format(t))\nassert in_tracers, \"Lambda binding with no args\"\nelif isinstance(recipe, FreeVar):\nenv[getvar(t)] = recipe.val\n" }, { "change_type": "MODIFY", "old_path": "mypy.ini", "new_path": "mypy.ini", "diff": "@@ -10,3 +10,5 @@ ignore_missing_imports = True\nignore_missing_imports = True\n[mypy-scipy.*]\nignore_missing_imports = True\n+[mypy-jax.interpreters.autospmd]\n+ignore_errors = True\n" } ]
Python
Apache License 2.0
google/jax
add type annotations to core.py tracing machinery also add .copy() method to core.trace_state global trace state
260,335
28.03.2020 13:52:40
25,200
67283a08ecdd3eab03b35355fb819d1dc9c3fcb0
add new custom_jvp tests from
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2289,6 +2289,76 @@ class CustomJVPTest(jtu.JaxTestCase):\n\"respectively.\"),\nlambda: api.jvp(f, (np.float32(2.),), (np.float32(1.),)))\n+ def test_multiple_rule_invocations(self):\n+ @jax.custom_jvp\n+ def expit(x):\n+ return 1 / (1 + lax.exp(-x))\n+\n+ @expit.defjvp\n+ def _expit_jvp(primals, tangents):\n+ (x,), (t,) = primals, tangents\n+ ans = expit(x)\n+ t_out = t * ans * (1 - ans)\n+ return ans, t_out\n+\n+ def scanned_fun(c, _):\n+ return [expit(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None\n+\n+ def foo(x):\n+ c, _ = lax.scan(scanned_fun, [x, 0., 0., 0., 0.], None, length=10)\n+ return c[-1]\n+\n+ # just make sure these don't crash\n+ foo(3.)\n+ grad(foo)(3.)\n+ grad(lambda x: jax.vmap(foo)(x).sum())(np.arange(3.))\n+\n+ def test_hard_stuff(self):\n+ arr = np.ones((5, 2, 2))\n+ api.jit(jax.vmap(np.linalg.det))(arr) # doesn't crash\n+\n+ def test_hard_stuff2(self):\n+ @jax.custom_jvp\n+ def f(x):\n+ return lax.tie_in(x, onp.zeros(x.shape, x.dtype))\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ t, = tangents\n+ return f(x), t\n+\n+ # don't crash\n+ jax.jit(jax.vmap(f))(np.arange(3.))\n+ jax.jit(jax.vmap(jax.grad(f)))(np.arange(3.))\n+ jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(np.arange(3.))\n+ jax.grad(lambda x: jax.vmap(f)(x).sum())(np.arange(3.))\n+ jax.jvp(jax.vmap(f), (np.arange(3.),), (np.ones(3),))\n+\n+ def test_hard_stuff3(self):\n+ @jax.custom_jvp\n+ def relu(x):\n+ return np.maximum(x, 0)\n+\n+ @relu.defjvp\n+ def _relu_jvp(primals, tangents):\n+ x, = primals\n+ t, = tangents\n+ return relu(x), lax.select(x > 0, t, lax.full_like(t, 0))\n+\n+ def scanned_fun(c, _):\n+ return [relu(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None\n+\n+ def f(x):\n+ c, _ = lax.scan(scanned_fun, [x, 0., 0., 0., 0.], None, length=10)\n+ return c[-1]\n+\n+ # don't crash\n+ jax.jit(jax.vmap(f))(np.arange(3.))\n+ jax.jit(jax.vmap(jax.grad(f)))(np.arange(3.))\n+ jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(np.arange(3.))\n+ jax.grad(lambda x: jax.vmap(f)(x).sum())(np.arange(3.))\n+ jax.jvp(jax.jit(jax.vmap(f)), (np.arange(3.),), (np.ones(3),))\nclass CustomVJPTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add new custom_jvp tests from #2500 Co-authored-by: Dougal Maclaurin <dougalm@google.com>
260,316
29.03.2020 16:28:17
14,400
ead80118377579aea33f26e85be6ef2f20063b6f
Added lots of trivial jet rules.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "from functools import partial\n-from collections import Counter\nimport numpy as onp\nfrom jax import core\n-from jax.util import unzip2, prod\n+from jax.util import unzip2\nfrom jax.tree_util import (register_pytree_node, tree_structure,\ntreedef_is_leaf, tree_flatten, tree_unflatten)\nimport jax.linear_util as lu\n-\n+from jax.interpreters import xla\n+from jax.lax import lax\n+from jax.lax import lax_fft\ndef jet(fun, primals, series):\ntry:\n@@ -124,8 +125,33 @@ zero_series = ZeroSeries()\nregister_pytree_node(ZeroSeries, lambda z: ((), None), lambda _, xs: zero_series)\n+### rule definitions\n+\njet_rules = {}\n+def defzero(prim):\n+ jet_rules[prim] = partial(zero_prop, prim)\n+\n+def zero_prop(prim, primals_in, series_in, **params):\n+ primal_out = prim.bind(*primals_in, **params)\n+ return primal_out, zero_series\n+\n+defzero(lax.le_p)\n+defzero(lax.lt_p)\n+defzero(lax.gt_p)\n+defzero(lax.ge_p)\n+defzero(lax.eq_p)\n+defzero(lax.ne_p)\n+defzero(lax.and_p)\n+defzero(lax.or_p)\n+defzero(lax.xor_p)\n+defzero(lax.floor_p)\n+defzero(lax.ceil_p)\n+defzero(lax.round_p)\n+defzero(lax.sign_p)\n+defzero(lax.stop_gradient_p)\n+\n+\ndef deflinear(prim):\njet_rules[prim] = partial(linear_prop, prim)\n@@ -134,14 +160,6 @@ def linear_prop(prim, primals_in, series_in, **params):\nseries_out = [prim.bind(*terms_in, **params) for terms_in in zip(*series_in)]\nreturn primal_out, series_out\n-\n-### rule definitions\n-\n-from jax.lax import lax\n-\n-def fact(n):\n- return lax.exp(lax.lgamma(n+1.))\n-\ndeflinear(lax.neg_p)\ndeflinear(lax.real_p)\ndeflinear(lax.complex_p)\n@@ -159,15 +177,26 @@ deflinear(lax.slice_p)\ndeflinear(lax.reduce_sum_p)\ndeflinear(lax.reduce_window_sum_p)\ndeflinear(lax.tie_in_p)\n+deflinear(lax_fft.fft_p)\n+deflinear(xla.device_put_p)\n+\n+\n+\n+### More complicated rules\n+\n+def fact(n):\n+ return lax.exp(lax.lgamma(n+1.))\n+\n+def _scale(k, j):\n+ return 1. / (fact(k - j) * fact(j - 1))\ndef _exp_taylor(primals_in, series_in):\nx, = primals_in\nseries, = series_in\nu = [x] + series\nv = [lax.exp(x)] + [None] * len(series)\n- def scale(k, j): return 1. / (fact(k-j) * fact(j-1))\nfor 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+ v[k] = fact(k-1) * sum([_scale(k, j)* v[k-j] * u[j] for j in range(1, k+1)])\nprimal_out, *series_out = v\nreturn primal_out, series_out\njet_rules[lax.exp_p] = _exp_taylor\n@@ -177,9 +206,8 @@ def _log_taylor(primals_in, series_in):\nseries, = series_in\nu = [x] + series\nv = [lax.log(x)] + [None] * len(series)\n- def scale(k, j): return 1. / (fact(k-j) * fact(j-1))\nfor k in range(1, len(v)):\n- conv = sum([scale(k, j) * v[j] * u[k-j] for j in range(1, k)])\n+ conv = sum([_scale(k, j) * v[j] * u[k-j] for j in range(1, k)])\nv[k] = (u[k] - fact(k - 1) * conv) / u[0]\nprimal_out, *series_out = v\nreturn primal_out, series_out\n@@ -223,10 +251,11 @@ def _gather_taylor_rule(primals_in, series_in, **params):\nreturn primal_out, series_out\njet_rules[lax.gather_p] = _gather_taylor_rule\n-def _reduce_max_taylor_rule(primals_in, series_in, **params):\n+def _gen_reduce_choose_taylor_rule(chooser_fun):\n+ def chooser_taylor_rule(primals_in, series_in, **params):\noperand, = primals_in\ngs, = series_in\n- primal_out = lax.reduce_max_p.bind(operand, **params)\n+ primal_out = chooser_fun(operand, **params)\naxes = params.pop(\"axes\", None)\nprimal_dtype = gs[0].dtype\nshape = [1 if i in axes else d for i, d in enumerate(operand.shape)]\n@@ -237,8 +266,15 @@ def _reduce_max_taylor_rule(primals_in, series_in, **params):\nreturn lax.div(lax._reduce_sum(lax.mul(g, location_indicators), axes), counts)\nseries_out = [_reduce_chooser_taylor_rule(g) for g in gs]\nreturn primal_out, series_out\n-jet_rules[lax.reduce_max_p] = _reduce_max_taylor_rule\n-\n-\n-from jax.interpreters import xla\n-deflinear(xla.device_put_p)\n+ return chooser_taylor_rule\n+jet_rules[lax.reduce_max_p] = _gen_reduce_choose_taylor_rule(lax.reduce_max_p.bind)\n+jet_rules[lax.reduce_min_p] = _gen_reduce_choose_taylor_rule(lax.reduce_min_p.bind)\n+\n+def _abs_taylor_rule(x, series_in, **params):\n+ x, = x\n+ primal_out = lax.abs_p.bind(x, **params)\n+ negs = lax.select(lax.lt(x, 0.0), lax.full_like(x, -1), lax.full_like(x, 1.0))\n+ fix_sign = lambda y: negs * y\n+ series_out = [fix_sign(*terms_in, **params) for terms_in in zip(*series_in)]\n+ return primal_out, series_out\n+jet_rules[lax.abs_p] = _abs_taylor_rule\n" }, { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "# limitations under the License.\n-from functools import partial, reduce\n-import operator as op\n-from unittest import SkipTest\n+from functools import reduce\nfrom absl.testing import absltest\n-from absl.testing import parameterized\nimport numpy as onp\n-from jax import core\nfrom jax import test_util as jtu\n-\nimport jax.numpy as np\nfrom jax import random\n-from jax import jacobian, jit\n+from jax import jacfwd\nfrom jax.experimental import stax\n-from jax.experimental.jet import jet, fact\n+from jax.experimental.jet import jet, fact, zero_series\n+from jax.tree_util import tree_map\n+from jax import lax\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n-\ndef jvp_taylor(fun, primals, series):\n+ # Computes the Taylor series the slow way, with nested jvp.\norder, = set(map(len, series))\ndef composition(eps):\ntaylor_terms = [sum([eps ** (i+1) * terms[i] / fact(i + 1)\n@@ -42,7 +39,7 @@ def jvp_taylor(fun, primals, series):\nnudged_args = [x + t for x, t in zip(primals, taylor_terms)]\nreturn fun(*nudged_args)\nprimal_out = fun(*primals)\n- terms_out = [repeated(jacobian, i+1)(composition)(0.) for i in range(order)]\n+ terms_out = [repeated(jacfwd, i+1)(composition)(0.) for i in range(order)]\nreturn primal_out, terms_out\ndef repeated(f, n):\n@@ -50,6 +47,9 @@ def repeated(f, n):\nreturn reduce(lambda x, _: f(x), range(n), p)\nreturn rfun\n+def transform(lims, x):\n+ return x * (lims[1] - lims[0]) + lims[0]\n+\nclass JetTest(jtu.JaxTestCase):\ndef check_jet(self, fun, primals, series, atol=1e-5, rtol=1e-5,\n@@ -58,24 +58,13 @@ class JetTest(jtu.JaxTestCase):\nexpected_y, expected_terms = jvp_taylor(fun, primals, series)\nself.assertAllClose(y, expected_y, atol=atol, rtol=rtol,\ncheck_dtypes=check_dtypes)\n- self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol,\n- check_dtypes=check_dtypes)\n- @jtu.skip_on_devices(\"tpu\")\n- def test_exp(self):\n- order, dim = 4, 3\n- rng = onp.random.RandomState(0)\n- primal_in = rng.randn(dim)\n- terms_in = [rng.randn(dim) for _ in range(order)]\n- self.check_jet(np.exp, (primal_in,), (terms_in,), atol=1e-4, rtol=1e-4)\n+ # TODO(duvenaud): Lower zero_series to actual zeros automatically.\n+ if terms == zero_series:\n+ terms = tree_map(np.zeros_like, expected_terms)\n- @jtu.skip_on_devices(\"tpu\")\n- def test_log(self):\n- order, dim = 4, 3\n- rng = onp.random.RandomState(0)\n- primal_in = np.exp(rng.randn(dim))\n- terms_in = [rng.randn(dim) for _ in range(order)]\n- self.check_jet(np.log, (primal_in,), (terms_in,), atol=1e-4, rtol=1e-4)\n+ self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol,\n+ check_dtypes=check_dtypes)\n@jtu.skip_on_devices(\"tpu\")\ndef test_dot(self):\n@@ -95,6 +84,7 @@ class JetTest(jtu.JaxTestCase):\norder = 3\ninput_shape = (1, 5, 5, 1)\nkey = random.PRNGKey(0)\n+ # TODO(duvenaud): Check all types of padding\ninit_fun, apply_fun = stax.Conv(3, (2, 2), padding='VALID')\n_, (W, b) = init_fun(key, input_shape)\n@@ -114,38 +104,79 @@ class JetTest(jtu.JaxTestCase):\nself.check_jet(f, primals, series_in, check_dtypes=False)\n- @jtu.skip_on_devices(\"tpu\")\n- def test_div(self):\n- primals = 1., 5.\n- order = 4\n+ def unary_check(self, fun, lims=[-2, 2], order=3):\n+ dims = 2, 3\nrng = onp.random.RandomState(0)\n- series_in = ([rng.randn() for _ in range(order)], [rng.randn() for _ in range(order)])\n- self.check_jet(op.truediv, primals, series_in)\n+ primal_in = transform(lims, rng.rand(*dims))\n+ terms_in = [rng.randn(*dims) for _ in range(order)]\n+ self.check_jet(fun, (primal_in,), (terms_in,), atol=1e-4, rtol=1e-4)\n- @jtu.skip_on_devices(\"tpu\")\n- def test_sub(self):\n- primals = 1., 5.\n- order = 4\n+ def binary_check(self, fun, lims=[-2, 2], order=3):\n+ dims = 2, 3\nrng = onp.random.RandomState(0)\n- series_in = ([rng.randn() for _ in range(order)], [rng.randn() for _ in range(order)])\n- self.check_jet(op.sub, primals, series_in)\n+ primal_in = (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+ self.check_jet(fun, primal_in, series_in, atol=1e-4, rtol=1e-4)\n@jtu.skip_on_devices(\"tpu\")\n- def test_gather(self):\n- order, dim = 4, 3\n- rng = onp.random.RandomState(0)\n- x = rng.randn(dim)\n- terms_in = [rng.randn(dim) for _ in range(order)]\n- self.check_jet(lambda x: x[1:], (x,), (terms_in,))\n+ def test_exp(self): self.unary_check(np.exp)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_neg(self): self.unary_check(np.negative)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_floor(self): self.unary_check(np.floor)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_ceil(self): self.unary_check(np.ceil)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_round(self): self.unary_check(np.round)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_sign(self): self.unary_check(np.sign)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_log(self): self.unary_check(np.log, lims=[0.8, 4.0])\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_gather(self): self.unary_check(lambda x: x[1:])\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_reduce_max(self): self.unary_check(lambda x: x.max(axis=1))\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_reduce_min(self): self.unary_check(lambda x: x.min(axis=1))\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_all_max(self): self.unary_check(np.max)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_all_min(self): self.unary_check(np.min)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_stopgrad(self): self.unary_check(lax.stop_gradient)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_abs(self): self.unary_check(np.abs)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_fft(self): self.unary_check(np.fft.fft)\n@jtu.skip_on_devices(\"tpu\")\n- def test_reduce_max(self):\n- dim1, dim2 = 3, 5\n- order = 6\n- rng = onp.random.RandomState(0)\n- x = rng.randn(dim1, dim2)\n- terms_in = [rng.randn(dim1, dim2) for _ in range(order)]\n- self.check_jet(lambda x: x.max(axis=1), (x,), (terms_in,))\n+ def 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_sub(self): self.binary_check(lambda x, y: x - y)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_add(self): self.binary_check(lambda x, y: x + y)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_mul(self): self.binary_check(lambda x, y: x * y)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_le(self): self.binary_check(lambda x, y: x <= y)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_gt(self): self.binary_check(lambda x, y: x > y)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_lt(self): self.binary_check(lambda x, y: x < y)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_ge(self): self.binary_check(lambda x, y: x >= y)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_eq(self): self.binary_check(lambda x, y: x == y)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def 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: np.logical_and(x, y))\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_or(self): self.binary_check(lambda x, y: np.logical_or(x, y))\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_xor(self): self.binary_check(lambda x, y: np.logical_xor(x, y))\nif __name__ == '__main__':\n" } ]
Python
Apache License 2.0
google/jax
Added lots of trivial jet rules. Co-Authored-By: jessebett <jessebett@gmail.com> Co-Authored-By: Jacob Kelly <jacob.kelly@mail.utoronto.ca>
260,335
29.03.2020 13:56:26
25,200
fcc1e76c5adda49e7027b901c0e3443a648a0332
add docstring / reference doc link for axis_index fixes
[ { "change_type": "MODIFY", "old_path": "docs/jax.lax.rst", "new_path": "docs/jax.lax.rst", "diff": "@@ -163,3 +163,4 @@ Parallelism support is experimental.\npmin\nppermute\npswapaxes\n+ axis_index\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -248,6 +248,43 @@ parallel_pure_rules: Dict[core.Primitive, Callable] = {}\ndef axis_index(axis_name):\n+ \"\"\"Return the index along the pmapped axis ``axis_name``.\n+\n+ Args:\n+ axis_name: hashable Python object used to name the pmapped axis (see the\n+ ``pmap`` docstring for more details).\n+\n+ Returns:\n+ An integer representing the index.\n+\n+ For example, with 8 XLA devices available:\n+\n+ >>> from functools import partial\n+ >>> @partial(pmap, axis_name='i')\n+ ... def f(_):\n+ ... return lax.axis_index('i')\n+ ...\n+ >>> f(np.zeros(4))\n+ ShardedDeviceArray([0, 1, 2, 3], dtype=int32)\n+ >>> f(np.zeros(8))\n+ ShardedDeviceArray([0, 1, 2, 3, 4, 5, 6, 7], dtype=int32)\n+ >>> @partial(pmap, axis_name='i')\n+ ... @partial(pmap, axis_name='j')\n+ ... def f(_):\n+ ... return lax.axis_index('i'), lax.axis_index('j')\n+ ...\n+ >>> x, y = f(np.zeros((4, 2)))\n+ >>> print(x)\n+ [[0 0]\n+ [1 1]\n+ [2 2]\n+ [3 3]]\n+ >>> print(y)\n+ [[0 1]\n+ [0 1]\n+ [0 1]\n+ [0 1]]\n+ \"\"\"\ndynamic_axis_env = _thread_local_state.dynamic_axis_env\nframe = dynamic_axis_env[axis_name]\nsizes = dynamic_axis_env.sizes[:dynamic_axis_env.index(frame)+1]\n" } ]
Python
Apache License 2.0
google/jax
add docstring / reference doc link for axis_index fixes #2534
260,335
29.03.2020 14:45:17
25,200
1762a8653137e29825c45afbcea39d8188a5a6a4
workaround for pmap output PRED arrays on cpu/gpu
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1640,6 +1640,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)\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/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -703,7 +703,7 @@ def _pmap_translation_rule(c, axis_env,\nc, call_jaxpr, backend, new_env, (),\nextend_name_stack(name_stack, wrap_name(name, 'pmap')), *in_nodes_sharded)\nout_avals = [v.aval for v in call_jaxpr.outvars]\n- outs = [_xla_unshard(c, aval, new_env, shard)\n+ outs = [_xla_unshard(c, aval, new_env, shard, backend=backend)\nfor aval, shard in zip(out_avals, sharded_outs)]\nreturn c.Tuple(*outs)\n@@ -723,17 +723,30 @@ def _xla_shard(c, aval, axis_env, x):\nraise TypeError((aval, c.GetShape(x)))\n# TODO(b/110096942): more efficient gather\n-def _xla_unshard(c, aval, axis_env, x):\n+def _xla_unshard(c, aval, axis_env, x, backend):\nif aval is core.abstract_unit:\nreturn x\nelif isinstance(aval, ShapedArray):\n- dims = list(c.GetShape(x).dimensions())\n- padded = c.Broadcast(c.Constant(onp.array(0, aval.dtype)),\n+ # TODO(mattjj): remove this logic when AllReduce PRED supported on CPU / GPU\n+ convert_bool = (onp.issubdtype(aval.dtype, onp.bool_)\n+ and xb.get_backend(backend).platform in ('cpu', 'gpu'))\n+ if convert_bool:\n+ x = c.ConvertElementType(x, xb.dtype_to_etype(onp.float32))\n+\n+ xla_shape = c.GetShape(x)\n+ dims = list(xla_shape.dimensions())\n+ padded = c.Broadcast(c.Constant(onp.array(0, xla_shape.numpy_dtype())),\n[axis_env.sizes[-1]] + dims)\nzero = c.Constant(onp.zeros((), dtype=onp.uint32))\nidxs = [_unravel_index(c, axis_env)] + [zero] * len(dims)\npadded = c.DynamicUpdateSlice(padded, c.Reshape(x, None, [1] + dims), idxs)\n- return c.CrossReplicaSum(padded, xla.axis_groups(axis_env, axis_env.names[-1]))\n+ out = c.CrossReplicaSum(padded, xla.axis_groups(axis_env, axis_env.names[-1]))\n+\n+ # TODO(mattjj): remove this logic when AllReduce PRED supported on CPU / GPU\n+ if convert_bool:\n+ nonzero = c.Ne(out, c.Constant(onp.array(0, dtype=onp.float32)))\n+ out = c.ConvertElementType(nonzero, xb.dtype_to_etype(onp.bool_))\n+ return out\nelse:\nraise TypeError((aval, c.GetShape(x)))\n" } ]
Python
Apache License 2.0
google/jax
workaround for pmap output PRED arrays on cpu/gpu
260,335
29.03.2020 20:48:08
25,200
7a4c4d555c125052ad4204ce4ab7b2b3553c1078
use custom_jvp for internal functions
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-from functools import partial, update_wrapper\n+from functools import partial, update_wrapper, reduce\nimport inspect\nimport itertools as it\nimport operator as op\nfrom . import core\nfrom . import linear_util as lu\n-from .tree_util import tree_flatten, tree_unflatten\n+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@@ -76,6 +76,12 @@ 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+ return reduce(ad.add_tangents, xs, x)\n+\n+def zeros_like_pytree(x):\n+ return tree_map(lambda _: zero, x)\n+\n### JVPs\n@@ -151,6 +157,21 @@ class custom_jvp:\n\"\"\"\nself.jvp = jvp\n+ def defjvps(self, *jvps):\n+ \"\"\"Convenience wrapper for defining JVPs for each argument separately.\"\"\"\n+ if self.nondiff_argnums:\n+ raise TypeError(\"Can't use ``defjvps`` with ``nondiff_argnums``.\")\n+\n+ def jvp(primals, tangents):\n+ primal_out = self(*primals)\n+ zeros = zeros_like_pytree(primal_out)\n+ all_tangents_out = [jvp(t, primal_out, *primals) if jvp else zeros\n+ for t, jvp in zip(tangents, jvps)]\n+ tangent_out = tree_multimap(sum_tangents, *all_tangents_out)\n+ return primal_out, tangent_out\n+\n+ self.defjvp(jvp)\n+\ndef __call__(self, *args, **kwargs):\nif not self.jvp:\nmsg = \"No JVP defined for custom_jvp function {} using defjvp.\"\n" }, { "change_type": "MODIFY", "old_path": "jax/nn/functions.py", "new_path": "jax/nn/functions.py", "diff": "import numpy as onp\n-from jax import custom_transforms, defjvp\n+from jax import custom_jvp\nfrom jax import dtypes\nfrom jax import lax\nfrom jax.scipy.special import expit\n@@ -25,7 +25,7 @@ import jax.numpy as np\n# activations\n-@custom_transforms\n+@custom_jvp\ndef relu(x):\nr\"\"\"Rectified linear unit activation function.\n@@ -35,7 +35,7 @@ def relu(x):\n\\mathrm{relu}(x) = \\max(x, 0)\n\"\"\"\nreturn np.maximum(x, 0)\n-defjvp(relu, lambda g, ans, x: lax.select(x > 0, g, lax.full_like(g, 0)))\n+relu.defjvps(lambda g, ans, x: lax.select(x > 0, g, lax.full_like(g, 0)))\ndef softplus(x):\nr\"\"\"Softplus activation function.\n" }, { "change_type": "MODIFY", "old_path": "jax/numpy/linalg.py", "new_path": "jax/numpy/linalg.py", "diff": "@@ -20,7 +20,7 @@ import textwrap\nimport operator\nfrom typing import Tuple, Union, cast\n-from jax import jit, vmap\n+from jax import jit, vmap, custom_jvp\nfrom .. import lax\nfrom .. import ops\nfrom .. import lax_linalg\n@@ -29,7 +29,6 @@ from .lax_numpy import _not_implemented\nfrom .lax_numpy import _wraps\nfrom .vectorize import vectorize\nfrom . import lax_numpy as np\n-from ..api import custom_transforms, defjvp\nfrom ..util import get_module_functions\nfrom ..third_party.numpy.linalg import cond, tensorinv, tensorsolve\n@@ -111,8 +110,8 @@ def matrix_rank(M, tol=None):\nreturn np.sum(S > tol)\n+@custom_jvp\n@_wraps(onp.linalg.slogdet)\n-@custom_transforms\n@jit\ndef slogdet(a):\na = _promote_arg_dtypes(np.asarray(a))\n@@ -137,11 +136,16 @@ def slogdet(a):\nis_zero, np.array(-np.inf, dtype=dtype),\nnp.sum(np.log(np.abs(diag)), axis=-1))\nreturn sign, np.real(logdet)\n-def _jvp_slogdet(g, ans, x):\n- jvp_sign = np.zeros(x.shape[:-2])\n- jvp_logdet = np.trace(solve(x, g), axis1=-1, axis2=-2)\n- return jvp_sign, jvp_logdet\n-defjvp(slogdet, _jvp_slogdet)\n+\n+@slogdet.defjvp\n+def _slogdet_jvp(primals, tangents):\n+ x, = primals\n+ g, = tangents\n+ if np.issubdtype(np._dtype(x), np.complexfloating):\n+ raise NotImplementedError # TODO(pfau): make this work for complex types\n+ sign, ans = slogdet(x)\n+ sign_dot, ans_dot = np.zeros_like(sign), np.trace(solve(x, g), axis1=-1, axis2=-2)\n+ return (sign, ans), (sign_dot, ans_dot)\n@_wraps(onp.linalg.det)\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/special.py", "new_path": "jax/scipy/special.py", "diff": "@@ -20,7 +20,6 @@ import scipy.special as osp_special\nfrom .. import util\nfrom .. import lax\nfrom .. import api\n-from ..api import custom_transforms, defjvp\nfrom ..numpy import lax_numpy as jnp\nfrom ..numpy.lax_numpy import (_wraps, asarray, _reduction_dims, _constant_like,\n_promote_args_inexact)\n@@ -80,21 +79,21 @@ def erfinv(x):\nreturn lax.erf_inv(x)\n+@api.custom_jvp\n@_wraps(osp_special.logit, update_doc=False)\n-@custom_transforms\ndef logit(x):\nx = asarray(x)\nreturn lax.log(lax.div(x, lax.sub(lax._const(x, 1), x)))\n-defjvp(logit, lambda g, ans, x: g / (x * (1 - x)))\n+logit.defjvp(lambda g, ans, x: g / (x * (1 - x)))\n+@api.custom_jvp\n@_wraps(osp_special.expit, update_doc=False)\n-@custom_transforms\ndef expit(x):\nx = asarray(x)\none = lax._const(x, 1)\nreturn lax.div(one, lax.add(one, lax.exp(lax.neg(x))))\n-defjvp(expit, lambda g, ans, x: g * ans * (lax._const(ans, 1) - ans))\n+expit.defjvps(lambda g, ans, x: g * ans * (lax._const(ans, 1) - ans))\n@_wraps(osp_special.logsumexp)\n@@ -407,7 +406,7 @@ def _ndtri(p):\nreturn x_nan_replaced\n-@custom_transforms\n+@partial(api.custom_jvp, nondiff_argnums=(1,))\ndef log_ndtr(x, series_order=3):\nr\"\"\"Log Normal distribution function.\n@@ -508,7 +507,12 @@ def log_ndtr(x, series_order=3):\nlax.log(_ndtr(lax.max(x, lower_segment))),\n_log_ndtr_lower(lax.min(x, lower_segment),\nseries_order)))\n-defjvp(log_ndtr, lambda g, ans, x: lax.mul(g, lax.exp(lax.sub(_norm_logpdf(x), ans))))\n+def _log_ndtr_jvp(series_order, primals, tangents):\n+ (x,), (t,) = primals, tangents\n+ ans = log_ndtr(x, series_order=series_order)\n+ t_out = lax.mul(t, lax.exp(lax.sub(_norm_logpdf(x), ans)))\n+ return ans, t_out\n+log_ndtr.defjvp(_log_ndtr_jvp)\ndef _log_ndtr_lower(x, series_order):\n\"\"\"Asymptotic expansion version of `Log[cdf(x)]`, appropriate for `x<<-1`.\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
use custom_jvp for internal functions
260,335
29.03.2020 23:00:40
25,200
74d358d0362e9bf3cc42de425758e874e5466377
skip ode test on import error (internal)
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2720,7 +2720,11 @@ class CustomVJPTest(jtu.JaxTestCase):\ndef test_odeint_vmap_grad(self):\n# https://github.com/google/jax/issues/2531\n+ # TODO(mattjj): factor out an ode tests file\n+ try:\nfrom jax.experimental.ode import odeint\n+ except ImportError:\n+ raise unittest.SkipTest(\"missing jax.experimental\") from None\ndef dx_dt(x, *args):\nreturn 0.1 * x\n" } ]
Python
Apache License 2.0
google/jax
skip ode test on import error (internal)
260,335
29.03.2020 23:29:55
25,200
bdc0c3bf43f2c76bd475180904799c62e2ae1dc3
remove remat context check, add initial staging
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -566,11 +566,7 @@ def _remat_partial_eval(trace, _, f, tracers, params):\n# Using the instantiated tracers, run call_bind like JaxprTrace.process_call.\nin_pvs, in_consts = unzip2(t.pval for t in instantiated_tracers)\nfun, aux = partial_eval(f, trace, in_pvs)\n- if concrete:\n- # TODO(mattjj): remove `remat_context` when confident no accidental FLOPs\n- with remat_context():\n- out_flat = remat_call_p.bind(fun, *in_consts, **params)\n- else:\n+ with core.initial_style_staging():\nout_flat = remat_call_p.bind(fun, *in_consts, **params)\nout_pvs, jaxpr, env = aux()\nenv = map(trace.full_raise, env)\n@@ -653,23 +649,6 @@ def _reconstruct_pval(pval1, const2, unknown):\nelse:\nreturn PartialVal((None, const2))\n-# TODO(mattjj): for https://github.com/google/jax/pull/1749 we allowed\n-# standard_abstract_eval to perform concrete evaluation (i.e. FLOPs), but we\n-# don't think it should happen except for in a remat context\n-@contextlib.contextmanager\n-def remat_context():\n- try:\n- prev_state = _thread_local_state.remat\n- _thread_local_state.remat = True\n- yield\n- finally:\n- _thread_local_state.remat = prev_state\n-\n-class _ThreadLocalState(threading.local):\n- def __init__(self):\n- self.remat = False\n-_thread_local_state = _ThreadLocalState()\n-\ndef move_binders_to_front(typed_jaxpr, to_move):\nassert not typed_jaxpr.jaxpr.constvars\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/lax.py", "new_path": "jax/lax/lax.py", "diff": "@@ -1525,10 +1525,6 @@ def standard_abstract_eval(prim, shape_rule, dtype_rule, *args, **kwargs):\nleast_specialized = _max(\nmap(type, args), key=operator.attrgetter('array_abstraction_level'))\nif least_specialized is ConcreteArray:\n- msg = (\"If you see this error, please let us know by opening an issue at\\n\"\n- \"https://github.com/google/jax/issues \\n\"\n- \"since we thought this was unreachable!\")\n- assert pe._thread_local_state.remat, msg\nreturn ConcreteArray(prim.impl(*[x.val for x in args], **kwargs))\nelif least_specialized is ShapedArray:\nreturn ShapedArray(shape_rule(*args, **kwargs), dtype_rule(*args, **kwargs))\n" } ]
Python
Apache License 2.0
google/jax
remove remat context check, add initial staging
260,335
30.03.2020 00:35:45
25,200
a6a837a65ef175a7222a3517b87c19627aa13371
add some stage_out=True indicators
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -311,7 +311,8 @@ def xla_computation(fun: Callable,\navals = map(xla.abstractify, jax_args)\npvals = [pe.PartialVal((aval, core.unit)) for aval in avals]\njaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals,\n- instantiate=instantiate_const_outputs)\n+ instantiate=instantiate_const_outputs,\n+ stage_out=True)\naxis_env_ = make_axis_env(xla.jaxpr_replicas(jaxpr))\nc = xb.make_computation_builder('xla_computation_{}'.format(fun_name))\nxla_consts = map(c.Constant, consts)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -653,7 +653,7 @@ def lower_fun(fun):\navals = [_array_aval_from_xla_shape(c.GetShape(x)) for x in xla_args]\npvals = [pe.PartialVal((a, core.unit)) for a in avals]\njaxpr, _, consts = pe.trace_to_jaxpr(\n- lu.wrap_init(fun, params), pvals, instantiate=True)\n+ lu.wrap_init(fun, params), pvals, instantiate=True, stage_out=True)\nconsts = _map(c.Constant, consts)\nouts = jaxpr_subcomp(c, jaxpr, None, AxisEnv(1), consts, '', *xla_args)\nreturn c.Tuple(*outs)\n@@ -670,7 +670,7 @@ def lower_fun_initial_style(fun):\ndef f(c, axis_env, name_stack, avals, backend, *xla_args, **params):\npvals = [pe.PartialVal((a, core.unit)) for a in avals]\njaxpr, _, consts = pe.trace_to_jaxpr(\n- lu.wrap_init(fun, params), pvals, instantiate=True)\n+ lu.wrap_init(fun, params), pvals, instantiate=True, stage_out=True)\nconsts = _map(c.Constant, consts)\nouts = jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, name_stack,\n*xla_args)\n" } ]
Python
Apache License 2.0
google/jax
add some stage_out=True indicators
260,335
30.03.2020 00:41:04
25,200
9d8823c912977949eb15198c07d9a38b4b56f890
add initial_style_staging to custom_transforms
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1586,6 +1586,7 @@ class CustomTransformsFunction(object):\nflat_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(self.fun), in_tree)\nin_pvals = [pe.PartialVal((raise_to_shaped(core.get_aval(x)), core.unit))\nfor x in args_flat]\n+ with core.initial_style_staging():\njaxpr, _, consts = pe.trace_to_jaxpr(flat_fun, in_pvals, instantiate=True)\nouts = self.prim.bind(*it.chain(consts, args_flat), jaxpr=jaxpr,\nin_tree=in_tree, out_tree=out_tree(),\n" } ]
Python
Apache License 2.0
google/jax
add initial_style_staging to custom_transforms
260,335
30.03.2020 11:31:29
25,200
f766c5e7b58c0b42bab4d8d75ee33aa78a3944cc
allow duck-typing in xla_computation arguments
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -303,12 +303,15 @@ def xla_computation(fun: Callable,\nnames, sizes = zip(*axis_env)\nreturn xla.AxisEnv(nreps, names, sizes)\n+ def abstractify(x):\n+ return ShapedArray(onp.shape(x), dtypes.result_type(x))\n+\n@wraps(fun)\ndef computation_maker(*args, **kwargs):\nwrapped = lu.wrap_init(fun)\njax_args, in_tree = tree_flatten((args, kwargs))\njaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)\n- avals = map(xla.abstractify, jax_args)\n+ avals = map(abstractify, jax_args)\npvals = [pe.PartialVal((aval, core.unit)) for aval in avals]\njaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals,\ninstantiate=instantiate_const_outputs,\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -838,6 +838,23 @@ class APITest(jtu.JaxTestCase):\nself.assertEqual(param_shapes[0].xla_element_type(),\nxb.xla_client.PrimitiveType.TUPLE)\n+ def test_xla_computation_duck_typing(self):\n+ def foo(x, y, z):\n+ return x + y + z\n+\n+ x = jax.ShapeDtypeStruct((), onp.float32)\n+ y = jax.ShapeDtypeStruct((), onp.float32)\n+ z = jax.ShapeDtypeStruct((), onp.float32)\n+\n+ c = api.xla_computation(foo)(x, y, z)\n+ self.assertEqual(len(c.GetProgramShape().parameter_shapes()), 3)\n+\n+ c = api.xla_computation(foo, tuple_args=True)(1., 2., 3.)\n+ param_shapes = c.GetProgramShape().parameter_shapes()\n+ self.assertEqual(len(param_shapes), 1)\n+ self.assertEqual(param_shapes[0].xla_element_type(),\n+ xb.xla_client.PrimitiveType.TUPLE)\n+\ndef test_staging_out_multi_replica(self):\ndef f(x):\nreturn api.pmap(np.mean)(x)\n" } ]
Python
Apache License 2.0
google/jax
allow duck-typing in xla_computation arguments
260,335
30.03.2020 11:57:03
25,200
70a3f47bed6caba8c944e4d5b724c81fccb1bdae
comments/defaults for process_custom_{jv,vj}p_call
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -328,6 +328,22 @@ class Trace:\nreturn '{}(level={}/{})'.format(\nself.__class__.__name__, self.level, self.sublevel)\n+ def procecss_call(self, call_primitive, f, tracers, params):\n+ raise NotImplementedError(\"must override to handle call-like primitives\")\n+\n+ def process_custom_jvp_call(self, primitive, fun, jvp, tracers):\n+ # As a default implementation, drop the custom differentiation rule. This\n+ # behavior is desirable when staging out of the JAX system, but not when\n+ # there are further differentiation transformations to be applied. Override\n+ # this method to allow differentiation to be performed downstream.\n+ del primitive, jvp # Unused.\n+ return fun.call_wrapped(*tracers)\n+\n+ def process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers, out_trees):\n+ # See comment in the above process_custom_jvp_call method.\n+ del primitive, fwd, bwd, out_trees # Unused.\n+ return fun.call_wrapped(*tracers)\n+\ndef escaped_tracer_error(detail):\nmsg = (\"Encountered an unexpected tracer. Perhaps this tracer escaped \"\n\"through global state from a previously traced function.\\n\"\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -227,10 +227,20 @@ class JaxprTrace(Trace):\nreturn out, todo\ndef process_custom_jvp_call(self, prim, fun, jvp, tracers):\n+ # We form jaxprs using JaxprTraces for two distinct purposes: to stage\n+ # program representations completely out of the JAX system (e.g. for XLA\n+ # using jit or pmap), and to build a representation of a function that may\n+ # require further JAX transformations (e.g. in \"initial-style\" higher-order\n+ # primitives, like for control flow). In particular, in the latter case we\n+ # need custom differentiation rules to stick around, but in the former we do\n+ # not. This method call should only be reachable in the former case, and so\n+ # we check that the former case is indicated (with a StagingJaxprTrace) and\n+ # then drop the differentiation rules.\nassert self.master.trace_type is StagingJaxprTrace\nreturn fun.call_wrapped(*tracers)\ndef process_custom_vjp_call(self, prim, fun, fwd, bwd, tracers, out_trees):\n+ # See comment in the above process_custom_jvp_call method.\nassert self.master.trace_type is StagingJaxprTrace\nreturn fun.call_wrapped(*tracers)\n" } ]
Python
Apache License 2.0
google/jax
comments/defaults for process_custom_{jv,vj}p_call
260,335
30.03.2020 13:49:56
25,200
b43051e488f345b85f8b6e98b98ebef15b1eb37e
minor fix to custom_transforms
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -622,7 +622,9 @@ def defvjp_all(prim, custom_vjp):\nprimals_out = [primals_out]\nout_avals = [raise_to_shaped(get_aval(x)) for x in primals_out]\nct_pvals = [pe.PartialVal((aval, core.unit)) for aval in out_avals]\n- jaxpr, _, res = pe.trace_to_jaxpr(lu.wrap_init(vjp_py), ct_pvals, instantiate=True)\n+ with core.initial_style_staging():\n+ jaxpr, _, res = pe.trace_to_jaxpr(lu.wrap_init(vjp_py), ct_pvals,\n+ instantiate=True)\ntangents_out = fun_lin_p.bind(*it.chain(res, tangents), trans_jaxpr=jaxpr,\nnum_res=len(res), out_avals=out_avals)\nreturn primals_out + tangents_out\n" } ]
Python
Apache License 2.0
google/jax
minor fix to custom_transforms
260,335
30.03.2020 17:48:07
25,200
df3b5fe42df0d1668f1b9b7c4f4e7ad126c84aff
fix a while-loop-of-pmap bug (thanks
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -188,7 +188,7 @@ def xla_primitive_callable(prim, *arg_specs, **params):\nbuilt_c = primitive_computation(prim, AxisEnv(nreps), backend, tuple_args,\n*avals, **params)\noptions = xb.get_compile_options(\n- num_replicas=1,\n+ num_replicas=nreps,\nnum_partitions=1,\ndevice_assignment=device and (device.id,))\ncompiled = built_c.Compile(compile_options=options, backend=backend)\n@@ -264,7 +264,9 @@ def _execute_replicated_primitive(prim, compiled, backend, tuple_args,\n[device_put(x, device) for x in args if x is not token]\nfor device in compiled.local_devices()]\nout_buf = compiled.ExecuteOnLocalDevices(\n- input_bufs, tuple_arguments=tuple_args)[0][0]\n+ input_bufs, tuple_arguments=tuple_args)[0]\n+ if not prim.multiple_results:\n+ out_buf, = out_buf\nreturn result_handler(out_buf)\ndef check_nans(prim, bufs):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -1816,6 +1816,23 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nexpected = onp.arange(10)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_while_loop_of_pmap(self):\n+ # code from jsnoek@\n+ def body(i, x):\n+ result = api.pmap(lambda z: lax.psum(np.sin(z), 'i'), axis_name='i')(x)\n+ return result + x\n+ f_loop = lambda x: lax.fori_loop(0, 3, body, x)\n+ ans = f_loop(np.ones(8))\n+ del body, f_loop\n+\n+ def body2(i, x):\n+ result = np.broadcast_to(np.sin(x).sum(), x.shape)\n+ return result + x\n+ g_loop = lambda x: lax.fori_loop(0, 3, body2, x)\n+ expected = g_loop(np.ones(8))\n+\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
fix a while-loop-of-pmap bug (thanks @jaspersnoek)
260,335
30.03.2020 17:53:47
25,200
375575a5e599ed056756fc9da43e50525390b997
skip new test on cpu unless num_devices > 1
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -1817,6 +1817,9 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\ndef test_while_loop_of_pmap(self):\n+ if api.device_count() == 1 and xla_bridge.get_backend().platform == 'cpu':\n+ raise SkipTest(\"test segfaults on cpu\") # TODO(mattjj): follow up w/ xla\n+\n# code from jsnoek@\ndef body(i, x):\nresult = api.pmap(lambda z: lax.psum(np.sin(z), 'i'), axis_name='i')(x)\n" } ]
Python
Apache License 2.0
google/jax
skip new test on cpu unless num_devices > 1
260,335
30.03.2020 19:45:45
25,200
15009c9014f0729d6198ea0140e27f2066ac6584
add docstring for defjvps, fix sphinx docs
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -96,7 +96,7 @@ class custom_jvp:\ndifferentiation of the underlying function's implementation. There is a single\ninstance method, ``defjvp``, which defines the custom JVP rule.\n- For example:\n+ For example::\nimport jax.numpy as np\n@@ -139,7 +139,7 @@ class custom_jvp:\nReturns:\nNone.\n- Example:\n+ Example::\nimport jax.numpy as np\n@@ -158,7 +158,28 @@ class custom_jvp:\nself.jvp = jvp\ndef defjvps(self, *jvps):\n- \"\"\"Convenience wrapper for defining JVPs for each argument separately.\"\"\"\n+ \"\"\"Convenience wrapper for defining JVPs for each argument separately.\n+\n+ This convenience wrapper cannot be used together with ``nondiff_argnums``.\n+\n+ Args:\n+ *jvps: a sequence of functions, one for each positional argument of the\n+ ``custom_jvp`` function. Each function takes as arguments the tangent\n+ value for the corresponding primal input, the primal output, and the\n+ primal inputs. See the example below.\n+\n+ Returns:\n+ None.\n+\n+ Example::\n+\n+ @jax.custom_jvp\n+ def f(x, y):\n+ return np.sin(x) * y\n+\n+ f.defjvps(lambda x_dot, primal_out, x, y: np.cos(x) * x_dot * y,\n+ lambda y_dot, primal_out, x, y: -np.sin(x) * y_dot)\n+ \"\"\"\nif self.nondiff_argnums:\nraise TypeError(\"Can't use ``defjvps`` with ``nondiff_argnums``.\")\n@@ -333,7 +354,7 @@ class custom_vjp:\nThis decorator precludes the use of forward-mode automatic differentiation.\n- For example:\n+ For example::\nimport jax.numpy as np\n@@ -387,7 +408,7 @@ class custom_vjp:\nReturns:\nNone.\n- Example:\n+ Example::\nimport jax.numpy as np\n" } ]
Python
Apache License 2.0
google/jax
add docstring for defjvps, fix sphinx docs
260,335
30.03.2020 20:10:39
25,200
1f03d48c836227a9fe39022ba4cc4212fbdba9e9
try resetting global tracer state in loops_test.py attempting to address
[ { "change_type": "MODIFY", "old_path": "tests/loops_test.py", "new_path": "tests/loops_test.py", "diff": "@@ -27,6 +27,15 @@ from jax.experimental import loops\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n+# Attempted fix for https://github.com/google/jax/issues/2507 based on resetting\n+# the global trace state. It could be that methods like _BodyTracer.end_subtrace\n+# are not cleaning up global trace state after exceptions because they don't use\n+# a try/finally pattern. This is just a guess though!\n+# TODO(mattjj,necula): check this attempted fix\n+from jax import core\n+def tearDownModule():\n+ core.trace_state = core.TraceState()\n+\nclass LoopsTest(jtu.JaxTestCase):\ndef test_scope_no_loops(self):\n" } ]
Python
Apache License 2.0
google/jax
try resetting global tracer state in loops_test.py attempting to address #2507
260,335
30.03.2020 20:12:33
25,200
b015e5716999b80e1bdb15749e5f040dec8955c0
try re-enabling control tests that trigger
[ { "change_type": "MODIFY", "old_path": "examples/control_test.py", "new_path": "examples/control_test.py", "diff": "@@ -215,7 +215,6 @@ class ControlExampleTest(jtu.JaxTestCase):\nself.assertAllClose(U[1:], np.zeros((T - 1, 2)), check_dtypes=True)\n- @jtu.skip_on_devices(\"cpu\") # TODO(mattjj,froystig): only fails on travis?\ndef testMpcWithLqrProblemSpecifiedGenerally(self):\nrandn = onp.random.RandomState(0).randn\ndim, T, num_iters = 2, 10, 3\n@@ -229,7 +228,6 @@ class ControlExampleTest(jtu.JaxTestCase):\nself.assertAllClose(U[1:], np.zeros((T - 1, 2)), check_dtypes=True)\n- @jtu.skip_on_devices(\"cpu\") # TODO(mattjj,froystig): only fails on travis?\ndef testMpcWithNonlinearProblem(self):\ndef cost(t, x, u):\nreturn (x[0] ** 2. + 1e-3 * u[0] ** 2.) / (t + 1.)\n" } ]
Python
Apache License 2.0
google/jax
try re-enabling control tests that trigger #2507
260,335
30.03.2020 20:22:04
25,200
909fee6a2d4b0cdb70bb3c85d5cb9a317996c596
try adding sphinx-autodoc-typehints
[ { "change_type": "MODIFY", "old_path": "docs/conf.py", "new_path": "docs/conf.py", "diff": "@@ -60,6 +60,7 @@ extensions = [\n'sphinx.ext.napoleon',\n'sphinx.ext.viewcode',\n'nbsphinx',\n+ 'sphinx_autodoc_typehints',\n]\nintersphinx_mapping = {\n" }, { "change_type": "MODIFY", "old_path": "docs/requirements.txt", "new_path": "docs/requirements.txt", "diff": "@@ -3,6 +3,7 @@ sphinx_rtd_theme\njaxlib\nipykernel\nnbsphinx\n+sphinx-autodoc-typehints\n# The next packages are for notebooks\nmatplotlib\nsklearn\n" } ]
Python
Apache License 2.0
google/jax
try adding sphinx-autodoc-typehints
260,335
30.03.2020 21:09:12
25,200
e7be43da8a6b03b109a5c280a21924b8a2294ee5
update api.py docstrings for sphinx highlighting
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -85,23 +85,22 @@ _thread_local_state = _ThreadLocalState()\ndef jit(fun: Callable, static_argnums: Union[int, Iterable[int]] = (),\ndevice=None, backend: Optional[str] = None) -> Callable:\n- \"\"\"Sets up `fun` for just-in-time compilation with XLA.\n+ \"\"\"Sets up ``fun`` for just-in-time compilation with XLA.\nArgs:\nfun: Function to be jitted. Should be a pure function, as side-effects may\nonly be executed once. Its arguments and return value should be arrays,\nscalars, or (nested) standard Python containers (tuple/list/dict) thereof.\n-\n- Positional arguments indicated by `static_argnums` can be anything at all,\n- provided they are hashable and have an equality operation defined. Static\n- arguments are included as part of a compilation cache key, which is why\n- hash and equality operators must be defined.\n+ Positional arguments indicated by ``static_argnums`` can be anything at\n+ all, provided they are hashable and have an equality operation defined.\n+ Static arguments are included as part of a compilation cache key, which is\n+ why hash and equality operators must be defined.\nstatic_argnums: An int or collection of ints specifying which positional\narguments to treat as static (compile-time constant). Operations that only\ndepend on static arguments will be constant-folded. Calling the jitted\nfunction with different values for these constants will trigger\nrecompilation. If the jitted function is called with fewer positional\n- arguments than indicated by `static_argnums` then an error is raised.\n+ arguments than indicated by ``static_argnums`` then an error is raised.\nDefaults to ().\ndevice: This is an experimental feature and the API is likely to change.\nOptional, the Device the jitted function will run on. (Available devices\n@@ -111,10 +110,10 @@ def jit(fun: Callable, static_argnums: Union[int, Iterable[int]] = (),\nOptional, a string representing the xla backend. 'cpu','gpu', or 'tpu'.\nReturns:\n- A wrapped version of `fun`, set up for just-in-time compilation.\n+ A wrapped version of ``fun``, set up for just-in-time compilation.\n- In the following example, `selu` can be compiled into a single fused kernel by\n- XLA:\n+ In the following example, ``selu`` can be compiled into a single fused kernel\n+ by XLA:\n>>> @jax.jit\n>>> def selu(x, alpha=1.67, lmbda=1.05):\n@@ -157,9 +156,9 @@ def jit(fun: Callable, static_argnums: Union[int, Iterable[int]] = (),\n@contextmanager\ndef disable_jit():\n- \"\"\"Context manager that disables `jit` behavior under its dynamic context.\n+ \"\"\"Context manager that disables ``jit`` behavior under its dynamic context.\n- For debugging purposes, it is useful to have a mechanism that disables `jit`\n+ For debugging purposes, it is useful to have a mechanism that disables ``jit``\neverywhere in a dynamic context.\nValues that have a data dependence on the arguments to a jitted function are\n@@ -179,10 +178,10 @@ def disable_jit():\nValue of y is Traced<ShapedArray(int32[3]):JaxprTrace(level=-1/1)>\n[5 7 9]\n- Here `y` has been abstracted by `jit` to a `ShapedArray`, which represents an\n- array with a fixed shape and type but an arbitrary value. It's also traced. If\n- we want to see a concrete value while debugging, and avoid the tracer too, we\n- can use the `disable_jit` context manager:\n+ Here ``y`` has been abstracted by ``jit`` to a ``ShapedArray``, which\n+ represents an array with a fixed shape and type but an arbitrary value. It's\n+ also traced. If we want to see a concrete value while debugging, and avoid the\n+ tracer too, we can use the ``disable_jit`` context manager:\n>>> with jax.disable_jit():\n>>> print(f(np.array([1, 2, 3])))\n@@ -328,28 +327,28 @@ def xla_computation(fun: Callable,\ndef grad(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\nhas_aux: bool = False, holomorphic: bool = False) -> Callable:\n- \"\"\"Creates a function which evaluates the gradient of `fun`.\n+ \"\"\"Creates a function which evaluates the gradient of ``fun``.\nArgs:\nfun: Function to be differentiated. Its arguments at positions specified by\n- `argnums` should be arrays, scalars, or standard Python containers. It\n- should return a scalar (which includes arrays with shape `()` but not\n- arrays with shape `(1,)` etc.)\n+ ``argnums`` should be arrays, scalars, or standard Python containers. It\n+ should return a scalar (which includes arrays with shape ``()`` but not\n+ arrays with shape ``(1,)`` etc.)\nargnums: Optional, integer or sequence of integers. Specifies which\npositional argument(s) to differentiate with respect to (default 0).\n- has_aux: Optional, bool. Indicates whether `fun` returns a pair where the\n+ has_aux: Optional, bool. Indicates whether ``fun`` returns a pair where the\nfirst element is considered the output of the mathematical function to be\ndifferentiated and the second element is auxiliary data. Default False.\n- holomorphic: Optional, bool. Indicates whether `fun` is promised to be\n+ holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\nholomorphic. Default False.\nReturns:\n- A function with the same arguments as `fun`, that evaluates the gradient of\n- `fun`. If `argnums` is an integer then the gradient has the same shape and\n- type as the positional argument indicated by that integer. If argnums is a\n- tuple of integers, the gradient is a tuple of values with the same shapes\n- and types as the corresponding arguments. If `has_aux` is True then a pair\n- of (gradient, auxiliary_data) is returned.\n+ A function with the same arguments as ``fun``, that evaluates the gradient\n+ of ``fun``. If ``argnums`` is an integer then the gradient has the same\n+ shape and type as the positional argument indicated by that integer. If\n+ argnums is a tuple of integers, the gradient is a tuple of values with the\n+ same shapes and types as the corresponding arguments. If ``has_aux`` is True\n+ then a pair of (gradient, auxiliary_data) is returned.\nFor example:\n@@ -379,28 +378,28 @@ def grad(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\ndef value_and_grad(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\nhas_aux: bool = False, holomorphic: bool = False) -> Callable:\n- \"\"\"Creates a function which evaluates both `fun` and the gradient of `fun`.\n+ \"\"\"Create a function which evaluates both ``fun`` and the gradient of ``fun``.\nArgs:\nfun: Function to be differentiated. Its arguments at positions specified by\n- `argnums` should be arrays, scalars, or standard Python containers. It\n- should return a scalar (which includes arrays with shape `()` but not\n- arrays with shape `(1,)` etc.)\n+ ``argnums`` should be arrays, scalars, or standard Python containers. It\n+ should return a scalar (which includes arrays with shape ``()`` but not\n+ arrays with shape ``(1,)`` etc.)\nargnums: Optional, integer or sequence of integers. Specifies which\npositional argument(s) to differentiate with respect to (default 0).\n- has_aux: Optional, bool. Indicates whether `fun` returns a pair where the\n+ has_aux: Optional, bool. Indicates whether ``fun`` returns a pair where the\nfirst element is considered the output of the mathematical function to be\ndifferentiated and the second element is auxiliary data. Default False.\n- holomorphic: Optional, bool. Indicates whether `fun` is promised to be\n+ holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\nholomorphic. Default False.\nReturns:\n- A function with the same arguments as `fun` that evaluates both `fun` and\n- the gradient of `fun` and returns them as a pair (a two-element tuple). If\n- `argnums` is an integer then the gradient has the same shape and type as the\n- positional argument indicated by that integer. If argnums is a sequence of\n- integers, the gradient is a tuple of values with the same shapes and types\n- as the corresponding arguments.\n+ A function with the same arguments as ``fun`` that evaluates both ``fun``\n+ and the gradient of ``fun`` and returns them as a pair (a two-element\n+ tuple). If ``argnums`` is an integer then the gradient has the same shape\n+ and type as the positional argument indicated by that integer. If argnums is\n+ a sequence of integers, the gradient is a tuple of values with the same\n+ shapes and types as the corresponding arguments.\n\"\"\"\ndocstr = (\"Value and gradient of {fun} with respect to positional \"\n@@ -458,18 +457,18 @@ def _check_scalar(x):\ndef jacfwd(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\nholomorphic: bool = False) -> Callable:\n- \"\"\"Jacobian of `fun` evaluated column-by-column using forward-mode AD.\n+ \"\"\"Jacobian of ``fun`` evaluated column-by-column using forward-mode AD.\nArgs:\nfun: Function whose Jacobian is to be computed.\nargnums: Optional, integer or sequence of integers. Specifies which\n- positional argument(s) to differentiate with respect to (default `0`).\n- holomorphic: Optional, bool. Indicates whether `fun` is promised to be\n+ positional argument(s) to differentiate with respect to (default ``0``).\n+ holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\nholomorphic. Default False.\nReturns:\n- A function with the same arguments as `fun`, that evaluates the Jacobian of\n- `fun` using forward-mode automatic differentiation.\n+ A function with the same arguments as ``fun``, that evaluates the Jacobian of\n+ ``fun`` using forward-mode automatic differentiation.\n>>> def f(x):\n... return jax.numpy.asarray(\n@@ -497,25 +496,25 @@ def _check_real_input_jacfwd(x):\naval = core.get_aval(x)\nif not dtypes.issubdtype(aval.dtype, onp.floating):\nmsg = (\"jacfwd only defined for functions with input dtypes that are \"\n- \"sub-dtypes of `np.floating` (i.e. that model real values), but got \"\n- \"{}. For holomorphic differentiation, pass holomorphic=True.\")\n+ \"sub-dtypes of `np.floating` (i.e. that model real values), but \"\n+ \"got {}. For holomorphic differentiation, pass holomorphic=True.\")\nraise TypeError(msg.format(aval.dtype.name))\ndef jacrev(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\nholomorphic: bool = False) -> Callable:\n- \"\"\"Jacobian of `fun` evaluated row-by-row using reverse-mode AD.\n+ \"\"\"Jacobian of ``fun`` evaluated row-by-row using reverse-mode AD.\nArgs:\nfun: Function whose Jacobian is to be computed.\n- argnums: Optional, integer or sequence of integers. Specifies which positional\n- argument(s) to differentiate with respect to (default `0`).\n- holomorphic: Optional, bool. Indicates whether `fun` is promised to be\n+ argnums: Optional, integer or sequence of integers. Specifies which\n+ positional argument(s) to differentiate with respect to (default ``0``).\n+ holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\nholomorphic. Default False.\nReturns:\n- A function with the same arguments as `fun`, that evaluates the Jacobian of\n- `fun` using reverse-mode automatic differentiation.\n+ A function with the same arguments as ``fun``, that evaluates the Jacobian of\n+ ``fun`` using reverse-mode automatic differentiation.\n>>> def f(x):\n... return jax.numpy.asarray(\n@@ -545,25 +544,25 @@ def _check_real_output_jacrev(x):\naval = core.get_aval(x)\nif not dtypes.issubdtype(aval.dtype, onp.floating):\nmsg = (\"jacrev only defined for functions with output dtypes that are \"\n- \"sub-dtypes of `np.floating` (i.e. that model real values), but got \"\n- \"{}. For holomorphic differentiation, pass holomorphic=True.\")\n+ \"sub-dtypes of `np.floating` (i.e. that model real values), but \"\n+ \"got {}. For holomorphic differentiation, pass holomorphic=True.\")\nraise TypeError(msg.format(aval.dtype.name))\ndef hessian(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\nholomorphic: bool = False) -> Callable:\n- \"\"\"Hessian of `fun`.\n+ \"\"\"Hessian of ``fun`` as a dense array.\nArgs:\nfun: Function whose Hessian is to be computed.\nargnums: Optional, integer or sequence of integers. Specifies which\n- positional argument(s) to differentiate with respect to (default `0`).\n- holomorphic: Optional, bool. Indicates whether `fun` is promised to be\n+ positional argument(s) to differentiate with respect to (default ``0``).\n+ holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\nholomorphic. Default False.\nReturns:\n- A function with the same arguments as `fun`, that evaluates the Hessian of\n- `fun`.\n+ A function with the same arguments as ``fun``, that evaluates the Hessian of\n+ ``fun``.\n>>> g = lambda(x): x[0]**3 - 2*x[0]*x[1] - x[1]**6\n>>> print(jax.hessian(g)(jax.numpy.array([1., 2.])))\n@@ -599,7 +598,7 @@ def _dtype(x):\ndef vmap(fun: Callable, in_axes=0, out_axes=0) -> Callable:\n- \"\"\"Vectorizing map. Creates a function which maps `fun` over argument axes.\n+ \"\"\"Vectorizing map. Creates a function which maps ``fun`` over argument axes.\nArgs:\nfun: Function to be mapped over additional axes.\n@@ -796,7 +795,7 @@ def pmap(fun: Callable, axis_name: Optional[AxisName] = None,\nOperations that only depend on static arguments will be constant-folded.\nCalling the pmaped function with different values for these constants will\ntrigger recompilation. If the pmaped function is called with fewer\n- positional arguments than indicated by `static_argnums` then an error is\n+ positional arguments than indicated by ``static_argnums`` then an error is\nraised. Each of the static arguments will be broadcasted to all devices.\nDefaults to ().\ndevices: This is an experimental feature and the API is likely to change.\n@@ -1130,24 +1129,26 @@ def _shape_spec_consistent(spec, expr):\ndef jvp(fun: Callable, primals, tangents) -> Tuple[Any, Any]:\n- \"\"\"Computes a (forward-mode) Jacobian-vector product of `fun`.\n+ \"\"\"Computes a (forward-mode) Jacobian-vector product of ``fun``.\nArgs:\nfun: Function to be differentiated. Its arguments should be arrays, scalars,\nor standard Python containers of arrays or scalars. It should return an\narray, scalar, or standard Python container of arrays or scalars.\n- primals: The primal values at which the Jacobian of `fun` should be\n+ primals: The primal values at which the Jacobian of ``fun`` should be\nevaluated. Should be either a tuple or a list of arguments,\n- and its length should equal to the number of positional parameters of `fun`.\n+ and its length should equal to the number of positional parameters of\n+ ``fun``.\ntangents: The tangent vector for which the Jacobian-vector product should be\nevaluated. Should be either a tuple or a list of tangents, with the same\n- tree structure and array shapes as `primals`.\n+ tree structure and array shapes as ``primals``.\nReturns:\n- A `(primals_out, tangents_out)` pair, where `primals_out` is\n- `fun(*primals)`, and `tangents_out` is the Jacobian-vector product of\n- `function` evaluated at `primals` with `tangents`. The `tangents_out` value\n- has the same Python tree structure and shapes as `primals_out`.\n+ A ``(primals_out, tangents_out)`` pair, where ``primals_out`` is\n+ ``fun(*primals)``, and ``tangents_out`` is the Jacobian-vector product of\n+ ``function`` evaluated at ``primals`` with ``tangents``. The\n+ ``tangents_out`` value has the same Python tree structure and shapes as\n+ ``primals_out``.\nFor example:\n@@ -1185,49 +1186,49 @@ def _jvp(fun: lu.WrappedFun, primals, tangents):\ntree_unflatten(out_tree(), out_tangents))\ndef linearize(fun: Callable, *primals) -> Tuple[Any, Callable]:\n- \"\"\"Produce a linear approximation to `fun` using `jvp` and partial evaluation.\n+ \"\"\"Produce a linear approximation to ``fun`` using ``jvp`` and partial eval.\nArgs:\nfun: Function to be differentiated. Its arguments should be arrays, scalars,\nor standard Python containers of arrays or scalars. It should return an\narray, scalar, or standard python container of arrays or scalars.\n- primals: The primal values at which the Jacobian of `fun` should be\n+ primals: The primal values at which the Jacobian of ``fun`` should be\nevaluated. Should be a tuple of arrays, scalar, or standard Python\ncontainer thereof. The length of the tuple is equal to the number of\n- positional parameters of `fun`.\n+ positional parameters of ``fun``.\nReturns:\n- A pair where the first element is the value of `f(*primals)` and the second\n- element is a function that evaluates the (forward-mode) Jacobian-vector\n- product of `fun` evaluated at `primals` without re-doing the linearization\n- work.\n+ A pair where the first element is the value of ``f(*primals)`` and the\n+ second element is a function that evaluates the (forward-mode)\n+ Jacobian-vector product of ``fun`` evaluated at ``primals`` without re-doing\n+ the linearization work.\n- In terms of values computed, `linearize` behaves much like a curried `jvp`,\n- where these two code blocks compute the same values::\n+ In terms of values computed, ``linearize`` behaves much like a curried\n+ ``jvp``, where these two code blocks compute the same values::\ny, out_tangent = jax.jvp(f, (x,), (in_tangent,))\ny, f_jvp = jax.linearize(f, x)\nout_tangent = f_jvp(in_tangent)\n- However, the difference is that `linearize` uses partial evaluation so that\n- the function `f` is not re-linearized on calls to `f_jvp`. In general that\n+ However, the difference is that ``linearize`` uses partial evaluation so that\n+ the function ``f`` is not re-linearized on calls to ``f_jvp``. In general that\nmeans the memory usage scales with the size of the computation, much like in\n- reverse-mode. (Indeed, `linearize` has a similar signature to `vjp`!)\n+ reverse-mode. (Indeed, ``linearize`` has a similar signature to ``vjp``!)\n- This function is mainly useful if you want to apply `f_jvp` multiple times,\n+ This function is mainly useful if you want to apply ``f_jvp`` multiple times,\ni.e. to evaluate a pushforward for many different input tangent vectors at the\nsame linearization point. Moreover if all the input tangent vectors are known\n- at once, it can be more efficient to vectorize using `vmap`, as in::\n+ at once, it can be more efficient to vectorize using ``vmap``, as in::\npushfwd = partial(jvp, f, (x,))\ny, out_tangents = vmap(pushfwd, out_axes=(None, 0))((in_tangents,))\n- By using `vmap` and `jvp` together like this we avoid the stored-linearization\n+ By using ``vmap`` and ``jvp`` together like this we avoid the stored-linearization\nmemory cost that scales with the depth of the computation, which is incurred\n- by both `linearize` and `vjp`.\n+ by both ``linearize`` and ``vjp``.\n- Here's a more complete example of using `linearize`:\n+ Here's a more complete example of using ``linearize``:\n>>> def f(x): return 3. * np.sin(x) + np.cos(x / 2.)\n...\n@@ -1294,19 +1295,19 @@ def _vjp_pullback_wrapper(fun, cotangent_dtypes, io_tree, py_args):\ndef vjp(fun: Callable, *primals, **kwargs\n) -> Union[Tuple[Any, Callable], Tuple[Any, Callable, Any]]:\n- \"\"\"Compute a (reverse-mode) vector-Jacobian product of `fun`.\n+ \"\"\"Compute a (reverse-mode) vector-Jacobian product of ``fun``.\n- :py:func:`grad` is implemented as a special case of :py:func:`vjp`.\n+ :py:func:``grad`` is implemented as a special case of :py:func:``vjp``.\nArgs:\nfun: Function to be differentiated. Its arguments should be arrays, scalars,\nor standard Python containers of arrays or scalars. It should return an\narray, scalar, or standard Python container of arrays or scalars.\n- primals: A sequence of primal values at which the Jacobian of `fun`\n- should be evaluated. The length of `primals` should be equal to the number\n- of positional parameters to `fun`. Each primal value should be a tuple of\n- arrays, scalar, or standard Python containers thereof.\n- has_aux: Optional, bool. Indicates whether `fun` returns a pair where the\n+ primals: A sequence of primal values at which the Jacobian of ``fun``\n+ should be evaluated. The length of ``primals`` should be equal to the\n+ number of positional parameters to ``fun``. Each primal value should be a\n+ tuple of arrays, scalar, or standard Python containers thereof.\n+ has_aux: Optional, bool. Indicates whether ``fun`` returns a pair where the\nfirst element is considered the output of the mathematical function to be\ndifferentiated and the second element is auxiliary data. Default False.\n@@ -1360,23 +1361,22 @@ def make_jaxpr(fun: Callable) -> Callable[..., core.TypedJaxpr]:\n\"\"\"Creates a function that produces its jaxpr given example args.\nArgs:\n- fun: The function whose `jaxpr` is to be computed. Its positional arguments\n- and return value should be arrays, scalars, or standard Python containers\n- (tuple/list/dict) thereof.\n+ fun: The function whose ``jaxpr`` is to be computed. Its positional\n+ arguments and return value should be arrays, scalars, or standard Python\n+ containers (tuple/list/dict) thereof.\nReturns:\n- A wrapped version of `fun` that when applied to example arguments returns a\n- TypedJaxpr representation of `fun` on those arguments.\n-\n- A `jaxpr` is JAX's intermediate representation for program traces. The `jaxpr`\n- language is based on the simply-typed first-order lambda calculus with\n- let-bindings. `make_jaxpr` adapts a function to return its `jaxpr`, which we\n- can inspect to understand what JAX is doing internally.\n+ A wrapped version of ``fun`` that when applied to example arguments returns a\n+ ``TypedJaxpr`` representation of ``fun`` on those arguments.\n- The `jaxpr` returned is a trace of `fun` abstracted to `ShapedArray` level.\n- Other levels of abstraction exist internally.\n+ A ``jaxpr`` is JAX's intermediate representation for program traces. The\n+ ``jaxpr`` language is based on the simply-typed first-order lambda calculus\n+ with let-bindings. ``make_jaxpr`` adapts a function to return its ``jaxpr``,\n+ which we can inspect to understand what JAX is doing internally. The ``jaxpr``\n+ returned is a trace of ``fun`` abstracted to ``ShapedArray`` level. Other\n+ levels of abstraction exist internally.\n- We do not describe the semantics of the `jaxpr` language in detail here, but\n+ We do not describe the semantics of the ``jaxpr`` language in detail here, but\ninstead give a few examples.\n>>> def f(x): return jax.numpy.sin(jax.numpy.cos(x))\n" } ]
Python
Apache License 2.0
google/jax
update api.py docstrings for sphinx highlighting
260,335
30.03.2020 21:30:47
25,200
7a9c550ed143b01f97ec4e2a15f4937994918326
add sphinx-autodoc-typehints to travis install
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -37,7 +37,7 @@ install:\n# The following are needed to test the Colab notebooks and the documentation building\n- if [ \"$JAX_ONLY_DOCUMENTATION\" = true ]; then\nconda install --yes -c conda-forge pandoc ipykernel;\n- conda install --yes sphinx sphinx_rtd_theme nbsphinx jupyter_client matplotlib;\n+ conda install --yes sphinx sphinx_rtd_theme nbsphinx sphinx-autodoc-typehints jupyter_client matplotlib;\npip install sklearn;\nfi\nscript:\n" } ]
Python
Apache License 2.0
google/jax
add sphinx-autodoc-typehints to travis install
260,335
30.03.2020 22:12:38
25,200
a4ceae1c001967a1fdedaa054b4ee8f05ca2ca1b
fix link in custom derivatives tutorial notebook
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "new_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "diff": "\"source\": [\n\"In words, we again start with a a primal function `f` that takes inputs of type `a` and produces outputs of type `b`. We associate with it two functions, `f_fwd` and `f_bwd`, which describe how to perform the forward- and backward-passes of reverse-mode autodiff, respectively.\\n\",\n\"\\n\",\n- \"The function `f_fwd` describes the forward pass, not only the primal computation but also what values to save for use on the backward pass. Its input signature is just like that of the primal function `f`, in that it takes a primal input of type `a`. But as output it produces a pair, where the first element is the primal output `b` and the second element is any \\\"residual\\\" data of type `c` to be stored for use by the backward pass. (This second output is analogous to [PyTorch's `save_for_backward` mechanism](https://pytorch.org/tutorials/beginner/examples_autograd/two_layer_net_custom_function.html).)\\n\",\n+ \"The function `f_fwd` describes the forward pass, not only the primal computation but also what values to save for use on the backward pass. Its input signature is just like that of the primal function `f`, in that it takes a primal input of type `a`. But as output it produces a pair, where the first element is the primal output `b` and the second element is any \\\"residual\\\" data of type `c` to be stored for use by the backward pass. (This second output is analogous to [PyTorch's save_for_backward mechanism](https://pytorch.org/tutorials/beginner/examples_autograd/two_layer_net_custom_function.html).)\\n\",\n\"\\n\",\n\"The function `f_bwd` describes the backward pass. It takes two inputs, where the first is the residual data of type `c` produced by `f_fwd` and the second is the output cotangents of type `CT b` corresponding to the output of the primal function. It produces an output of type `CT a` representing the cotangents corresponding to the input of the primal function. In particular, the output of `f_bwd` must be a sequence (e.g. a tuple) of length equal to the number of arguments to the primal function.\"\n]\n" } ]
Python
Apache License 2.0
google/jax
fix link in custom derivatives tutorial notebook
260,411
31.03.2020 11:11:47
-7,200
59ed4aeaed4637f2c6e14f925ee873e2e1dcad92
Disable test_while_loop_of_pmap on all platforms Issue: Disable the test so that we can continue the google3 tests
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -1816,10 +1816,9 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nexpected = onp.arange(10)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @jtu.skip_on_devices(\"tpu\", \"gpu\", \"cpu\")# TODO(mattjj): follow up w/ xla\n+ # Issue #2554\ndef test_while_loop_of_pmap(self):\n- if api.device_count() == 1 and xla_bridge.get_backend().platform == 'cpu':\n- raise SkipTest(\"test segfaults on cpu\") # TODO(mattjj): follow up w/ xla\n-\n# code from jsnoek@\ndef body(i, x):\nresult = api.pmap(lambda z: lax.psum(np.sin(z), 'i'), axis_name='i')(x)\n" } ]
Python
Apache License 2.0
google/jax
Disable test_while_loop_of_pmap on all platforms Issue: #2554 Disable the test so that we can continue the google3 tests
260,335
31.03.2020 11:54:57
25,200
29c581bdb40d43cfe89f7b62ad0e2b68847e7e6f
don't hardcode array size in test Fixes
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -1816,22 +1816,21 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nexpected = onp.arange(10)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @jtu.skip_on_devices(\"tpu\", \"gpu\", \"cpu\")# TODO(mattjj): follow up w/ xla\n- # Issue #2554\ndef test_while_loop_of_pmap(self):\n# code from jsnoek@\n+\ndef body(i, x):\nresult = api.pmap(lambda z: lax.psum(np.sin(z), 'i'), axis_name='i')(x)\nreturn result + x\nf_loop = lambda x: lax.fori_loop(0, 3, body, x)\n- ans = f_loop(np.ones(8))\n+ ans = f_loop(np.ones(api.device_count()))\ndel body, f_loop\ndef body2(i, x):\nresult = np.broadcast_to(np.sin(x).sum(), x.shape)\nreturn result + x\ng_loop = lambda x: lax.fori_loop(0, 3, body2, x)\n- expected = g_loop(np.ones(8))\n+ expected = g_loop(np.ones(api.device_count()))\nself.assertAllClose(ans, expected, check_dtypes=False)\n" } ]
Python
Apache License 2.0
google/jax
don't hardcode array size in test Fixes #2554
260,469
31.03.2020 19:59:57
14,400
4fa153439e3dee41dd1469a55729b72fee383580
FIX: batch norm w/ no scale, center
[ { "change_type": "MODIFY", "old_path": "jax/experimental/stax.py", "new_path": "jax/experimental/stax.py", "diff": "@@ -134,12 +134,10 @@ def BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True,\n# TODO(phawkins): np.expand_dims should accept an axis tuple.\n# (https://github.com/numpy/numpy/issues/12290)\ned = tuple(None if i in axis else slice(None) for i in range(np.ndim(x)))\n- beta = beta[ed]\n- gamma = gamma[ed]\nz = normalize(x, axis, epsilon=epsilon)\n- if center and scale: return gamma * z + beta\n- if center: return z + beta\n- if scale: return gamma * z\n+ if center and scale: return gamma[ed] * z + beta[ed]\n+ if center: return z + beta[ed]\n+ if scale: return gamma[ed] * z\nreturn z\nreturn init_fun, apply_fun\n" }, { "change_type": "MODIFY", "old_path": "tests/stax_test.py", "new_path": "tests/stax_test.py", "diff": "@@ -212,6 +212,19 @@ class StaxTest(jtu.JaxTestCase):\nassert out_shape == out.shape\nassert onp.allclose(onp.sum(onp.asarray(out), -1), 1.)\n+ def testBatchNormNoScaleOrCenter(self):\n+ key = random.PRNGKey(0)\n+ axes = (0, 1, 2)\n+ init_fun, apply_fun = stax.BatchNorm(axis=axes, center=False, scale=False)\n+ input_shape = (4, 5, 6, 7)\n+ inputs = random_inputs(onp.random.RandomState(0), input_shape)\n+\n+ out_shape, params = init_fun(key, input_shape)\n+ out = apply_fun(params, inputs)\n+ means = onp.mean(out, axis=(0, 1, 2))\n+ std_devs = onp.std(out, axis=(0, 1, 2))\n+ assert onp.allclose(means, onp.zeros_like(means), atol=1e-4)\n+ assert onp.allclose(std_devs, onp.ones_like(std_devs), atol=1e-4)\ndef testBatchNormShapeNHWC(self):\nkey = random.PRNGKey(0)\n" } ]
Python
Apache License 2.0
google/jax
FIX: batch norm w/ no scale, center
260,335
31.03.2020 18:46:15
25,200
83b9575145c4d59bb6bf318be8bb659fa05e3f8c
add callable typechecks to more api.py functions
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -480,6 +480,7 @@ def jacfwd(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n[ 0. , 16. , -2. ],\n[ 1.6209068 , 0. , 0.84147096]]\n\"\"\"\n+ _check_callable(fun)\ndef jacfun(*args, **kwargs):\nf = lu.wrap_init(fun, kwargs)\n@@ -526,6 +527,8 @@ def jacrev(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n[ 0. , 16. , -2. ],\n[ 1.6209068 , 0. , 0.84147096]]\n\"\"\"\n+ _check_callable(fun)\n+\ndef jacfun(*args, **kwargs):\nf = lu.wrap_init(fun, kwargs)\nf_partial, dyn_args = argnums_partial(f, argnums, args)\n@@ -662,6 +665,7 @@ def vmap(fun: Callable, in_axes=0, out_axes=0) -> Callable:\n>>> print(vfoo(tree)).shape\n(6, 2, 5)\n\"\"\"\n+ _check_callable(fun)\ndocstr = (\"Vectorized version of {fun}. Takes similar arguments as {fun} \"\n\"but with additional array axes over which {fun} is mapped.\")\n@@ -673,7 +677,6 @@ def vmap(fun: Callable, in_axes=0, out_axes=0) -> Callable:\n# rather than raising an error. https://github.com/google/jax/issues/2367\nin_axes = tuple(in_axes)\n- _check_callable(fun)\nif (not isinstance(in_axes, (list, tuple, type(None), int))\nor not isinstance(out_axes, (list, tuple, type(None), int))):\nmsg = (\"vmap arguments in_axes and out_axes must each be an integer, None, \"\n@@ -1062,6 +1065,7 @@ def _parallelize(fun):\ndef mask(fun: Callable, in_shapes, out_shape) -> Callable:\n+ _check_callable(fun)\nin_specs, in_shapes_tree = tree_flatten(in_shapes)\nout_specs, out_shapes_tree = tree_flatten(out_shape)\n@@ -1113,6 +1117,7 @@ def _bind_shapes(shape_exprs, shapes):\n@curry\ndef shapecheck(in_shapes, out_shape, fun):\n+ _check_callable(fun)\nin_shapes, in_tree = tree_flatten(in_shapes)\nin_shapes = map(masking.parse_spec, in_shapes)\nout_shapes, out_tree = tree_flatten(out_shape)\n@@ -1158,6 +1163,7 @@ def jvp(fun: Callable, primals, tangents) -> Tuple[Any, Any]:\n>>> print(v)\n0.19900084\n\"\"\"\n+ _check_callable(fun)\nreturn _jvp(lu.wrap_init(fun), primals, tangents)\ndef _jvp(fun: lu.WrappedFun, primals, tangents):\n@@ -1242,6 +1248,7 @@ def linearize(fun: Callable, *primals) -> Tuple[Any, Callable]:\n>>> print(f_jvp(4.))\n-6.676704\n\"\"\"\n+ _check_callable(fun)\nf = lu.wrap_init(fun)\nprimals_flat, in_tree = tree_flatten((primals, {}))\njaxtree_fun, out_tree = flatten_fun(f, in_tree)\n@@ -1249,11 +1256,11 @@ def linearize(fun: Callable, *primals) -> Tuple[Any, Callable]:\nout_tree = out_tree()\nout_primal_py = tree_unflatten(out_tree, out_primals)\nprimal_avals = list(map(core.get_aval, primals_flat))\n- lifted_jvp = partial(lift_linearized, jaxpr, primal_avals, consts,\n+ lifted_jvp = partial(_lift_linearized, jaxpr, primal_avals, consts,\n(in_tree, out_tree), out_pvals)\nreturn out_primal_py, lifted_jvp\n-def lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args):\n+def _lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args):\ndef fun(*tangents):\ntangent_avals = list(map(core.get_aval, tangents))\nfor primal_aval, tangent_aval in zip(primal_avals, tangent_avals):\n@@ -1331,6 +1338,7 @@ def vjp(fun: Callable, *primals, **kwargs\n>>> print(ybar)\n-0.2524413\n\"\"\"\n+ _check_callable(fun)\nreturn _vjp(lu.wrap_init(fun), *primals, **kwargs)\ndef _vjp(fun: lu.WrappedFun, *primals, **kwargs):\n" } ]
Python
Apache License 2.0
google/jax
add callable typechecks to more api.py functions
260,411
31.03.2020 10:01:19
-7,200
d2a827a08a87a85c2ba62fcadbc4d28cf5a4c092
Ensure the global trace_state is restored on errors in loops This is an attempted fix for
[ { "change_type": "MODIFY", "old_path": "jax/experimental/loops.py", "new_path": "jax/experimental/loops.py", "diff": "@@ -136,6 +136,7 @@ class Scope(object):\ndef __init__(self):\nself._mutable_state = {} # state to be functionalized, indexed by name.\nself._active_ranges = [] # stack of active ranges, last one is the innermost.\n+ self._count_subtraces = 0 # How many net started subtraces, for error recovery\ndef range(self, first, second=None, third=None):\n\"\"\"Creates an iterator for bounded iterations to be functionalized.\n@@ -246,7 +247,7 @@ class Scope(object):\nCalled for *all* attribute setting.\n\"\"\"\n- if key in [\"_active_ranges\", \"_mutable_state\"]:\n+ if key in [\"_active_ranges\", \"_mutable_state\", \"_count_subtraces\"]:\nobject.__setattr__(self, key, value)\nelse:\nif self._active_ranges and key not in self._mutable_state:\n@@ -258,6 +259,7 @@ class Scope(object):\nreturn self\ndef __exit__(self, exc_type, exc_val, exc_tb):\n+ try:\nif exc_type is None:\nif self._active_ranges: # We have some ranges that we did not exit properly\nself._error_premature_exit_range()\n@@ -267,6 +269,24 @@ class Scope(object):\n# exception propagate, assuming it terminates the tracing. If not, the\n# tracers may be left in an inconsistent state.\nreturn False # re-raise\n+ finally:\n+ # Ensure we leave the global trace_state as we found it\n+ while self._count_subtraces > 0:\n+ self.end_subtrace()\n+\n+ def start_subtrace(self):\n+ \"\"\"Starts a nested trace, returns the Trace object.\"\"\"\n+ # TODO: This follows the __enter__ part of core.new_master.\n+ level = core.trace_state.trace_stack.next_level(False)\n+ master = core.MasterTrace(level, pe.JaxprTrace)\n+ core.trace_state.trace_stack.push(master, False)\n+ self._count_subtraces += 1\n+ return pe.JaxprTrace(master, core.cur_sublevel())\n+\n+ def end_subtrace(self):\n+ # TODO: This follows the __exit__ part of core.new_master\n+ core.trace_state.trace_stack.pop(False)\n+ self._count_subtraces -= 1\nclass _BodyTracer(object):\n@@ -333,7 +353,7 @@ class _BodyTracer(object):\nself.carried_state_names = sorted(self.scope._mutable_state.keys())\n# TODO: This is the first part of partial_eval.trace_to_subjaxpr. Share.\n- self.trace = _BodyTracer.start_subtrace()\n+ self.trace = self.scope.start_subtrace()\n# Set the scope._mutable_state to new tracing variables.\nfor key, initial in self.carried_state_initial.items():\nmt_aval = _BodyTracer.abstractify(initial)\n@@ -376,7 +396,7 @@ class _BodyTracer(object):\n\"index variable returned by iterator.\") from e\nraise\n# End the subtrace for the loop body, before we trace the condition\n- _BodyTracer.end_subtrace()\n+ self.scope.end_subtrace()\ncarried_init_val = tuple([self.carried_state_initial[ms]\nfor ms in self.carried_state_names])\n@@ -392,20 +412,6 @@ class _BodyTracer(object):\nfor ms, mv in zip(self.carried_state_names, carried_mutable_state_unflattened):\nself.scope._mutable_state[ms] = mv\n- @staticmethod\n- def start_subtrace():\n- \"\"\"Starts a nested trace, returns the Trace object.\"\"\"\n- # TODO: This follows the __enter__ part of core.new_master. share\n- level = core.trace_state.trace_stack.next_level(False)\n- master = core.MasterTrace(level, pe.JaxprTrace)\n- core.trace_state.trace_stack.push(master, False)\n- return pe.JaxprTrace(master, core.cur_sublevel())\n-\n- @staticmethod\n- def end_subtrace():\n- # TODO: This follows the __exit__ part of core.new_master\n- core.trace_state.trace_stack.pop(False)\n-\n@staticmethod\ndef abstractify(x):\nreturn abstract_arrays.raise_to_shaped(core.get_aval(x))\n" }, { "change_type": "MODIFY", "old_path": "tests/loops_test.py", "new_path": "tests/loops_test.py", "diff": "@@ -20,6 +20,7 @@ import numpy as onp\nimport re\nfrom jax import api, lax, ops\n+from jax import core\nfrom jax import numpy as np\nfrom jax import test_util as jtu\nfrom jax.experimental import loops\n@@ -27,17 +28,15 @@ from jax.experimental import loops\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n-# Attempted fix for https://github.com/google/jax/issues/2507 based on resetting\n-# the global trace state. It could be that methods like _BodyTracer.end_subtrace\n-# are not cleaning up global trace state after exceptions because they don't use\n-# a try/finally pattern. This is just a guess though!\n-# TODO(mattjj,necula): check this attempted fix\n-from jax import core\n-def tearDownModule():\n- core.trace_state = core.TraceState()\nclass LoopsTest(jtu.JaxTestCase):\n+ def tearDown(self) -> None:\n+ # Check that the global state manipulated by loops is restored\n+ if core.trace_state.trace_stack.downward or core.trace_state.trace_stack.upward:\n+ core.trace_state = core.TraceState()\n+ assert False # Fail this test\n+\ndef test_scope_no_loops(self):\ndef f_op(r):\nwith loops.Scope() as s:\n" } ]
Python
Apache License 2.0
google/jax
Ensure the global trace_state is restored on errors in loops This is an attempted fix for https://github.com/google/jax/issues/2507
260,335
01.04.2020 08:25:32
25,200
86a4073a756126bb659c7027b85eb309aed98d60
enable beta test on float64 values * enable beta test on float64 values cf. * Enable beta test on all platforms. It seems sufficiently fast now.
[ { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -226,11 +226,10 @@ class LaxRandomTest(jtu.JaxTestCase):\n\"a\": a, \"b\": b, \"dtype\": onp.dtype(dtype).name}\nfor a in [0.2, 5.]\nfor b in [0.2, 5.]\n- for dtype in [onp.float32, onp.float64]))\n- # TODO(phawkins): slow compilation times on cpu and tpu.\n- # TODO(mattjj): test fails after https://github.com/google/jax/pull/1123\n- @jtu.skip_on_devices(\"cpu\", \"gpu\", \"tpu\")\n+ for dtype in [onp.float64])) # NOTE: KS test fails with float32\ndef testBeta(self, a, b, dtype):\n+ if not FLAGS.jax_enable_x64:\n+ raise SkipTest(\"skip test except on X64\")\nkey = random.PRNGKey(0)\nrand = lambda key, a, b: random.beta(key, a, b, (10000,), dtype)\ncrand = api.jit(rand)\n" } ]
Python
Apache License 2.0
google/jax
enable beta test on float64 values (#1177) * enable beta test on float64 values cf. #1123 * Enable beta test on all platforms. It seems sufficiently fast now. Co-authored-by: Peter Hawkins <phawkins@google.com>
260,411
02.04.2020 11:13:40
-7,200
0c53ce9def83699f107f3b5a3f683d0b2a50986a
Disable test with float16 on TPU
[ { "change_type": "MODIFY", "old_path": "jax/test_util.py", "new_path": "jax/test_util.py", "diff": "@@ -314,6 +314,10 @@ def supported_dtypes():\ndtypes.bfloat16, onp.float16, onp.float32, onp.float64,\nonp.complex64, onp.complex128}\n+def skip_if_unsupported_type(dtype):\n+ if dtype not in supported_dtypes():\n+ raise SkipTest(f\"Type {dtype} not supported on {device_under_test()}\")\n+\ndef skip_on_devices(*disabled_devices):\n\"\"\"A decorator for test methods to skip the test on certain devices.\"\"\"\ndef skip(test_method):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1261,6 +1261,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nif (dtype not in [jnp.bfloat16, onp.float16, onp.float32]\nand not FLAGS.jax_enable_x64):\nself.skipTest(\"Only run float64 testcase when float64 is enabled.\")\n+ jtu.skip_if_unsupported_type(dtype)\nrng = rng_factory()\nonp_fun = lambda x: onp.frexp(x)\njnp_fun = lambda x: jnp.frexp(x)\n" } ]
Python
Apache License 2.0
google/jax
Disable test with float16 on TPU
260,411
02.04.2020 13:10:50
-7,200
32c45fbb42e716291c56060109c77e8f1e8adeea
Another attempt to disable new failing test on TPU
[ { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1228,6 +1228,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfor x1_shape, x2_shape in filter(_shapes_are_broadcast_compatible,\nCombosWithReplacement(array_shapes, 2))\nfor x1_dtype in default_dtypes))\n+ @jtu.skip_on_devices(\"tpu\") # TODO(b/153053081)\ndef testLdexp(self, x1_shape, x1_dtype, x2_shape, x1_rng_factory, x2_rng_factory):\n# integer types are converted to float64 in numpy's implementation\nif (x1_dtype not in [jnp.bfloat16, onp.float16, onp.float32]\n@@ -1256,12 +1257,12 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n])\nfor shape in all_shapes\nfor dtype in default_dtypes))\n+ @jtu.skip_on_devices(\"tpu\")\ndef testFrexp(self, shape, dtype, rng_factory):\n# integer types are converted to float64 in numpy's implementation\nif (dtype not in [jnp.bfloat16, onp.float16, onp.float32]\nand not FLAGS.jax_enable_x64):\nself.skipTest(\"Only run float64 testcase when float64 is enabled.\")\n- jtu.skip_if_unsupported_type(dtype)\nrng = rng_factory()\nonp_fun = lambda x: onp.frexp(x)\njnp_fun = lambda x: jnp.frexp(x)\n" } ]
Python
Apache License 2.0
google/jax
Another attempt to disable new failing test on TPU
260,335
02.04.2020 07:52:17
25,200
84dc6cc1c4661afaa6cb0c1d61514131f31bab2c
post process call of jet! Also included David's jet rule for lax.select.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -49,12 +49,18 @@ def jet(fun, primals, series):\nyield tree_flatten(ans)\nf, out_tree = flatten_fun_output(lu.wrap_init(fun))\n- out_primals, out_terms = jet_transform(f).call_wrapped(primals, series)\n+ out_primals, out_terms = jet_fun(jet_subtrace(f)).call_wrapped(primals, series)\nreturn tree_unflatten(out_tree(), out_primals), tree_unflatten(out_tree(), out_terms)\n@lu.transformation\n-def jet_transform(primals, series):\n+def jet_fun(primals, series):\nwith core.new_master(JetTrace) as master:\n+ out_primals, out_terms = yield (master, primals, series), {}\n+ del master\n+ yield out_primals, out_terms\n+\n+@lu.transformation\n+def jet_subtrace(master, primals, series):\ntrace = JetTrace(master, core.cur_sublevel())\nin_tracers = map(partial(JetTracer, trace), primals, series)\nans = yield in_tracers, {}\n@@ -62,6 +68,13 @@ def jet_transform(primals, series):\nout_primals, out_terms = unzip2((t.primal, t.terms) for t in out_tracers)\nyield out_primals, out_terms\n+@lu.transformation_with_aux\n+def traceable(in_tree_def, *primals_and_series):\n+ primals_in, series_in = tree_unflatten(in_tree_def, primals_and_series)\n+ primals_out, series_out = yield (primals_in, series_in), {}\n+ out_flat, out_tree_def = tree_flatten((primals_out, series_out))\n+ yield out_flat, out_tree_def\n+\nclass JetTracer(core.Tracer):\n__slots__ = [\"primal\", \"terms\"]\n@@ -94,6 +107,7 @@ class JetTrace(core.Trace):\nreturn JetTracer(self, val.primal, val.terms)\ndef process_primitive(self, primitive, tracers, params):\n+ assert not primitive.multiple_results # TODO\nprimals_in, series_in = unzip2((t.primal, t.terms) for t in tracers)\norder, = {len(terms) for terms in series_in if terms is not zero_series}\nseries_in = [[zero_term] * order if s is zero_series else s\n@@ -107,10 +121,23 @@ class JetTrace(core.Trace):\nreturn JetTracer(self, primal_out, terms_out)\ndef process_call(self, call_primitive, f, tracers, params):\n- assert False # TODO\n-\n- def post_process_call(self, call_primitive, out_tracer, params):\n- assert False # TODO\n+ primals_in, series_in = unzip2((t.primal, t.terms) for t in tracers)\n+ primals_and_series, in_tree_def = tree_flatten((primals_in, series_in))\n+ f_jet, out_tree_def = traceable(jet_subtrace(f, self.master), in_tree_def)\n+ result = call_primitive.bind(f_jet, *primals_and_series, **params)\n+ primals_out, series_out = tree_unflatten(out_tree_def(), result)\n+ return [JetTracer(self, p, ts) for p, ts in zip(primals_out, series_out)]\n+\n+ def post_process_call(self, call_primitive, out_tracers, params):\n+ primals, series = unzip2((t.primal, t.terms) for t in out_tracers)\n+ out, treedef = tree_flatten((primals, series))\n+ del primals, series\n+ master = self.master\n+ def todo(x):\n+ primals, series = tree_unflatten(treedef, x)\n+ trace = JetTrace(master, core.cur_sublevel())\n+ return map(partial(JetTracer, trace), primals, series)\n+ return out, todo\ndef join(self, xt, yt):\nassert False # TODO?\n@@ -278,3 +305,12 @@ def _abs_taylor_rule(x, series_in, **params):\nseries_out = [fix_sign(*terms_in, **params) for terms_in in zip(*series_in)]\nreturn primal_out, series_out\njet_rules[lax.abs_p] = _abs_taylor_rule\n+\n+def _select_taylor_rule(primal_in, series_in, **params):\n+ b, x, y = primal_in\n+ primal_out = lax.select_p.bind(b, x, y, **params)\n+ sel = lambda _, x, y: lax.select(b, x, y)\n+ series_out = [sel(*terms_in, **params) for terms_in in zip(*series_in)]\n+ return primal_out, series_out\n+jet_rules[lax.select_p] = _select_taylor_rule\n+\n" }, { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -21,7 +21,7 @@ import numpy as onp\nfrom jax import test_util as jtu\nimport jax.numpy as np\nfrom jax import random\n-from jax import jacfwd\n+from jax import jacfwd, jit\nfrom jax.experimental import stax\nfrom jax.experimental.jet import jet, fact, zero_series\nfrom jax.tree_util import tree_map\n@@ -178,6 +178,31 @@ class JetTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_xor(self): self.binary_check(lambda x, y: np.logical_xor(x, y))\n+ def test_process_call(self):\n+ def f(x):\n+ return jit(lambda x: x * x)(x)\n+ self.unary_check(f)\n+\n+ def test_post_process_call(self):\n+ def f(x):\n+ return jit(lambda y: x * y)(2.)\n+\n+ self.unary_check(f)\n+\n+ def test_select(self):\n+ M, K = 2, 3\n+ order = 3\n+ rng = onp.random.RandomState(0)\n+ b = rng.rand(M, K) < 0.5\n+ x = rng.randn(M, K)\n+ y = rng.randn(M, K)\n+ primals = (b, x, y)\n+ terms_b = [rng.randn(*b.shape) for _ in range(order)]\n+ terms_x = [rng.randn(*x.shape) for _ in range(order)]\n+ terms_y = [rng.randn(*y.shape) for _ in range(order)]\n+ series_in = (terms_b, terms_x, terms_y)\n+ self.check_jet(np.where, primals, series_in)\n+\nif __name__ == '__main__':\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
post process call of jet! Also included David's jet rule for lax.select. Co-authored-by: Jesse Bettencourt <jessebett@cs.toronto.edu> Co-authored-by: Jacob Kelly <jacob.jin.kelly@gmail.com> Co-authored-by: David Duvenaud <duvenaud@cs.toronto.edu>
260,335
02.04.2020 15:52:01
25,200
c72abf6dab27fb9f43178808f9357dfa795c5b7d
re-enable travis mypy testing (typo broke it)
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -44,7 +44,7 @@ script:\n- if [ \"$JAX_ONLY_DOCUMENTATION\" = true ]; then\nsphinx-build -b html -D nbsphinx_execute=always docs docs/build/html ;\nelif [ \"$JAX_ONLY_CHECK_TYPES\" = true ]; then\n- echo \"===== Checking with mypy ====\"\n+ echo \"===== Checking with mypy ====\" &&\ntime mypy --config-file=mypy.ini jax ;\nelse\npytest tests examples -W ignore ;\n" } ]
Python
Apache License 2.0
google/jax
re-enable travis mypy testing (typo broke it)
260,335
02.04.2020 17:18:47
25,200
ab0a005452d04cae33164e88b616e45f6e5c19f5
check sublevel is reset in loops_test.py
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -46,6 +46,13 @@ FLAGS = config.FLAGS\nclass APITest(jtu.JaxTestCase):\n+ def tearDown(self) -> None:\n+ if (core.trace_state.substack != [core.Sublevel(0)] or\n+ core.trace_state.trace_stack.downward or\n+ core.trace_state.trace_stack.upward):\n+ core.trace_state = core.TraceState()\n+ assert False # Fail this test\n+\ndef test_grad_argnums(self):\ndef f(x, y, z, flag=False):\nassert flag\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -61,6 +61,13 @@ def high_precision_dot(a, b):\nclass LaxControlFlowTest(jtu.JaxTestCase):\n+ def tearDown(self) -> None:\n+ if (core.trace_state.substack != [core.Sublevel(0)] or\n+ core.trace_state.trace_stack.downward or\n+ core.trace_state.trace_stack.upward):\n+ core.trace_state = core.TraceState()\n+ assert False # Fail this test\n+\ndef testWhileWithTuple(self):\nlimit = 10\n" }, { "change_type": "MODIFY", "old_path": "tests/loops_test.py", "new_path": "tests/loops_test.py", "diff": "@@ -33,7 +33,9 @@ class LoopsTest(jtu.JaxTestCase):\ndef tearDown(self) -> None:\n# Check that the global state manipulated by loops is restored\n- if core.trace_state.trace_stack.downward or core.trace_state.trace_stack.upward:\n+ if (core.trace_state.substack != [core.Sublevel(0)] or\n+ core.trace_state.trace_stack.downward or\n+ core.trace_state.trace_stack.upward):\ncore.trace_state = core.TraceState()\nassert False # Fail this test\n" } ]
Python
Apache License 2.0
google/jax
check sublevel is reset in loops_test.py
260,335
02.04.2020 18:03:58
25,200
b78b7a03090aa4a7146ec32eb29b068f68bbf0ec
add global trace state checks to more tests
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -542,6 +542,17 @@ class TraceState(threading.local):\nreturn new\ntrace_state = TraceState()\n+def reset_trace_state() -> bool:\n+ \"Reset the global trace state and return True if it was already clean.\"\n+ global trace_state\n+ if (trace_state.substack != [Sublevel(0)] or\n+ trace_state.trace_stack.downward or\n+ trace_state.trace_stack.upward):\n+ trace_state = TraceState()\n+ return False\n+ else:\n+ return True\n+\ndef cur_sublevel() -> Sublevel:\nreturn trace_state.substack[-1]\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -47,11 +47,7 @@ FLAGS = config.FLAGS\nclass APITest(jtu.JaxTestCase):\ndef tearDown(self) -> None:\n- if (core.trace_state.substack != [core.Sublevel(0)] or\n- core.trace_state.trace_stack.downward or\n- core.trace_state.trace_stack.upward):\n- core.trace_state = core.TraceState()\n- assert False # Fail this test\n+ assert core.reset_trace_state()\ndef test_grad_argnums(self):\ndef f(x, y, z, flag=False):\n@@ -1596,6 +1592,9 @@ class APITest(jtu.JaxTestCase):\nclass JaxprTest(jtu.JaxTestCase):\n+ def tearDown(self) -> None:\n+ assert core.reset_trace_state()\n+\ndef test_scalar_literals(self):\njaxpr = api.make_jaxpr(lambda x: x + 2)(42)\nself.assertLen(jaxpr.jaxpr.constvars, 0)\n@@ -1808,6 +1807,9 @@ class JaxprTest(jtu.JaxTestCase):\nclass LazyTest(jtu.JaxTestCase):\n+ def tearDown(self) -> None:\n+ assert core.reset_trace_state()\n+\n@contextmanager\ndef count_compiles(self):\n@@ -1988,6 +1990,9 @@ class LazyTest(jtu.JaxTestCase):\nclass CustomJVPTest(jtu.JaxTestCase):\n+ def tearDown(self) -> None:\n+ assert core.reset_trace_state()\n+\ndef test_basic(self):\n@api.custom_jvp\ndef f(x):\n@@ -2425,6 +2430,9 @@ class CustomJVPTest(jtu.JaxTestCase):\nclass CustomVJPTest(jtu.JaxTestCase):\n+ def tearDown(self) -> None:\n+ assert core.reset_trace_state()\n+\ndef test_basic(self):\n@api.custom_vjp\ndef f(x):\n@@ -2776,6 +2784,9 @@ class CustomVJPTest(jtu.JaxTestCase):\nclass DeprecatedCustomTransformsTest(jtu.JaxTestCase):\n+ def tearDown(self) -> None:\n+ assert core.reset_trace_state()\n+\ndef test_defvjp_all(self):\nfoo_p = Primitive('foo')\ndef foo(x): return 2. * foo_p.bind(x)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -62,11 +62,7 @@ def high_precision_dot(a, b):\nclass LaxControlFlowTest(jtu.JaxTestCase):\ndef tearDown(self) -> None:\n- if (core.trace_state.substack != [core.Sublevel(0)] or\n- core.trace_state.trace_stack.downward or\n- core.trace_state.trace_stack.upward):\n- core.trace_state = core.TraceState()\n- assert False # Fail this test\n+ assert core.reset_trace_state()\ndef testWhileWithTuple(self):\nlimit = 10\n" }, { "change_type": "MODIFY", "old_path": "tests/loops_test.py", "new_path": "tests/loops_test.py", "diff": "@@ -32,12 +32,7 @@ config.parse_flags_with_absl()\nclass LoopsTest(jtu.JaxTestCase):\ndef tearDown(self) -> None:\n- # Check that the global state manipulated by loops is restored\n- if (core.trace_state.substack != [core.Sublevel(0)] or\n- core.trace_state.trace_stack.downward or\n- core.trace_state.trace_stack.upward):\n- core.trace_state = core.TraceState()\n- assert False # Fail this test\n+ assert core.reset_trace_state()\ndef test_scope_no_loops(self):\ndef f_op(r):\n" } ]
Python
Apache License 2.0
google/jax
add global trace state checks to more tests
260,335
02.04.2020 18:19:44
25,200
6d4987cc04e47d338e6d37bd9a75c84f1664809c
make core.trace_state resetting be thread-local
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -544,11 +544,10 @@ trace_state = TraceState()\ndef reset_trace_state() -> bool:\n\"Reset the global trace state and return True if it was already clean.\"\n- global trace_state\nif (trace_state.substack != [Sublevel(0)] or\ntrace_state.trace_stack.downward or\ntrace_state.trace_stack.upward):\n- trace_state = TraceState()\n+ trace_state.__init__()\nreturn False\nelse:\nreturn True\n" } ]
Python
Apache License 2.0
google/jax
make core.trace_state resetting be thread-local
260,335
02.04.2020 20:14:12
25,200
5d3f1bdf4c140db29c15d4dfca594ddfae27f577
tell mypy: using __init__ to reinitialize is OK
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -547,7 +547,7 @@ def reset_trace_state() -> bool:\nif (trace_state.substack != [Sublevel(0)] or\ntrace_state.trace_stack.downward or\ntrace_state.trace_stack.upward):\n- trace_state.__init__()\n+ trace_state.__init__() # type: ignore\nreturn False\nelse:\nreturn True\n" } ]
Python
Apache License 2.0
google/jax
tell mypy: using __init__ to reinitialize is OK
260,335
02.04.2020 21:04:12
25,200
297c90246d22dccfa8d280097a5fa653e992643c
make tracers tree-pretty-print their contents
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -449,7 +449,18 @@ class Tracer(object):\nreturn attr\ndef __repr__(self):\n- return 'Traced<{}>with<{}>'.format(self.aval, self._trace)\n+ base = pp('Traced<{}>with<{}>'.format(self.aval, self._trace))\n+ contents = self._contents()\n+ if contents:\n+ base += pp(' with ') >> vcat(pp('{} = '.format(name)) >> pp_payload\n+ for name, pp_payload in contents)\n+ return str(base)\n+\n+ def _contents(self):\n+ try:\n+ return [(name, pp(repr(getattr(self, name)))) for name in self.__slots__]\n+ except AttributeError:\n+ return ()\ndef __copy__(self):\nreturn self\n" } ]
Python
Apache License 2.0
google/jax
make tracers tree-pretty-print their contents
260,335
02.04.2020 22:01:43
25,200
f2de1bf3457b7cece346c8e8762f1bd67bfdcc32
add trace state check tearDown to JaxTestCase
[ { "change_type": "MODIFY", "old_path": "jax/test_util.py", "new_path": "jax/test_util.py", "diff": "@@ -668,6 +668,9 @@ def cases_from_gens(*gens):\nclass JaxTestCase(parameterized.TestCase):\n\"\"\"Base class for JAX tests including numerical checks and boilerplate.\"\"\"\n+ def tearDown(self) -> None:\n+ assert core.reset_trace_state()\n+\ndef assertArraysAllClose(self, x, y, check_dtypes, atol=None, rtol=None):\n\"\"\"Assert that x and y are close (up to numerical tolerances).\"\"\"\nself.assertEqual(x.shape, y.shape)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -46,9 +46,6 @@ FLAGS = config.FLAGS\nclass APITest(jtu.JaxTestCase):\n- def tearDown(self) -> None:\n- assert core.reset_trace_state()\n-\ndef test_grad_argnums(self):\ndef f(x, y, z, flag=False):\nassert flag\n@@ -1592,9 +1589,6 @@ class APITest(jtu.JaxTestCase):\nclass JaxprTest(jtu.JaxTestCase):\n- def tearDown(self) -> None:\n- assert core.reset_trace_state()\n-\ndef test_scalar_literals(self):\njaxpr = api.make_jaxpr(lambda x: x + 2)(42)\nself.assertLen(jaxpr.jaxpr.constvars, 0)\n@@ -1807,9 +1801,6 @@ class JaxprTest(jtu.JaxTestCase):\nclass LazyTest(jtu.JaxTestCase):\n- def tearDown(self) -> None:\n- assert core.reset_trace_state()\n-\n@contextmanager\ndef count_compiles(self):\n@@ -1990,9 +1981,6 @@ class LazyTest(jtu.JaxTestCase):\nclass CustomJVPTest(jtu.JaxTestCase):\n- def tearDown(self) -> None:\n- assert core.reset_trace_state()\n-\ndef test_basic(self):\n@api.custom_jvp\ndef f(x):\n@@ -2430,9 +2418,6 @@ class CustomJVPTest(jtu.JaxTestCase):\nclass CustomVJPTest(jtu.JaxTestCase):\n- def tearDown(self) -> None:\n- assert core.reset_trace_state()\n-\ndef test_basic(self):\n@api.custom_vjp\ndef f(x):\n@@ -2784,9 +2769,6 @@ class CustomVJPTest(jtu.JaxTestCase):\nclass DeprecatedCustomTransformsTest(jtu.JaxTestCase):\n- def tearDown(self) -> None:\n- assert core.reset_trace_state()\n-\ndef test_defvjp_all(self):\nfoo_p = Primitive('foo')\ndef foo(x): return 2. * foo_p.bind(x)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -61,9 +61,6 @@ def high_precision_dot(a, b):\nclass LaxControlFlowTest(jtu.JaxTestCase):\n- def tearDown(self) -> None:\n- assert core.reset_trace_state()\n-\ndef testWhileWithTuple(self):\nlimit = 10\n" }, { "change_type": "MODIFY", "old_path": "tests/loops_test.py", "new_path": "tests/loops_test.py", "diff": "@@ -31,9 +31,6 @@ config.parse_flags_with_absl()\nclass LoopsTest(jtu.JaxTestCase):\n- def tearDown(self) -> None:\n- assert core.reset_trace_state()\n-\ndef test_scope_no_loops(self):\ndef f_op(r):\nwith loops.Scope() as s:\n" } ]
Python
Apache License 2.0
google/jax
add trace state check tearDown to JaxTestCase
260,335
02.04.2020 22:52:07
25,200
0e49133e12c2a318e02e5c9dd3d664d730e0be45
add full lower to custom_jvp/vjp call bind fixes
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -252,6 +252,7 @@ def _flatten_jvp(in_tree, *args):\nyield primals_out + tangents_out, out_tree\ndef _custom_jvp_call_bind(prim, fun, jvp, *args):\n+ args = map(core.full_lower, args)\ntop_trace = core.find_top_trace(args)\nlevel = (core.trace_state.trace_stack.next_level(True)\nif top_trace is None else top_trace.level)\n@@ -490,6 +491,7 @@ def _flatten_bwd(in_tree, out_trees, *args):\nyield cts_in\ndef _custom_vjp_call_bind(prim, fun, fwd, bwd, *args, out_trees):\n+ args = map(core.full_lower, args)\ntop_trace = core.find_top_trace(args)\nlevel = (core.trace_state.trace_stack.next_level(True)\nif top_trace is None else top_trace.level)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2781,6 +2781,19 @@ class CustomVJPTest(jtu.JaxTestCase):\nexpected = jax.grad(f, 0)(2., 0.1) + jax.grad(f, 0)(2., 0.2)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_lowering_out_of_traces(self):\n+ # https://github.com/google/jax/issues/2578\n+\n+ class F(collections.namedtuple(\"F\", [\"a\"])):\n+ def __call__(self, x):\n+ return jax.nn.relu(self.a) * x\n+\n+ @jax.jit\n+ def g(f, x):\n+ return f(x)\n+\n+ jax.grad(g, argnums=(1,))(F(2.0), 0.) # doesn't crash\n+\nclass DeprecatedCustomTransformsTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add full lower to custom_jvp/vjp call bind fixes #2578
260,335
02.04.2020 23:11:55
25,200
ba8225f394b0e4aa5a9e09476cce8e917ebda527
skip all parallelize tests (abandonware right now)
[ { "change_type": "MODIFY", "old_path": "tests/parallel_test.py", "new_path": "tests/parallel_test.py", "diff": "import itertools\nimport unittest\n-from unittest import SkipTest\n+from unittest import SkipTest, skip\nimport numpy as onp\nfrom absl.testing import absltest\n@@ -130,6 +130,7 @@ class PapplyTest(jtu.JaxTestCase):\nmake_jaxpr(pfun)(onp.ones(3)) # doesn't crash\n+@skip(\"causing trace state errors that affect other tests\")\nclass ParallelizeTest(jtu.JaxTestCase):\ndef dedup(self, arr, expected_rank):\n" } ]
Python
Apache License 2.0
google/jax
skip all parallelize tests (abandonware right now)
260,510
03.04.2020 13:27:02
25,200
72783bb71b1848442549ad9c6b699e88cd07d0cb
Fix grad(logit) to use defjvps and enable it in tests
[ { "change_type": "MODIFY", "old_path": "jax/scipy/special.py", "new_path": "jax/scipy/special.py", "diff": "@@ -84,7 +84,7 @@ def erfinv(x):\ndef logit(x):\nx = asarray(x)\nreturn lax.log(lax.div(x, lax.sub(lax._const(x, 1), x)))\n-logit.defjvp(lambda g, ans, x: g / (x * (1 - x)))\n+logit.defjvps(lambda g, ans, x: g / (x * (1 - x)))\n@api.custom_jvp\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_scipy_test.py", "new_path": "tests/lax_scipy_test.py", "diff": "@@ -68,7 +68,7 @@ JAX_SPECIAL_FUNCTION_RECORDS = [\nop_record(\"expit\", 1, float_dtypes, jtu.rand_small_positive, True),\n# TODO: gammaln has slightly high error.\nop_record(\"gammaln\", 1, float_dtypes, jtu.rand_positive, False),\n- op_record(\"logit\", 1, float_dtypes, jtu.rand_small_positive, False),\n+ op_record(\"logit\", 1, float_dtypes, jtu.rand_uniform, True),\nop_record(\"log_ndtr\", 1, float_dtypes, jtu.rand_default, True),\nop_record(\"ndtri\", 1, float_dtypes, partial(jtu.rand_uniform, 0.05, 0.95),\nTrue),\n" } ]
Python
Apache License 2.0
google/jax
Fix grad(logit) to use defjvps and enable it in tests
260,411
02.04.2020 14:44:36
-7,200
f5f35c5c3b9087aa4f122d934437c7f0ff36ba76
Adapted vmap out_axes check to sum_match
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -59,7 +59,7 @@ def _batch_fun(sum_match, in_dims, out_dims_thunk, out_dim_dests, *in_vals, **pa\nout_dim_dests = out_dim_dests() if callable(out_dim_dests) else out_dim_dests\nout_dims = out_dims_thunk()\nfor od, od_dest in zip(out_dims, out_dim_dests):\n- if od is not None and not isinstance(od_dest, int) and not od_dest is last:\n+ if 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)\nout_vals = map(partial(matchaxis, size, sum_match=sum_match), out_dims, out_dim_dests, out_vals)\n" } ]
Python
Apache License 2.0
google/jax
Adapted vmap out_axes check to sum_match
260,313
06.04.2020 19:48:42
-3,600
fc23e071bcb73d2181c890d240f94cdcec47a058
Also enable nan checking for complex numbers
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -279,7 +279,7 @@ def check_nans(prim, bufs):\ndef _check_nans(name, xla_shape, buf):\nassert not xla_shape.is_tuple()\n- if dtypes.issubdtype(xla_shape.element_type(), onp.floating):\n+ if dtypes.issubdtype(xla_shape.element_type(), onp.inexact):\nif onp.any(onp.isnan(buf.to_py())):\nmsg = \"invalid value (nan) encountered in {}\"\nraise FloatingPointError(msg.format(name))\n" } ]
Python
Apache License 2.0
google/jax
Also enable nan checking for complex numbers (#2616)
260,700
07.04.2020 17:55:07
14,400
4d7b63c5ecb92419319fa1f5809d595ebce43fa7
add expm1 and log1p
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -228,6 +228,17 @@ 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 _log_taylor(primals_in, series_in):\nx, = primals_in\nseries, = series_in\n@@ -240,6 +251,18 @@ def _log_taylor(primals_in, series_in):\nreturn primal_out, series_out\njet_rules[lax.log_p] = _log_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+\ndef _div_taylor_rule(primals_in, series_in, **params):\nx, y = primals_in\nx_terms, y_terms = series_in\n" }, { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -150,6 +150,10 @@ class JetTest(jtu.JaxTestCase):\ndef test_abs(self): self.unary_check(np.abs)\n@jtu.skip_on_devices(\"tpu\")\ndef test_fft(self): self.unary_check(np.fft.fft)\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_log1p(self): self.unary_check(np.log1p, lims=[0, 4.])\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_expm1(self): self.unary_check(np.expm1)\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 expm1 and log1p
260,700
08.04.2020 21:51:44
14,400
1fa0e8a67df65a4c941d4970f1961d5cb5e4d450
jet of pow using comp with exp, mul, log
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -239,6 +239,22 @@ def _expm1_taylor(primals_in, series_in):\nreturn lax.expm1(x), series_out\njet_rules[lax.expm1_p] = _expm1_taylor\n+def _pow_taylor(primals_in, series_in):\n+ u_, r_ = primals_in\n+ u_terms, r_terms = series_in\n+ u = [u_] + u_terms\n+ r = [r_] + r_terms\n+\n+ logu_, logu_terms = _log_taylor((u_, ), (u_terms, ))\n+\n+ v_, v_terms = _bilinear_taylor_rule(lax.mul_p, (logu_, r_), (logu_terms, r_terms))\n+\n+ v_, v_terms = _exp_taylor((v_, ), (v_terms, ))\n+\n+ return v_, v_terms\n+jet_rules[lax.pow_p] = _pow_taylor\n+\n+\ndef _log_taylor(primals_in, series_in):\nx, = primals_in\nseries, = series_in\n" }, { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -181,6 +181,8 @@ class JetTest(jtu.JaxTestCase):\ndef test_or(self): self.binary_check(lambda x, y: np.logical_or(x, y))\n@jtu.skip_on_devices(\"tpu\")\ndef test_xor(self): self.binary_check(lambda x, y: np.logical_xor(x, y))\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_pow2(self): self.binary_check(lambda x, y: x ** y, lims=[0.2, 15])\ndef test_process_call(self):\ndef f(x):\n" } ]
Python
Apache License 2.0
google/jax
jet of pow using comp with exp, mul, log Co-authored-by: Jesse Bettencourt <jessebett@cs.toronto.edu> Co-authored-by: David Duvenaud <duvenaud@cs.toronto.edu>
260,335
03.04.2020 21:33:32
25,200
7ab67756c804adf33f832a525eb8975e6ddc995f
make float and complex builtins error on Tracers cf.
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -419,13 +419,19 @@ class Tracer(object):\ndef __getitem__(self, idx): return self.aval._getitem(self, idx)\ndef __nonzero__(self): return self.aval._nonzero(self)\ndef __bool__(self): return self.aval._bool(self)\n- def __float__(self): return self.aval._float(self)\ndef __int__(self): return self.aval._int(self)\ndef __long__(self): return self.aval._long(self)\n- def __complex__(self): return self.aval._complex(self)\ndef __hex__(self): return self.aval._hex(self)\ndef __oct__(self): return self.aval._oct(self)\n+ def __float__(self):\n+ raise TypeError(\"JAX Tracer object cannot be interpreted as a float. \"\n+ \"Try using `x.astype(float)` instead.\")\n+\n+ def __complex__(self):\n+ raise TypeError(\"JAX Tracer object cannot be interpreted as a complex. \"\n+ \"Try using `x.astype(complex)` instead.\")\n+\ndef __setitem__(self, idx, val):\nraise TypeError(\"JAX 'Tracer' objects do not support item assignment\")\n@@ -748,11 +754,11 @@ class UnshapedArray(AbstractValue):\n_bool = _nonzero = concretization_function_error(bool)\n_float = concretization_function_error(\n- float, \"Try using `value.astype(float)` instead.\")\n+ float, \"Try using `x.astype(float)` instead.\")\n_int = concretization_function_error(\n- int, \"Try using `value.astype(int)` instead.\")\n+ int, \"Try using `x.astype(int)` instead.\")\n_complex = concretization_function_error(\n- complex, \"Try using `value.astype(complex)` instead.\")\n+ complex, \"Try using `x.astype(complex)` instead.\")\n_hex = concretization_function_error(hex)\n_oct = concretization_function_error(oct)\n@@ -884,9 +890,7 @@ class ConcreteArray(ShapedArray):\nreturn ConcreteArray(self.val) if self.weak_type else self\n_bool = _nonzero = partialmethod(_forward_to_value, bool)\n- _float = partialmethod(_forward_to_value, float)\n_int = partialmethod(_forward_to_value, int)\n- _complex = partialmethod(_forward_to_value, complex)\n_hex = partialmethod(_forward_to_value, hex)\n_oct = partialmethod(_forward_to_value, oct)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -212,7 +212,7 @@ class APITest(jtu.JaxTestCase):\nself.assertRaisesRegex(\nTypeError,\n- \"Try using `value.astype\\({}\\)` instead\".format(castfun.__name__),\n+ \"Try using `x.astype\\({}\\)` instead.\".format(castfun.__name__),\nlambda: jit(f)(1.0))\ndef test_switch_value_jit(self):\n@@ -241,7 +241,7 @@ class APITest(jtu.JaxTestCase):\nlambda: jit(f)(0, 5))\ndef test_casts(self):\n- for castfun in [float, complex, hex, oct, int]:\n+ for castfun in [hex, oct, int]:\nf = lambda x: castfun(x)\nself.assertRaisesRegex(\nTypeError,\n" } ]
Python
Apache License 2.0
google/jax
make float and complex builtins error on Tracers cf. #2508
260,411
09.04.2020 14:10:52
-7,200
5965225011292dd126a06e8eb2b2a4ace0f99248
Fix type hints for pytype * We have to be careful for return types to specify that we return Tuple[T, ...] instead of Sequence[T], at least in those places where the caller assumes that the result is a tuple.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -370,8 +370,9 @@ class JaxprTracer(Tracer):\n# TODO(necula): this should return a TypedJaxpr\ndef trace_to_jaxpr(fun: lu.WrappedFun, pvals: Sequence[PartialVal],\n- instantiate=False, stage_out=False, bottom=False) \\\n- -> Tuple[Jaxpr, Sequence[PartialVal], Sequence[core.Value]]:\n+ instantiate: Union[bool, Sequence[bool]] = False,\n+ stage_out=False, bottom=False) \\\n+ -> Tuple[Jaxpr, Tuple[PartialVal, ...], Tuple[core.Value, ...]]:\n\"\"\"Traces a function into a Jaxpr, given PartialVals for inputs.\nReturns (`jaxpr`, `out_pvals`, `consts`).\n@@ -548,7 +549,8 @@ def convert_constvars_jaxpr(jaxpr):\nreturn lifted_jaxpr\ndef partial_eval_jaxpr(jaxpr: TypedJaxpr, unknowns: Sequence[bool],\n- instantiate: bool) -> Tuple[TypedJaxpr, TypedJaxpr, Sequence[bool]]:\n+ instantiate: Union[bool, Sequence[bool]]\n+ ) -> Tuple[TypedJaxpr, TypedJaxpr, Sequence[bool]]:\n\"\"\"Specializes a Jaxpr given an indication of which inputs are known.\nReturns: (jaxpr_known, jaxpr_unknown, out_unknowns).\n" } ]
Python
Apache License 2.0
google/jax
Fix type hints for pytype * We have to be careful for return types to specify that we return Tuple[T, ...] instead of Sequence[T], at least in those places where the caller assumes that the result is a tuple.
260,284
09.04.2020 20:36:09
-3,600
1694a56fa344bd677bbb36e5da818dd24f8659e1
Fixes a fallthrough in the tensordot axes verification logic
[ { "change_type": "MODIFY", "old_path": "jax/numpy/lax_numpy.py", "new_path": "jax/numpy/lax_numpy.py", "diff": "@@ -2455,6 +2455,9 @@ def tensordot(a, b, axes=2, precision=None):\nraise TypeError(msg.format(ax1, ax2))\ncontracting_dims = (tuple(_canonicalize_axis(i, a_ndim) for i in ax1),\ntuple(_canonicalize_axis(i, b_ndim) for i in ax2))\n+ else:\n+ msg = \"tensordot requires both axes lists to be either ints, tuples or lists, got {} and {}\"\n+ raise TypeError(msg.format(ax1, ax2))\nelse:\nmsg = (\"tensordot axes argument must be an int, a pair of ints, or a pair \"\n\"of lists/tuples of ints.\")\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -823,6 +823,19 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nTypeError, \"Number of tensordot axes.*exceeds input ranks.*\",\nlambda: jnp.tensordot(a, b, axes=2))\n+ self.assertRaisesRegex(\n+ TypeError, \"tensordot requires axes lists to have equal length.*\",\n+ lambda: jnp.tensordot(a, b, axes=([0], [0, 1])))\n+\n+ self.assertRaisesRegex(\n+ TypeError, \"tensordot requires both axes lists to be either ints, tuples or lists.*\",\n+ lambda: jnp.tensordot(a, b, axes=('bad', 'axes')))\n+\n+ self.assertRaisesRegex(\n+ TypeError, \"tensordot axes argument must be an int, a pair of ints, or a pair of lists.*\",\n+ lambda: jnp.tensordot(a, b, axes='badaxes'))\n+\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_{}\".format(\njtu.format_shape_dtype_string(lhs_shape, lhs_dtype),\n" } ]
Python
Apache License 2.0
google/jax
Fixes a fallthrough in the tensordot axes verification logic (#2658)
260,554
09.04.2020 13:27:16
25,200
25d797b1d9236a76c681a7e9061a4bc87339ee35
Added callback_transform, examples, and tests.
[ { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/.#callback.py", "diff": "+schsam@schsam-macbookpro2.roam.corp.google.com.3400\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/callback.py", "diff": "+# Copyright 2018 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import numpy as onp\n+from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Union\n+\n+import jax.numpy as np\n+\n+from jax import core\n+from jax.core import Trace, Tracer, new_master\n+from jax import linear_util as lu\n+from jax.util import partial, safe_map, wrap_name\n+from jax.interpreters import xla\n+from jax.interpreters import partial_eval as pe\n+\n+import inspect\n+from jax.api_util import (wraps, flatten_fun_nokwargs)\n+from jax.tree_util import (tree_flatten, tree_unflatten)\n+from jax import lax\n+\n+map = safe_map\n+\n+### Public\n+\n+def callback_transform(\n+ fun: Callable, callback: Callable, strip_calls=False) -> Callable:\n+ _check_callable(fun)\n+\n+ @wraps(fun)\n+ def wrapped_fun(*args):\n+ args_flat, in_tree = tree_flatten(args)\n+ f = lu.wrap_init(fun)\n+ flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\n+ out_flat = callback_fun(flat_fun, args_flat, callback, strip_calls)\n+ return tree_unflatten(out_tree(), out_flat)\n+\n+ return wrapped_fun\n+\n+### Example Transform\n+\n+def find_by_value(fun: Callable, queries) -> Callable:\n+ def find_callback(p, vals, params):\n+ vals = p.bind(*vals, **params)\n+ _contains_query(vals, queries)\n+ return vals\n+ return callback_transform(fun, find_callback, True)\n+\n+def rewrite(fun: Callable, rules) -> Callable:\n+ assert isinstance(rules, dict)\n+ def rewrite_callback(p, vals, params):\n+ if p in rules:\n+ return rules[p](*vals, **params)\n+ return p.bind(*vals, **params)\n+ return callback_transform(fun, rewrite_callback)\n+\n+class FoundValue(Exception):\n+ pass\n+\n+def _contains_query(vals, query):\n+ if isinstance(query, tuple):\n+ return map(partial(contains_query, vals), query)\n+\n+ if np.isnan(query):\n+ if np.any(np.isnan(vals)):\n+ raise FoundValue('NaN')\n+ elif np.isinf(query):\n+ if np.any(np.isinf(vals)):\n+ raise FoundValue('Found Inf')\n+ elif np.isscalar(query):\n+ if np.any(vals == query):\n+ raise FoundValue(str(query))\n+ else:\n+ raise ValueError('Malformed Query: {}'.format(query))\n+\n+### Helper Functions\n+\n+def callback_fun(fun : lu.WrappedFun, in_vals, callback, strip_calls):\n+ fun = callback_subtrace(fun)\n+ fun = _callback_fun(fun, callback, strip_calls)\n+ return fun.call_wrapped(*in_vals)\n+\n+@lu.transformation\n+def callback_subtrace(master, *in_vals, **params):\n+ trace = CallbackTrace(master, core.cur_sublevel())\n+ in_tracers = [CallbackTracer(trace, val) for val in in_vals]\n+ outs = yield in_tracers, params\n+ out_tracers = map(trace.full_raise, outs)\n+ out_vals = [t.val for t in out_tracers]\n+ yield out_vals\n+\n+@lu.transformation\n+def _callback_fun(callback, strip_calls, *in_vals, **params):\n+ with new_master(CallbackTrace) as master:\n+ master.callback = callback # NOTE: Is this OK?\n+ master.strip_calls = strip_calls\n+ out_vals = yield (master,) + in_vals, params\n+ del master\n+ yield out_vals\n+\n+def _check_callable(fun):\n+ if not callable(fun):\n+ raise TypeError(f\"Expected a callable value, got {fun}\")\n+ if inspect.isgeneratorfunction(fun):\n+ raise TypeError(f\"Expected a function, got a generator function: {fun}\")\n+\n+### Tracer\n+\n+class CallbackTracer(Tracer):\n+ __slots__ = ['val']\n+\n+ def __init__(self, trace, val):\n+ self._trace = trace\n+ self.val = val\n+\n+ @property\n+ def aval(self):\n+ return core.get_aval(self.val)\n+\n+ def full_lower(self):\n+ return self\n+\n+class CallbackTrace(Trace):\n+ def pure(self, val):\n+ return CallbackTracer(self, val)\n+\n+ def lift(self, val):\n+ return CallbackTracer(self, val)\n+\n+ def sublift(self, val):\n+ return CallbackTracer(self, val.val)\n+\n+ def process_primitive(self, primitive, tracers, params):\n+ vals_in = [t.val for t in tracers]\n+ vals_out = self.master.callback(primitive, vals_in, params)\n+ if primitive.multiple_results:\n+ return [CallbackTracer(self, val) for val in vals_out]\n+ return CallbackTracer(self, vals_out)\n+\n+ def process_call(self, call_primitive, f: lu.WrappedFun, tracers, params):\n+ if self.master.strip_calls:\n+ return f.call_wrapped(*tracers)\n+ vals_in = [t.val for t in tracers]\n+ f = callback_subtrace(f, self.master)\n+ vals_out = call_primitive.bind(f, *vals_in, **params)\n+ return [CallbackTracer(self, val) for val in vals_out]\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/callback_test.py", "diff": "+# Copyright 2018 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from absl.testing import absltest\n+from absl.testing import parameterized\n+\n+import numpy as onp\n+\n+from jax import test_util as jtu\n+from jax.experimental.callback import (\n+ callback_transform, find_by_value, rewrite, FoundValue)\n+import jax.numpy as np\n+from jax import lax\n+\n+from jax.config import config\n+config.parse_flags_with_absl()\n+\n+class CallbackTest(jtu.JaxTestCase):\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {'testcase_name': '_value={}'.format(value), 'value': value}\n+ for value in [np.inf, np.nan]))\n+ def testFindByValueFound(self, value):\n+ def f(x):\n+ y = x ** 2\n+ z = 1 - y\n+ r = 1 / z\n+ return r * 0\n+\n+ with self.assertRaises(FoundValue):\n+ find_by_value(f, value)(np.array([1.0, 2.0, 3.0]))\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {'testcase_name': '_value={}'.format(value), 'value': value}\n+ for value in [np.inf, np.nan]))\n+ def testFindByValueNotFound(self, value):\n+ def f(x):\n+ y = x ** 2\n+ z = 1 - y\n+ return z\n+\n+ find_by_value(f, value)(np.array([1.0, 2.0, 3.0]))\n+\n+ def testRewrite(self):\n+ def f(x):\n+ return x * 2\n+\n+ x = np.array([2.0, 4.0])\n+ self.assertAllClose(f(x), np.array([4.0, 8.0]), True)\n+\n+ self.assertAllClose(\n+ rewrite(f, {lax.mul_p: lambda x, y: x + y})(x),\n+ np.array([4.0, 6.0]), True)\n+\n+if __name__ == \"__main__\":\n+ absltest.main()\n" } ]
Python
Apache License 2.0
google/jax
Added callback_transform, examples, and tests.
260,554
09.04.2020 13:52:14
25,200
940640d8d26711cef72f6c46240e6ee9ae599760
Added tests of callback_transform(jit(fn)).
[ { "change_type": "MODIFY", "old_path": "tests/callback_test.py", "new_path": "tests/callback_test.py", "diff": "@@ -22,6 +22,7 @@ from jax.experimental.callback import (\ncallback_transform, find_by_value, rewrite, FoundValue)\nimport jax.numpy as np\nfrom jax import lax\n+from jax import jit\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -40,6 +41,21 @@ class CallbackTest(jtu.JaxTestCase):\nwith self.assertRaises(FoundValue):\nfind_by_value(f, value)(np.array([1.0, 2.0, 3.0]))\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {'testcase_name': '_value={}'.format(value), 'value': value}\n+ for value in [np.inf, np.nan]))\n+ def testFindByValueFoundJIT(self, value):\n+ def f(x):\n+ @jit\n+ def g(x):\n+ y = x ** 2\n+ z = 1 - y\n+ r = 1 / z\n+ return r * 0\n+ return g(x)\n+ with self.assertRaises(FoundValue):\n+ find_by_value(f, value)(np.array([1.0, 2.0, 3.0]))\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{'testcase_name': '_value={}'.format(value), 'value': value}\nfor value in [np.inf, np.nan]))\n@@ -62,5 +78,19 @@ class CallbackTest(jtu.JaxTestCase):\nrewrite(f, {lax.mul_p: lambda x, y: x + y})(x),\nnp.array([4.0, 6.0]), True)\n+ def testRewriteJIT(self):\n+ def f(x):\n+ @jit\n+ def g(x):\n+ return x * 2\n+ return g(x)\n+\n+ x = np.array([2.0, 4.0])\n+ self.assertAllClose(f(x), np.array([4.0, 8.0]), True)\n+\n+ self.assertAllClose(\n+ rewrite(f, {lax.mul_p: lambda x, y: x + y})(x),\n+ np.array([4.0, 6.0]), True)\n+\nif __name__ == \"__main__\":\nabsltest.main()\n" } ]
Python
Apache License 2.0
google/jax
Added tests of callback_transform(jit(fn)).
260,370
09.04.2020 18:10:49
14,400
60d856ab9f6d82cdb370b2d6d0eba1ada6a22253
remove from __future__ code
[ { "change_type": "MODIFY", "old_path": "examples/control.py", "new_path": "examples/control.py", "diff": "Model-predictive non-linear control example.\n\"\"\"\n-from __future__ import absolute_import\n-from __future__ import division\n-from __future__ import print_function\n-\nimport collections\nfrom jax import lax, grad, jacfwd, jacobian, vmap\n" }, { "change_type": "MODIFY", "old_path": "examples/control_test.py", "new_path": "examples/control_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-from __future__ import absolute_import\n-from __future__ import division\n-from __future__ import print_function\n-\nfrom functools import partial\nfrom unittest import SkipTest\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/logistic.py", "new_path": "jax/scipy/stats/logistic.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-from __future__ import absolute_import\n-from __future__ import division\n-from __future__ import print_function\n-\nimport scipy.stats as osp_stats\nfrom jax.scipy.special import expit, logit\n" } ]
Python
Apache License 2.0
google/jax
remove from __future__ code
260,554
09.04.2020 15:20:41
25,200
f5908cb5ee78b550110f6262275d64538ab5bf01
Fixed copyright, added type annotations, disabled mypy on one line.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/callback.py", "new_path": "jax/experimental/callback.py", "diff": "-# Copyright 2018 Google LLC\n+# 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@@ -27,14 +27,13 @@ from jax.interpreters import partial_eval as pe\nimport inspect\nfrom jax.api_util import (wraps, flatten_fun_nokwargs)\nfrom jax.tree_util import (tree_flatten, tree_unflatten)\n-from jax import lax\nmap = safe_map\n### Public\ndef callback_transform(\n- fun: Callable, callback: Callable, strip_calls=False) -> Callable:\n+ fun: Callable, callback: Callable, strip_calls: bool=False) -> Callable:\n_check_callable(fun)\n@wraps(fun)\n@@ -50,18 +49,24 @@ def callback_transform(\n### Example Transform\ndef find_by_value(fun: Callable, queries) -> Callable:\n- def find_callback(p, vals, params):\n- vals = p.bind(*vals, **params)\n+ def find_callback(\n+ prim: core.Primitive,\n+ vals: Sequence[core.Tracer],\n+ params: Dict[str, Any]) -> Union[core.Tracer, Sequence[core.Tracer]]:\n+ vals = prim.bind(*vals, **params)\n_contains_query(vals, queries)\nreturn vals\nreturn callback_transform(fun, find_callback, True)\ndef rewrite(fun: Callable, rules) -> Callable:\nassert isinstance(rules, dict)\n- def rewrite_callback(p, vals, params):\n- if p in rules:\n- return rules[p](*vals, **params)\n- return p.bind(*vals, **params)\n+ def rewrite_callback(\n+ prim: core.Primitive,\n+ vals: Sequence[core.Tracer],\n+ params: Dict[str, Any]) -> Union[core.Tracer, Sequence[core.Tracer]]:\n+ if prim in rules:\n+ return rules[prim](*vals, **params)\n+ return prim.bind(*vals, **params)\nreturn callback_transform(fun, rewrite_callback)\nclass FoundValue(Exception):\n@@ -148,7 +153,7 @@ class CallbackTrace(Trace):\nreturn CallbackTracer(self, vals_out)\ndef process_call(self, call_primitive, f: lu.WrappedFun, tracers, params):\n- if self.master.strip_calls:\n+ if self.master.strip_calls: # type: ignore\nreturn f.call_wrapped(*tracers)\nvals_in = [t.val for t in tracers]\nf = callback_subtrace(f, self.master)\n" }, { "change_type": "MODIFY", "old_path": "tests/callback_test.py", "new_path": "tests/callback_test.py", "diff": "-# Copyright 2018 Google LLC\n+# 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" } ]
Python
Apache License 2.0
google/jax
Fixed copyright, added type annotations, disabled mypy on one line.
260,700
09.04.2020 10:27:01
14,400
8a65e9da6038a3cc269598a5cf4eb9b4670316f7
call jet and manually propagate through exp
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -241,17 +241,16 @@ jet_rules[lax.expm1_p] = _expm1_taylor\ndef _pow_taylor(primals_in, series_in):\nu_, r_ = primals_in\n- u_terms, r_terms = series_in\n- u = [u_] + u_terms\n- r = [r_] + r_terms\n- logu_, logu_terms = _log_taylor((u_, ), (u_terms, ))\n+ x, series = jet(lambda x, y: lax.mul(y, lax.log(x)), primals_in, series_in)\n- v_, v_terms = _bilinear_taylor_rule(lax.mul_p, (logu_, r_), (logu_terms, r_terms))\n-\n- v_, v_terms = _exp_taylor((v_, ), (v_terms, ))\n+ u = [x] + series\n+ v = [u_ ** r_] + [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 v_, v_terms\n+ return primal_out, series_out\njet_rules[lax.pow_p] = _pow_taylor\n" } ]
Python
Apache License 2.0
google/jax
call jet and manually propagate through exp Co-authored-by: Stephan Hoyer <shoyer@google.com>
260,700
09.04.2020 11:16:00
14,400
8503656ea87eb990d3a7428203e6a703ce59e0a3
add finite test, add sep lims for binary_check
[ { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -56,6 +56,32 @@ class JetTest(jtu.JaxTestCase):\ncheck_dtypes=True):\ny, terms = jet(fun, primals, series)\nexpected_y, expected_terms = jvp_taylor(fun, primals, series)\n+\n+ self.assertAllClose(y, expected_y, atol=atol, rtol=rtol,\n+ check_dtypes=check_dtypes)\n+\n+ # TODO(duvenaud): Lower zero_series to actual zeros automatically.\n+ if terms == zero_series:\n+ terms = tree_map(np.zeros_like, expected_terms)\n+\n+ self.assertAllClose(terms, expected_terms, atol=atol, rtol=rtol,\n+ check_dtypes=check_dtypes)\n+\n+ def check_jet_finite(self, fun, primals, series, atol=1e-5, rtol=1e-5,\n+ check_dtypes=True):\n+\n+ y, terms = jet(fun, primals, series)\n+ expected_y, expected_terms = jvp_taylor(fun, primals, series)\n+\n+ def _convert(x):\n+ return np.where(np.isfinite(x), x, np.nan)\n+\n+ y = _convert(y)\n+ expected_y = _convert(expected_y)\n+\n+ terms = _convert(np.asarray(terms))\n+ expected_terms = _convert(np.asarray(expected_terms))\n+\nself.assertAllClose(y, expected_y, atol=atol, rtol=rtol,\ncheck_dtypes=check_dtypes)\n@@ -111,14 +137,21 @@ class JetTest(jtu.JaxTestCase):\nterms_in = [rng.randn(*dims) 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):\n+ def binary_check(self, fun, lims=[-2, 2], order=3, finite=True):\ndims = 2, 3\nrng = onp.random.RandomState(0)\n- primal_in = (transform(lims, rng.rand(*dims)),\n- transform(lims, rng.rand(*dims)))\n+ if isinstance(lims, tuple):\n+ x_lims, y_lims = lims\n+ else:\n+ x_lims, y_lims = lims, lims\n+ primal_in = (transform(x_lims, rng.rand(*dims)),\n+ transform(y_lims, rng.rand(*dims)))\nseries_in = ([rng.randn(*dims) for _ in range(order)],\n[rng.randn(*dims) for _ in range(order)])\n+ if finite:\nself.check_jet(fun, primal_in, series_in, atol=1e-4, rtol=1e-4)\n+ else:\n+ self.check_jet_finite(fun, primal_in, series_in, atol=1e-4, rtol=1e-4)\n@jtu.skip_on_devices(\"tpu\")\ndef test_exp(self): self.unary_check(np.exp)\n@@ -182,7 +215,7 @@ class JetTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_xor(self): self.binary_check(lambda x, y: np.logical_xor(x, y))\n@jtu.skip_on_devices(\"tpu\")\n- def test_pow2(self): self.binary_check(lambda x, y: x ** y, lims=[0.2, 15])\n+ def test_pow(self): self.binary_check(lambda x, y: x ** y, lims=([0.2, 500], [-500, 500]), finite=False)\ndef test_process_call(self):\ndef f(x):\n" } ]
Python
Apache License 2.0
google/jax
add finite test, add sep lims for binary_check
260,335
10.04.2020 11:41:35
25,200
61abdc1e108002918ecdb075e9a7a071c43f97fa
add missing instantiate_zeros in custom_jvp fixes
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -294,7 +294,8 @@ 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- outs = core.jaxpr_as_fun(jvp_jaxpr)(*(primals + tangents))\n+ tangents = map(ad.instantiate_zeros, primals, tangents)\n+ outs = 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" } ]
Python
Apache License 2.0
google/jax
add missing instantiate_zeros in custom_jvp fixes #2657
260,380
10.04.2020 20:30:01
-3,600
656c3a95041884e612173d683a7f5c7226421848
fix a typo in docs notebook
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/How_JAX_primitives_work.ipynb", "new_path": "docs/notebooks/How_JAX_primitives_work.ipynb", "diff": "\"\\n\",\n\" This function does not need to be JAX traceable.\\n\",\n\" Args:\\n\",\n- \" x, y, z: the concrete arguments of the primitive. Will only be caled with \\n\",\n+ \" x, y, z: the concrete arguments of the primitive. Will only be called with \\n\",\n\" concrete values.\\n\",\n\" Returns:\\n\",\n\" the concrete result of the primitive.\\n\",\n" } ]
Python
Apache License 2.0
google/jax
fix a typo in docs notebook (#2672)
260,411
11.04.2020 12:09:05
-7,200
ee2cd44918d28ace85fce627370120d6cc7fb688
Added missing import warnings Also fixed a couple of unnecessary f-strings (Cider was flagging them)
[ { "change_type": "MODIFY", "old_path": "jax/scipy/signal.py", "new_path": "jax/scipy/signal.py", "diff": "# limitations under the License.\nimport scipy.signal as osp_signal\n+import warnings\nfrom .. import lax\nfrom ..numpy import lax_numpy as jnp\n@@ -60,7 +61,7 @@ def convolve(in1, in2, mode='full', method='auto'):\nif jnp.issubdtype(in1.dtype, jnp.complexfloating) or jnp.issubdtype(in2.dtype, jnp.complexfloating):\nraise NotImplementedError(\"convolve() does not support complex inputs\")\nif jnp.ndim(in1) != 1 or jnp.ndim(in2) != 1:\n- raise ValueError(f\"convolve() only supports 1-dimensional inputs.\")\n+ raise ValueError(\"convolve() only supports 1-dimensional inputs.\")\nreturn _convolve_nd(in1, in2, mode)\n@@ -71,7 +72,7 @@ def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0):\nif jnp.issubdtype(in1.dtype, jnp.complexfloating) or jnp.issubdtype(in2.dtype, jnp.complexfloating):\nraise NotImplementedError(\"convolve2d() does not support complex inputs\")\nif jnp.ndim(in1) != 2 or jnp.ndim(in2) != 2:\n- raise ValueError(f\"convolve2d() only supports 2-dimensional inputs.\")\n+ raise ValueError(\"convolve2d() only supports 2-dimensional inputs.\")\nreturn _convolve_nd(in1, in2, mode)\n" } ]
Python
Apache License 2.0
google/jax
Added missing import warnings Also fixed a couple of unnecessary f-strings (Cider was flagging them)