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
30.04.2022 21:50:18
25,200
83a8dc4e7f69f09c19f9afe9755ca647f566393c
[new-remat] add _scan_partial_eval_custom rule for new remat Also enable scan-of-remat tests which weren't passing before.
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_checkpoint.py", "new_path": "jax/_src/ad_checkpoint.py", "diff": "@@ -388,6 +388,22 @@ def remat_vmap(axis_size, axis_name, main_type, args, dims, *, jaxpr, **params):\nreturn remat_p.bind(*consts, *args, jaxpr=jaxpr_batched, **params), out_dims\nbatching.axis_primitive_batchers[remat_p] = remat_vmap\n+# TODO(mattjj,sharadmv): test this more\n+# TODO(mattjj,sharadmv): de-duplicate with pe.dce_jaxpr_call_rule\n+def remat_dce(used_outputs: List[bool], eqn: core.JaxprEqn\n+ ) -> Tuple[List[bool], Optional[core.JaxprEqn]]:\n+ new_jaxpr, used_inputs = pe.dce_jaxpr(eqn.params['jaxpr'], used_outputs)\n+ new_params = dict(eqn.params, jaxpr=new_jaxpr)\n+ if not any(used_inputs) and not any(used_outputs) and not new_jaxpr.effects:\n+ return used_inputs, None\n+ else:\n+ new_eqn = pe.new_jaxpr_eqn(\n+ [v for v, used in zip(eqn.invars, used_inputs) if used],\n+ [v for v, used in zip(eqn.outvars, used_outputs) if used],\n+ eqn.primitive, new_params, new_jaxpr.effects, eqn.source_info)\n+ return used_inputs, new_eqn\n+pe.dce_rules[remat_p] = remat_dce\n+\ndef checkpoint_name(x, name):\nreturn name_p.bind(x, name=name)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/loops.py", "new_path": "jax/_src/lax/control_flow/loops.py", "diff": "@@ -46,6 +46,7 @@ from jax._src.traceback_util import api_boundary\nfrom jax._src.util import (\ncache,\nextend_name_stack,\n+ partition_list,\nsafe_map,\nsafe_zip,\nsplit_list,\n@@ -829,6 +830,107 @@ def _scan_dce_rule(used_outputs: List[bool], eqn: core.JaxprEqn\nassert len(new_eqn.outvars) == len(new_params['jaxpr'].out_avals)\nreturn used_inputs, new_eqn\n+# TODO(mattjj): de-duplicate code with _scan_partial_eval\n+def _scan_partial_eval_custom(saveable, unks_in, inst_in, eqn):\n+ jaxpr = eqn.params['jaxpr']\n+ num_consts, num_carry = eqn.params['num_consts'], eqn.params['num_carry']\n+ num_ys = len(jaxpr.out_avals) - num_carry\n+\n+ # Fixpoint (currently trivial on 'inst_in')\n+ const_uk, carry_uk, xs_uk = split_list(unks_in, [num_consts, num_carry])\n+ for _ in range(1 + len(carry_uk)):\n+ unks_in = const_uk + carry_uk + xs_uk\n+ jaxpr_known_, jaxpr_staged_, unks_out, inst_out, num_res = \\\n+ pe.partial_eval_jaxpr_custom(\n+ jaxpr.jaxpr, in_unknowns=unks_in, in_inst=[True] * len(unks_in),\n+ ensure_out_unknowns=carry_uk + [False] * num_ys,\n+ ensure_out_inst=True, saveable=saveable)\n+ carry_uk_out , ys_uk = split_list(unks_out, [num_carry])\n+ if carry_uk_out == carry_uk:\n+ break\n+ else:\n+ carry_uk = _map(operator.or_, carry_uk , carry_uk_out )\n+ else:\n+ assert False, \"Fixpoint not reached\"\n+ jaxpr_known = core.ClosedJaxpr(jaxpr_known_ , jaxpr.consts)\n+ jaxpr_staged = core.ClosedJaxpr(jaxpr_staged_, jaxpr.consts)\n+\n+ # Ensure residuals are all moved to the back.\n+ # TODO(mattjj): make jaxpr_staged only take instantiated inputs\n+ res_avals = jaxpr_staged.in_avals[:num_res]\n+ jaxpr_staged = pe.move_binders_to_back(\n+ jaxpr_staged, [True] * num_res + [False] * len(jaxpr.in_avals))\n+\n+ # Instantiate all inputs (b/c jaxpr_staged takes all inputs).\n+ new_inst = [x for x, inst in zip(eqn.invars, inst_in)\n+ if type(x) is core.Var and not inst]\n+ inst_in = [True] * len(inst_in)\n+\n+ # As an optimization, hoist loop-invariant residuals out of the loop rather\n+ # than using extensive outputs for them. See _scan_partial_eval for comments.\n+ num_const_known = len(const_uk) - sum(const_uk)\n+ num_carry_known = len(carry_uk) - sum(carry_uk)\n+ num_xs_known = len( xs_uk) - sum( xs_uk)\n+ jaxpr_known_hoist, jaxpr_known_loop, loop_dep, _ = \\\n+ pe.partial_eval_jaxpr_nounits(\n+ jaxpr_known,\n+ [False] * num_const_known + [True] * (num_carry_known + num_xs_known),\n+ [True] * (len(unks_out) - sum(unks_out)) + [False] * num_res)\n+ # jaxpr_known_hoist produces intensive residuals followed by the constants for\n+ # jaxpr_known_loop. We adjust jaxpr_staged to accept intensive res as consts.\n+ _, loop_dep_res = split_list(loop_dep, [len(loop_dep) - num_res])\n+ jaxpr_staged = pe.move_binders_to_front(\n+ jaxpr_staged, [False] * sum(inst_in) + _map(operator.not_, loop_dep_res))\n+ num_intensive_res = len(loop_dep_res) - sum(loop_dep_res)\n+ del loop_dep, num_carry_known, num_xs_known\n+\n+ # Create residual variables.\n+ intensive_avals, ext_avals_mapped = partition_list(loop_dep_res, res_avals)\n+ ext_avals = [core.unmapped_aval(eqn.params['length'], core.no_axis_name, 0, a)\n+ for a in ext_avals_mapped]\n+ newvar = core.gensym()\n+ intensive_res = _map(newvar, intensive_avals)\n+ extensive_res = _map(newvar, ext_avals)\n+\n+ # Create known eqn, which is a call_p combining evaluation of\n+ # jaxpr_known_hoist and a scan of jaxpr_known_loop.\n+ ins_known, _ = partition_list(unks_in, eqn.invars)\n+ out_binders_known, _ = partition_list(unks_out, eqn.outvars)\n+ linear_known = [l for l, uk in zip(eqn.params['linear'], unks_in) if not uk]\n+ params_known = dict(eqn.params, jaxpr=jaxpr_known_loop,\n+ num_consts=len(const_uk)-sum(const_uk),\n+ num_carry=len(carry_uk)-sum(carry_uk),\n+ linear=tuple(linear_known))\n+\n+ @lu.wrap_init\n+ def known(*ins_known):\n+ consts_known_hoist, ins_known_lp = split_list(ins_known, [num_const_known])\n+ out_hoist = core.jaxpr_as_fun(jaxpr_known_hoist)(*consts_known_hoist)\n+ intensive_res, consts_known_lp = split_list(out_hoist, [num_intensive_res])\n+ out_loop = scan_p.bind(*consts_known_lp, *ins_known_lp, **params_known)\n+ return [*intensive_res, *out_loop]\n+ call_jaxpr_, _, call_jaxpr_consts = pe.trace_to_jaxpr_dynamic(\n+ known, [v.aval for v in ins_known])\n+ call_jaxpr = core.ClosedJaxpr(call_jaxpr_, call_jaxpr_consts)\n+ eqn_known = pe.new_jaxpr_eqn(\n+ ins_known, [*intensive_res, *out_binders_known, *extensive_res],\n+ core.closed_call_p, dict(call_jaxpr=call_jaxpr), call_jaxpr.effects,\n+ eqn.source_info)\n+\n+ _, out_binders_staged = partition_list(inst_out, eqn.outvars)\n+ linear_staged = ([False] * len(intensive_res) + list(eqn.params['linear']) +\n+ [False] * len(extensive_res))\n+ params_staged = dict(eqn.params, jaxpr=jaxpr_staged,\n+ num_consts=len(intensive_res) + eqn.params['num_consts'],\n+ linear=tuple(linear_staged))\n+ eqn_staged = pe.new_jaxpr_eqn([*intensive_res, *eqn.invars, *extensive_res],\n+ out_binders_staged, eqn.primitive,\n+ params_staged, jaxpr_staged.effects,\n+ eqn.source_info)\n+\n+ new_vars = [*new_inst, *intensive_res, *extensive_res]\n+ return eqn_known, eqn_staged, unks_out, inst_out, new_vars\n+\ndef _scan_typecheck(bind_time, *in_atoms, reverse, length, num_consts, num_carry,\njaxpr, linear, unroll):\navals = [x.aval for x in in_atoms]\n@@ -899,8 +1001,7 @@ mlir.register_lowering(scan_p,\nbatching.axis_primitive_batchers[scan_p] = _scan_batching_rule\nmasking.masking_rules[scan_p] = _scan_masking_rule\ncore.custom_typechecks[scan_p] = partial(_scan_typecheck, False)\n-pe.partial_eval_jaxpr_custom_rules[scan_p] = \\\n- partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'scan')\n+pe.partial_eval_jaxpr_custom_rules[scan_p] = _scan_partial_eval_custom\npe.padding_rules[scan_p] = _scan_padding_rule\npe.dce_rules[scan_p] = _scan_dce_rule\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -589,7 +589,11 @@ def traceable(num_primals, in_tree_def, *primals_and_tangents):\ndef call_transpose(primitive, params, call_jaxpr, args, ct, _, reduce_axes):\n- all_args, in_tree_def = tree_flatten(((), args, ct)) # empty consts\n+ if isinstance(call_jaxpr, core.ClosedJaxpr):\n+ call_jaxpr, consts = call_jaxpr.jaxpr, call_jaxpr.consts\n+ else:\n+ consts = ()\n+ all_args, in_tree_def = tree_flatten((consts, args, ct))\nfun = lu.hashable_partial(lu.wrap_init(backward_pass), call_jaxpr,\nreduce_axes, False)\nfun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -997,7 +997,6 @@ def lower_fun(fun: Callable, multiple_results: bool = True) -> Callable:\nreturn f_lowered\n-\ndef _call_lowering(fn_name, stack_name, call_jaxpr, backend, ctx, avals_in,\navals_out, tokens_in, *args):\nif isinstance(call_jaxpr, core.Jaxpr):\n@@ -1041,6 +1040,9 @@ register_lowering(core.call_p, partial(_named_call_lowering, name=\"core_call\"))\nregister_lowering(core.closed_call_p,\npartial(_named_call_lowering, name=\"core_closed_call\"))\n+register_lowering(core.closed_call_p,\n+ partial(_named_call_lowering, name=\"core_closed_call\"))\n+\ndef full_like_aval(value, aval: core.ShapedArray) -> ir.Value:\n\"\"\"Returns an IR constant shaped full of `value` shaped like `aval`.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -915,7 +915,7 @@ def _partial_eval_jaxpr_nounits(jaxpr, in_unknowns, instantiate):\nassert ([v.aval.strip_weak_type() for v in jaxpr_known.outvars] ==\n[a.strip_weak_type() for a, uk in zip(jaxpr.out_avals, out_unknowns)\nif not uk] + [a.strip_weak_type() for a in res_avals])\n- # check jaxpr_unknown has input type corresponding to unknown inputs plus res\n+ # check jaxpr_unknown has input type corresponding to res plus unknown inputs\nassert ([v.aval for v in jaxpr_unknown.invars] ==\nres_avals + [a for a, uk in zip(jaxpr.in_avals, in_unknowns) if uk])\n# check jaxpr_unknown has output type corresponding to unknown outputs\n@@ -1092,6 +1092,7 @@ def _partial_eval_jaxpr_custom_cached(\nknown_eqns, staged_eqns = [], []\nmap(write, in_unknowns, in_inst, jaxpr.invars)\n+ map(partial(write, False, True), jaxpr.constvars)\nfor eqn in jaxpr.eqns:\nunks_in, inst_in = unzip2(map(read, eqn.invars))\nrule = partial_eval_jaxpr_custom_rules.get(eqn.primitive)\n@@ -1277,12 +1278,15 @@ dce_rules: Dict[Primitive, DCERule] = {}\ndef dce_jaxpr_call_rule(used_outputs: List[bool], eqn: JaxprEqn\n- ) -> Tuple[List[bool], JaxprEqn]:\n+ ) -> Tuple[List[bool], Optional[JaxprEqn]]:\nnew_jaxpr, used_inputs = dce_jaxpr(eqn.params['call_jaxpr'], used_outputs)\nnew_params = dict(eqn.params, call_jaxpr=new_jaxpr)\nupdate_params = call_param_updaters.get(eqn.primitive)\nif update_params:\nnew_params = update_params(new_params, used_inputs, 0)\n+ if not any(used_inputs) and not any(used_outputs) and not new_jaxpr.effects:\n+ return used_inputs, None\n+ else:\nnew_eqn = new_jaxpr_eqn(\n[v for v, used in zip(eqn.invars, used_inputs) if used],\n[v for v, used in zip(eqn.outvars, used_outputs) if used],\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3895,7 +3895,13 @@ class RematTest(jtu.JaxTestCase):\nexpected = api.grad(api.grad(f))(3.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- def test_remat_scan(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', api.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_remat_scan(self, remat):\nto_scan = lambda c, x: (jnp.sin(c), None)\ndef f_noremat(x):\n@@ -3903,7 +3909,7 @@ class RematTest(jtu.JaxTestCase):\nreturn y\ndef f_yesremat(x):\n- y, _ = lax.scan(api.remat(to_scan), x, np.arange(3.))\n+ y, _ = lax.scan(remat(to_scan), x, np.arange(3.))\nreturn y\nans = f_yesremat(4.)\n@@ -3973,7 +3979,13 @@ class RematTest(jtu.JaxTestCase):\nself.assertAllClose(f1(x), f2(x), check_dtypes=False)\nself.assertAllClose(api.grad(f1)(x), api.grad(f2)(x), check_dtypes=False)\n- def test_remat_symbolic_zeros(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', api.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_remat_symbolic_zeros(self, remat):\n# code from https://github.com/google/jax/issues/1907\nkey = jax.random.PRNGKey(0)\n@@ -3994,7 +4006,7 @@ class RematTest(jtu.JaxTestCase):\nF = apply_fn(R)\nreturn shift(R, 0.001 * F), jnp.array([0.])\n- move = api.remat(move)\n+ move = remat(move)\nR, temp = lax.scan(move, Rinit, jnp.arange(2))\nreturn R[0, 0]\n@@ -4020,10 +4032,16 @@ class RematTest(jtu.JaxTestCase):\nself.assertAllClose(f(3), 6, check_dtypes=False)\n- def test_remat_nontrivial_env(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', api.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_remat_nontrivial_env(self, remat):\n# simplified from https://github.com/google/jax/issues/2030\n- @api.remat\n+ @remat\ndef foo(state, dt=0.5, c=1):\nu, u_t = state\nu_tt = c**2 * u\n@@ -4081,14 +4099,20 @@ class RematTest(jtu.JaxTestCase):\nf = remat(f)\napi.grad(f)(w, x) # doesn't crash\n- def test_remat_scan2(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', api.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_remat_scan2(self, remat):\n# https://github.com/google/jax/issues/1963\ndef scan_bug(x0):\nf = lambda x, _: (x + 1, None)\ndef scanned_f(x, _):\nreturn lax.scan(f, x, xs=None, length=1)[0], None\n- x, _ = jax.remat(scanned_f)(x0, None)\n+ x, _ = remat(scanned_f)(x0, None)\nreturn x\njax.grad(scan_bug)(1.0) # doesn't crash\n@@ -4219,8 +4243,14 @@ class RematTest(jtu.JaxTestCase):\nself.assertTrue('while' in text or 'conditional' in text\nor 'opt-barrier' in text)\n- def test_no_cse_widget_with_prevent_cse_false(self):\n- @partial(api.remat, prevent_cse=False)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', api.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_no_cse_widget_with_prevent_cse_false(self, remat):\n+ @partial(remat, prevent_cse=False)\ndef g(x):\nreturn lax.sin(lax.sin(x)), 3.\n@@ -4635,15 +4665,202 @@ class RematTest(jtu.JaxTestCase):\nf_vjp(1.)[0].block_until_ready()\nself.assertEqual(count[0], 1) # fwd execute_trivial, backward_pass on bwd\n- def test_remat_of_scan(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', api.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_remat_of_scan(self, remat):\nto_scan = lambda c, _: (jnp.sin(c), jnp.sin(c))\nf = lambda x: lax.scan(to_scan, x, None, length=3)\n- jtu.check_grads(jax.remat(f), (3.,), order=2, modes=['rev'])\n+ jtu.check_grads(remat(f), (3.,), order=2, modes=['rev'])\n- jaxpr = api.make_jaxpr(api.linearize(jax.remat(f), 4.)[1])(1.)\n+ jaxpr = api.make_jaxpr(api.linearize(remat(f), 4.)[1])(1.)\nself.assertIn(' sin ', str(jaxpr))\nself.assertIn(' cos ', str(jaxpr))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', api.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_const_in_jvp(self, remat):\n+ @api.custom_jvp\n+ def f(x):\n+ return x * np.arange(3.)\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ (x,), (xdot,) = primals, tangents\n+ return f(x), xdot * np.arange(3.)\n+\n+ @remat\n+ def g(x):\n+ def body(c, _):\n+ return f(c), None\n+ y, _ = jax.lax.scan(body, x, None, length=1)\n+ return y.sum()\n+\n+ jax.grad(g)(jnp.arange(3.)) # doesn't crash\n+\n+ def test_remat_checkpoint_dots_outside_scan(self):\n+ # see also above test test_remat_checkpoint_dots_inside_scan\n+ x = jnp.ones((5,))\n+\n+ @partial(new_checkpoint, policy=jax.checkpoint_policies.checkpoint_dots)\n+ def f(W):\n+ def f(x):\n+ x = jnp.sin(jnp.dot(x, W, precision=lax.Precision.HIGHEST))\n+ x = jnp.sin(jnp.dot(x, W, precision=lax.Precision.HIGHEST))\n+ x = jnp.sin(jnp.dot(x, W, precision=lax.Precision.HIGHEST))\n+ return x\n+\n+ def body(x, _): return f(x), None\n+ return lax.scan(body, x, None, length=2)[0]\n+\n+ _, f_vjp = api.vjp(f, jnp.ones((5, 5)))\n+ jaxpr = f_vjp.args[0].func.args[1]\n+ jaxpr_text = str(jaxpr)\n+\n+ self.assertEqual(jaxpr_text.count(' sin '), 3)\n+ self.assertEqual(jaxpr_text.count(' cos '), 3)\n+ # Six calls to dot_general in the backward pass because we save the primal\n+ # matmuls and only compure the backward pass ones (two for each primal one).\n+ self.assertEqual(jaxpr_text.count(' dot_'), 6)\n+\n+ jtu.check_grads(api.jit(f), (jnp.ones((5, 5)),), order=2,\n+ modes=['fwd', 'rev'])\n+\n+ @unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\n+ def test_remat_of_scan_policy(self):\n+ save_cos = lambda prim, *_, **__: str(prim) == 'cos'\n+ to_scan = lambda c, _: (jnp.sin(c), jnp.sin(c))\n+ f = new_checkpoint(lambda x: lax.scan(to_scan, x, None, length=3),\n+ policy=save_cos)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 0)\n+ self.assertEqual(jaxpr_text.count(' cos '), 0)\n+\n+ @unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\n+ def test_remat_of_scan_funky_custom_jvp(self):\n+ def scan_apply(f, x):\n+ y, _ = lax.scan(lambda x, _: (f(x), None), x, None, length=1)\n+ return y\n+\n+ @api.custom_jvp\n+ def sin(x):\n+ return jnp.sin(x)\n+ def sin_jvp(primals, tangents):\n+ x, = primals\n+ xdot, = tangents\n+ y, c = jax.jit(lambda: (jnp.sin(x), jnp.cos(x)))()\n+ ydot = c * xdot\n+ return y, ydot\n+ sin.defjvp(sin_jvp)\n+\n+ save_cos = lambda prim, *_, **__: str(prim) == 'cos'\n+ f = new_checkpoint(partial(scan_apply, sin), policy=save_cos)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 0)\n+ self.assertEqual(jaxpr_text.count(' cos '), 0)\n+\n+ save_sin = lambda prim, *_, **__: str(prim) == 'sin'\n+ f = new_checkpoint(partial(scan_apply, sin), policy=save_sin)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 0)\n+ self.assertEqual(jaxpr_text.count(' cos '), 1)\n+\n+ f = new_checkpoint(partial(scan_apply, sin),\n+ policy=jax.checkpoint_policies.everything_saveable)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 0)\n+ self.assertEqual(jaxpr_text.count(' cos '), 0)\n+\n+ f = new_checkpoint(partial(scan_apply, sin),\n+ policy=jax.checkpoint_policies.nothing_saveable)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 1) # +1 b/c dce fixed point\n+ self.assertEqual(jaxpr_text.count(' cos '), 1)\n+\n+ f = new_checkpoint(lambda x: scan_apply(sin, scan_apply(sin, x)),\n+ policy=jax.checkpoint_policies.nothing_saveable)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 2) # +1 b/c dce fixed point\n+ self.assertEqual(jaxpr_text.count(' cos '), 2)\n+\n+ @unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\n+ def test_remat_of_scan_funky_custom_jvp2(self):\n+ # Like the above test but instead of using jit inside custom_jvp, use scan.\n+\n+ def scan_apply(f, x):\n+ y, _ = lax.scan(lambda x, _: (f(x), None), x, None, length=1)\n+ return y\n+\n+ @api.custom_jvp\n+ def sin(x):\n+ return jnp.sin(x)\n+ def sin_jvp(primals, tangents):\n+ x, = primals\n+ xdot, = tangents\n+ y, c = scan_apply(lambda xs: (jnp.sin(xs[0]), jnp.cos(xs[1])), (x, x))\n+ ydot = c * xdot\n+ return y, ydot\n+ sin.defjvp(sin_jvp)\n+\n+ save_cos = lambda prim, *_, **__: str(prim) == 'cos'\n+ f = new_checkpoint(partial(scan_apply, sin), policy=save_cos)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 1) # +1 b/c dce fixed point\n+ self.assertEqual(jaxpr_text.count(' cos '), 0)\n+\n+ save_sin = lambda prim, *_, **__: str(prim) == 'sin'\n+ f = new_checkpoint(partial(scan_apply, sin), policy=save_sin)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 0)\n+ self.assertEqual(jaxpr_text.count(' cos '), 1)\n+\n+ f = new_checkpoint(partial(scan_apply, sin),\n+ policy=jax.checkpoint_policies.everything_saveable)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 0)\n+ self.assertEqual(jaxpr_text.count(' cos '), 0)\n+\n+ f = new_checkpoint(partial(scan_apply, sin),\n+ policy=jax.checkpoint_policies.nothing_saveable)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 1) # +1 b/c dce fixed point\n+ self.assertEqual(jaxpr_text.count(' cos '), 1)\n+\n+ f = new_checkpoint(lambda x: scan_apply(sin, scan_apply(sin, x)),\n+ policy=jax.checkpoint_policies.nothing_saveable)\n+ jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n+ jaxpr = api.make_jaxpr(api.linearize(f, 4.)[1])(1.)\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 2) # +1 b/c dce fixed point\n+ self.assertEqual(jaxpr_text.count(' cos '), 2)\n+\nclass JaxprTest(jtu.JaxTestCase):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -36,6 +36,7 @@ from jax import tree_util\nfrom jax._src.util import unzip2\nfrom jax.experimental import maps\nfrom jax.interpreters import partial_eval as pe\n+from jax.ad_checkpoint import checkpoint as new_checkpoint, checkpoint_policies\nimport jax.numpy as jnp # scan tests use numpy\nimport jax.scipy as jsp\nfrom jax._src.lax.control_flow import for_loop\n@@ -59,6 +60,17 @@ def cond_via_switch(pred, true_fun, false_fun, op, *args):\nreturn lax.switch(index, [false_fun, true_fun], op)\n+# We wanted to try all scan tests with the scan partial evaluation rule that\n+# happens under ad_checkpoint.checkpoint, so we make a scan wrapper which\n+# wraps a ad_checkpoint.checkpoint around the computation.\n+def scan_with_new_checkpoint(f, *args, **kwargs):\n+ return new_checkpoint(partial(lax.scan, f, **kwargs),\n+ policy=checkpoint_policies.nothing_saveable)(*args)\n+def scan_with_new_checkpoint2(f, *args, **kwargs):\n+ return new_checkpoint(partial(lax.scan, f, **kwargs),\n+ policy=checkpoint_policies.everything_saveable)(*args)\n+\n+\nCOND_IMPLS = [\n(lax.cond, 'cond'),\n(cond_via_switch, 'switch'),\n@@ -68,6 +80,8 @@ COND_IMPLS = [\nSCAN_IMPLS = [\n(lax.scan, 'unroll1'),\n(partial(lax.scan, unroll=2), 'unroll2'),\n+ (scan_with_new_checkpoint , 'new_checkpoint'),\n+ (scan_with_new_checkpoint2, 'new_checkpoint2'),\n]\n@@ -1534,10 +1548,14 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nas_ = rng.randn(5, 3)\nc = rng.randn(4)\n+ if scan is scan_with_new_checkpoint2:\n+ rtol = {np.float64: 1e-12, np.float32: 1e-4}\n+ else:\n+ rtol = {np.float64: 1e-14, np.float32: 1e-4}\n+\nans = jax.linearize(lambda c, as_: scan(f, c, as_), c, as_)[1](c, as_)\nexpected = jax.linearize(lambda c, as_: scan_reference(f, c, as_), c, as_)[1](c, as_)\n- self.assertAllClose(ans, expected, check_dtypes=False,\n- rtol={np.float64: 1e-14, np.float32: 1e-4})\n+ self.assertAllClose(ans, expected, check_dtypes=False, rtol=rtol)\n@parameterized.named_parameters(\n{\"testcase_name\": \"_jit_scan={}_jit_f={}_impl={}\".format(\n@@ -1569,11 +1587,15 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nans = jax.grad(lambda c, as_: list( scan(f, c, as_))[0].sum())(c, as_)\nexpected = jax.grad(lambda c, as_: list(scan_reference(f, c, as_))[0].sum())(c, as_)\n- self.assertAllClose(ans, expected, check_dtypes=False,\n- rtol={np.float32: 2e-5, np.float64: 1e-13})\n+ if scan is scan_with_new_checkpoint:\n+ rtol = {np.float32: 5e-5, np.float64: 1e-13}\n+ else:\n+ rtol = {np.float32: 2e-5, np.float64: 1e-13}\n+ self.assertAllClose(ans, expected, check_dtypes=False, rtol=rtol)\n+ rtol = 5e-3 if scan is not scan_with_new_checkpoint2 else 5e-2\njtu.check_grads(partial(scan, f), (c, as_), order=2, modes=[\"rev\"],\n- atol=1e-3, rtol=5e-3)\n+ atol=1e-3, rtol=rtol)\n@jtu.skip_on_devices(\"tpu\") # TPU lacks precision for this test.\n@jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n@@ -1642,7 +1664,10 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nbatched_inputs, batched_targets)))\nself.assertAllClose(losses, expected, check_dtypes=False, rtol=1e-2)\n- def testIssue711(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_impl={}\".format(scan_name), \"scan\": scan_impl}\n+ for scan_impl, scan_name in SCAN_IMPLS)\n+ def testIssue711(self, scan):\n# Tests reverse-mode differentiation through a scan for which the scanned\n# function also involves reverse-mode differentiation.\n# See https://github.com/google/jax/issues/711\n@@ -1659,7 +1684,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nreturn new_carry, _\nx0 = jnp.array([1., 2., 3.])\n- carry_final, _ = lax.scan(apply_carry, (0, x0), jnp.zeros((75, 0)))\n+ carry_final, _ = scan(apply_carry, (0, x0), jnp.zeros((75, 0)))\n_, x_final = carry_final\nreturn x_final\n@@ -1799,13 +1824,16 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nans = jax.vmap(lambda c, as_: lax.scan(f, c, as_), in_axes)(c, as_)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- def testScanVmapFixpoint(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_impl={}\".format(scan_name), \"scan\": scan_impl}\n+ for scan_impl, scan_name in SCAN_IMPLS)\n+ def testScanVmapFixpoint(self, scan):\ndef f(carry_init):\ndef scan_body(c, x):\n# The carry is a 4-tuple, the last element starts batched,\n# and the carry is shifted left at each iteration.\nreturn ((c[1], c[2], c[3], 0.), None)\n- return lax.scan(scan_body, (0., 1., 2., carry_init), jnp.zeros(2))\n+ return scan(scan_body, (0., 1., 2., carry_init), jnp.zeros(2))\ncarry_init = jnp.array([3., 4., 5.])\ncarry_out, _ = jax.vmap(f)(carry_init)\nself.assertAllClose(carry_out[3], jnp.array([0., 0., 0.]), check_dtypes=False)\n@@ -2338,21 +2366,33 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nresult = lax.while_loop(cond_fun, body_fun, init_weak)\nself.assertArraysEqual(result, jnp.full_like(increment, 2))\n- def test_scan_vjp_forwards_extensive_residuals(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', None),\n+ ('new_remat', new_checkpoint),\n+ ])\n+ def test_scan_vjp_forwards_extensive_residuals(self, remat):\n# https://github.com/google/jax/issues/4510\ndef cumprod(x):\ns = jnp.ones((2, 32), jnp.float32)\nreturn lax.scan(lambda s, x: (x*s, s), s, x)\n+ if remat is not None:\n+ cumprod = remat(cumprod)\nrng = self.rng()\nx = jnp.asarray(rng.randn(32, 2, 32).astype('float32'))\n_, vjp_fun = jax.vjp(cumprod, x)\n# Need to spelunk into vjp_fun. This is fragile, and if it causes problems\n- # just skip this test.\n+ # just skip this test and make an issue for mattjj.\n*_, ext_res = vjp_fun.args[0].args[0]\nself.assertIs(ext_res, x)\n+ if remat is not None:\n+ # TODO(mattjj): make the numpy.ndarray test pass w/ remat\n+ raise unittest.SkipTest(\"new-remat-of-scan doesn't convert numpy.ndarray\")\n+\nx = rng.randn(32, 2, 32).astype('float32') # numpy.ndarray, not DeviceArray\n_, vjp_fun = jax.vjp(cumprod, x)\n*_, ext_res = vjp_fun.args[0].args[0]\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -48,6 +48,7 @@ from jax.interpreters import pxla\nfrom jax.interpreters import xla\nfrom jax.experimental import array\nfrom jax.experimental.sharding import PmapSharding\n+from jax.ad_checkpoint import checkpoint as new_checkpoint\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -1673,7 +1674,13 @@ class PythonPmapTest(jtu.JaxTestCase):\ntol = 1e-1 if jtu.device_under_test() == \"tpu\" else 1e-3\nself.assertAllClose(result, expected, check_dtypes=False, atol=tol, rtol=tol)\n- def testAxisIndexRemat(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', jax.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def testAxisIndexRemat(self, remat):\n# https://github.com/google/jax/issues/2716\nn = len(jax.devices())\n@@ -1682,7 +1689,7 @@ class PythonPmapTest(jtu.JaxTestCase):\nreturn random.bernoulli(key, p=0.5)\nkeys = random.split(random.PRNGKey(0), n)\n- self.pmap(jax.remat(f), axis_name='i')(keys)\n+ self.pmap(remat(f), axis_name='i')(keys)\ndef testPmapMapVmapCombinations(self):\n# https://github.com/google/jax/issues/2822\n" } ]
Python
Apache License 2.0
google/jax
[new-remat] add _scan_partial_eval_custom rule for new remat Also enable scan-of-remat tests which weren't passing before. Co-authored-by: Sharad Vikram <sharadmv@google.com>
260,335
17.06.2022 15:53:53
25,200
a001c52f878824cd1c0a67c73d9d318ed30286c9
[dynamic-shapes] basic jvp working, including with broadcast
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -2660,7 +2660,10 @@ def _broadcast_in_dim_typecheck_rule(\noperand.aval.weak_type)\nreturn [out_aval], core.no_effects\n-def _broadcast_in_dim_transpose_rule(ct, operand, *, shape, broadcast_dimensions):\n+def _broadcast_in_dim_transpose_rule(ct, operand, *dyn_shape,\n+ shape, broadcast_dimensions):\n+ if dyn_shape:\n+ raise NotImplementedError(\"dynamic shape broadcast transpose not implemented\")\nshape_in = operand.aval.shape\nunit_dimensions = tuple(i for i, s in enumerate(shape_in) if core.symbolic_equal_dim(s, 1))\nbdims = tuple(np.delete(broadcast_dimensions, unit_dimensions))\n@@ -2721,9 +2724,18 @@ def _broadcast_in_dim_padding_rule(in_avals, out_avals, x, *dyn_shape,\nreturn [broadcast_in_dim_p.bind(x, *new_dyn_shape, shape=new_shape,\nbroadcast_dimensions=broadcast_dimensions)]\n+def _broadcast_in_dim_jvp_rule(primals, tangents, *, shape, broadcast_dimensions):\n+ operand, *dyn_shape = primals\n+ operand_dot, *_ = tangents\n+ y = broadcast_in_dim_p.bind(operand , *dyn_shape, shape=shape,\n+ broadcast_dimensions=broadcast_dimensions)\n+ y_dot = broadcast_in_dim_p.bind(operand_dot, *dyn_shape, shape=shape,\n+ broadcast_dimensions=broadcast_dimensions)\n+ return y, y_dot\nbroadcast_in_dim_p = standard_primitive(\n_broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')\n-ad.deflinear2(broadcast_in_dim_p, _broadcast_in_dim_transpose_rule)\n+ad.primitive_jvps[broadcast_in_dim_p] = _broadcast_in_dim_jvp_rule\n+ad.primitive_transposes[broadcast_in_dim_p] = _broadcast_in_dim_transpose_rule\nbatching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule\npe.forwarding_rules[broadcast_in_dim_p] = _broadcast_in_dim_fwd_rule\npe.custom_staging_rules[broadcast_in_dim_p] = _broadcast_in_dim_staging_rule\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1315,6 +1315,10 @@ class DShapedArray(UnshapedArray):\nelse:\nraise TypeError(self, other)\n+ def at_least_vspace(self):\n+ return DShapedArray(self.shape, primal_dtype_to_tangent_dtype(self.dtype),\n+ self.weak_type)\n+\ndel AxisSize, AxisSizeForTracing, AxisSizeForJaxprType, \\\nAxisSizeForJaxprTracingSpec\n@@ -1323,8 +1327,9 @@ class ShapedArray(UnshapedArray):\narray_abstraction_level = 1\ndef __init__(self, shape, dtype, weak_type=False, named_shape=None):\n- super().__init__(dtype, weak_type=weak_type)\nself.shape = canonicalize_shape(shape)\n+ self.dtype = np.dtype(dtype)\n+ self.weak_type = weak_type\nself.named_shape = {} if named_shape is None else dict(named_shape)\ndef update(self, shape=None, dtype=None, weak_type=None, named_shape=None):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -46,8 +46,11 @@ def _update_annotation(\n) -> lu.WrappedFun:\nif orig_type is None:\nreturn f\n- tan_types = [(aval.at_least_vspace(), keep)\n- for nz, (aval, keep) in zip(nonzeros, orig_type) if nz]\n+ # Implicit arguments never have tangents, so generate the tangent part of the\n+ # type annotation from explicit arguments only.\n+ orig_avals = [aval for aval, explicit in orig_type if explicit]\n+ tan_types = [(aval.at_least_vspace(), True)\n+ for nz, aval in zip(nonzeros, orig_avals) if nz]\nreturn lu.annotate(f, (*orig_type, *tan_types))\ndef jvp(fun: lu.WrappedFun, has_aux=False, instantiate=True,\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -8980,6 +8980,73 @@ class DynamicShapeTest(jtu.JaxTestCase):\nx = jax.jit(lambda n: jnp.ones(2 * n))(3)\nself.assertAllClose(x, jnp.ones(2 * 3))\n+ def test_jvp_broadcast(self):\n+ @jax.jit\n+ def fn(n, x):\n+ return lax.broadcast_in_dim(x, (n,), ())\n+\n+ outer_jaxpr = jax.make_jaxpr(\n+ lambda x, t: jax.jvp(lambda y: fn(3, y), (x,), (t,))\n+ )(3., 4.)\n+ # { lambda ; a:f32[] b:f32[]. let\n+ # c:f32[3] d:f32[3] = xla_call[\n+ # call_jaxpr={ lambda ; e:i32[] f:f32[] g:f32[]. let\n+ # h:f32[e] = broadcast_in_dim[broadcast_dimensions=() shape=(None,)] f e\n+ # i:f32[e] = broadcast_in_dim[broadcast_dimensions=() shape=(None,)] g e\n+ # in (h, i) }\n+ # name=f\n+ # ] 3 a b\n+ # in (c, d) }\n+ self.assertLen(outer_jaxpr.jaxpr.eqns, 1)\n+ eqn, = outer_jaxpr.jaxpr.eqns\n+ self.assertIn('call_jaxpr', eqn.params)\n+ jaxpr = eqn.params['call_jaxpr']\n+ self.assertLen(jaxpr.invars, 3)\n+ e, f, g = jaxpr.invars\n+ self.assertEqual(e.aval.shape, ())\n+ self.assertEqual(f.aval.shape, ())\n+ self.assertEqual(g.aval.shape, ())\n+ self.assertLen(jaxpr.outvars, 2)\n+ h, i = jaxpr.outvars\n+ self.assertEqual(h.aval.shape, (e,))\n+ self.assertEqual(i.aval.shape, (e,))\n+ self.assertLen(eqn.outvars, 2)\n+ c, d = eqn.outvars\n+ self.assertEqual(c.aval.shape, (3,))\n+ self.assertEqual(d.aval.shape, (3,))\n+\n+ def test_jvp_basic(self):\n+ @partial(jax.jit, abstracted_axes=('n',))\n+ def foo(x):\n+ return jnp.sin(x)\n+\n+ x = t = jnp.arange(3.)\n+ outer_jaxpr = jax.make_jaxpr(lambda x, t: jax.jvp(foo, (x,), (t,)))(x, t)\n+ # { lambda ; a:f32[3] b:f32[3]. let\n+ # c:f32[3] d:f32[3] = xla_call[\n+ # call_jaxpr={ lambda ; e:i32[] f:f32[e] g:f32[e]. let\n+ # h:f32[e] = sin f\n+ # i:f32[e] = cos f\n+ # j:f32[e] = mul g i\n+ # in (h, j) }\n+ # name=f\n+ # ] 3 a b\n+ # in (c, d) }\n+ self.assertLen(outer_jaxpr.jaxpr.eqns, 1)\n+ eqn, = outer_jaxpr.eqns\n+ self.assertIn('call_jaxpr', eqn.params)\n+ jaxpr = eqn.params['call_jaxpr']\n+ self.assertLen(jaxpr.invars, 3)\n+ e, f, g = jaxpr.invars\n+ self.assertEqual(e.aval.shape, ())\n+ self.assertEqual(f.aval.shape, (e,))\n+ self.assertEqual(g.aval.shape, (e,))\n+ self.assertLen(jaxpr.outvars, 2)\n+ self.assertLen(eqn.outvars, 2)\n+ c, d = eqn.outvars\n+ self.assertEqual(c.aval.shape, (3,))\n+ self.assertEqual(d.aval.shape, (3,))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[dynamic-shapes] basic jvp working, including with broadcast
260,411
20.06.2022 10:48:15
-7,200
4b03ebf4f5e774bad9865278f9f0f8b75948e647
Fix overflow of large prng computation Fixes:
[ { "change_type": "MODIFY", "old_path": "jax/_src/prng.py", "new_path": "jax/_src/prng.py", "diff": "@@ -542,7 +542,7 @@ def threefry_random_bits(key: jnp.ndarray, bit_width, shape):\n)\n)\n)\n- bits = lax.reshape(bits, (np.uint32(max_count * 32 // bit_width),), (1, 0))\n+ bits = lax.reshape(bits, ((max_count * 32 // bit_width),), (1, 0))\nbits = lax.convert_element_type(bits, dtype)[:size]\nreturn lax.reshape(bits, shape)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -1454,6 +1454,14 @@ class LaxRandomTest(jtu.JaxTestCase):\nself.assertGreater((r == 0).sum(), 0)\nself.assertGreater((r == 255).sum(), 0)\n+ def test_large_prng(self):\n+ # https://github.com/google/jax/issues/11010\n+ def f():\n+ return jax.random.uniform(jax.random.PRNGKey(3), (308000000, 128), dtype=jnp.bfloat16)\n+\n+ # just lower, don't run, takes too long\n+ jax.jit(f).lower()\n+\nthreefry_seed = jax._src.prng.threefry_seed\nthreefry_split = jax._src.prng.threefry_split\n" } ]
Python
Apache License 2.0
google/jax
Fix overflow of large prng computation Fixes: #11010
260,424
19.04.2022 16:08:09
-3,600
9167f7248a5551d2a03626629bf026bf1fa17675
Checkify: support discharging checks from control-flow through effects. Currently supports scan and while-loop.
[ { "change_type": "MODIFY", "old_path": "jax/_src/checkify.py", "new_path": "jax/_src/checkify.py", "diff": "@@ -25,9 +25,11 @@ import jax.numpy as jnp\nfrom jax import core\nfrom jax import linear_util as lu\nfrom jax.api_util import flatten_fun\n+from jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\nfrom jax.tree_util import tree_flatten, tree_unflatten, register_pytree_node\nfrom jax._src import source_info_util, traceback_util\n+from jax._src.lax import control_flow as cf\nfrom jax import lax\nfrom jax._src.util import (as_hashable_function, unzip2, split_list, safe_map,\nsafe_zip)\n@@ -457,14 +459,23 @@ def assert_impl(pred, code, payload, *, msgs):\nError(~pred, code, msgs, payload).throw()\nreturn []\n-@assert_p.def_abstract_eval\n+CheckEffect = object()\n+\n+@assert_p.def_effectful_abstract_eval\ndef assert_abstract_eval(pred, code, payload, *, msgs):\n- # TODO(lenamartens) add in-depth explanation to link to in module docs.\n+ return [], {CheckEffect}\n+\n+def assert_lowering_rule(*a, **k):\n+ # TODO(lenamartens): actually throw an error through emit_python_callable\n+ # TODO(lenamartens) add in-depth error explanation to link to in module docs.\nraise ValueError('Cannot abstractly evaluate a checkify.check which was not'\n' functionalized. This probably means you tried to stage'\n' (jit/scan/pmap/...) a `check` without functionalizing it'\n' through `checkify.checkify`.'\n)\n+mlir.register_lowering(assert_p, assert_lowering_rule)\n+mlir.lowerable_effects.add(CheckEffect)\n+cf.allowed_effects.add(CheckEffect)\n## checkify rules\n@@ -611,17 +622,11 @@ def checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error, enabled_errors, c_c\nreturn checkify_fun_to_jaxpr(lu.wrap_init(new_body_f), error, enabled_errors,\nbody_jaxpr.in_avals)\n-def ignore_errors_jaxpr(jaxpr, error):\n- \"\"\"Constructs a jaxpr which takes two extra args but ignores them.\"\"\"\n- err_aval = core.raise_to_shaped(core.get_aval(error.err))\n- code_aval = core.raise_to_shaped(core.get_aval(error.code))\n- payload_aval = core.raise_to_shaped(core.get_aval(error.payload))\n+def ignore_error_output_jaxpr(jaxpr):\n+ \"\"\"Constructs a checked jaxpr which does not output its error value.\"\"\"\nconsts = jaxpr.consts\njaxpr = jaxpr.jaxpr\n- new_vars = core.gensym([jaxpr])\n- new_invars = (new_vars(err_aval), new_vars(code_aval),\n- new_vars(payload_aval), *jaxpr.invars)\n- new_jaxpr = jaxpr.replace(invars=new_invars)\n+ new_jaxpr = jaxpr.replace(outvars=jaxpr.outvars[3:])\nreturn core.ClosedJaxpr(new_jaxpr, consts)\ndef while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\n@@ -629,17 +634,17 @@ def while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\nc_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\n# Check if the first cond application will error.\n- cond_jaxpr_, msgs_cond = checkify_jaxpr(cond_jaxpr, error, enabled_errors)\n- cond_err, cond_code, cond_payload, _ = core.jaxpr_as_fun(cond_jaxpr_)(\n+ checked_cond_jaxpr, msgs_cond = checkify_jaxpr(cond_jaxpr, error,\n+ enabled_errors)\n+ cond_err, cond_code, cond_payload, _ = core.jaxpr_as_fun(checked_cond_jaxpr)(\nerror.err, error.code, error.payload, *c_consts, *carry)\n- del cond_jaxpr_\nchecked_body_jaxpr_, msgs_body = checkify_while_body_jaxpr(\ncond_jaxpr, body_jaxpr, error, enabled_errors, c_consts)\nto_move = [False] * 3 + [True] * body_nconsts + [False] * len(carry)\nchecked_body_jaxpr = pe.move_binders_to_front(checked_body_jaxpr_, to_move)\n- compat_cond_jaxpr_ = ignore_errors_jaxpr(cond_jaxpr, error)\n+ compat_cond_jaxpr_ = ignore_error_output_jaxpr(checked_cond_jaxpr)\nto_move = [False] * 3 + [True] * cond_nconsts + [False] * len(carry)\ncompat_cond_jaxpr = pe.move_binders_to_front(compat_cond_jaxpr_, to_move)\nnew_in_flat = [*c_consts, *b_consts, cond_err, cond_code, cond_payload, *carry]\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -993,6 +993,7 @@ tf_not_yet_impl = [\n# Not high priority?\n\"after_all\",\n\"all_to_all\",\n+ \"assert\",\n\"create_token\",\n\"custom_transpose_call\",\n\"custom_vmap_call\",\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -24,6 +24,7 @@ from jax import lax\nimport jax._src.test_util as jtu\nfrom jax.config import config\nfrom jax.experimental import checkify\n+from jax._src.checkify import CheckEffect\nimport jax.numpy as jnp\nconfig.parse_flags_with_absl()\n@@ -628,7 +629,7 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, \"hi\"):\nf()\n- def test_assert_primitive_staging(self):\n+ def test_assert_primitive_lowering(self):\n@jax.jit\ndef f():\ncheckify.check(False, \"hi\")\n@@ -636,6 +637,19 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, \"Cannot abstractly evaluate\"):\nf()\n+ def test_assert_primitive_jaxpr_effects(self):\n+ def f():\n+ checkify.check(False, \"hi\")\n+\n+ self.assertSetEqual(jax.make_jaxpr(f)().effects, {CheckEffect})\n+\n+ def test_assert_primitive_eval_shape(self):\n+ # The check is abstractly evaluated but not lowered.\n+ def f():\n+ checkify.check(False, \"hi\")\n+\n+ jax.eval_shape(f) # does not crash.\n+\ndef test_assert_discharging(self):\n@checkify.checkify\ndef f(x):\n@@ -675,6 +689,47 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"must be positive\")\n+ def test_assert_discharging_scan(self):\n+ def body(carry, x):\n+ checkify.check(jnp.all(x > 0), \"must be positive\")\n+ return carry, x\n+\n+ def f(x):\n+ return jax.lax.scan(body, (None,), x)\n+\n+ err, _ = checkify.checkify(f)(jnp.array([-1]))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"must be positive\")\n+\n+ err, _ = checkify.checkify(f)(jnp.array([1, 0, -1]))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"must be positive\")\n+\n+ def test_assert_discharging_while_loop(self):\n+ def while_cond(val):\n+ i, _ = val\n+ checkify.check(i < 0, \"i must be negative\")\n+ return i < 2\n+\n+ def while_body(val):\n+ i, x = val\n+ checkify.check(x < 0, \"x must be negative\")\n+ return i+1., x+1\n+\n+ @jax.jit\n+ def f(init_i, init_val):\n+ return lax.while_loop(while_cond, while_body, (init_i, init_val))\n+\n+ checked_f = checkify.checkify(f)\n+\n+ err, _ = checked_f(0, 1)\n+ self.assertIsNotNone(err)\n+ self.assertStartsWith(err.get(), \"i must be negative\")\n+\n+ err, _ = checked_f(-1, 0)\n+ self.assertIsNotNone(err)\n+ self.assertStartsWith(err.get(), \"x must be negative\")\n+\ndef test_check_error(self):\ndef f():\ncheckify.check_error(checkify.Error(True, 0, {0: \"hi\"}))\n" } ]
Python
Apache License 2.0
google/jax
Checkify: support discharging checks from control-flow through effects. Currently supports scan and while-loop.
260,657
21.06.2022 11:15:14
-7,200
4e057c9f2312c6ee86af88f3121565a13b7fbb37
DOC: update pprof install instructions
[ { "change_type": "MODIFY", "old_path": "docs/device_memory_profiling.md", "new_path": "docs/device_memory_profiling.md", "diff": "@@ -13,11 +13,11 @@ pprof (<https://github.com/google/pprof>). Start by installing `pprof`,\nby following its\n[installation instructions](https://github.com/google/pprof#building-pprof).\nAt the time of writing, installing `pprof` requires first installing\n-[Go](https://golang.org/) and [Graphviz](http://www.graphviz.org/), and then\n-running\n+[Go](https://golang.org/) of version 1.16+,\n+[Graphviz](http://www.graphviz.org/), and then running\n```shell\n-go get -u github.com/google/pprof\n+go install github.com/google/pprof@latest\n```\nwhich installs `pprof` as `$GOPATH/bin/pprof`, where `GOPATH` defaults to\n" } ]
Python
Apache License 2.0
google/jax
DOC: update pprof install instructions
260,510
21.06.2022 12:41:26
25,200
9bd1bd67e0052d3b030a61aba01e32454bd61efa
Update versions for jax/jaxlib release
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -8,7 +8,11 @@ Remember to align the itemized text with the first line of an item within a list\nPLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n-->\n-## jax 0.3.14 (Unreleased)\n+## jax 0.3.15 (Unreleased)\n+\n+## jaxlib 0.3.15 (Unreleased)\n+\n+## jax 0.3.14 (June 21, 2022)\n* [GitHub commits](https://github.com/google/jax/compare/jax-v0.3.13...main).\n* Breaking changes\n* {func}`jax.experimental.compilation_cache.initialize_cache` does not support\n@@ -57,7 +61,7 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\nbucket path as input.\n* Added {func}`jax.scipy.stats.gennorm`.\n-## jaxlib 0.3.11 (Unreleased)\n+## jaxlib 0.3.14 (June 21, 2022)\n* [GitHub commits](https://github.com/google/jax/compare/jaxlib-v0.3.10...main).\n* x86-64 Mac wheels now require Mac OS 10.14 (Mojave) or newer. Mac OS 10.14\nwas released in 2018, so this should not be a very onerous requirement.\n" }, { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -7,10 +7,10 @@ load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"db36e99e992dc44c59f6630070c50d1cb85ea229bcb3bc30b45d23c15a9cd0ea\",\n- strip_prefix = \"tensorflow-ea9e3b4fb5640294479b517a7efc493e8f9d02f2\",\n+ sha256 = \"bb0770fab82bdb243e0118671cb056253c1c74fc46fb64cc9c4c7d8ce2773c29\",\n+ strip_prefix = \"tensorflow-0550a551f158167fa88acb17261d96e959529f70\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/ea9e3b4fb5640294479b517a7efc493e8f9d02f2.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/0550a551f158167fa88acb17261d96e959529f70.tar.gz\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/version.py", "new_path": "jaxlib/version.py", "diff": "# reflect the most recent available binaries.\n# __version__ should be increased after releasing the current version\n# (i.e. on main, this is always the next version to be released).\n-__version__ = \"0.3.11\"\n+__version__ = \"0.3.14\"\n" }, { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "from setuptools import setup, find_packages\n-_current_jaxlib_version = '0.3.10'\n+_current_jaxlib_version = '0.3.14'\n# The following should be updated with each new jaxlib release.\n_latest_jaxlib_version_on_pypi = '0.3.10'\n_available_cuda_versions = ['11']\n_default_cuda_version = '11'\n_available_cudnn_versions = ['82', '805']\n_default_cudnn_version = '82'\n-_libtpu_version = '0.1.dev20220504'\n+_libtpu_version = '0.1.dev20220621'\n_dct = {}\nwith open('jax/version.py') as f:\n" } ]
Python
Apache License 2.0
google/jax
Update versions for jax/jaxlib release
260,510
21.06.2022 14:34:22
25,200
217d89812420ada8130b851b5656539a89658156
Update TF version for jaxlib build
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -7,10 +7,10 @@ load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"bb0770fab82bdb243e0118671cb056253c1c74fc46fb64cc9c4c7d8ce2773c29\",\n- strip_prefix = \"tensorflow-0550a551f158167fa88acb17261d96e959529f70\",\n+ sha256 = \"18bee43e5413494424a7208fd76ba328645be236c75892d7f5ddeda674aa49f6\",\n+ strip_prefix = \"tensorflow-d38f1c03fd6e8d4cc3141f661598d5e4e37c40de\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/0550a551f158167fa88acb17261d96e959529f70.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/d38f1c03fd6e8d4cc3141f661598d5e4e37c40de.tar.gz\",\n],\n)\n" } ]
Python
Apache License 2.0
google/jax
Update TF version for jaxlib build
260,411
23.06.2022 16:49:47
-10,800
391aaf417787410f41b0401592df0d9e372de88c
[jax2tf] Fix the documentation for handling dimension polynomials.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -419,6 +419,30 @@ The dimension polynomials have the following behavior for arithmetic operations:\nare overloaded, such that `+`, `*`, `np.sum`, `np.prod` work directly on\ndimension polynomials.\nThese arise, e.g., in `jax.numpy.concatenate` or `jax.numpy.reshape`.\n+\n+For example, in the following code to flatten a 2D array, the computation\n+`x.shape[0] * x.shape[1]` computes the dimension polynomial `4 * b`:\n+\n+```\n+jax2tf.convert(lambda x: jnp.reshape(x, (x.shape[0] * x.shape[1],)),\n+ polymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4))\n+```\n+\n+Replacing the multiplication with `np.prod(x.shape)` would also\n+work. Note that the dimension polynomials can be used only as shape arguments\n+to JAX functions. If you try to use them in place of array arguments you will get\n+an error:\n+\n+```\n+jax2tf.convert(lambda x: jnp.prod(x.shape),\n+ polymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4))\n+Uncaught exception TypeError: \"Argument 'b' of type <class 'jax.experimental.jax2tf.shape_poly._DimPolynomial'> is not a valid JAX type\"\n+```\n+\n+See below for how you can turn a dimension polynomial into a JAX value.\n+\n+More operations are partially supported for dimension polynomials:\n+\n* division is a special case. It is also overloaded, but it is only partially\nsupported, when either (a) there is no remainder, or (b) the divisor is a constant\nin which case there may be a constant remainder. The need for division in JAX core\n@@ -449,19 +473,6 @@ as `False` and produce a converted function that returns `1` just because the di\nare not identical: there are some concrete input shapes for which the function\nshould return `0`.\n-Note that JAX will give an error when trying to use a dimension polynomial\n-as a JAX value, e.g., in the following code:\n-\n-```\n-jax2tf.convert(lambda x: jnp.prod(jnp.array(x.shape)),\n- polymorphic_shapes=[\"(b, ...)\"])(np.ones((3, 4)))\n-```\n-\n-Note that the above code would work if we replace `jnp.array` and `jnp.prod`\n-with `np.array`and `np.prod`, because dimension polynomials overload multiplication.\n-See the next section if you do need to convert a dimension polynomials to\n-a JAX value.\n-\n### Dimension variables appearing in the numeric computation\nThere are some situations when dimension variables arise in the staged computation itself.\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "diff": "@@ -891,6 +891,17 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# will invoke broadcast_in_dim with shape=(1, w, w)\njax2tf.convert(image_mask_jax, polymorphic_shapes=[\"(b, w, w)\", \"(w, w)\"])\n+ jax2tf.convert(lambda x: jnp.reshape(x, (x.shape[0] * x.shape[1],)),\n+ polymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4)))\n+\n+ jax2tf.convert(lambda x: jnp.reshape(x, (np.prod(x.shape),)),\n+ polymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4)))\n+\n+ with self.assertRaisesRegex(TypeError,\n+ \"Argument 'b' of type <class 'jax.experimental.jax2tf.shape_poly._DimPolynomial'> is not a valid JAX type\"):\n+ jax2tf.convert(lambda x: jnp.prod(x.shape),\n+ polymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4)))\n+\ndef test_readme_shape_error(self):\n\"\"\"Some of the examples from the README.\"\"\"\nwith self.assertRaisesRegex(\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix the documentation for handling dimension polynomials.
260,424
23.06.2022 17:23:43
-3,600
8efeb3e297617f3bfa47062de906868121773188
Fix getting aval of BatchTracers that are not mapped.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -138,6 +138,8 @@ class BatchTracer(Tracer):\n@property\ndef aval(self):\naval = raise_to_shaped(core.get_aval(self.val))\n+ if self.batch_dim is not_mapped:\n+ return aval\nreturn core.mapped_aval(aval.shape[self.batch_dim], self.batch_dim, aval)\ndef full_lower(self):\n" } ]
Python
Apache License 2.0
google/jax
Fix getting aval of BatchTracers that are not mapped.
260,631
23.06.2022 11:31:47
25,200
e4d1e1beb3c9e2f4d9a2ece4be2e41a23ece9d65
Copybara import of the project: by Matthew Johnson [dynamic-shapes] basic jvp working, including with broadcast
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -2660,10 +2660,7 @@ def _broadcast_in_dim_typecheck_rule(\noperand.aval.weak_type)\nreturn [out_aval], core.no_effects\n-def _broadcast_in_dim_transpose_rule(ct, operand, *dyn_shape,\n- shape, broadcast_dimensions):\n- if dyn_shape:\n- raise NotImplementedError(\"dynamic shape broadcast transpose not implemented\")\n+def _broadcast_in_dim_transpose_rule(ct, operand, *, shape, broadcast_dimensions):\nshape_in = operand.aval.shape\nunit_dimensions = tuple(i for i, s in enumerate(shape_in) if core.symbolic_equal_dim(s, 1))\nbdims = tuple(np.delete(broadcast_dimensions, unit_dimensions))\n@@ -2724,18 +2721,9 @@ def _broadcast_in_dim_padding_rule(in_avals, out_avals, x, *dyn_shape,\nreturn [broadcast_in_dim_p.bind(x, *new_dyn_shape, shape=new_shape,\nbroadcast_dimensions=broadcast_dimensions)]\n-def _broadcast_in_dim_jvp_rule(primals, tangents, *, shape, broadcast_dimensions):\n- operand, *dyn_shape = primals\n- operand_dot, *_ = tangents\n- y = broadcast_in_dim_p.bind(operand , *dyn_shape, shape=shape,\n- broadcast_dimensions=broadcast_dimensions)\n- y_dot = broadcast_in_dim_p.bind(operand_dot, *dyn_shape, shape=shape,\n- broadcast_dimensions=broadcast_dimensions)\n- return y, y_dot\nbroadcast_in_dim_p = standard_primitive(\n_broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')\n-ad.primitive_jvps[broadcast_in_dim_p] = _broadcast_in_dim_jvp_rule\n-ad.primitive_transposes[broadcast_in_dim_p] = _broadcast_in_dim_transpose_rule\n+ad.deflinear2(broadcast_in_dim_p, _broadcast_in_dim_transpose_rule)\nbatching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule\npe.forwarding_rules[broadcast_in_dim_p] = _broadcast_in_dim_fwd_rule\npe.custom_staging_rules[broadcast_in_dim_p] = _broadcast_in_dim_staging_rule\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1315,10 +1315,6 @@ class DShapedArray(UnshapedArray):\nelse:\nraise TypeError(self, other)\n- def at_least_vspace(self):\n- return DShapedArray(self.shape, primal_dtype_to_tangent_dtype(self.dtype),\n- self.weak_type)\n-\ndel AxisSize, AxisSizeForTracing, AxisSizeForJaxprType, \\\nAxisSizeForJaxprTracingSpec\n@@ -1327,9 +1323,8 @@ class ShapedArray(UnshapedArray):\narray_abstraction_level = 1\ndef __init__(self, shape, dtype, weak_type=False, named_shape=None):\n+ super().__init__(dtype, weak_type=weak_type)\nself.shape = canonicalize_shape(shape)\n- self.dtype = np.dtype(dtype)\n- self.weak_type = weak_type\nself.named_shape = {} if named_shape is None else dict(named_shape)\ndef update(self, shape=None, dtype=None, weak_type=None, named_shape=None):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -46,11 +46,8 @@ def _update_annotation(\n) -> lu.WrappedFun:\nif orig_type is None:\nreturn f\n- # Implicit arguments never have tangents, so generate the tangent part of the\n- # type annotation from explicit arguments only.\n- orig_avals = [aval for aval, explicit in orig_type if explicit]\n- tan_types = [(aval.at_least_vspace(), True)\n- for nz, aval in zip(nonzeros, orig_avals) if nz]\n+ tan_types = [(aval.at_least_vspace(), keep)\n+ for nz, (aval, keep) in zip(nonzeros, orig_type) if nz]\nreturn lu.annotate(f, (*orig_type, *tan_types))\ndef jvp(fun: lu.WrappedFun, has_aux=False, instantiate=True,\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -8980,73 +8980,6 @@ class DynamicShapeTest(jtu.JaxTestCase):\nx = jax.jit(lambda n: jnp.ones(2 * n))(3)\nself.assertAllClose(x, jnp.ones(2 * 3))\n- def test_jvp_broadcast(self):\n- @jax.jit\n- def fn(n, x):\n- return lax.broadcast_in_dim(x, (n,), ())\n-\n- outer_jaxpr = jax.make_jaxpr(\n- lambda x, t: jax.jvp(lambda y: fn(3, y), (x,), (t,))\n- )(3., 4.)\n- # { lambda ; a:f32[] b:f32[]. let\n- # c:f32[3] d:f32[3] = xla_call[\n- # call_jaxpr={ lambda ; e:i32[] f:f32[] g:f32[]. let\n- # h:f32[e] = broadcast_in_dim[broadcast_dimensions=() shape=(None,)] f e\n- # i:f32[e] = broadcast_in_dim[broadcast_dimensions=() shape=(None,)] g e\n- # in (h, i) }\n- # name=f\n- # ] 3 a b\n- # in (c, d) }\n- self.assertLen(outer_jaxpr.jaxpr.eqns, 1)\n- eqn, = outer_jaxpr.jaxpr.eqns\n- self.assertIn('call_jaxpr', eqn.params)\n- jaxpr = eqn.params['call_jaxpr']\n- self.assertLen(jaxpr.invars, 3)\n- e, f, g = jaxpr.invars\n- self.assertEqual(e.aval.shape, ())\n- self.assertEqual(f.aval.shape, ())\n- self.assertEqual(g.aval.shape, ())\n- self.assertLen(jaxpr.outvars, 2)\n- h, i = jaxpr.outvars\n- self.assertEqual(h.aval.shape, (e,))\n- self.assertEqual(i.aval.shape, (e,))\n- self.assertLen(eqn.outvars, 2)\n- c, d = eqn.outvars\n- self.assertEqual(c.aval.shape, (3,))\n- self.assertEqual(d.aval.shape, (3,))\n-\n- def test_jvp_basic(self):\n- @partial(jax.jit, abstracted_axes=('n',))\n- def foo(x):\n- return jnp.sin(x)\n-\n- x = t = jnp.arange(3.)\n- outer_jaxpr = jax.make_jaxpr(lambda x, t: jax.jvp(foo, (x,), (t,)))(x, t)\n- # { lambda ; a:f32[3] b:f32[3]. let\n- # c:f32[3] d:f32[3] = xla_call[\n- # call_jaxpr={ lambda ; e:i32[] f:f32[e] g:f32[e]. let\n- # h:f32[e] = sin f\n- # i:f32[e] = cos f\n- # j:f32[e] = mul g i\n- # in (h, j) }\n- # name=f\n- # ] 3 a b\n- # in (c, d) }\n- self.assertLen(outer_jaxpr.jaxpr.eqns, 1)\n- eqn, = outer_jaxpr.eqns\n- self.assertIn('call_jaxpr', eqn.params)\n- jaxpr = eqn.params['call_jaxpr']\n- self.assertLen(jaxpr.invars, 3)\n- e, f, g = jaxpr.invars\n- self.assertEqual(e.aval.shape, ())\n- self.assertEqual(f.aval.shape, (e,))\n- self.assertEqual(g.aval.shape, (e,))\n- self.assertLen(jaxpr.outvars, 2)\n- self.assertLen(eqn.outvars, 2)\n- c, d = eqn.outvars\n- self.assertEqual(c.aval.shape, (3,))\n- self.assertEqual(d.aval.shape, (3,))\n-\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Copybara import of the project: -- a001c52f878824cd1c0a67c73d9d318ed30286c9 by Matthew Johnson <mattjj@google.com>: [dynamic-shapes] basic jvp working, including with broadcast PiperOrigin-RevId: 456822732
260,335
23.06.2022 15:29:46
25,200
5f97dc8954529791ddd789b86a53efa2d90e3ef5
Roll forward with simple fix: handle Zero cotangents in _broadcast_in_dim transpose rule (previously handled by the deflinear2 wrapper, which it's no longer using).
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -2660,12 +2660,17 @@ def _broadcast_in_dim_typecheck_rule(\noperand.aval.weak_type)\nreturn [out_aval], core.no_effects\n-def _broadcast_in_dim_transpose_rule(ct, operand, *, shape, broadcast_dimensions):\n- shape_in = operand.aval.shape\n- unit_dimensions = tuple(i for i, s in enumerate(shape_in) if core.symbolic_equal_dim(s, 1))\n- bdims = tuple(np.delete(broadcast_dimensions, unit_dimensions))\n+def _broadcast_in_dim_transpose_rule(ct, operand, *dyn_shape,\n+ shape, broadcast_dimensions):\n+ if dyn_shape:\n+ raise NotImplementedError(\"dynamic shape broadcast transpose not implemented\")\n+ if type(ct) is ad_util.Zero:\n+ return [ad_util.Zero(operand.aval)]\n+ unit_axes = [i for i, s in enumerate(operand.aval.shape)\n+ if core.symbolic_equal_dim(s, 1)]\n+ bdims = tuple(np.delete(broadcast_dimensions, unit_axes))\naxes = tuple(np.delete(range(len(shape)), bdims))\n- return [expand_dims(_reduce_sum(ct, axes), unit_dimensions)]\n+ return [expand_dims(_reduce_sum(ct, axes), unit_axes)]\ndef _broadcast_in_dim_batch_rule(batched_args, batch_dims, *, shape,\nbroadcast_dimensions):\n@@ -2721,9 +2726,18 @@ def _broadcast_in_dim_padding_rule(in_avals, out_avals, x, *dyn_shape,\nreturn [broadcast_in_dim_p.bind(x, *new_dyn_shape, shape=new_shape,\nbroadcast_dimensions=broadcast_dimensions)]\n+def _broadcast_in_dim_jvp_rule(primals, tangents, *, shape, broadcast_dimensions):\n+ operand, *dyn_shape = primals\n+ operand_dot, *_ = tangents\n+ y = broadcast_in_dim_p.bind(operand , *dyn_shape, shape=shape,\n+ broadcast_dimensions=broadcast_dimensions)\n+ y_dot = broadcast_in_dim_p.bind(operand_dot, *dyn_shape, shape=shape,\n+ broadcast_dimensions=broadcast_dimensions)\n+ return y, y_dot\nbroadcast_in_dim_p = standard_primitive(\n_broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')\n-ad.deflinear2(broadcast_in_dim_p, _broadcast_in_dim_transpose_rule)\n+ad.primitive_jvps[broadcast_in_dim_p] = _broadcast_in_dim_jvp_rule\n+ad.primitive_transposes[broadcast_in_dim_p] = _broadcast_in_dim_transpose_rule\nbatching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule\npe.forwarding_rules[broadcast_in_dim_p] = _broadcast_in_dim_fwd_rule\npe.custom_staging_rules[broadcast_in_dim_p] = _broadcast_in_dim_staging_rule\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1315,6 +1315,10 @@ class DShapedArray(UnshapedArray):\nelse:\nraise TypeError(self, other)\n+ def at_least_vspace(self):\n+ return DShapedArray(self.shape, primal_dtype_to_tangent_dtype(self.dtype),\n+ self.weak_type)\n+\ndel AxisSize, AxisSizeForTracing, AxisSizeForJaxprType, \\\nAxisSizeForJaxprTracingSpec\n@@ -1323,8 +1327,9 @@ class ShapedArray(UnshapedArray):\narray_abstraction_level = 1\ndef __init__(self, shape, dtype, weak_type=False, named_shape=None):\n- super().__init__(dtype, weak_type=weak_type)\nself.shape = canonicalize_shape(shape)\n+ self.dtype = np.dtype(dtype)\n+ self.weak_type = weak_type\nself.named_shape = {} if named_shape is None else dict(named_shape)\ndef update(self, shape=None, dtype=None, weak_type=None, named_shape=None):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -46,8 +46,11 @@ def _update_annotation(\n) -> lu.WrappedFun:\nif orig_type is None:\nreturn f\n- tan_types = [(aval.at_least_vspace(), keep)\n- for nz, (aval, keep) in zip(nonzeros, orig_type) if nz]\n+ # Implicit arguments never have tangents, so generate the tangent part of the\n+ # type annotation from explicit arguments only.\n+ orig_avals = [aval for aval, explicit in orig_type if explicit]\n+ tan_types = [(aval.at_least_vspace(), True)\n+ for nz, aval in zip(nonzeros, orig_avals) if nz]\nreturn lu.annotate(f, (*orig_type, *tan_types))\ndef jvp(fun: lu.WrappedFun, has_aux=False, instantiate=True,\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -8980,6 +8980,73 @@ class DynamicShapeTest(jtu.JaxTestCase):\nx = jax.jit(lambda n: jnp.ones(2 * n))(3)\nself.assertAllClose(x, jnp.ones(2 * 3))\n+ def test_jvp_broadcast(self):\n+ @jax.jit\n+ def fn(n, x):\n+ return lax.broadcast_in_dim(x, (n,), ())\n+\n+ outer_jaxpr = jax.make_jaxpr(\n+ lambda x, t: jax.jvp(lambda y: fn(3, y), (x,), (t,))\n+ )(3., 4.)\n+ # { lambda ; a:f32[] b:f32[]. let\n+ # c:f32[3] d:f32[3] = xla_call[\n+ # call_jaxpr={ lambda ; e:i32[] f:f32[] g:f32[]. let\n+ # h:f32[e] = broadcast_in_dim[broadcast_dimensions=() shape=(None,)] f e\n+ # i:f32[e] = broadcast_in_dim[broadcast_dimensions=() shape=(None,)] g e\n+ # in (h, i) }\n+ # name=f\n+ # ] 3 a b\n+ # in (c, d) }\n+ self.assertLen(outer_jaxpr.jaxpr.eqns, 1)\n+ eqn, = outer_jaxpr.jaxpr.eqns\n+ self.assertIn('call_jaxpr', eqn.params)\n+ jaxpr = eqn.params['call_jaxpr']\n+ self.assertLen(jaxpr.invars, 3)\n+ e, f, g = jaxpr.invars\n+ self.assertEqual(e.aval.shape, ())\n+ self.assertEqual(f.aval.shape, ())\n+ self.assertEqual(g.aval.shape, ())\n+ self.assertLen(jaxpr.outvars, 2)\n+ h, i = jaxpr.outvars\n+ self.assertEqual(h.aval.shape, (e,))\n+ self.assertEqual(i.aval.shape, (e,))\n+ self.assertLen(eqn.outvars, 2)\n+ c, d = eqn.outvars\n+ self.assertEqual(c.aval.shape, (3,))\n+ self.assertEqual(d.aval.shape, (3,))\n+\n+ def test_jvp_basic(self):\n+ @partial(jax.jit, abstracted_axes=('n',))\n+ def foo(x):\n+ return jnp.sin(x)\n+\n+ x = t = jnp.arange(3.)\n+ outer_jaxpr = jax.make_jaxpr(lambda x, t: jax.jvp(foo, (x,), (t,)))(x, t)\n+ # { lambda ; a:f32[3] b:f32[3]. let\n+ # c:f32[3] d:f32[3] = xla_call[\n+ # call_jaxpr={ lambda ; e:i32[] f:f32[e] g:f32[e]. let\n+ # h:f32[e] = sin f\n+ # i:f32[e] = cos f\n+ # j:f32[e] = mul g i\n+ # in (h, j) }\n+ # name=f\n+ # ] 3 a b\n+ # in (c, d) }\n+ self.assertLen(outer_jaxpr.jaxpr.eqns, 1)\n+ eqn, = outer_jaxpr.eqns\n+ self.assertIn('call_jaxpr', eqn.params)\n+ jaxpr = eqn.params['call_jaxpr']\n+ self.assertLen(jaxpr.invars, 3)\n+ e, f, g = jaxpr.invars\n+ self.assertEqual(e.aval.shape, ())\n+ self.assertEqual(f.aval.shape, (e,))\n+ self.assertEqual(g.aval.shape, (e,))\n+ self.assertLen(jaxpr.outvars, 2)\n+ self.assertLen(eqn.outvars, 2)\n+ c, d = eqn.outvars\n+ self.assertEqual(c.aval.shape, (3,))\n+ self.assertEqual(d.aval.shape, (3,))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Roll forward with simple fix: handle Zero cotangents in _broadcast_in_dim transpose rule (previously handled by the deflinear2 wrapper, which it's no longer using). PiperOrigin-RevId: 456874635
260,335
23.06.2022 20:53:45
25,200
8c5632123bd7357b7e6f644c4eb28aff618694d4
fix ad_util.Zero handling in broadcast_in_dim_jvp_rule
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -2731,6 +2731,9 @@ def _broadcast_in_dim_jvp_rule(primals, tangents, *, shape, broadcast_dimensions\noperand_dot, *_ = tangents\ny = broadcast_in_dim_p.bind(operand, *dyn_shape, shape=shape,\nbroadcast_dimensions=broadcast_dimensions)\n+ if type(operand_dot) is ad_util.Zero:\n+ y_dot = ad_util.Zero.from_value(y)\n+ else:\ny_dot = broadcast_in_dim_p.bind(operand_dot, *dyn_shape, shape=shape,\nbroadcast_dimensions=broadcast_dimensions)\nreturn y, y_dot\n" } ]
Python
Apache License 2.0
google/jax
fix ad_util.Zero handling in broadcast_in_dim_jvp_rule PiperOrigin-RevId: 456922766
260,399
24.06.2022 12:18:11
25,200
0cc2ada432ab8449d66a02f86a50947f46306cdb
Fix broken links for moved design_notes folder
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -723,7 +723,7 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* `TraceContext` --> {func}`~jax.profiler.TraceAnnotation`\n* `StepTraceContext` --> {func}`~jax.profiler.StepTraceAnnotation`\n* `trace_function` --> {func}`~jax.profiler.annotate_function`\n- * Omnistaging can no longer be disabled. See [omnistaging](https://github.com/google/jax/blob/main/design_notes/omnistaging.md)\n+ * Omnistaging can no longer be disabled. See [omnistaging](https://github.com/google/jax/blob/main/docs/design_notes/omnistaging.md)\nfor more information.\n* Python integers larger than the maximum `int64` value will now lead to an overflow\nin all cases, rather than being silently converted to `uint64` in some cases ({jax-issue}`#6047`).\n@@ -983,7 +983,7 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* [GitHub commits](https://github.com/google/jax/compare/jax-v0.1.77...jax-v0.2.0).\n* Improvements:\n* Omnistaging on by default. See {jax-issue}`#3370` and\n- [omnistaging](https://github.com/google/jax/blob/main/design_notes/omnistaging.md)\n+ [omnistaging](https://github.com/google/jax/blob/main/docs/design_notes/omnistaging.md)\n## jax (0.1.77) (September 15 2020)\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb", "new_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb", "diff": "\"id\": \"COjzGBpO4tzL\"\n},\n\"source\": [\n- \"JAX instead implements an _explicit_ PRNG where entropy production and consumption are handled by explicitly passing and iterating PRNG state. JAX uses a modern [Threefry counter-based PRNG](https://github.com/google/jax/blob/main/design_notes/prng.md) that's __splittable__. That is, its design allows us to __fork__ the PRNG state into new PRNGs for use with parallel stochastic generation.\\n\",\n+ \"JAX instead implements an _explicit_ PRNG where entropy production and consumption are handled by explicitly passing and iterating PRNG state. JAX uses a modern [Threefry counter-based PRNG](https://github.com/google/jax/blob/main/docs/design_notes/prng.md) that's __splittable__. That is, its design allows us to __fork__ the PRNG state into new PRNGs for use with parallel stochastic generation.\\n\",\n\"\\n\",\n\"The random state is described by two unsigned-int32s that we call a __key__:\"\n]\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/Common_Gotchas_in_JAX.md", "new_path": "docs/notebooks/Common_Gotchas_in_JAX.md", "diff": "@@ -504,7 +504,7 @@ The Mersenne Twister PRNG is also known to have a [number](https://cs.stackexcha\n+++ {\"id\": \"COjzGBpO4tzL\"}\n-JAX instead implements an _explicit_ PRNG where entropy production and consumption are handled by explicitly passing and iterating PRNG state. JAX uses a modern [Threefry counter-based PRNG](https://github.com/google/jax/blob/main/design_notes/prng.md) that's __splittable__. That is, its design allows us to __fork__ the PRNG state into new PRNGs for use with parallel stochastic generation.\n+JAX instead implements an _explicit_ PRNG where entropy production and consumption are handled by explicitly passing and iterating PRNG state. JAX uses a modern [Threefry counter-based PRNG](https://github.com/google/jax/blob/main/docs/design_notes/prng.md) that's __splittable__. That is, its design allows us to __fork__ the PRNG state into new PRNGs for use with parallel stochastic generation.\nThe random state is described by two unsigned-int32s that we call a __key__:\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -175,18 +175,18 @@ class Config:\nif not FLAGS.jax_omnistaging:\nraise Exception(\n\"Disabling of omnistaging is no longer supported in JAX version 0.2.12 and higher: \"\n- \"see https://github.com/google/jax/blob/main/design_notes/omnistaging.md.\\n\"\n+ \"see https://github.com/google/jax/blob/main/docs/design_notes/omnistaging.md.\\n\"\n\"To remove this warning, unset the JAX_OMNISTAGING environment variable.\")\ndef enable_omnistaging(self):\nwarnings.warn(\n\"enable_omnistaging() is a no-op in JAX versions 0.2.12 and higher;\\n\"\n- \"see https://github.com/google/jax/blob/main/design_notes/omnistaging.md\")\n+ \"see https://github.com/google/jax/blob/main/docs/design_notes/omnistaging.md\")\ndef disable_omnistaging(self):\nraise Exception(\n\"Disabling of omnistaging is no longer supported in JAX version 0.2.12 and higher: \"\n- \"see https://github.com/google/jax/blob/main/design_notes/omnistaging.md.\")\n+ \"see https://github.com/google/jax/blob/main/docs/design_notes/omnistaging.md.\")\ndef define_bool_state(\nself, name: str, default: bool, help: str, *,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -971,7 +971,7 @@ before conversion. (This is a hypothesis, we have not yet verified it extensivel\nThere is one know case when the performance of the converted code will be different.\nJAX programs use a [stateless\n-deterministic PRNG](https://github.com/google/jax/blob/main/design_notes/prng.md)\n+deterministic PRNG](https://github.com/google/jax/blob/main/docs/design_notes/prng.md)\nand it has an internal JAX primitive for it.\nThis primitive is at the moment converted to a soup of tf.bitwise operations,\nwhich has a clear performance penalty. We plan to look into using the\n" } ]
Python
Apache License 2.0
google/jax
Fix broken links for moved design_notes folder
260,624
17.06.2022 16:38:56
0
df8c6263de122853f33669970f416a531b10aadb
Change JAX_PLATFORMS to raise an exception when platform initialization fails
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -21,6 +21,7 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Breaking changes\n* {func}`jax.experimental.compilation_cache.initialize_cache` does not support\n`max_cache_size_ bytes` anymore and will not get that as an input.\n+ * `JAX_PLATFORMS` now raises an exception when platform initialization fails.\n* Changes\n* {func}`jax.numpy.linalg.slogdet` now accepts an optional `method` argument\nthat allows selection between an LU-decomposition based implementation and\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -602,6 +602,22 @@ jax2tf_associative_scan_reductions = config.define_bool_state(\n)\n)\n+jax_platforms = config.define_string_state(\n+ name='jax_platforms',\n+ default=None,\n+ help=(\n+ 'Comma-separated list of platform names specifying which platforms jax '\n+ 'should initialize. If any of the platforms in this list are not successfully '\n+ 'initialized, an exception will be raised and the program will be aborted. '\n+ 'The first platform in the list will be the default platform. '\n+ 'For example, config.jax_platforms=cpu,tpu means that CPU and TPU backends '\n+ 'will be initialized, and the CPU backend will be used unless otherwise '\n+ 'specified. If TPU initialization fails, it will raise an exception. '\n+ 'By default, jax will try to initialize all available '\n+ 'platforms and will default to GPU or TPU if available, and fallback to CPU '\n+ 'otherwise.'\n+ ))\n+\nenable_checks = config.define_bool_state(\nname='jax_enable_checks',\ndefault=False,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lib/xla_bridge.py", "new_path": "jax/_src/lib/xla_bridge.py", "diff": "@@ -35,6 +35,7 @@ from jax._src.config import flags, bool_env, int_env\nfrom jax._src.lib import tpu_driver_client\nfrom jax._src.lib import xla_client\nfrom jax._src import util, traceback_util\n+from jax.config import config\nimport numpy as np\niree: Optional[Any]\n@@ -64,17 +65,6 @@ flags.DEFINE_string(\n'jax_platform_name',\nos.getenv('JAX_PLATFORM_NAME', '').lower(),\n'Deprecated, please use --jax_platforms instead.')\n-flags.DEFINE_string(\n- 'jax_platforms',\n- os.getenv('JAX_PLATFORMS', '').lower(),\n- 'Comma-separated list of platform names specifying which platforms jax '\n- 'should attempt to initialize. The first platform in the list that is '\n- 'successfully initialized will be used as the default platform. For '\n- 'example, --jax_platforms=cpu,gpu means that CPU and GPU backends will be '\n- 'initialized, and the CPU backend will be used unless otherwise specified; '\n- '--jax_platforms=cpu means that only the CPU backend will be initialized. '\n- 'By default, jax will try to initialize all available platforms and will '\n- 'default to GPU or TPU if available, and fallback to CPU otherwise.')\nflags.DEFINE_bool(\n'jax_disable_most_optimizations',\nbool_env('JAX_DISABLE_MOST_OPTIMIZATIONS', False),\n@@ -297,9 +287,8 @@ def backends():\nwith _backend_lock:\nif _backends:\nreturn _backends\n-\n- if FLAGS.jax_platforms:\n- jax_platforms = FLAGS.jax_platforms.split(\",\")\n+ if config.jax_platforms:\n+ jax_platforms = config.jax_platforms.split(\",\")\nplatforms = []\n# Allow platform aliases in the list of platforms.\nfor platform in jax_platforms:\n@@ -310,7 +299,6 @@ def backends():\nplatforms_and_priorites = (\n(platform, priority) for platform, (_, priority)\nin _backend_factories.items())\n-\ndefault_priority = -1000\nfor platform, priority in platforms_and_priorites:\ntry:\n@@ -337,9 +325,12 @@ def backends():\nelse:\n# If the backend isn't built into the binary, or if it has no devices,\n# we expect a RuntimeError.\n- logging.info(\"Unable to initialize backend '%s': %s\", platform,\n- err)\n+ err_msg = f\"Unable to initialize backend '{platform}': {err}\"\n+ if config.jax_platforms:\n+ raise RuntimeError(err_msg)\n+ else:\n_backends_errors[platform] = str(err)\n+ logging.info(err_msg)\ncontinue\n# We don't warn about falling back to CPU on Mac OS, because we don't\n# support anything else there at the moment and warning would be pointless.\n" } ]
Python
Apache License 2.0
google/jax
Change JAX_PLATFORMS to raise an exception when platform initialization fails
260,424
23.06.2022 17:23:43
-3,600
740fe6926a9ba7192c7ddfac9a95febbc10958d1
Checkify: add (checkify-of-)vmap-of-check.
[ { "change_type": "MODIFY", "old_path": "jax/_src/checkify.py", "new_path": "jax/_src/checkify.py", "diff": "@@ -25,6 +25,7 @@ import jax.numpy as jnp\nfrom jax import core\nfrom jax import linear_util as lu\nfrom jax.api_util import flatten_fun\n+from jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\nfrom jax.tree_util import tree_flatten, tree_unflatten, register_pytree_node\n@@ -477,6 +478,18 @@ mlir.register_lowering(assert_p, assert_lowering_rule)\nmlir.lowerable_effects.add(CheckEffect)\ncf.allowed_effects.add(CheckEffect)\n+\n+def assert_batching_rule(batched_args, batch_dims, *, msgs):\n+ size = next(x.shape[dim] for x, dim in zip(batched_args, batch_dims)\n+ if dim is not batching.not_mapped)\n+ pred, code, payload = (batching.bdim_at_front(a, d, size)\n+ for a, d in zip(batched_args, batch_dims))\n+ err = Error(jnp.logical_not(pred), code, msgs, payload)\n+ check_error(err)\n+ return [], []\n+\n+batching.primitive_batchers[assert_p] = assert_batching_rule\n+\n## checkify rules\ndef summary() -> str:\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -723,13 +723,42 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nchecked_f = checkify.checkify(f)\nerr, _ = checked_f(0, 1)\n- self.assertIsNotNone(err)\n+ self.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"i must be negative\")\nerr, _ = checked_f(-1, 0)\n- self.assertIsNotNone(err)\n+ self.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"x must be negative\")\n+ def test_assert_batching_rule(self):\n+ @jax.vmap\n+ def f(x):\n+ checkify.check(jnp.sum(x) == 1., \"x must sum to one.\")\n+ return x\n+\n+ no_failures = jnp.array([[0.5, 0.5], [1., 0.]])\n+ one_batch_fails = jnp.array([[0.5, 0.5], [1, 1]])\n+ mult_batch_fail = jnp.array([[0.5, 0.5], [1, 1], [2, 2]])\n+\n+ f(no_failures)\n+ with self.assertRaisesRegex(ValueError, \"x must sum to one.\"):\n+ f(one_batch_fails)\n+\n+ with self.assertRaisesRegex(ValueError, \"x must sum to one.\"):\n+ f(mult_batch_fail)\n+\n+ checked_f = checkify.checkify(f)\n+ err, _ = checked_f(no_failures)\n+ self.assertIsNone(err.get())\n+\n+ err, _ = checked_f(one_batch_fails)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"x must sum to one\")\n+\n+ err, _ = checked_f(mult_batch_fail)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"x must sum to one\")\n+\ndef test_check_error(self):\ndef f():\ncheckify.check_error(checkify.Error(True, 0, {0: \"hi\"}))\n" } ]
Python
Apache License 2.0
google/jax
Checkify: add (checkify-of-)vmap-of-check.
260,510
22.06.2022 12:36:13
25,200
236a445b49ec7ec3dc6937a1958c60ed831af77f
Add `for_loop` primitive and impl rule
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "\"\"\"Module for the `for_loop` primitive.\"\"\"\nfrom functools import partial\n-from typing import Any, Dict, List, Sequence, Tuple\n+from typing import Any, Callable, Dict, Generic, List, Sequence, Tuple, TypeVar\nfrom jax import core\nfrom jax import lax\nfrom jax import linear_util as lu\n+from jax.api_util import flatten_fun_nokwargs\nfrom jax.interpreters import ad\n+from jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\n+from jax.interpreters import xla\n+from jax.tree_util import (tree_flatten, tree_structure, tree_unflatten,\n+ treedef_tuple, PyTreeDef)\nfrom jax._src import ad_util\nfrom jax._src import pretty_printer as pp\n-from jax._src import util\n+from jax._src.util import safe_map, safe_zip, split_list\n+import jax.numpy as jnp\n## JAX utilities\n-map, unsafe_map = util.safe_map, map\n-zip, unsafe_zip = util.safe_zip, zip\n+map, unsafe_map = safe_map, map\n+zip, unsafe_zip = safe_zip, zip\n## Helpful type aliases\n-Ref = Any\n+S = TypeVar('S')\n+T = TypeVar('T')\n+class Ref(Generic[T]): pass\nArray = Any\n## State effect\nclass StateEffect: pass\n-State = StateEffect\n+State = StateEffect()\n## get/swap/addupdate implementations\n@@ -57,6 +65,7 @@ get_p.def_impl(_get_impl)\ndef ref_get(ref: Ref, idx: Tuple[int]) -> Array:\n\"\"\"Reads a value from a `Ref`, a.k.a. value <- ref[idx].\"\"\"\n+ idx = map(jnp.int32, idx)\nreturn get_p.bind(ref, *idx)\n# `swap` mutates a `Ref`, setting its value and returns its previous value.\n@@ -84,6 +93,7 @@ swap_p.def_impl(_swap_impl)\ndef ref_swap(ref: Ref, idx: Tuple[int], value: Array) -> Array:\n\"\"\"Sets a `Ref`'s value and returns the original value.\"\"\"\n+ idx = map(jnp.int32, idx)\nreturn swap_p.bind(ref, value, *idx)\ndef ref_set(ref: Ref, idx: Tuple[int], value: Array) -> None:\n@@ -168,6 +178,10 @@ def _swap_abstract_eval(ref_aval: ShapedArrayRef, val_aval: core.AbstractValue,\nf\"Ref shape: {ref_aval.shape}. \"\nf\"Value shape: {val_aval.shape}. \"\nf\"Indices: {idx}. \")\n+ if ref_aval.dtype != val_aval.dtype:\n+ raise ValueError(\"Invalid dtype for `swap`. \"\n+ f\"Ref dtype: {ref_aval.dtype}. \"\n+ f\"Value shape: {val_aval.dtype}. \")\nreturn core.ShapedArray(ref_aval.shape[len(idx):], ref_aval.dtype), {State}\nswap_p.def_effectful_abstract_eval(_swap_abstract_eval)\n@@ -372,3 +386,115 @@ def _eval_jaxpr_discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any],\nref_vals = map(\nread, [v for v in jaxpr.invars if type(v.aval) is ShapedArrayRef])\nreturn out_vals + ref_vals\n+\n+## `for_loop` implementation\n+\n+for_p = core.Primitive('for')\n+for_p.multiple_results = True\n+\n+### Tracing utilities\n+\n+def _hoist_consts_to_refs(jaxpr: core.Jaxpr) -> core.Jaxpr:\n+ num_consts = len(jaxpr.constvars)\n+\n+ # Note that this function is meant for use w/ `for_loop` since it assumes\n+ # that the index is the first argument and preserves this after hoisting\n+ # consts.\n+ def _hoist(i, *consts_args):\n+ const_refs, args = split_list(consts_args, [num_consts])\n+ # We immediately read the const values out of the `Ref`s.\n+ consts = [r[()] for r in const_refs]\n+ return core.eval_jaxpr(jaxpr, consts, i, *args)\n+ assert all(isinstance(var.aval, core.ShapedArray) for var in jaxpr.constvars)\n+ const_avals = [ShapedArrayRef(var.aval.shape, var.aval.dtype) for var in # pytype: disable=attribute-error\n+ jaxpr.constvars]\n+ i_aval, *arg_avals = [var.aval for var in jaxpr.invars]\n+ in_avals = [i_aval, *const_avals, *arg_avals]\n+ hoisted_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(\n+ lu.wrap_init(_hoist), in_avals)\n+ assert not consts, \"All consts should have been converted to refs\"\n+ return hoisted_jaxpr\n+\n+def _trace_to_jaxpr_with_refs(f, state_tree: PyTreeDef,\n+ state_avals: Sequence[core.AbstractValue]\n+ ) -> Tuple[core.Jaxpr, List[Any], PyTreeDef]:\n+ f, out_tree_thunk = flatten_fun_nokwargs(\n+ lu.wrap_init(f), treedef_tuple((tree_structure(0), state_tree)))\n+ jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(\n+ f, state_avals)\n+ return jaxpr, consts, out_tree_thunk()\n+\n+def val_to_ref_aval(x) -> ShapedArrayRef:\n+ aval = core.raise_to_shaped(core.get_aval(x))\n+ if type(aval) is not core.ShapedArray:\n+ raise Exception(f\"can't make ref from {x}\")\n+ return ShapedArrayRef(aval.shape, aval.dtype)\n+\n+def for_loop(nsteps: int, body: Callable[[Array, Ref[S]], None], init_state: S) -> S:\n+ \"\"\"A for-loop combinator that allows read/write semantics in the loop body.\n+\n+ `for_loop` is a higher-order function that enables writing loops that can be\n+ staged out in JIT-ted JAX computations. Unlike `jax.lax.fori_loop`, it allows\n+ mutation in its body using `Ref`s.\n+\n+ `for_loop` will initialize `Ref`s with the values in `init_state`. Each\n+ iteration, `body` will be called with the current `Ref`s, which can be read\n+ from and written to using `ref_get` and `ref_set`.\n+\n+ `for_loop` is semantically equivalent to the following Python code:\n+\n+ ```python\n+ def for_loop(nsteps, body, init_state):\n+ refs = tree_map(make_ref, init_state)\n+ for i in range(nsteps):\n+ body(i, refs)\n+ return tree_map(ref_get, refs)\n+ ```\n+\n+ Args:\n+ nsteps: Number of iterations\n+ body: A callable that takes in the iteration number as its first argument\n+ and `Ref`s corresponding to `init_state` as its second argument.\n+ `body` is free to read from and write to its `Ref`s. `body` should\n+ not return anything.\n+ init_state: A Pytree of JAX-compatible values used to initialize the `Ref`s\n+ that will be passed into the for loop body.\n+ Returns:\n+ A Pytree of values representing the output of the for loop.\n+ \"\"\"\n+ flat_state, state_tree = tree_flatten(init_state)\n+ state_avals = map(val_to_ref_aval, flat_state)\n+ idx_aval = core.ShapedArray((), jnp.dtype(\"int32\"))\n+ jaxpr, consts, out_tree = _trace_to_jaxpr_with_refs(\n+ body, state_tree, [idx_aval, *state_avals])\n+ if out_tree != tree_structure(None):\n+ raise Exception(\"`body` should not return anything.\")\n+ # Remove constvars from jaxpr and turn them into `Ref`s\n+ jaxpr = _hoist_consts_to_refs(jaxpr)\n+ which_linear = (False,) * (len(consts) + len(flat_state))\n+ out_flat = for_p.bind(*consts, *flat_state, jaxpr=jaxpr, nsteps=int(nsteps),\n+ reverse=False, which_linear=which_linear)\n+ # Consts are `Ref`s so they are both inputs and outputs. We remove them from\n+ # the outputs.\n+ out_flat = out_flat[len(consts):]\n+ return tree_unflatten(state_tree, out_flat)\n+\n+@for_p.def_abstract_eval\n+def _for_abstract_eval(*avals, jaxpr, **__):\n+ return list(avals)\n+\n+def _for_impl(*args, jaxpr, nsteps, reverse, which_linear):\n+ del which_linear\n+ discharged_jaxpr, consts = discharge_state(jaxpr, ())\n+ def cond(carry):\n+ i, _ = carry\n+ return i < nsteps\n+ def body(carry):\n+ i, state = carry\n+ i_ = nsteps - i - 1 if reverse else i\n+ next_state = core.eval_jaxpr(discharged_jaxpr, consts, i_, *state)\n+ return i + 1, next_state\n+ _, state = lax.while_loop(cond, body, (jnp.int32(0), list(args)))\n+ return state\n+mlir.register_lowering(for_p, mlir.lower_fun(_for_impl, multiple_results=True))\n+for_p.def_impl(partial(xla.apply_primitive, for_p))\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -2567,8 +2567,8 @@ class ForLoopTest(jtu.JaxTestCase):\ndef test_can_represent_get_and_swap_in_jaxprs(self):\ndef body(x):\n- x[()] = 1\n- x[()] = 2\n+ x[()] = jnp.int32(1)\n+ x[()] = jnp.int32(2)\nreturn (x[()],)\njaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(\nlu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n@@ -2581,7 +2581,7 @@ class ForLoopTest(jtu.JaxTestCase):\ndef test_can_represent_addupdate_in_jaxprs(self):\ndef body(x):\n- for_loop.ref_addupdate(x, (), 1)\n+ for_loop.ref_addupdate(x, (), jnp.int32(1))\nreturn (x[()],)\njaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(\nlu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n@@ -2599,7 +2599,7 @@ class ForLoopTest(jtu.JaxTestCase):\ndef test_set_custom_pretty_printing_rule(self):\ndef body(x_ref):\n- x_ref[()] = 2\n+ x_ref[()] = jnp.int32(2)\nreturn []\njaxpr, _ , _ = pe.trace_to_jaxpr_dynamic(\nlu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n@@ -2607,7 +2607,7 @@ class ForLoopTest(jtu.JaxTestCase):\ndef test_swap_custom_pretty_printing_rule(self):\ndef body(x_ref):\n- x = for_loop.ref_swap(x_ref, (), 2)\n+ x = for_loop.ref_swap(x_ref, (), jnp.int32(2))\nreturn [x]\njaxpr, _ , _ = pe.trace_to_jaxpr_dynamic(\nlu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n@@ -2615,7 +2615,7 @@ class ForLoopTest(jtu.JaxTestCase):\ndef test_addupdate_custom_pretty_printing_rule(self):\ndef body(x_ref):\n- for_loop.ref_addupdate(x_ref, (), 2)\n+ for_loop.ref_addupdate(x_ref, (), jnp.int32(2))\nreturn []\njaxpr, _ , _ = pe.trace_to_jaxpr_dynamic(\nlu.wrap_init(body), [for_loop.ShapedArrayRef((), jnp.int32)])\n@@ -2803,5 +2803,84 @@ class ForLoopTest(jtu.JaxTestCase):\nself.assertTrue((b == inval + 1).all())\nself.assertTrue((refval == inval).all())\n+ def test_for_loop_impl_trivial(self):\n+ out = for_loop.for_loop(5, lambda i, _: None, None)\n+ self.assertEqual(out, None)\n+\n+ def test_for_loop_can_write_to_ref(self):\n+ def body(_, x_ref):\n+ x_ref[()] = jnp.float32(1.)\n+ out = for_loop.for_loop(1, body, jnp.float32(0.))\n+ self.assertEqual(out, 1.)\n+\n+ def body2(i, x_ref):\n+ x_ref[()] = jnp.float32(i)\n+ out = for_loop.for_loop(2, body2, jnp.float32(0.))\n+ self.assertEqual(out, 1.)\n+\n+ def body3(i, x_ref):\n+ x_ref[()] = jnp.float32(i) * 2.\n+ out = for_loop.for_loop(2, body3, jnp.float32(0.))\n+ self.assertEqual(out, 2.)\n+\n+ def test_for_loop_can_write_to_multiple_refs(self):\n+ def body(_, refs):\n+ x_ref, y_ref = refs\n+ x_ref[()] = jnp.float32(1.)\n+ y_ref[()] = jnp.float32(2.)\n+ x, y = for_loop.for_loop(1, body, (jnp.float32(0.), jnp.float32(0.)))\n+ self.assertEqual(x, 1.)\n+ self.assertEqual(y, 2.)\n+\n+ def test_for_loop_can_read_from_ref(self):\n+ def body(_, x_ref):\n+ x_ref[()]\n+ x = for_loop.for_loop(1, body, jnp.float32(0.))\n+ self.assertEqual(x, 0.)\n+\n+ def test_for_loop_can_read_from_and_write_to_ref(self):\n+ def body(_, x_ref):\n+ x = x_ref[()]\n+ x_ref[()] = x + jnp.float32(1.)\n+ x = for_loop.for_loop(5, body, jnp.float32(0.))\n+ self.assertEqual(x, 5.)\n+\n+ def test_for_loop_can_read_from_and_write_to_refs(self):\n+ def body2(_, refs):\n+ x_ref, y_ref = refs\n+ x = x_ref[()]\n+ y_ref[()] = x + 1.\n+ x_ref[()] = x + 1.\n+ x, y = for_loop.for_loop(5, body2, (0., 0.))\n+ self.assertEqual(x, 5.)\n+ self.assertEqual(y, 5.)\n+\n+ def test_for_loop_can_read_from_and_write_to_ref_slice(self):\n+ def body(i, x_ref):\n+ x = x_ref[i]\n+ x_ref[i] = x + jnp.float32(1.)\n+ x = for_loop.for_loop(4, body, jnp.ones(4, jnp.float32))\n+ np.testing.assert_allclose(x, 2 * jnp.ones(4, jnp.float32))\n+\n+ def body2(i, x_ref):\n+ x = x_ref[i, 0]\n+ x_ref[i, 1] = x + x_ref[i, 1]\n+ x = for_loop.for_loop(4, body2, jnp.arange(8.).reshape((4, 2)))\n+ np.testing.assert_allclose(\n+ x, jnp.array([[0., 1.], [2., 5.], [4., 9.], [6., 13.]]))\n+\n+ def test_for_loop_can_implement_cumsum(self):\n+ def cumsum(x):\n+ def body(i, refs):\n+ x_ref, accum_ref = refs\n+ accum_ref[i + 1] = accum_ref[i] + x_ref[i]\n+ accum = jnp.zeros(x.shape[0] + 1, x.dtype)\n+ _, accum_out = for_loop.for_loop(x.shape[0], body, (x, accum))\n+ return accum_out[1:]\n+\n+ key = jax.random.PRNGKey(0)\n+ x = jax.random.normal(key, (8,))\n+ np.testing.assert_allclose(cumsum(x), jnp.cumsum(x))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add `for_loop` primitive and impl rule Co-authored-by: Matthew Johnson <mattjj@google.com>
260,310
27.06.2022 16:49:54
25,200
de464fcf22c8bf7a2931182f8095bc01530df9fe
update jax2tf README: add walkaround about tf.Module magic conversion. Here we will use tree_util.flatten and unflatten to provide a general walkwaround for tfModule Dict->_DictWrapper conversion. It will works for List and Tuple.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -997,6 +997,33 @@ possibly behave differently, performance-wise or even numerically,\nthan either the TensorFlow native or JAX native batch normalization.\nA similar example is that of an LSTM cell.\n+\n+### Errors due to tf.Module magic conversion during attribute assignment\n+\n+tf.Module will automatically wrap the standard Python container data types into\n+trackable classes during attribute assignment.\n+Python Dict/List/Tuple are changed to _DictWrapper/_ListWrapper/_TupleWrapper\n+classes.\n+In most situation, these Wrapper classes work exactly as the standard\n+Python data types. However, the low-level pytree data structures are different\n+and this can lead to errors.\n+\n+In such cases, the user can use this walkaround:\n+\n+```python\n+import tensorflow as tf\n+input_data = #Any data object\n+\n+m = tf.Module()\n+flat, tree_def = jax.tree_util.tree_flatten(input_data)\n+m.input_data = {\"flat\": flat, \"tree_def\": tree_def}\n+```\n+\n+Later the user can use tree_unflatten for the reverse process\n+```\n+input_data = jax.tree_util.tree_unflatten(m.input_data['tree_def'], m.input_data['flat'])\n+```\n+\n# Calling TensorFlow functions from JAX\nThe function ```call_tf``` allows JAX functions to call\n" } ]
Python
Apache License 2.0
google/jax
update jax2tf README: add walkaround about tf.Module magic conversion. Here we will use tree_util.flatten and unflatten to provide a general walkwaround for tfModule Dict->_DictWrapper conversion. It will works for List and Tuple. PiperOrigin-RevId: 457597147
260,510
27.06.2022 18:20:13
25,200
c4b938ffbea68b4d7407da37f77c35126ddc99ad
Add `jvp` rule for `for_loop`
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "# limitations under the License.\n\"\"\"Module for the `for_loop` primitive.\"\"\"\nfrom functools import partial\n+import operator\nfrom typing import Any, Callable, Dict, Generic, List, Sequence, Tuple, TypeVar\n@@ -31,6 +32,8 @@ from jax._src import pretty_printer as pp\nfrom jax._src.util import safe_map, safe_zip, split_list\nimport jax.numpy as jnp\n+from jax._src.lax.control_flow import loops\n+\n## JAX utilities\nmap, unsafe_map = safe_map, map\n@@ -268,7 +271,7 @@ def _swap_jvp(primals: List[Any], tangents: List[Any]):\nref_tangent, x_tangent, *_ = tangents\nassert isinstance(ref_tangent.aval, ShapedArrayRef)\nx_tangent = ad_util.instantiate(x_tangent)\n- return (ref_swap(ref_tangent, idx, x_primal), # type: ignore[arg-type]\n+ return (ref_swap(ref_primal, idx, x_primal), # type: ignore[arg-type]\nref_swap(ref_tangent, idx, x_tangent)) # type: ignore[arg-type]\nad.primitive_jvps[swap_p] = _swap_jvp\n@@ -498,3 +501,67 @@ def _for_impl(*args, jaxpr, nsteps, reverse, which_linear):\nreturn state\nmlir.register_lowering(for_p, mlir.lower_fun(_for_impl, multiple_results=True))\nfor_p.def_impl(partial(xla.apply_primitive, for_p))\n+\n+def _for_jvp(primals, tangents, *, jaxpr, nsteps, reverse, which_linear):\n+ nonzero_tangents = [not isinstance(t, ad_util.Zero) for t in tangents]\n+ # We need to find out which `Ref`s have nonzero tangents after running the\n+ # for loop. Ordinarily we do this with a fixed point on the body jaxpr but\n+ # a `for` body jaxpr is stateful and has no outputs. We therefore discharge\n+ # the state effect from the jaxpr and we will now have a \"symmetric\" jaxpr\n+ # where the inputs line up with the outputs. We use this discharged jaxpr\n+ # for the fixed point.\n+ discharged_jaxpr, body_consts = discharge_state(jaxpr, ())\n+ for _ in range(len(nonzero_tangents)):\n+ _, out_nonzero_tangents = ad.jvp_jaxpr(\n+ core.ClosedJaxpr(discharged_jaxpr, body_consts),\n+ [False] + nonzero_tangents, instantiate=nonzero_tangents)\n+ if out_nonzero_tangents == nonzero_tangents:\n+ break\n+ nonzero_tangents = map(operator.or_, nonzero_tangents, out_nonzero_tangents)\n+ else:\n+ raise Exception(\"Invalid fixpoint\")\n+ tangents = [ad.instantiate_zeros(t) if inst else t for t, inst in\n+ zip(tangents, nonzero_tangents)]\n+ tangents = [t for t in tangents if type(t) is not ad_util.Zero]\n+ closed_jaxpr = core.ClosedJaxpr(jaxpr, ())\n+ jvp_jaxpr_, _ = ad.jvp_jaxpr(closed_jaxpr, [False] + nonzero_tangents, [])\n+ jvp_jaxpr, jvp_consts = jvp_jaxpr_.jaxpr, jvp_jaxpr_.consts\n+ jvp_which_linear = ((False,) * len(jvp_consts) + which_linear\n+ + (True,) * len(tangents))\n+ out_flat = for_p.bind(*jvp_consts, *primals, *tangents, jaxpr=jvp_jaxpr,\n+ nsteps=nsteps, reverse=reverse,\n+ which_linear=jvp_which_linear)\n+ # `out_flat` includes constant inputs into the `for_loop` which are\n+ # converted into outputs as well. We don't care about these in AD so we\n+ # throw them out.\n+ _, out_primals, out_tangents = split_list(out_flat,\n+ [len(jvp_consts), len(primals)])\n+ out_tangents_iter = iter(out_tangents)\n+ out_tangents = [next(out_tangents_iter) if nz else ad_util.Zero.from_value(p)\n+ for p, nz in zip(out_primals, nonzero_tangents)]\n+ return out_primals, out_tangents\n+ad.primitive_jvps[for_p] = _for_jvp\n+\n+\n+### Testing utility\n+\n+def discharged_for_loop(nsteps, body, init_state):\n+ \"\"\"A `for_loop` implementation that discharges its body right away.\n+\n+ Potentially useful for testing and benchmarking.\n+ \"\"\"\n+ flat_state, state_tree = tree_flatten(init_state)\n+ state_avals = map(val_to_ref_aval, flat_state)\n+ idx_aval = core.ShapedArray((), jnp.dtype(\"int32\"))\n+ jaxpr, consts, out_tree = _trace_to_jaxpr_with_refs(\n+ body, state_tree, [idx_aval, *state_avals])\n+ if out_tree != tree_structure(None):\n+ raise Exception(\"`body` should not return anything.\")\n+ discharged_jaxpr, discharged_consts = discharge_state(jaxpr, consts)\n+\n+ def fori_body(i, carry):\n+ out_flat = core.eval_jaxpr(discharged_jaxpr, discharged_consts,\n+ jnp.int32(i), *carry)\n+ return out_flat\n+ out_flat = loops.fori_loop(0, nsteps, fori_body, flat_state)\n+ return tree_unflatten(state_tree, out_flat)\n" } ]
Python
Apache License 2.0
google/jax
Add `jvp` rule for `for_loop` Co-authored-by: Matthew Johnson <mattjj@google.com>
260,510
27.06.2022 18:20:32
25,200
e1ba52bb256fdcfd6b9ba08c265c82cd91efc876
Add tests for `jvp(for_loop)`
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -2882,5 +2882,98 @@ class ForLoopTest(jtu.JaxTestCase):\nx = jax.random.normal(key, (8,))\nnp.testing.assert_allclose(cumsum(x), jnp.cumsum(x))\n+def for_body_swap(i, refs):\n+ a_ref, b_ref = refs\n+ a, b = a_ref[i], b_ref[i]\n+ b_ref[i] = a\n+ a_ref[i] = b\n+\n+def swap_ref(a, b):\n+ return b, a\n+\n+def for_body_swap_swap(i, refs):\n+ for_body_swap(i, refs)\n+ for_body_swap(i, refs)\n+\n+swap_swap_ref = lambda a, b: (a, b)\n+\n+def for_body_sincos(i, refs):\n+ a_ref, b_ref = refs\n+ a = a_ref[i]\n+ b_ref[i] = jnp.sin(jnp.cos(a))\n+\n+sincos_ref = lambda x, y: (x, jnp.sin(jnp.cos(x)))\n+\n+def for_body_sincostan(i, refs):\n+ a_ref, b_ref = refs\n+ a = a_ref[i]\n+ b_ref[i] = jnp.tan(jnp.sin(jnp.cos(a)))\n+\n+sincostan_ref = lambda x, y: (x, jnp.tan(jnp.sin(jnp.cos(x))))\n+\n+def for_body_accum(i, refs):\n+ x_ref, accum_ref = refs\n+ accum_ref[i + 1] = accum_ref[i] + x_ref[i]\n+\n+def accum_ref(x, accum):\n+ for i in range(x.shape[0] - 1):\n+ accum = accum.at[i + 1].set(accum[i] + x[i])\n+ return x, accum\n+\n+def for_body_sin_sq(i, refs):\n+ x_ref, y_ref = refs\n+ x = x_ref[i]\n+ y = x\n+ y_ref[i] = y\n+ y = y_ref[i]\n+ y_ref[i] = jnp.sin(y * y)\n+\n+sin_sq_ref = lambda x, y: (x, jnp.sin(x * x))\n+\n+def for_body_reverse(i, refs):\n+ x_ref, y_ref = refs\n+ j = y_ref.shape[0] - i - 1\n+ y_ref[i] = x_ref[j]\n+\n+reverse_ref = lambda x, y: (x, x[::-1])\n+\n+identity = lambda x, y: (x, y)\n+for_reference = for_loop.discharged_for_loop\n+\n+\n+class ForLoopTransformationTest(jtu.JaxTestCase):\n+\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_jit_for={}_f={}_nsteps={}\".format(\n+ jit_for, for_body_name, nsteps),\n+ \"jit_for\": jit_for, \"f\": for_body, \"body_shapes\": body_shapes,\n+ \"ref\": ref, \"n\": nsteps}\n+ for jit_for in [False, True]\n+ for for_body_name, for_body, ref, body_shapes, nsteps in [\n+ (\"swap\", for_body_swap, swap_ref, [(4,), (4,)], 4),\n+ (\"swap_swap\", for_body_swap_swap, swap_swap_ref, [(4,), (4,)], 4),\n+ (\"sincos\", for_body_sincos, sincos_ref, [(4,), (4,)], 4),\n+ (\"sincostan\", for_body_sincostan, sincostan_ref, [(4,), (4,)], 4),\n+ (\"accum\", for_body_accum, accum_ref, [(4,), (4,)], 3),\n+ (\"sin_sq\", for_body_sin_sq, sin_sq_ref, [(4,), (4,)], 4),\n+ (\"reverse\", for_body_reverse, reverse_ref, [(4,), (4,)], 4),\n+ ])\n+ def test_for_jvp(self, jit_for, f, ref, body_shapes, n):\n+ for_ = for_loop.for_loop\n+ rng = self.rng()\n+\n+ args = [rng.randn(*s) for s in body_shapes]\n+\n+ if jit_for:\n+ for_ = jax.jit(for_, static_argnums=(0, 1))\n+ tol = {np.float64: 1e-12, np.float32: 1e-4}\n+ ans = jax.jvp( lambda *args: for_( n, f, args), args, args)\n+ ans_discharged = jax.jvp(lambda *args: for_reference(n, f, args), args, args)\n+ expected = jax.jvp(ref, args, args)\n+ self.assertAllClose(ans, ans_discharged, check_dtypes=True, rtol=tol, atol=tol)\n+ self.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\n+ jtu.check_grads(partial(for_, n, f), (args,), order=3, modes=[\"fwd\"])\n+\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add tests for `jvp(for_loop)`
260,523
28.06.2022 13:11:23
18,000
cc8e30293367837cf1b4636ae90159b81381b5c5
Update ci-build.yaml Update ci-build.yaml
[ { "change_type": "MODIFY", "old_path": ".github/workflows/ci-build.yaml", "new_path": ".github/workflows/ci-build.yaml", "diff": "@@ -31,7 +31,7 @@ jobs:\nuses: actions/setup-python@v4\nwith:\npython-version: 3.8\n- - uses: pre-commit/action@v2.0.3\n+ - uses: pre-commit/action@v3.0.0\nbuild:\nname: \"build ${{ matrix.name-prefix }} (py ${{ matrix.python-version }} on ${{ matrix.os }}, x64=${{ matrix.enable-x64}})\"\n" } ]
Python
Apache License 2.0
google/jax
Update ci-build.yaml Update ci-build.yaml
260,510
28.06.2022 13:01:27
25,200
1daea700f299567c46d151623c2444db902f644f
Bump JAX/Jaxlib versions
[ { "change_type": "MODIFY", "old_path": "docs/jax.lib.rst", "new_path": "docs/jax.lib.rst", "diff": "@@ -35,5 +35,4 @@ jax.lib.xla_extension\n:toctree: _autosummary\nDevice\n- GpuDevice\nTpuDevice\n" }, { "change_type": "MODIFY", "old_path": "jax/version.py", "new_path": "jax/version.py", "diff": "def _version_as_tuple(version_str):\nreturn tuple(int(i) for i in version_str.split(\".\") if i.isdigit())\n-__version__ = \"0.3.14\"\n+__version__ = \"0.3.15\"\n__version_info__ = _version_as_tuple(__version__)\n_minimum_jaxlib_version = \"0.3.7\"\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/version.py", "new_path": "jaxlib/version.py", "diff": "# reflect the most recent available binaries.\n# __version__ should be increased after releasing the current version\n# (i.e. on main, this is always the next version to be released).\n-__version__ = \"0.3.14\"\n+__version__ = \"0.3.15\"\n" }, { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "@@ -16,7 +16,7 @@ from setuptools import setup, find_packages\n_current_jaxlib_version = '0.3.14'\n# The following should be updated with each new jaxlib release.\n-_latest_jaxlib_version_on_pypi = '0.3.10'\n+_latest_jaxlib_version_on_pypi = '0.3.14'\n_available_cuda_versions = ['11']\n_default_cuda_version = '11'\n_available_cudnn_versions = ['82', '805']\n" } ]
Python
Apache License 2.0
google/jax
Bump JAX/Jaxlib versions
260,510
28.06.2022 15:13:10
25,200
fcf65ac64eff9435920d36f7695ac6b0908ce49e
Bump minimum jaxlib version to 0.3.10
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -1653,11 +1653,7 @@ def _tan_impl(x):\ntan_p = standard_unop(_float | _complex, 'tan')\nad.defjvp2(tan_p, lambda g, ans, x: mul(g, _const(x, 1) + square(ans)))\n-if jax._src.lib.mlir_api_version >= 11:\nmlir.register_lowering(tan_p, partial(_nary_lower_mhlo, chlo.TanOp))\n-else:\n- mlir.register_lowering(tan_p,\n- mlir.lower_fun(_tan_impl, multiple_results=False))\ndef asin_impl(x):\nif dtypes.issubdtype(_dtype(x), np.complexfloating):\n@@ -1713,35 +1709,21 @@ mlir.register_lowering(sinh_p, partial(_nary_lower_mhlo, chlo.SinhOp))\ncosh_p = standard_unop(_float | _complex, 'cosh')\nad.defjvp(cosh_p, lambda g, x: mul(g, sinh(x)))\n-if jax._src.lib.mlir_api_version >= 10:\n- mlir.register_lowering(cosh_p, partial(_nary_lower_mhlo, chlo.CoshOp))\n-else:\n- xla.register_translation(cosh_p, standard_translate(cosh_p))\n- if jax._src.lib.mlir_api_version >= 8:\nmlir.register_lowering(cosh_p, partial(_nary_lower_mhlo, chlo.CoshOp))\nasinh_p = standard_unop(_float | _complex, 'asinh')\nad.defjvp(asinh_p, lambda g, x: mul(g, rsqrt(square(x) + _one(x))))\n-if jax._src.lib.mlir_api_version >= 10:\nmlir.register_lowering(asinh_p, partial(_nary_lower_mhlo, chlo.AsinhOp))\n-else:\n- xla.register_translation(asinh_p, standard_translate(asinh_p))\nacosh_p = standard_unop(_float | _complex, 'acosh')\nad.defjvp(acosh_p,\nlambda g, x: mul(g, rsqrt((x - _one(x)) * (x + _one(x)))))\n-if jax._src.lib.mlir_api_version >= 10:\nmlir.register_lowering(acosh_p, partial(_nary_lower_mhlo, chlo.AcoshOp))\n-else:\n- xla.register_translation(acosh_p, standard_translate(acosh_p))\natanh_p = standard_unop(_float | _complex, 'atanh')\nad.defjvp(atanh_p,\nlambda g, x: mul(reciprocal(_one(x) + x), div(g, (_one(x) - x))))\n-if jax._src.lib.mlir_api_version >= 10:\nmlir.register_lowering(atanh_p, partial(_nary_lower_mhlo, chlo.AtanhOp))\n-else:\n- xla.register_translation(atanh_p, standard_translate(atanh_p))\nregularized_incomplete_beta_p = standard_naryop(\n[_float, _float, _float], 'regularized_incomplete_beta')\n@@ -1816,18 +1798,12 @@ ad.defjvp2(bessel_i1e_p, _bessel_i1e_jvp)\nerf_p = standard_unop(_float, 'erf')\nad.defjvp(erf_p, lambda g, x: mul(_const(x, 2. / np.sqrt(np.pi)),\nmul(g, exp(neg(square(x))))))\n-if jax._src.lib.mlir_api_version >= 12:\nmlir.register_lowering(erf_p, partial(_nary_lower_mhlo, chlo.ErfOp))\n-else:\n- xla.register_translation(erf_p, standard_translate(erf_p))\nerfc_p = standard_unop(_float, 'erfc')\nad.defjvp(erfc_p, lambda g, x: mul(_const(x, -2. / np.sqrt(np.pi)),\nmul(g, exp(neg(square(x))))))\n-if jax._src.lib.mlir_api_version >= 12:\nmlir.register_lowering(erfc_p, partial(_nary_lower_mhlo, chlo.ErfcOp))\n-else:\n- xla.register_translation(erfc_p, standard_translate(erfc_p))\nerf_inv_p = standard_unop(_float, 'erf_inv')\nad.defjvp2(erf_inv_p, lambda g, ans, x: mul(_const(x, np.sqrt(np.pi) / 2.),\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/slicing.py", "new_path": "jax/_src/lax/slicing.py", "diff": "@@ -905,12 +905,6 @@ ad.primitive_transposes[dynamic_slice_p] = _dynamic_slice_transpose_rule\nbatching.primitive_batchers[dynamic_slice_p] = _dynamic_slice_batching_rule\ndef _dynamic_slice_lower(ctx, x, *start_indices, slice_sizes):\n- if jax._src.lib.mlir_api_version < 13:\n- aval_out, = ctx.avals_out\n- return mhlo.DynamicSliceOp(mlir.aval_to_ir_type(aval_out), x,\n- start_indices,\n- mlir.dense_int_elements(slice_sizes)).results\n- else:\nreturn mhlo.DynamicSliceOp(x, start_indices,\nmlir.dense_int_elements(slice_sizes)).results\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/windowed_reductions.py", "new_path": "jax/_src/lax/windowed_reductions.py", "diff": "@@ -646,14 +646,8 @@ def _select_and_gather_add_lowering(\nconst = lambda dtype, x: mlir.ir_constant(np.array(x, dtype=dtype),\ncanonicalize_types=False)\n- if jax._src.lib.mlir_api_version >= 9:\ndef _broadcast(x, dims):\nreturn mhlo.BroadcastOp(x, mlir.dense_int_elements(dims))\n- else:\n- def _broadcast(x, dims):\n- etype = ir.RankedTensorType(x.type).element_type\n- return mhlo.BroadcastOp(ir.RankedTensorType(dims, etype), x,\n- mlir.dense_int_elements(dims))\nif double_word_reduction:\n# TODO(b/73062247): XLA doesn't yet implement ReduceWindow on tuples, so\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -1011,8 +1011,7 @@ def _outside_call_translation_rule(ctx, avals_in, avals_out,\nuse_outfeed = _use_outfeed(ctx.platform)\n# TODO(sharadmv): Delete non-outfeed path when jaxlib minimum version is\n# bumped past 0.3.8.\n- assert use_outfeed or jaxlib.version < (0, 3, 8), (\n- 'Should be using MLIR path for `CustomCall` lowering')\n+ assert use_outfeed, 'Should be using MLIR path for `CustomCall` lowering'\nsend_infeed = use_outfeed and need_callback_results_on_device\ngenerated_infeed = False # Keep track if we emitted an infeed op\nif use_outfeed:\n@@ -1198,7 +1197,6 @@ def _outside_call_lowering(\nf\"identity = {identity}\")\nreturn results + [next_token, next_itoken]\n-if jaxlib.version >= (0, 3, 8):\nmlir.register_lowering(outside_call_p, _outside_call_lowering, platform=\"cpu\")\ndef _outside_call_run_callback(\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -208,7 +208,6 @@ def _numpy_array_constant(x: np.ndarray, canonicalize_types\nif canonicalize_types:\nx = np.asarray(x, dtypes.canonicalize_dtype(x.dtype))\nelement_type = dtype_to_ir_type(x.dtype)\n- ir_type = ir.RankedTensorType.get(x.shape, element_type)\nshape = x.shape\nif x.dtype == np.bool_:\nnelems = x.size\n@@ -222,15 +221,9 @@ def _numpy_array_constant(x: np.ndarray, canonicalize_types\nx = np.ascontiguousarray(x)\nattr = ir.DenseElementsAttr.get(x, type=element_type, shape=shape)\nif jax._src.lib.mlir_api_version < 21:\n- if jax._src.lib.xla_extension_version >= 64:\nreturn (mhlo.ConstOp(attr).result,)\nelse:\n- return (mhlo.ConstOp(ir_type, attr).result,)\n- else:\n- if jax._src.lib.xla_extension_version >= 64:\nreturn (mhlo.ConstantOp(attr).result,)\n- else:\n- return (mhlo.ConstantOp(ir_type, attr).result,)\n@@ -1047,10 +1040,6 @@ register_lowering(core.closed_call_p,\ndef full_like_aval(value, aval: core.ShapedArray) -> ir.Value:\n\"\"\"Returns an IR constant shaped full of `value` shaped like `aval`.\"\"\"\nzero = ir_constant(np.array(value, aval.dtype))\n- if jax._src.lib.mlir_api_version < 9:\n- return mhlo.BroadcastOp(aval_to_ir_type(aval), zero,\n- dense_int_elements(aval.shape)).result\n- else:\nreturn mhlo.BroadcastOp(zero, dense_int_elements(aval.shape)).result\n" }, { "change_type": "MODIFY", "old_path": "jax/version.py", "new_path": "jax/version.py", "diff": "@@ -18,5 +18,5 @@ def _version_as_tuple(version_str):\n__version__ = \"0.3.15\"\n__version_info__ = _version_as_tuple(__version__)\n-_minimum_jaxlib_version = \"0.3.7\"\n+_minimum_jaxlib_version = \"0.3.10\"\n_minimum_jaxlib_version_info = _version_as_tuple(_minimum_jaxlib_version)\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/pocketfft.py", "new_path": "jaxlib/pocketfft.py", "diff": "@@ -149,12 +149,6 @@ def pocketfft_mhlo(a, dtype, *, fft_type: FftType, fft_lengths: List[int]):\nir.RankedTensorType.get([], out_type),\nir.DenseElementsAttr.get(\nnp.array(0, dtype=out_dtype), type=out_type))\n- if jax._src.lib.mlir_api_version < 9:\n- return mhlo.BroadcastOp(\n- ir.RankedTensorType.get(out_shape, out_type),\n- zero,\n- ir.DenseElementsAttr.get(np.asarray(out_shape, np.int64))).result\n- else:\nreturn mhlo.BroadcastOp(\nzero,\nir.DenseElementsAttr.get(np.asarray(out_shape, np.int64))).result\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -401,11 +401,5 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\nlines = [f\"{i}\\n\" for i in range(40)]\nself._assertLinesEqual(output(), \"\".join(lines))\n-if jaxlib.version < (0, 3, 8):\n- # No lowering for `emit_python_callback` in older jaxlibs.\n- del DebugPrintTest\n- del DebugPrintControlFlowTest\n- del DebugPrintParallelTest\n-\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -578,11 +578,8 @@ class EffectOrderingTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_can_execute_python_callback(self):\n- # TODO(sharadmv): remove jaxlib check when minimum version is bumped\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n# supported\n- if jaxlib.version < (0, 3, 8):\n- raise unittest.SkipTest(\"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\nlog = []\ndef log_value(x):\nlog.append(x)\n@@ -600,11 +597,8 @@ class EffectOrderingTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_ordered_effect_remains_ordered_across_multiple_devices(self):\n- # TODO(sharadmv): remove jaxlib check when minimum version is bumped\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n# supported\n- if jaxlib.version < (0, 3, 8):\n- raise unittest.SkipTest(\"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\nif jax.device_count() < 2:\nraise unittest.SkipTest(\"Test requires >= 2 devices.\")\nlog = []\n@@ -636,11 +630,8 @@ class EffectOrderingTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_different_threads_get_different_tokens(self):\n- # TODO(sharadmv): remove jaxlib check when minimum version is bumped\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n# supported\n- if jaxlib.version < (0, 3, 8):\n- raise unittest.SkipTest(\"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\nif jax.device_count() < 2:\nraise unittest.SkipTest(\"Test requires >= 2 devices.\")\ntokens = []\n@@ -693,11 +684,8 @@ class ParallelEffectsTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_can_pmap_unordered_callback(self):\n- # TODO(sharadmv): remove jaxlib check when minimum version is bumped\n# TODO(sharadmv): enable this test on GPU and TPU when backends are\n# supported\n- if jaxlib.version < (0, 3, 8):\n- raise unittest.SkipTest(\"`emit_python_callback` only supported in jaxlib >= 0.3.8\")\nif jax.device_count() < 2:\nraise unittest.SkipTest(\"Test requires >= 2 devices.\")\nlog = set()\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -41,8 +41,6 @@ T = lambda x: np.swapaxes(x, -1, -2)\nfloat_types = jtu.dtypes.floating\ncomplex_types = jtu.dtypes.complex\n-jaxlib_version = jax._src.lib.version\n-\nclass NumpyLinalgTest(jtu.JaxTestCase):\n@@ -739,7 +737,6 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nqr = partial(jnp.linalg.qr, mode=mode)\njtu.check_jvp(qr, partial(jvp, qr), (a,), atol=3e-3)\n- @unittest.skipIf(jaxlib_version < (0, 3, 8), \"test requires jaxlib>=0.3.8\")\n@jtu.skip_on_devices(\"tpu\")\ndef testQrInvalidDtypeCPU(self, shape=(5, 6), dtype=np.float16):\n# Regression test for https://github.com/google/jax/issues/10530\n" } ]
Python
Apache License 2.0
google/jax
Bump minimum jaxlib version to 0.3.10
260,510
28.06.2022 10:28:45
25,200
e8bd71b31cb354a52eda390ed45a830a0adf7912
Add JAX debugger
[ { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/debugger/__init__.py", "diff": "+# Copyright 2022 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+from jax._src.debugger.cli_debugger import breakpoint\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/debugger/cli_debugger.py", "diff": "+# Copyright 2022 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+from __future__ import annotations\n+\n+import cmd\n+import dataclasses\n+import inspect\n+import sys\n+import threading\n+import traceback\n+\n+from typing import Any, Callable, Dict, IO, List, Optional\n+\n+import numpy as np\n+from jax import core\n+from jax import tree_util\n+from jax._src import debugging\n+from jax._src import traceback_util\n+from jax._src import util\n+import jax.numpy as jnp\n+\n+\n+@tree_util.register_pytree_node_class\n+@dataclasses.dataclass(frozen=True)\n+class DebuggerFrame:\n+ \"\"\"Encapsulates Python frame information.\"\"\"\n+ filename: str\n+ locals: Dict[str, Any]\n+ code_context: str\n+ source: List[str]\n+ lineno: int\n+ offset: Optional[int]\n+\n+ def tree_flatten(self):\n+ flat_locals, locals_tree = tree_util.tree_flatten(self.locals)\n+ is_valid = [\n+ isinstance(l, (core.Tracer, jnp.ndarray, np.ndarray))\n+ for l in flat_locals\n+ ]\n+ invalid_locals, valid_locals = util.partition_list(is_valid, flat_locals)\n+ return valid_locals, (is_valid, invalid_locals, locals_tree, self.filename,\n+ self.code_context, self.source, self.lineno,\n+ self.offset)\n+\n+ @classmethod\n+ def tree_unflatten(cls, info, valid_locals):\n+ (is_valid, invalid_locals, locals_tree, filename, code_context, source,\n+ lineno, offset) = info\n+ flat_locals = util.merge_lists(is_valid, invalid_locals, valid_locals)\n+ locals_ = tree_util.tree_unflatten(locals_tree, flat_locals)\n+ return DebuggerFrame(filename, locals_, code_context, source, lineno,\n+ offset)\n+\n+ @classmethod\n+ def from_frameinfo(cls, frame_info) -> DebuggerFrame:\n+ try:\n+ _, start = inspect.getsourcelines(frame_info.frame)\n+ source = inspect.getsource(frame_info.frame).split('\\n')\n+ offset = frame_info.lineno - start\n+ except OSError:\n+ source = []\n+ offset = None\n+ return DebuggerFrame(\n+ filename=frame_info.filename,\n+ locals=frame_info.frame.f_locals,\n+ code_context=frame_info.code_context,\n+ source=source,\n+ lineno=frame_info.lineno,\n+ offset=offset)\n+\n+\n+debug_lock = threading.Lock()\n+\n+\n+def breakpoint(*, ordered: bool = False, **kwargs): # pylint: disable=redefined-builtin\n+ \"\"\"Enters a breakpoint at a point in a program.\"\"\"\n+ frame_infos = inspect.stack()\n+ # Filter out internal frames\n+ frame_infos = [\n+ frame_info for frame_info in frame_infos\n+ if traceback_util.include_frame(frame_info.frame)\n+ ]\n+ frames = [\n+ DebuggerFrame.from_frameinfo(frame_info) for frame_info in frame_infos\n+ ]\n+ # Throw out first frame corresponding to this function\n+ frames = frames[1:]\n+ flat_args, frames_tree = tree_util.tree_flatten(frames)\n+\n+ def _breakpoint_callback(*flat_args):\n+ frames = tree_util.tree_unflatten(frames_tree, flat_args)\n+ thread_id = None\n+ if threading.current_thread() is not threading.main_thread():\n+ thread_id = threading.get_ident()\n+ with debug_lock:\n+ TextDebugger(frames, thread_id, **kwargs).run()\n+\n+ if ordered:\n+ effect = debugging.DebugEffect.ORDERED_PRINT\n+ else:\n+ effect = debugging.DebugEffect.PRINT\n+ debugging.debug_callback(_breakpoint_callback, effect, *flat_args)\n+\n+\n+class TextDebugger(cmd.Cmd):\n+ \"\"\"A text-based debugger.\"\"\"\n+ prompt = '(jaxdb) '\n+ use_rawinput: bool = False\n+\n+ def __init__(self, frames: List[DebuggerFrame], thread_id,\n+ stdin: Optional[IO[str]] = None, stdout: Optional[IO[str]] = None,\n+ completekey: str = \"tab\"):\n+ super().__init__(stdin=stdin, stdout=stdout, completekey=completekey)\n+ self.frames = frames\n+ self.frame_index = 0\n+ self.thread_id = thread_id\n+ self.intro = 'Entering jaxdb:'\n+\n+ def current_frame(self):\n+ return self.frames[self.frame_index]\n+\n+ def evaluate(self, expr):\n+ env = {}\n+ curr_frame = self.frames[self.frame_index]\n+ env.update(curr_frame.locals)\n+ return eval(expr, {}, env)\n+\n+ def print_backtrace(self):\n+ self.stdout.write('Traceback:\\n')\n+ for frame in self.frames[::-1]:\n+ self.stdout.write(f' File \"{frame.filename}\", line {frame.lineno}\\n')\n+ if frame.offset is None:\n+ self.stdout.write(' <no source>\\n')\n+ else:\n+ line = frame.source[frame.offset]\n+ self.stdout.write(f' {line}\\n')\n+\n+ def print_context(self, num_lines=2):\n+ curr_frame = self.frames[self.frame_index]\n+ self.stdout.write(f'> {curr_frame.filename}({curr_frame.lineno})\\n')\n+ for i, line in enumerate(curr_frame.source):\n+ assert curr_frame.offset is not None\n+ if (curr_frame.offset - 1 - num_lines <= i <=\n+ curr_frame.offset + num_lines):\n+ if i == curr_frame.offset:\n+ self.stdout.write(f'-> {line}\\n')\n+ else:\n+ self.stdout.write(f' {line}\\n')\n+\n+ def do_p(self, arg):\n+ try:\n+ self.stdout.write(repr(self.evaluate(arg)) + \"\\n\")\n+ except Exception:\n+ traceback.print_exc(limit=1)\n+\n+ def do_u(self, arg):\n+ if self.frame_index == len(self.frames) - 1:\n+ self.stdout.write('At topmost frame.\\n')\n+ else:\n+ self.frame_index += 1\n+ self.print_context()\n+\n+ def do_d(self, arg):\n+ if self.frame_index == 0:\n+ self.stdout.write('At bottommost frame.\\n')\n+ else:\n+ self.frame_index -= 1\n+ self.print_context()\n+\n+ def do_l(self, arg):\n+ self.print_context(num_lines=5)\n+\n+ def do_ll(self, arg):\n+ self.print_context(num_lines=5)\n+\n+ def do_c(self, arg):\n+ return True\n+\n+ def do_EOF(self, arg):\n+ sys.exit(0)\n+\n+ def do_bt(self, arg):\n+ self.print_backtrace()\n+\n+ def run(self):\n+ while True:\n+ try:\n+ self.cmdloop()\n+ break\n+ except KeyboardInterrupt:\n+ self.stdout.write('--KeyboardInterrupt--\\n')\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/debugger_test.py", "diff": "+# Copyright 2022 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+import io\n+import textwrap\n+import unittest\n+\n+from typing import IO, Sequence, Tuple\n+\n+from absl.testing import absltest\n+import jax\n+from jax.config import config\n+from jax._src import debugger\n+from jax._src import lib as jaxlib\n+from jax._src import test_util as jtu\n+import jax.numpy as jnp\n+\n+config.parse_flags_with_absl()\n+\n+def make_fake_stdin_stdout(commands: Sequence[str]) -> Tuple[IO[str], io.StringIO]:\n+ fake_stdin = io.StringIO()\n+ fake_stdin.truncate(0)\n+ for command in commands:\n+ fake_stdin.write(command + \"\\n\")\n+ fake_stdin.seek(0)\n+ return fake_stdin, io.StringIO()\n+\n+def _format_multiline(text):\n+ return textwrap.dedent(text).lstrip()\n+\n+prev_xla_flags = None\n+\n+def setUpModule():\n+ global prev_xla_flags\n+ # This will control the CPU devices. On TPU we always have 2 devices\n+ prev_xla_flags = jtu.set_host_platform_device_count(2)\n+\n+# Reset to previous configuration in case other test modules will be run.\n+def tearDownModule():\n+ prev_xla_flags()\n+\n+# TODO(sharadmv): remove jaxlib guards for GPU tests when jaxlib minimum\n+# version is >= 0.3.11\n+disabled_backends = [\"tpu\"]\n+if jaxlib.version < (0, 3, 11):\n+ disabled_backends.append(\"gpu\")\n+\n+class CliDebuggerTest(jtu.JaxTestCase):\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_eof(self):\n+ stdin, stdout = make_fake_stdin_stdout([])\n+\n+ def f(x):\n+ y = jnp.sin(x)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+ with self.assertRaises(SystemExit):\n+ f(2.)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_can_continue(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"c\"])\n+\n+ def f(x):\n+ y = jnp.sin(x)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+ f(2.)\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ (jaxdb) \"\"\")\n+ self.assertEqual(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_can_print_value(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"p x\", \"c\"])\n+\n+ def f(x):\n+ y = jnp.sin(x)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ (jaxdb) DeviceArray(2., dtype=float32)\n+ (jaxdb) \"\"\")\n+ f(jnp.array(2., jnp.float32))\n+ self.assertEqual(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_can_print_value_in_jit(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"p x\", \"c\"])\n+\n+ @jax.jit\n+ def f(x):\n+ y = jnp.sin(x)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ (jaxdb) array(2., dtype=float32)\n+ (jaxdb) \"\"\")\n+ f(jnp.array(2., jnp.float32))\n+ self.assertEqual(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_can_print_multiple_values(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"p x, y\", \"c\"])\n+\n+ @jax.jit\n+ def f(x):\n+ y = x + 1.\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ (jaxdb) (array(2., dtype=float32), array(3., dtype=float32))\n+ (jaxdb) \"\"\")\n+ f(jnp.array(2., jnp.float32))\n+ self.assertEqual(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_can_print_context(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"l\", \"c\"])\n+\n+ @jax.jit\n+ def f(x):\n+ y = jnp.sin(x)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+ f(2.)\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ \\(jaxdb\\) > .*debugger_test\\.py\\([0-9]+\\)\n+ @jax\\.jit\n+ def f\\(x\\):\n+ y = jnp\\.sin\\(x\\)\n+ -> debugger\\.breakpoint\\(stdin=stdin, stdout=stdout\\)\n+ return y\n+ .*\n+ \\(jaxdb\\) \"\"\")\n+ self.assertRegex(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_can_print_backtrace(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"bt\", \"c\"])\n+\n+ @jax.jit\n+ def f(x):\n+ y = jnp.sin(x)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:.*\n+ \\(jaxdb\\) Traceback:.*\n+ \"\"\")\n+ f(2.)\n+ self.assertRegex(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_can_work_with_multiple_stack_frames(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"l\", \"u\", \"p x\", \"d\", \"c\"])\n+\n+ def f(x):\n+ y = jnp.sin(x)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+\n+ @jax.jit\n+ def g(x):\n+ y = f(x)\n+ return jnp.exp(y)\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ \\(jaxdb\\) > .*debugger_test\\.py\\([0-9]+\\)\n+ def f\\(x\\):\n+ y = jnp\\.sin\\(x\\)\n+ -> debugger\\.breakpoint\\(stdin=stdin, stdout=stdout\\)\n+ return y\n+ .*\n+ \\(jaxdb\\) > .*debugger_test\\.py\\([0-9]+\\).*\n+ @jax\\.jit\n+ def g\\(x\\):\n+ -> y = f\\(x\\)\n+ return jnp\\.exp\\(y\\)\n+ .*\n+ \\(jaxdb\\) array\\(2\\., dtype=float32\\)\n+ \\(jaxdb\\) > .*debugger_test\\.py\\([0-9]+\\)\n+ def f\\(x\\):\n+ y = jnp\\.sin\\(x\\)\n+ -> debugger\\.breakpoint\\(stdin=stdin, stdout=stdout\\)\n+ return y\n+ .*\n+ \\(jaxdb\\) \"\"\")\n+ g(jnp.array(2., jnp.float32))\n+ self.assertRegex(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_can_use_multiple_breakpoints(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"p y\", \"c\", \"p y\", \"c\"])\n+\n+ def f(x):\n+ y = x + 1.\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, ordered=True)\n+ return y\n+\n+ @jax.jit\n+ def g(x):\n+ y = f(x) * 2.\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, ordered=True)\n+ return jnp.exp(y)\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ (jaxdb) array(3., dtype=float32)\n+ (jaxdb) Entering jaxdb:\n+ (jaxdb) array(6., dtype=float32)\n+ (jaxdb) \"\"\")\n+ g(jnp.array(2., jnp.float32))\n+ jax.effects_barrier()\n+ self.assertEqual(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_works_with_vmap(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"p y\", \"c\", \"p y\", \"c\"])\n+\n+ def f(x):\n+ y = x + 1.\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return 2. * y\n+\n+ @jax.jit\n+ @jax.vmap\n+ def g(x):\n+ y = f(x)\n+ return jnp.exp(y)\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ (jaxdb) array(1., dtype=float32)\n+ (jaxdb) Entering jaxdb:\n+ (jaxdb) array(2., dtype=float32)\n+ (jaxdb) \"\"\")\n+ g(jnp.arange(2., dtype=jnp.float32))\n+ self.assertEqual(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_works_with_pmap(self):\n+ if jax.local_device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices.\")\n+ stdin, stdout = make_fake_stdin_stdout([\"p y\", \"c\", \"p y\", \"c\"])\n+\n+ def f(x):\n+ y = jnp.sin(x)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+\n+ @jax.pmap\n+ def g(x):\n+ y = f(x)\n+ return jnp.exp(y)\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ \\(jaxdb\\) array\\(.*, dtype=float32\\)\n+ \\(jaxdb\\) Entering jaxdb:\n+ \\(jaxdb\\) array\\(.*, dtype=float32\\)\n+ \\(jaxdb\\) \"\"\")\n+ g(jnp.arange(2., dtype=jnp.float32))\n+ self.assertRegex(stdout.getvalue(), expected)\n+\n+if __name__ == '__main__':\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add JAX debugger
260,510
28.06.2022 16:29:38
25,200
790135989da61b1240dbd2e8126ef0d97b753ce6
Add scan implementation using `for` and tests
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "from functools import partial\nimport operator\n-from typing import Any, Callable, Dict, Generic, List, Sequence, Tuple, TypeVar\n+from typing import Any, Callable, Dict, Generic, List, Optional, Sequence, Tuple, TypeVar\nfrom jax import core\nfrom jax import lax\nfrom jax import linear_util as lu\nfrom jax.api_util import flatten_fun_nokwargs\nfrom jax.interpreters import ad\n+from jax.interpreters import masking\nfrom jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\nfrom jax.tree_util import (tree_flatten, tree_structure, tree_unflatten,\n- treedef_tuple, PyTreeDef)\n+ treedef_tuple, tree_map, tree_leaves, PyTreeDef)\nfrom jax._src import ad_util\n+from jax._src import dtypes\nfrom jax._src import pretty_printer as pp\nfrom jax._src.util import safe_map, safe_zip, split_list\nimport jax.numpy as jnp\nfrom jax._src.lax.control_flow import loops\n+from jax._src.lax.control_flow.common import _abstractify, _initial_style_jaxpr\n## JAX utilities\n@@ -433,7 +436,8 @@ def val_to_ref_aval(x) -> ShapedArrayRef:\nraise Exception(f\"can't make ref from {x}\")\nreturn ShapedArrayRef(aval.shape, aval.dtype)\n-def for_loop(nsteps: int, body: Callable[[Array, Ref[S]], None], init_state: S) -> S:\n+def for_loop(nsteps: int, body: Callable[[Array, Ref[S]], None], init_state: S,\n+ *, reverse: bool = False) -> S:\n\"\"\"A for-loop combinator that allows read/write semantics in the loop body.\n`for_loop` is a higher-order function that enables writing loops that can be\n@@ -476,12 +480,81 @@ def for_loop(nsteps: int, body: Callable[[Array, Ref[S]], None], init_state: S)\njaxpr = _hoist_consts_to_refs(jaxpr)\nwhich_linear = (False,) * (len(consts) + len(flat_state))\nout_flat = for_p.bind(*consts, *flat_state, jaxpr=jaxpr, nsteps=int(nsteps),\n- reverse=False, which_linear=which_linear)\n+ reverse=reverse, which_linear=which_linear)\n# Consts are `Ref`s so they are both inputs and outputs. We remove them from\n# the outputs.\nout_flat = out_flat[len(consts):]\nreturn tree_unflatten(state_tree, out_flat)\n+Carry = TypeVar('Carry')\n+X = TypeVar('X')\n+Y = TypeVar('Y')\n+\n+def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\n+ init: Carry,\n+ xs: X,\n+ length: Optional[int] = None,\n+ reverse: bool = False,\n+ unroll: int = 1) -> Tuple[Carry, Y]:\n+ if unroll != 1:\n+ raise NotImplementedError(\"Unroll not implemented\")\n+ if not callable(f):\n+ raise TypeError(\"scan: f argument should be a callable.\")\n+ xs_flat, xs_tree = tree_flatten(xs)\n+\n+ try:\n+ lengths = [x.shape[0] for x in xs_flat]\n+ except AttributeError as err:\n+ msg = \"scan got value with no leading axis to scan over: {}.\"\n+ raise ValueError(\n+ msg.format(', '.join(str(x) for x in xs_flat\n+ if not hasattr(x, 'shape')))) from err\n+\n+ if length is not None:\n+ length = int(length)\n+ if not all(length == l for l in lengths):\n+ msg = (\"scan got `length` argument of {} which disagrees with \"\n+ \"leading axis sizes {}.\")\n+ raise ValueError(msg.format(length, [x.shape[0] for x in xs_flat]))\n+ else:\n+ unique_lengths = set(lengths)\n+ if len(unique_lengths) > 1:\n+ msg = \"scan got values with different leading axis sizes: {}.\"\n+ raise ValueError(msg.format(', '.join(str(x.shape[0]) for x in xs_flat)))\n+ elif len(unique_lengths) == 0:\n+ msg = \"scan got no values to scan over and `length` not provided.\"\n+ raise ValueError(msg)\n+ else:\n+ length, = unique_lengths\n+\n+ x_shapes = [masking.padded_shape_as_value(x.shape[1:]) for x in xs_flat]\n+ x_dtypes = [dtypes.canonicalize_dtype(x.dtype) for x in xs_flat]\n+ x_avals = tuple(map(core.ShapedArray, x_shapes, x_dtypes))\n+\n+ def _create_jaxpr(init):\n+ init_flat = tree_leaves(init)\n+ _, in_tree = tree_flatten((init, xs))\n+\n+ carry_avals = tuple(map(_abstractify, init_flat))\n+ jaxpr, _, out_tree = _initial_style_jaxpr(\n+ f, in_tree, carry_avals + x_avals, \"scan\")\n+ return jaxpr, out_tree\n+ jaxpr, out_tree = _create_jaxpr(init)\n+ _, ys_avals = tree_unflatten(out_tree, jaxpr.out_avals)\n+ ys = tree_map(lambda aval: jnp.zeros([length, *aval.shape], aval.dtype),\n+ ys_avals)\n+ def for_body(i, refs):\n+ carry_refs, xs_refs, ys_refs = refs\n+ carry = tree_map(lambda x: x[()], carry_refs)\n+ x = tree_map(lambda x: x[i], xs_refs)\n+ carry, y = f(carry, x)\n+ tree_map(lambda c_ref, c: ref_set(c_ref, (), c), carry_refs, carry)\n+ tree_map(lambda y_ref, y: ref_set(y_ref, (i,), y), ys_refs, y)\n+ assert isinstance(length, int)\n+ init, _, ys = for_loop(length, for_body, (init, xs, ys), reverse=reverse)\n+ return init, ys\n+\n+\n@for_p.def_abstract_eval\ndef _for_abstract_eval(*avals, jaxpr, **__):\nreturn list(avals)\n@@ -545,7 +618,7 @@ ad.primitive_jvps[for_p] = _for_jvp\n### Testing utility\n-def discharged_for_loop(nsteps, body, init_state):\n+def discharged_for_loop(nsteps, body, init_state, *, reverse: bool = False):\n\"\"\"A `for_loop` implementation that discharges its body right away.\nPotentially useful for testing and benchmarking.\n@@ -560,8 +633,11 @@ def discharged_for_loop(nsteps, body, init_state):\ndischarged_jaxpr, discharged_consts = discharge_state(jaxpr, consts)\ndef fori_body(i, carry):\n+ i = jnp.int32(i)\n+ if reverse:\n+ i = nsteps - i - 1\nout_flat = core.eval_jaxpr(discharged_jaxpr, discharged_consts,\n- jnp.int32(i), *carry)\n+ i, *carry)\nreturn out_flat\nout_flat = loops.fori_loop(0, nsteps, fori_body, flat_state)\nreturn tree_unflatten(state_tree, out_flat)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -70,6 +70,8 @@ def scan_with_new_checkpoint2(f, *args, **kwargs):\nreturn new_checkpoint(partial(lax.scan, f, **kwargs),\npolicy=checkpoint_policies.everything_saveable)(*args)\n+def scan_with_for(f, *args, **kwargs):\n+ return for_loop.scan(f, *args, **kwargs)\nCOND_IMPLS = [\n(lax.cond, 'cond'),\n@@ -84,6 +86,14 @@ SCAN_IMPLS = [\n(scan_with_new_checkpoint2, 'new_checkpoint2'),\n]\n+SCAN_IMPLS_WITH_FOR = [\n+ (lax.scan, 'unroll1'),\n+ (partial(lax.scan, unroll=2), 'unroll2'),\n+ (scan_with_new_checkpoint , 'new_checkpoint'),\n+ (scan_with_new_checkpoint2, 'new_checkpoint2'),\n+ (scan_with_for, 'for'),\n+]\n+\ndef while_loop_reference(cond, body, carry):\nwhile cond(carry):\n@@ -1454,11 +1464,12 @@ class LaxControlFlowTest(jtu.JaxTestCase):\n@parameterized.named_parameters(\n{\"testcase_name\": \"_jit_scan={}_jit_f={}_impl={}\".format(\njit_scan, jit_f, scan_name),\n- \"jit_scan\": jit_scan, \"jit_f\": jit_f, \"scan\": scan_impl}\n+ \"jit_scan\": jit_scan, \"jit_f\": jit_f, \"scan\": scan_impl,\n+ \"impl_name\": scan_name}\nfor jit_scan in [False, True]\nfor jit_f in [False, True]\n- for scan_impl, scan_name in SCAN_IMPLS)\n- def testScanImpl(self, jit_scan, jit_f, scan):\n+ for scan_impl, scan_name in SCAN_IMPLS_WITH_FOR)\n+ def testScanImpl(self, jit_scan, jit_f, scan, impl_name):\nrng = self.rng()\nd = rng.randn(2)\n@@ -1480,12 +1491,17 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nans = scan(f, c, as_)\nexpected = scan_reference(f, c, as_)\n+ rtol = {np.float64: 1.4e-15}\n+ atol = {np.float64: 8e-15}\n+ if impl_name == \"for\":\n+ rtol[np.float32] = 8e-5\n+ atol[np.float32] = 3e-5\nself.assertAllClose(\nans,\nexpected,\ncheck_dtypes=False,\n- rtol={np.float64: 1.4e-15},\n- atol={np.float64: 8e-15})\n+ rtol=rtol,\n+ atol=atol)\n@parameterized.named_parameters(\n{\"testcase_name\": \"_jit_scan={}_jit_f={}_impl={}\".format(\n@@ -1493,7 +1509,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\n\"jit_scan\": jit_scan, \"jit_f\": jit_f, \"scan\": scan_impl}\nfor jit_scan in [False, True]\nfor jit_f in [False, True]\n- for scan_impl, scan_name in SCAN_IMPLS)\n+ for scan_impl, scan_name in SCAN_IMPLS_WITH_FOR)\ndef testScanJVP(self, jit_scan, jit_f, scan):\nrng = self.rng()\n@@ -2141,7 +2157,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\n@parameterized.named_parameters(\n{\"testcase_name\": f\"_{scan_name}\",\n\"scan\": scan_impl}\n- for scan_impl, scan_name in SCAN_IMPLS)\n+ for scan_impl, scan_name in SCAN_IMPLS_WITH_FOR)\ndef test_scan_reverse(self, scan):\ndef cumsum(x, reverse):\nreturn scan(lambda c, x: (c + x, c + x), 0, x, reverse=reverse)[1]\n" } ]
Python
Apache License 2.0
google/jax
Add scan implementation using `for` and tests
260,579
29.06.2022 15:47:12
25,200
fa1a93195a39ee50ede1511485c3e02bc26c0c81
Create `AsyncManager`, which factors out thread management functionality from `GlobalAsyncCheckpointManager` and makes it available for use (such as in Orbax) by classes supporting async read/write.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/gda_serialization/serialization.py", "new_path": "jax/experimental/gda_serialization/serialization.py", "diff": "@@ -17,8 +17,7 @@ import abc\nimport asyncio\nimport re\nimport threading\n-import time\n-from typing import Callable\n+from typing import Callable, Sequence\nfrom absl import logging\nimport jax\n@@ -257,8 +256,7 @@ class GlobalAsyncCheckpointManagerBase(metaclass=abc.ABCMeta):\n\"\"\"Deserializes GDAs from TensorStore.\"\"\"\n-class GlobalAsyncCheckpointManager(GlobalAsyncCheckpointManagerBase):\n- \"\"\"Responsible for serializing GDAs via TensorStore.\"\"\"\n+class AsyncManager:\ndef __init__(self, timeout_secs=300):\nself._timeout_secs = timeout_secs\n@@ -273,21 +271,19 @@ class GlobalAsyncCheckpointManager(GlobalAsyncCheckpointManagerBase):\n'`jax.distributed.initialize()` at the start of your '\n'program.')\nself._client = distributed.global_state.client\n- self._final_ckpt_dir = None\n+ self._final_checkpoint_dir = None\ndef __del__(self):\nif self._thread is not None and self._thread.is_alive():\nlogging.warning('Please add `.wait_until_finished()` in the main thread '\n'before your program finishes because there is a '\n'possibility of losing errors raised if the '\n- 'GlobalAsyncCheckpointManager is deleted before '\n- 'serialization is completed.')\n+ 'this class is deleted before writing is completed.')\ndef _thread_func(self, temp_checkpoint_dir, final_checkpoint_dir):\ntry:\nfor future in self._commit_futures:\n- for f in future:\n- f.result()\n+ future.result()\ncurrent_process = jax.process_index()\nlogging.info('Commit to storage layer has completed by process: %s',\n@@ -295,18 +291,24 @@ class GlobalAsyncCheckpointManager(GlobalAsyncCheckpointManagerBase):\n# All processes will wait at the barrier. When all processes are at the\n# barrier, the barrier will be satisfied. If not, then it will timeout.\n- self._client.wait_at_barrier(self._final_ckpt_dir, self._timeout_in_ms)\n- logging.info('Finished waiting at barrier for process %s', current_process)\n+ self._client.wait_at_barrier(self._final_checkpoint_dir,\n+ self._timeout_in_ms)\n+ logging.info('Finished waiting at barrier for process %s',\n+ current_process)\nif current_process == 0:\n- logging.info('Renaming %s to %s', temp_checkpoint_dir, final_checkpoint_dir)\n+ logging.info('Renaming %s to %s', temp_checkpoint_dir,\n+ final_checkpoint_dir)\nepath.Path(temp_checkpoint_dir).rename(final_checkpoint_dir)\n- logging.info('Finished saving GDA checkpoint to `%s`.', final_checkpoint_dir)\n- self._client.key_value_set(_get_key(self._final_ckpt_dir), _CHECKPOINT_SUCCESS)\n+ logging.info('Finished saving checkpoint to `%s`.',\n+ final_checkpoint_dir)\n+ self._client.key_value_set(\n+ _get_key(self._final_checkpoint_dir), _CHECKPOINT_SUCCESS)\nexcept Exception as e:\nself._exception = e\ndef _start_async_commit(self, temp_checkpoint_dir, final_checkpoint_dir):\n+ self._final_checkpoint_dir = final_checkpoint_dir\nself._thread = threading.Thread(\ntarget=self._thread_func,\nargs=(temp_checkpoint_dir, final_checkpoint_dir))\n@@ -326,11 +328,18 @@ class GlobalAsyncCheckpointManager(GlobalAsyncCheckpointManagerBase):\nself.check_for_errors()\n- if self._final_ckpt_dir is not None:\n+ if self._final_checkpoint_dir is not None:\n# Block until process 0 writes success value to the key value store.\n# If it fails to write it, then `blocking_key_value_get` will time out.\n- self._client.blocking_key_value_get(_get_key(self._final_ckpt_dir),\n- self._timeout_in_ms)\n+ self._client.blocking_key_value_get(\n+ _get_key(self._final_checkpoint_dir), self._timeout_in_ms)\n+\n+ def _add_futures(self, futures: Sequence[asyncio.Future]):\n+ self._commit_futures = futures\n+\n+\n+class GlobalAsyncCheckpointManager(AsyncManager, GlobalAsyncCheckpointManagerBase):\n+ \"\"\"Responsible for serializing GDAs via TensorStore.\"\"\"\ndef serialize(self, gdas, tensorstore_specs, *, temp_checkpoint_dir,\nfinal_checkpoint_dir):\n@@ -356,17 +365,19 @@ class GlobalAsyncCheckpointManager(GlobalAsyncCheckpointManagerBase):\nlogging.info('Waiting for previous serialization to finish.')\nself.wait_until_finished()\n- self._commit_futures = [[] for _ in range(len(tensorstore_specs))]\n+ commit_futures = [[] for _ in range(len(tensorstore_specs))]\nasync def _run_serializer():\n- future_writer = jax.tree_map(async_serialize, gdas,\n- tensorstore_specs, self._commit_futures)\n+ future_writer = jax.tree_map(async_serialize, gdas, tensorstore_specs,\n+ commit_futures)\nreturn await asyncio.gather(*future_writer)\n+\nasyncio.run(_run_serializer())\n+ self._add_futures(jax.tree_flatten(commit_futures)[0])\n+\n# Used in wait_until_finished to check on process != 0, if the checkpoint\n# has finished writing.\n- self._final_ckpt_dir = final_checkpoint_dir\nself._start_async_commit(temp_checkpoint_dir, final_checkpoint_dir)\ndef deserialize(self, global_meshes, mesh_axes, tensorstore_specs,\n" } ]
Python
Apache License 2.0
google/jax
Create `AsyncManager`, which factors out thread management functionality from `GlobalAsyncCheckpointManager` and makes it available for use (such as in Orbax) by classes supporting async read/write. PiperOrigin-RevId: 458081905
260,368
30.06.2022 10:28:45
25,200
61b3dc5801640234987aca7434274f07c7d98beb
[JAX] Update approx_top_k doc with arxiv link.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/ann.py", "new_path": "jax/_src/lax/ann.py", "diff": "@@ -91,6 +91,8 @@ def approx_max_k(operand: Array,\naggregate_to_topk: bool = True) -> Tuple[Array, Array]:\n\"\"\"Returns max ``k`` values and their indices of the ``operand`` in an approximate manner.\n+ See https://arxiv.org/abs/2206.14286 for the algorithm details.\n+\nArgs:\noperand : Array to search for max-k. Must be a floating number type.\nk : Specifies the number of max-k.\n@@ -150,6 +152,8 @@ def approx_min_k(operand: Array,\naggregate_to_topk: bool = True) -> Tuple[Array, Array]:\n\"\"\"Returns min ``k`` values and their indices of the ``operand`` in an approximate manner.\n+ See https://arxiv.org/abs/2206.14286 for the algorithm details.\n+\nArgs:\noperand : Array to search for min-k. Must be a floating number type.\nk : Specifies the number of min-k.\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Update approx_top_k doc with arxiv link. PiperOrigin-RevId: 458258457
260,631
30.06.2022 11:02:07
25,200
4e224bcfb99c3bd9b6a32b8ad7836d12517e788f
[jax2tf] Add support for common audio convolutions (1D variants, dilated depthwise, transpose with SAME padding).
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/impl_no_xla.py", "new_path": "jax/experimental/jax2tf/impl_no_xla.py", "diff": "@@ -50,6 +50,12 @@ def _xla_disabled_error(primitive_name: str,\nreturn NotImplementedError(msg)\n+def _conv_error(msg):\n+ suffix = (\"See source code for the precise conditions under which \"\n+ \"convolutions can be converted without XLA.\")\n+ return _xla_disabled_error(\"conv_general_dilated\", f\"{msg} - {suffix}\")\n+\n+\ndef _unimplemented(name):\ndef op(*arg, **kwargs):\n@@ -66,13 +72,20 @@ def _transpose_for_tf_conv(lhs, rhs, dimension_numbers):\n# TODO(marcvanzee): Consider merging tranposes if we want to optimize.\n# For `lhs_perm` / `output_perm`, perm (0, 1, 2, 3) corresponds to \"NCHW\".\nlhs = tf.transpose(lhs, lhs_perm) # lhs --> \"NCHW\"\n+ if len(lhs_perm) == 3:\n+ # For 1D convolution, we add a trivial \"W\" dimension, so that 2D Convolution\n+ # logic can be applied downstream.\n+ lhs = lhs[:, :, :, np.newaxis]\n# However, the TF ops only support \"NHWC\" on CPU, so we transpose again.\nlhs = tf.transpose(lhs, (0, 2, 3, 1)) # \"NCHW\" --> \"NHWC\"\n+\n# For `rhs_perm`, perm (0, 1, 2, 3) corresponds to \"OIHW\".\nrhs = tf.transpose(rhs, rhs_perm) # rhs --> \"OIHW\"\n+ # Handle conv1d case.\n+ if len(rhs_perm) == 3:\n+ rhs = rhs[:, :, :, np.newaxis]\n# For the tf ops, rhs is expected to be \"OIHW\".\nrhs = tf.transpose(rhs, (2, 3, 1, 0)) # \"OIHW\" --> \"HWIO\"\n-\nreturn lhs, rhs\n@@ -84,26 +97,116 @@ def pads_to_padtype(in_shape, window_shape, window_strides, padding) -> str:\nreturn \"EXPLICIT\"\n-def _pad_spatial_dims(in_shape, padding):\n+def _pad_spatial_dims(in_shape, padding, is_conv1d):\n\"\"\"Pads `in_shape` using `padding`, which specifies padding for the spatial dimensions.\"\"\"\n# Add empty padding for batch and feature dimensions.\nno_pad = tf.constant([[0, 0]])\n+ if is_conv1d:\n+ padding = tf.concat([no_pad, padding, no_pad], 0)\n+ # Add empty padding for dummy dimension, too.\n+ padding = tf.concat([no_pad, padding, no_pad, no_pad], 0)\n+ else:\npadding = tf.concat([no_pad, padding, no_pad], 0)\nin_shape = tf.pad(in_shape, padding)\nreturn in_shape\n-def _is_valid_padding(kernel_sdims, strides, padding):\n- \"\"\"Returns True if `padding` corresponds to \"VALID\" padding for a transposed convolution.\"\"\"\n- # This is simply the padding == 'VALID' part of lax._conv_transpose_padding.\n- for (begin, end), k, s in zip(padding, kernel_sdims, strides):\n- pad_len = k + s - 2 + builtins.max(k - s, 0)\n+def _conv_transpose_pads_to_padtype(kernel_sdims, lhs_dilation, padding):\n+ \"\"\"Finds the padding type for a transpose convolution.\"\"\"\n+ # This is simply checking agreement with lax._conv_transpose_padding.\n+ is_valid = True\n+ is_same = True\n+ if not len(kernel_sdims) == len(lhs_dilation) == len(padding):\n+ raise ValueError(f'Found different lengths for '\n+ f'kernel_sdims ({kernel_sdims}), '\n+ f'lhs_dilation ({lhs_dilation}), '\n+ f'and padding ({padding}).')\n+ for k, s, (begin, end) in zip(kernel_sdims, lhs_dilation, padding):\n+ # Check for VALID padding.\n+ pad_len_valid = k + s - 2 + builtins.max(k - s, 0)\npad_a = k - 1\n- pad_b = pad_len - pad_a\n+ pad_b = pad_len_valid - pad_a\nif begin != pad_a or end != pad_b:\n- return False\n+ is_valid = False\n+\n+ # Check for SAME padding.\n+ pad_len_same = k + s - 2\n+ if s > k - 1:\n+ pad_a = k - 1\n+ else:\n+ pad_a = int(np.ceil(pad_len_same / 2))\n+ pad_b = pad_len_same - pad_a\n+ if begin != pad_a or end != pad_b:\n+ is_same = False\n+\n+ if is_valid:\n+ return 'VALID'\n+ elif is_same:\n+ return 'SAME'\n+ raise ValueError('Transpose convolution padding mode must be '\n+ '`SAME` or `VALID`.')\n+\n+def _validate_spatial_dimensions(nr_spatial_dimensions):\n+ \"\"\"Check spatial dimension support.\"\"\"\n+ # Currently we only support 1D+2D convolutions because it keeps the code\n+ # relatively simple and covers most cases.\n+ if nr_spatial_dimensions > 2:\n+ raise _conv_error(\n+ \"We only support 1D or 2D convolutions, but found \"\n+ f\"{nr_spatial_dimensions}.\")\n+\n+\n+def _normalize_padding_and_dilations(\n+ padding, lhs_dilation, rhs_dilation, is_conv1d):\n+ if is_conv1d:\n+ lhs_dilation = list(lhs_dilation) + [1]\n+ rhs_dilation = list(rhs_dilation) + [1]\n+ # Empty padding in the dummy dimension.\n+ # Note that when kernel_size=stride=1, padding of (0, 0) is both 'VALID' and\n+ # 'SAME'. So the inferred padding type will still register according to the\n+ # first dimension padding.\n+ padding = list(padding) + [(0, 0)]\n+ return padding, lhs_dilation, rhs_dilation\n+\n+def _normalize_window_strides(window_strides):\n+ \"\"\"Ensure window_strides has length 4.\"\"\"\n+ # Some TF ops require len(window_strides) == 4 while others do not. We simply\n+ # ensure it always has len(4).\n+ if len(window_strides) == 1:\n+ # This is the Conv1D case. We add a dummy dimension to allow using 2D ops,\n+ # and use stride=1 on the dummy dimension.\n+ window_strides = list(window_strides) + [1]\n+ if len(window_strides) == 2:\n+ window_strides = [1] + list(window_strides) + [1]\n+ return window_strides\n+\n+def _normalize_output_perm(output_perm, is_conv1d):\n+ \"\"\"Ensure that output_perm has length 4.\"\"\"\n+ if is_conv1d:\n+ output_perm = list(output_perm) + [1]\n+ return output_perm\n+\n+def _validate_conv_features(\n+ is_transpose, is_atrous, is_depthwise, feature_group_count,\n+ batch_group_count, preferred_element_type, lhs_dtype):\n+ if feature_group_count > 1 and not is_depthwise:\n+ raise _conv_error(\"Grouped convolutions are unsupported\")\n+ if (is_depthwise and is_atrous) and not is_transpose:\n+ # We allow dilated depthwise convolutions.\n+ pass\n+ elif [is_depthwise, is_atrous, is_transpose].count(True) > 1:\n+ raise _conv_error(\n+ f\"Can only do one of depthwise ({is_depthwise}), atrous ({is_atrous}) \"\n+ f\"and tranposed convolutions ({is_transpose})\")\n- return True\n+ # We can implement batch grouping when there is a need for it.\n+ if batch_group_count != 1:\n+ raise _conv_error(\"Unimplemented support for batch_group_count != 1 \"\n+ f\"(found {batch_group_count})\")\n+\n+ if (preferred_element_type is not None and\n+ preferred_element_type != lhs_dtype):\n+ raise _conv_error(\"Unimplemented support for preferred_element_type\")\ndef _conv_general_dilated(\n@@ -116,63 +219,39 @@ def _conv_general_dilated(\n\"\"\"Implementation of lax.conv_general_dilated_p using XlaConv.\"\"\"\ndel lhs_shape, rhs_shape, precision # Unused arguments.\nout_shape = jax2tf._aval_to_tf_shape(_out_aval)\n+ _validate_spatial_dimensions(len(lhs.shape) - 2)\n+ is_conv1d = len(lhs.shape) - 2 == 1\n- def error(msg):\n- suffix = (\"See source code for the precise conditions under which \"\n- \"convolutions can be converted without XLA.\")\n- return _xla_disabled_error(\"conv_general_dilated\", f\"{msg} - {suffix}\")\n-\n- nr_spatial_dimensions = len(lhs.shape) - 2\n-\n- # Currently we only support 2D convolutions because it keeps the code\n- # relatively simple and covers most cases.\n- if nr_spatial_dimensions != 2:\n- error(\n- f\"We only support 2D convolutions, but found {nr_spatial_dimensions}.\")\n-\n- # We can implement batch grouping when there is a need for it.\n- if batch_group_count != 1:\n- raise error(\"Unimplemented support for batch_group_count != 1 \"\n- f\"(found {batch_group_count})\")\n-\n- if (preferred_element_type is not None and\n- preferred_element_type != lhs.dtype.as_numpy_dtype):\n- raise error(\"Unimplemented support for preferred_element_type\")\n+ tf_window_strides = _normalize_window_strides(window_strides)\n+ padding, lhs_dilation, rhs_dilation = _normalize_padding_and_dilations(\n+ padding, lhs_dilation, rhs_dilation, is_conv1d)\nlhs, rhs = _transpose_for_tf_conv(lhs, rhs, dimension_numbers)\n- output_perm = dimension_numbers[2]\nin_channels = lhs.shape[-1]\n*rhs_spatial_shapes, _, rhs_out_channel = rhs.shape\n+ is_transpose = any([d != 1 for d in lhs_dilation])\n+ is_atrous = any([d != 1 for d in rhs_dilation])\nis_depthwise = in_channels == feature_group_count and feature_group_count > 1\n- is_transpose = list(lhs_dilation) != [1] * nr_spatial_dimensions\n- is_atrous = list(rhs_dilation) != [1] * nr_spatial_dimensions\n-\n- if feature_group_count > 1 and not is_depthwise:\n- raise error(\"Grouped convolutions are unsupported\")\n-\n- if is_transpose:\n- # We provide support for transposed convolutions called through\n- # lax.conv2d_tranpose, but only if the provided padding was VALID.\n- if not _is_valid_padding(rhs_spatial_shapes, window_strides, padding):\n- raise error(\n- \"Can only convert Transposed Convolutions with 'VALID' padding\")\n-\n- if [is_depthwise, is_atrous, is_transpose].count(True) > 1:\n- raise error(\n- \"Can only do one of depthwise, atrous and tranposed convolutions\")\n+ _validate_conv_features(is_transpose, is_atrous, is_depthwise,\n+ feature_group_count, batch_group_count,\n+ preferred_element_type, lhs.dtype.as_numpy_dtype)\nrhs_dilated_shape = [\n(k - 1) * r + 1 for k, r in zip(rhs_spatial_shapes, rhs_dilation)\n]\n+ output_perm = dimension_numbers[2]\n- padding_type = pads_to_padtype(lhs.shape[1:3], rhs_dilated_shape, window_strides, padding)\n-\n- # We only manually pad if we aren't using a tranposed convolutions, because\n- # there we don't do any padding.\n- if padding_type == \"EXPLICIT\" and not is_transpose:\n- lhs = _pad_spatial_dims(lhs, padding)\n+ if is_transpose:\n+ padding_type = _conv_transpose_pads_to_padtype(\n+ rhs_spatial_shapes, lhs_dilation, padding)\n+ else:\n+ padding_type = pads_to_padtype(\n+ lhs.shape[1:3], rhs_dilated_shape, window_strides, padding)\n+ # We only manually pad if we aren't using a tranposed convolutions.\n+ if padding_type == \"EXPLICIT\":\n+ lhs = _pad_spatial_dims(lhs, padding, is_conv1d)\npadding_type = \"VALID\"\nif any(r > l for l, r in zip(lhs.shape[1:3], rhs_dilated_shape)\n@@ -182,13 +261,6 @@ def _conv_general_dilated(\n# We thus return zeros to make sure the behavior is consistent.\nreturn tf.broadcast_to(tf.constant(0, dtype=tf.float32), out_shape)\n- # Some TF ops require len(window_strides) == 4 while others do not. We simply\n- # ensure it always has len(4).\n- if type(window_strides) == int:\n- window_strides = [window_strides] * 2\n- if len(window_strides) == 2:\n- window_strides = [1] + list(window_strides) + [1]\n-\nif is_depthwise:\n# Reshape filter from\n# [filter_height, filter_width, 1, in_channels * channel_multiplier] to\n@@ -198,7 +270,7 @@ def _conv_general_dilated(\noutput = tf.nn.depthwise_conv2d(\ninput=lhs,\nfilter=tf.reshape(rhs, new_rhs_shape),\n- strides=window_strides,\n+ strides=tf_window_strides,\npadding=padding_type,\ndilations=rhs_dilation)\n@@ -207,29 +279,34 @@ def _conv_general_dilated(\nrhs_t = tf.reverse(rhs, [0, 1])\nrhs_t = tf.transpose(rhs_t, (0, 1, 3, 2))\n- # We should tranpose `out_shape` so it conforms to what TF expects.\n- tf_out_shape = tuple(out_shape[i] for i in output_perm) # \"NCHW\"\n- tf_out_shape = tuple(\n- tf_out_shape[i] for i in (0, 2, 3, 1)) # \"NCHW\" -> \"NHWC\"\n-\n+ # We should tranpose `out_shape` to \"NHWC\", which is what TF expects.\n+ # First transpose to \"NCHW\".\n+ if is_conv1d:\n+ tf_out_shape = tuple(out_shape[i] for i in output_perm) + (1,)\n+ else:\n+ tf_out_shape = tuple(out_shape[i] for i in output_perm)\n+ # Then transpose \"NCHW\" to \"NHWC\".\n+ tf_out_shape = tuple(tf_out_shape[i] for i in (0, 2, 3, 1))\noutput = tf.nn.conv2d_transpose(\ninput=lhs,\nfilters=rhs_t,\noutput_shape=tf_out_shape,\nstrides=lhs_dilation,\n- padding=\"VALID\")\n+ padding=padding_type)\nelse:\noutput = tf.nn.conv2d(\ninput=lhs,\nfilters=rhs,\n- strides=window_strides,\n+ strides=tf_window_strides,\npadding=padding_type,\ndilations=rhs_dilation)\n# TF outputs in format \"NHWC\", so convert to \"NCHW\", which is lax's default\n# format.\noutput = tf.transpose(output, (0, 3, 1, 2)) # \"NHWC\" --> \"NCHW\"\n+ if is_conv1d:\n+ output = output[:, :, :, 0]\n# To determine the right permutation, we compute the inverse permutation of\n# `output_perm`, so that when `output_perm` is applied to `output`, we obtain\n# the outpt in NCHW format.\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -2889,8 +2889,19 @@ for batch_group_count, feature_group_count in [\nfeature_group_count=feature_group_count,\nbatch_group_count=batch_group_count)\n+#--- BEGIN Tests for conv_general_dilated with works_without_xla=True ---\n-#--- BEGIN Tests for conv_general_dilated with works_for_xla=True ---\n+# Validate Conv1D.\n+_make_conv_harness(\n+ \"conv1d\",\n+ lhs_shape=(2, 3, 10),\n+ rhs_shape=(3, 3, 5),\n+ window_strides=(1,),\n+ padding=((0, 0),),\n+ lhs_dilation=(1,),\n+ rhs_dilation=(1,),\n+ dimension_numbers=(\"NCH\", \"OIH\", \"NCH\"),\n+ works_without_xla=True)\n# feature_group_count is supported for enable_xla=False only if we are doing a\n@@ -2904,6 +2915,39 @@ _make_conv_harness(\nfeature_group_count=3,\nworks_without_xla=True)\n+_make_conv_harness(\n+ \"depthwise2d_dilated\",\n+ lhs_shape=(2, 3, 9, 9), # \"NCHW\": in_channels == 3\n+ rhs_shape=(12, 1, 3, 3), # \"OIHW\": channel_multiplier = 12/3 = 4\n+ feature_group_count=3,\n+ lhs_dilation=(1, 1),\n+ rhs_dilation=(2, 1),\n+ works_without_xla=True)\n+\n+_make_conv_harness(\n+ \"depthwise1d\",\n+ lhs_shape=(2, 3, 9), # \"NCH\": in_channels == 3\n+ rhs_shape=(12, 1, 3), # \"OIH\": channel_multiplier = 12/3 = 4\n+ feature_group_count=3,\n+ lhs_dilation=(1,),\n+ rhs_dilation=(1,),\n+ window_strides=(1, ),\n+ padding=((0, 0),),\n+ dimension_numbers=(\"NCH\", \"OIH\", \"NCH\"),\n+ works_without_xla=True)\n+\n+_make_conv_harness(\n+ \"depthwise1d_dilated\",\n+ lhs_shape=(2, 3, 9), # \"NCH\": in_channels == 3\n+ rhs_shape=(12, 1, 3), # \"OIH\": channel_multiplier = 12/3 = 4\n+ feature_group_count=3,\n+ lhs_dilation=(1,),\n+ rhs_dilation=(2,),\n+ window_strides=(1,),\n+ padding=((0, 0),),\n+ dimension_numbers=(\"NCH\", \"OIH\", \"NCH\"),\n+ works_without_xla=True)\n+\n# Validate variations of window_strides\nfor window_strides in [(2, 3)]:\n_make_conv_harness(\n@@ -2939,6 +2983,39 @@ _make_conv_harness(\ndimension_numbers=(\"NHWC\", \"HWIO\", \"NHWC\"),\nworks_without_xla=True)\n+# Simulate a call from lax.conv_transpose.\n+_make_conv_harness(\n+ \"conv_tranpose1d_valid_padding\",\n+ lhs_shape=(1, 16, 2),\n+ rhs_shape=(3, 2, 2),\n+ window_strides=(1,),\n+ lhs_dilation=(2,),\n+ rhs_dilation=(1,),\n+ padding=((2, 2), ),\n+ dimension_numbers=(\"NHC\", \"HIO\", \"NHC\"),\n+ works_without_xla=True)\n+\n+_make_conv_harness(\n+ \"conv_tranpose1d_same_padding\",\n+ lhs_shape=(1, 16, 2),\n+ rhs_shape=(3, 2, 2),\n+ window_strides=(1,),\n+ lhs_dilation=(2,),\n+ rhs_dilation=(1,),\n+ padding=((2, 1), ),\n+ dimension_numbers=(\"NHC\", \"HIO\", \"NHC\"),\n+ works_without_xla=True)\n+\n+_make_conv_harness(\n+ \"conv_tranpose2d_same_padding\",\n+ lhs_shape=(1, 16, 16, 2),\n+ rhs_shape=(2, 3, 2, 2),\n+ window_strides=(1, 1),\n+ lhs_dilation=(2, 2),\n+ padding=((1, 1), (2, 1)),\n+ dimension_numbers=(\"NHWC\", \"HWIO\", \"NHWC\"),\n+ works_without_xla=True)\n+\n# Validate rhs > lhs.\n# One dimension of rhs is bigger than lhs.\n_make_conv_harness(\n@@ -3008,7 +3085,7 @@ for padding, lhs_dilation, rhs_dilation in [\nrhs_dilation=rhs_dilation,\nworks_without_xla=True)\n-#--- END Tests for conv_general_dilated with works_for_xla=True ---\n+#--- END Tests for conv_general_dilated with works_without_xla=True ---\nfor lhs_dilation, rhs_dilation in [\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Add support for common audio convolutions (1D variants, dilated depthwise, transpose with SAME padding). PiperOrigin-RevId: 458266485
260,461
30.06.2022 15:24:10
25,200
4bfb26c7090800dd2acb79c00a482384ac7af760
Skip F64 tests on GPU. I had erroneously assumed that GPU would be as-high accuracy for f64 (both in numerics and eigh) when submitting so I did not disable f64 tests on that platform. This is of course not the case, so those tests should be disabled.
[ { "change_type": "MODIFY", "old_path": "tests/lobpcg_test.py", "new_path": "tests/lobpcg_test.py", "diff": "@@ -382,16 +382,16 @@ class F32LobpcgTest(LobpcgTest):\nclass F64LobpcgTest(LobpcgTest):\n@parameterized.named_parameters(_make_concrete_cases(f64=True))\n- @jtu.skip_on_devices(\"tpu\", \"iree\")\n+ @jtu.skip_on_devices(\"tpu\", \"iree\", \"gpu\")\ndef testLobpcgConsistencyF64(self, matrix_name, n, k, m):\nself.checkLobpcgConsistency(matrix_name, n, k, m, jnp.float64)\n@parameterized.named_parameters(_make_concrete_cases(f64=True))\n- @jtu.skip_on_devices(\"tpu\", \"iree\")\n+ @jtu.skip_on_devices(\"tpu\", \"iree\", \"gpu\")\ndef testLobpcgMonotonicityF64(self, matrix_name, n, k, m):\nself.checkLobpcgMonotonicity(matrix_name, n, k, m, jnp.float64)\n@parameterized.named_parameters(_make_callable_cases(f64=True))\n- @jtu.skip_on_devices(\"tpu\", \"iree\")\n+ @jtu.skip_on_devices(\"tpu\", \"iree\", \"gpu\")\ndef testCallableMatricesF64(self, matrix_name):\nself.checkApproxEigs(matrix_name, jnp.float64)\n" } ]
Python
Apache License 2.0
google/jax
Skip F64 tests on GPU. I had erroneously assumed that GPU would be as-high accuracy for f64 (both in numerics and eigh) when submitting #3112, so I did not disable f64 tests on that platform. This is of course not the case, so those tests should be disabled.
260,510
30.06.2022 23:09:50
25,200
7b59bd02ae28be71e26f718fb738fbc62f8477e4
Deflake debugger_test
[ { "change_type": "MODIFY", "old_path": "tests/debugger_test.py", "new_path": "tests/debugger_test.py", "diff": "@@ -274,6 +274,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\n\\(jaxdb\\) array\\(.*, dtype=float32\\)\n\\(jaxdb\\) \"\"\")\ng(jnp.arange(2., dtype=jnp.float32))\n+ jax.effects_barrier()\nself.assertRegex(stdout.getvalue(), expected)\nif __name__ == '__main__':\n" } ]
Python
Apache License 2.0
google/jax
Deflake debugger_test PiperOrigin-RevId: 458392106
260,510
29.06.2022 11:32:52
25,200
a82047dd4a786fc82808f88e732f5aabcdece795
Add partial_eval rule for `for`
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "@@ -31,7 +31,9 @@ from jax.tree_util import (tree_flatten, tree_structure, tree_unflatten,\nfrom jax._src import ad_util\nfrom jax._src import dtypes\nfrom jax._src import pretty_printer as pp\n-from jax._src.util import safe_map, safe_zip, split_list\n+from jax._src import source_info_util\n+from jax._src.util import (partition_list, merge_lists, safe_map, safe_zip,\n+ split_list)\nimport jax.numpy as jnp\nfrom jax._src.lax.control_flow import loops\n@@ -616,6 +618,157 @@ def _for_jvp(primals, tangents, *, jaxpr, nsteps, reverse, which_linear):\nad.primitive_jvps[for_p] = _for_jvp\n+def _partial_eval_jaxpr_custom(jaxpr, in_unknowns, policy):\n+ # A simple wrapper around `pe.partial_eval_jaxpr_custom` that assumes all\n+ # inputs are instantiated and doesn't ensure any outputs are unknown or\n+ # instantiated.\n+ return pe.partial_eval_jaxpr_custom(\n+ jaxpr, in_unknowns, [True] * len(in_unknowns), False, False, policy)\n+\n+_save_everything = lambda *_, **__: True\n+\n+def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\n+ jaxpr: core.Jaxpr, nsteps: int, reverse: bool,\n+ which_linear: Tuple[bool]) -> List[pe.JaxprTracer]:\n+ num_inputs = len(tracers)\n+ in_unknowns = [not t.pval.is_known() for t in tracers]\n+ # We first need to run a fixpoint to determine which of the `Ref`s are unknown\n+ # after running the for loop. We want to use the jaxpr to determine which\n+ # `Ref`s are unknown after executing the for loop body given which `Ref`s are\n+ # unknown before. However, the jaxpr has no outputs. Instead, we discharge\n+ # the body and run the fixpoint with the discharged jaxpr. We can do this\n+ # because the outputs of the jaxpr are one-to-one with the inputs.\n+ discharged_jaxpr, discharged_consts = discharge_state(jaxpr, ())\n+ discharged_jaxpr = discharged_jaxpr.replace(\n+ invars=discharged_jaxpr.constvars + discharged_jaxpr.invars,\n+ constvars=[])\n+ for _ in range(num_inputs):\n+ jaxpr_in_unknowns = [False] * len(discharged_consts) + [False, *in_unknowns]\n+ _, _, out_unknowns, _, _ = _partial_eval_jaxpr_custom(\n+ discharged_jaxpr, jaxpr_in_unknowns, _save_everything)\n+ out_unknowns = list(out_unknowns)\n+ if out_unknowns == in_unknowns:\n+ break\n+ in_unknowns = map(operator.or_, in_unknowns, out_unknowns)\n+ else:\n+ raise Exception(\"Invalid fixpoint\")\n+ del out_unknowns # redundant since it's the same as `in_unknowns`\n+ tracers = tuple(trace.instantiate_const(t) if uk else t\n+ for t, uk in zip(tracers, in_unknowns))\n+\n+ # We use `partial_eval_jaxpr_custom` here because it won't remove effectful\n+ # primitives like `get`/`set`.\n+ jaxpr_known_resout, jaxpr_unknown_resin_, _, _, num_res = \\\n+ _partial_eval_jaxpr_custom(jaxpr, [False, *in_unknowns],\n+ _save_everything)\n+ # `partial_eval_jaxpr_custom` will give us jaxprs that have hybrid `Ref` and\n+ # regular valued input/outputs. However, we'd like to bind these jaxprs to a\n+ # `for`, which expects only `Ref` inputs and no output. We need to convert\n+ # both of these jaxprs into ones that are compatible with `for`.\n+ # TODO(sharadmv,mattjj): implement \"passthrough\" optimization.\n+ # TODO(sharadmv,mattjj): rematerialize loop-dependent values instead of\n+ # passing the loop index as a residual\n+\n+ # `jaxpr_known_resout` is a jaxpr that maps from all the input `Refs`\n+ # to output residual values (none of them should be `Ref`s). We'll need to\n+ # convert the output residual values into `Ref`s that are initially empty\n+ # `Ref`s that are written to at the end of the jaxpr.\n+ # TODO(sharadmv,mattjj): detect which residuals are loop-invariant\n+ jaxpr_known, res_avals = _convert_outputs_to_writes(nsteps,\n+ jaxpr_known_resout)\n+ # We now run the known jaxpr to obtain our residual values.\n+ known_tracers, _ = partition_list(in_unknowns, tracers)\n+ known_vals = [t.pval.get_known() for t in known_tracers]\n+ empty_res = map(ad_util.zeros_like_aval, res_avals)\n+ jaxpr_known_args = [*known_vals, *empty_res]\n+ jaxpr_known_which_linear = (False,) * len(jaxpr_known_args)\n+ out_flat = for_p.bind(*jaxpr_known_args, jaxpr=jaxpr_known, nsteps=nsteps,\n+ reverse=reverse, which_linear=jaxpr_known_which_linear)\n+ known_outputs, residuals = split_list(out_flat, [len(known_tracers)])\n+ residuals = map(trace.new_instantiated_const, residuals)\n+\n+ # Now we handle the `jaxpr_unknown` that expects residual values as inputs.\n+ # This jaxpr is the output of `partial_eval_jaxpr_custom` that marks which\n+ # inputs are actually used.\n+ # `partial_eval_jaxpr_custom` doesn't remove extra inputs/outputs for you\n+ # so we use `dce_jaxpr` here to do that.\n+ jaxpr_unknown_resin, used_inputs = pe.dce_jaxpr(\n+ jaxpr_unknown_resin_, [], [True] * num_res + [True, *in_unknowns])\n+ used_res, (used_i,), used_refs = split_list(used_inputs, [num_res, 1])\n+ assert all(used_res), \"All residuals should be used\"\n+ # To make it compatible with `for`, we need to convert those residual values\n+ # into `Ref`s.\n+ jaxpr_unknown = _convert_inputs_to_reads(nsteps, len(res_avals),\n+ jaxpr_unknown_resin)\n+ # Since not all inputs are used in jaxpr_unknown, we filter the input tracers\n+ # down using the output of `dce_jaxpr`.\n+ _, used_tracers = partition_list(used_refs, tracers)\n+ _, used_which_linear = partition_list(used_refs, which_linear)\n+ which_linear_unknown = (False,) * num_res + tuple(used_which_linear)\n+ unknown_inputs = [*residuals, *used_tracers]\n+ # Outputs match inputs so we construct output tracers that look like the input\n+ # tracers.\n+ res_ref_unknown_outputs = [\n+ pe.JaxprTracer(trace, pe.PartialVal.unknown(t.aval), None)\n+ for t in unknown_inputs]\n+ name_stack = source_info_util.current_name_stack()[len(trace.name_stack):]\n+ source = source_info_util.current().replace(name_stack=name_stack)\n+\n+ eqn = pe.new_eqn_recipe(unknown_inputs, res_ref_unknown_outputs,\n+ for_p, dict(jaxpr=jaxpr_unknown, nsteps=nsteps,\n+ reverse=reverse,\n+ which_linear=which_linear_unknown),\n+ core.no_effects, source)\n+ _, unknown_outputs = split_list(res_ref_unknown_outputs, [num_res])\n+ for t in unknown_outputs: t.recipe = eqn\n+ return merge_lists(in_unknowns, known_outputs, unknown_outputs)\n+pe.custom_partial_eval_rules[for_p] = _for_partial_eval\n+\n+def _convert_outputs_to_writes(\n+ nsteps: int, jaxpr: core.Jaxpr) -> Tuple[core.Jaxpr,\n+ List[core.ShapedArray]]:\n+ assert not jaxpr.constvars, \"Jaxpr shouldn't have constvars.\"\n+\n+ in_avals = [v.aval for v in jaxpr.invars] # [i, *orig_ref_avals]\n+ @lu.wrap_init\n+ def eval_jaxpr(i, *refs):\n+ # We split the refs into the original input refs and the dummy residual\n+ # refs.\n+ orig_refs, residual_refs = split_list(refs, [len(in_avals) - 1])\n+ residual_vals = core.eval_jaxpr(jaxpr, (), i, *orig_refs)\n+ for res_ref, res_val in zip(residual_refs, residual_vals):\n+ # TODO(sharadmv): loop-invariant residuals should not be an indexed write\n+ res_ref[i] = res_val\n+ return []\n+ res_ref_avals = [ShapedArrayRef((nsteps, *v.aval.shape), v.aval.dtype) # pytype: disable=attribute-error\n+ for v in jaxpr.outvars]\n+ jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(\n+ eval_jaxpr, [*in_avals, *res_ref_avals])\n+ assert not consts\n+ return jaxpr, [core.ShapedArray(a.shape, a.dtype) for a in res_ref_avals]\n+\n+def _convert_inputs_to_reads(\n+ nsteps: int, num_res: int, jaxpr: core.Jaxpr,\n+ ) -> core.Jaxpr:\n+ assert not jaxpr.constvars, \"Jaxpr should not have constvars\"\n+\n+ @lu.wrap_init\n+ def eval_jaxpr(i, *refs):\n+ residual_refs, orig_refs = split_list(refs, [num_res])\n+ # TODO(sharadmv): don't do an indexed read for loop-invariant residuals\n+ residual_vals = [r[i] for r in residual_refs]\n+ () = core.eval_jaxpr(jaxpr, (), *residual_vals, i, *orig_refs)\n+ return []\n+\n+ res_val_avals, (i_aval,), orig_ref_avals = \\\n+ split_list([v.aval for v in jaxpr.invars], [num_res, 1])\n+ res_ref_avals = [ShapedArrayRef((nsteps, *aval.shape), aval.dtype) # pytype: disable=attribute-error\n+ for aval in res_val_avals]\n+\n+ jaxpr, _, () = pe.trace_to_jaxpr_dynamic(\n+ eval_jaxpr, [i_aval, *res_ref_avals, *orig_ref_avals])\n+ return jaxpr\n+\n### Testing utility\ndef discharged_for_loop(nsteps, body, init_state, *, reverse: bool = False):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -1543,7 +1543,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\n\"jit_scan\": jit_scan, \"jit_f\": jit_f, \"scan\": scan_impl}\nfor jit_scan in [False, True]\nfor jit_f in [False, True]\n- for scan_impl, scan_name in SCAN_IMPLS)\n+ for scan_impl, scan_name in SCAN_IMPLS_WITH_FOR)\ndef testScanLinearize(self, jit_scan, jit_f, scan):\nrng = self.rng()\n@@ -1944,6 +1944,15 @@ class LaxControlFlowTest(jtu.JaxTestCase):\npython_should_be_executing = False\nlax.while_loop(cond, body, 0)\n+ def test_caches_depend_on_axis_env(self):\n+ # https://github.com/google/jax/issues/9187\n+ scanned_f = lambda _, __: (lax.psum(1, 'i'), None)\n+ f = lambda: lax.scan(scanned_f, 0, None, length=1)[0]\n+ ans = jax.vmap(f, axis_name='i', axis_size=2, out_axes=None)()\n+ self.assertEqual(ans, 2)\n+ ans = jax.vmap(f, axis_name='i', axis_size=3, out_axes=None)()\n+ self.assertEqual(ans, 3)\n+\ndef testWhileCondConstant(self):\nout = lax.while_loop(lambda _: False, lambda _: (), ()) # doesn't crash\nself.assertEqual(out, ())\n@@ -2990,15 +2999,36 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\njtu.check_grads(partial(for_, n, f), (args,), order=3, modes=[\"fwd\"])\n- def test_caches_depend_on_axis_env(self):\n- # https://github.com/google/jax/issues/9187\n- scanned_f = lambda _, __: (lax.psum(1, 'i'), None)\n- f = lambda: lax.scan(scanned_f, 0, None, length=1)[0]\n- ans = jax.vmap(f, axis_name='i', axis_size=2, out_axes=None)()\n- self.assertEqual(ans, 2)\n- ans = jax.vmap(f, axis_name='i', axis_size=3, out_axes=None)()\n- self.assertEqual(ans, 3)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_jit_for={}_f={}_nsteps={}\".format(\n+ jit_for, for_body_name, nsteps),\n+ \"jit_for\": jit_for, \"f\": for_body, \"body_shapes\": body_shapes,\n+ \"ref\": ref, \"n\": nsteps}\n+ for jit_for in [False, True]\n+ for for_body_name, for_body, ref, body_shapes, nsteps in [\n+ (\"swap\", for_body_swap, swap_ref, [(4,), (4,)], 4),\n+ (\"swap_swap\", for_body_swap_swap, swap_swap_ref, [(4,), (4,)], 4),\n+ (\"sincos\", for_body_sincos, sincos_ref, [(4,), (4,)], 4),\n+ (\"sincostan\", for_body_sincostan, sincostan_ref, [(4,), (4,)], 4),\n+ (\"accum\", for_body_accum, accum_ref, [(4,), (4,)], 3),\n+ (\"sin_sq\", for_body_sin_sq, sin_sq_ref, [(4,), (4,)], 4),\n+ (\"reverse\", for_body_reverse, reverse_ref, [(4,), (4,)], 4),\n+ ])\n+ def test_for_linearize(self, jit_for, f, ref, body_shapes, n):\n+ for_ = for_loop.for_loop\n+ rng = self.rng()\n+\n+ args = [rng.randn(*s) for s in body_shapes]\n+ if jit_for:\n+ for_ = jax.jit(for_, static_argnums=(0, 1))\n+ tol = {np.float64: 1e-12, np.float32: 1e-4}\n+ ans = jax.linearize(lambda *args: for_( n, f, args), *args)[1](*args)\n+ ans_discharged = jax.linearize(lambda *args: for_reference(n, f, args),\n+ *args)[1](*args)\n+ expected = jax.linearize(ref, *args)[1](*args)\n+ self.assertAllClose(ans, ans_discharged, check_dtypes=True, rtol=tol, atol=tol)\n+ self.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add partial_eval rule for `for` Co-authored-by: Matthew Johnson <mattjj@google.com>
260,637
03.07.2022 19:02:30
0
2d063d3f85afb3e44824f0cb27c4b8f499cef6e1
Fix typos in omnistaging.md
[ { "change_type": "MODIFY", "old_path": "docs/design_notes/omnistaging.md", "new_path": "docs/design_notes/omnistaging.md", "diff": "@@ -41,7 +41,7 @@ disabled in JAX versions 0.2.12 and higher*\nIt is temporarily possible to disable omnistaging by\n1. setting the shell environment variable `JAX_OMNISTAGING` to something falsey;\n-2. setting the boolean flag `jax_omnistaging` to soething falsey if your code\n+2. setting the boolean flag `jax_omnistaging` to something falsey if your code\nparses flags with absl;\n3. using this statement near the top of your main file:\n```python\n@@ -296,7 +296,7 @@ abstract tracer value caused a problem (the `jnp.reshape` line in the full stack\ntrace, on omni.py:10), we also explain why this value became a tracer in the\nfirst place by pointing to the upstream primitive operation that caused it to\nbecome an abstract tracer (the `reduce_prod` from `jnp.prod` on omni.py:9) and to\n-which `jit`-decorated function the tracer belongs (`ex` on omni.py:7).\n+which `jit`-decorated function the tracer belongs (`ex1` on omni.py:6).\n### Side-effects\n" } ]
Python
Apache License 2.0
google/jax
Fix typos in omnistaging.md
260,411
16.11.2021 11:17:42
-7,200
5983d385dab539caeb445f89fb414fab35c5726f
[dynamic-shapes] Expand the handling of dynamic shapes for reshape and iota. Also add more tests.
[ { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -840,7 +840,7 @@ bcoo_cusparse_lowering = config.define_bool_state(\n# if the intended backend can handle lowering the result\nconfig.define_bool_state(\nname='jax_dynamic_shapes',\n- default=False,\n+ default=bool(os.getenv('JAX_DYNAMIC_SHAPES', '')),\nhelp=('Enables experimental features for staging out computations with '\n'dynamic shapes.'),\nupdate_global_hook=lambda val: \\\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -302,6 +302,7 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nshape=tuple(expected_shape), dtype=expected_type.dtype,\nweak_type=expected_type.weak_type)\nassert core.typematch(expected_aval, aval)\n+\nwith log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n\"for jit in {elapsed_time} sec\"):\njaxpr, out_type, consts = pe.trace_to_jaxpr_final2(\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -18,8 +18,8 @@ import functools\nfrom functools import partial\nimport itertools\nimport operator\n-from typing import (Any, Callable, Optional, Sequence, Tuple, List, TypeVar,\n- Union, cast as type_cast)\n+from typing import (Any, Callable, Dict, Optional, Sequence, Tuple,\n+ List, TypeVar, Union, cast as type_cast)\nimport warnings\nimport numpy as np\n@@ -156,6 +156,60 @@ def _broadcast_ranks(s1, s2):\ndef _identity(x): return x\n+def _extract_tracers_dyn_shape(shape: Sequence[Union[int, core.Tracer]]\n+ ) -> Tuple[Sequence[core.Tracer],\n+ Sequence[Optional[int]]]:\n+ \"\"\"Returns the list of tracers in `shape`, and a static versio of `shape`\n+ with tracers replaced with None\"\"\"\n+ if config.jax_dynamic_shapes:\n+ # We must gate this behavior under a flag because otherwise the errors\n+ # raised are different (and have worse source provenance information).\n+ dyn_shape = [d for d in shape if isinstance(d, core.Tracer)]\n+ static_shape = [d if not isinstance(d, core.Tracer) else None for d in shape]\n+ return dyn_shape, static_shape\n+ else:\n+ return [], shape\n+\n+\n+def _merge_dyn_shape(static_shape: Sequence[Optional[int]],\n+ dyn_shape: Sequence[mlir.Value],\n+ ) -> Sequence[mlir.Value]:\n+ \"\"\"Returns static_shape with None values filled in from dyn_shape.\"\"\"\n+ dyn_shape = iter(dyn_shape)\n+ shape = [next(dyn_shape) if d is None else d for d in static_shape]\n+ assert next(dyn_shape, None) is None\n+ return shape\n+\n+def _stage_with_dyn_shape(trace: core.Trace,\n+ prim: core.Primitive,\n+ args: Sequence[core.Tracer],\n+ dyn_shape_args: Sequence[core.Tracer],\n+ params: Dict[str, Any],\n+ static_shape: Sequence[Optional[int]],\n+ out_dtype: core.Type,\n+ out_weak_type: bool,\n+ ) -> core.Tracer:\n+ \"\"\"Stages out a primitive that takes dynamic shapes.\n+\n+ dyn_shape_args are the tracers corresponding to the None values in static_shape.\n+ \"\"\"\n+ if not dyn_shape_args:\n+ return trace.default_process_primitive(prim, args, params)\n+ assert len(dyn_shape_args) == sum(d is None for d in static_shape)\n+ source_info = source_info_util.current()\n+\n+ ds = iter(dyn_shape_args)\n+ out_shape_for_tracer: List[Union[int, core.Tracer]] = [\n+ next(ds) if d is None else d for d in static_shape]\n+ aval = core.DShapedArray(tuple(out_shape_for_tracer), out_dtype, out_weak_type)\n+ out_tracer = pe.DynamicJaxprTracer(trace, aval, source_info)\n+ invars = [*(trace.getvar(x) for x in args), *(trace.getvar(d) for d in dyn_shape_args)]\n+ eqn = pe.new_jaxpr_eqn(invars, [trace.makevar(out_tracer)],\n+ prim, params, core.no_effects, source_info)\n+ trace.frame.eqns.append(eqn)\n+\n+ return out_tracer\n+\n### traceables\ndef neg(x: Array) -> Array:\n@@ -740,16 +794,9 @@ def broadcast_in_dim(operand: Array, shape: Shape,\nif (np.ndim(operand) == len(shape) and not len(broadcast_dimensions)\nand isinstance(operand, (device_array.DeviceArray, core.Tracer))):\nreturn operand\n- if config.jax_dynamic_shapes:\n- # We must gate this behavior under a flag because otherwise the errors\n- # raised are different (and have worse source provenance information).\n- dyn_shape = [d for d in shape if isinstance(d, core.Tracer)]\n- shape_ = [d if not isinstance(d, core.Tracer) else None for d in shape]\n- else:\n- dyn_shape = []\n- shape_ = shape # type: ignore\n+ dyn_shape, static_shape = _extract_tracers_dyn_shape(shape)\nreturn broadcast_in_dim_p.bind(\n- operand, *dyn_shape, shape=tuple(shape_),\n+ operand, *dyn_shape, shape=tuple(static_shape),\nbroadcast_dimensions=tuple(broadcast_dimensions))\ndef broadcast_to_rank(x: Array, rank: int) -> Array:\n@@ -808,8 +855,10 @@ def reshape(operand: Array, new_sizes: Shape,\nand isinstance(operand, (core.Tracer, device_array.DeviceArray))):\nreturn operand\nelse:\n+ dyn_shape, static_new_sizes = _extract_tracers_dyn_shape(new_sizes)\n+\nreturn reshape_p.bind(\n- operand, new_sizes=new_sizes,\n+ operand, *dyn_shape, new_sizes=static_new_sizes,\ndimensions=None if dims is None or same_dims else dims)\ndef pad(operand: Array, padding_value: Array,\n@@ -1118,7 +1167,8 @@ def iota(dtype: DType, size: int) -> Array:\n\"\"\"\ndtype = dtypes.canonicalize_dtype(dtype)\nsize, = canonicalize_shape((size,))\n- return iota_p.bind(dtype=dtype, shape=(size,), dimension=0)\n+ dyn_shape, static_shape = _extract_tracers_dyn_shape((size,))\n+ return iota_p.bind(*dyn_shape, dtype=dtype, shape=static_shape, dimension=0)\ndef broadcasted_iota(dtype: DType, shape: Shape, dimension: int) -> Array:\n\"\"\"Convenience wrapper around ``iota``.\"\"\"\n@@ -2638,9 +2688,7 @@ def _broadcast_in_dim_typecheck_rule(\nreturn [out_aval], effects\nelse:\n# TODO(mattjj): perform more checks like _broadcast_in_dim_shape_rule\n- dyn_shape_ = iter(dyn_shape)\n- out_shape = [next(dyn_shape_) if d is None else d for d in shape]\n- assert next(dyn_shape_, None) is None\n+ out_shape = _merge_dyn_shape(shape, dyn_shape)\nout_shape = [x.val if type(x) is core.Literal else x for x in out_shape]\nout_aval = core.DShapedArray(tuple(out_shape), operand.aval.dtype,\noperand.aval.weak_type)\n@@ -2676,22 +2724,9 @@ def _broadcast_in_dim_fwd_rule(eqn):\ndef _broadcast_in_dim_staging_rule(\ntrace, x, *dyn_shape, shape, broadcast_dimensions):\nparams = dict(shape=shape, broadcast_dimensions=broadcast_dimensions)\n- if not dyn_shape:\n- return trace.default_process_primitive(broadcast_in_dim_p, (x,), params)\n- assert len(dyn_shape) == sum(d is None for d in shape)\n- source_info = source_info_util.current()\n-\n- ds = iter(dyn_shape)\n- out_shape_for_tracer: List[Union[int, core.Tracer]] = [\n- next(ds) if d is None else d for d in shape]\n- aval = core.DShapedArray(tuple(out_shape_for_tracer), x.dtype, x.weak_type)\n- out_tracer = pe.DynamicJaxprTracer(trace, aval, source_info)\n- invars = [trace.getvar(x), *(trace.getvar(d) for d in dyn_shape)]\n- eqn = pe.new_jaxpr_eqn(invars, [trace.makevar(out_tracer)],\n- broadcast_in_dim_p, params, core.no_effects, source_info)\n- trace.frame.eqns.append(eqn)\n-\n- return out_tracer\n+ return _stage_with_dyn_shape(trace, broadcast_in_dim_p,\n+ (x,), dyn_shape, params,\n+ shape, x.dtype, x.weak_type)\ndef _broadcast_in_dim_padding_rule(in_avals, out_avals, x, *dyn_shape,\nshape, broadcast_dimensions):\n@@ -2746,9 +2781,7 @@ def _broadcast_in_dim_partial_eval(\ndef _broadcast_in_dim_lower(ctx, x, *dyn_shape, shape, broadcast_dimensions):\naval_out, = ctx.avals_out\nif dyn_shape:\n- dyn_shape = iter(dyn_shape)\n- shape = [next(dyn_shape) if d is None else d for d in shape]\n- assert next(dyn_shape, None) is None\n+ shape = _merge_dyn_shape(shape, dyn_shape)\nreturn mhlo.DynamicBroadcastInDimOp(\nmlir.aval_to_ir_type(aval_out), x,\nmlir.shape_tensor(shape),\n@@ -3115,7 +3148,8 @@ def _reshape_shape_rule(operand, *, new_sizes, dimensions):\nif not all(core.greater_equal_dim(d, 0) for d in new_sizes):\nmsg = 'reshape new_sizes must all be positive, got {}.'\nraise TypeError(msg.format(new_sizes))\n- if not core.same_shape_sizes(np.shape(operand), new_sizes):\n+ # TODO(necula): re-enable this check\n+ if not config.jax_dynamic_shapes and not core.same_shape_sizes(np.shape(operand), new_sizes):\nmsg = 'reshape total size must be unchanged, got new_sizes {} for shape {}.'\nraise TypeError(msg.format(new_sizes, np.shape(operand)))\nif dimensions is not None:\n@@ -3168,13 +3202,30 @@ ad.deflinear2(reshape_p, _reshape_transpose_rule)\nbatching.primitive_batchers[reshape_p] = _reshape_batch_rule\nmasking.masking_rules[reshape_p] = _reshape_masking_rule\n-def _reshape_lower(ctx, x, *, new_sizes, dimensions):\n+def _reshape_lower(ctx, x, *dyn_shape, new_sizes, dimensions):\naval_out, = ctx.avals_out\nif dimensions is not None:\nx = mhlo.TransposeOp(x, mlir.dense_int_elements(dimensions)).result\n+ if dyn_shape:\n+ shape = _merge_dyn_shape(new_sizes, dyn_shape)\n+ return mhlo.DynamicReshapeOp(\n+ mlir.aval_to_ir_type(aval_out), x,\n+ mlir.shape_tensor(shape),\n+ ).results\n+ else:\nreturn mhlo.ReshapeOp(mlir.aval_to_ir_type(aval_out), x).results\n+\nmlir.register_lowering(reshape_p, _reshape_lower)\n+def _reshape_staging_rule(\n+ trace, x, *dyn_shape, new_sizes, dimensions):\n+ params = dict(new_sizes=new_sizes, dimensions=dimensions)\n+ # TODO(necula): shouldn't this include the same checks as in reshape_shape_rule?\n+ return _stage_with_dyn_shape(trace, reshape_p, (x,), dyn_shape, params,\n+ new_sizes, x.dtype, x.weak_type)\n+\n+pe.custom_staging_rules[reshape_p] = _reshape_staging_rule\n+\ndef _rev_shape_rule(operand, *, dimensions):\n_check_shapelike('rev', 'dimensions', dimensions)\nif len(set(dimensions)) != len(dimensions):\n@@ -4325,9 +4376,36 @@ iota_p = Primitive('iota')\niota_p.def_impl(partial(xla.apply_primitive, iota_p))\niota_p.def_abstract_eval(_iota_abstract_eval)\n-def _iota_lower(ctx, *, dtype, shape, dimension):\n- del dtype, shape\n+def _iota_staging_rule(\n+ trace, *dyn_shape, dtype, shape, dimension):\n+ params = dict(dtype=dtype, shape=shape, dimension=dimension)\n+ return _stage_with_dyn_shape(trace, iota_p, (), dyn_shape, params,\n+ shape, dtype, False)\n+pe.custom_staging_rules[iota_p] = _iota_staging_rule\n+\n+def _iota_typecheck_rule(*dyn_shape, dtype, shape, dimension):\n+ if not dyn_shape:\n+ out_aval, effects = iota_p.abstract_eval(\n+ dtype=dtype, shape=shape, dimension=dimension)\n+ return [out_aval], effects\n+ else:\n+ out_shape = _merge_dyn_shape(shape, dyn_shape)\n+ out_shape = [x.val if type(x) is core.Literal else x for x in out_shape]\n+ out_aval = core.DShapedArray(tuple(out_shape), dtype, False)\n+ return [out_aval], core.no_effects\n+core.custom_typechecks[iota_p] = _iota_typecheck_rule\n+\n+def _iota_lower(ctx, *dyn_shape, dtype, shape, dimension):\n+ del dtype\naval_out, = ctx.avals_out\n+ if dyn_shape:\n+ shape = _merge_dyn_shape(shape, dyn_shape)\n+ return mhlo.DynamicIotaOp(\n+ mlir.aval_to_ir_type(aval_out),\n+ mlir.shape_tensor(shape),\n+ mlir.i64_attr(dimension),\n+ ).results\n+ else:\nreturn mhlo.IotaOp(mlir.aval_to_ir_type(aval_out),\nmlir.i64_attr(dimension)).results\nmlir.register_lowering(iota_p, _iota_lower)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -2094,7 +2094,7 @@ def arange(start: core.DimSize, stop: Optional[core.DimSize]=None,\nraise ValueError(\n\"jax.numpy.arange supports non-constant arguments only in single-argument form. \"\nf\"Found jax.numpy.arange(start={start}, stop={stop}, step={step})\")\n- return lax.iota(int_, start)\n+ return lax.iota(dtype or int_, start)\nif dtype is None:\ndtype = result_type(start, *(x for x in [stop, step] if x is not None))\ndtype = _jnp_dtype(dtype)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1653,10 +1653,6 @@ def symbolic_equal_shape(s1: Shape, s2: Shape) -> bool:\nall(unsafe_map(symbolic_equal_dim, s1, s2)))\ndef greater_equal_dim(d1: DimSize, d2: DimSize) -> bool:\n- # TODO(mattjj): revise this temporary workaround for dynamic shapes\n- if isinstance(d1, Tracer) or isinstance(d2, Tracer):\n- return True\n-\nhandler, ds = _dim_handler_and_canonical(d1, d2)\nreturn handler.greater_equal(*ds)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -54,6 +54,8 @@ zip, unsafe_zip = util.safe_zip, zip\nT = typing.TypeVar(\"T\")\n+Value = ir.Value\n+\n# mypy implicitly sets this variable to true when type checking.\nMYPY = False\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -2365,6 +2365,44 @@ def _substitute_vars_in_type(\nelse:\nreturn a\n+\n+class DimensionHandlerTracer(core.DimensionHandler):\n+ \"\"\"See core.DimensionHandler.\n+\n+ Most methods are inherited.\n+ \"\"\"\n+ def is_constant(self, d: core.DimSize) -> bool:\n+ assert isinstance(d, Tracer)\n+ return False\n+\n+ def symbolic_equal(self, d1: core.DimSize, d2: core.DimSize) -> bool:\n+ return d1 is d2\n+\n+ def greater_equal(self, d1: core.DimSize, d2: core.DimSize):\n+ raise core.InconclusiveDimensionOperation(\"TODO\")\n+\n+ def divide_shape_sizes(self, s1: core.Shape, s2: core.Shape) -> core.DimSize:\n+ \"\"\"Computes integer \"i\" such that i * size(s2) == size(s1).\n+\n+ Raise InconclusiveDimensionOperation if there is no such integer for all\n+ contexts.\n+ \"\"\"\n+ s1_size = functools.reduce(op.mul, s1, 1)\n+ s2_size = functools.reduce(op.mul, s2, 1)\n+ q, r = divmod(s1_size, s2_size)\n+ # TODO(necula): must check that r == 0!\n+ return q\n+\n+ def stride(self, d: core.DimSize, window_size: core.DimSize, window_stride: core.DimSize) -> core.DimSize:\n+ \"\"\"Implements `(d - window_size) // window_stride + 1`\"\"\"\n+ raise core.InconclusiveDimensionOperation(\"TODO\")\n+\n+ def as_value(self, d: core.DimSize):\n+ \"\"\"Turns a dimension size into a Jax value that we can compute with.\"\"\"\n+ raise core.InconclusiveDimensionOperation(\"TODO\")\n+\n+core._SPECIAL_DIMENSION_HANDLERS[DynamicJaxprTracer] = DimensionHandlerTracer()\n+\nConst = Any\nVal = Any\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -8986,8 +8986,8 @@ class DynamicShapeTest(jtu.JaxTestCase):\ncount += 1\nreturn jnp.sum(x)\n- x = f(jnp.arange(3))\n- y = f(jnp.arange(4))\n+ x = f(np.arange(3))\n+ y = f(np.arange(4))\nself.assertAllClose(x, 3., check_dtypes=False)\nself.assertAllClose(y, 6., check_dtypes=False)\nself.assertEqual(count, 1)\n@@ -9003,10 +9003,119 @@ class DynamicShapeTest(jtu.JaxTestCase):\ncount += 1\nreturn jnp.ones(i, dtype='float32')\n- self.assertAllClose(f(3), jnp.ones(3, dtype='float32'), check_dtypes=True)\n- self.assertAllClose(f(4), jnp.ones(4, dtype='float32'), check_dtypes=True)\n+ self.assertAllClose(f(3), np.ones(3, dtype='float32'), check_dtypes=True)\n+ self.assertAllClose(f(4), np.ones(4, dtype='float32'), check_dtypes=True)\nself.assertEqual(count, 1)\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ @unittest.skip(\"TODO: need typechecking rule for concatenate\")\n+ def test_concatenate(self):\n+ @partial(jax.jit, abstracted_axes=({0: 'n'},))\n+ def f(x): # x: f32[n, 4]\n+ return jnp.concatenate([x, x, x], axis=0)\n+\n+ f(np.ones((5, 4), dtype=np.float32))\n+ # TODO: add assertions\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_reshape(self):\n+ @partial(jax.jit, abstracted_axes=({0: 'n'},))\n+ def f(x): # x: f32[n, 4]\n+ return jnp.reshape(x, (2, -1))\n+\n+ f(np.ones((5, 4), dtype=np.float32))\n+ # TODO: add assertions\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_nested(self):\n+ @jax.jit\n+ def nested_f(x): # f32[h, v] -> f32[h, v]\n+ # A nested call that needs shape variables\n+ return jnp.sin(x)\n+\n+ @partial(jax.jit, abstracted_axes=({0: 'h', 1: 'v'},))\n+ def f(x): # f32[h, w] -> f32[h, w]\n+ return jnp.sin(x) + jax.jit(nested_f)(x)\n+ f(np.ones((3, 5), dtype=np.float32))\n+ # TODO: add assertions\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_nested_arange(self):\n+ def nested_f(x): # f32[h, v] -> f32[h, v]\n+ # A nested call that needs to compute with shapes\n+ return jnp.arange(x.shape[0] * x.shape[1], dtype=x.dtype).reshape(x.shape)\n+\n+ @partial(jax.jit, abstracted_axes=({0: 'h', 1: 'w'},))\n+ def f(x): # f32[h, w] -> f32[h, w]\n+ return x + jax.jit(nested_f)(x)\n+ f(np.ones((3, 5), dtype=np.float32))\n+ # TODO: add assertions\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ @unittest.skip(\"TODO: investigate failure\")\n+ def test_transpose(self):\n+ @partial(jax.jit, abstracted_axes=({0: 'h', 1: 'w'},))\n+ def f(x): # f32[h, w] -> f32[w, h]\n+ return x.T\n+\n+ f(np.ones((3, 5), dtype=np.float32))\n+ # TODO: add assertions\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_matmul(self):\n+ @partial(jax.jit, abstracted_axes=({0: 'w', 1: 'w'},))\n+ def f(x): # f32[w, w] -> f32[w, w]\n+ return jnp.matmul(x, x)\n+\n+ f(np.ones((5, 5), dtype=np.float32))\n+ # TODO: add assertions\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_matmul_shape_error(self):\n+ @partial(jax.jit, abstracted_axes=({0: 'h', 1: 'w'},))\n+ def f(x): # f32[h, w] -> error\n+ return jnp.matmul(x, x)\n+\n+ with self.assertRaisesRegex(TypeError,\n+ re.escape(\"dot_general requires contracting dimensions to have the same shape, got (w,) and (h,)\")):\n+ f(np.ones((5, 5), dtype=np.float32))\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ @unittest.skip(\"TODO: investigate failure\")\n+ def test_cond(self):\n+ @partial(jax.jit, abstracted_axes=({0: 'w', 1: 'w'},))\n+ def f(x): # f32[w, w] -> f32[w, w]\n+ return lax.cond(True,\n+ lambda x: jnp.sin(x),\n+ lambda x: jnp.matmul(x, x), x)\n+ f(np.ones((5, 5), dtype=np.float32))\n+ # TODO: add assertions\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_arange(self):\n+ @partial(jax.jit, abstracted_axes=({0: 'w'},))\n+ def f(x): # f32[w] -> f32[w]\n+ return jnp.arange(x.shape[0], dtype=x.dtype) + x\n+ f(np.ones((5,), dtype=np.float32))\n+ # TODO: add assertions\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_broadcast(self):\n+ @partial(jax.jit, abstracted_axes=({0: 'w'},))\n+ def f(x): # f32[w] -> f32[w, w]\n+ return jnp.broadcast_to(x, (x.shape[0], x.shape[0]))\n+ f(np.ones((5,), dtype=np.float32))\n+ # TODO: add assertions\n+\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_stack(self):\n+ @partial(jax.jit, abstracted_axes=({0: 'w'},))\n+ def f(x):\n+ return jnp.stack([jnp.sin(x), jnp.cos(x)])\n+\n+ f(np.ones((5,), dtype=np.float32))\n+ # TODO: add assertions\n+\ndef test_slicing_basic(self):\nf = jax.jit(lambda x, n: jnp.sum(x[:n]))\n# TODO(mattjj): revise getslice, add typecheck rule for it, enable checks\n" } ]
Python
Apache License 2.0
google/jax
[dynamic-shapes] Expand the handling of dynamic shapes for reshape and iota. Also add more tests.
260,287
05.07.2022 11:15:39
0
7439e1b1f84d093c078c6c86bfcd4eed51b00a14
Properly count sublevels when tracing xmap body Otherwise it can lead to tracer leak errors. I'm not a 100% sure how this works out, because the sublevel counting has changed since I read it previously. This replicates the changes applied to DynamicJaxprTrace.process_map since I last looked at it.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1015,6 +1015,7 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nmapped_in_avals = [_delete_aval_axes(a, a_in_axes, global_axis_sizes)\nfor a, a_in_axes in zip(in_avals, params['in_axes'])]\nwith core.extend_axis_env_nd(global_axis_sizes.items()):\n+ with core.new_sublevel():\njaxpr, mapped_out_avals, consts = trace_to_subjaxpr_dynamic(\nf, self.main, mapped_in_avals)\nout_axes = params['out_axes_thunk']()\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -365,6 +365,19 @@ class XMapTest(XMapTestCase):\nxmap(f, in_axes=['a', ...], out_axes=['a', ...],\naxis_resources={'a': 'x'})(x)\n+ def testNoTracerLeak(self):\n+ @jax.jit\n+ def xmap_linearize(xs):\n+ eye = jnp.eye(xs.shape[0], dtype=jnp.float32)\n+ primal, grad_f = jax.linearize(jnp.sin, xs)\n+ return maps.xmap(\n+ grad_f,\n+ in_axes=['i', ...],\n+ out_axes=['i', ...],\n+ axis_resources={'i': maps.SerialLoop(1)})(eye)\n+ xs = jnp.arange(1, 4, step=1).astype(jnp.float32)\n+ xmap_linearize(xs) # Doesn't raise a tracer leak error\n+\n@parameterized.named_parameters(\n{\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\nfor name, mesh, axis_resources in (\n" } ]
Python
Apache License 2.0
google/jax
Properly count sublevels when tracing xmap body Otherwise it can lead to tracer leak errors. I'm not a 100% sure how this works out, because the sublevel counting has changed since I read it previously. This replicates the changes applied to DynamicJaxprTrace.process_map since I last looked at it.
260,411
05.07.2022 14:01:19
-7,200
dc3d7763119ff8171def4c07f62834574a73f5ef
[shape_poly] Refactor tests to separate the vmap tests Introduce ShapePolyVmapPrimitivesTest to contain all the tests that vmap results in batch polymprphic code. Also fix some warnings about eig, eigh, and qr taking only kwarg arguments.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -1648,9 +1648,8 @@ for dtype in jtu.dtypes.all_floating + jtu.dtypes.complex:\ndefine(\nlax.linalg.qr_p,\nf\"multi_array_shape={jtu.format_shape_dtype_string(shape, dtype)}_fullmatrices={full_matrices}\",\n- lax.linalg.qr,\n- [RandArg(shape, dtype),\n- StaticArg(full_matrices)],\n+ partial(lax.linalg.qr, full_matrices=full_matrices),\n+ [RandArg(shape, dtype)],\n# See jax._src.lib.lapack.geqrf for the list of compatible types\njax_unimplemented=[\nLimitation(\n@@ -1758,10 +1757,9 @@ for dtype in jtu.dtypes.all_inexact:\ndefine(\nlax.linalg.eig_p,\nf\"shape={jtu.format_shape_dtype_string(shape, dtype)}_computelefteigenvectors={compute_left_eigenvectors}_computerighteigenvectors={compute_right_eigenvectors}\",\n- lax.linalg.eig, [\n+ partial(lax.linalg.eig, compute_left_eigenvectors=compute_left_eigenvectors, compute_right_eigenvectors=compute_right_eigenvectors),\n+ [\nRandArg(shape, dtype),\n- StaticArg(compute_left_eigenvectors),\n- StaticArg(compute_right_eigenvectors)\n],\njax_unimplemented=[\nLimitation(\n@@ -1795,8 +1793,7 @@ for dtype in jtu.dtypes.all_inexact:\n# Make operand lower/upper triangular\nlambda operand, lower, symmetrize_input: (lax.linalg.eigh(\njnp.tril(operand)\n- if lower else jnp.triu(operand), lower, symmetrize_input)),\n- # lax.linalg.eigh,\n+ if lower else jnp.triu(operand), lower=lower, symmetrize_input=symmetrize_input)),\n[\nCustomArg(\npartial(_make_triangular_eigh_operand, shape, dtype, lower)),\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "diff": "@@ -1718,134 +1718,9 @@ _POLY_SHAPE_TEST_HARNESSES = [\npoly_axes=[0, None, 0]),\n]\n-### We add to the test harnesses some that are obtained from the\n-### primitive harnesses by applying vmap to the function and then asserting\n-### that we can convert shape polymorphically the result.\n-\n-def _add_vmap_primitive_harnesses():\n- \"\"\"For each harness group, pick a single dtype.\n-\n- Ignore harnesses that fail in graph mode in jax2tf.\n- \"\"\"\n- all_h = primitive_harness.all_harnesses\n- # Index by group\n- harness_groups: Dict[\n- str, Sequence[primitive_harness.Harness]] = collections.defaultdict(list)\n- device = jtu.device_under_test()\n-\n- for h in all_h:\n- # Drop the JAX limitations\n- if not h.filter(device_under_test=device, include_jax_unimpl=False):\n- continue\n- # And the jax2tf limitations that are known to result in TF error.\n- if any(l.expect_tf_error for l in _get_jax2tf_limitations(device, h)):\n- continue\n- # TODO(marcvanzee): We currently exclude tests with enable_xla=False because\n- # this doesn't work with vmap due to a call to lax.gather. We should include\n- # them once vmap works with enable_xla=False.\n- if not h.params.get(\"enable_xla\", True):\n- continue\n- harness_groups[h.group_name].append(h)\n-\n- selected_harnesses = []\n- for group_name, hlist in harness_groups.items():\n- # Pick the dtype with the most harnesses in this group. Some harness\n- # groups only test different use cases at a few dtypes.\n- c = collections.Counter([h.dtype for h in hlist])\n- (dtype, _), = c.most_common(1)\n- selected_harnesses.extend([h for h in hlist if h.dtype == dtype])\n-\n- # We do not yet support shape polymorphism for vmap for some primitives\n- _NOT_SUPPORTED_YET = frozenset([\n- # In linalg._lu_python we do reshape(-1, ...)\n- \"lu\",\n- \"custom_linear_solve\",\n-\n- # We do *= shapes in the batching rule for conv_general_dilated\n- \"conv_general_dilated\",\n-\n- \"tridiagonal_solve\", # batching not implemented in JAX\n- \"iota\", # vmap does not make sense for 0-argument functions\n- \"rng_bit_generator\", # vmap not implemented\n- ])\n-\n- batch_size = 3\n- for h in selected_harnesses:\n- if h.group_name in _NOT_SUPPORTED_YET:\n- continue\n-\n- def make_batched_arg_descriptor(\n- ad: primitive_harness.ArgDescriptor) -> Optional[primitive_harness.ArgDescriptor]:\n- if isinstance(ad, RandArg):\n- return RandArg((batch_size,) + ad.shape, ad.dtype)\n- elif isinstance(ad, CustomArg):\n- def wrap_custom(rng):\n- arg = ad.make(rng)\n- return np.stack([arg] * batch_size)\n-\n- return CustomArg(wrap_custom)\n- else:\n- assert isinstance(ad, np.ndarray), ad\n- return np.stack([ad] * batch_size)\n-\n- new_args = [make_batched_arg_descriptor(ad)\n- for ad in h.arg_descriptors\n- if not isinstance(ad, StaticArg)]\n-\n- # This test does not make sense for nullary functions\n- if not new_args:\n- continue\n-\n- # We do not check the result of harnesses that require custom assertions.\n- check_result = all(not l.custom_assert and not l.skip_comparison and l.tol is None\n- for l in _get_jax2tf_limitations(device, h))\n- vmap_harness = _make_harness(h.group_name, f\"vmap_{h.name}\",\n- jax.vmap(h.dyn_fun, in_axes=0, out_axes=0),\n- new_args,\n- poly_axes=[0] * len(new_args),\n- check_result=check_result,\n- **h.params)\n- _POLY_SHAPE_TEST_HARNESSES.append(vmap_harness)\n-\n-\n-def _get_jax2tf_limitations(\n- device, h: primitive_harness.Harness) -> Sequence[Jax2TfLimitation]:\n- # And the jax2tf limitations\n- def applicable_jax2tf_limitation(l: Jax2TfLimitation) -> bool:\n- # The CheckShapePolymorphism uses tf.function, so we care about \"graph\"\n- return l.filter(device=device, dtype=h.dtype, mode=\"graph\")\n-\n- limitations = Jax2TfLimitation.limitations_for_harness(h)\n- return tuple(filter(applicable_jax2tf_limitation, limitations))\n-\n-\n-_add_vmap_primitive_harnesses()\n-\n-def _flatten_harnesses(harnesses):\n- res = []\n- for h in harnesses:\n- if isinstance(h, Sequence):\n- res.extend(h)\n- else:\n- res.append(h)\n- return res\n-\n-class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n- \"\"\"Tests for primitives that take shape values as parameters.\"\"\"\n-\n- # This test runs for all _POLY_SHAPE_PRIMITIVE_HARNESSES.\n-\n- # For each primitive \"xxx\" the test will be called \"test_prim_xxx_...\".\n- # If you want to run this test for only one harness that includes \"foo\"\n- # in the name (after test_prim), add parameter `one_containing=\"foo\"`\n- # to parameterized below.\n- @primitive_harness.parameterized(\n- _flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"take_along_axis_1_poly_axes=[0, 0]\"\n- )\n- def test_prim(self, harness: Harness):\n- args = harness.dyn_args_maker(self.rng())\n+def _test_one_harness(tst: tf_test_util.JaxToTfTestCase, harness: Harness):\n+ args = harness.dyn_args_maker(tst.rng())\npoly_axes = harness.params[\"poly_axes\"] # type: Sequence[Sequence[int]]\nassert len(args) == len(poly_axes)\n# Make the polymorphic_shapes and input_signature\n@@ -1881,15 +1756,15 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nenable_xla = harness.params.get(\"enable_xla\", True)\nexpect_error_type, expect_error_regex = harness.params[\"expect_error\"]\nif expect_error_type is not None:\n- with self.assertRaisesRegex(expect_error_type, expect_error_regex):\n- f_tf = self.CheckShapePolymorphism(\n+ with tst.assertRaisesRegex(expect_error_type, expect_error_regex):\n+ f_tf = tst.CheckShapePolymorphism(\nharness.dyn_fun,\ninput_signature=input_signature,\npolymorphic_shapes=polymorphic_shapes,\nexpected_output_signature=None,\nenable_xla=enable_xla)\nelse:\n- f_tf = self.CheckShapePolymorphism(\n+ f_tf = tst.CheckShapePolymorphism(\nharness.dyn_fun,\ninput_signature=input_signature,\npolymorphic_shapes=polymorphic_shapes,\n@@ -1898,8 +1773,44 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nif not skip_jax_run and expect_error_type is None and harness.params[\"check_result\"]:\ntol = harness.params[\"tol\"]\n- self.assertAllClose(res_jax, f_tf(*args), atol=tol, rtol=tol)\n+ tst.assertAllClose(res_jax, f_tf(*args), atol=tol, rtol=tol)\n+\n+\n+def _get_jax2tf_limitations(\n+ device, h: primitive_harness.Harness) -> Sequence[Jax2TfLimitation]:\n+ # And the jax2tf limitations\n+ def applicable_jax2tf_limitation(l: Jax2TfLimitation) -> bool:\n+ # The CheckShapePolymorphism uses tf.function, so we care about \"graph\"\n+ return l.filter(device=device, dtype=h.dtype, mode=\"graph\")\n+ limitations = Jax2TfLimitation.limitations_for_harness(h)\n+ return tuple(filter(applicable_jax2tf_limitation, limitations))\n+\n+\n+def _flatten_harnesses(harnesses):\n+ res = []\n+ for h in harnesses:\n+ if isinstance(h, Sequence):\n+ res.extend(h)\n+ else:\n+ res.append(h)\n+ return res\n+\n+class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n+ \"\"\"Tests for primitives that take shape values as parameters.\"\"\"\n+\n+ # This test runs for all _POLY_SHAPE_PRIMITIVE_HARNESSES.\n+\n+ # For each primitive \"xxx\" the test will be called \"test_prim_xxx_...\".\n+ # If you want to run this test for only one harness that includes \"foo\"\n+ # in the name (after test_prim), add parameter `one_containing=\"foo\"`\n+ # to parameterized below.\n+ @primitive_harness.parameterized(\n+ _flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n+ #one_containing=\"take_along_axis_1_poly_axes=[0, 0]\"\n+ )\n+ def test_prim(self, harness: Harness):\n+ _test_one_harness(self, harness)\ndef test_vmap_while(self):\ndef cond_func(x): # x: f32[3]\n@@ -1949,6 +1860,117 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(res_jax, f_tf(x))\nself.assertFalse(traced) # We are not tracing again\n+### We add to the test harnesses some that are obtained from the\n+### primitive harnesses by applying vmap to the function and then asserting\n+### that we can convert shape polymorphically the result.\n+\n+def _make_vmap_primitive_harnesses():\n+ \"\"\"For each harness group, pick a single dtype.\n+\n+ Ignore harnesses that fail in graph mode in jax2tf.\n+ \"\"\"\n+ all_h = primitive_harness.all_harnesses\n+ res = []\n+\n+ # Index by group\n+ harness_groups: Dict[\n+ str, Sequence[primitive_harness.Harness]] = collections.defaultdict(list)\n+ device = jtu.device_under_test()\n+\n+ for h in all_h:\n+ # Drop the JAX limitations\n+ if not h.filter(device_under_test=device, include_jax_unimpl=False):\n+ continue\n+ # And the jax2tf limitations that are known to result in TF error.\n+ if any(l.expect_tf_error for l in _get_jax2tf_limitations(device, h)):\n+ continue\n+ # TODO(marcvanzee): We currently exclude tests with enable_xla=False because\n+ # this doesn't work with vmap due to a call to lax.gather. We should include\n+ # them once vmap works with enable_xla=False.\n+ if not h.params.get(\"enable_xla\", True):\n+ continue\n+ harness_groups[h.group_name].append(h)\n+\n+ selected_harnesses = []\n+ for group_name, hlist in harness_groups.items():\n+ # Pick the dtype with the most harnesses in this group. Some harness\n+ # groups only test different use cases at a few dtypes.\n+ c = collections.Counter([h.dtype for h in hlist])\n+ (dtype, _), = c.most_common(1)\n+ selected_harnesses.extend([h for h in hlist if h.dtype == dtype])\n+\n+ # We do not yet support shape polymorphism for vmap for some primitives\n+ _NOT_SUPPORTED_YET = frozenset([\n+ # In linalg._lu_python we do reshape(-1, ...)\n+ \"lu\",\n+ \"custom_linear_solve\",\n+\n+ # We do *= shapes in the batching rule for conv_general_dilated\n+ \"conv_general_dilated\",\n+\n+ \"tridiagonal_solve\", # batching not implemented in JAX\n+ \"iota\", # vmap does not make sense for 0-argument functions\n+ \"rng_bit_generator\", # vmap not implemented\n+ ])\n+\n+ batch_size = 3\n+ for h in selected_harnesses:\n+ if h.group_name in _NOT_SUPPORTED_YET:\n+ continue\n+\n+ def make_batched_arg_descriptor(\n+ ad: primitive_harness.ArgDescriptor) -> Optional[primitive_harness.ArgDescriptor]:\n+ if isinstance(ad, RandArg):\n+ return RandArg((batch_size,) + ad.shape, ad.dtype)\n+ elif isinstance(ad, CustomArg):\n+ def wrap_custom(rng):\n+ arg = ad.make(rng)\n+ return np.stack([arg] * batch_size)\n+\n+ return CustomArg(wrap_custom)\n+ else:\n+ assert isinstance(ad, np.ndarray), ad\n+ return np.stack([ad] * batch_size)\n+\n+ new_args = [make_batched_arg_descriptor(ad)\n+ for ad in h.arg_descriptors\n+ if not isinstance(ad, StaticArg)]\n+\n+ # This test does not make sense for nullary functions\n+ if not new_args:\n+ continue\n+\n+ # We do not check the result of harnesses that require custom assertions.\n+ check_result = all(not l.custom_assert and not l.skip_comparison and l.tol is None\n+ for l in _get_jax2tf_limitations(device, h))\n+ vmap_harness = _make_harness(h.group_name, h.name,\n+ jax.vmap(h.dyn_fun, in_axes=0, out_axes=0),\n+ new_args,\n+ poly_axes=[0] * len(new_args),\n+ check_result=check_result,\n+ **h.params)\n+ res.append(vmap_harness)\n+ return res\n+\n+_POLY_SHAPE_VMAP_TEST_HARNESSES = _make_vmap_primitive_harnesses()\n+\n+\n+class ShapePolyVmapPrimitivesTest(tf_test_util.JaxToTfTestCase):\n+ \"\"\"Tests that we can handle batch polymorphism for vmapped primitives.\"\"\"\n+\n+ # This test runs for all _POLY_SHAPE_VMAP_PRIMITIVE_HARNESSES.\n+\n+ # For each primitive \"xxx\" the test will be called \"test_vmap_prim_xxx_...\".\n+ # If you want to run this test for only one harness that includes \"foo\"\n+ # in the name (after test_prim), add parameter `one_containing=\"foo\"`\n+ # to parameterized below.\n+ @primitive_harness.parameterized(\n+ _flatten_harnesses(_POLY_SHAPE_VMAP_TEST_HARNESSES),\n+ #one_containing=\"eig_shape=float32[0,0]_computelefteigenvectors=False_computerighteigenvectors=False_poly_axes=[0]\"\n+ )\n+ def test_vmap_prim(self, harness: Harness):\n+ return _test_one_harness(self, harness)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[shape_poly] Refactor tests to separate the vmap tests Introduce ShapePolyVmapPrimitivesTest to contain all the tests that vmap results in batch polymprphic code. Also fix some warnings about eig, eigh, and qr taking only kwarg arguments.
260,287
05.07.2022 12:06:47
25,200
5777c1eac26fe96e4039c343de3b2b8f04ea7339
Add support for post_process of xmap in BatchTrace
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -49,7 +49,7 @@ from jax.interpreters import batching\nfrom jax.interpreters import ad\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\n-from jax._src.util import (safe_map, safe_zip, HashableFunction, unzip2,\n+from jax._src.util import (safe_map, safe_zip, HashableFunction, unzip2, unzip3,\nas_hashable_function, distributed_debug_log,\ntuple_insert, moveaxis, split_list, wrap_name,\nmerge_lists, partition_list)\n@@ -848,7 +848,10 @@ class XMapPrimitive(core.MapPrimitive):\nreturn trace.process_xmap(self, fun, tracers, params)\ndef post_process(self, trace, out_tracers, params):\n+ post_process = getattr(trace, 'post_process_xmap', None)\n+ if post_process is None:\nraise NotImplementedError\n+ return post_process(self, out_tracers, params)\ndef get_bind_params(self, params):\nnew_params = dict(params)\n@@ -1228,6 +1231,17 @@ def _batch_trace_update_spmd_axes(\nreturn new_spmd_in_axes, new_spmd_out_axes_thunk\n+def _axis_after_insertion(axis, inserted_named_axes):\n+ for inserted_axis in sorted(inserted_named_axes.values()):\n+ if inserted_axis >= axis:\n+ break\n+ axis += 1\n+ return axis\n+\n+def _fmap_dims(axes, f):\n+ return AxisNamePos(((name, f(axis)) for name, axis in axes.items()),\n+ user_repr=axes.user_repr)\n+\ndef _batch_trace_process_xmap(self, is_spmd, primitive, f: lu.WrappedFun, tracers, params):\nnot_mapped = batching.not_mapped\nvals, dims = unzip2((t.val, t.batch_dim) for t in tracers)\n@@ -1236,25 +1250,16 @@ def _batch_trace_process_xmap(self, is_spmd, primitive, f: lu.WrappedFun, tracer\nreturn primitive.bind(f, *vals, **params)\nelse:\nassert len({x.shape[d] for x, d in zip(vals, dims) if d is not not_mapped}) == 1\n- def fmap_dims(axes, f):\n- return AxisNamePos(((name, f(axis)) for name, axis in axes.items()),\n- user_repr=axes.user_repr)\nnew_in_axes = tuple(\n- fmap_dims(in_axes, lambda a: a + (d is not not_mapped and d <= a))\n+ _fmap_dims(in_axes, lambda a: a + (d is not not_mapped and d <= a))\nfor d, in_axes in zip(dims, params['in_axes']))\nmapped_dims_in = tuple(\nd if d is not_mapped else d - sum(a < d for a in in_axis.values())\nfor d, in_axis in zip(dims, params['in_axes']))\nf, mapped_dims_out = batching.batch_subtrace(f, self.main, mapped_dims_in)\nout_axes_thunk: Callable[[], Sequence[AxisNamePos]] = params['out_axes_thunk']\n- dims_out_thunk = lambda: tuple(d if d is not_mapped else axis_after_insertion(d, out_axes)\n+ dims_out_thunk = lambda: tuple(d if d is not_mapped else _axis_after_insertion(d, out_axes)\nfor d, out_axes in zip(mapped_dims_out(), out_axes_thunk()))\n- def axis_after_insertion(axis, inserted_named_axes):\n- for inserted_axis in sorted(inserted_named_axes.values()):\n- if inserted_axis >= axis:\n- break\n- axis += 1\n- return axis\n# NOTE: This assumes that the choice of the dimensions over which outputs\n# are batched is entirely dependent on the function and not e.g. on the\n# data or its shapes.\n@@ -1262,7 +1267,7 @@ def _batch_trace_process_xmap(self, is_spmd, primitive, f: lu.WrappedFun, tracer\ndef new_out_axes_thunk():\nreturn tuple(\nout_axes if d is not_mapped else\n- fmap_dims(out_axes, lambda a, nd=axis_after_insertion(d, out_axes): a + (nd <= a))\n+ _fmap_dims(out_axes, lambda a, nd=_axis_after_insertion(d, out_axes): a + (nd <= a))\nfor out_axes, d in zip(out_axes_thunk(), mapped_dims_out()))\nif not is_spmd:\n@@ -1285,6 +1290,23 @@ batching.BatchTrace.process_xmap = partialmethod(_batch_trace_process_xmap, Fals\npxla.SPMDBatchTrace.process_xmap = partialmethod(_batch_trace_process_xmap, True) # type: ignore\n+def _batch_trace_post_process_xmap(self, primitive, out_tracers, params):\n+ not_mapped = batching.not_mapped\n+ BT = batching.BatchTracer\n+ vals, dims, srcs = unzip3((t.val, t.batch_dim, t.source_info) for t in out_tracers)\n+ main = self.main\n+ def todo(vals):\n+ trace = main.with_cur_sublevel()\n+ return [BT(trace, v, d if d is not_mapped else _axis_after_insertion(d, oa), s)\n+ for v, d, oa, s in zip(vals, dims, params['out_axes_thunk'](), srcs)]\n+ def out_axes_transform(out_axes):\n+ return tuple(oa if d is not_mapped else\n+ _fmap_dims(oa, lambda a, nd=_axis_after_insertion(d, oa): a + (nd <= a))\n+ for oa, d in zip(out_axes, dims))\n+ return vals, (todo, out_axes_transform)\n+batching.BatchTrace.post_process_xmap = _batch_trace_post_process_xmap\n+\n+\n# -------- nested xmap handling --------\ndef _xmap_lowering_rule(ctx, *args, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -552,6 +552,12 @@ class XMapTest(XMapTestCase):\ny = rng.randn(*yshape)\nself.assertAllClose(fm(x, y), fref(x, y))\n+ def testBatchingPostProcess(self):\n+ x = jnp.arange(10).reshape(5, 2)\n+ f = jax.vmap(lambda y: xmap(lambda x: x + y, in_axes=['i', ...], out_axes=['i', ...])(x))\n+ ref = jax.vmap(lambda y: jax.vmap(lambda x: x + y)(x))\n+ self.assertAllClose(f(x * 2), ref(x * 2))\n+\ndef testAutodiffBroadcast(self):\nf = xmap(lambda x, y: jnp.cos(lax.dot(x, jnp.sin(y),\nprecision=lax.Precision.HIGHEST)),\n" } ]
Python
Apache License 2.0
google/jax
Add support for post_process of xmap in BatchTrace PiperOrigin-RevId: 459108183
260,718
06.07.2022 10:59:02
14,400
de08344cb73b168220cfec77d3d3304339c88849
Avoid casting input to _fft_helper.
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/signal.py", "new_path": "jax/_src/scipy/signal.py", "diff": "@@ -26,8 +26,7 @@ from jax._src import dtypes\nfrom jax._src.numpy.lax_numpy import _check_arraylike\nfrom jax._src.numpy import lax_numpy as jnp\nfrom jax._src.numpy import linalg\n-from jax._src.numpy.lax_numpy import _promote_dtypes_inexact\n-from jax._src.numpy.util import _wraps\n+from jax._src.numpy.util import _wraps, _promote_dtypes_inexact, _promote_dtypes_complex\nfrom jax._src.third_party.scipy import signal_helper\nfrom jax._src.util import canonicalize_axis, tuple_delete, tuple_insert\n@@ -180,6 +179,8 @@ def _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides):\nresult = detrend_func(result)\n# Apply window by multiplication\n+ if jnp.iscomplexobj(win):\n+ result, = _promote_dtypes_complex(result)\nresult = win.reshape((1,) * len(batch_shape) + (1, nperseg)) * result\n# Perform the fft on last axis. Zero-pads automatically\n@@ -286,7 +287,7 @@ def _spectral_helper(x, y,\nraise ValueError('nperseg must be a positive integer')\n# parse window; if array like, then set nperseg = win.shape\nwin, nperseg = signal_helper._triage_segments(\n- window, nperseg, input_length=x.shape[axis], dtype=result_dtype)\n+ window, nperseg, input_length=x.shape[axis], dtype=x.dtype)\nif noverlap is None:\nnoverlap = nperseg // 2\n@@ -369,6 +370,7 @@ def _spectral_helper(x, y,\nraise ValueError(f'Unknown scaling: {scaling}')\nif mode == 'stft':\nscale = jnp.sqrt(scale)\n+ scale, = _promote_dtypes_complex(scale)\n# Determine onesided/ two-sided\nif return_onesided:\n@@ -386,12 +388,12 @@ def _spectral_helper(x, y,\nfreqs = jax.numpy.fft.rfftfreq(nfft, 1/fs).astype(freq_dtype)\n# Perform the windowed FFTs\n- result = _fft_helper(x.astype(result_dtype), win, detrend_func,\n+ result = _fft_helper(x, win, detrend_func,\nnperseg, noverlap, nfft, sides)\nif y is not None:\n# All the same operations on the y data\n- result_y = _fft_helper(y.astype(result_dtype), win, detrend_func,\n+ result_y = _fft_helper(y, win, detrend_func,\nnperseg, noverlap, nfft, sides)\nresult = jnp.conjugate(result) * result_y\nelif mode == 'psd':\n" } ]
Python
Apache License 2.0
google/jax
Avoid casting input to _fft_helper.
260,631
06.07.2022 12:35:50
25,200
354c684873373e16265d12816eddfa1872eba02d
[jax2tf] Update docs for supported convolution types.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/no_xla_limitations.md", "new_path": "jax/experimental/jax2tf/g3doc/no_xla_limitations.md", "diff": "@@ -59,23 +59,24 @@ lax.conv_general_dilated(\nWe provide support for convolutions as follows:\n-* Only 2D convolutions, i.e. `lhs.ndim == 4`.\n-* Regular convolutions and atrous convolutions\n+* Only 1D and 2D convolutions, i.e. `lhs.ndim == 3 or 4`.\n+* Regular convolutions and atrous (aka, dilated) convolutions\n(i.e., `rhs_dilation != (1, 1, ...)`) are supported through the TF op\n[`tf.nn.conv2d`](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d).\n* Transposed convolutions (i.e., `lhs_dilation != (1, 1, ...)`) are supported\nthrough\n- [`tf.nn.conv2d_transpose`](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d_transpose).\n- If using transposed convolutions, then `padding == 'VALID'`.\n+ [`tf.nn.conv2d_transpose`](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d_transpose),\n+ with either 'SAME' or 'VALID' padding.\n* Depthwise convolutions (i.e.\n`in_channels == feature_group_count and feature_group_count > 1`) are\nsupported through\n[`tf.nn.depthwise_conv2d`](https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d).\n+ Note that atrous depthwise convolutions are supported.\n* No support for batch groups, i.e. `batch_group_count == 1`.\n* No support for feature groups, except for depth-wise convolutions.\n* Input may be provided in any order (specified using `dimension_numbers`).\n-* Only one of depthwise, atrous and tranposed convolutions may be used at the\n- same time.\n+* Only one of depthwise, atrous and transposed convolutions may be used at the\n+ same time, though depthwise atrous convolutions are supported.\n### XlaGather\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Update docs for supported convolution types. PiperOrigin-RevId: 459316769
260,335
29.06.2022 13:55:30
25,200
6bb90fde9e074d4bb38a9a111383bc8ac720c81c
[dynamic shapes] revive iree
[ { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -192,7 +192,10 @@ def _device_from_arg_devices(devices: Sequence[Optional[Device]]) -> Optional[De\ndef _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name,\ndonated_invars, inline, keep_unused: bool):\ndel inline # Only used at tracing time\n+ if fun.in_type is None:\narg_specs = unsafe_map(arg_spec, args)\n+ else:\n+ arg_specs = [(None, getattr(x, '_device', None)) for x in args]\ncompiled_fun = xla_callable(fun, device, backend, name, donated_invars,\nkeep_unused, *arg_specs)\ntry:\n@@ -283,25 +286,8 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nin_type = tuple(unsafe_zip(abstract_args, itertools.repeat(True)))\nfun = lu.annotate(fun, in_type)\nelse:\n- # Check that the provided abstract_args are consistent with in_type by first\n- # collecting values of axis size arguments, then substituting them in for\n- # DBIdx occurrences.\n- axis_sizes: Dict[core.DBIdx, int] = {}\n- abstract_args_iter = iter(abstract_args)\n- for expected_type, explicit in fun.in_type:\n- if explicit:\n- aval = next(abstract_args_iter)\n- if isinstance(expected_type, core.DShapedArray):\n- # Check the value for any DBIdx variables is consistent.\n- assert all(axis_sizes.setdefault(d1, d2) == d2\n- for d1, d2 in zip(expected_type.shape, aval.shape)\n- if type(d1) is core.DBIdx)\n- # Check the type matches after substitution.\n- expected_shape = [axis_sizes.get(d, d) for d in expected_type.shape] # type: ignore\n- expected_aval = core.ShapedArray(\n- shape=tuple(expected_shape), dtype=expected_type.dtype,\n- weak_type=expected_type.weak_type)\n- assert core.typematch(expected_aval, aval)\n+ assert abstract_args == (None,) * len(abstract_args)\n+ abstract_args = [aval for aval, _ in fun.in_type]\nwith log_elapsed_time(f\"Finished tracing + transforming {fun.__name__} \"\n\"for jit in {elapsed_time} sec\"):\njaxpr, out_type, consts = pe.trace_to_jaxpr_final2(\n@@ -326,7 +312,7 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nif i in kept_var_idx]\ndel kept_const_idx\nelse:\n- kept_var_idx = set(range(len(abstract_args)))\n+ kept_var_idx = set(range(len(fun.in_type)))\nnreps = jaxpr_replicas(jaxpr)\ndevice = _xla_callable_device(nreps, backend, device, arg_devices)\n@@ -430,12 +416,10 @@ def jaxpr_has_pmap(jaxpr):\nreturn False\ndef jaxpr_has_bints(jaxpr: core.Jaxpr) -> bool:\n- return (any(type(d) is core.Var for v in jaxpr.invars\n- if type(v.aval) is core.DShapedArray for d in v.aval.shape) or\n- any(type(d) is core.Var\n+ return (any(type(v.aval) is core.AbstractBInt for v in jaxpr.invars) or\n+ any(type(v.aval) is core.AbstractBInt\nfor j in itertools.chain([jaxpr], core.subjaxprs(jaxpr))\n- for e in j.eqns for v in itertools.chain(e.invars, e.outvars)\n- if type(v.aval) is core.DShapedArray for d in v.aval.shape))\n+ for e in j.eqns for v in e.outvars))\ndef _prune_unused_inputs(\njaxpr: core.Jaxpr) -> Tuple[core.Jaxpr, Set[int], Set[int]]:\n@@ -545,7 +529,7 @@ def _input_handler(backend: Backend,\nin_avals, which_explicit = util.unzip2(in_type)\n# Check whether we actually need an input_handler.\nneeds_implicit = which_explicit and not all(which_explicit)\n- needs_out_handling = any(type(d) is core.InDBIdx for a in out_type or []\n+ needs_out_handling = any(type(d) is core.InDBIdx for a, _ in out_type or []\nif type(a) is core.DShapedArray for d in a.shape)\nif not needs_implicit and not needs_out_handling:\n@@ -565,7 +549,7 @@ def _input_handler(backend: Backend,\n# Precompute which input values are needed for output types.\ninputs_needed_for_out_types = out_type and [\n- d.val for aval in out_type if type(aval) is core.DShapedArray # type: ignore\n+ d.val for aval, _ in out_type if type(aval) is core.DShapedArray # type: ignore\nfor d in aval.shape if type(d) is core.InDBIdx]\ndef elaborate(explicit_args: Sequence[Any]) -> Tuple[Tuple, Optional[Tuple]]:\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -18,8 +18,8 @@ import functools\nfrom functools import partial\nimport itertools\nimport operator\n-from typing import (Any, Callable, Dict, Optional, Sequence, Tuple,\n- List, TypeVar, Union, cast as type_cast)\n+from typing import (Any, Callable, Optional, Sequence, Tuple, List, Dict,\n+ TypeVar, Union, cast as type_cast)\nimport warnings\nimport numpy as np\n@@ -106,13 +106,20 @@ def _try_broadcast_shapes(\nrank, *others = {len(shape) for shape in shapes}\nif others: return None # must have consistent rank\nif not rank: return () # scalar case\n- result_shape = [-1] * rank\n- for i, sizes in enumerate(zip(*shapes)):\n- non_1s = {d for d in sizes if not core.symbolic_equal_dim(d, 1)}\n- if len(non_1s) > 1:\n- return None # must have equal sizes other than 1-sized axes\n- result_shape[i] = next(iter(non_1s), 1)\n-\n+ result_shape = []\n+ for ds in unsafe_zip(*shapes):\n+ if all(core.same_referent(d, ds[0]) for d in ds[1:]):\n+ # if all axes are identical objects, the resulting size is the object\n+ result_shape.append(ds[0])\n+ else:\n+ # if all dims are equal (or 1), the result is the non-1 size (or 1)\n+ non_1s = [d for d in ds if not core.symbolic_equal_dim(d, 1)]\n+ if not non_1s:\n+ result_shape.append(1)\n+ elif all(core.symbolic_equal_dim(non_1s[0], d) for d in non_1s[1:]):\n+ result_shape.append(non_1s[0])\n+ else:\n+ return None\nreturn tuple(result_shape)\ndef broadcast_shapes(*shapes: Tuple[Union[int, core.Tracer], ...]\n@@ -156,60 +163,39 @@ def _broadcast_ranks(s1, s2):\ndef _identity(x): return x\n-def _extract_tracers_dyn_shape(shape: Sequence[Union[int, core.Tracer]]\n- ) -> Tuple[Sequence[core.Tracer],\n- Sequence[Optional[int]]]:\n- \"\"\"Returns the list of tracers in `shape`, and a static version of `shape`\n- with tracers replaced with None\"\"\"\n+def _extract_tracers_dyn_shape(\n+ shape: Sequence[Union[int, core.Tracer]]\n+ ) -> Tuple[List[core.Tracer], List[Optional[int]]]:\n+ # Given a sequence representing a shape, pull out Tracers, replacing with None\nif config.jax_dynamic_shapes:\n# We must gate this behavior under a flag because otherwise the errors\n# raised are different (and have worse source provenance information).\n- dyn_shape = tuple(d for d in shape if isinstance(d, core.Tracer))\n- static_shape = tuple(d if not isinstance(d, core.Tracer) else None for d in shape)\n+ dyn_shape = [d for d in shape if isinstance(d, core.Tracer)]\n+ static_shape = [None if isinstance(d, core.Tracer) else d for d in shape]\nreturn dyn_shape, static_shape\nelse:\n- return (), shape # type: ignore[return-value]\n-\n+ return [], list(shape) # type: ignore\n-def _merge_dyn_shape(static_shape: Sequence[Optional[int]],\n- dyn_shape: Sequence[mlir.Value],\n- ) -> Sequence[mlir.Value]:\n- \"\"\"Returns static_shape with None values filled in from dyn_shape.\"\"\"\n+def _merge_dyn_shape(\n+ static_shape: Sequence[Optional[int]],\n+ dyn_shape: Sequence[Any],\n+ ) -> Tuple[Union[int, mlir.Value], ...]:\n+ # Replace Nones in static_shape with elements of dyn_shape, in order\ndyn_shape_it = iter(dyn_shape)\nshape = tuple(next(dyn_shape_it) if d is None else d for d in static_shape)\nassert next(dyn_shape_it, None) is None\nreturn shape\n-def _stage_with_dyn_shape(trace: core.Trace,\n- prim: core.Primitive,\n- args: Sequence[core.Tracer],\n- dyn_shape_args: Sequence[core.Tracer],\n- params: Dict[str, Any],\n- static_shape: Sequence[Optional[int]],\n- out_dtype: Any,\n- out_weak_type: bool,\n- ) -> core.Tracer:\n- \"\"\"Stages out a primitive that takes dynamic shapes.\n-\n- dyn_shape_args are the tracers corresponding to the None values in static_shape.\n- \"\"\"\n- if not dyn_shape_args:\n- return trace.default_process_primitive(prim, args, params) # type: ignore\n- assert len(dyn_shape_args) == sum(d is None for d in static_shape)\n+def _dyn_shape_staging_rule(trace, prim, out_aval, *args, **params):\nsource_info = source_info_util.current()\n-\n- ds = iter(dyn_shape_args)\n- out_shape_for_tracer: List[Union[int, core.Tracer]] = [\n- next(ds) if d is None else d for d in static_shape]\n- aval = core.DShapedArray(tuple(out_shape_for_tracer), out_dtype, out_weak_type)\n- out_tracer = pe.DynamicJaxprTracer(trace, aval, source_info)\n- invars = [*(trace.getvar(x) for x in args), *(trace.getvar(d) for d in dyn_shape_args)] # type: ignore\n- eqn = pe.new_jaxpr_eqn(invars, [trace.makevar(out_tracer)], # type: ignore\n+ out_tracer = pe.DynamicJaxprTracer(trace, out_aval, source_info)\n+ eqn = pe.new_jaxpr_eqn([trace.getvar(x) for x in args],\n+ [trace.makevar(out_tracer)],\nprim, params, core.no_effects, source_info)\n- trace.frame.eqns.append(eqn) # type: ignore\n-\n+ trace.frame.add_eqn(eqn)\nreturn out_tracer\n+\n### traceables\ndef neg(x: Array) -> Array:\n@@ -794,7 +780,12 @@ def broadcast_in_dim(operand: Array, shape: Shape,\nif (np.ndim(operand) == len(shape) and not len(broadcast_dimensions)\nand isinstance(operand, (device_array.DeviceArray, core.Tracer))):\nreturn operand\n+ if config.jax_dynamic_shapes:\n+ # We must gate this behavior under a flag because otherwise the errors\n+ # raised are different (and have worse source provenance information).\ndyn_shape, static_shape = _extract_tracers_dyn_shape(shape)\n+ else:\n+ dyn_shape, static_shape = [], shape # type: ignore\nreturn broadcast_in_dim_p.bind(\noperand, *dyn_shape, shape=tuple(static_shape),\nbroadcast_dimensions=tuple(broadcast_dimensions))\n@@ -858,7 +849,7 @@ def reshape(operand: Array, new_sizes: Shape,\ndyn_shape, static_new_sizes = _extract_tracers_dyn_shape(new_sizes)\nreturn reshape_p.bind(\n- operand, *dyn_shape, new_sizes=static_new_sizes,\n+ operand, *dyn_shape, new_sizes=tuple(static_new_sizes),\ndimensions=None if dims is None or same_dims else dims)\ndef pad(operand: Array, padding_value: Array,\n@@ -1165,18 +1156,18 @@ def iota(dtype: DType, size: int) -> Array:\n<https://www.tensorflow.org/xla/operation_semantics#iota>`_\noperator.\n\"\"\"\n- dtype = dtypes.canonicalize_dtype(dtype)\n- size, = canonicalize_shape((size,))\n- dyn_shape, static_shape = _extract_tracers_dyn_shape((size,))\n- return iota_p.bind(*dyn_shape, dtype=dtype, shape=static_shape, dimension=0)\n+ return broadcasted_iota(dtype, (size,), 0)\ndef broadcasted_iota(dtype: DType, shape: Shape, dimension: int) -> Array:\n\"\"\"Convenience wrapper around ``iota``.\"\"\"\ndtype = dtypes.canonicalize_dtype(dtype)\nshape = canonicalize_shape(shape)\n+ dynamic_shape = [d for d in shape if isinstance(d, core.Tracer)]\n+ static_shape = [None if isinstance(d, core.Tracer) else d for d in shape]\ndimension = core.concrete_or_error(\nint, dimension, \"dimension argument of lax.broadcasted_iota\")\n- return iota_p.bind(dtype=dtype, shape=shape, dimension=dimension)\n+ return iota_p.bind(*dynamic_shape, dtype=dtype, shape=tuple(static_shape),\n+ dimension=dimension)\ndef _eye(dtype: DType, shape: Shape, offset: int) -> Array:\n\"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\"\"\"\n@@ -1484,6 +1475,7 @@ def _broadcasting_shape_rule(name, *avals):\nif len({len(shape) for shape in shapes}) != 1:\nmsg = '{}: arrays must have same number of dimensions, got {}.'\nraise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))\n+ # TODO(mattjj): de-duplicate with _try_broadcast_shapes\nresult_shape = []\nfor ds in zip(*shapes):\nif all(core.same_referent(d, ds[0]) for d in ds[1:]):\n@@ -1492,14 +1484,13 @@ def _broadcasting_shape_rule(name, *avals):\nelse:\n# if all dims are equal (or 1), the result is the non-1 size\nnon_1s = [d for d in ds if not core.symbolic_equal_dim(d, 1)]\n- if non_1s:\n- first_non_1 = non_1s.pop()\n- if tuple(filter(lambda d: not core.symbolic_equal_dim(d, first_non_1), non_1s)):\n+ if not non_1s:\n+ result_shape.append(1)\n+ elif all(core.symbolic_equal_dim(non_1s[0], d) for d in non_1s[1:]):\n+ result_shape.append(non_1s[0])\n+ else:\nraise TypeError(f'{name} got incompatible shapes for broadcasting: '\nf'{\", \".join(map(str, map(tuple, shapes)))}.')\n- result_shape.append(first_non_1)\n- else:\n- result_shape.append(1)\nreturn tuple(result_shape)\n@@ -1582,6 +1573,11 @@ def broadcast_mhlo(\nassert len(aval.shape) <= len(aval_out.shape), (aval, aval_out)\ndims = mlir.dense_int_elements(\nrange(len(aval_out.shape) - len(aval.shape), len(aval_out.shape)))\n+ if any(isinstance(d, ir.Value) for d in aval_out.shape):\n+ arg = mhlo.DynamicBroadcastInDimOp(\n+ mlir.aval_to_ir_type(aval_out), arg,\n+ mlir.shape_tensor(aval_out.shape), dims).result\n+ else:\narg = mhlo.BroadcastInDimOp(\nmlir.aval_to_ir_type(aval.update(shape=aval_out.shape)), arg,\ndims).result\n@@ -1598,13 +1594,23 @@ def _nary_lower_mhlo(op: Callable, ctx,\nprovided?\n\"\"\"\ndel params\n- aval_out, = ctx.avals_out\n- broadcasted_args = broadcast_mhlo(aval_out, ctx.avals_in, args)\n+ avals_in, (aval_out,) = ctx.avals_in, ctx.avals_out\n+ if config.jax_dynamic_shapes:\n+ substitute = partial(_substitute_axis_sizes_in_aval, ctx.axis_size_env)\n+ avals_in = map(substitute, avals_in)\n+ aval_out = substitute(aval_out)\n+ broadcasted_args = broadcast_mhlo(aval_out, avals_in, args)\nif explicit_type:\nreturn op(mlir.aval_to_ir_type(aval_out), *broadcasted_args).results\nelse:\nreturn op(*broadcasted_args).results\n+def _substitute_axis_sizes_in_aval(\n+ env: Dict[core.Var, ir.Value], a: core.AbstractValue) -> core.AbstractValue:\n+ if isinstance(a, core.DShapedArray):\n+ return a.update(shape=tuple(env.get(d, d) for d in a.shape)) # type: ignore\n+ return a\n+\n_float = {np.floating}\n_complex = {np.complexfloating}\n@@ -2727,11 +2733,13 @@ def _broadcast_in_dim_fwd_rule(eqn):\nreturn [None], eqn\ndef _broadcast_in_dim_staging_rule(\n- trace, x, *dyn_shape, shape, broadcast_dimensions):\n+ trace, x, *dyn, shape, broadcast_dimensions):\nparams = dict(shape=shape, broadcast_dimensions=broadcast_dimensions)\n- return _stage_with_dyn_shape(trace, broadcast_in_dim_p,\n- (x,), dyn_shape, params,\n- shape, x.dtype, x.weak_type)\n+ if not dyn:\n+ return trace.default_process_primitive(broadcast_in_dim_p, (x,), params)\n+ aval = core.DShapedArray(_merge_dyn_shape(shape, dyn), x.dtype, x.weak_type)\n+ return _dyn_shape_staging_rule(trace, broadcast_in_dim_p, aval, x, *dyn,\n+ **params)\ndef _broadcast_in_dim_padding_rule(in_avals, out_avals, x, *dyn_shape,\nshape, broadcast_dimensions):\n@@ -2791,7 +2799,6 @@ def _broadcast_in_dim_lower(ctx, x, *dyn_shape, shape, broadcast_dimensions):\nmlir.aval_to_ir_type(aval_out), x,\nmlir.shape_tensor(shape),\nmlir.dense_int_elements(broadcast_dimensions),\n- None, None,\n).results\nelse:\nreturn mhlo.BroadcastInDimOp(\n@@ -2824,6 +2831,7 @@ pe.custom_staging_rules[broadcast_in_dim_p] = _broadcast_in_dim_staging_rule\npe.padding_rules[broadcast_in_dim_p] = _broadcast_in_dim_padding_rule\ncore.custom_typechecks[broadcast_in_dim_p] = _broadcast_in_dim_typecheck_rule\nmlir.register_lowering(broadcast_in_dim_p, _broadcast_in_dim_lower)\n+# TODO(mattjj): un-comment the next line\n# core.pp_eqn_rules[broadcast_in_dim_p] = _broadcast_in_dim_pp_rule\n@@ -3154,7 +3162,8 @@ def _reshape_shape_rule(operand, *, new_sizes, dimensions):\nmsg = 'reshape new_sizes must all be positive, got {}.'\nraise TypeError(msg.format(new_sizes))\n# TODO(necula): re-enable this check\n- if not config.jax_dynamic_shapes and not core.same_shape_sizes(np.shape(operand), new_sizes):\n+ if (not config.jax_dynamic_shapes and\n+ not core.same_shape_sizes(np.shape(operand), new_sizes)):\nmsg = 'reshape total size must be unchanged, got new_sizes {} for shape {}.'\nraise TypeError(msg.format(new_sizes, np.shape(operand)))\nif dimensions is not None:\n@@ -3201,12 +3210,6 @@ def _reshape_masking_rule(padded_args, logical_shapes, polymorphic_shapes,\nnew_sizes=masking.padded_shape_as_value(new_sizes),\ndimensions=dimensions)\n-reshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,\n- 'reshape')\n-ad.deflinear2(reshape_p, _reshape_transpose_rule)\n-batching.primitive_batchers[reshape_p] = _reshape_batch_rule\n-masking.masking_rules[reshape_p] = _reshape_masking_rule\n-\ndef _reshape_lower(ctx, x, *dyn_shape, new_sizes, dimensions):\naval_out, = ctx.avals_out\nif dimensions is not None:\n@@ -3220,17 +3223,23 @@ def _reshape_lower(ctx, x, *dyn_shape, new_sizes, dimensions):\nelse:\nreturn mhlo.ReshapeOp(mlir.aval_to_ir_type(aval_out), x).results\n-mlir.register_lowering(reshape_p, _reshape_lower)\n-\ndef _reshape_staging_rule(\n- trace, x, *dyn_shape, new_sizes, dimensions):\n+ trace, x, *dyn, new_sizes, dimensions):\nparams = dict(new_sizes=new_sizes, dimensions=dimensions)\n- # TODO(necula): shouldn't this include the same checks as in reshape_shape_rule?\n- return _stage_with_dyn_shape(trace, reshape_p, (x,), dyn_shape, params,\n- new_sizes, x.dtype, x.weak_type)\n+ if not dyn:\n+ return trace.default_process_primitive(reshape_p, (x,), params)\n+ av = core.DShapedArray(_merge_dyn_shape(new_sizes, dyn), x.dtype, x.weak_type)\n+ return _dyn_shape_staging_rule(trace, reshape_p, av, x, *dyn, **params)\n+reshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,\n+ 'reshape')\n+ad.deflinear2(reshape_p, _reshape_transpose_rule)\n+batching.primitive_batchers[reshape_p] = _reshape_batch_rule\n+masking.masking_rules[reshape_p] = _reshape_masking_rule\n+mlir.register_lowering(reshape_p, _reshape_lower)\npe.custom_staging_rules[reshape_p] = _reshape_staging_rule\n+\ndef _rev_shape_rule(operand, *, dimensions):\n_check_shapelike('rev', 'dimensions', dimensions)\nif len(set(dimensions)) != len(dimensions):\n@@ -4381,11 +4390,12 @@ iota_p = Primitive('iota')\niota_p.def_impl(partial(xla.apply_primitive, iota_p))\niota_p.def_abstract_eval(_iota_abstract_eval)\n-def _iota_staging_rule(\n- trace, *dyn_shape, dtype, shape, dimension):\n+def _iota_staging_rule(trace, *dyn_shape, dtype, shape, dimension):\nparams = dict(dtype=dtype, shape=shape, dimension=dimension)\n- return _stage_with_dyn_shape(trace, iota_p, (), dyn_shape, params,\n- shape, dtype, False)\n+ if not dyn_shape:\n+ return trace.default_process_primitive(iota_p, (), params)\n+ aval = core.DShapedArray(_merge_dyn_shape(shape, dyn_shape), dtype, False)\n+ return _dyn_shape_staging_rule(trace, iota_p, aval, *dyn_shape, **params)\npe.custom_staging_rules[iota_p] = _iota_staging_rule\ndef _iota_typecheck_rule(*dyn_shape, dtype, shape, dimension):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -71,9 +71,10 @@ from jax._src.numpy.ufuncs import ( # noqa: F401\nreciprocal, remainder, right_shift, rint, sign, signbit, sin, sinc, sinh, sqrt,\nsquare, subtract, tan, tanh, true_divide)\nfrom jax._src.numpy.util import ( # noqa: F401\n- _arraylike, _broadcast_arrays, _broadcast_to, _check_arraylike, _complex_elem_type, _promote_args,\n- _promote_args_inexact, _promote_dtypes, _promote_dtypes_inexact, _promote_shapes, _register_stackable,\n- _stackable, _where, _wraps)\n+ _arraylike, _broadcast_arrays, _broadcast_to, _check_arraylike,\n+ _complex_elem_type, _promote_args, _promote_args_inexact, _promote_dtypes,\n+ _promote_dtypes_inexact, _promote_shapes, _register_stackable, _stackable,\n+ _where, _wraps)\nfrom jax._src.numpy.vectorize import vectorize\nfrom jax._src.ops import scatter\nfrom jax._src.util import (unzip2, prod as _prod, subvals, safe_zip, ceil_of_ratio,\n@@ -2099,6 +2100,10 @@ def arange(start: core.DimSize, stop: Optional[core.DimSize]=None,\ndtype = result_type(start, *(x for x in [stop, step] if x is not None))\ndtype = _jnp_dtype(dtype)\nif stop is None and step is None:\n+ if (jax.config.jax_dynamic_shapes and\n+ not isinstance(core.get_aval(start), core.ConcreteArray)):\n+ start = ceil(start).astype(int) # note using jnp here\n+ else:\nstart = require(start, msg(\"stop\"))\nstart = np.ceil(start).astype(int)\nreturn lax.iota(dtype, start)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/util.py", "new_path": "jax/_src/numpy/util.py", "diff": "@@ -24,13 +24,16 @@ from jax._src.config import config\nfrom jax._src import dtypes\nfrom jax._src.lax import lax as lax_internal\nfrom jax._src.numpy.ndarray import ndarray\n-from jax._src.util import safe_zip\n+from jax._src.util import safe_zip, safe_map\nfrom jax._src import api\nfrom jax import core\nfrom jax._src.lax import lax\nimport numpy as np\n+zip, unsafe_zip = safe_zip, zip\n+map, unsafe_map = safe_map, map\n+\n_T = TypeVar(\"_T\")\n_parameter_break = re.compile(\"\\n(?=[A-Za-z_])\")\n@@ -219,20 +222,21 @@ def _promote_shapes(fun_name, *args):\nreturn args\nelse:\nshapes = [np.shape(arg) for arg in args]\n+ if config.jax_dynamic_shapes:\n+ # With dynamic shapes we don't support singleton-dimension broadcasting;\n+ # we instead broadcast out to the full shape as a temporary workaround.\n+ # TODO(mattjj): revise this workaround\n+ res_shape = lax.broadcast_shapes(*shapes) # Can raise an error!\n+ return [_broadcast_to(arg, res_shape) for arg, shp in zip(args, shapes)]\n+ else:\nif all(len(shapes[0]) == len(s) for s in shapes[1:]):\nreturn args # no need for rank promotion, so rely on lax promotion\nnonscalar_ranks = {len(shp) for shp in shapes if shp}\nif len(nonscalar_ranks) < 2:\n- return args\n+ return args # rely on lax scalar promotion\nelse:\nif config.jax_numpy_rank_promotion != \"allow\":\n_rank_promotion_warning_or_error(fun_name, shapes)\n- if config.jax_dynamic_shapes:\n- # With dynamic shapes we don't support singleton-dimension broadcasting;\n- # we instead broadcast out to the full shape as a temporary workaround.\n- res_shape = lax.broadcast_shapes(*shapes)\n- return [_broadcast_to(arg, res_shape) for arg, shp in zip(args, shapes)]\n- else:\nresult_rank = len(lax.broadcast_shapes(*shapes))\nreturn [_broadcast_to(arg, (1,) * (result_rank - len(shp)) + shp)\nfor arg, shp in zip(args, shapes)]\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -315,34 +315,33 @@ class JVPTrace(Trace):\ndef process_call(self, call_primitive, f, tracers, params):\nassert call_primitive.multiple_results\nprimals, tangents = unzip2((t.primal, t.tangent) for t in tracers)\n- nonzero_tangents, tangent_tree_def = tree_flatten(tangents)\n- nz_tangents = [type(t) is not Zero for t in tangents]\n+ which_nz = [ type(t) is not Zero for t in tangents]\n+ tangents = [t if type(t) is not Zero else None for t in tangents]\n+ args, in_tree = tree_flatten((primals, tangents))\nif 'name' in params and not config.jax_experimental_name_stack:\nparams = dict(params, name=wrap_name(params['name'], 'jvp'))\nf_jvp = jvp_subtrace(f, self.main)\n- f_jvp, nz_tangents_out = nonzero_tangent_outputs(f_jvp)\n+ f_jvp, which_nz_out = nonzero_tangent_outputs(f_jvp)\nif isinstance(call_primitive, core.MapPrimitive):\nin_axes = params['in_axes']\n- tangent_in_axes = [ax for ax, nz in zip(in_axes, nz_tangents) if nz]\n+ tangent_in_axes = [ax for ax, nz in zip(in_axes, which_nz) if nz]\nout_axes_thunk = params['out_axes_thunk']\n- # The new thunk depends deterministically on the old thunk and the wrapped function.\n- # Any caching already has to include the wrapped function as part of the key, so we\n- # only use the previous thunk for equality checks.\n- # NOTE: This assumes that the output tangents being zero is a deterministic\n- # function of which input tangents were zero.\n- @as_hashable_function(closure=(tuple(nz_tangents), out_axes_thunk))\n+ # NOTE: This assumes that the output tangents being zero is a\n+ # deterministic function of which input tangents were zero.\n+ @as_hashable_function(closure=out_axes_thunk)\ndef new_out_axes_thunk():\n- out_axes = out_axes_thunk()\n- return (*out_axes, *(ax for ax, nz in zip(out_axes, nz_tangents_out()) if nz))\n- params = dict(params,\n- in_axes=(*in_axes, *tangent_in_axes),\n+ out_ax = out_axes_thunk()\n+ return (*out_ax, *(ax for ax, nz in zip(out_ax, which_nz_out()) if nz))\n+ params = dict(params, in_axes=(*in_axes, *tangent_in_axes),\nout_axes_thunk=new_out_axes_thunk)\n- f_jvp, out_tree_def = traceable(f_jvp, len(primals), tangent_tree_def)\n+ f_jvp, out_tree = traceable(f_jvp, in_tree)\nupdate_params = call_param_updaters.get(call_primitive)\n- new_params = update_params(params, nz_tangents) if update_params else params\n- f_jvp = _update_annotation(f_jvp, f.in_type, nz_tangents)\n- result = call_primitive.bind(f_jvp, *primals, *nonzero_tangents, **new_params)\n- primal_out, tangent_out = tree_unflatten(out_tree_def(), result)\n+ new_params = update_params(params, which_nz) if update_params else params\n+ result = call_primitive.bind(_update_annotation(f_jvp, f.in_type, which_nz),\n+ *args, **new_params)\n+ primal_out, tangent_out = tree_unflatten(out_tree(), result)\n+ tangent_out = [Zero(get_aval(p).at_least_vspace()) if t is None else t\n+ for p, t in zip(primal_out, tangent_out)]\nreturn [JVPTracer(self, p, t) for p, t in zip(primal_out, tangent_out)]\ndef post_process_call(self, call_primitive, out_tracers, params):\n@@ -588,13 +587,14 @@ def instantiate_zeros_aval(aval, tangent):\nreturn tangent\n@lu.transformation_with_aux\n-def traceable(num_primals, in_tree_def, *primals_and_tangents):\n- new_primals = primals_and_tangents[:num_primals]\n- new_tangents = primals_and_tangents[num_primals:]\n- new_tangents = tree_unflatten(in_tree_def, new_tangents)\n- primal_out, tangent_out = yield (new_primals, new_tangents), {}\n- out_flat, tree_def = tree_flatten((primal_out, tangent_out))\n- yield out_flat, tree_def\n+def traceable(in_tree, *primals_and_tangents):\n+ primals, tangents = tree_unflatten(in_tree, primals_and_tangents)\n+ tangents = [Zero(get_aval(p).at_least_vspace()) if t is None else t\n+ for p, t in zip(primals, tangents)]\n+ primals_out, tangents_out = yield (primals, tangents), {}\n+ tangents_out = [None if type(t) is Zero else t for t in tangents_out]\n+ out_flat, out_tree = tree_flatten((primals_out, tangents_out))\n+ yield out_flat, out_tree\ndef call_transpose(primitive, params, call_jaxpr, args, ct, _, reduce_axes):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -418,6 +418,7 @@ class LoweringRuleContext:\navals_out: Any # Usually Sequence[core.AbstractValue], but sometimes None.\ntokens_in: TokenSet\ntokens_out: Optional[TokenSet] # Mutable store for output containers\n+ axis_size_env: Optional[Dict[core.Var, ir.Value]] = None # Dynamic axis sizes\ndef set_tokens_out(self, tokens_out: TokenSet):\nassert self.tokens_out is None, 'Should only set `tokens_out` once.'\n@@ -931,10 +932,16 @@ def jaxpr_subcomp(ctx: ModuleContext, jaxpr: core.Jaxpr,\nconfig.jax_experimental_name_stack else ctx)\neffects = [eff for eff in eqn.effects if eff in core.ordered_effects]\ntokens_in = tokens.subset(effects)\n+ avals_in = map(aval, eqn.invars)\nrule_ctx = LoweringRuleContext(\n- module_context=eqn_ctx, primitive=eqn.primitive,\n- avals_in=map(aval, eqn.invars), avals_out=map(aval, eqn.outvars),\n- tokens_in=tokens_in, tokens_out=None)\n+ module_context=eqn_ctx, primitive=eqn.primitive, avals_in=avals_in,\n+ avals_out=map(aval, eqn.outvars), tokens_in=tokens_in,\n+ tokens_out=None)\n+ if config.jax_dynamic_shapes:\n+ axis_size_env = {d: read(d)[0] for a in avals_in\n+ if type(a) is core.DShapedArray for d in a.shape\n+ if type(d) is core.Var}\n+ rule_ctx = rule_ctx.replace(axis_size_env=axis_size_env)\nans = rule(rule_ctx, *map(_unwrap_singleton_ir_values, in_nodes),\n**eqn.params)\nif effects:\n@@ -976,15 +983,32 @@ def lower_fun(fun: Callable, multiple_results: bool = True) -> Callable:\nThe returned function does not use `avals_out`, so callers may pass any value\nas `avals_out`.\"\"\"\ndef f_lowered(ctx, *args, **params):\n- if multiple_results:\n- f = fun\n- else:\n- f = lambda *args, **kw: (fun(*args, **kw),)\n+ f = fun if multiple_results else lambda *args, **kw: (fun(*args, **kw),)\nwrapped_fun = lu.wrap_init(f, params)\naxis_env = ctx.module_context.axis_env\n+\n+ if config.jax_dynamic_shapes:\n+ # We might be applying this function to arguments with dynamic shapes,\n+ # i.e. there might be Vars in the shape tuples of ctx.avals_in. In that\n+ # case, we need to form a jaxpr with leading binders for those axis size\n+ # arguments (by computing an InputType and using trace_to_jaxpr_dynamic2),\n+ # and we need to call jaxpr_subcomp with these arguments made explicit.\n+ args = (*ctx.axis_size_env.values(), *args)\n+ idx = {d: core.DBIdx(i) for i, d in enumerate(ctx.axis_size_env)}\n+ i32_aval = core.ShapedArray((), np.dtype('int32'))\n+ implicit_args = [(i32_aval, False)] * len(ctx.axis_size_env)\n+ explicit_args = [(a.update(shape=tuple(idx.get(d, d) for d in a.shape))\n+ if type(a) is core.DShapedArray else a, True)\n+ for a in ctx.avals_in]\n+ wrapped_fun = lu.annotate(wrapped_fun, (*implicit_args, *explicit_args))\n+ with core.extend_axis_env_nd(zip(axis_env.names, axis_env.sizes)):\n+ jaxpr, _, consts = pe.trace_to_jaxpr_dynamic2(wrapped_fun)\n+ else:\nwith core.extend_axis_env_nd(zip(axis_env.names, axis_env.sizes)):\njaxpr, _, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, ctx.avals_in)\n- out, tokens = jaxpr_subcomp(ctx.module_context, jaxpr, ctx.tokens_in, _ir_consts(consts),\n+\n+ out, tokens = jaxpr_subcomp(\n+ ctx.module_context, jaxpr, ctx.tokens_in, _ir_consts(consts),\n*map(wrap_singleton_ir_values, args))\nctx.set_tokens_out(tokens)\nreturn out\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -8522,7 +8522,8 @@ class DynamicShapeTest(jtu.JaxTestCase):\nx = np.ones(3)\ny = np.ones(3)\n- with self.assertRaisesRegex(TypeError, 'add got incompatible shapes for broadcasting'):\n+ with self.assertRaisesRegex(\n+ Exception, '[Ii]ncompatible shapes for broadcasting'):\n_ = jax.make_jaxpr(f, abstracted_axes=({0: 'n'}, {}))(x, y)\ndef test_shape_errors_distinct_vars(self):\n@@ -8531,7 +8532,8 @@ class DynamicShapeTest(jtu.JaxTestCase):\nx = np.ones(3)\ny = np.ones(3)\n- with self.assertRaisesRegex(TypeError, 'add got incompatible shapes for broadcasting'):\n+ with self.assertRaisesRegex(\n+ Exception, '[Ii]ncompatible shapes for broadcasting'):\n_ = jax.make_jaxpr(f, abstracted_axes=({0: 'n'}, {0: 'm'}))(x, y)\ndef test_basic_dot(self):\n@@ -9096,6 +9098,7 @@ class DynamicShapeTest(jtu.JaxTestCase):\nf(np.ones((5,), dtype=np.float32))\n# TODO: add assertions\n+ @unittest.skip('failing w/ iree error')\n@unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\ndef test_broadcast(self):\n@partial(jax.jit, abstracted_axes=({0: 'w'},))\n@@ -9112,6 +9115,7 @@ class DynamicShapeTest(jtu.JaxTestCase):\nf(np.ones((5,), dtype=np.float32))\n# TODO: add assertions\n+ @unittest.skip('failing w/ iree error')\n@unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\ndef test_stack(self):\n@partial(jax.jit, abstracted_axes=({0: 'w'},))\n@@ -9121,6 +9125,23 @@ class DynamicShapeTest(jtu.JaxTestCase):\nf(np.ones((5,), dtype=np.float32))\n# TODO: add assertions\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_jit_dependent_pair_output_iree(self):\n+ # Like the above 'polymorhpic output' test, but now with a `2 * n`!\n+ count = 0\n+\n+ @jax.jit\n+ def f(n):\n+ nonlocal count\n+ count += 1\n+ return jnp.arange(2 * n)\n+\n+ x = f(3)\n+ y = f(4)\n+ self.assertAllClose(x, jnp.arange(2 * 3), check_dtypes=False)\n+ self.assertAllClose(y, jnp.arange(2 * 4), check_dtypes=False)\n+ self.assertEqual(count, 1)\n+\ndef test_slicing_basic(self):\nf = jax.jit(lambda x, n: jnp.sum(x[:n]))\n# TODO(mattjj): revise getslice, add typecheck rule for it, enable checks\n@@ -9446,6 +9467,48 @@ class DynamicShapeTest(jtu.JaxTestCase):\njaxpr = jax.make_jaxpr(jax.grad(loss))(params, batch)\ncore.check_jaxpr(jaxpr.jaxpr)\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\n+ def test_mlp_autodiff_dynamic_batch_iree(self):\n+ count = 0\n+\n+ def predict(params, inputs):\n+ for W, b in params:\n+ outputs = jnp.dot(inputs, W) + b\n+ inputs = jnp.maximum(0, outputs)\n+ return outputs\n+\n+ def loss_ref(params, batch):\n+ nonlocal count\n+ count += 1 # count retraces\n+ inputs, targets = batch\n+ predictions = predict(params, inputs)\n+ return jnp.sum((predictions - targets) ** 2)\n+\n+ loss = jax.jit(loss_ref, abstracted_axes=({}, {0: 'n'}))\n+\n+ params = [(jnp.ones((784, 256)), jnp.ones(256)),\n+ (jnp.ones((256, 10)), jnp.ones( 10))]\n+\n+ # two different size batches\n+ batch1 = (inputs, targets) = (jnp.ones((128, 784)), jnp.ones((128, 10)))\n+ batch2 = (inputs, targets) = (jnp.ones((32, 784)), jnp.ones((32, 10)))\n+\n+ _ = loss(params, batch1)\n+ _ = loss(params, batch2)\n+ self.assertEqual(count, 1)\n+\n+ _ = grad(loss)(params, batch1)\n+ _ = grad(loss)(params, batch2)\n+ self.assertEqual(count, 2)\n+\n+ ans = loss( params, batch1)\n+ expected = loss_ref(params, batch1)\n+ self.assertAllClose(ans, expected)\n+\n+ ans = grad(loss )(params, batch1)\n+ expected = grad(loss_ref)(params, batch1)\n+ self.assertAllClose(ans, expected)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[dynamic shapes] revive iree
260,510
06.07.2022 20:52:08
25,200
6274b9ed39425b25af580ce2cf4f20e9575a0043
Enable Python callbacks on TFRT TPU backend
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -891,7 +891,7 @@ def xla_computation(fun: Callable,\nif eff not in core.ordered_effects]\nordered_effects = [eff for eff in jaxpr.effects\nif eff in core.ordered_effects]\n- m, _ = mlir.lower_jaxpr_to_module(\n+ lowering_result = mlir.lower_jaxpr_to_module(\nf\"xla_computation_{fun_name}\",\ncore.ClosedJaxpr(jaxpr, consts),\nunordered_effects=unordered_effects,\n@@ -906,7 +906,8 @@ def xla_computation(fun: Callable,\nmap(xla.sharding_to_proto, out_parts_flat)))\nshould_tuple = tuple_args if tuple_args is not None else (len(avals) > 100)\nbuilt = xc._xla.mlir.mlir_module_to_xla_computation(\n- mlir.module_to_string(m), use_tuple_args=should_tuple,\n+ mlir.module_to_string(lowering_result.module),\n+ use_tuple_args=should_tuple,\nreturn_tuple=True)\nout_shapes_flat = [\nShapeDtypeStruct(a.shape, a.dtype, a.named_shape) for a in out_avals]\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugging.py", "new_path": "jax/_src/debugging.py", "diff": "@@ -91,30 +91,20 @@ def debug_callback_transpose_rule(*flat_args, callback: Callable[..., Any],\nraise ValueError(\"Transpose doesn't support debugging callbacks.\")\nad.primitive_transposes[debug_callback_p] = debug_callback_transpose_rule\n-def _ordered_effect_lowering(ctx, token, *args, **params):\n- avals_in = [core.abstract_token, *ctx.avals_in]\n- avals_out = [core.abstract_token, *ctx.avals_out]\n- args = (token, *args)\n- def _callback(token, *flat_args):\n- out = debug_callback_p.impl(*flat_args, **params)\n- return (token, *out)\n- (token, *result), keepalive = mlir.emit_python_callback(\n- ctx.module_context.platform, _callback, list(args), avals_in, avals_out,\n- True)\n- return result, keepalive, token\n-\ndef debug_callback_lowering(ctx, *args, effect, callback, **params):\n+\n+ def _callback(*flat_args):\n+ return tuple(\n+ debug_callback_p.impl(\n+ *flat_args, effect=effect, callback=callback, **params))\nif effect in core.ordered_effects:\ntoken = ctx.tokens_in.get(effect)[0]\n- result, keepalive, token = _ordered_effect_lowering(ctx, token,\n- *args, effect=effect, callback=callback, **params)\n+ result, token, keepalive = mlir.emit_python_callback(\n+ ctx, _callback, token, list(args), ctx.avals_in, ctx.avals_out, True)\nctx.set_tokens_out(mlir.TokenSet({effect: (token,)}))\nelse:\n- def _callback(*flat_args):\n- return tuple(debug_callback_p.impl(\n- *flat_args, effect=effect, callback=callback, **params))\n- result, keepalive = mlir.emit_python_callback(ctx.module_context.platform,\n- _callback, list(args), ctx.avals_in, ctx.avals_out, True)\n+ result, token, keepalive = mlir.emit_python_callback(\n+ ctx, _callback, None, list(args), ctx.avals_in, ctx.avals_out, True)\nctx.module_context.add_keepalive(keepalive)\nreturn result\nmlir.register_lowering(debug_callback_p, debug_callback_lowering,\n@@ -122,6 +112,9 @@ mlir.register_lowering(debug_callback_p, debug_callback_lowering,\nif jaxlib.version >= (0, 3, 11):\nmlir.register_lowering(\ndebug_callback_p, debug_callback_lowering, platform=\"gpu\")\n+if jaxlib.version >= (0, 3, 15):\n+ mlir.register_lowering(\n+ debug_callback_p, debug_callback_lowering, platform=\"tpu\")\ndef debug_callback(callback: Callable[..., Any], effect: DebugEffect, *args,\n**kwargs):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -333,7 +333,7 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nname, None, True, None, None, None, jaxpr=jaxpr, consts=consts,\ndevice=device, in_avals=abstract_args, out_avals=out_avals,\nhas_unordered_effects=False, ordered_effects=[],\n- kept_var_idx=kept_var_idx, keepalive=None)\n+ kept_var_idx=kept_var_idx, keepalive=None, host_callbacks=[])\nif not _on_exit:\nlog_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG\n@@ -372,17 +372,20 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nif eff not in core.ordered_effects]\nordered_effects = [eff for eff in closed_jaxpr.effects\nif eff in core.ordered_effects]\n- module, keepalive = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, unordered_effects, ordered_effects,\n- backend.platform, mlir.ReplicaAxisContext(axis_env), name_stack,\n- donated_invars)\n+ lowering_result = mlir.lower_jaxpr_to_module(\n+ module_name, closed_jaxpr,\n+ unordered_effects, ordered_effects, backend.platform,\n+ mlir.ReplicaAxisContext(axis_env), name_stack, donated_invars)\n+ module, keepalive, host_callbacks = (\n+ lowering_result.module, lowering_result.keepalive,\n+ lowering_result.host_callbacks)\nreturn XlaComputation(\nname, module, False, donated_invars, fun.in_type, out_type, nreps=nreps,\ndevice=device, backend=backend, tuple_args=tuple_args,\nin_avals=abstract_args, out_avals=out_avals,\nhas_unordered_effects=bool(unordered_effects),\nordered_effects=ordered_effects, kept_var_idx=kept_var_idx,\n- keepalive=keepalive)\n+ keepalive=keepalive, host_callbacks=host_callbacks)\ndef _backend_supports_unbounded_dynamic_shapes(backend: Backend) -> bool:\n@@ -751,7 +754,8 @@ def _execute_replicated(name: str, compiled: XlaExecutable,\ndef _execute_trivial(jaxpr, device: Optional[Device], consts, avals, handlers,\nhas_unordered_effects: bool,\n- ordered_effects: List[core.Effect], kept_var_idx, *args):\n+ ordered_effects: List[core.Effect], kept_var_idx,\n+ host_callbacks, *args):\nenv: Dict[core.Var, Any] = {}\npruned_args = (x for i, x in enumerate(args) if i in kept_var_idx)\nmap(env.setdefault, jaxpr.invars, pruned_args)\n@@ -818,9 +822,15 @@ class XlaComputation(stages.XlaLowering):\nreturn self._executable\n@profiler.annotate_function\n-def backend_compile(backend, built_c, options):\n+def backend_compile(backend, built_c, options, host_callbacks):\n# we use a separate function call to ensure that XLA compilation appears\n# separately in Python profiling results\n+ if host_callbacks:\n+ return backend.compile(built_c, compile_options=options,\n+ host_callbacks=host_callbacks)\n+ # Some backends don't have `host_callbacks` option yet\n+ # TODO(sharadmv): remove this fallback when all backends allow `compile`\n+ # to take in `host_callbacks`\nreturn backend.compile(built_c, compile_options=options)\n# TODO(phawkins): update users.\n@@ -838,7 +848,8 @@ def _dump_ir_to_file(name: str, ir: str):\nname.write_text(ir)\n-def compile_or_get_cached(backend, computation, compile_options):\n+def compile_or_get_cached(backend, computation, compile_options,\n+ host_callbacks):\n# Avoid import cycle between jax and jax.experimental\nfrom jax.experimental.compilation_cache import compilation_cache as cc\n@@ -861,7 +872,8 @@ def compile_or_get_cached(backend, computation, compile_options):\nlogging.info('Persistent compilation cache hit for %s.', module_name)\nreturn cached_executable\nelse:\n- compiled = backend_compile(backend, computation, compile_options)\n+ compiled = backend_compile(backend, computation, compile_options,\n+ host_callbacks)\ncc.put_executable(module_name, computation, compile_options, compiled,\nbackend)\nreturn compiled\n@@ -875,7 +887,7 @@ def compile_or_get_cached(backend, computation, compile_options):\nassert isinstance(computation, str)\nir_str = computation\n_dump_ir_to_file(module_name, ir_str)\n- return backend_compile(backend, computation, compile_options)\n+ return backend_compile(backend, computation, compile_options, host_callbacks)\nclass XlaCompiledComputation(stages.XlaExecutable):\n@@ -890,21 +902,17 @@ class XlaCompiledComputation(stages.XlaExecutable):\nself.unsafe_call.keepalive = keepalive\n@staticmethod\n- def from_xla_computation(\n- name: str,\n- xla_computation: Optional[ir.Module],\n+ def from_xla_computation(name: str, xla_computation: Optional[ir.Module],\nin_type: Optional[pe.InputType],\n- out_type: Optional[pe.OutputType],\n- nreps: int,\n- device: Optional[Device],\n- backend: Backend,\n+ out_type: Optional[pe.OutputType], nreps: int,\n+ device: Optional[Device], backend: Backend,\ntuple_args: bool,\nin_avals: Sequence[core.AbstractValue],\nout_avals: Sequence[core.AbstractValue],\nhas_unordered_effects: bool,\nordered_effects: List[core.Effect],\n- kept_var_idx: Set[int],\n- keepalive: Optional[Any]) -> XlaCompiledComputation:\n+ kept_var_idx: Set[int], keepalive: Optional[Any],\n+ host_callbacks: List[Any]) -> XlaCompiledComputation:\nsticky_device = device\ninput_handler = _input_handler(backend, in_type, out_type)\nresult_handler = _result_handler(backend, sticky_device, out_type)\n@@ -914,7 +922,8 @@ class XlaCompiledComputation(stages.XlaExecutable):\noptions.parameter_is_tupled_arguments = tuple_args\nwith log_elapsed_time(f\"Finished XLA compilation of {name} \"\n\"in {elapsed_time} sec\"):\n- compiled = compile_or_get_cached(backend, xla_computation, options)\n+ compiled = compile_or_get_cached(backend, xla_computation, options,\n+ host_callbacks)\nbuffer_counts = [aval_to_num_buffers(aval) for aval in out_avals]\nif ordered_effects or has_unordered_effects:\nnum_output_tokens = len(ordered_effects) + has_unordered_effects\n@@ -937,15 +946,15 @@ class XlaCompiledComputation(stages.XlaExecutable):\nreturn self._xla_executable\n@staticmethod\n- def from_trivial_jaxpr(\n- jaxpr, consts, device, in_avals, out_avals, has_unordered_effects,\n- ordered_effects, kept_var_idx, keepalive: Optional[Any]\n- ) -> XlaCompiledComputation:\n+ def from_trivial_jaxpr(jaxpr, consts, device, in_avals, out_avals,\n+ has_unordered_effects, ordered_effects, kept_var_idx,\n+ keepalive: Optional[Any],\n+ host_callbacks: List[Any]) -> XlaCompiledComputation:\nassert keepalive is None\nresult_handlers = map(partial(aval_to_result_handler, device), out_avals)\n- unsafe_call = partial(_execute_trivial, jaxpr, device, consts,\n- out_avals, result_handlers, has_unordered_effects,\n- ordered_effects, kept_var_idx)\n+ unsafe_call = partial(_execute_trivial, jaxpr, device, consts, out_avals,\n+ result_handlers, has_unordered_effects,\n+ ordered_effects, kept_var_idx, host_callbacks)\nreturn XlaCompiledComputation(None, in_avals, kept_var_idx, unsafe_call,\nkeepalive)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -1159,16 +1159,16 @@ def _outside_call_lowering(\n# inside pmap, but does not work when we just execute on a single device,\n# because in such executions we always get replica_id == 0.\nreplica_id = mhlo.ReplicaIdOp()\n- callback_operands = [current_token, replica_id, *args_to_outfeed]\n+ callback_operands = [replica_id, *args_to_outfeed]\ncallback_operand_avals = [\n- core.abstract_token, core.ShapedArray((), np.uint32), *ctx.avals_in[:-2]]\n+ core.ShapedArray((), np.uint32), *ctx.avals_in[:-2]]\nif identity:\n- callback_flat_results_aval = [core.abstract_token]\n+ callback_flat_results_aval = []\nelse:\n- callback_flat_results_aval = [core.abstract_token, *flat_results_aval]\n+ callback_flat_results_aval = [*flat_results_aval]\ndef wrapped_callback(*args):\n- token, replica_id, *arrays = args\n+ replica_id, *arrays = args\nresult_arrays = _outside_call_run_callback(\narrays,\nxb.local_devices()[replica_id],\n@@ -1180,13 +1180,13 @@ def _outside_call_lowering(\nif identity:\n# For identity, we do not pass the any results back to the device\nresult_arrays = ()\n- return (token,) + result_arrays\n+ return result_arrays\n- results, keep_alive = mlir.emit_python_callback(platform, wrapped_callback,\n- callback_operands, callback_operand_avals, callback_flat_results_aval, # type: ignore[arg-type]\n+ results, next_token, keep_alive = mlir.emit_python_callback(ctx,\n+ wrapped_callback, current_token, callback_operands,\n+ callback_operand_avals, callback_flat_results_aval, # type: ignore[arg-type]\nhas_side_effect=True)\n_callback_handler_data.keep_alives.append(keep_alive)\n- next_token, *results = results\n# We must put the two tokens at the end\nif identity:\nresults = list(args_to_outfeed)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -24,8 +24,8 @@ import io\nimport itertools\nimport re\nimport typing\n-from typing import (Any, Callable, Dict, List, Optional, Sequence, Set, Tuple,\n- Type, Union, FrozenSet)\n+from typing import (Any, Callable, Dict, Iterator, List, NamedTuple, Optional,\n+ Sequence, Set, Tuple, Type, Union, FrozenSet)\nfrom typing_extensions import Protocol\nimport warnings\n@@ -372,6 +372,8 @@ class ModuleContext:\naxis_context: AxisContext\nname_stack: NameStack\nkeepalives: List[Any]\n+ channel_iterator: Iterator[int]\n+ host_callbacks: List[Any]\n# Cached primitive lowerings.\ncached_primitive_lowerings: Dict[Any, func_dialect.FuncOp]\n@@ -386,11 +388,14 @@ class ModuleContext:\naxis_context: AxisContext,\nname_stack: NameStack,\nkeepalives: List[Any],\n+ channel_iterator: Iterator[int],\n+ host_callbacks: List[Any],\ncontext: Optional[ir.Context] = None,\nmodule: Optional[ir.Module] = None,\nip: Optional[ir.InsertionPoint] = None,\nsymbol_table: Optional[ir.SymbolTable] = None,\n- cached_primitive_lowerings: Optional[Dict[Any, func_dialect.FuncOp]] = None):\n+ cached_primitive_lowerings: Optional[Dict[Any,\n+ func_dialect.FuncOp]] = None):\nassert platform is not None\nself.context = context or make_ir_context()\nself.module = module or ir.Module.create(loc=ir.Location.unknown(self.context))\n@@ -401,7 +406,15 @@ class ModuleContext:\nself.name_stack = name_stack\nself.cached_primitive_lowerings = ({} if cached_primitive_lowerings is None\nelse cached_primitive_lowerings)\n+ self.channel_iterator = channel_iterator\nself.keepalives = keepalives\n+ self.host_callbacks = host_callbacks\n+\n+ def new_channel(self) -> int:\n+ return next(self.channel_iterator)\n+\n+ def add_host_callback(self, host_callback: Any) -> None:\n+ self.host_callbacks.append(host_callback)\ndef add_keepalive(self, keepalive: Any) -> None:\nself.keepalives.append(keepalive)\n@@ -493,17 +506,25 @@ def sharded_aval(aval: core.ShapedArray,\nreturn aval.update(tuple(sharded_shape))\n+class LoweringResult(NamedTuple):\n+ module: ir.Module\n+ keepalive: Optional[Any]\n+ host_callbacks: List[Any]\n+\n+\ndef lower_jaxpr_to_module(\n- module_name: str, jaxpr: core.ClosedJaxpr,\n+ module_name: str,\n+ jaxpr: core.ClosedJaxpr,\nunordered_effects: List[core.Effect],\nordered_effects: List[core.Effect],\nplatform: str,\naxis_context: AxisContext,\n- name_stack: NameStack, donated_args: Sequence[bool],\n+ name_stack: NameStack,\n+ donated_args: Sequence[bool],\nreplicated_args: Optional[Sequence[bool]] = None,\narg_shardings: Optional[Sequence[Optional[xc.OpSharding]]] = None,\nresult_shardings: Optional[Sequence[Optional[xc.OpSharding]]] = None\n- ) -> Tuple[ir.Module, Optional[Any]]:\n+) -> LoweringResult:\n\"\"\"Lowers a top-level jaxpr to an MHLO module.\nHandles the quirks of the argument/return value passing conventions of the\n@@ -540,9 +561,13 @@ def lower_jaxpr_to_module(\nmsg = f\"Donation is not implemented for {platform}.\\n{msg}\"\nwarnings.warn(f\"Some donated buffers were not usable: {', '.join(unused_donations)}.\\n{msg}\")\n+ # MHLO channels need to start at 1\n+ channel_iter = itertools.count(1)\n# Create a keepalives list that will be mutated during the lowering.\nkeepalives: List[Any] = []\n- ctx = ModuleContext(platform, axis_context, name_stack, keepalives)\n+ host_callbacks: List[Any] = []\n+ ctx = ModuleContext(platform, axis_context, name_stack, keepalives,\n+ channel_iter, host_callbacks)\nwith ctx.context, ir.Location.unknown(ctx.context):\n# Remove module name characters that XLA would alter. This ensures that\n# XLA computation preserves the module name.\n@@ -565,7 +590,7 @@ def lower_jaxpr_to_module(\ninput_output_aliases=input_output_aliases)\nctx.module.operation.verify()\n- return ctx.module, ctx.keepalives\n+ return LoweringResult(ctx.module, ctx.keepalives, ctx.host_callbacks)\ndef module_to_string(module: ir.Module) -> str:\noutput = io.StringIO()\n@@ -600,7 +625,7 @@ Token = Sequence[ir.Value]\ndef token_type() -> Sequence[ir.Type]:\nreturn [mhlo.TokenType.get()]\n-def token() -> Token:\n+def create_token() -> Token:\nreturn wrap_singleton_ir_values(\nmhlo.CreateTokenOp(mhlo.TokenType.get()).result)\n@@ -625,7 +650,7 @@ class TokenSet:\n@classmethod\ndef create(cls, effects: Sequence[core.Effect]) -> TokenSet:\n\"\"\"Creates a `TokenSet` corresponding to a list of `core.Effect`s.\"\"\"\n- tokens = [token() for _ in effects]\n+ tokens = [create_token() for _ in effects]\nreturn TokenSet(zip(effects, tokens))\ndef items(self) -> Sequence[Tuple[core.Effect, Token]]:\n@@ -1274,30 +1299,145 @@ def xla_fallback_lowering(prim: core.Primitive):\nregister_lowering(ad.custom_lin_p, ad._raise_custom_vjp_error_on_jvp)\n-def emit_python_callback(platform, callback,\n- operands: List[ir.Value],\n- operand_avals: List[core.AbstractValue],\n+SEND_TO_HOST_TYPE = 2\n+RECV_FROM_HOST_TYPE = 3\n+\n+_dtype_to_xla_type_string_map = {\n+ np.dtype(\"bool\"): \"pred\",\n+ np.dtype(\"float16\"): \"f16\",\n+ np.dtype(\"float32\"): \"f32\",\n+ np.dtype(\"float64\"): \"f64\",\n+ np.dtype(\"int8\"): \"s8\",\n+ np.dtype(\"uint8\"): \"u8\",\n+ np.dtype(\"int16\"): \"s16\",\n+ np.dtype(\"uint16\"): \"u16\",\n+ np.dtype(\"int32\"): \"s32\",\n+ np.dtype(\"uint32\"): \"u32\",\n+ np.dtype(\"int64\"): \"s64\",\n+ np.dtype(\"uint64\"): \"u64\",\n+ dtypes._bfloat16_dtype: \"bf16\",\n+ np.dtype(\"complex64\"): \"c64\",\n+ np.dtype(\"complex128\"): \"c128\",\n+}\n+\n+def _dtype_to_xla_type_string(dtype: np.dtype) -> str:\n+ if dtype not in _dtype_to_xla_type_string_map:\n+ raise NotImplementedError(dtype)\n+ return _dtype_to_xla_type_string_map[dtype]\n+\n+def send_to_host(channel: int, token: mhlo.TokenType, operand: Any,\n+ aval: core.ShapedArray, name: str) -> ir.Value:\n+ channel_handle = mhlo.ChannelHandle.get(channel, SEND_TO_HOST_TYPE)\n+ send_op = mhlo.SendOp(mhlo.TokenType.get(), [operand], token, channel_handle,\n+ is_host_transfer=ir.BoolAttr.get(True))\n+ dtype_str = _dtype_to_xla_type_string(aval.dtype)\n+ if dtype_str in {\"f64\", \"s64\", \"u64\", \"c64\", \"c128\"}:\n+ raise NotImplementedError(\"64-bit types not supported.\")\n+ send_op.attributes[\"mhlo.frontend_attributes\"] = ir.DictAttr.get(\n+ dict(\n+ _xla_host_transfer_handler_name=ir.StringAttr.get(str(name)),\n+ _xla_host_transfer_original_type=ir.StringAttr.get(dtype_str),\n+ _xla_host_transfer_rendezvous=ir.StringAttr.get(str(name))))\n+ return send_op.result\n+\n+\n+def receive_from_host(channel: int, token: mhlo.TokenType,\n+ out_aval: core.ShapedArray, name: str) -> ir.Value:\n+ channel_handle = mhlo.ChannelHandle.get(channel, RECV_FROM_HOST_TYPE)\n+ recv_op = mhlo.RecvOp([aval_to_ir_type(out_aval),\n+ mhlo.TokenType.get()], token, channel_handle,\n+ is_host_transfer=ir.BoolAttr.get(True))\n+ dtype_str = _dtype_to_xla_type_string(out_aval.dtype)\n+ if dtype_str in {\"f64\", \"s64\", \"u64\", \"c64\", \"c128\"}:\n+ raise NotImplementedError(\"64-bit types not supported.\")\n+ recv_op.attributes[\"mhlo.frontend_attributes\"] = ir.DictAttr.get(\n+ dict(\n+ _xla_host_transfer_handler_name=ir.StringAttr.get(str(name)),\n+ _xla_host_transfer_original_type=ir.StringAttr.get(dtype_str),\n+ _xla_host_transfer_rendezvous=ir.StringAttr.get(str(name))))\n+ # Token should be at the end of the results\n+ result, token = recv_op.results\n+ return token, result\n+\n+\n+def emit_python_callback(\n+ ctx: LoweringRuleContext, callback, token: Optional[Any],\n+ operands: List[ir.Value], operand_avals: List[core.AbstractValue],\nresult_avals: List[core.AbstractValue],\n- has_side_effect: bool) -> Tuple[List[ir.Value], Any]:\n+ has_side_effect: bool) -> Tuple[List[ir.Value], Any, Any]:\n\"\"\"Creates an MHLO `CustomCallOp` that calls back to the provided function.\"\"\"\n+ platform = ctx.module_context.platform\nif platform in {\"cuda\", \"rocm\"} and jax._src.lib.version < (0, 3, 11):\nraise ValueError(\n\"`EmitPythonCallback` on CUDA only supported on jaxlib >= 0.3.11\")\n- if platform not in {\"cpu\", \"cuda\", \"rocm\"}:\n+ if platform in {\"tpu\"} and jax._src.lib.version < (0, 3, 15):\n+ raise ValueError(\n+ \"`EmitPythonCallback` on TPU only supported on jaxlib >= 0.3.15\")\n+ if platform not in {\"cpu\", \"cuda\", \"rocm\", \"tpu\"}:\nraise ValueError(\n- \"`EmitPythonCallback` only supported on CPU, CUDA, and ROCM backends.\")\n+ f\"`EmitPythonCallback` not supported on {platform} backend.\")\nbackend = xb.get_backend(platform)\nresult_shapes = util.flatten(\n[xla.aval_to_xla_shapes(result_aval) for result_aval in result_avals])\noperand_shapes = util.flatten(\n[xla.aval_to_xla_shapes(op_aval) for op_aval in operand_avals])\n- callback_descriptor, keepalive = backend.get_emit_python_callback_descriptor(\n- callback, operand_shapes, result_shapes)\n+ if platform == \"tpu\":\n+ if result_avals:\n+ raise NotImplementedError(\n+ \"Callback with return values not supported on TPU.\")\n+ token = token or mhlo.CreateTokenOp(mhlo.TokenType.get()).result\n+ send_channels = []\n+ for operand, operand_aval in zip(operands, operand_avals):\n+ channel = ctx.module_context.new_channel()\n+ token = send_to_host(channel, token, operand, operand_aval,\n+ callback.__name__)\n+ send_channels.append(channel)\n+ recv_channels = []\n+ recv_channel = ctx.module_context.new_channel()\n+\n+ # `send-to-host`s can be interleaved by the transfer manager so we add in a\n+ # dummy recv to sequence them (the recv can only happen after all the sends\n+ # are done). We'd like to send back a 0-shaped array to avoid unnecessary\n+ # copies but that currently doesn't work with the transfer\n+ # manager as well.\n+ # TODO(b/238239458): enable sending back a 0-dim array\n+ # TODO(b/238239928): avoid interleaving sends in the transfer manager\n+ def _wrapped_callback(*args, **kwargs):\n+ callback(*args, **kwargs)\n+ return (np.zeros(1, np.float32),)\n+\n+ dummy_recv_aval = core.ShapedArray((1,), np.float32)\n+ result_shapes = [*result_shapes, xla.aval_to_xla_shapes(dummy_recv_aval)[0]]\n+ token, _ = receive_from_host(recv_channel, token, dummy_recv_aval,\n+ callback.__name__)\n+ recv_channels.append(recv_channel)\n+ opaque = backend.make_python_callback_from_host_send_and_recv(\n+ _wrapped_callback, operand_shapes, result_shapes, send_channels,\n+ recv_channels)\n+ ctx.module_context.add_host_callback(opaque)\n+ return [], token, opaque\n+ result_types = util.flatten([aval_to_ir_types(aval) for aval in result_avals])\n+ wrapped_callback = callback\n+ if token:\n+\n+ def wrapped_callback(token, *args): # type: ignore\n+ return tuple((token, *callback(*args)))\n+\n+ operand_shapes = [\n+ xla.aval_to_xla_shapes(core.abstract_token)[0], *operand_shapes\n+ ]\n+ result_shapes = [\n+ xla.aval_to_xla_shapes(core.abstract_token)[0], *result_shapes\n+ ]\n+ operands = [token, *operands]\n+ result_types = [token_type()[0], *result_types]\n+ callback_descriptor, keepalive = (\n+ backend.get_emit_python_callback_descriptor(wrapped_callback,\n+ operand_shapes,\n+ result_shapes))\ndescriptor_operand = ir_constant(\ncallback_descriptor, canonicalize_types=False)\ncallback_operands = [descriptor_operand, *operands]\n- result_types = util.flatten(\n- [aval_to_ir_types(aval) for aval in result_avals])\nresult_type = ir.TupleType.get_tuple(result_types)\ncall_target_name = (\"xla_python_gpu_callback\"\nif platform in {\"cuda\", \"rocm\"} else \"xla_python_cpu_callback\")\n@@ -1315,7 +1455,9 @@ def emit_python_callback(platform, callback,\nmhlo.GetTupleElementOp(result, i32_attr(i)).result\nfor i in range(len(result_types))\n]\n- return results, keepalive\n+ if token:\n+ token, *results = results\n+ return results, token, keepalive\n# Lax ops missing MLIR lowerings.\n# # TODO(b/203775215): these are missing from the cHLO dialect. Either add\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1089,16 +1089,19 @@ def lower_parallel_callable(\nraise ValueError(\"Ordered effects not supported in `pmap`.\")\nunordered_effects = [eff for eff in closed_jaxpr.effects\nif eff not in core.ordered_effects]\n- module, keepalive = mlir.lower_jaxpr_to_module(\n+ lowering_result = mlir.lower_jaxpr_to_module(\nmodule_name, closed_jaxpr, unordered_effects, [],\nbackend.platform, mlir.ReplicaAxisContext(axis_env),\nname_stack, donated_invars, replicated_args=replicated_args,\narg_shardings=_shardings_to_mlir_shardings(parts.arg_parts),\nresult_shardings=_shardings_to_mlir_shardings(parts.out_parts))\n+ module, keepalive, host_callbacks = (\n+ lowering_result.module, lowering_result.keepalive,\n+ lowering_result.host_callbacks)\nreturn PmapComputation(module, pci=pci, replicas=replicas, parts=parts,\nshards=shards, tuple_args=tuple_args,\nunordered_effects=unordered_effects,\n- keepalive=keepalive)\n+ keepalive=keepalive, host_callbacks=host_callbacks)\nclass PmapComputation(stages.XlaLowering):\n@@ -1152,6 +1155,7 @@ class PmapExecutable(stages.XlaExecutable):\nshards: ShardInfo,\ntuple_args: bool,\nunordered_effects: List[core.Effect],\n+ host_callbacks: List[Any],\nkeepalive: Any):\ndevices = pci.devices\nif devices is None:\n@@ -1270,7 +1274,7 @@ class PmapExecutable(stages.XlaExecutable):\nwith dispatch.log_elapsed_time(\nf\"Finished XLA compilation of {pci.name} in {{elapsed_time}} sec\"):\ncompiled = dispatch.compile_or_get_cached(\n- pci.backend, xla_computation, compile_options)\n+ pci.backend, xla_computation, compile_options, host_callbacks)\nhandle_args = InputsHandler(\ncompiled.local_devices(), input_sharding_specs, input_indices)\nexecute_fun = ExecuteReplicated(compiled, pci.backend, handle_args,\n@@ -2350,17 +2354,19 @@ def lower_mesh_computation(\nraise ValueError(\"Ordered effects not supported in mesh computations.\")\nunordered_effects = [eff for eff in closed_jaxpr.effects\nif eff not in core.ordered_effects]\n- module, keepalive = mlir.lower_jaxpr_to_module(\n+ lowering_result = mlir.lower_jaxpr_to_module(\nmodule_name, closed_jaxpr, unordered_effects, [], backend.platform,\naxis_ctx, name_stack, donated_invars, replicated_args=replicated_args,\narg_shardings=in_partitions, result_shardings=out_partitions)\n-\n+ module, keepalive, host_callbacks = (\n+ lowering_result.module, lowering_result.keepalive,\n+ lowering_result.host_callbacks)\nreturn MeshComputation(\nstr(name_stack), module, donated_invars, mesh=mesh, global_in_avals=global_in_avals,\nglobal_out_avals=global_out_avals, in_axes=in_axes, out_axes=out_axes,\nspmd_lowering=spmd_lowering, tuple_args=tuple_args, in_is_global=in_is_global,\nauto_spmd_lowering=auto_spmd_lowering,\n- unordered_effects=unordered_effects,\n+ unordered_effects=unordered_effects, host_callbacks=host_callbacks,\nkeepalive=keepalive)\n@@ -2471,6 +2477,7 @@ class MeshExecutable(stages.XlaExecutable):\n_allow_propagation_to_outputs: bool,\n_allow_compile_replicated: bool,\nunordered_effects: List[core.Effect],\n+ host_callbacks: List[Any],\nkeepalive: Any) -> MeshExecutable:\nassert not mesh.empty\nbackend = xb.get_device_backend(mesh.devices.flat[0])\n@@ -2510,7 +2517,8 @@ class MeshExecutable(stages.XlaExecutable):\nelse:\nwith dispatch.log_elapsed_time(f\"Finished XLA compilation of {name} \"\n\"in {elapsed_time} sec\"):\n- xla_executable = dispatch.compile_or_get_cached(backend, computation, compile_options)\n+ xla_executable = dispatch.compile_or_get_cached(\n+ backend, computation, compile_options, host_callbacks)\nif auto_spmd_lowering or (out_axes and all(_is_unspecified(o) for o in out_axes)):\nin_axes, out_axes = _get_array_mapping_from_executable(xla_executable, mesh)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/sharded_jit.py", "new_path": "jax/interpreters/sharded_jit.py", "diff": "@@ -141,7 +141,7 @@ def _sharded_callable(\nif eff not in core.ordered_effects]\nordered_effects = [eff for eff in jaxpr.effects\nif eff in core.ordered_effects]\n- module, _ = mlir.lower_jaxpr_to_module(\n+ lowering_result = mlir.lower_jaxpr_to_module(\nf\"spjit_{fun.__name__}\",\ncore.ClosedJaxpr(jaxpr, consts),\nunordered_effects, ordered_effects,\n@@ -151,6 +151,8 @@ def _sharded_callable(\ndonated_args=[False]*len(in_parts),\narg_shardings=safe_map(xla.sharding_to_proto, in_parts),\nresult_shardings=safe_map(xla.sharding_to_proto, out_parts))\n+ module, host_callbacks = (lowering_result.module,\n+ lowering_result.host_callbacks)\nbuilt = xc._xla.mlir.mlir_module_to_xla_computation(\nmlir.module_to_string(module), use_tuple_args=False,\nreturn_tuple=True)\n@@ -166,7 +168,8 @@ def _sharded_callable(\ncompiled = dispatch.backend_compile(\nxb.get_backend(), built,\n- xb.get_compile_options(nrep, nparts, device_assignment))\n+ xb.get_compile_options(nrep, nparts, device_assignment),\n+ host_callbacks)\ninput_specs = [\npxla.partitioned_sharding_spec(local_nparts, parts, aval)\n" }, { "change_type": "MODIFY", "old_path": "tests/BUILD", "new_path": "tests/BUILD", "diff": "@@ -843,16 +843,28 @@ jax_test(\njax_test(\nname = \"jaxpr_effects_test\",\nsrcs = [\"jaxpr_effects_test.py\"],\n+ enable_configs = [\n+ \"gpu\",\n+ \"cpu\",\n+ ],\n)\njax_test(\nname = \"debugging_primitives_test\",\nsrcs = [\"debugging_primitives_test.py\"],\n+ enable_configs = [\n+ \"gpu\",\n+ \"cpu\",\n+ ],\n)\njax_test(\nname = \"debugger_test\",\nsrcs = [\"debugger_test.py\"],\n+ enable_configs = [\n+ \"gpu\",\n+ \"cpu\",\n+ ],\n)\nexports_files(\n" }, { "change_type": "MODIFY", "old_path": "tests/debugger_test.py", "new_path": "tests/debugger_test.py", "diff": "@@ -51,9 +51,13 @@ def tearDownModule():\n# TODO(sharadmv): remove jaxlib guards for GPU tests when jaxlib minimum\n# version is >= 0.3.11\n-disabled_backends = [\"tpu\"]\n+# TODO(sharadmv): remove jaxlib guards for TPU tests when jaxlib minimum\n+# version is >= 0.3.15\n+disabled_backends = []\nif jaxlib.version < (0, 3, 11):\ndisabled_backends.append(\"gpu\")\n+if jaxlib.version < (0, 3, 15):\n+ disabled_backends.append(\"tpu\")\nclass CliDebuggerTest(jtu.JaxTestCase):\n@@ -67,6 +71,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\nreturn y\nwith self.assertRaises(SystemExit):\nf(2.)\n+ jax.effects_barrier()\n@jtu.skip_on_devices(*disabled_backends)\ndef test_debugger_can_continue(self):\n@@ -77,6 +82,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndebugger.breakpoint(stdin=stdin, stdout=stdout)\nreturn y\nf(2.)\n+ jax.effects_barrier()\nexpected = _format_multiline(r\"\"\"\nEntering jaxdb:\n(jaxdb) \"\"\")\n@@ -95,6 +101,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\n(jaxdb) DeviceArray(2., dtype=float32)\n(jaxdb) \"\"\")\nf(jnp.array(2., jnp.float32))\n+ jax.effects_barrier()\nself.assertEqual(stdout.getvalue(), expected)\n@jtu.skip_on_devices(*disabled_backends)\n@@ -111,6 +118,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\n(jaxdb) array(2., dtype=float32)\n(jaxdb) \"\"\")\nf(jnp.array(2., jnp.float32))\n+ jax.effects_barrier()\nself.assertEqual(stdout.getvalue(), expected)\n@jtu.skip_on_devices(*disabled_backends)\n@@ -127,6 +135,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\n(jaxdb) (array(2., dtype=float32), array(3., dtype=float32))\n(jaxdb) \"\"\")\nf(jnp.array(2., jnp.float32))\n+ jax.effects_barrier()\nself.assertEqual(stdout.getvalue(), expected)\n@jtu.skip_on_devices(*disabled_backends)\n@@ -139,6 +148,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndebugger.breakpoint(stdin=stdin, stdout=stdout)\nreturn y\nf(2.)\n+ jax.effects_barrier()\nexpected = _format_multiline(r\"\"\"\nEntering jaxdb:\n\\(jaxdb\\) > .*debugger_test\\.py\\([0-9]+\\)\n@@ -165,6 +175,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\n\\(jaxdb\\) Traceback:.*\n\"\"\")\nf(2.)\n+ jax.effects_barrier()\nself.assertRegex(stdout.getvalue(), expected)\n@jtu.skip_on_devices(*disabled_backends)\n@@ -203,6 +214,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\n.*\n\\(jaxdb\\) \"\"\")\ng(jnp.array(2., jnp.float32))\n+ jax.effects_barrier()\nself.assertRegex(stdout.getvalue(), expected)\n@jtu.skip_on_devices(*disabled_backends)\n@@ -232,10 +244,14 @@ class CliDebuggerTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_debugger_works_with_vmap(self):\nstdin, stdout = make_fake_stdin_stdout([\"p y\", \"c\", \"p y\", \"c\"])\n+ # On TPU, the breakpoints can be reordered inside of vmap but can be fixed\n+ # by ordering sends.\n+ # TODO(sharadmv): change back to ordered = False when sends are ordered\n+ ordered = jax.default_backend() == \"tpu\"\ndef f(x):\ny = x + 1.\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, ordered=ordered)\nreturn 2. * y\n@jax.jit\n@@ -250,6 +266,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\n(jaxdb) array(2., dtype=float32)\n(jaxdb) \"\"\")\ng(jnp.arange(2., dtype=jnp.float32))\n+ jax.effects_barrier()\nself.assertEqual(stdout.getvalue(), expected)\n@jtu.skip_on_devices(*disabled_backends)\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\nimport contextlib\n+import collections\nimport functools\nimport io\nimport textwrap\n@@ -59,9 +60,13 @@ def tearDownModule():\n# TODO(sharadmv): remove jaxlib guards for GPU tests when jaxlib minimum\n# version is >= 0.3.11\n-disabled_backends = [\"tpu\"]\n+# TODO(sharadmv): remove jaxlib guards for TPU tests when jaxlib minimum\n+# version is >= 0.3.15\n+disabled_backends = []\nif jaxlib.version < (0, 3, 11):\ndisabled_backends.append(\"gpu\")\n+if jaxlib.version < (0, 3, 15):\n+ disabled_backends.append(\"tpu\")\nclass DebugPrintTest(jtu.JaxTestCase):\n@@ -193,6 +198,13 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\nclass DebugPrintControlFlowTest(jtu.JaxTestCase):\n+ def _assertLinesEqual(self, text1, text2):\n+\n+ def _count(lines):\n+ return collections.Counter(lines)\n+\n+ self.assertDictEqual(_count(text1.split(\"\\n\")), _count(text2.split(\"\\n\")))\n+\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\nfor ordered in [False, True]))\n@@ -220,19 +232,29 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\ndef test_can_print_inside_for_loop(self, ordered):\ndef f(x):\ndef _body(i, x):\n+ debug_print(\"i: {i}\", i=i, ordered=ordered)\ndebug_print(\"x: {x}\", x=x, ordered=ordered)\nreturn x + 1\nreturn lax.fori_loop(0, 5, _body, x)\nwith capture_stdout() as output:\nf(2)\njax.effects_barrier()\n- self.assertEqual(output(), _format_multiline(\"\"\"\n+ expected = _format_multiline(\"\"\"\n+ i: 0\nx: 2\n+ i: 1\nx: 3\n+ i: 2\nx: 4\n+ i: 3\nx: 5\n+ i: 4\nx: 6\n- \"\"\"))\n+ \"\"\")\n+ if ordered:\n+ self.assertEqual(output(), expected)\n+ else:\n+ self._assertLinesEqual(output(), expected)\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\n@@ -333,6 +355,7 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nreturn lax.switch(x, (b1, b2, b3), x)\nwith capture_stdout() as output:\nf(0)\n+ jax.effects_barrier()\nself.assertEqual(output(), _format_multiline(\"\"\"\nb1: 0\n\"\"\"))\n@@ -352,7 +375,11 @@ class DebugPrintControlFlowTest(jtu.JaxTestCase):\nclass DebugPrintParallelTest(jtu.JaxTestCase):\ndef _assertLinesEqual(self, text1, text2):\n- self.assertSetEqual(set(text1.split(\"\\n\")), set(text2.split(\"\\n\")))\n+\n+ def _count(lines):\n+ return collections.Counter(lines)\n+\n+ self.assertDictEqual(_count(text1.split(\"\\n\")), _count(text2.split(\"\\n\")))\n@jtu.skip_on_devices(*disabled_backends)\ndef test_ordered_print_not_supported_in_pmap(self):\n@@ -394,12 +421,35 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\ndebug_print(\"{}\", x, ordered=False)\nf = maps.xmap(f, in_axes=['a'], out_axes=None, backend='cpu',\naxis_resources={'a': 'dev'})\n- with maps.Mesh(np.array(jax.devices(backend='cpu')), ['dev']):\n+ with maps.Mesh(np.array(jax.devices()), ['dev']):\nwith capture_stdout() as output:\nf(jnp.arange(40))\njax.effects_barrier()\nlines = [f\"{i}\\n\" for i in range(40)]\nself._assertLinesEqual(output(), \"\".join(lines))\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_unordered_print_works_in_pmap_of_while(self):\n+\n+ if jax.device_count() < 2:\n+ raise unittest.SkipTest(\"Test requires >= 2 devices.\")\n+\n+ @jax.pmap\n+ def f(x):\n+ def cond(x):\n+ return x < 3\n+ def body(x):\n+ debug_print(\"hello: {}\", x, ordered=False)\n+ return x + 1\n+ return lax.while_loop(cond, body, x)\n+\n+ with capture_stdout() as output:\n+ f(jnp.arange(2))\n+ jax.effects_barrier()\n+\n+ self._assertLinesEqual(\n+ output(), \"hello: 0\\nhello: 1\\nhello: 2\\n\"\n+ \"hello: 1\\nhello: 2\\n\")\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -61,9 +61,13 @@ lcf.allowed_effects.add('while2')\n# TODO(sharadmv): remove jaxlib guards for GPU tests when jaxlib minimum\n# version is >= 0.3.11\n-disabled_backends = ['tpu']\n+# TODO(sharadmv): remove jaxlib guards for TPU tests when jaxlib minimum\n+# version is >= 0.3.15\n+disabled_backends = []\nif jaxlib.version < (0, 3, 11):\ndisabled_backends.append('gpu')\n+if jaxlib.version < (0, 3, 15):\n+ disabled_backends.append('tpu')\ndef trivial_effect_lowering(ctx, *, effect):\n@@ -108,23 +112,16 @@ def _(*avals, callback, out_avals, effect):\ndef callback_effect_lowering(ctx: mlir.LoweringRuleContext, *args, callback, out_avals, effect):\ndel out_avals\n+ token_in = None\nif effect in core.ordered_effects:\n- def _token_callback(token, *args):\n- out = callback(*args)\n- flat_out = jax.tree_util.tree_leaves(out)\n- return (token, *flat_out)\ntoken_in = ctx.tokens_in.get(effect)[0]\n- (token_out, *out_op), keep_alive = mlir.emit_python_callback(\n- ctx.module_context.platform, _token_callback,\n- [token_in, *args], [core.abstract_token, *ctx.avals_in],\n- [core.abstract_token, *ctx.avals_out], True)\n+\n+ out_op, token_out, keep_alive = mlir.emit_python_callback(\n+ ctx, callback, token_in, list(args), list(ctx.avals_in),\n+ list(ctx.avals_out), True)\n+ if token_out:\nctx.set_tokens_out(ctx.tokens_in.update_tokens(mlir.TokenSet({effect:\ntoken_out})))\n- else:\n- out_op, keep_alive = mlir.emit_python_callback(\n- ctx.module_context.platform, callback,\n- list(args), list(ctx.avals_in),\n- list(ctx.avals_out), True)\nctx.module_context.add_keepalive(keep_alive)\nreturn out_op\n@@ -297,6 +294,7 @@ class EffectfulJaxprLoweringTest(jtu.JaxTestCase):\nctx.set_tokens_out(ctx.tokens_in)\nreturn []\nmlir.register_lowering(effect_p, _effect_lowering)\n+ jax.effects_barrier()\ndispatch.runtime_tokens.clear()\ndef tearDown(self):\n@@ -590,10 +588,11 @@ class EffectOrderingTest(jtu.JaxTestCase):\nreturn callback_p.bind(x, callback=log_value, effect='log', out_avals=[])\nf(2.)\n+ jax.effects_barrier()\nself.assertListEqual(log, [2.])\nf(3.)\n+ jax.effects_barrier()\nself.assertListEqual(log, [2., 3.])\n- dispatch.runtime_tokens.block_until_ready()\n@jtu.skip_on_devices(*disabled_backends)\ndef test_ordered_effect_remains_ordered_across_multiple_devices(self):\n@@ -623,15 +622,14 @@ class EffectOrderingTest(jtu.JaxTestCase):\ng(3.)\nf(jnp.ones((500, 500)))\ng(3.)\n- dispatch.runtime_tokens.block_until_ready()\n+ jax.effects_barrier()\nx_, y_ = float(jnp.log(1.25e8)), 3.\nexpected_log = [x_, y_, x_, y_, x_, y_]\nself.assertListEqual(log, expected_log)\n+ @jtu.skip_on_devices(\"tpu\")\n@jtu.skip_on_devices(*disabled_backends)\ndef test_different_threads_get_different_tokens(self):\n- # TODO(sharadmv): enable this test on GPU and TPU when backends are\n- # supported\nif jax.device_count() < 2:\nraise unittest.SkipTest(\"Test requires >= 2 devices.\")\ntokens = []\n" } ]
Python
Apache License 2.0
google/jax
Enable Python callbacks on TFRT TPU backend PiperOrigin-RevId: 459415455
260,335
29.06.2022 13:55:30
25,200
98e71fe31de8f6ea26be76488d41fb471fef56eb
[dynamic-shapes] revive basic bounded int machinery, add tests
[ { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -299,6 +299,7 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nif config.jax_dynamic_shapes:\nkeep_unused = True\nhas_outfeed = False\n+ donated_invars = [False] * len(fun.in_type)\nelse:\nhas_outfeed = core.jaxpr_uses_outfeed(jaxpr)\njaxpr = apply_outfeed_rewriter(jaxpr)\n@@ -318,8 +319,7 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\ndevice = _xla_callable_device(nreps, backend, device, arg_devices)\nbackend = xb.get_device_backend(device) if device else xb.get_backend(backend)\n- if (config.jax_dynamic_shapes and jaxpr_has_bints(jaxpr) and\n- not _backend_supports_unbounded_dynamic_shapes(backend)):\n+ if config.jax_dynamic_shapes and jaxpr_has_bints(jaxpr):\njaxpr, consts = pe.pad_jaxpr(jaxpr, consts)\nmap(prefetch, itertools.chain(consts, jaxpr_literals(jaxpr)))\n@@ -517,6 +517,7 @@ num_buffers_handlers[core.AbstractToken] = lambda _: 1\nnum_buffers_handlers[core.ShapedArray] = lambda _: 1\nnum_buffers_handlers[core.DShapedArray] = lambda _: 1\nnum_buffers_handlers[core.ConcreteArray] = lambda _: 1\n+num_buffers_handlers[core.AbstractBInt] = lambda _: 1\ndef _input_handler(backend: Backend,\n@@ -649,19 +650,24 @@ def dynamic_array_result_handler(sticky_device: Optional[Device],\nreturn partial(_dynamic_array_result_handler, sticky_device, aval)\ndef _dynamic_array_result_handler(sticky_device, aval, env, buf):\n- if all(type(d) is int for d in aval.shape):\n- del env\n- return _maybe_create_array_from_da(buf, aval, sticky_device)\n- else:\n- assert env is not None\n- in_env, out_env = env\n+ in_env, out_env = env or (None, None)\nshape = [in_env[d.val] if type(d) is core.InDBIdx else\nout_env[d.val] if type(d) is core.OutDBIdx else d\nfor d in aval.shape]\n+ if all(type(d) is int for d in shape):\n+ aval = core.ShapedArray(tuple(shape), aval.dtype)\n+ return _maybe_create_array_from_da(buf, aval, sticky_device)\n+ elif any(type(d) is core.BInt for d in shape):\n+ padded_shape = [d.bound if type(d) is core.BInt else d for d in shape]\n+ buf_aval = core.ShapedArray(tuple(padded_shape), aval.dtype, aval.weak_type)\n+ data = _maybe_create_array_from_da(buf, buf_aval, sticky_device)\n+ return core.PaddedArray(aval.update(shape=tuple(shape)), data)\n+ else:\naval = core.ShapedArray(tuple(shape), aval.dtype)\nreturn _maybe_create_array_from_da(buf, aval, sticky_device)\n+\nresult_handlers: Dict[\nType[core.AbstractValue],\nCallable[[Optional[Device], Any], ResultHandler]] = {}\n@@ -669,6 +675,8 @@ result_handlers[core.AbstractToken] = lambda _, __: lambda _, __: core.token\nresult_handlers[core.ShapedArray] = array_result_handler\nresult_handlers[core.DShapedArray] = dynamic_array_result_handler\nresult_handlers[core.ConcreteArray] = array_result_handler\n+result_handlers[core.AbstractBInt] = \\\n+ lambda _, a: lambda _, b: core.BInt(int(b), a.bound)\ndef needs_check_special():\n@@ -1005,6 +1013,7 @@ device_put_handlers: Dict[Any, Callable[[Any, Optional[Device]], Tuple[Any]]] =\ndevice_put_handlers.update((t, _device_put_array) for t in array_types)\ndevice_put_handlers.update((t, _device_put_scalar) for t in _scalar_types)\ndevice_put_handlers[core.Token] = _device_put_token\n+device_put_handlers[core.BInt] = lambda x, d: _device_put_scalar(x.val, d)\ndef _device_put_device_array(x: Union[device_array.DeviceArrayProtocol, device_array._DeviceArray], device: Optional[Device]):\n@@ -1012,6 +1021,7 @@ def _device_put_device_array(x: Union[device_array.DeviceArrayProtocol, device_a\nreturn (x.device_buffer,)\nfor t in device_array.device_array_types:\ndevice_put_handlers[t] = _device_put_device_array\n+device_put_handlers[core.PaddedArray] = lambda x, d: device_put(x._data, d)\ndef _copy_device_array_to_device(\nx: Union[device_array.DeviceArrayProtocol, device_array._DeviceArray],\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/iree.py", "new_path": "jax/_src/iree.py", "diff": "@@ -104,8 +104,8 @@ class IreeBuffer(xla_client.DeviceArrayBase):\nreturn self # no async\n# overrides repr on base class which expects _value and aval attributes\n- def __repr__(self):\n- return f'IreeBuffer({self.to_py()})'\n+ def __repr__(self): return f'IreeBuffer({self.to_py()})'\n+ _value = property(to_py)\nclass IreeExecutable:\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -1440,6 +1440,7 @@ def unop(result_dtype, accepted_dtypes, name):\nweak_type_rule=weak_type_rule)\nbatching.defvectorized(prim)\nmasking.defvectorized(prim)\n+ pe.padding_rules[prim] = lambda _, __, x, **kw: [prim.bind(x, **kw)]\nreturn prim\nstandard_unop = partial(unop, _identity)\n_attrgetter = lambda name: lambda x, **kwargs: getattr(x, name)\n@@ -1515,6 +1516,7 @@ def naryop(result_dtype, accepted_dtypes, name):\nweak_type_rule=weak_type_rule)\nbatching.defbroadcasting(prim)\nmasking.defnaryop(prim)\n+ pe.padding_rules[prim] = lambda _, __, *xs, **kw: [prim.bind(*xs, **kw)]\nreturn prim\nstandard_naryop = partial(naryop, _input_dtype)\n@@ -2080,7 +2082,6 @@ add_p: Primitive = standard_naryop([_num, _num], 'add')\nad.primitive_jvps[add_p] = _add_jvp\nad.primitive_transposes[add_p] = _add_transpose\nmlir.register_lowering(add_p, partial(_nary_lower_mhlo, mhlo.AddOp))\n-pe.padding_rules[add_p] = lambda _, __, x, y: [add(x, y)]\ndef _sub_jvp(primals, tangents):\nx, y = primals\n@@ -2110,7 +2111,6 @@ sub_p = standard_naryop([_num, _num], 'sub')\nad.primitive_jvps[sub_p] = _sub_jvp\nad.primitive_transposes[sub_p] = _sub_transpose\nmlir.register_lowering(sub_p, partial(_nary_lower_mhlo, mhlo.SubOp))\n-pe.padding_rules[sub_p] = lambda _, __, x, y: [sub(x, y)]\ndef _mul_transpose(ct, x, y):\n@@ -2137,7 +2137,6 @@ ad.defjvp(mul_p,\nlambda ydot, x, y: mul(x, ydot))\nad.primitive_transposes[mul_p] = _mul_transpose\nmlir.register_lowering(mul_p, partial(_nary_lower_mhlo, mhlo.MulOp))\n-pe.padding_rules[mul_p] = lambda _, __, x, y: [mul(x, y)]\ndef _div_transpose_rule(cotangent, x, y):\nassert ad.is_undefined_primal(x) and not ad.is_undefined_primal(y)\n@@ -2174,7 +2173,6 @@ ad.defjvp2(max_p,\nlambda g, ans, x, y: mul(g, _balanced_eq(x, ans, y)),\nlambda g, ans, x, y: mul(g, _balanced_eq(y, ans, x)))\nmlir.register_lowering(max_p, partial(_nary_lower_mhlo, mlir.max_mhlo))\n-pe.padding_rules[max_p] = lambda _, __, x, y: [max(x, y)]\nmin_p: core.Primitive = standard_naryop([_any, _any], 'min')\nad.defjvp2(min_p,\n@@ -2297,9 +2295,13 @@ def _convert_elt_type_pp_rule(eqn, context, settings):\nprinted_params = {}\nif eqn.params['weak_type']:\nprinted_params['weak_type'] = True\n- return [pp.text(eqn.primitive.name),\n+ lhs = core.pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\n+ rhs = [pp.text(eqn.primitive.name),\ncore.pp_kv_pairs(sorted(printed_params.items()), context, settings),\npp.text(\" \") + core.pp_vars(eqn.invars, context)]\n+ annotation = (source_info_util.summarize(eqn.source_info)\n+ if settings.source_info else None)\n+ return [lhs, pp.text(\" = \", annotation=annotation), *rhs]\nconvert_element_type_p = Primitive('convert_element_type')\n@@ -2756,7 +2758,7 @@ def _broadcast_in_dim_padding_rule(in_avals, out_avals, x, *dyn_shape,\nassert isinstance(d, core.Tracer)\nnew_shape.append(None)\nnew_dyn_shape.append(d)\n- return [broadcast_in_dim_p.bind(x, *new_dyn_shape, shape=new_shape,\n+ return [broadcast_in_dim_p.bind(x, *new_dyn_shape, shape=tuple(new_shape),\nbroadcast_dimensions=broadcast_dimensions)]\ndef _broadcast_in_dim_jvp_rule(primals, tangents, *, shape, broadcast_dimensions):\n@@ -2820,8 +2822,18 @@ def _broadcast_in_dim_pp_rule(eqn, context, settings):\nif settings.source_info else None)\nreturn [lhs, pp.text(\" = \", annotation=annotation), *rhs]\n+def _broadcast_in_dim_abstract_eval(x, *dyn_shape, shape, broadcast_dimensions):\n+ if not any(isinstance(d, core.BInt) for d in shape):\n+ shape = _broadcast_in_dim_shape_rule( # error checking\n+ x, shape=shape, broadcast_dimensions=broadcast_dimensions)\n+ return core.ShapedArray(shape, x.dtype, x.weak_type, x.named_shape)\n+ # If any BInts in shape, produce a DShapedArray (even if x is a ShapedArray)\n+ # TODO(mattjj): unify DShapedArray with ShapedArray, and remove this code\n+ return core.DShapedArray(shape, x.dtype, x.weak_type)\n+\nbroadcast_in_dim_p = standard_primitive(\n_broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')\n+broadcast_in_dim_p.def_abstract_eval(_broadcast_in_dim_abstract_eval)\nad.primitive_jvps[broadcast_in_dim_p] = _broadcast_in_dim_jvp_rule\nad.primitive_transposes[broadcast_in_dim_p] = _broadcast_in_dim_transpose_rule\nbatching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule\n@@ -3605,8 +3617,8 @@ def _reduce_sum_padding_rule(in_avals, out_avals, operand, *, axes):\ndef _replace_masked_values(x, val, padded_axes):\nif not padded_axes: return x\n- masks = [broadcasted_iota(np.dtype('int32'), x.shape, i) < d\n- for i, d in padded_axes]\n+ dtype = dtypes._scalar_type_to_dtype(int)\n+ masks = [broadcasted_iota(dtype, x.shape, i) < d for i, d in padded_axes]\nreturn select(_reduce(operator.and_, masks), x, full_like(x, val))\n@@ -4384,7 +4396,10 @@ def _iota_abstract_eval(*, dtype, shape, dimension):\nif not 0 <= dimension < len(shape):\nraise ValueError(\"iota dimension must be between 0 and len(shape), got \"\nf\"dimension={dimension} for shape {shape}\")\n+ if not any(isinstance(d, core.BInt) for d in shape):\nreturn ShapedArray(shape, dtype)\n+ # TODO(mattjj): unify DShapedArray with ShapedArray, and remove this code\n+ return core.DShapedArray(shape, dtype, False)\niota_p = Primitive('iota')\niota_p.def_impl(partial(xla.apply_primitive, iota_p))\n@@ -4425,12 +4440,46 @@ def _iota_lower(ctx, *dyn_shape, dtype, shape, dimension):\nmlir.i64_attr(dimension)).results\nmlir.register_lowering(iota_p, _iota_lower)\n+def _iota_pp_rule(eqn, context, settings):\n+ printed_params = {}\n+ if len(eqn.params['shape']) > 1:\n+ printed_params['dimension'] = eqn.params['dimension']\n+ lhs = core.pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\n+ rhs = [pp.text(eqn.primitive.name),\n+ core.pp_kv_pairs(sorted(printed_params.items()), context, settings),\n+ pp.text(\" \") + core.pp_vars(eqn.invars, context)]\n+ annotation = (source_info_util.summarize(eqn.source_info)\n+ if settings.source_info else None)\n+ return [lhs, pp.text(\" = \", annotation=annotation), *rhs]\n+# core.pp_eqn_rules[iota_p] = _iota_pp_rule\n+\n+def _iota_padding_rule(in_avals, out_avals, *dyn_shape, dtype, shape, dimension):\n+ out_aval, = out_avals\n+ new_shape = []\n+ new_dyn_shape = []\n+ for d in out_aval.shape:\n+ if type(d) is pe.BoundedAxisSize:\n+ new_shape.append(d.bound)\n+ elif type(d) is int:\n+ new_shape.append(d)\n+ else:\n+ assert isinstance(d, core.Tracer)\n+ new_shape.append(None)\n+ new_dyn_shape.append(d)\n+ return [iota_p.bind(*new_dyn_shape, shape=tuple(new_shape),\n+ dtype=dtype, dimension=dimension)]\n+pe.padding_rules[iota_p] = _iota_padding_rule\n+\ndef make_bint(i, bd: int):\nreturn bint_p.bind(i, bd=bd)\nbint_p = core.Primitive('bint')\n+@bint_p.def_impl\n+def _bint_impl(i, *, bd):\n+ return core.BInt(i, bd)\n+\n@bint_p.def_abstract_eval\ndef bint_abstract_eval(_, *, bd: int):\nreturn core.AbstractBInt(bound=bd)\n@@ -4566,7 +4615,7 @@ def _check_shapelike(fun_name, arg_name, obj, non_zero_shape=False):\nif not len(obj): # pylint: disable=g-explicit-length-test\nreturn\nif (config.jax_dynamic_shapes and isinstance(obj, (tuple, list)) and\n- any(isinstance(d, core.Tracer) for d in obj)):\n+ any(isinstance(d, (core.Tracer, core.BInt)) for d in obj)):\nreturn # TODO(mattjj): handle more checks in the dynamic shape case\nobj_arr = np.array(obj)\nif obj_arr.ndim != 1:\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/slicing.py", "new_path": "jax/_src/lax/slicing.py", "diff": "@@ -903,7 +903,7 @@ def _dynamic_slice_batching_rule(batched_args, batch_dims, *, slice_sizes):\ndynamic_slice_p = standard_primitive(\n_dynamic_slice_shape_rule, _dynamic_slice_dtype_rule, 'dynamic_slice',\nweak_type_rule=_argnum_weak_type(0))\n-ad.primitive_jvps[dynamic_slice_p] = _dynamic_slice_jvp # TODO\n+ad.primitive_jvps[dynamic_slice_p] = _dynamic_slice_jvp\nad.primitive_transposes[dynamic_slice_p] = _dynamic_slice_transpose_rule\nbatching.primitive_batchers[dynamic_slice_p] = _dynamic_slice_batching_rule\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -2101,8 +2101,12 @@ def arange(start: core.DimSize, stop: Optional[core.DimSize]=None,\ndtype = _jnp_dtype(dtype)\nif stop is None and step is None:\nif (jax.config.jax_dynamic_shapes and\n+ not isinstance(core.get_aval(start), core.AbstractBInt) and\nnot isinstance(core.get_aval(start), core.ConcreteArray)):\nstart = ceil(start).astype(int) # note using jnp here\n+ elif (isinstance(start, core.BInt) or isinstance(start, core.Tracer) and\n+ isinstance(core.get_aval(start), core.AbstractBInt)):\n+ pass\nelse:\nstart = require(start, msg(\"stop\"))\nstart = np.ceil(start).astype(int)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -122,15 +122,19 @@ def dtype_to_ir_type(dtype: Union[np.dtype, np.generic]) -> ir.Type:\nf\"No dtype_to_ir_type handler for dtype: {dtype}\") from err\nreturn ir_type_factory()\n-def _array_ir_types(aval: core.ShapedArray) -> Sequence[ir.Type]:\n+def _array_ir_types(aval: Union[core.ShapedArray, core.DShapedArray]\n+ ) -> Sequence[ir.Type]:\nreturn (ir.RankedTensorType.get(aval.shape, dtype_to_ir_type(aval.dtype)),)\ndef _dynamic_array_ir_types(aval: core.ShapedArray) -> Sequence[ir.Type]:\n- shape = [d if type(d) is int else -1 for d in aval.shape]\n+ # in the MHLO builder, -1 indicates a '?' axis size\n+ shape = [d if type(d) is int else d.bound if type(d) is core.BInt else -1\n+ for d in aval.shape]\nreturn (ir.RankedTensorType.get(shape, dtype_to_ir_type(aval.dtype)),)\ndef _bint_ir_types(aval: core.AbstractBInt) -> Sequence[ir.Type]:\n- return (ir.RankedTensorType.get((), dtype_to_ir_type(dtypes.dtype('int32'))),)\n+ dtype = dtypes._scalar_type_to_dtype(int)\n+ return (ir.RankedTensorType.get((), dtype_to_ir_type(dtype)),)\nir_type_handlers: Dict[Type[core.AbstractValue],\nCallable[[Any], Sequence[ir.Type]]] = {}\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -2414,7 +2414,7 @@ def pad_jaxpr(jaxpr: Jaxpr, consts: Sequence[Const]\ndef substitute(aval: AbstractValue) -> AbstractValue:\nif isinstance(aval, AbstractBInt):\n- return ShapedArray((), np.dtype('int32'))\n+ return ShapedArray((), dtypes._scalar_type_to_dtype(int))\nelif isinstance(aval, DShapedArray):\nshape = [bounds.get(d, idxs.get(d, d)) for d in aval.shape] # type: ignore\ntyp = ShapedArray if all(type(d) is int for d in shape) else DShapedArray\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -253,12 +253,15 @@ def _canonicalize_python_scalar_dtype(typ, x):\ncanonicalize_dtype_handlers: Dict[Any, Callable] = {}\nfor t in device_array.device_array_types:\n- canonicalize_dtype_handlers[t] = lambda x: x\n+ canonicalize_dtype_handlers[t] = identity\ncanonicalize_dtype_handlers.update(\n(t, _canonicalize_ndarray_dtype) for t in array_types)\ncanonicalize_dtype_handlers.update(\n(t, partial(_canonicalize_python_scalar_dtype, t)) for t in _scalar_types)\n-canonicalize_dtype_handlers[core.Token] = lambda x: x\n+canonicalize_dtype_handlers[core.Token] = identity\n+canonicalize_dtype_handlers[core.PaddedArray] = identity\n+canonicalize_dtype_handlers[core.BInt] = \\\n+ lambda x: core.BInt(_canonicalize_python_scalar_dtype(int, x.val), x.bound)\ndef abstractify(x) -> core.AbstractValue:\ntyp = type(x)\n@@ -277,6 +280,8 @@ def _make_abstract_python_scalar(typ, val):\npytype_aval_mappings: Dict[Any, Callable[[Any], core.AbstractValue]] = {}\nfor t in device_array.device_array_types:\npytype_aval_mappings[t] = operator.attrgetter('aval')\n+pytype_aval_mappings[core.BInt] = lambda x: core.AbstractBInt(x.bound)\n+pytype_aval_mappings[core.PaddedArray] = operator.attrgetter('_aval')\npytype_aval_mappings[core.Token] = lambda _: core.abstract_token\npytype_aval_mappings.update((t, make_shaped_array) for t in array_types)\npytype_aval_mappings.update(\n" } ]
Python
Apache License 2.0
google/jax
[dynamic-shapes] revive basic bounded int machinery, add tests
260,335
07.07.2022 10:30:41
25,200
12a56c3064ca2e6bb7d7cd48478bbcb1db8b9642
[dynamic-shapes] add basic abstracted_axes support to jit(f, ...).lower(...)
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -382,11 +382,13 @@ def _jit(\ndonate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)\nif use_cpp_jit:\n- return _cpp_jit(fun, static_argnums=static_argnums, static_argnames=static_argnames,\n- device=device, backend=backend,\n- donate_argnums=donate_argnums, inline=inline, keep_unused=keep_unused)\n+ return _cpp_jit(\n+ fun, static_argnums=static_argnums, static_argnames=static_argnames,\n+ device=device, backend=backend, donate_argnums=donate_argnums,\n+ inline=inline, keep_unused=keep_unused)\n- return _python_jit(fun, static_argnums=static_argnums, static_argnames=static_argnames,\n+ return _python_jit(\n+ fun, static_argnums=static_argnums, static_argnames=static_argnames,\ndevice=device, backend=backend, donate_argnums=donate_argnums,\ninline=inline, keep_unused=keep_unused, abstracted_axes=abstracted_axes)\n@@ -434,7 +436,7 @@ def _python_jit(\nflat_fun, out_tree = flatten_fun(closed_fun, in_tree)\nfor arg in args_flat:\n_check_arg(arg)\n- if config.jax_dynamic_shapes:\n+ if jax.config.jax_dynamic_shapes:\naxes_specs = (None if abstracted_axes is None else\n_flat_axes_specs(abstracted_axes, *args, **kwargs))\nin_type = pe.infer_lambda_input_type(axes_specs, args_flat)\n@@ -447,7 +449,8 @@ def _python_jit(\nreturn tree_unflatten(out_tree(), out_flat)\nf_jitted.lower = _jit_lower(fun, static_argnums, static_argnames, device,\n- backend, donate_argnums, inline, keep_unused)\n+ backend, donate_argnums, inline, keep_unused,\n+ abstracted_axes)\ndef clear_cache():\ndispatch.xla_callable.evict_function(fun)\n@@ -597,7 +600,8 @@ def _cpp_jit(\nf_jitted = wraps(fun)(cpp_jitted_f)\nf_jitted.lower = _jit_lower(fun, static_argnums, static_argnames, device,\n- backend, donate_argnums, inline, keep_unused)\n+ backend, donate_argnums, inline, keep_unused,\n+ None)\nf_jitted._fun = fun\ntype(f_jitted).clear_cache = _cpp_jit_clear_cache\n@@ -605,7 +609,8 @@ def _cpp_jit(\ndef _jit_lower(fun, static_argnums, static_argnames, device, backend,\n- donate_argnums, inline, keep_unused: bool):\n+ donate_argnums, inline, keep_unused: bool,\n+ abstracted_axes: Optional[PytreeOfAbstractedAxesSpec]):\n\"\"\"Make a ``lower`` method for jitted functions.\"\"\"\n# If the function we returned from ``jit`` were a class instance,\n# this might naturally be a method, with ``fun`` as a ``self`` and\n@@ -613,11 +618,9 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\ndef arg_spec(x):\n# like xla.arg_spec but duck-types on x.shape and x.dtype\n- aval = shaped_abstractify(x)\n- try:\n- return aval, x._device\n- except:\n- return aval, None\n+ aval = None if jax.config.jax_dynamic_shapes else shaped_abstractify(x)\n+ device = getattr(x, '_device', None)\n+ return aval, device\n@api_boundary\ndef lower(*args, **kwargs) -> stages.Lowered:\n@@ -633,19 +636,20 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\nclosed_fun, in_tree, args_flat, donated_invars = _prepare_jit(\nfun, static_argnums, static_argnames, donate_argnums, args, kwargs)\nflat_fun, out_tree = flatten_fun(closed_fun, in_tree)\n- name = flat_fun.__name__\n- arg_specs_and_device = list(unsafe_map(arg_spec, args_flat))\n- # Only do this if the list is not empty\n- if arg_specs_and_device:\n- arg_specs = zip(*arg_specs_and_device)[0]\n+ arg_specs_and_devices = map(arg_spec, args_flat)\n+ if jax.config.jax_dynamic_shapes:\n+ axes_specs = (None if abstracted_axes is None else\n+ _flat_axes_specs(abstracted_axes, *args, **kwargs))\n+ in_type = pe.infer_lambda_input_type(axes_specs, args_flat)\n+ flat_fun = lu.annotate(flat_fun, in_type)\n+ in_avals = [aval for aval, explicit in in_type if explicit]\nelse:\n- arg_specs = []\n- computation = dispatch.lower_xla_callable(flat_fun, device, backend, name,\n- donated_invars, True,\n- keep_unused,\n- *arg_specs_and_device)\n+ in_avals, _ = unzip2(arg_specs_and_devices)\n+ computation = dispatch.lower_xla_callable(\n+ flat_fun, device, backend, flat_fun.__name__, donated_invars, True,\n+ keep_unused, *arg_specs_and_devices)\nreturn stages.Lowered.from_flat_info(\n- computation, in_tree, arg_specs, donate_argnums, out_tree())\n+ computation, in_tree, in_avals, donate_argnums, out_tree())\nreturn lower\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/stages.py", "new_path": "jax/_src/stages.py", "diff": "@@ -35,6 +35,7 @@ from dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple\nfrom typing_extensions import Protocol\n+import jax\nfrom jax import core\nfrom jax import tree_util\nfrom jax.lib import xla_client as xc\n@@ -247,7 +248,7 @@ class XlaLowering(Lowering):\n@dataclass\nclass ArgInfo:\n- aval: core.ShapedArray\n+ aval: core.AbstractValue\ndonated: bool\n@@ -379,6 +380,8 @@ class Compiled(Stage):\nreturn self._executable.runtime_executable()\ndef __call__(self, *args, **kwargs):\n+ if jax.config.jax_dynamic_shapes:\n+ raise NotImplementedError\nif self._no_kwargs and kwargs:\nkws = ', '.join(kwargs.keys())\nraise NotImplementedError(\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -9602,6 +9602,15 @@ class DynamicShapeTest(jtu.JaxTestCase):\nself.assertEqual(y, 6)\nself.assertEqual(count, 2)\n+ def test_lower_abstracted_axes(self):\n+ @partial(jax.jit, abstracted_axes=('n',))\n+ def f(x):\n+ return x.sum()\n+\n+ f_lowered = f.lower(np.arange(3, dtype='int32'))\n+ mhlo = f_lowered.compiler_ir('mhlo')\n+ self.assertIn('tensor<?xi32>', str(mhlo))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[dynamic-shapes] add basic abstracted_axes support to jit(f, ...).lower(...)
260,430
07.07.2022 00:37:10
-28,800
7c707832aa3c750443d8a34385bc94dfadcc0c72
Enable CustomCall implementation on GPU
[ { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -537,6 +537,8 @@ def _inline_host_callback() -> bool:\ndef _use_outfeed(platform: str) -> bool:\n+ if jaxlib.version >= (0, 3, 15):\n+ return platform == \"tpu\" or FLAGS.jax_host_callback_outfeed\nreturn (platform in (\"tpu\", \"gpu\", \"cuda\", \"rocm\") or FLAGS.jax_host_callback_outfeed)\nxops = xla_client._xla.ops\n@@ -1198,6 +1200,8 @@ def _outside_call_lowering(\nreturn results + [next_token, next_itoken]\nmlir.register_lowering(outside_call_p, _outside_call_lowering, platform=\"cpu\")\n+if jaxlib.version >= (0, 3, 15):\n+ mlir.register_lowering(outside_call_p, _outside_call_lowering, platform=\"gpu\")\ndef _outside_call_run_callback(\narrays, device, *,\n" }, { "change_type": "MODIFY", "old_path": "tests/BUILD", "new_path": "tests/BUILD", "diff": "@@ -776,7 +776,6 @@ jax_test(\nsrcs = [\"host_callback_test.py\"],\nargs = [\"--jax_host_callback_outfeed=false\"],\ndisable_backends = [\n- \"gpu\",\n\"tpu\", # On TPU we always use outfeed\n],\nmain = \"host_callback_test.py\",\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -2456,6 +2456,8 @@ class HostCallbackCallTest(jtu.JaxTestCase):\nexpected_exc_txt: str):\n\"\"\"Calls thunk() and checks for expected exceptions.\n\"\"\"\n+ if not FLAGS.jax_host_callback_outfeed:\n+ raise SkipTest(\"TODO: implement error handling for customcall\")\nif jtu.device_under_test() == \"cpu\":\n# On CPU the runtime crashes, and the tests are all aborted\nraise SkipTest(\"TODO: CPU runtime crashes on unexpected infeed\")\n" } ]
Python
Apache License 2.0
google/jax
Enable CustomCall implementation on GPU
260,631
08.07.2022 13:33:14
25,200
1bb1fe0658cbce1de055826f800ffd78cf80f6e7
Remove workaround for rank-0 zarr chunk layout bug in TensorStore This has now been fixed in TensorStore.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/gda_serialization/serialization.py", "new_path": "jax/experimental/gda_serialization/serialization.py", "diff": "@@ -171,8 +171,6 @@ def run_serialization(gdas, tensorstore_specs):\ndef estimate_read_memory_footprint(t: ts.TensorStore) -> int:\nrank = t.rank\nnum_bytes = t.dtype.numpy_dtype.itemsize\n- if rank == 0:\n- return num_bytes\nchunk_template = t.chunk_layout.read_chunk_template\norigin = t.domain.origin\nshape = t.domain.shape\n" } ]
Python
Apache License 2.0
google/jax
Remove workaround for rank-0 zarr chunk layout bug in TensorStore This has now been fixed in TensorStore. PiperOrigin-RevId: 459824051
260,510
07.07.2022 19:37:05
25,200
bff71b2c4f166da8605b84b53016d0c6ef38cb31
Add loop-invariant residual optimization for `for`
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "@@ -673,9 +673,39 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\n# to output residual values (none of them should be `Ref`s). We'll need to\n# convert the output residual values into `Ref`s that are initially empty\n# `Ref`s that are written to at the end of the jaxpr.\n- # TODO(sharadmv,mattjj): detect which residuals are loop-invariant\n+\n+ # # Loop-invariant residual optimization\n+ # Here we are interested in finding out which of the residuals are *not*\n+ # dependent on the loop index. If a residual is not dependent on the loop\n+ # index, we don't need add an extra loop dimension we're reading from when we\n+ # convert it from an output into a write.\n+\n+ # In order to detect which residuals are loop-invariant, we need to run a\n+ # fixpoint. This is because the residual could be dependent on a `Ref` that\n+ # changes each iteration of the loop so we need to first detect which `Ref`s\n+ # are loop-varying. We can do this by discharging the state from the jaxpr and\n+ # running partial_eval with initially only the loop-index being loop-varying.\n+ # The fixpoint will eventually propagate the loop-varying-ness over the\n+ # inputs/outputs and we will converge.\n+ loop_var_res = [False] * len(jaxpr_known_resout.outvars)\n+ loop_var_refs = [False] * (len(jaxpr_known_resout.invars) - 1)\n+ discharged_jaxpr_known_resout = core.ClosedJaxpr(\n+ *discharge_state(jaxpr_known_resout, ()))\n+ for _ in range(len(discharged_jaxpr_known_resout.jaxpr.invars)):\n+ (_, _, loop_var_outputs, _) = pe.partial_eval_jaxpr_nounits(\n+ discharged_jaxpr_known_resout, [True] + loop_var_refs, False)\n+ loop_var_res, loop_var_refs_ = split_list(\n+ loop_var_outputs, [len(loop_var_res)])\n+ if loop_var_refs == loop_var_refs_:\n+ break\n+ loop_var_refs = map(operator.or_, loop_var_refs, loop_var_refs_)\n+ # Now that the fixpoint is complete, we know which residuals are\n+ # loop-invariant.\n+ loop_invar_res = map(operator.not_, loop_var_res)\n+\njaxpr_known, res_avals = _convert_outputs_to_writes(nsteps,\n- jaxpr_known_resout)\n+ jaxpr_known_resout,\n+ loop_invar_res)\n# We now run the known jaxpr to obtain our residual values.\nknown_tracers, _ = partition_list(in_unknowns, tracers)\nknown_vals = [t.pval.get_known() for t in known_tracers]\n@@ -699,7 +729,8 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\n# To make it compatible with `for`, we need to convert those residual values\n# into `Ref`s.\njaxpr_unknown = _convert_inputs_to_reads(nsteps, len(res_avals),\n- jaxpr_unknown_resin)\n+ jaxpr_unknown_resin,\n+ loop_invar_res)\n# Since not all inputs are used in jaxpr_unknown, we filter the input tracers\n# down using the output of `dce_jaxpr`.\n_, used_tracers = partition_list(used_refs, tracers)\n@@ -725,8 +756,8 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\npe.custom_partial_eval_rules[for_p] = _for_partial_eval\ndef _convert_outputs_to_writes(\n- nsteps: int, jaxpr: core.Jaxpr) -> Tuple[core.Jaxpr,\n- List[core.ShapedArray]]:\n+ nsteps: int, jaxpr: core.Jaxpr, loop_invar_res: Sequence[bool]\n+ ) -> Tuple[core.Jaxpr, List[core.ShapedArray]]:\nassert not jaxpr.constvars, \"Jaxpr shouldn't have constvars.\"\nin_avals = [v.aval for v in jaxpr.invars] # [i, *orig_ref_avals]\n@@ -736,12 +767,17 @@ def _convert_outputs_to_writes(\n# refs.\norig_refs, residual_refs = split_list(refs, [len(in_avals) - 1])\nresidual_vals = core.eval_jaxpr(jaxpr, (), i, *orig_refs)\n- for res_ref, res_val in zip(residual_refs, residual_vals):\n- # TODO(sharadmv): loop-invariant residuals should not be an indexed write\n+ for res_ref, res_val, loop_invar in zip(residual_refs, residual_vals,\n+ loop_invar_res):\n+ if loop_invar:\n+ res_ref[()] = res_val\n+ else:\nres_ref[i] = res_val\nreturn []\n- res_ref_avals = [ShapedArrayRef((nsteps, *v.aval.shape), v.aval.dtype) # pytype: disable=attribute-error\n- for v in jaxpr.outvars]\n+ res_ref_avals = [ShapedArrayRef(v.aval.shape, v.aval.dtype) # pytype: disable=attribute-error\n+ if loop_invar else\n+ ShapedArrayRef((nsteps, *v.aval.shape), v.aval.dtype)\n+ for v, loop_invar in zip(jaxpr.outvars, loop_invar_res)]\njaxpr, _, consts = pe.trace_to_jaxpr_dynamic(\neval_jaxpr, [*in_avals, *res_ref_avals])\nassert not consts\n@@ -749,21 +785,22 @@ def _convert_outputs_to_writes(\ndef _convert_inputs_to_reads(\nnsteps: int, num_res: int, jaxpr: core.Jaxpr,\n- ) -> core.Jaxpr:\n+ loop_invar_res: Sequence[bool]) -> core.Jaxpr:\nassert not jaxpr.constvars, \"Jaxpr should not have constvars\"\n@lu.wrap_init\ndef eval_jaxpr(i, *refs):\nresidual_refs, orig_refs = split_list(refs, [num_res])\n- # TODO(sharadmv): don't do an indexed read for loop-invariant residuals\n- residual_vals = [r[i] for r in residual_refs]\n+ residual_vals = [r[()] if loop_invar else r[i] for r, loop_invar\n+ in zip(residual_refs, loop_invar_res)]\n() = core.eval_jaxpr(jaxpr, (), *residual_vals, i, *orig_refs)\nreturn []\nres_val_avals, (i_aval,), orig_ref_avals = \\\nsplit_list([v.aval for v in jaxpr.invars], [num_res, 1])\n- res_ref_avals = [ShapedArrayRef((nsteps, *aval.shape), aval.dtype) # pytype: disable=attribute-error\n- for aval in res_val_avals]\n+ res_ref_avals = [ShapedArrayRef(aval.shape, aval.dtype) if loop_invar else\n+ ShapedArrayRef((nsteps, *aval.shape), aval.dtype) # pytype: disable=attribute-error\n+ for aval, loop_invar in zip(res_val_avals, loop_invar_res)]\njaxpr, _, () = pe.trace_to_jaxpr_dynamic(\neval_jaxpr, [i_aval, *res_ref_avals, *orig_ref_avals])\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -3030,5 +3030,20 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nself.assertAllClose(ans, ans_discharged, check_dtypes=True, rtol=tol, atol=tol)\nself.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\n+ def test_for_loop_invar(self):\n+ def f(x):\n+ s = jnp.ones((2, 32), x.dtype)\n+ def body(i, refs):\n+ x_ref, y_ref = refs\n+ y_ref[i] = s * x_ref[i] * jnp.cos(s)\n+ # We should save `s` and `jnp.cos(s)` as residuals and not broadcast\n+ # them.\n+ return for_loop.for_loop(x.shape[0], body, (x, jnp.zeros_like(x)))\n+ _, f_vjp = jax.linearize(f, jnp.ones((5, 2, 32)))\n+ jaxpr = jax.make_jaxpr(f_vjp)(jnp.ones((5, 2, 32)))\n+ consts = [v.aval for v in jaxpr.jaxpr.constvars\n+ if v.aval.shape == (2, 32)]\n+ self.assertLen(consts, 2)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add loop-invariant residual optimization for `for`
260,335
07.07.2022 16:44:00
25,200
5b82ba787c5750260ec831561c4083d11123bc08
[dynamic-shapes] start basic vmap compatibility
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -1575,24 +1575,25 @@ def _mapped_axis_size(tree, vals, dims, name, *, kws=False):\nf\"containing an array, got empty *args={args} and **kwargs={kwargs}\"\n)\n- def _get_axis_size(name: str, shape: Tuple[int, ...], axis: int):\n+ def _get_axis_size(name: str, shape: Tuple[core.AxisSize, ...], axis: int\n+ ) -> core.AxisSize:\ntry:\nreturn shape[axis]\nexcept (IndexError, TypeError) as e:\nmin_rank = axis + 1 if axis >= 0 else -axis\n- raise ValueError(f\"{name} was requested to map its argument along axis {axis}, \"\n+ raise ValueError(\n+ f\"{name} was requested to map its argument along axis {axis}, \"\nf\"which implies that its rank should be at least {min_rank}, \"\nf\"but is only {len(shape)} (its shape is {shape})\") from e\n- mapped_axis_sizes = {_get_axis_size(name, np.shape(x), d)\n- for x, d in zip(vals, dims)\n- if d is not None}\n- try:\n- size, = mapped_axis_sizes\n- return size\n- except ValueError as e:\n- if not mapped_axis_sizes:\n- raise ValueError(f\"{name} must have at least one non-None value in in_axes\") from e\n+ axis_sizes = core.dedup_referents(\n+ _get_axis_size(name, np.shape(x), d) for x, d in zip(vals, dims)\n+ if d is not None)\n+ if len(axis_sizes) == 1:\n+ return axis_sizes[0]\n+ if not axis_sizes:\n+ msg = f\"{name} must have at least one non-None value in in_axes\"\n+ raise ValueError(msg)\nmsg = f\"{name} got inconsistent sizes for array axes to be mapped:\\n\" + \"{}\"\n# we switch the error message based on whether args is a tuple of arrays,\n# in which case we can produce an error message based on argument indices,\n@@ -1628,6 +1629,7 @@ def _mapped_axis_size(tree, vals, dims, name, *, kws=False):\nsizes = tree_unflatten(tree, sizes)\nraise ValueError(msg.format(f\"the tree of axis sizes is:\\n{sizes}\")) from None\n+\ndef pmap(\nfun: Callable,\naxis_name: Optional[AxisName] = None,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/util.py", "new_path": "jax/_src/util.py", "diff": "@@ -21,7 +21,7 @@ import operator\nimport types\nimport threading\nfrom typing import (Any, Callable, Dict, Iterable, List, Tuple, Generic,\n- TypeVar, Set, Iterator, Sequence)\n+ TypeVar, Set, Iterator, Sequence, Optional)\nimport weakref\nfrom absl import logging\n@@ -546,3 +546,18 @@ class OrderedSet(Generic[T]):\ndef __contains__(self, elt: T) -> bool:\nreturn elt in self.elts_set\n+\n+\n+class HashableWrapper:\n+ x: Any\n+ hash: Optional[int]\n+ def __init__(self, x):\n+ self.x = x\n+ try: self.hash = hash(x)\n+ except: self.hash = None\n+ def __hash__(self):\n+ return self.hash if self.hash is not None else id(self.x)\n+ def __eq__(self, other):\n+ if not isinstance(other, HashableWrapper):\n+ return False\n+ return self.x == other.x if self.hash is not None else self.x is other.x\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -43,7 +43,7 @@ from jax import linear_util as lu\nfrom jax._src import source_info_util\nfrom jax._src.util import (safe_zip, safe_map, curry, prod, tuple_insert,\ntuple_delete, as_hashable_function,\n- HashableFunction, weakref_lru_cache)\n+ HashableFunction, HashableWrapper, weakref_lru_cache)\nimport jax._src.pretty_printer as pp\nfrom jax._src import lib\nfrom jax._src.lib import jax_jit\n@@ -1039,6 +1039,9 @@ def get_referent(x: Any) -> Any:\ndef same_referent(x: Any, y: Any) -> bool:\nreturn get_referent(x) is get_referent(y)\n+def dedup_referents(itr: Iterable[Any]) -> List[Any]:\n+ return list({HashableWrapper(get_referent(x)):x for x in itr}.values())\n+\n# -------------------- abstract values --------------------\n@@ -1405,7 +1408,7 @@ def primal_dtype_to_tangent_dtype(primal_dtype):\n# Tracer (while tracing), Var (when used as jaxpr type annotations), or\n# DBIdx/InDBIdx/OutDBIdx (when used in InputType or OutputType). We could reduce\n# this polymorphism if it seems cleaner, though it's kind of convenient!\n-AxisSize = Any\n+AxisSize = Union[int, 'BInt', Tracer, Var, DBIdx, InDBIdx, OutDBIdx]\nclass DShapedArray(UnshapedArray):\n__slots__ = ['shape']\n@@ -2070,16 +2073,16 @@ def process_env_traces_map(primitive: MapPrimitive, level: int,\nyield outs, (tuple(todo), tuple(out_axes_transforms))\n-def mapped_aval(size: int, axis: Optional[int], aval: AbstractValue\n- ) -> AbstractValue:\n+def mapped_aval(size: AxisSize, axis: Optional[int],\n+ aval: AbstractValue) -> AbstractValue:\nhandler, _ = aval_mapping_handlers.get(type(aval), (None, None))\nif handler is not None:\nreturn handler(size, axis, aval)\nelse:\nraise TypeError(f\"no mapping handler for {aval} of type {type(aval)}\")\n-def unmapped_aval(size: int, axis_name, axis: Optional[int], aval: AbstractValue\n- ) -> AbstractValue:\n+def unmapped_aval(size: AxisSize, axis_name, axis: Optional[int],\n+ aval: AbstractValue) -> AbstractValue:\n_, handler = aval_mapping_handlers.get(type(aval), (None, None))\nif handler is not None:\nreturn handler(size, axis_name, axis, aval)\n@@ -2103,19 +2106,18 @@ def _unmap_shaped_array(size: int, axis_name, axis: Optional[int],\nreturn ShapedArray(tuple_insert(aval.shape, axis, size), aval.dtype,\nnamed_shape=named_shape, weak_type=aval.weak_type)\n-def _map_dshaped_array(size: Union[int, Tracer], axis: Optional[int],\n- aval: ShapedArray) -> ShapedArray:\n- assert False # TODO(mattjj, dougalm)\n+def _map_dshaped_array(size: AxisSize, axis: Optional[int],\n+ aval: DShapedArray) -> DShapedArray:\n+ if axis is None: return aval\n+ return DShapedArray(tuple_delete(aval.shape, axis), aval.dtype,\n+ aval.weak_type)\ndef _unmap_dshaped_array(\n- size: Union[int, Tracer], axis_name, axis: Optional[int],\n+ size: AxisSize, axis_name, axis: Optional[int],\naval: DShapedArray) -> DShapedArray:\n- if isinstance(size, int):\nif axis is None: return aval\nreturn DShapedArray(tuple_insert(aval.shape, axis, size), aval.dtype,\nweak_type=aval.weak_type)\n- else:\n- assert False # TODO(mattjj, dougalm)\nAvalMapHandlerPair = Tuple[Callable, Callable]\naval_mapping_handlers: Dict[Type, AvalMapHandlerPair] = {\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -36,15 +36,18 @@ from jax.interpreters import partial_eval as pe\nmap = safe_map\ndef _update_annotation(\n- f: lu.WrappedFun,\n- orig_type: Optional[Tuple[Tuple[core.AbstractValue, bool], ...]],\n- axis_size: int, axis_name: core.AxisName, in_dims: Sequence[Optional[int]]\n- ) -> lu.WrappedFun:\n- if orig_type is None:\n- return f\n- batched_in_type = [(core.unmapped_aval(axis_size, axis_name, dim, aval), keep)\n+ f: lu.WrappedFun, orig_type: Optional[core.InputType],\n+ axis_size: core.AxisSize, axis_name: core.AxisName,\n+ in_dims: Sequence[Optional[int]]) -> lu.WrappedFun:\n+ if orig_type is None: return f\n+ if isinstance(axis_size, core.Tracer):\n+ in_type_ = [(core.unmapped_aval(core.DBIdx(0), axis_name, dim, aval), keep)\n+ for dim, (aval, keep) in zip(in_dims, orig_type)]\n+ in_type = [(axis_size.aval, False), *in_type_]\n+ else:\n+ in_type = [(core.unmapped_aval(axis_size, axis_name, dim, aval), keep)\nfor dim, (aval, keep) in zip(in_dims, orig_type)]\n- return lu.annotate(f, tuple(batched_in_type))\n+ return lu.annotate(f, tuple(in_type))\n### vmappable typeclass\n@@ -187,7 +190,8 @@ class BatchTrace(Trace):\nif self.axis_name is core.no_axis_name:\n# If axis name is `no_axis_name` we can't find it via `core.axis_name` so\n# we reconstruct it from the information we have available\n- axis_size, = {x.shape[d] for x, d in zip(vals, dims) if d is not not_mapped}\n+ axis_size, = core.dedup_referents(x.shape[d] for x, d in zip(vals, dims)\n+ if d is not not_mapped)\nreturn core.AxisEnvFrame(self.axis_name, axis_size, self.main)\nreturn core.axis_frame(self.axis_name)\n@@ -223,8 +227,9 @@ class BatchTrace(Trace):\nreturn call_primitive.bind(f, *vals, **params)\nelse:\nf_, dims_out = batch_subtrace(f, self.main, dims)\n- ax_size, = {x.shape[d] for x, d in zip(vals, dims) if d is not not_mapped}\n- f_ = _update_annotation(f_, f.in_type, ax_size, self.axis_name, dims)\n+ axis_size, = core.dedup_referents(x.shape[d] for x, d in zip(vals, dims)\n+ if d is not not_mapped)\n+ f_ = _update_annotation(f_, f.in_type, axis_size, self.axis_name, dims)\nvals_out = call_primitive.bind(f_, *vals, **params)\nsrc = source_info_util.current()\nreturn [BatchTracer(self, v, d, src) for v, d in zip(vals_out, dims_out())]\n@@ -610,12 +615,14 @@ def broadcast_batcher(prim, args, dims, **params):\neither an int indicating the batch dimension, or else `not_mapped`\nindicating no batching.\n\"\"\"\n- shapes = {(x.shape, d) for x, d in zip(args, dims) if np.ndim(x)}\n- if len(shapes) == 1:\n+ assert len(args) > 1\n+ shape, dim = next((x.shape, d) for x, d in zip(args, dims)\n+ if d is not not_mapped)\n+ if all(core.symbolic_equal_shape(shape, x.shape) and d == dim\n+ for x, d in zip(args, dims) if np.ndim(x)):\n# if there's only agreeing batch dims and scalars, just call the primitive\n- d = next(d for d in dims if d is not not_mapped)\nout = prim.bind(*args, **params)\n- return (out, (d,) * len(out)) if prim.multiple_results else (out, d)\n+ return (out, (dim,) * len(out)) if prim.multiple_results else (out, dim)\nelse:\n# We pass size of 1 here because (1) at least one argument has a real batch\n# dimension and (2) all unmapped axes can have a singleton axis inserted and\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -9611,6 +9611,23 @@ class DynamicShapeTest(jtu.JaxTestCase):\nmhlo = f_lowered.compiler_ir('mhlo')\nself.assertIn('tensor<?xi32>', str(mhlo))\n+ def test_vmap_abstracted_axis(self):\n+ def foo(x, y):\n+ z = jax.vmap(jnp.sin)(x) * y\n+ return jax.vmap(jnp.add)(x, z)\n+\n+ x = jnp.arange(3.)\n+ jaxpr = jax.make_jaxpr(foo, abstracted_axes=('n',))(x, x).jaxpr\n+ self.assertLen(jaxpr.invars, 3)\n+ a, b, c = jaxpr.invars\n+ self.assertEqual(a.aval.shape, ())\n+ self.assertEqual(b.aval.shape, (a,))\n+ self.assertEqual(c.aval.shape, (a,))\n+ self.assertLen(jaxpr.eqns, 3)\n+ self.assertLen(jaxpr.outvars, 1)\n+ f, = jaxpr.outvars\n+ self.assertEqual(f.aval.shape, (a,))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[dynamic-shapes] start basic vmap compatibility
260,510
10.07.2022 13:04:44
25,200
b666f665ece2b91e7c07c65d27cf485a779638b6
Rollback of HCB GPU custom call due to internal failures
[ { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -537,8 +537,6 @@ def _inline_host_callback() -> bool:\ndef _use_outfeed(platform: str) -> bool:\n- if jaxlib.version >= (0, 3, 15):\n- return platform == \"tpu\" or FLAGS.jax_host_callback_outfeed\nreturn (platform in (\"tpu\", \"gpu\", \"cuda\", \"rocm\") or FLAGS.jax_host_callback_outfeed)\nxops = xla_client._xla.ops\n@@ -1200,8 +1198,6 @@ def _outside_call_lowering(\nreturn results + [next_token, next_itoken]\nmlir.register_lowering(outside_call_p, _outside_call_lowering, platform=\"cpu\")\n-if jaxlib.version >= (0, 3, 15):\n- mlir.register_lowering(outside_call_p, _outside_call_lowering, platform=\"gpu\")\ndef _outside_call_run_callback(\narrays, device, *,\n" }, { "change_type": "MODIFY", "old_path": "tests/BUILD", "new_path": "tests/BUILD", "diff": "@@ -783,6 +783,7 @@ jax_test(\nsrcs = [\"host_callback_test.py\"],\nargs = [\"--jax_host_callback_outfeed=false\"],\ndisable_backends = [\n+ \"gpu\",\n\"tpu\", # On TPU we always use outfeed\n],\nmain = \"host_callback_test.py\",\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -2456,8 +2456,6 @@ class HostCallbackCallTest(jtu.JaxTestCase):\nexpected_exc_txt: str):\n\"\"\"Calls thunk() and checks for expected exceptions.\n\"\"\"\n- if not FLAGS.jax_host_callback_outfeed:\n- raise SkipTest(\"TODO: implement error handling for customcall\")\nif jtu.device_under_test() == \"cpu\":\n# On CPU the runtime crashes, and the tests are all aborted\nraise SkipTest(\"TODO: CPU runtime crashes on unexpected infeed\")\n" } ]
Python
Apache License 2.0
google/jax
Rollback of HCB GPU custom call due to internal failures PiperOrigin-RevId: 460079787
260,510
09.07.2022 11:20:16
25,200
9d610e2de6891f134ddfdc2bb65d3b19ac0b6ffe
Add loop invariant residual fixpoint test
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "@@ -216,7 +216,7 @@ pp_ref = partial(pp.color, intensity=pp.Intensity.NORMAL,\nforeground=pp.Color.GREEN)\ndef _get_pp_rule(eqn, context, settings):\n- # Pretty prints `a = get x i` as `x[i] <- a`\n+ # Pretty prints `a = get x i` as `a <- x[i]`\ny, = eqn.outvars\nx, *idx = eqn.invars\nidx = ','.join(core.pp_var(i, context) for i in idx)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -3045,5 +3045,27 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nif v.aval.shape == (2, 32)]\nself.assertLen(consts, 2)\n+ def test_for_loop_fixpoint_correctly_identifies_loop_varying_residuals(self):\n+\n+ def body(i, refs):\n+ a_ref, b_ref, c_ref = refs\n+ a = a_ref[i]\n+ b = b_ref[()]\n+ x = jnp.sin(a)\n+ b_ref[()] = jnp.sin(b * x)\n+ c_ref[i] = x * b\n+ def f(a, b):\n+ c = jnp.zeros_like(a)\n+ _, b, c = for_loop.for_loop(5, body, (a, b, c))\n+ return b, c\n+ a = jnp.arange(5.) + 1.\n+ b = 1.\n+ _, f_lin = jax.linearize(f, a, b)\n+ expected_tangents = f_lin(a, b)\n+ _, actual_tangents = jax.jvp(f, (a, b), (a, b))\n+ np.testing.assert_allclose(actual_tangents[0], expected_tangents[0])\n+ np.testing.assert_allclose(actual_tangents[1], expected_tangents[1])\n+\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add loop invariant residual fixpoint test
260,310
11.07.2022 17:11:24
25,200
153b6aeb78c86d3ce55cfb71f1af93ee1ef26c85
Fix limitations-of-call_tf github link typo. call_tf misspell as "call-tf" on multiple places.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/call_tf.py", "new_path": "jax/experimental/jax2tf/call_tf.py", "diff": "@@ -104,7 +104,7 @@ def call_tf(callable_tf: Callable) -> Callable:\nif any(not core.is_constant_dim(d) for d in a_jax.shape):\nmsg = (\"call_tf cannot be applied to shape-polymorphic arguments. \"\nf\"Found argument shape: {a_jax.shape}. \"\n- \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion.\")\n+ \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call_tf for a discussion.\")\nraise ValueError(msg)\nreturn tf.TensorSpec(a_jax.shape, a_tf_dtype)\n@@ -299,7 +299,7 @@ def _code_generator_and_avals(\nmsg = (\n\"call_tf works best with a TensorFlow function that does not capture \"\n\"variables or tensors from the context. \"\n- \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion. \"\n+ \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call_tf for a discussion. \"\nf\"The following captures were found {concrete_function_flat_tf.captured_inputs}\")\nlogging.warning(msg)\nfor inp in concrete_function_flat_tf.captured_inputs:\n@@ -341,7 +341,7 @@ def _code_generator_and_avals(\nmsg = (\"Error compiling TensorFlow function. call_tf can used \" +\n\"in a staged context (under jax.jit, lax.scan, etc.) only with \" +\n\"compileable functions with static output shapes. \" +\n- \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion.\")\n+ \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call_tf for a discussion.\")\nraise ValueError(msg) from e\nxla_comp = xla_client.XlaComputation(func_tf_hlo)\n@@ -365,7 +365,7 @@ def _code_generator_and_avals(\nf\"{expected_parameter_avals}. Perhaps the TensorFlow function \" +\n\"has shape-influencing inputs, and thus needs to be recompiled \" +\n\"for each value of some inputs. \" +\n- \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion.\")\n+ \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call_tf for a discussion.\")\nraise ValueError(msg)\n# Canonicalize the results; e.g., makes them x32 if JAX is in 32-bit mode\n@@ -375,7 +375,7 @@ def _code_generator_and_avals(\nf\"{res_shape}. call_tf can used \" +\n\"in a staged context (under jax.jit, lax.scan, etc.) only with \" +\n\"compileable functions with static output shapes. \" +\n- \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion.\")\n+ \"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call_tf for a discussion.\")\nraise ValueError(msg)\nres_dtype = res_shape.numpy_dtype()\n" } ]
Python
Apache License 2.0
google/jax
Fix limitations-of-call_tf github link typo. call_tf misspell as "call-tf" on multiple places. PiperOrigin-RevId: 460335218
260,411
12.07.2022 12:40:55
-10,800
3d9c8fbe6f06821a55bfcc1364c6ba27aeb3f68a
[dynamic-shapes] Ensure that the axis_size_env is passed to sub lowering contexts
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3977,13 +3977,9 @@ def _sort_lower(ctx, *operands, dimension, is_stable, num_keys):\nwith ir.InsertionPoint(comparator):\nlower_comparator = mlir.lower_fun(partial(_sort_lt_comparator),\nmultiple_results=False)\n- sub_ctx = mlir.LoweringRuleContext(\n- module_context = ctx.module_context,\n- primitive=None,\n+ sub_ctx = ctx.replace(primitive=None,\navals_in=util.flatten(zip(scalar_avals, scalar_avals)),\n- avals_out=[core.ShapedArray((), np.bool_)],\n- tokens_in=ctx.tokens_in,\n- tokens_out=ctx.tokens_out)\n+ avals_out=[core.ShapedArray((), np.bool_)])\nout = lower_comparator(sub_ctx, *[[a] for a in comparator.arguments],\nnum_keys=num_keys)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/linalg.py", "new_path": "jax/_src/lax/linalg.py", "diff": "@@ -1199,12 +1199,7 @@ def _lu_cpu_gpu_lowering(getrf_impl, ctx, operand):\nir.IntegerType.get_signless(1)),\nok, mlir.dense_int_elements(range(len(batch_dims)))).result,\nlu, _nan_like_mhlo(out_aval))\n- sub_ctx = mlir.LoweringRuleContext(module_context=ctx.module_context,\n- primitive=None,\n- avals_in=[pivot_aval],\n- avals_out=[perm_aval],\n- tokens_in=ctx.tokens_in,\n- tokens_out=ctx.tokens_out)\n+ sub_ctx = ctx.replace(primitive=None, avals_in=[pivot_aval], avals_out=[perm_aval])\nperm_fn = mlir.lower_fun(lambda x: lu_pivots_to_permutation(x, m),\nmultiple_results=False)\nperm, = perm_fn(sub_ctx, pivot)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -704,13 +704,7 @@ def _allreduce_lowering(prim, pos_fn, ctx, *args, axes, axis_index_groups):\naval_out = aval.update(\nshape=np.delete(np.array(aval.shape, dtype=np.int64),\npositional_axes))\n- reducer_ctx = mlir.LoweringRuleContext(\n- module_context=ctx.module_context,\n- primitive=None,\n- avals_in=[aval],\n- avals_out=[aval_out],\n- tokens_in=ctx.tokens_in,\n- tokens_out=ctx.tokens_out)\n+ reducer_ctx = ctx.replace(primitive=None, avals_in=[aval], avals_out=[aval_out])\nout, = reducer(reducer_ctx, arg, axes=tuple(positional_axes))[0]\nreturn out\nargs = map(_positional_reduce, ctx.avals_in, args)\n@@ -728,10 +722,8 @@ def _allreduce_lowering(prim, pos_fn, ctx, *args, axes, axis_index_groups):\nreducer_block = op.regions[0].blocks.append(scalar_type, scalar_type)\nwith ir.InsertionPoint(reducer_block):\nlower_reducer = mlir.lower_fun(prim.bind, multiple_results=False)\n- reducer_ctx = mlir.LoweringRuleContext(\n- module_context = ctx.module_context,\n- primitive=None, avals_in=[scalar_aval] * 2, avals_out=[scalar_aval],\n- tokens_in=ctx.tokens_in, tokens_out=ctx.tokens_out)\n+ reducer_ctx = ctx.replace(primitive=None,\n+ avals_in=[scalar_aval] * 2, avals_out=[scalar_aval])\nout_nodes = lower_reducer(\nreducer_ctx, *([a] for a in reducer_block.arguments))\nmhlo.ReturnOp(util.flatten(out_nodes))\n@@ -1284,10 +1276,9 @@ def _reduce_scatter_lowering(prim, reducer, ctx, x,\nreducer_block = op.regions[0].blocks.append(scalar_type, scalar_type)\nwith ir.InsertionPoint(reducer_block):\nlower_reducer = mlir.lower_fun(prim.bind, multiple_results=False)\n- reducer_ctx = mlir.LoweringRuleContext(\n- module_context = ctx.module_context,\n- primitive=None, avals_in=[scalar_aval] * 2, avals_out=[scalar_aval],\n- tokens_in=ctx.tokens_in, tokens_out=ctx.tokens_out)\n+ reducer_ctx = ctx.replace(primitive=None,\n+ avals_in=[scalar_aval] * 2,\n+ avals_out=[scalar_aval])\nout_nodes = lower_reducer(\nreducer_ctx, *([a] for a in reducer_block.arguments))\nmhlo.ReturnOp(util.flatten(out_nodes))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1372,11 +1372,8 @@ def _xmap_lowering_rule_replica(ctx, *in_nodes,\nmlir.lower_fun(partial(_tile, in_axes=arg_in_axes,\naxis_sizes=local_mesh_shape),\nmultiple_results=False)(\n- mlir.LoweringRuleContext(module_context=ctx.module_context,\n- primitive=None,\n- avals_in=[aval], avals_out=None,\n- tokens_in=ctx.tokens_in,\n- tokens_out=ctx.tokens_out),\n+ ctx.replace(primitive=None,\n+ avals_in=[aval], avals_out=None),\nin_node)[0]\nfor v, aval, in_node, arg_in_axes\nin zip(call_jaxpr.invars, ctx.avals_in, in_nodes, mesh_in_axes))\n@@ -1398,12 +1395,9 @@ def _xmap_lowering_rule_replica(ctx, *in_nodes,\npartial(_untile, out_axes=ans_out_axes, axis_sizes=local_mesh_shape,\nplatform=ctx.module_context.platform),\nmultiple_results=False)(\n- mlir.LoweringRuleContext(module_context=ctx.module_context,\n- primitive=None,\n+ ctx.replace(primitive=None,\navals_in=[vectorized_outvar.aval],\n- avals_out=None,\n- tokens_in=ctx.tokens_in,\n- tokens_out=ctx.tokens_out), tiled_out)[0]\n+ avals_out=None), tiled_out)[0]\nfor v, vectorized_outvar, tiled_out, ans_out_axes\nin zip(call_jaxpr.outvars, vectorized_jaxpr.outvars, tiled_outs,\nmesh_out_axes)]\n" } ]
Python
Apache License 2.0
google/jax
[dynamic-shapes] Ensure that the axis_size_env is passed to sub lowering contexts
260,510
12.07.2022 17:44:37
25,200
7f8378e0dbcbf8c154944bec7a0527861bc6dee7
Refactor debugger to have a registry
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugger/__init__.py", "new_path": "jax/_src/debugger/__init__.py", "diff": "# 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-from jax._src.debugger.cli_debugger import breakpoint\n+from jax._src.debugger.core import breakpoint\n+from jax._src.debugger import cli_debugger\n+\n+del cli_debugger # For registration only\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/cli_debugger.py", "new_path": "jax/_src/debugger/cli_debugger.py", "diff": "from __future__ import annotations\nimport cmd\n-import dataclasses\n-import inspect\nimport sys\n-import threading\nimport traceback\n-from typing import Any, Callable, Dict, IO, List, Optional\n-\n-import numpy as np\n-from jax import core\n-from jax import tree_util\n-from jax._src import debugging\n-from jax._src import traceback_util\n-from jax._src import util\n-import jax.numpy as jnp\n-\n-\n-@tree_util.register_pytree_node_class\n-@dataclasses.dataclass(frozen=True)\n-class DebuggerFrame:\n- \"\"\"Encapsulates Python frame information.\"\"\"\n- filename: str\n- locals: Dict[str, Any]\n- code_context: str\n- source: List[str]\n- lineno: int\n- offset: Optional[int]\n-\n- def tree_flatten(self):\n- flat_locals, locals_tree = tree_util.tree_flatten(self.locals)\n- is_valid = [\n- isinstance(l, (core.Tracer, jnp.ndarray, np.ndarray))\n- for l in flat_locals\n- ]\n- invalid_locals, valid_locals = util.partition_list(is_valid, flat_locals)\n- return valid_locals, (is_valid, invalid_locals, locals_tree, self.filename,\n- self.code_context, self.source, self.lineno,\n- self.offset)\n-\n- @classmethod\n- def tree_unflatten(cls, info, valid_locals):\n- (is_valid, invalid_locals, locals_tree, filename, code_context, source,\n- lineno, offset) = info\n- flat_locals = util.merge_lists(is_valid, invalid_locals, valid_locals)\n- locals_ = tree_util.tree_unflatten(locals_tree, flat_locals)\n- return DebuggerFrame(filename, locals_, code_context, source, lineno,\n- offset)\n-\n- @classmethod\n- def from_frameinfo(cls, frame_info) -> DebuggerFrame:\n- try:\n- _, start = inspect.getsourcelines(frame_info.frame)\n- source = inspect.getsource(frame_info.frame).split('\\n')\n- offset = frame_info.lineno - start\n- except OSError:\n- source = []\n- offset = None\n- return DebuggerFrame(\n- filename=frame_info.filename,\n- locals=frame_info.frame.f_locals,\n- code_context=frame_info.code_context,\n- source=source,\n- lineno=frame_info.lineno,\n- offset=offset)\n-\n-\n-debug_lock = threading.Lock()\n-\n-\n-def breakpoint(*, ordered: bool = False, **kwargs): # pylint: disable=redefined-builtin\n- \"\"\"Enters a breakpoint at a point in a program.\"\"\"\n- frame_infos = inspect.stack()\n- # Filter out internal frames\n- frame_infos = [\n- frame_info for frame_info in frame_infos\n- if traceback_util.include_frame(frame_info.frame)\n- ]\n- frames = [\n- DebuggerFrame.from_frameinfo(frame_info) for frame_info in frame_infos\n- ]\n- # Throw out first frame corresponding to this function\n- frames = frames[1:]\n- flat_args, frames_tree = tree_util.tree_flatten(frames)\n-\n- def _breakpoint_callback(*flat_args):\n- frames = tree_util.tree_unflatten(frames_tree, flat_args)\n- thread_id = None\n- if threading.current_thread() is not threading.main_thread():\n- thread_id = threading.get_ident()\n- with debug_lock:\n- TextDebugger(frames, thread_id, **kwargs).run()\n-\n- if ordered:\n- effect = debugging.DebugEffect.ORDERED_PRINT\n- else:\n- effect = debugging.DebugEffect.PRINT\n- debugging.debug_callback(_breakpoint_callback, effect, *flat_args)\n+from typing import Any, IO, List, Optional\n+\n+from jax._src.debugger import core as debugger_core\n-class TextDebugger(cmd.Cmd):\n+DebuggerFrame = debugger_core.DebuggerFrame\n+\n+class CliDebugger(cmd.Cmd):\n\"\"\"A text-based debugger.\"\"\"\nprompt = '(jaxdb) '\nuse_rawinput: bool = False\n@@ -200,3 +111,8 @@ class TextDebugger(cmd.Cmd):\nbreak\nexcept KeyboardInterrupt:\nself.stdout.write('--KeyboardInterrupt--\\n')\n+\n+def run_debugger(frames: List[DebuggerFrame], thread_id: Optional[int],\n+ **kwargs: Any):\n+ CliDebugger(frames, thread_id, **kwargs).run()\n+debugger_core.register_debugger(\"cli\", run_debugger, -1)\n" } ]
Python
Apache License 2.0
google/jax
Refactor debugger to have a registry
260,411
10.07.2022 18:44:18
-7,200
78028441999b5a9b6c4bea0f1ecc37dbbb8ab673
[dynamic_shapes] Fix the lowering of shapes in x64 mode. The mhlo.reshape op has the constraint that the operand and the result must have the same element type. Cast the dimension size to int32 to meet this constraint even in 64-bit mode.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -81,9 +81,13 @@ def i64_attr(i): return ir.IntegerAttr.get(ir.IntegerType.get_signless(64), i)\ndef shape_tensor(sizes: Sequence[Union[int, ir.RankedTensorType]]\n) -> ir.RankedTensorType:\n- int1d = aval_to_ir_type(core.ShapedArray((1,), np.dtype('int32')))\n- d, *ds = [ir_constant(np.array([d], np.dtype('int32'))) if type(d) is int\n- else mhlo.ReshapeOp(int1d, d) for d in sizes]\n+ int1d = aval_to_ir_type(core.ShapedArray((1,), np.int32))\n+ def lower_dim(d):\n+ if type(d) is int:\n+ return ir_constant(np.array([d], np.int32))\n+ else:\n+ return mhlo.ReshapeOp(int1d, mhlo.ConvertOp(aval_to_ir_type(core.ShapedArray((), np.int32)), d))\n+ d, *ds = map(lower_dim, sizes)\nif not ds:\nreturn d\nelse:\n@@ -964,9 +968,9 @@ def jaxpr_subcomp(ctx: ModuleContext, jaxpr: core.Jaxpr,\navals_out=map(aval, eqn.outvars), tokens_in=tokens_in,\ntokens_out=None)\nif config.jax_dynamic_shapes:\n- axis_size_env = {d: read(d)[0] for a in avals_in\n- if type(a) is core.DShapedArray for d in a.shape\n- if type(d) is core.Var}\n+ axis_size_env = {d: read(d)[0]\n+ for a in avals_in if type(a) is core.DShapedArray\n+ for d in a.shape if type(d) is core.Var}\nrule_ctx = rule_ctx.replace(axis_size_env=axis_size_env)\nans = rule(rule_ctx, *map(_unwrap_singleton_ir_values, in_nodes),\n**eqn.params)\n" } ]
Python
Apache License 2.0
google/jax
[dynamic_shapes] Fix the lowering of shapes in x64 mode. The mhlo.reshape op has the constraint that the operand and the result must have the same element type. Cast the dimension size to int32 to meet this constraint even in 64-bit mode.
260,411
13.07.2022 17:08:51
-10,800
e6f93bcdc0cdbffd40846bb44980a9e7ca48ce74
[shape-poly] Improve the error reporting for division Added a section to README to explain the division errors and to show a workaround. Changed the division errors to include more detail as to what the error is, and to include a link to the new section in the README
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -448,6 +448,7 @@ More operations are partially supported for dimension polynomials:\nin which case there may be a constant remainder. The need for division in JAX core\narises in a couple of specific situations, e.g.,\n`jax.numpy.reshape(-1)` and operations involving striding.\n+ See [#division-of-shape-polynomials-is-partially-supported](below) for a discussion.\n* equality and disequality are partially supported. They result in a boolean value only when\nthe same result would be obtained for any valuation of the dimension variables. In\nother situations, an exception `core.InconclusiveDimensionOperation` is raised.\n@@ -549,18 +550,34 @@ that `v == 4`, the shape checking rules fail with the above error.\nSince the converted function works only for square matrices, the correct\n`polymorphic_shapes` is `[\"(v, v)\"]`.\n-You would also encounter shape errors if the code attempts to use the\n-dimension variables in unsupported arithmetic operations, such as in the code\n-below that fails to compute the inferred dimension for a `reshape` operations:\n+\n+Certain codes that use shapes in the actual computation may not yet work\n+if those shapes are polymorphic. In the code below, the expression `x.shape[0]`\n+will have the value of the dimension variable `v`. This case is not yet implemented:\n+\n+```\n+jax2tf.convert(lambda x: jnp.sum(x, axis=0) / x.shape[0],\n+ polymorphic_shapes=[\"(v, _)\"])(np.ones((4, 4)))\n+```\n+\n+### Division of shape polynomials is partially supported\n+\n+Unlike addition and multiplication, which are fully supported on\n+shape polynomials, division is supported when either (a) there\n+is no remainder, or (b) the divisor is a constant\n+in which case there may be a constant remainder.\n+For example, the code below results in a division error when trying to\n+compute the inferred dimension for a `reshape` operation:\n```\njax2tf.convert(lambda x: jnp.reshape(x, (2, -1)),\npolymorphic_shapes=[\"(b, ...)\"])(np.ones((4, 5, 7)))\n```\n-In this case you will see the error `Cannot divide evenly the sizes of shapes (b, 5, 7) and (2, -1)`.\n-This is because the shape of `x` is `(b, 5, 7)`, with a total size represented as the\n-dimension polynomial `35 b`, which is not divisible by `2`.\n+In this case you will see the error `Cannot divide evenly the sizes of shapes (b, 5, 7) and (2, -1)`,\n+with a further `Details: Cannot divide '35*b' by '-2'`.\n+The polynomial `35*b` represents the total size of the input tensor.\n+\nNote that the following will succeed:\n```\n@@ -573,13 +590,18 @@ jax2tf.convert(lambda x: jnp.reshape(x, (-1, x.shape[0])),\npolymorphic_shapes=[\"(b1, b2, ...)\"])(np.ones((4, 5, 6)))\n```\n-Finally, certain codes that use shapes in the actual computation may not yet work\n-if those shapes are polymorphic. In the code below, the expression `x.shape[0]`\n-will have the value of the dimension variable `v`. This case is not yet implemented:\n+You may also encounter division errors when working with strides, such as\n+when computing the padding in a strided convolution.\n+\n+In some cases you may know that one of the dimension variables\n+is a multiple of the divisor,\n+e.g., `b` in the above example of dividing `35*b` by `-2` may\n+be known to be a multiple of `2`. You can specify that by replacing\n+`b` with `2*b` in the polymorphic shape specification:\n```\n-jax2tf.convert(lambda x: jnp.sum(x, axis=0) / x.shape[0],\n- polymorphic_shapes=[\"(v, _)\"])(np.ones((4, 4)))\n+jax2tf.convert(lambda x: jnp.reshape(x, (2, -1)),\n+ polymorphic_shapes=[\"(2*b, ...)\"])(np.ones((4, 5, 7)))\n```\n## Known issues\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/shape_poly.py", "new_path": "jax/experimental/jax2tf/shape_poly.py", "diff": "@@ -297,6 +297,13 @@ class _DimPolynomial():\ndef __lt__(self, other: DimSize):\nreturn not self.__ge__(other)\n+ def _division_error_msg(self, dividend, divisor, details: str = \"\") -> str:\n+ msg = f\"Cannot divide '{dividend}' by '{divisor}'.\"\n+ if details:\n+ msg += f\"\\nDetails: {details}.\"\n+ msg += \"\\nSee https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#division-of-shape-polynomials-is-partially-supported.\"\n+ return msg\n+\ndef divmod(self, divisor: DimSize) -> Tuple[DimSize, int]:\n\"\"\"\nFloor division with remainder (divmod) generalized to polynomials.\n@@ -309,18 +316,19 @@ class _DimPolynomial():\ndivisor = _ensure_poly(divisor)\ndmon, dcount = divisor.leading_term\ndividend, quotient = self, 0\n- err_msg = f\"Dimension polynomial '{self}' is not a multiple of '{divisor}'\"\n# invariant: self = dividend + divisor * quotient\n# the leading term of dividend decreases through the loop.\nwhile is_poly_dim(dividend) and not dividend.is_constant:\nmon, count = dividend.leading_term\ntry:\nqmon = mon.divide(dmon)\n- except InconclusiveDimensionOperation:\n- raise InconclusiveDimensionOperation(err_msg)\n+ except InconclusiveDimensionOperation as e:\n+ raise InconclusiveDimensionOperation(\n+ self._division_error_msg(self, divisor, str(e)))\nqcount, rcount = divmod(count, dcount)\nif rcount != 0:\n- raise InconclusiveDimensionOperation(err_msg)\n+ raise InconclusiveDimensionOperation(\n+ self._division_error_msg(self, divisor))\nq = _DimPolynomial.from_coeffs({qmon: qcount})\nquotient += q\n@@ -333,7 +341,8 @@ class _DimPolynomial():\nremainder = r\nelse:\nif dividend != 0:\n- raise InconclusiveDimensionOperation(err_msg)\n+ raise InconclusiveDimensionOperation(\n+ self._division_error_msg(self, divisor))\nremainder = 0\nif config.jax_enable_checks:\n@@ -351,13 +360,14 @@ class _DimPolynomial():\nq, r = self.divmod(divisor)\nif r != 0:\nraise InconclusiveDimensionOperation(\n- f\"Dimension polynomial '{self}' is not a multiple of '{divisor}'\")\n+ self._division_error_msg(self, divisor,\n+ f\"Remainder is not zero: {r}\"))\nreturn q\ndef __rtruediv__(self, dividend: DimSize):\n# Used for \"/\", when dividend is not a _DimPolynomial\nraise InconclusiveDimensionOperation(\n- f\"Division of '{dividend}' by dimension polynomial '{self}' is not supported\")\n+ self._division_error_msg(dividend, self, \"Dividend must be a polynomial\"))\ndef __mod__(self, divisor: DimSize) -> int:\nreturn self.divmod(divisor)[1]\n@@ -433,10 +443,10 @@ class DimensionHandlerPoly(core.DimensionHandler):\nerr_msg = f\"Cannot divide evenly the sizes of shapes {tuple(s1)} and {tuple(s2)}\"\ntry:\nq, r = _ensure_poly(sz1).divmod(sz2)\n- except InconclusiveDimensionOperation:\n- raise InconclusiveDimensionOperation(err_msg)\n+ except InconclusiveDimensionOperation as e:\n+ raise InconclusiveDimensionOperation(err_msg + f\"\\nDetails: {e}\")\nif r != 0:\n- raise InconclusiveDimensionOperation(err_msg)\n+ raise InconclusiveDimensionOperation(err_msg + f\"\\nRemainder is not zero: {r}\")\nreturn q # type: ignore[return-value]\ndef stride(self, d: DimSize, window_size: DimSize, window_stride: DimSize) -> DimSize:\n@@ -448,7 +458,7 @@ class DimensionHandlerPoly(core.DimensionHandler):\nexcept InconclusiveDimensionOperation as e:\nraise InconclusiveDimensionOperation(\nf\"Cannot compute stride for dimension '{d}', \"\n- f\"window_size '{window_size}', stride '{window_stride}'. Reason: {e}.\")\n+ f\"window_size '{window_size}', stride '{window_stride}'.\\nDetails: {e}.\")\nreturn d\ndef as_value(self, d: DimSize):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "diff": "@@ -270,7 +270,7 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\ndef test_poly_divmod(self, *, dividend, quotient, divisor, remainder):\nif quotient is None:\nwith self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n- \"Dimension polynomial .* is not a multiple of .*\"):\n+ \"Cannot divide .* by .*\"):\ndivmod(dividend, divisor)\nelse:\nself.assertEqual((quotient, remainder), divmod(dividend, divisor))\n@@ -294,7 +294,7 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\ndef test_poly_truediv(self, *, dividend, divisor, quotient):\nif quotient is None:\nwith self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n- \"Dimension polynomial .* is not a multiple of .*\"):\n+ \"Cannot divide .* by .*\"):\ndividend / divisor\nelse:\nself.assertEqual(quotient, dividend / divisor)\n@@ -302,7 +302,7 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\ndef test_poly_truediv_error(self):\na, = shape_poly._parse_spec(\"a,\", (2,))\nwith self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n- \"Division of '3' by dimension polynomial .* is not supported\"):\n+ \"Cannot divide .* by .*\"):\n3 / a\ndef test_dilate_shape(self):\n@@ -327,7 +327,7 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\ncore.InconclusiveDimensionOperation,\nre.escape(\n- \"Cannot compute stride for dimension 'a', window_size '1', stride '2'. Reason: Dimension polynomial 'a + -1' is not a multiple of '2'\")):\n+ \"Cannot compute stride for dimension 'a', window_size '1', stride '2'.\\nDetails: Cannot divide 'a + -1' by '2'\")):\ncore.stride_shape((a, 20), (1, 3), (2, 2))\n@@ -929,7 +929,8 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[\"(v, 4)\"])(np.ones((4, 4)))\nwith self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n- re.escape(\"Cannot divide evenly the sizes of shapes (b, 5, 7) and (2, -1)\")):\n+ re.compile(\"Cannot divide evenly the sizes of shapes \\\\(b, 5, 7\\\\) and \\\\(2, -1\\\\).*Details: Cannot divide '35\\\\*b' by '-2'\",\n+ re.DOTALL)):\njax2tf.convert(lambda x: jnp.reshape(x, (2, -1)),\npolymorphic_shapes=[\"(b, _, _)\"])(np.ones((4, 5, 7)))\n@@ -938,9 +939,12 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\njax2tf.convert(lambda x: jnp.reshape(x, (-1, x.shape[0])),\npolymorphic_shapes=[\"(b1, b2, ...)\"])(np.ones((4, 5, 6)))\n+ jax2tf.convert(lambda x: jnp.reshape(x, (2, -1)),\n+ polymorphic_shapes=[\"(2*b, ...)\"])(np.ones((4, 5, 7)))\n+\nwith self.assertRaisesRegex(\ncore.InconclusiveDimensionOperation,\n- re.compile(\"Division of .* by dimension polynomial .* is not supported\",\n+ re.compile(\"Cannot divide .* by 'v'.*Dividend must be a polynomial.\",\nre.DOTALL)):\njax2tf.convert(lambda x: jnp.sum(x, axis=0) / x.shape[0],\npolymorphic_shapes=[\"(v, _)\"])(np.ones((4, 4)))\n@@ -1275,20 +1279,40 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[RandArg((3, 4, 5), _f32)],\npoly_axes=[(0, 1)]),\n- # Issue #11402 InconclusiveDimensionOperation: Dimension polynomial '-1*t' is not a multiple of '2'\n- # TODO(still fails)\n- # _make_harness(\"conv_general_dilated\", \"1d_1\",\n- # lambda lhs, rhs: lax.conv_general_dilated(\n- # lhs, rhs,\n- # window_strides=(2,),\n- # padding=\"SAME\",\n- # rhs_dilation=None,\n- # dimension_numbers=lax.ConvDimensionNumbers(lhs_spec=(0, 2, 1),\n- # rhs_spec=(2, 1, 0),\n- # out_spec=(0, 2, 1))),\n- # [RandArg((1, 12, 16), _f32), RandArg((4, 16, 16), _f32)],\n- # poly_axes=[1, None],\n- # enable_and_disable_xla=True),\n+ # Issue #11402\n+ # We play a trick here. Since the stride is 2, when we compute the padding\n+ # for \"SAME\" we need to divide by 2. We cannot do this in general, so we\n+ # write the test with the assumption that the dimension is a multiple of 2.\n+ # We pass the lhs as (1, b, 2, 16) and then we\n+ # reshape it as (1, 2*b, 16), so that we know that the lhs's dimension 1\n+ # is a multiple of 2.\n+ _make_harness(\"conv_general_dilated\", \"1d_1\",\n+ lambda lhs, rhs: lax.conv_general_dilated(\n+ jnp.reshape(lhs, (1, -1, 16)), rhs,\n+ window_strides=(2,),\n+ padding=\"SAME\",\n+ rhs_dilation=None,\n+ dimension_numbers=lax.ConvDimensionNumbers(lhs_spec=(0, 2, 1),\n+ rhs_spec=(2, 1, 0),\n+ out_spec=(0, 2, 1))),\n+ [RandArg((1, 6, 2, 16), _f32), RandArg((4, 16, 16), _f32)],\n+ poly_axes=[1, None],\n+ enable_and_disable_xla=True),\n+ # The same example from above, but without the reshape trick.\n+ _make_harness(\"conv_general_dilated\", \"1d_1err\",\n+ lambda lhs, rhs: lax.conv_general_dilated(\n+ lhs, rhs,\n+ window_strides=(2,),\n+ padding=\"SAME\",\n+ rhs_dilation=None,\n+ dimension_numbers=lax.ConvDimensionNumbers(lhs_spec=(0, 2, 1),\n+ rhs_spec=(2, 1, 0),\n+ out_spec=(0, 2, 1))),\n+ [RandArg((1, 12, 16), _f32), RandArg((4, 16, 16), _f32)],\n+ poly_axes=[1, None],\n+ enable_and_disable_xla=True,\n+ expect_error=(core.InconclusiveDimensionOperation,\n+ \"Cannot divide .* by '2'\")),\n# Issue #11402\n_make_harness(\"conv_general_dilated\", \"1d_2\",\nlambda lhs, rhs: lax.conv_transpose(lhs, rhs,\n@@ -1842,7 +1866,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# to parameterized below.\n@primitive_harness.parameterized(\n_flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"conv_general_dilated_1d_2_noxla_poly_axes=[0, None]\"\n+ #one_containing=\"conv_general_dilated_1d_1err_poly_axes=[1, None]\"\n)\ndef test_prim(self, harness: Harness):\n_test_one_harness(self, harness)\n" } ]
Python
Apache License 2.0
google/jax
[shape-poly] Improve the error reporting for division Added a section to README to explain the division errors and to show a workaround. Changed the division errors to include more detail as to what the error is, and to include a link to the new section in the README
260,447
14.07.2022 20:34:40
25,200
b421e24bb064c9a09926484b340628498df1d996
[sparse] Update `_validate_coo_mhlo` in gpu_sparse.
[ { "change_type": "MODIFY", "old_path": "jaxlib/gpu_sparse.py", "new_path": "jaxlib/gpu_sparse.py", "diff": "@@ -57,7 +57,7 @@ def _validate_csr_mhlo(data, indices, indptr, shape):\nassert indptr_type.shape == [shape[0] + 1]\nreturn data_type.element_type, indices_type.element_type, nnz\n-def _validate_coo_mhlo(data, row, col, shape):\n+def _validate_coo_mhlo(data, row, col):\ndata_type = ir.RankedTensorType(data.type)\nrow_type = ir.RankedTensorType(row.type)\ncol_type = ir.RankedTensorType(col.type)\n@@ -194,7 +194,7 @@ rocm_csr_matmat = partial(_csr_matmat_mhlo, \"hip\", _hipsparse)\ndef _coo_todense_mhlo(platform, gpu_sparse, data, row, col, *, shape,\ndata_dtype, index_dtype):\n\"\"\"COO to dense matrix.\"\"\"\n- data_type, _, nnz = _validate_coo_mhlo(data, row, col, shape)\n+ data_type, _, nnz = _validate_coo_mhlo(data, row, col)\nrows, cols = shape\nbuffer_size, opaque = gpu_sparse.build_coo_todense_descriptor(\n@@ -249,7 +249,7 @@ def _coo_matvec_mhlo(platform, gpu_sparse, data, row, col, x, *, shape,\ntranspose=False, compute_dtype=None, compute_type=None,\nindex_dtype, data_dtype, x_dtype):\n\"\"\"COO matrix/vector multiply.\"\"\"\n- data_type, index_type, nnz = _validate_coo_mhlo(data, row, col, shape)\n+ data_type, _, nnz = _validate_coo_mhlo(data, row, col)\nrows, cols = shape\nif compute_dtype is None:\n@@ -282,7 +282,7 @@ def _coo_matmat_mhlo(platform, gpu_sparse, data, row, col, B, *, shape,\ntranspose=False, compute_dtype=None, compute_type=None,\nx_dtype, data_dtype, index_dtype):\n\"\"\"COO from dense matrix.\"\"\"\n- data_type, index_type, nnz = _validate_coo_mhlo(data, row, col, shape)\n+ data_type, _, nnz = _validate_coo_mhlo(data, row, col)\nrows, cols = shape\nB_shape = ir.RankedTensorType(B.type).shape\n_, Ccols = B_shape\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Update `_validate_coo_mhlo` in gpu_sparse. PiperOrigin-RevId: 461111317
260,631
15.07.2022 01:23:27
25,200
023e6f5955e28734b9c5d1524710e85cd7bffd33
Copybara import of the project: by Roy Frostig maintain an alias to `jax.tree_util.tree_map` in the top level `jax` module
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -17,12 +17,12 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Binary operations between JAX arrays and built-in collections (`dict`, `list`, `set`, `tuple`)\nnow raise a `TypeError` in all cases. Previously some cases (particularly equality and inequality)\nwould return boolean scalars inconsistent with similar operations in NumPy ({jax-issue}`#11234`).\n- * Several {mod}`jax.tree_util` routines accessed as top-level JAX package imports are now\n- deprecated, and will be removed in a future JAX release in accordance with the\n- {ref}`api-compatibility` policy:\n+ * {mod}`jax.tree_util` routines accessed as top-level JAX package imports are now deprecated, and\n+ will be removed in a future JAX release in accordance with the {ref}`api-compatibility` policy:\n* {func}`jax.treedef_is_leaf` is deprecated in favor of {func}`jax.tree_util.treedef_is_leaf`\n* {func}`jax.tree_flatten` is deprecated in favor of {func}`jax.tree_util.tree_flatten`\n* {func}`jax.tree_leaves` is deprecated in favor of {func}`jax.tree_util.tree_leaves`\n+ * {func}`jax.tree_map` is deprecated in favor of {func}`jax.tree_util.tree_map`\n* {func}`jax.tree_structure` is deprecated in favor of {func}`jax.tree_util.tree_structure`\n* {func}`jax.tree_transpose` is deprecated in favor of {func}`jax.tree_util.tree_transpose`\n* {func}`jax.tree_unflatten` is deprecated in favor of {func}`jax.tree_util.tree_unflatten`\n" }, { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -115,12 +115,12 @@ from jax.experimental.maps import soft_pmap as soft_pmap\nfrom jax.version import __version__ as __version__\nfrom jax.version import __version_info__ as __version_info__\n-from jax._src.tree_util import (\n- tree_map as tree_map,\n# TODO(jakevdp): remove these deprecated routines after October 2022\n+from jax._src.tree_util import (\n_deprecated_treedef_is_leaf as treedef_is_leaf,\n_deprecated_tree_flatten as tree_flatten,\n_deprecated_tree_leaves as tree_leaves,\n+ _deprecated_tree_map as tree_map,\n_deprecated_tree_multimap as tree_multimap,\n_deprecated_tree_structure as tree_structure,\n_deprecated_tree_transpose as tree_transpose,\n" } ]
Python
Apache License 2.0
google/jax
Copybara import of the project: -- e1f1e93e0c8b53e62a064b06b56c84a2bfedb911 by Roy Frostig <frostig@google.com>: maintain an alias to `jax.tree_util.tree_map` in the top level `jax` module PiperOrigin-RevId: 461146464
260,631
18.07.2022 01:27:43
25,200
ae4aee762a6ab18b17d61b68d8ee32d2c4e3b957
[jax2tf] Fix conv1d padding; it's already normalized before the _pad_spatial_dims call. Enable non-XLA tests of conv1d.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/impl_no_xla.py", "new_path": "jax/experimental/jax2tf/impl_no_xla.py", "diff": "@@ -118,16 +118,11 @@ def pads_to_padtype(in_shape, window_shape, window_strides, padding) -> str:\nreturn \"EXPLICIT\"\n-def _pad_spatial_dims(x, x_shape, padding, is_conv1d):\n+def _pad_spatial_dims(x, x_shape, padding):\n\"\"\"Pads `x` using `padding`, which specifies padding for the spatial dimensions.\"\"\"\n# Add empty padding for batch and feature dimensions.\nno_pad = ((0, 0),)\npadding = tuple(padding)\n- if is_conv1d:\n- padding = no_pad + padding + no_pad\n- # Add empty padding for dummy dimension, too.\n- padding = no_pad + padding + no_pad + no_pad\n- else:\npadding = no_pad + padding + no_pad\nx = tf.pad(x, padding)\nassert len(x.shape) == len(padding)\n@@ -285,7 +280,7 @@ def _conv_general_dilated(\nlhs_shape[1:3], rhs_dilated_shape, window_strides, padding)\n# We only manually pad if we aren't using a tranposed convolutions.\nif padding_type == \"EXPLICIT\":\n- lhs, lhs_shape = _pad_spatial_dims(lhs, lhs_shape, padding, is_conv1d)\n+ lhs, lhs_shape = _pad_spatial_dims(lhs, lhs_shape, padding)\npadding_type = \"VALID\"\nif padding_type != \"SAME\" and any(l < r for l, r in zip(lhs_shape[1:3], rhs_dilated_shape)):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -3082,19 +3082,6 @@ for padding, lhs_dilation, rhs_dilation in [\nrhs_dilation=rhs_dilation,\nworks_without_xla=True)\n-#--- END Tests for conv_general_dilated with works_without_xla=True ---\n-\n-\n-for lhs_dilation, rhs_dilation in [\n- # Note: LHS dilation does work for enable_xla=False, but only if\n- # padding=='VALID' (see test above for conv_transpose2d_valid_padding).\n- ((2, 2), (1, 1)), # dilation only on LHS (transposed)\n- ((2, 3), (3, 2)) # dilation on both LHS and RHS (transposed & atrous)\n-]:\n- _make_conv_harness(\n- \"dilations\", lhs_dilation=lhs_dilation, rhs_dilation=rhs_dilation)\n-\n-\nfor padding, lhs_dilation, rhs_dilation in [\n(\"VALID\", (1,), (1,)), # no dilation with \"VALID\" padding\n(\"SAME\", (1,), (1,)), # no dilation with \"SAME\" padding\n@@ -3112,7 +3099,19 @@ for padding, lhs_dilation, rhs_dilation in [\ndimension_numbers=dimension_numbers,\nwindow_strides=(1,),\nlhs_dilation=lhs_dilation,\n- rhs_dilation=rhs_dilation)\n+ rhs_dilation=rhs_dilation,\n+ works_without_xla=True)\n+\n+#--- END Tests for conv_general_dilated with works_without_xla=True ---\n+\n+for lhs_dilation, rhs_dilation in [\n+ # Note: LHS dilation does work for enable_xla=False, but only if\n+ # padding=='VALID' (see test above for conv_transpose2d_valid_padding).\n+ ((2, 2), (1, 1)), # dilation only on LHS (transposed)\n+ ((2, 3), (3, 2)) # dilation on both LHS and RHS (transposed & atrous)\n+]:\n+ _make_conv_harness(\n+ \"dilations\", lhs_dilation=lhs_dilation, rhs_dilation=rhs_dilation)\nfor padding, lhs_dilation, rhs_dilation in [\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix conv1d padding; it's already normalized before the _pad_spatial_dims call. Enable non-XLA tests of conv1d. PiperOrigin-RevId: 461556553
260,707
18.07.2022 16:39:52
-3,600
4808c4f11397b611ba9f3f6ecff1462854f98562
Update docs: div/rev
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -453,11 +453,25 @@ def mul(x: Array, y: Array) -> Array:\nreturn mul_p.bind(x, y)\ndef div(x: Array, y: Array) -> Array:\n- r\"\"\"Elementwise division: :math:`x \\over y`.\"\"\"\n+ r\"\"\"Elementwise division: :math:`x \\over y`.\n+\n+ Integer division overflow\n+ (division by zero or signed division of INT_SMIN with -1)\n+ produces an implementation defined value.\n+ \"\"\"\nreturn div_p.bind(x, y)\ndef rem(x: Array, y: Array) -> Array:\n- r\"\"\"Elementwise remainder: :math:`x \\bmod y`.\"\"\"\n+ r\"\"\"Elementwise remainder: :math:`x \\bmod y`.\n+\n+ The sign of the result is taken from the dividend,\n+ and the absolute value of the result is always\n+ less than the divisor's absolute value.\n+\n+ Integer division overflow\n+ (remainder by zero or remainder of INT_SMIN with -1)\n+ produces an implementation defined value.\n+ \"\"\"\nreturn rem_p.bind(x, y)\ndef max(x: Array, y: Array) -> Array:\n" } ]
Python
Apache License 2.0
google/jax
Update docs: div/rev
260,631
18.07.2022 10:04:59
25,200
d98d5ddce5c883b6db2f02e3a087291ebb869d67
[JAX] Add `jax_unique_mhlo_module_names` flag to control if MHLO should be made unique. Some clients of JAX expect module names to not be altered so that they can cache XLA compilations.
[ { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -853,6 +853,12 @@ config.define_bool_state(\ndefault=True,\nhelp='Enable using the context manager-based name stack.')\n+config.define_bool_state(\n+ name='jax_unique_mhlo_module_names',\n+ default=True,\n+ help='Enables the generation of unique MHLO module names. This is useful '\n+ 'to clients that expect modules to have unique names (e.g, trace data).')\n+\n# This flag is temporary during rollout of the remat barrier.\n# TODO(parkers): Remove if there are no complaints.\nconfig.define_bool_state(\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -593,10 +593,14 @@ def lower_jaxpr_to_module(\n# Remove module name characters that XLA would alter. This ensures that\n# XLA computation preserves the module name.\nmodule_name = _module_name_regex.sub(\"_\", module_name)\n+ if config.jax_unique_mhlo_module_names:\n# Some clients expect modules to have unique names, e.g., in trace data.\n# This may or may not be a reasonable assumption.\nctx.module.operation.attributes[\"sym_name\"] = ir.StringAttr.get(\nf\"{module_name}.{next(_module_unique_id)}\")\n+ else:\n+ ctx.module.operation.attributes[\"sym_name\"] = ir.StringAttr.get(\n+ module_name)\nunlowerable_effects = {eff for eff in jaxpr.effects\nif eff not in lowerable_effects}\nif unlowerable_effects:\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Add `jax_unique_mhlo_module_names` flag to control if MHLO should be made unique. Some clients of JAX expect module names to not be altered so that they can cache XLA compilations. PiperOrigin-RevId: 461648129
260,510
12.07.2022 18:30:40
25,200
09fd173a3e24d9a12e81b9d893a982a62d37c071
Add colab debugger
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugger/__init__.py", "new_path": "jax/_src/debugger/__init__.py", "diff": "# limitations under the License.\nfrom jax._src.debugger.core import breakpoint\nfrom jax._src.debugger import cli_debugger\n+from jax._src.debugger import colab_debugger\ndel cli_debugger # For registration only\n+del colab_debugger # For registration only\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/cli_debugger.py", "new_path": "jax/_src/debugger/cli_debugger.py", "diff": "@@ -21,7 +21,6 @@ from typing import Any, IO, List, Optional\nfrom jax._src.debugger import core as debugger_core\n-\nDebuggerFrame = debugger_core.DebuggerFrame\nclass CliDebugger(cmd.Cmd):\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/debugger/colab_debugger.py", "diff": "+# Copyright 2022 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+\"\"\"Module for Colab-specific debugger.\"\"\"\n+from __future__ import annotations\n+\n+import html\n+import inspect\n+import traceback\n+\n+from typing import List\n+\n+import uuid\n+\n+from jax._src.debugger import colab_lib\n+from jax._src.debugger import core as debugger_core\n+from jax._src.debugger import cli_debugger\n+\n+# pylint: disable=g-import-not-at-top\n+# pytype: disable=import-error\n+if colab_lib.IS_COLAB_ENABLED:\n+ from google.colab import output\n+try:\n+ import pygments\n+ IS_PYGMENTS_ENABLED = True\n+except ImportError:\n+ IS_PYGMENTS_ENABLED = False\n+# pytype: enable=import-error\n+# pylint: enable=g-import-not-at-top\n+\n+\n+class CodeViewer(colab_lib.DynamicDOMElement):\n+ \"\"\"A mutable DOM element that displays code as HTML.\"\"\"\n+\n+ def __init__(self, code_: str, highlights: List[int], linenostart: int = 1):\n+ self._code = code_\n+ self._highlights = highlights\n+ self._view = colab_lib.dynamic(colab_lib.div())\n+ self._linenostart = linenostart\n+\n+ def render(self):\n+ self.update_code(\n+ self._code, self._highlights, linenostart=self._linenostart)\n+\n+ def clear(self):\n+ self._view.clear()\n+\n+ def append(self, child):\n+ raise NotImplementedError\n+\n+ def update(self, elem):\n+ self._view.update(elem)\n+\n+ def _highlight_code(self, code: str, highlights, linenostart: int):\n+ is_dark_mode = output.eval_js(\n+ 'document.documentElement.matches(\"[theme=dark]\");')\n+ code_style = \"monokai\" if is_dark_mode else \"default\"\n+ hl_color = \"#4e56b7\" if is_dark_mode else \"#fff7c1\"\n+ if IS_PYGMENTS_ENABLED:\n+ lexer = pygments.lexers.get_lexer_by_name(\"python\")\n+ formatter = pygments.formatters.HtmlFormatter(\n+ full=False,\n+ hl_lines=highlights,\n+ linenos=True,\n+ linenostart=linenostart,\n+ style=code_style)\n+ if hl_color:\n+ formatter.style.highlight_color = hl_color\n+ css_ = formatter.get_style_defs()\n+ code = pygments.highlight(code, lexer, formatter)\n+ else:\n+ return \"\";\n+ return code, css_\n+\n+ def update_code(self, code_, highlights, *, linenostart: int = 1):\n+ \"\"\"Updates the code viewer to use new code.\"\"\"\n+ self._code = code_\n+ self._view.clear()\n+ code_, css_ = self._highlight_code(self._code, highlights, linenostart)\n+ uuid_ = uuid.uuid4()\n+ code_div = colab_lib.div(\n+ colab_lib.css(css_),\n+ code_,\n+ id=f\"code-{uuid_}\",\n+ style=colab_lib.style({\n+ \"max-height\": \"500px\",\n+ \"overflow-y\": \"scroll\",\n+ \"background-color\": \"var(--colab-border-color)\",\n+ \"padding\": \"5px 5px 5px 5px\",\n+ }))\n+ if highlights:\n+ percent_scroll = highlights[0] / len(self._code.split(\"\\n\"))\n+ else:\n+ percent_scroll = 0.\n+ self.update(code_div)\n+ # Scroll to where the line is\n+ output.eval_js(\"\"\"\n+ console.log(\"{id}\")\n+ var elem = document.getElementById(\"{id}\")\n+ var maxScrollPosition = elem.scrollHeight - elem.clientHeight;\n+ elem.scrollTop = maxScrollPosition * {percent_scroll}\n+ \"\"\".format(id=f\"code-{uuid_}\", percent_scroll=percent_scroll))\n+\n+\n+class FramePreview(colab_lib.DynamicDOMElement):\n+ \"\"\"Displays information about a stack frame.\"\"\"\n+\n+ def __init__(self, frame):\n+ super().__init__()\n+ self._header = colab_lib.dynamic(\n+ colab_lib.div(colab_lib.pre(colab_lib.code(\"\"))))\n+ self._code_view = CodeViewer(\"\", highlights=[])\n+ self.frame = frame\n+ self._file_cache = {}\n+\n+ def clear(self):\n+ self._header.clear()\n+ self._code_view.clear()\n+\n+ def append(self, child):\n+ raise NotImplementedError\n+\n+ def update(self, elem):\n+ raise NotImplementedError\n+\n+ def update_frame(self, frame):\n+ \"\"\"Updates the frame viewer to use a new frame.\"\"\"\n+ self.frame = frame\n+ lineno = self.frame.lineno or None\n+ filename = self.frame.filename.strip()\n+ if inspect.getmodulename(filename):\n+ if filename not in self._file_cache:\n+ try:\n+ with open(filename, \"r\") as fp:\n+ self._file_cache[filename] = fp.read()\n+ source = self._file_cache[filename]\n+ highlight = lineno\n+ linenostart = 1\n+ except FileNotFoundError:\n+ source = \"\\n\".join(frame.source)\n+ highlight = min(frame.offset + 1, len(frame.source) - 1)\n+ linenostart = lineno - frame.offset\n+ else:\n+ source = \"\\n\".join(frame.source)\n+ highlight = min(frame.offset + 1, len(frame.source) - 1)\n+ linenostart = lineno - frame.offset\n+ self._header.clear()\n+ self._header.update(\n+ colab_lib.div(\n+ colab_lib.pre(colab_lib.code(f\"{html.escape(filename)}({lineno})\")),\n+ style=colab_lib.style({\n+ \"padding\": \"5px 5px 5px 5px\",\n+ \"background-color\": \"var(--colab-highlighted-surface-color)\",\n+ })))\n+ self._code_view.update_code(source, [highlight], linenostart=linenostart)\n+\n+ def render(self):\n+ self.update_frame(self.frame)\n+\n+\n+class DebuggerView(colab_lib.DynamicDOMElement):\n+ \"\"\"Main view for the Colab debugger.\"\"\"\n+\n+ def __init__(self, frame, *, log_color=\"\"):\n+ super().__init__()\n+ self._interaction_log = colab_lib.dynamic(colab_lib.div())\n+ self._frame_preview = FramePreview(frame)\n+ self._header = colab_lib.dynamic(\n+ colab_lib.div(\n+ colab_lib.span(\"Breakpoint\"),\n+ style=colab_lib.style({\n+ \"background-color\": \"var(--colab-secondary-surface-color)\",\n+ \"color\": \"var(--colab-primary-text-color)\",\n+ \"padding\": \"5px 5px 5px 5px\",\n+ \"font-weight\": \"bold\",\n+ })))\n+\n+ def render(self):\n+ self._header.render()\n+ self._frame_preview.render()\n+ self._interaction_log.render()\n+\n+ def append(self, child):\n+ raise NotImplementedError\n+\n+ def update(self, elem):\n+ raise NotImplementedError\n+\n+ def clear(self):\n+ self._header.clear()\n+ self._interaction_log.clear()\n+ self._frame_preview.clear()\n+\n+ def update_frame(self, frame):\n+ self._frame_preview.update_frame(frame)\n+\n+ def log(self, text):\n+ self._interaction_log.append(colab_lib.pre(text))\n+\n+ def read(self):\n+ with output.use_tags([\"stdin\"]):\n+ user_input = input()\n+ output.clear(output_tags=[\"stdin\"])\n+ return user_input\n+\n+\n+class ColabDebugger(cli_debugger.CliDebugger):\n+ \"\"\"A JAX debugger for a Colab environment.\"\"\"\n+\n+ def __init__(self,\n+ frames: List[debugger_core.DebuggerFrame],\n+ thread_id: int):\n+ super().__init__(frames, thread_id)\n+ self._debugger_view = DebuggerView(self.current_frame())\n+\n+ def read(self):\n+ return self._debugger_view.read()\n+\n+ def cmdloop(self, intro=None):\n+ self.preloop()\n+ stop = None\n+ while not stop:\n+ if self.cmdqueue:\n+ line = self.cmdqueue.pop(0)\n+ else:\n+ try:\n+ line = self.read()\n+ except EOFError:\n+ line = \"EOF\"\n+ line = self.precmd(line)\n+ stop = self.onecmd(line)\n+ stop = self.postcmd(stop, line)\n+ self.postloop()\n+\n+ def do_u(self, _):\n+ if self.frame_index == len(self.frames) - 1:\n+ self.log(\"At topmost frame.\")\n+ return False\n+ self.frame_index += 1\n+ self._debugger_view.update_frame(self.current_frame())\n+ return False\n+\n+ def do_d(self, _):\n+ if self.frame_index == 0:\n+ self.log(\"At bottommost frame.\")\n+ return False\n+ self.frame_index -= 1\n+ self._debugger_view.update_frame(self.current_frame())\n+ return False\n+\n+ def do_bt(self, _):\n+ self.log(\"Traceback:\")\n+ for frame in self.frames[::-1]:\n+ filename = frame.filename.strip()\n+ filename = filename or \"<no filename>\"\n+ self.log(f\" File: {filename}, line ({frame.lineno})\")\n+ if frame.offset < len(frame.source):\n+ line = frame.source[frame.offset]\n+ self.log(f\" {line.strip()}\")\n+ else:\n+ self.log(\" \")\n+\n+ def do_c(self, _):\n+ return True\n+\n+ def do_q(self, _):\n+ return True\n+\n+ def do_EOF(self, _):\n+ return True\n+\n+ def do_p(self, arg):\n+ try:\n+ value = self.evaluate(arg)\n+ self.log(repr(value))\n+ except Exception: # pylint: disable=broad-except\n+ self.log(traceback.format_exc(limit=1))\n+ return False\n+\n+ do_pp = do_p\n+\n+ def log(self, text):\n+ self._debugger_view.log(html.escape(text))\n+\n+ def run(self):\n+ self._debugger_view.render()\n+ try:\n+ self.cmdloop()\n+ except KeyboardInterrupt:\n+ self.log(\"--Keyboard-Interrupt--\")\n+ pass\n+ self._debugger_view.clear()\n+\n+\n+def _run_debugger(frames, thread_id, **kwargs):\n+ try:\n+ ColabDebugger(frames, thread_id, **kwargs).run()\n+ except Exception:\n+ traceback.print_exc()\n+\n+\n+if colab_lib.IS_COLAB_ENABLED:\n+ debugger_core.register_debugger(\"colab\", _run_debugger, 1)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/debugger/colab_lib.py", "diff": "+# Copyright 2022 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+\"\"\"Module for building interfaces in Colab.\"\"\"\n+from __future__ import annotations\n+\n+import abc\n+import dataclasses\n+import functools\n+import uuid\n+\n+from typing import Any, Dict, List, Union\n+\n+# pylint: disable=g-import-not-at-top\n+# pytype: disable=import-error\n+try:\n+ from google.colab import output\n+ from IPython import display\n+ IS_COLAB_ENABLED = True\n+except ImportError:\n+ IS_COLAB_ENABLED = False\n+# pytype: enable=import-error\n+# pylint: enable=g-import-not-at-top\n+\n+\n+class DOMElement(metaclass=abc.ABCMeta):\n+\n+ @abc.abstractmethod\n+ def render(self):\n+ pass\n+\n+\n+Element = Union[DOMElement, str]\n+\n+\n+class DynamicDOMElement(DOMElement):\n+ \"\"\"A DOM element that can be mutated.\"\"\"\n+\n+ @abc.abstractmethod\n+ def render(self):\n+ pass\n+\n+ @abc.abstractmethod\n+ def append(self, child: DOMElement):\n+ pass\n+\n+ @abc.abstractmethod\n+ def update(self, elem: DOMElement):\n+ pass\n+\n+ @abc.abstractmethod\n+ def clear(self):\n+ pass\n+\n+@dataclasses.dataclass\n+class DynamicDiv(DynamicDOMElement):\n+ \"\"\"A `div` that can be edited.\"\"\"\n+ _uuid: str = dataclasses.field(init=False)\n+ _root_elem: DOMElement = dataclasses.field(init=False)\n+ elem: Union[DOMElement, str]\n+\n+ def __post_init__(self):\n+ self._uuid = str(uuid.uuid4())\n+ self._rendered = False\n+ self._root_elem = div(id=self.tag)\n+\n+ @property\n+ def tag(self):\n+ return f\"tag-{self._uuid}\"\n+\n+ def render(self):\n+ if self._rendered:\n+ raise ValueError(\"Can't call `render` twice.\")\n+ self._root_elem.render()\n+ self._rendered = True\n+ self.append(self.elem)\n+\n+ def append(self, child: DOMElement):\n+ if not self._rendered:\n+ self.render()\n+ with output.use_tags([self.tag]):\n+ with output.redirect_to_element(f\"#{self.tag}\"):\n+ child.render()\n+\n+ def update(self, elem: DOMElement):\n+ self.clear()\n+ self.elem = elem\n+ self.render()\n+\n+ def clear(self):\n+ output.clear(output_tags=[self.tag])\n+ self._rendered = False\n+\n+\n+@dataclasses.dataclass\n+class StaticDOMElement(DOMElement):\n+ \"\"\"An immutable DOM element.\"\"\"\n+ _uuid: str = dataclasses.field(init=False)\n+ name: str\n+ children: List[Union[str, DOMElement]]\n+ attrs: Dict[str, str]\n+\n+ def html(self):\n+ attr_str = \"\"\n+ if self.attrs:\n+ attr_str = \" \" + (\" \".join(\n+ [f\"{key}=\\\"{value}\\\"\" for key, value in self.attrs.items()]))\n+ children = []\n+ children = \"\\n\".join([str(c) for c in self.children])\n+ return f\"<{self.name}{attr_str}>{children}</{self.name}>\"\n+\n+ def render(self):\n+ display.display(display.HTML(self.html()))\n+\n+ def attr(self, key: str) -> str:\n+ return self.attrs[key]\n+\n+ def __str__(self):\n+ return self.html()\n+\n+ def __repr__(self):\n+ return self.html()\n+\n+ def append(self, child: DOMElement) -> DOMElement:\n+ return dataclasses.replace(self, children=[*self.children, child])\n+\n+ def replace(self, **kwargs) -> DOMElement:\n+ return dataclasses.replace(self, **kwargs)\n+\n+\n+def _style_dict_to_str(style_dict: Dict[str, Any]) -> str:\n+ return \" \".join([f\"{k}: {v};\" for k, v in style_dict.items()])\n+\n+\n+def dynamic(elem: StaticDOMElement) -> DynamicDiv:\n+ return DynamicDiv(elem)\n+\n+\n+def _make_elem(tag: str, *children: Element, **attrs) -> StaticDOMElement:\n+ \"\"\"Helper function for making DOM elements.\"\"\"\n+ return StaticDOMElement(tag, list(children), attrs)\n+\n+\n+code = functools.partial(_make_elem, \"code\")\n+div = functools.partial(_make_elem, \"div\")\n+li = functools.partial(_make_elem, \"li\")\n+ol = functools.partial(_make_elem, \"ol\")\n+pre = functools.partial(_make_elem, \"pre\")\n+progress = functools.partial(_make_elem, \"progress\")\n+span = functools.partial(_make_elem, \"span\")\n+\n+\n+def css(text: str) -> StaticDOMElement:\n+ return StaticDOMElement(\"style\", [text], {})\n+\n+\n+def style(*args, **kwargs):\n+ return _style_dict_to_str(dict(*args, **kwargs))\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/debugger/core.py", "diff": "+# Copyright 2022 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+from __future__ import annotations\n+\n+import dataclasses\n+import inspect\n+import threading\n+\n+from typing import Any, Dict, List, Optional, Tuple\n+from typing_extensions import Protocol\n+\n+import jax.numpy as jnp\n+from jax import core\n+from jax import tree_util\n+from jax._src import debugging\n+from jax._src import traceback_util\n+from jax._src import util\n+import numpy as np\n+\n+@tree_util.register_pytree_node_class\n+@dataclasses.dataclass(frozen=True)\n+class DebuggerFrame:\n+ \"\"\"Encapsulates Python frame information.\"\"\"\n+ filename: str\n+ locals: Dict[str, Any]\n+ code_context: str\n+ source: List[str]\n+ lineno: int\n+ offset: Optional[int]\n+\n+ def tree_flatten(self):\n+ flat_locals, locals_tree = tree_util.tree_flatten(self.locals)\n+ is_valid = [\n+ isinstance(l, (core.Tracer, jnp.ndarray, np.ndarray))\n+ for l in flat_locals\n+ ]\n+ invalid_locals, valid_locals = util.partition_list(is_valid, flat_locals)\n+ return valid_locals, (is_valid, invalid_locals, locals_tree, self.filename,\n+ self.code_context, self.source, self.lineno,\n+ self.offset)\n+\n+ @classmethod\n+ def tree_unflatten(cls, info, valid_locals):\n+ (is_valid, invalid_locals, locals_tree, filename, code_context, source,\n+ lineno, offset) = info\n+ flat_locals = util.merge_lists(is_valid, invalid_locals, valid_locals)\n+ locals_ = tree_util.tree_unflatten(locals_tree, flat_locals)\n+ return DebuggerFrame(filename, locals_, code_context, source, lineno,\n+ offset)\n+\n+ @classmethod\n+ def from_frameinfo(cls, frame_info) -> DebuggerFrame:\n+ try:\n+ _, start = inspect.getsourcelines(frame_info.frame)\n+ source = inspect.getsource(frame_info.frame).split('\\n')\n+ offset = frame_info.lineno - start\n+ except OSError:\n+ source = []\n+ offset = None\n+ return DebuggerFrame(\n+ filename=frame_info.filename,\n+ locals=frame_info.frame.f_locals,\n+ code_context=frame_info.code_context,\n+ source=source,\n+ lineno=frame_info.lineno,\n+ offset=offset)\n+\n+\n+class Debugger(Protocol):\n+\n+ def __call__(self, frames: List[DebuggerFrame], thread_id: Optional[int],\n+ **kwargs: Any) -> None:\n+ ...\n+_debugger_registry: Dict[str, Tuple[int, Debugger]] = {}\n+\n+\n+def get_debugger() -> Debugger:\n+ debuggers = sorted(_debugger_registry.values(), key=lambda x: -x[0])\n+ if not debuggers:\n+ raise ValueError(\"No debuggers registered!\")\n+ return debuggers[0][1]\n+\n+\n+def register_debugger(name: str, debugger: Debugger, priority: int) -> None:\n+ if name in _debugger_registry:\n+ raise ValueError(f\"Debugger with name \\\"{name}\\\" already registered.\")\n+ _debugger_registry[name] = (priority, debugger)\n+\n+\n+debug_lock = threading.Lock()\n+\n+\n+def breakpoint(*, ordered: bool = False, **kwargs): # pylint: disable=redefined-builtin\n+ \"\"\"Enters a breakpoint at a point in a program.\"\"\"\n+ frame_infos = inspect.stack()\n+ # Filter out internal frames\n+ frame_infos = [\n+ frame_info for frame_info in frame_infos\n+ if traceback_util.include_frame(frame_info.frame)\n+ ]\n+ frames = [\n+ DebuggerFrame.from_frameinfo(frame_info) for frame_info in frame_infos\n+ ]\n+ # Throw out first frame corresponding to this function\n+ frames = frames[1:]\n+ flat_args, frames_tree = tree_util.tree_flatten(frames)\n+\n+ def _breakpoint_callback(*flat_args):\n+ frames = tree_util.tree_unflatten(frames_tree, flat_args)\n+ thread_id = None\n+ if threading.current_thread() is not threading.main_thread():\n+ thread_id = threading.get_ident()\n+ debugger = get_debugger()\n+ # Lock here because this could be called from multiple threads at the same\n+ # time.\n+ with debug_lock:\n+ debugger(frames, thread_id, **kwargs)\n+\n+ if ordered:\n+ effect = debugging.DebugEffect.ORDERED_PRINT\n+ else:\n+ effect = debugging.DebugEffect.PRINT\n+ debugging.debug_callback(_breakpoint_callback, effect, *flat_args)\n" } ]
Python
Apache License 2.0
google/jax
Add colab debugger
260,411
19.07.2022 08:19:22
-7,200
c45fe49821961d3025614b0917b5c0010c245a65
[dynamic-shapes] Add typechecking rule for reshape
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3187,6 +3187,20 @@ def _reshape_shape_rule(operand, *, new_sizes, dimensions):\nraise TypeError(msg.format(dimensions, np.shape(operand)))\nreturn tuple(new_sizes)\n+def _reshape_typecheck_rule(operand, *dyn_shape, new_sizes, dimensions):\n+ if not dyn_shape:\n+ out_aval, effects = reshape_p.abstract_eval(\n+ operand.aval, new_sizes=new_sizes, dimensions=dimensions)\n+ return [out_aval], effects\n+ else:\n+ # TODO(mattjj, necula): perform more checks like _reshape_shape_rule\n+ out_shape = _merge_dyn_shape(new_sizes, dyn_shape)\n+ out_shape = [x.val if type(x) is core.Literal else x for x in out_shape]\n+ out_aval = core.DShapedArray(tuple(out_shape), operand.aval.dtype,\n+ operand.aval.weak_type)\n+ return [out_aval], core.no_effects\n+\n+\ndef _reshape_dtype_rule(operand, *, new_sizes, dimensions):\nreturn operand.dtype\n@@ -3251,6 +3265,7 @@ ad.deflinear2(reshape_p, _reshape_transpose_rule)\nbatching.primitive_batchers[reshape_p] = _reshape_batch_rule\nmasking.masking_rules[reshape_p] = _reshape_masking_rule\nmlir.register_lowering(reshape_p, _reshape_lower)\n+core.custom_typechecks[reshape_p] = _reshape_typecheck_rule\npe.custom_staging_rules[reshape_p] = _reshape_staging_rule\n" }, { "change_type": "MODIFY", "old_path": "tests/dynamic_api_test.py", "new_path": "tests/dynamic_api_test.py", "diff": "@@ -629,7 +629,7 @@ class DynamicShapeTest(jtu.JaxTestCase):\nf(np.ones((5, 4), dtype=np.float32))\n# TODO: add assertions\n- @unittest.skip('TODO: need typechecking rule for reshape')\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\ndef test_reshape(self):\n@partial(jax.jit, abstracted_axes=({0: 'n'},))\ndef f(x): # x: f32[n, 4]\n@@ -638,7 +638,7 @@ class DynamicShapeTest(jtu.JaxTestCase):\nf(np.ones((5, 4), dtype=np.float32))\n# TODO: add assertions\n- @unittest.skip('TODO: need typechecking rule for reshape')\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\ndef test_nested(self):\n@jax.jit\ndef nested_f(x): # f32[h, v] -> f32[h, v]\n@@ -651,7 +651,7 @@ class DynamicShapeTest(jtu.JaxTestCase):\nf(np.ones((3, 5), dtype=np.float32))\n# TODO: add assertions\n- @unittest.skip('TODO: need typechecking rule for reshape')\n+ @unittest.skipIf(jtu.device_under_test() != 'iree', \"iree test\")\ndef test_nested_arange(self):\ndef nested_f(x): # f32[h, v] -> f32[h, v]\n# A nested call that needs to compute with shapes\n" } ]
Python
Apache License 2.0
google/jax
[dynamic-shapes] Add typechecking rule for reshape
260,419
19.07.2022 11:13:32
18,000
7589c6d7f0e67767e6a0e2b20da75f28bfb8ff35
Fix MultiProcessGpuTest test Since MultiProcessGpuTest was using 'shell=True', only the first element of the args was executed (i.e. python). Therefore the spawn processes never executed jax code. Fix the test and make sure 'jax.distributed' initialize by checking jax.device_count().
[ { "change_type": "MODIFY", "old_path": "tests/distributed_test.py", "new_path": "tests/distributed_test.py", "diff": "@@ -93,16 +93,20 @@ class MultiProcessGpuTest(jtu.JaxTestCase):\nargs = [\nsys.executable,\n\"-c\",\n- ('\"import jax, os; '\n+ ('import jax, os; '\n'jax.distributed.initialize('\n- 'f\"localhost:{os.environ[\"JAX_PORT\"]}\", '\n- 'os.environ[\"NUM_TASKS\"], os.environ[\"TASK\"])\"'\n+ 'f\\'localhost:{os.environ[\"JAX_PORT\"]}\\', '\n+ 'int(os.environ[\"NUM_TASKS\"]), int(os.environ[\"TASK\"])); '\n+ 'print(f\\'{jax.local_device_count()},{jax.device_count()}\\', end=\"\")'\n)\n]\n- subprocesses.append(subprocess.Popen(args, env=env, shell=True))\n+ subprocesses.append(subprocess.Popen(args, env=env, stdout=subprocess.PIPE,\n+ stderr=subprocess.PIPE, universal_newlines=True))\n- for i in range(num_tasks):\n- self.assertEqual(subprocesses[i].wait(), 0)\n+ for proc in subprocesses:\n+ out, _ = proc.communicate()\n+ self.assertEqual(proc.returncode, 0)\n+ self.assertEqual(out, f'{num_gpus_per_task},{num_gpus}')\nif __name__ == \"__main__\":\n" } ]
Python
Apache License 2.0
google/jax
Fix MultiProcessGpuTest test Since MultiProcessGpuTest was using 'shell=True', only the first element of the args was executed (i.e. python). Therefore the spawn processes never executed jax code. Fix the test and make sure 'jax.distributed' initialize by checking jax.device_count().
260,335
19.07.2022 08:54:28
25,200
e35089437127654fa0fb5ad42f1e095e580f8b2e
remove resnet50 example
[ { "change_type": "MODIFY", "old_path": "examples/examples_test.py", "new_path": "examples/examples_test.py", "diff": "import os\nimport sys\n-import unittest\nimport zlib\nfrom absl.testing import absltest\n@@ -23,14 +22,12 @@ from absl.testing import parameterized\nimport numpy as np\n-import jax\nfrom jax import lax\nfrom jax import random\nimport jax.numpy as jnp\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom examples import kernel_lsq\n-from examples import resnet50\nsys.path.pop()\nfrom jax.config import config\n@@ -49,36 +46,6 @@ class ExamplesTest(parameterized.TestCase):\ndef setUp(self):\nself.rng = np.random.default_rng(zlib.adler32(self.__class__.__name__.encode()))\n- @parameterized.named_parameters(\n- {\"testcase_name\": f\"_input_shape={input_shape}\",\n- \"input_shape\": input_shape}\n- for input_shape in [(2, 20, 25, 2)])\n- @unittest.skipIf(config.x64_enabled, \"skip in x64 mode\")\n- def testIdentityBlockShape(self, input_shape):\n- init_fun, apply_fun = resnet50.IdentityBlock(2, (4, 3))\n- _CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n-\n- @parameterized.named_parameters(\n- {\"testcase_name\": f\"_input_shape={input_shape}\",\n- \"input_shape\": input_shape}\n- for input_shape in [(2, 20, 25, 3)])\n- @unittest.skipIf(config.x64_enabled, \"skip in x64 mode\")\n- def testConvBlockShape(self, input_shape):\n- init_fun, apply_fun = resnet50.ConvBlock(3, (2, 3, 4))\n- _CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n-\n- @parameterized.named_parameters(\n- {\"testcase_name\": \"_num_classes={}_input_shape={}\"\n- .format(num_classes, input_shape),\n- \"num_classes\": num_classes, \"input_shape\": input_shape}\n- for num_classes in [5, 10]\n- for input_shape in [(224, 224, 3, 2)])\n- @unittest.skipIf(config.x64_enabled, \"skip in x64 mode\")\n- @jax.numpy_rank_promotion(\"allow\") # Uses stax, which exercises implicit rank promotion.\n- def testResNet50Shape(self, num_classes, input_shape):\n- init_fun, apply_fun = resnet50.ResNet50(num_classes)\n- _CheckShapeAgreement(self, init_fun, apply_fun, input_shape)\n-\ndef testKernelRegressionGram(self):\nn, d = 100, 20\nxs = self.rng.normal(size=(n, d))\n" }, { "change_type": "DELETE", "old_path": "examples/resnet50.py", "new_path": null, "diff": "-# Copyright 2018 Google LLC\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-\"\"\"A mock-up showing a ResNet50 network with training on synthetic data.\n-\n-This file uses the stax neural network definition library and the optimizers\n-optimization library.\n-\"\"\"\n-\n-import numpy.random as npr\n-\n-import jax.numpy as jnp\n-from jax import jit, grad, random\n-from jax.example_libraries import optimizers\n-from jax.example_libraries import stax\n-from jax.example_libraries.stax import (AvgPool, BatchNorm, Conv, Dense,\n- FanInSum, FanOut, Flatten, GeneralConv,\n- Identity, MaxPool, Relu, LogSoftmax)\n-\n-\n-# ResNet blocks compose other layers\n-\n-def ConvBlock(kernel_size, filters, strides=(2, 2)):\n- ks = kernel_size\n- filters1, filters2, filters3 = filters\n- Main = stax.serial(\n- Conv(filters1, (1, 1), strides), BatchNorm(), Relu,\n- Conv(filters2, (ks, ks), padding='SAME'), BatchNorm(), Relu,\n- Conv(filters3, (1, 1)), BatchNorm())\n- Shortcut = stax.serial(Conv(filters3, (1, 1), strides), BatchNorm())\n- return stax.serial(FanOut(2), stax.parallel(Main, Shortcut), FanInSum, Relu)\n-\n-\n-def IdentityBlock(kernel_size, filters):\n- ks = kernel_size\n- filters1, filters2 = filters\n- def make_main(input_shape):\n- # the number of output channels depends on the number of input channels\n- return stax.serial(\n- Conv(filters1, (1, 1)), BatchNorm(), Relu,\n- Conv(filters2, (ks, ks), padding='SAME'), BatchNorm(), Relu,\n- Conv(input_shape[3], (1, 1)), BatchNorm())\n- Main = stax.shape_dependent(make_main)\n- return stax.serial(FanOut(2), stax.parallel(Main, Identity), FanInSum, Relu)\n-\n-\n-# ResNet architectures compose layers and ResNet blocks\n-\n-def ResNet50(num_classes):\n- return stax.serial(\n- GeneralConv(('HWCN', 'OIHW', 'NHWC'), 64, (7, 7), (2, 2), 'SAME'),\n- BatchNorm(), Relu, MaxPool((3, 3), strides=(2, 2)),\n- ConvBlock(3, [64, 64, 256], strides=(1, 1)),\n- IdentityBlock(3, [64, 64]),\n- IdentityBlock(3, [64, 64]),\n- ConvBlock(3, [128, 128, 512]),\n- IdentityBlock(3, [128, 128]),\n- IdentityBlock(3, [128, 128]),\n- IdentityBlock(3, [128, 128]),\n- ConvBlock(3, [256, 256, 1024]),\n- IdentityBlock(3, [256, 256]),\n- IdentityBlock(3, [256, 256]),\n- IdentityBlock(3, [256, 256]),\n- IdentityBlock(3, [256, 256]),\n- IdentityBlock(3, [256, 256]),\n- ConvBlock(3, [512, 512, 2048]),\n- IdentityBlock(3, [512, 512]),\n- IdentityBlock(3, [512, 512]),\n- AvgPool((7, 7)), Flatten, Dense(num_classes), LogSoftmax)\n-\n-\n-if __name__ == \"__main__\":\n- rng_key = random.PRNGKey(0)\n-\n- batch_size = 8\n- num_classes = 1001\n- input_shape = (224, 224, 3, batch_size)\n- step_size = 0.1\n- num_steps = 10\n-\n- init_fun, predict_fun = ResNet50(num_classes)\n- _, init_params = init_fun(rng_key, input_shape)\n-\n- def loss(params, batch):\n- inputs, targets = batch\n- logits = predict_fun(params, inputs)\n- return -jnp.sum(logits * targets)\n-\n- def accuracy(params, batch):\n- inputs, targets = batch\n- target_class = jnp.argmax(targets, axis=-1)\n- predicted_class = jnp.argmax(predict_fun(params, inputs), axis=-1)\n- return jnp.mean(predicted_class == target_class)\n-\n- def synth_batches():\n- rng = npr.RandomState(0)\n- while True:\n- images = rng.rand(*input_shape).astype('float32')\n- labels = rng.randint(num_classes, size=(batch_size, 1))\n- onehot_labels = labels == jnp.arange(num_classes)\n- yield images, onehot_labels\n-\n- opt_init, opt_update, get_params = optimizers.momentum(step_size, mass=0.9)\n- batches = synth_batches()\n-\n- @jit\n- def update(i, opt_state, batch):\n- params = get_params(opt_state)\n- return opt_update(i, grad(loss)(params, batch), opt_state)\n-\n- opt_state = opt_init(init_params)\n- for i in range(num_steps):\n- opt_state = update(i, opt_state, next(batches))\n- trained_params = get_params(opt_state)\n" } ]
Python
Apache License 2.0
google/jax
remove resnet50 example
260,411
19.07.2022 15:05:22
-7,200
2106d65561d42db84943406ff26e7d6a3a463e18
[dynamic-shapes] Add check that --jax_dynamic_shapes is set when using abstracted_axes. abstracted_axes has no effect without the --jax_dynamic_shapes. Make this and explicit error.
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -334,6 +334,8 @@ def jit(\n>>> g(jnp.arange(4), 3)\nDeviceArray([ 0, 1, 256, 6561], dtype=int32)\n\"\"\"\n+ if abstracted_axes and not config.jax_dynamic_shapes:\n+ raise ValueError(\"abstracted_axes must be used with --jax_dynamic_shapes\")\nif FLAGS.experimental_cpp_jit and not config.jax_dynamic_shapes:\nreturn _jit(True, fun, static_argnums, static_argnames, device, backend,\ndonate_argnums, inline, keep_unused)\n@@ -642,6 +644,8 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\nflat_fun = lu.annotate(flat_fun, in_type)\nin_avals = [aval for aval, explicit in in_type if explicit]\nelse:\n+ if abstracted_axes:\n+ raise ValueError(\"abstracted_axes must be used with --jax_dynamic_shapes\")\nin_avals, _ = unzip2(arg_specs_and_devices)\ncomputation = dispatch.lower_xla_callable(\nflat_fun, device, backend, flat_fun.__name__, donated_invars, True,\n" } ]
Python
Apache License 2.0
google/jax
[dynamic-shapes] Add check that --jax_dynamic_shapes is set when using abstracted_axes. abstracted_axes has no effect without the --jax_dynamic_shapes. Make this and explicit error.
260,335
19.07.2022 16:36:38
25,200
7cb5c2447ed698a4dbdc7b46246279794ec1f041
[dynamic-shapes] fix minor bint bugs
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1561,7 +1561,9 @@ raise_to_shaped_mappings : Dict[type, Callable] = {\nBot: lambda aval, _: aval,\nUnshapedArray: lambda aval, _: aval,\nShapedArray: lambda aval, weak_type: ShapedArray(\n- aval.shape, aval.dtype, weak_type, aval.named_shape)\n+ aval.shape, aval.dtype, weak_type, aval.named_shape),\n+ DConcreteArray: lambda aval, weak_type: DShapedArray(\n+ aval.shape, aval.dtype, weak_type),\n}\n### Operations on shapes and dimension sizes.\n" }, { "change_type": "MODIFY", "old_path": "jax/linear_util.py", "new_path": "jax/linear_util.py", "diff": "@@ -245,7 +245,7 @@ def annotate(f: WrappedFun,\nassert (type(in_type) is tuple and all(type(e) is tuple for e in in_type) and\nall(isinstance(a, core.AbstractValue) and type(b) is bool\nand not isinstance(a, core.ConcreteArray) for a, b in in_type) and\n- all(isinstance(d, (int, core.DBIdx)) for a, _ in in_type\n+ all(isinstance(d, (int, core.BInt, core.DBIdx)) for a, _ in in_type\nif type(a) is core.DShapedArray for d in a.shape))\nprovided = [e for _, e in in_type]\nfor aval, _ in in_type:\n" }, { "change_type": "MODIFY", "old_path": "tests/dynamic_api_test.py", "new_path": "tests/dynamic_api_test.py", "diff": "@@ -1213,6 +1213,16 @@ class DynamicShapeTest(jtu.JaxTestCase):\nself.assertEqual(y, 6)\nself.assertEqual(count, 2)\n+ def test_bint_add(self):\n+ d = lax.make_bint(4, 6)\n+ x = jnp.arange(d)\n+\n+ @jax.jit\n+ def f(x):\n+ return x + x\n+\n+ f(x) # doesn't crash\n+\ndef test_lower_abstracted_axes(self):\n@partial(jax.jit, abstracted_axes=('n',))\ndef f(x):\n" } ]
Python
Apache License 2.0
google/jax
[dynamic-shapes] fix minor bint bugs Co-authored-by: Eugene Burmako <burmako@google.com>
260,569
20.07.2022 18:57:12
-32,400
9f770425ac8afce354ce7201cb5aaafede6526a7
Correct spelling on word
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1051,7 +1051,7 @@ def bincount(x, weights=None, minlength=0, *, length=None):\n\"The error occurred because of argument 'minlength' of jnp.bincount.\")\nif length is None:\nx = core.concrete_or_error(asarray, x,\n- \"The error occured because of argument 'x' of jnp.bincount. \"\n+ \"The error occurred because of argument 'x' of jnp.bincount. \"\n\"To avoid this error, pass a static `length` argument.\")\nlength = _max(minlength, x.size and x.max() + 1)\nelse:\n@@ -2144,9 +2144,9 @@ def _wrap_numpy_nullary_function(f):\n\"\"\"\n@_wraps(f, update_doc=False)\ndef wrapper(*args, **kwargs):\n- args = [core.concrete_or_error(None, arg, f\"the error occured in argument {i} jnp.{f.__name__}()\")\n+ args = [core.concrete_or_error(None, arg, f\"the error occurred in argument {i} jnp.{f.__name__}()\")\nfor i, arg in enumerate(args)]\n- kwargs = {key: core.concrete_or_error(None, val, f\"the error occured in argument '{key}' jnp.{f.__name__}()\")\n+ kwargs = {key: core.concrete_or_error(None, val, f\"the error occurred in argument '{key}' jnp.{f.__name__}()\")\nfor key, val in kwargs.items()}\nreturn asarray(f(*args, **kwargs))\nreturn wrapper\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/optimize/minimize.py", "new_path": "jax/_src/scipy/optimize/minimize.py", "diff": "@@ -30,7 +30,7 @@ class OptimizeResults(NamedTuple):\nfun: final function value.\njac: final jacobian array.\nhess_inv: final inverse Hessian estimate.\n- nfev: integer number of funcation calls used.\n+ nfev: integer number of function calls used.\nnjev: integer number of gradient evaluations.\nnit: integer number of iterations of the optimization algorithm.\n\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/test_util.py", "new_path": "jax/_src/test_util.py", "diff": "@@ -238,7 +238,7 @@ def is_device_cuda():\nreturn xla_bridge.get_backend().platform_version.startswith('cuda')\ndef _get_device_tags():\n- \"\"\"returns a set of tags definded for the device under test\"\"\"\n+ \"\"\"returns a set of tags defined for the device under test\"\"\"\nif is_device_rocm():\ndevice_tags = {device_under_test(), \"rocm\"}\nelif is_device_cuda():\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcoo.py", "new_path": "jax/experimental/sparse/bcoo.py", "diff": "@@ -1795,7 +1795,7 @@ def bcoo_reduce_sum(mat, *, axes):\nmat: A BCOO-format array.\nshape: The shape of the target array.\naxes: A tuple or list or ndarray which contains axes of ``mat`` over which\n- sum is perfomed.\n+ sum is performed.\nReturns:\nA BCOO-format array containing the result.\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1566,7 +1566,7 @@ class DynamicJaxprTracer(core.Tracer):\nif len(progenitor_eqns) > 5:\norigin += \"\\n\\n(Additional originating lines are not shown.)\"\nelse:\n- origin = (f\"The error occured while tracing the function {dbg.func_src_info} \"\n+ origin = (f\"The error occurred while tracing the function {dbg.func_src_info} \"\nf\"for {dbg.traced_for}.\")\nreturn \"\\n\" + origin\n" }, { "change_type": "MODIFY", "old_path": "tests/dtypes_test.py", "new_path": "tests/dtypes_test.py", "diff": "@@ -439,7 +439,7 @@ class TestPromotionTables(jtu.JaxTestCase):\nvals = [typecode_to_val(t) for t in typecodes]\ntable = [[val_to_typecode(v1 + v2) for v1 in vals] for v2 in vals]\n- def show_differences(epected, actual):\n+ def show_differences(expected, actual):\ndiffs = \"\"\nfor i, t1 in enumerate(typecodes):\nfor j, t2 in enumerate(typecodes):\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -1419,7 +1419,7 @@ class PythonPmapTest(jtu.JaxTestCase):\n# output = [[0, 4], [2, 6], [1, 5], [3, 7]]\n#\n# This is essentially like splitting the number of rows in the input in two\n- # groups of rows, and swaping the two inner axes (axis=1 and axis=2), which\n+ # groups of rows, and swapping the two inner axes (axis=1 and axis=2), which\n# is exactly what the test case checks.\ndevice_count = jax.device_count()\nif device_count % 2 != 0:\n" } ]
Python
Apache License 2.0
google/jax
Correct spelling on word
260,406
20.07.2022 11:49:52
25,200
38f74ad66692c779a07c56a067148457a56bbccb
Add wait_until_finished to GDA deserialization
[ { "change_type": "MODIFY", "old_path": "jax/experimental/gda_serialization/serialization.py", "new_path": "jax/experimental/gda_serialization/serialization.py", "diff": "@@ -439,5 +439,6 @@ class GlobalAsyncCheckpointManager(AsyncManager, GlobalAsyncCheckpointManagerBas\ndef deserialize(self, global_meshes, mesh_axes, tensorstore_specs,\nglobal_shapes=None, dtypes=None):\n+ self.wait_until_finished()\nreturn run_deserialization(global_meshes, mesh_axes, tensorstore_specs,\nglobal_shapes, dtypes)\n" } ]
Python
Apache License 2.0
google/jax
Add wait_until_finished to GDA deserialization
260,411
21.07.2022 17:01:20
-7,200
6c9d2a0b543f3aef8a8422b18c4fe4112d82787a
[jax2tf] Raise errors for experimental_native_lowering and custom_call Raise explicit error when the experimental_native_lowering encounters a mhlo.custom_call. This would lead to failure when trying to run in TF.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -52,6 +52,7 @@ from jax._src.lax import lax as lax_internal\nfrom jax._src.lax import linalg as lax_linalg\nfrom jax._src.lax import slicing as lax_slicing\nfrom jax._src.lax import windowed_reductions as lax_windowed_reductions\n+from jax._src import lib as jaxlib\nfrom jax._src.lib import xla_client\nfrom jax.experimental.jax2tf import shape_poly\n@@ -609,6 +610,24 @@ def _lower_native(fun: lu.WrappedFun, in_vals: Sequence[TfVal],\nmhlo_module = lowered.mhlo()\nmhlo_module_text = mlir.module_to_string(mhlo_module)\n+ if jaxlib.version <= (0, 3, 14):\n+ mhlo_module_text = _fixup_mhlo_module_text(mhlo_module_text)\n+ # We do not support custom_call, try to give an error for now\n+ if \"mhlo.custom_call\" in mhlo_module_text:\n+ # Try to give a nice error message. We could just dump the module...\n+ msg = (\"experimental_native_lowering does not work with custom calls. \"\n+ \"Most likely you are running this on CPU or GPU for JAX programs that \"\n+ \"use custom calls on those platforms. The serialization should \"\n+ \"work on TPU.\")\n+ custom_calls = re.findall(r'mhlo.custom_call.*call_target_name\\s+=\\s+\"([^\"]+)\".*loc\\(([^\\)]+)\\)',\n+ mhlo_module_text)\n+ for cc in custom_calls:\n+ msg += f\"\\n{cc[0]}\"\n+ # Get the line number\n+ m = re.search('^' + cc[1] + ' =.*', mhlo_module_text, re.MULTILINE)\n+ if m:\n+ msg += f\"\\n from line {m.group(0)}\"\n+ raise NotImplementedError(msg)\nlogging.vlog(2, f\"XlaCallModule {mhlo_module_text}\")\n# Figure out the result types and shapes\n@@ -645,6 +664,14 @@ def _lower_native(fun: lu.WrappedFun, in_vals: Sequence[TfVal],\nfor res_val, out_aval in zip(res, out_avals))\nreturn zip(res, out_avals)\n+def _fixup_mhlo_module_text(mhlo_module_text: str) -> str:\n+ # A workaround for MHLO not (yet) having backwards compatibility. With\n+ # jaxlib 0.3.14 we have an old serialization method that puts \"...\" around\n+ # MHLO attributes. The parser is new and does not accept those attributes.\n+ # We try to fix it up here, temporarily.\n+ import re\n+ return re.sub(r'#mhlo<\"([^\"]+)\">', \"#mhlo<\\\\1>\", mhlo_module_text)\n+\ndef _call_wrapped_with_new_constant_cache(fun: lu.WrappedFun,\nin_vals: Sequence[TfVal],\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -36,6 +36,7 @@ from jax.experimental import jax2tf\nfrom jax.experimental.jax2tf.tests import tf_test_util\nimport jax.interpreters.mlir as mlir\nfrom jax._src import source_info_util\n+from jax._src import lib as jaxlib\nimport jax._src.lib.xla_bridge\nimport numpy as np\n@@ -1245,6 +1246,8 @@ def get_serialized_computation(\nlowered = jax.jit(f_jax, abstracted_axes=abstracted_axes).lower(*args)\nmhlo_module = lowered.compiler_ir(dialect='mhlo')\nmhlo_module_text = mlir.module_to_string(mhlo_module)\n+ if jaxlib.version <= (0, 3, 14):\n+ mhlo_module_text = jax2tf.jax2tf._fixup_mhlo_module_text(mhlo_module_text)\nlogging.info(f'Serialized ir.Module = {mhlo_module_text}')\nreturn mhlo_module_text\n@@ -1266,7 +1269,6 @@ class XlaCallModuleTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(tf.nest.map_structure(lambda t: t.numpy(), res),\n[jax_res])\n- @unittest.skip(\"TODO(necula): Cannot deserialize MHLO computation\")\ndef test_while(self):\n# With nested computation\ndef f_jax(count, x):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitives_test.py", "new_path": "jax/experimental/jax2tf/tests/primitives_test.py", "diff": "@@ -56,6 +56,7 @@ import os\nfrom typing import Any, Dict, Tuple\nimport unittest\n+from absl import logging\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -101,7 +102,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(\nprimitive_harness.all_harnesses,\ninclude_jax_unimpl=False,\n- #one_containing=\"conv_general_dilated_dtype_precision_lhs=float16[2,3,9,10]_rhs=float16[3,3,4,5]_windowstrides=(1,1)_padding=((0,0),(0,0))_lhsdilation=(1,1)_rhsdilation=(1,1)_dimensionnumbers=('NCHW','OIHW','NCHW')_featuregroupcount=1_batchgroupcount=1_precision=DEFAULT_preferred=float64_enablexla=True\"\n+ #one_containing=\"custom_linear_solve_\"\n)\n@jtu.ignore_warning(\ncategory=UserWarning, message=\"Using reduced precision for gradient.*\")\n@@ -113,10 +114,17 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nfunc_jax = harness.dyn_fun\nargs = harness.dyn_args_maker(self.rng())\nenable_xla = harness.params.get(\"enable_xla\", True)\n+ if config.jax2tf_default_experimental_native_lowering and not enable_xla:\n+ return\nassociative_scan_reductions = harness.params.get(\"associative_scan_reductions\", False)\n+ try:\nwith jax.jax2tf_associative_scan_reductions(associative_scan_reductions):\nself.ConvertAndCompare(func_jax, *args, limitations=limitations,\nenable_xla=enable_xla)\n+ except Exception as e:\n+ if (config.jax2tf_default_experimental_native_lowering and\n+ \"does not work with custom calls\" in str(e)):\n+ logging.warning(\"Supressing error %s\", e)\ndef test_primitive_coverage(self):\n\"\"\"Fail if there are JAX primitives that are not implemented.\"\"\"\n@@ -139,6 +147,9 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nfor p in all_primitives:\nif p.name == \"axis_index\":\ncontinue\n+ # TODO: remove once we delete sharded_jit.py\n+ if p.name in [\"sharded_call\", \"sharding_constraint\"]:\n+ continue\n# TODO: Remove once tensorflow is 2.10.0 everywhere.\nif p.name == \"optimization_barrier\":\ncontinue\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Raise errors for experimental_native_lowering and custom_call Raise explicit error when the experimental_native_lowering encounters a mhlo.custom_call. This would lead to failure when trying to run in TF.
260,510
21.07.2022 11:22:54
25,200
d6c172d53e06483d24dba767edf667a93d89757e
Fix PE not allowing double JIT-ted effectful functions
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_checkpoint.py", "new_path": "jax/_src/ad_checkpoint.py", "diff": "@@ -280,8 +280,6 @@ def remat_impl(*args, jaxpr, prevent_cse, differentiated, policy):\n@remat_p.def_effectful_abstract_eval\ndef remat_abstract_eval(*args, jaxpr, prevent_cse, differentiated, policy):\ndel args, prevent_cse, differentiated, policy # Unused.\n- if jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `remat`.')\nreturn [v.aval for v in jaxpr.outvars], jaxpr.effects\ndef remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\n@@ -303,6 +301,9 @@ ad.primitive_jvps[remat_p] = remat_jvp\ndef remat_partial_eval(trace, *tracers, jaxpr, **params):\nassert not jaxpr.constvars\n+ if jaxpr.effects:\n+ raise NotImplementedError(\n+ 'Effects not supported in partial-eval of `checkpoint`/`remat`.')\npolicy = params['policy'] or nothing_saveable\nin_unknowns = [not t.is_known() for t in tracers]\njaxpr_known, jaxpr_staged, out_unknowns, out_inst, num_res = \\\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -1071,9 +1071,10 @@ def _call_lowering(fn_name, stack_name, call_jaxpr, backend, ctx, avals_in,\nif isinstance(call_jaxpr, core.Jaxpr):\ncall_jaxpr = core.ClosedJaxpr(call_jaxpr, ())\nxla.check_backend_matches(backend, ctx.platform)\n+ effects = tokens_in.effects()\noutput_types = map(aval_to_ir_types, avals_out)\n+ output_types = [token_type()] * len(effects) + output_types\nflat_output_types = util.flatten(output_types)\n- effects = tokens_in.effects()\nsymbol_name = lower_jaxpr_to_fun(ctx, fn_name, call_jaxpr, effects).name.value\nargs = [*tokens_in.tokens(), *args]\ncall = func_dialect.CallOp(flat_output_types,\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1149,9 +1149,11 @@ def _remat_partial_eval(trace, _, f, tracers, params):\nf, aux = partial_eval_wrapper_nounits(f, tuple(in_knowns), tuple(in_avals))\nconsts = remat_call_p.bind(f, **params) # no known inputs\n_, out_avals, jaxpr, env = aux()\n+ if jaxpr.effects:\n+ raise NotImplementedError(\n+ 'Effects not supported in partial-eval of `checkpoint`/`remat`.')\nenv_tracers = map(trace.full_raise, env)\njaxpr = convert_constvars_jaxpr(jaxpr)\n- if jaxpr.effects: raise NotImplementedError\ndel in_pvals, in_knowns, in_avals, out_avals, f, aux, env\n# When concrete=True, we could avoid some redundant computation by extracting\n# values from any ConcreteArrays in `out_avals`, but we eschew that\n@@ -1823,8 +1825,6 @@ class DynamicJaxprTrace(core.Trace):\nelse:\njaxpr, out_type, consts = trace_to_subjaxpr_dynamic2_memoized(\nf, self.main).val\n- if jaxpr.effects:\n- raise NotImplementedError('Effects not supported for call primitives.')\nif params.get('inline', False):\nreturn core.eval_jaxpr(jaxpr, consts, *in_tracers)\nsource_info = source_info_util.current()\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -114,6 +114,17 @@ class DebugPrintTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_can_double_stage_out_ordered_print(self):\n+ @jax.jit\n+ @jax.jit\n+ def f(x):\n+ debug_print('x: {x}', x=x, ordered=True)\n+ with capture_stdout() as output:\n+ f(2)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"x: 2\\n\")\n+\n@jtu.skip_on_devices(*disabled_backends)\ndef test_can_stage_out_ordered_print_with_pytree(self):\n@jax.jit\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -25,6 +25,7 @@ from jax import core\nfrom jax import lax\nfrom jax import linear_util as lu\nfrom jax.config import config\n+from jax.interpreters import ad\nfrom jax.experimental import maps\nfrom jax.experimental import pjit\nfrom jax.interpreters import mlir\n@@ -41,8 +42,12 @@ effect_p = core.Primitive('effect')\neffect_p.multiple_results = True\n@effect_p.def_effectful_abstract_eval\n-def _(*, effect):\n- return [], {effect}\n+def _(*avals, effect):\n+ return avals, {effect}\n+\n+def effect_jvp_rule(primals, tangents, effect):\n+ return effect_p.bind(*primals, effect=effect), tangents\n+ad.primitive_jvps[effect_p] = effect_jvp_rule\nmlir.lowerable_effects.add('foo')\nmlir.lowerable_effects.add('foo2')\n@@ -189,7 +194,6 @@ class HigherOrderPrimitiveTest(jtu.JaxTestCase):\neffect_p.bind(effect='bar')\nreturn [x]\nreturn core.call(f_, x)[0]\n- with self.assertRaisesRegex(NotImplementedError, 'Effects not supported'):\njax.make_jaxpr(f)(2.)\ndef test_xla_call_primitive_inherits_effects(self):\n@@ -199,7 +203,6 @@ class HigherOrderPrimitiveTest(jtu.JaxTestCase):\neffect_p.bind(effect='foo')\neffect_p.bind(effect='bar')\nreturn x\n- with self.assertRaisesRegex(NotImplementedError, 'Effects not supported'):\njax.make_jaxpr(f)(2.)\n@parameterized.named_parameters(jtu.cases_from_list(\n@@ -210,11 +213,12 @@ class HigherOrderPrimitiveTest(jtu.JaxTestCase):\n@remat\ndef f(x):\n- effect_p.bind(effect='foo')\n- effect_p.bind(effect='bar')\n+ x, = effect_p.bind(x, effect='foo')\n+ x, = effect_p.bind(x, effect='bar')\nreturn x\n- with self.assertRaisesRegex(NotImplementedError, 'Effects not supported'):\njax.make_jaxpr(f)(2.)\n+ with self.assertRaisesRegex(NotImplementedError, \"Effects not supported\"):\n+ jax.make_jaxpr(lambda x: jax.linearize(f, x)[1](x))(2.)\ndef test_custom_jvp_primitive_inherits_effects(self):\n" } ]
Python
Apache License 2.0
google/jax
Fix PE not allowing double JIT-ted effectful functions
260,510
21.07.2022 20:21:38
25,200
4870710891dc6f03b18f019eee6f41956f6b91d5
Enable debugging callbacks with pjit on TPU
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1393,8 +1393,8 @@ def _xmap_lowering_rule_replica(ctx, *in_nodes,\nsub_ctx = ctx.module_context.replace(\nname_stack=xla.extend_name_stack(ctx.module_context.name_stack,\nwrap_name(name, 'xmap')))\n- if vectorized_jaxpr.effects:\n- raise NotImplementedError('Cannot lower effectful `xmap`')\n+ if any(eff in core.ordered_effects for eff in vectorized_jaxpr.effects):\n+ raise NotImplementedError('Cannot lower `xmap` with ordered effects.')\ntiled_outs, _ = mlir.jaxpr_subcomp(sub_ctx, vectorized_jaxpr, mlir.TokenSet(), (), *tiled_ins)\nouts = [\n@@ -1458,8 +1458,8 @@ def _xmap_lowering_rule_spmd(ctx, *global_in_nodes,\nsub_ctx = ctx.module_context.replace(\nname_stack=xla.extend_name_stack(ctx.module_context.name_stack,\nwrap_name(name, 'xmap')))\n- if vectorized_jaxpr.effects:\n- raise NotImplementedError('Cannot lower effectful `xmap`')\n+ if any(eff in core.ordered_effects for eff in vectorized_jaxpr.effects):\n+ raise NotImplementedError('Cannot lower `xmap` with ordered effects.')\nglobal_out_nodes, _ = mlir.jaxpr_subcomp(sub_ctx, vectorized_jaxpr,\nmlir.TokenSet(), (), *sharded_global_in_nodes)\n@@ -1509,8 +1509,8 @@ def _xmap_lowering_rule_spmd_manual(ctx, *global_in_nodes,\nname_stack=xla.extend_name_stack(ctx.module_context.name_stack,\nwrap_name(name, 'xmap')),\naxis_context=ctx.module_context.axis_context.extend_manual(manual_mesh_axes))\n- if vectorized_jaxpr.effects:\n- raise NotImplementedError('Cannot lower effectful `xmap`')\n+ if any(eff in core.ordered_effects for eff in vectorized_jaxpr.effects):\n+ raise NotImplementedError('Cannot lower `xmap` with ordered effects.')\nglobal_out_nodes, _ = mlir.jaxpr_subcomp(sub_ctx, vectorized_jaxpr,\nmlir.TokenSet(), (), *([n] for n in global_in_nodes))\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -1352,7 +1352,8 @@ def _dtype_to_xla_type_string(dtype: np.dtype) -> str:\nreturn _dtype_to_xla_type_string_map[dtype]\ndef send_to_host(channel: int, token: mhlo.TokenType, operand: Any,\n- aval: core.ShapedArray, name: str) -> ir.Value:\n+ aval: core.ShapedArray, name: str, *,\n+ sharding: Optional[xc.OpSharding] = None) -> ir.Value:\nchannel_handle = mhlo.ChannelHandle.get(channel, SEND_TO_HOST_TYPE)\nsend_op = mhlo.SendOp(mhlo.TokenType.get(), [operand], token, channel_handle,\nis_host_transfer=ir.BoolAttr.get(True))\n@@ -1364,11 +1365,14 @@ def send_to_host(channel: int, token: mhlo.TokenType, operand: Any,\n_xla_host_transfer_handler_name=ir.StringAttr.get(str(name)),\n_xla_host_transfer_original_type=ir.StringAttr.get(dtype_str),\n_xla_host_transfer_rendezvous=ir.StringAttr.get(str(name))))\n+ if sharding is not None:\n+ set_sharding(send_op, sharding)\nreturn send_op.result\ndef receive_from_host(channel: int, token: mhlo.TokenType,\n- out_aval: core.ShapedArray, name: str) -> ir.Value:\n+ out_aval: core.ShapedArray, name: str, *,\n+ sharding: Optional[xc.OpSharding] = None) -> ir.Value:\nchannel_handle = mhlo.ChannelHandle.get(channel, RECV_FROM_HOST_TYPE)\nrecv_op = mhlo.RecvOp([aval_to_ir_type(out_aval),\nmhlo.TokenType.get()], token, channel_handle,\n@@ -1381,6 +1385,8 @@ def receive_from_host(channel: int, token: mhlo.TokenType,\n_xla_host_transfer_handler_name=ir.StringAttr.get(str(name)),\n_xla_host_transfer_original_type=ir.StringAttr.get(dtype_str),\n_xla_host_transfer_rendezvous=ir.StringAttr.get(str(name))))\n+ if sharding is not None:\n+ set_sharding(recv_op, sharding)\n# Token should be at the end of the results\nresult, token = recv_op.results\nreturn token, result\n@@ -1410,10 +1416,19 @@ def emit_python_callback(\n\"Callback with return values not supported on TPU.\")\ntoken = token or mhlo.CreateTokenOp(mhlo.TokenType.get()).result\nsend_channels = []\n+ if isinstance(ctx.module_context.axis_context,\n+ (SPMDAxisContext, ShardingContext)):\n+ # Apply maximal sharding so pjit only executes the callback on device 0.\n+ sharding = xc.OpSharding()\n+ sharding.type = xc.OpSharding.Type.MAXIMAL\n+ sharding.tile_assignment_dimensions = [1]\n+ sharding.tile_assignment_devices = [0]\n+ else:\n+ sharding = None\nfor operand, operand_aval in zip(operands, operand_avals):\nchannel = ctx.module_context.new_channel()\ntoken = send_to_host(channel, token, operand, operand_aval,\n- callback.__name__)\n+ callback.__name__, sharding=sharding)\nsend_channels.append(channel)\nrecv_channels = []\nrecv_channel = ctx.module_context.new_channel()\n@@ -1432,7 +1447,7 @@ def emit_python_callback(\ndummy_recv_aval = core.ShapedArray((1,), np.float32)\nresult_shapes = [*result_shapes, xla.aval_to_xla_shapes(dummy_recv_aval)[0]]\ntoken, _ = receive_from_host(recv_channel, token, dummy_recv_aval,\n- callback.__name__)\n+ callback.__name__, sharding=sharding)\nrecv_channels.append(recv_channel)\nopaque = backend.make_python_callback_from_host_send_and_recv(\n_wrapped_callback, operand_shapes, result_shapes, send_channels,\n" }, { "change_type": "MODIFY", "old_path": "tests/debugger_test.py", "new_path": "tests/debugger_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\nimport io\n+import re\nimport textwrap\nimport unittest\n@@ -20,10 +21,13 @@ from typing import IO, Sequence, Tuple\nfrom absl.testing import absltest\nimport jax\nfrom jax.config import config\n+from jax.experimental import maps\n+from jax.experimental import pjit\nfrom jax._src import debugger\nfrom jax._src import lib as jaxlib\nfrom jax._src import test_util as jtu\nimport jax.numpy as jnp\n+import numpy as np\nconfig.parse_flags_with_absl()\n@@ -290,5 +294,33 @@ class CliDebuggerTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertRegex(stdout.getvalue(), expected)\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_works_with_pjit(self):\n+ if jax.default_backend() != \"tpu\":\n+ raise unittest.SkipTest(\"`pjit` doesn't work with CustomCall.\")\n+ stdin, stdout = make_fake_stdin_stdout([\"p y\", \"c\"])\n+\n+ def f(x):\n+ y = x + 1\n+ debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ return y\n+\n+ def g(x):\n+ y = f(x)\n+ return jnp.exp(y)\n+ g = pjit.pjit(g, in_axis_resources=pjit.PartitionSpec(\"dev\"),\n+ out_axis_resources=pjit.PartitionSpec(\"dev\"))\n+ with maps.Mesh(np.array(jax.devices()), [\"dev\"]):\n+ arr = (1 + np.arange(8)).astype(np.int32)\n+ expected = _format_multiline(r\"\"\"\n+ Entering jaxdb:\n+ \\(jaxdb\\) {}\n+ \\(jaxdb\\) \"\"\".format(re.escape(repr(arr))))\n+ g(jnp.arange(8, dtype=jnp.int32))\n+ jax.effects_barrier()\n+ print(stdout.getvalue())\n+ print(expected)\n+ self.assertRegex(stdout.getvalue(), expected)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -27,6 +27,7 @@ import jax\nfrom jax import lax\nfrom jax.config import config\nfrom jax.experimental import maps\n+from jax.experimental import pjit\nfrom jax._src import debugging\nfrom jax._src import lib as jaxlib\nfrom jax._src import test_util as jtu\n@@ -421,6 +422,85 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\njax.effects_barrier()\nself._assertLinesEqual(output(), \"hello: 0\\nhello: 1\\nhello: 2\\nhello: 3\\n\")\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_unordered_print_with_pjit(self):\n+ if jax.default_backend() != \"tpu\":\n+ raise unittest.SkipTest(\"`pjit` doesn't work with CustomCall.\")\n+\n+ def f(x):\n+ debug_print(\"{}\", x, ordered=False)\n+ return x\n+ f = pjit.pjit(f, in_axis_resources=pjit.PartitionSpec('dev'),\n+ out_axis_resources=pjit.PartitionSpec('dev'))\n+ with maps.Mesh(np.array(jax.devices()), ['dev']):\n+ with capture_stdout() as output:\n+ f(jnp.arange(8, dtype=jnp.int32))\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"[0 1 2 3 4 5 6 7]\\n\")\n+\n+ def f2(x):\n+ y = x.dot(x)\n+ debug_print(\"{}\", y, ordered=False)\n+ return y\n+ f2 = pjit.pjit(f2, in_axis_resources=pjit.PartitionSpec('dev'),\n+ out_axis_resources=pjit.PartitionSpec())\n+ with maps.Mesh(np.array(jax.devices()), ['dev']):\n+ with capture_stdout() as output:\n+ f2(jnp.arange(8, dtype=jnp.int32))\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"140\\n\")\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_unordered_print_of_pjit_of_while(self):\n+ if jax.default_backend() != \"tpu\":\n+ raise unittest.SkipTest(\"`pjit` doesn't work with CustomCall.\")\n+\n+ def f(x):\n+ def cond(carry):\n+ i, *_ = carry\n+ return i < 5\n+ def body(carry):\n+ i, x = carry\n+ debug_print(\"{}\", x, ordered=False)\n+ x = x + 1\n+ return (i + 1, x)\n+ return lax.while_loop(cond, body, (0, x))[1]\n+ f = pjit.pjit(f, in_axis_resources=pjit.PartitionSpec('dev'),\n+ out_axis_resources=pjit.PartitionSpec('dev'))\n+ with maps.Mesh(np.array(jax.devices()), ['dev']):\n+ with capture_stdout() as output:\n+ f(jnp.arange(8, dtype=jnp.int32))\n+ jax.effects_barrier()\n+ self.assertEqual(output(),\n+ \"[0 1 2 3 4 5 6 7]\\n\"\n+ \"[1 2 3 4 5 6 7 8]\\n\"\n+ \"[2 3 4 5 6 7 8 9]\\n\"\n+ \"[ 3 4 5 6 7 8 9 10]\\n\"\n+ \"[ 4 5 6 7 8 9 10 11]\\n\")\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_unordered_print_of_pjit_of_xmap(self):\n+ if jax.default_backend() != \"tpu\":\n+ raise unittest.SkipTest(\"`pjit` doesn't work with CustomCall.\")\n+\n+ def f(x):\n+ def foo(x):\n+ idx = lax.axis_index('foo')\n+ debug_print(\"{idx}: {x}\", idx=idx, x=x)\n+ return jnp.mean(x, axis=['foo'])\n+ out = maps.xmap(foo, in_axes=['foo'], out_axes=[...])(x)\n+ debug_print(\"Out: {}\", out)\n+ return out\n+ f = pjit.pjit(f, in_axis_resources=pjit.PartitionSpec('dev'),\n+ out_axis_resources=pjit.PartitionSpec())\n+ with maps.Mesh(np.array(jax.devices()), ['dev']):\n+ with capture_stdout() as output:\n+ f(jnp.arange(8, dtype=jnp.int32) * 2)\n+ lines = [\"0: 0\", \"1: 2\", \"2: 4\", \"3: 6\", \"4: 8\", \"5: 10\", \"6: 12\",\n+ \"7: 14\", \"Out: 7.0\", \"\"]\n+ jax.effects_barrier()\n+ self._assertLinesEqual(output(), \"\\n\".join(lines))\n+\n@jtu.skip_on_devices(*disabled_backends)\ndef test_unordered_print_with_xmap(self):\n" } ]
Python
Apache License 2.0
google/jax
Enable debugging callbacks with pjit on TPU PiperOrigin-RevId: 462527181
260,510
22.07.2022 15:30:22
25,200
fc1fa134c815a79f4abcfa63b0ec626b7384d76a
Adjust debug_callback JVP rule to only call on primals
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugging.py", "new_path": "jax/_src/debugging.py", "diff": "@@ -76,13 +76,8 @@ def debug_callback_batching_rule(args, dims, **params):\nreturn outs, (0,) * len(outs)\nbatching.primitive_batchers[debug_callback_p] = debug_callback_batching_rule\n-def debug_callback_jvp_rule(*flat_args, callback: Callable[..., Any],\n- effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n- del flat_args, callback, effect, in_tree\n- # TODO(sharadmv): link to relevant documentation when it exists\n- raise ValueError(\n- \"JVP doesn't support debugging callbacks. \"\n- \"Instead, you can use them with `jax.custom_jvp` or `jax.custom_vjp`.\")\n+def debug_callback_jvp_rule(primals, tangents, **params):\n+ return debug_callback_p.bind(*primals, **params), []\nad.primitive_jvps[debug_callback_p] = debug_callback_jvp_rule\ndef debug_callback_transpose_rule(*flat_args, callback: Callable[..., Any],\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -169,17 +169,65 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\ndef test_debug_print_jvp_rule(self):\ndef f(x):\n- debug_print('should never be called: {}', x)\n- with self.assertRaisesRegex(\n- ValueError, \"JVP doesn't support debugging callbacks\"):\n+ debug_print('x: {}', x)\n+ with capture_stdout() as output:\njax.jvp(f, (1.,), (1.,))\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"x: 1.0\\n\")\ndef test_debug_print_vjp_rule(self):\ndef f(x):\n- debug_print('should never be called: {}', x)\n- with self.assertRaisesRegex(\n- ValueError, \"JVP doesn't support debugging callbacks\"):\n+ debug_print('x: {}', x)\n+ with capture_stdout() as output:\njax.vjp(f, 1.)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"x: 1.0\\n\")\n+\n+ def test_debug_print_in_custom_jvp(self):\n+\n+ @jax.custom_jvp\n+ def print_tangent(x):\n+ return x\n+\n+ @print_tangent.defjvp\n+ def _(primals, tangents):\n+ (x,), (t,) = primals, tangents\n+ debug_print(\"x_tangent: {}\", t)\n+ return x, t\n+\n+ def f(x):\n+ x = jnp.sin(x)\n+ x = print_tangent(x)\n+ return x\n+\n+ with capture_stdout() as output:\n+ x = jnp.array(1., jnp.float32)\n+ jax.jvp(f, (x,), (x,)) # should print out cos(1.)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"x_tangent: 0.5403022766113281\\n\")\n+\n+ def test_debug_print_grad_with_custom_vjp_rule(self):\n+ @jax.custom_vjp\n+ def print_grad(x):\n+ return x\n+\n+ def print_grad_fwd(x):\n+ return x, None\n+\n+ def print_grad_bwd(_, x_grad):\n+ debug_print(\"x_grad: {}\", x_grad)\n+ return (x_grad,)\n+\n+ print_grad.defvjp(print_grad_fwd, print_grad_bwd)\n+ def f(x):\n+ debug_print(\"x: {}\", x)\n+ x = print_grad(x)\n+ return jnp.sin(x)\n+\n+ with capture_stdout() as output:\n+ jax.grad(f)(jnp.array(1., jnp.float32))\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"x: 1.0\\nx_grad: 0.5403022766113281\\n\")\ndef test_debug_print_transpose_rule(self):\ndef f(x):\n" } ]
Python
Apache License 2.0
google/jax
Adjust debug_callback JVP rule to only call on primals
260,411
24.07.2022 11:59:32
-10,800
ab7d03627154d49ae718018ef644dbd408c725d2
Remove dependencies on masking.py
[ { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -95,7 +95,6 @@ from jax._src.api import (\nlinearize as linearize,\nlinear_transpose as linear_transpose,\nmake_jaxpr as make_jaxpr,\n-\nnamed_call as named_call,\nnamed_scope as named_scope,\npmap as pmap,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -37,7 +37,6 @@ from jax import linear_util as lu\nfrom jax.errors import UnexpectedTracerError\nimport jax.interpreters.ad as ad\nimport jax.interpreters.batching as batching\n-import jax.interpreters.masking as masking\nimport jax.interpreters.mlir as mlir\nimport jax.interpreters.xla as xla\nimport jax.interpreters.partial_eval as pe\n@@ -1074,7 +1073,6 @@ device_put_p = core.Primitive('device_put')\ndevice_put_p.def_impl(_device_put_impl)\ndevice_put_p.def_abstract_eval(lambda x, device=None: x)\nad.deflinear2(device_put_p, lambda cotangent, _, **kwargs: [cotangent])\n-masking.defvectorized(device_put_p)\nbatching.defvectorized(device_put_p)\ndef _device_put_lowering(ctx, x, *, device):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "@@ -529,7 +529,7 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\nelse:\nlength, = unique_lengths\n- x_shapes = [masking.padded_shape_as_value(x.shape[1:]) for x in xs_flat]\n+ x_shapes = [x.shape[1:] for x in xs_flat]\nx_dtypes = [dtypes.canonicalize_dtype(x.dtype) for x in xs_flat]\nx_avals = tuple(map(core.ShapedArray, x_shapes, x_dtypes))\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/loops.py", "new_path": "jax/_src/lax/control_flow/loops.py", "diff": "@@ -233,7 +233,7 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\nstacked_y = tree_map(stack, *maybe_reversed(ys))\nreturn carry, stacked_y\n- x_shapes = [masking.padded_shape_as_value(x.shape[1:]) for x in xs_flat]\n+ x_shapes = [x.shape[1:] for x in xs_flat]\nx_dtypes = [dtypes.canonicalize_dtype(x.dtype) for x in xs_flat]\nx_avals = tuple(_map(ShapedArray, x_shapes, x_dtypes))\n@@ -759,21 +759,6 @@ def _scan_batching_rule(axis_size, axis_name, main_type, args, dims, reverse, le\nys_bdims = [1 if b else batching.not_mapped for b in ys_batched]\nreturn outs, carry_bdims + ys_bdims\n-def _scan_masking_rule(padded_vals, logical_shapes, reverse, length,\n- jaxpr, num_consts, num_carry, linear, unroll):\n- dynamic_length, = masking.shape_as_value((length,))\n- masked_jaxpr = _masked_scan_jaxpr(jaxpr, num_consts, num_carry)\n- consts, init, xs = split_list(padded_vals, [num_consts, num_carry])\n- max_length, = {x.shape[0] for x in xs}\n- const_linear, init_linear, xs_linear = split_list(linear, [num_consts, num_carry])\n- dynamic_length = lax.convert_element_type(dynamic_length, dtypes.int_)\n- out_vals = scan_p.bind(dynamic_length, *consts, dtypes.int_(0), *init, *xs,\n- reverse=reverse, length=max_length, jaxpr=masked_jaxpr,\n- num_consts=1 + num_consts, num_carry=1 + num_carry,\n- linear=tuple([False] + const_linear + [False] + init_linear + xs_linear),\n- unroll=unroll)\n- return out_vals[1:]\n-\ndef _masked_scan_jaxpr(jaxpr, num_consts, num_carry):\nfun = core.jaxpr_as_fun(jaxpr)\n@@ -1001,7 +986,6 @@ xla.register_initial_style_primitive(scan_p)\nmlir.register_lowering(scan_p,\nmlir.lower_fun(_scan_impl, multiple_results=True))\nbatching.axis_primitive_batchers[scan_p] = _scan_batching_rule\n-masking.masking_rules[scan_p] = _scan_masking_rule\ncore.custom_typechecks[scan_p] = partial(_scan_typecheck, False)\npe.partial_eval_jaxpr_custom_rules[scan_p] = _scan_partial_eval_custom\npe.padding_rules[scan_p] = _scan_padding_rule\n@@ -1633,24 +1617,6 @@ def map(f, xs):\n_, ys = scan(g, (), xs)\nreturn ys\n-\n-def _concat_masking_rule(padded_vals, logical_shapes, dimension):\n- result = lax.concatenate(padded_vals, dimension) # fragmented\n- offset = 0\n- for padded_val, logical_shape in zip(padded_vals, logical_shapes):\n- result = _memcpy(dimension, logical_shape[dimension], padded_val,\n- result, offset)\n- offset = offset + logical_shape[dimension]\n- return result\n-\n-def _memcpy(axis, num, src, dst, offset):\n- def body(i, dst):\n- update = slicing.dynamic_index_in_dim(src, i, axis)\n- return slicing.dynamic_update_index_in_dim(dst, update, i + offset, axis)\n- return fori_loop(0, num, body, dst)\n-\n-masking.masking_rules[lax.concatenate_p] = _concat_masking_rule # type: ignore\n-\ndef _rng_bit_generator_batching_rule(batched_args, batch_dims, *, shape, dtype, algorithm):\n\"\"\"Calls RBG in a loop and stacks the results.\"\"\"\nkey, = batched_args\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/convolution.py", "new_path": "jax/_src/lax/convolution.py", "diff": "@@ -24,7 +24,6 @@ from jax._src import dtypes\nfrom jax._src.lax import lax\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\n-from jax.interpreters import masking\nfrom jax.interpreters import mlir\nfrom jax._src import util\nimport jax._src.lib\n@@ -632,31 +631,6 @@ def _conv_general_dilated_batch_rule(\nout = _reshape_axis_into(out_spec[1], out_spec[1] + 1, out)\nreturn out, out_spec[1]\n-def _conv_general_dilated_masking_rule(\n- padded_vals, logical_shapes, window_strides, padding, lhs_dilation,\n- rhs_dilation, dimension_numbers, feature_group_count, batch_group_count,\n- lhs_shape, rhs_shape, precision, preferred_element_type):\n- lhs, rhs = padded_vals\n- logical_lhs_shape, logical_rhs_shape = logical_shapes\n-\n- o, i, *window_dimensions = dimension_numbers.rhs_spec\n- assert (np.all(np.take(rhs.shape, window_dimensions)\n- == np.take(logical_rhs_shape, window_dimensions))), \\\n- \"Conv filter masking not yet implemented.\"\n-\n- n, c, *padded_dimensions = dimension_numbers.lhs_spec\n-\n- return conv_general_dilated(\n- lax._masked(lhs, logical_lhs_shape, padded_dimensions),\n- lax._masked(rhs, logical_rhs_shape, (i,)),\n- window_strides=window_strides, padding=padding,\n- lhs_dilation=lhs_dilation, rhs_dilation=rhs_dilation,\n- dimension_numbers=dimension_numbers,\n- feature_group_count=feature_group_count,\n- batch_group_count=batch_group_count,\n- precision=precision,\n- preferred_element_type=preferred_element_type)\n-\nconv_general_dilated_p = lax.standard_primitive(\n_conv_general_dilated_shape_rule, _conv_general_dilated_dtype_rule,\n'conv_general_dilated')\n@@ -666,8 +640,6 @@ ad.defbilinear(conv_general_dilated_p,\n_conv_general_dilated_transpose_rhs)\nbatching.primitive_batchers[conv_general_dilated_p] = \\\n_conv_general_dilated_batch_rule\n-masking.masking_rules[conv_general_dilated_p] = \\\n- _conv_general_dilated_masking_rule\ndef _complex_mul(mul, x, y):\n# We use a trick for complex multiplication sometimes attributed to Gauss\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -44,7 +44,6 @@ from jax.interpreters import xla\nfrom jax.interpreters import pxla\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\n-from jax.interpreters import masking\nimport jax._src.pretty_printer as pp\nfrom jax._src import util\nfrom jax._src.util import (cache, prod, safe_zip, safe_map, canonicalize_axis,\n@@ -1439,7 +1438,6 @@ def unop(result_dtype, accepted_dtypes, name):\nprim = standard_primitive(_attrgetter('shape'), dtype_rule, name,\nweak_type_rule=weak_type_rule)\nbatching.defvectorized(prim)\n- masking.defvectorized(prim)\npe.padding_rules[prim] = lambda _, __, x, **kw: [prim.bind(x, **kw)]\nreturn prim\nstandard_unop = partial(unop, _identity)\n@@ -1515,7 +1513,6 @@ def naryop(result_dtype, accepted_dtypes, name):\nprim = standard_primitive(shape_rule, dtype_rule, name,\nweak_type_rule=weak_type_rule)\nbatching.defbroadcasting(prim)\n- masking.defnaryop(prim)\npe.padding_rules[prim] = lambda _, __, *xs, **kw: [prim.bind(*xs, **kw)]\nreturn prim\nstandard_naryop = partial(naryop, _input_dtype)\n@@ -1994,7 +1991,6 @@ def _integer_pow_jvp(g, x, *, y):\ninteger_pow_p = standard_primitive(\n_attrgetter('shape'), _integer_pow_dtype_rule, 'integer_pow')\nbatching.defvectorized(integer_pow_p)\n-masking.defvectorized(integer_pow_p)\nad.defjvp(integer_pow_p, _integer_pow_jvp)\npe.padding_rules[integer_pow_p] = lambda _, __, x, y: [integer_pow_p.bind(x, y=y)]\n@@ -2322,7 +2318,6 @@ convert_element_type_p.def_abstract_eval(\nad.defjvp(convert_element_type_p, _convert_element_type_jvp_rule)\nad.primitive_transposes[convert_element_type_p] = _convert_element_type_transpose_rule\nbatching.defvectorized(convert_element_type_p)\n-masking.defvectorized(convert_element_type_p)\npe.const_fold_rules[convert_element_type_p] = _convert_elt_type_folding_rule\npe.forwarding_rules[convert_element_type_p] = _convert_elt_type_fwd_rule\n# TODO(mattjj): un-comment the next line (see #9456)\n@@ -2359,7 +2354,6 @@ bitcast_convert_type_p = standard_primitive(\n'bitcast_convert_type', weak_type_rule=_strip_weak_type)\nad.defjvp_zero(bitcast_convert_type_p)\nbatching.defvectorized(bitcast_convert_type_p)\n-masking.defvectorized(bitcast_convert_type_p)\ndef _bitcast_convert_type_lower(ctx, operand, *, new_dtype):\naval_out, = ctx.avals_out\n@@ -2574,19 +2568,6 @@ def _dot_general_batch_dim_nums(ndims, batch_dims, dimension_numbers):\nnew_dimension_numbers = ((lhs_contract, rhs_contract), (lhs_batch, rhs_batch))\nreturn new_dimension_numbers, int(result_batch_dim)\n-def _dot_general_masking_rule(padded_vals, logical_shapes, *, dimension_numbers,\n- precision,\n- preferred_element_type: Optional[DType]):\n- lhs, rhs = padded_vals\n- # Only need to mask off contraction dims of one side - we mask the lhs here\n- # but this is arbitrary. Could check the sizes of lhs and rhs and mask\n- # whichever is smallest.\n- lhs_shape, _ = logical_shapes\n- (lhs_contract, _), _ = dimension_numbers\n- return dot_general(_masked(lhs, lhs_shape, lhs_contract),\n- rhs, dimension_numbers, precision=precision,\n- preferred_element_type=preferred_element_type)\n-\ndef _dot_general_padding_rule(in_avals, out_avals, lhs, rhs, *,\ndimension_numbers, **params):\nlhs_aval, _ = in_avals\n@@ -2617,7 +2598,6 @@ dot_general_p = standard_primitive(_dot_general_shape_rule,\nad.defbilinear(dot_general_p,\n_dot_general_transpose_lhs, _dot_general_transpose_rhs)\nbatching.primitive_batchers[dot_general_p] = _dot_general_batch_rule\n-masking.masking_rules[dot_general_p] = _dot_general_masking_rule\npe.padding_rules[dot_general_p] = _dot_general_padding_rule\n# TODO(mattjj): un-comment the next line\n# core.pp_eqn_rules[dot_general_p] = _dot_general_pp_rule\n@@ -2982,9 +2962,6 @@ def _concatenate_batch_rule(batched_args, batch_dims, *, dimension):\nfor op, bdim in zip(batched_args, batch_dims)]\nreturn concatenate(operands, dimension + 1), 0\n-# The concatenate_p masking rule requires use of a while-loop construct and so\n-# is defined in lax_control_flow.py\n-\nconcatenate_p = standard_primitive(\n_concatenate_shape_rule, _concatenate_dtype_rule, 'concatenate')\nad.deflinear2(concatenate_p, _concatenate_transpose_rule)\n@@ -3061,21 +3038,9 @@ def _pad_batch_rule(batched_args, batch_dims, *, padding_config):\n(operand_bdim,))\nreturn select(mask, x, broadcasted_padding), operand_bdim\n-def _pad_masking_rule(padded_vals, logical_shapes, padding_config):\n- operand, padding_value = padded_vals\n- shape, _ = logical_shapes\n-\n- out = pad(operand, padding_value, padding_config)\n- out_shape = [lo + shape[i] * (interior + 1)\n- for i, (lo, hi, interior) in enumerate(padding_config)]\n- padded_dims = [i for i, config in enumerate(padding_config)\n- if config != (0, 0, 0)]\n- return _masked(out, out_shape, padded_dims, padding_value)\n-\npad_p = standard_primitive(_pad_shape_rule, _pad_dtype_rule, 'pad')\nad.deflinear2(pad_p, _pad_transpose)\nbatching.primitive_batchers[pad_p] = _pad_batch_rule\n-masking.masking_rules[pad_p] = _pad_masking_rule\ndef _pad_lower(ctx, x, padding_value, *, padding_config):\nlow, high, interior = util.unzip3(padding_config)\n@@ -3220,23 +3185,6 @@ def _reshape_batch_rule(batched_args, batch_dims, *, new_sizes, dimensions):\ndimensions = (0,) + tuple(np.add(1, dimensions))\nreturn reshape(operand, operand.shape[:1] + new_sizes, dimensions), 0\n-def _reshape_masking_rule(padded_args, logical_shapes, polymorphic_shapes,\n- new_sizes, dimensions):\n- operand, = padded_args\n- old_shape, = polymorphic_shapes\n- def is_poly(size): return type(size) is masking.Poly and not size.is_constant\n- def merge_const_sizes(shape):\n- \"\"\"Merges all nonpolymorphic sizes into the previous polymorphic size.\"\"\"\n- poly_dims = [i for i, size in enumerate(shape) if is_poly(size)]\n- return [prod(shape[start:stop])\n- for start, stop in zip([0] + poly_dims, poly_dims + [len(shape)])]\n- if merge_const_sizes(old_shape) != merge_const_sizes(new_sizes):\n- raise NotImplementedError(\n- \"Reshape on padded dimensions causing fragmentation is not supported.\")\n-\n- return reshape(operand,\n- new_sizes=masking.padded_shape_as_value(new_sizes),\n- dimensions=dimensions)\ndef _reshape_lower(ctx, x, *dyn_shape, new_sizes, dimensions):\naval_out, = ctx.avals_out\n@@ -3263,7 +3211,6 @@ reshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,\n'reshape')\nad.deflinear2(reshape_p, _reshape_transpose_rule)\nbatching.primitive_batchers[reshape_p] = _reshape_batch_rule\n-masking.masking_rules[reshape_p] = _reshape_masking_rule\nmlir.register_lowering(reshape_p, _reshape_lower)\ncore.custom_typechecks[reshape_p] = _reshape_typecheck_rule\npe.custom_staging_rules[reshape_p] = _reshape_staging_rule\n@@ -3311,15 +3258,11 @@ def _transpose_batch_rule(batched_args, batch_dims, *, permutation):\nperm = (bdim,) + tuple(i if i < bdim else i+1 for i in permutation)\nreturn transpose(operand, perm), 0\n-def _transpose_masking_rule(padded_vals, logical_shapes, permutation):\n- return transpose(*padded_vals, permutation=permutation)\n-\ntranspose_p = standard_primitive(_transpose_shape_rule, _input_dtype,\n'transpose')\nad.deflinear2(transpose_p,\nlambda t, _, permutation: [transpose(t, np.argsort(permutation))]) # type: ignore[arg-type]\nbatching.primitive_batchers[transpose_p] = _transpose_batch_rule\n-masking.masking_rules[transpose_p] = _transpose_masking_rule\ndef _transpose_lower(ctx, x, *, permutation):\naval_out, = ctx.avals_out\n@@ -3404,13 +3347,6 @@ def _select_batch_rule(batched_args, batch_dims, **unused_kwargs):\ncases = [broadcast(c, which.shape) for c in cases]\nreturn select_n(which, *cases), 0\n-def _select_masking_rule(padded_vals, logical_shapes):\n- which_shape, true_shape, false_shape = (\n- masking.padded_shape_as_value(val.shape) for val in padded_vals)\n- assert np.array_equal(which_shape, true_shape)\n- assert np.array_equal(which_shape, false_shape)\n- return select_n(*padded_vals)\n-\ndef _select_jvp(primals, tangents):\nwhich, *case_primals = primals\ncase_tangents = tangents[1:]\n@@ -3456,7 +3392,6 @@ select_n_p = standard_primitive(\nad.primitive_jvps[select_n_p] = _select_jvp\nad.primitive_transposes[select_n_p] = _select_transpose_rule\nbatching.primitive_batchers[select_n_p] = _select_batch_rule\n-masking.masking_rules[select_n_p] = _select_masking_rule\nmlir.register_lowering(select_n_p, _select_mhlo_lowering)\n@@ -3550,21 +3485,6 @@ def _reduce_jvp_rule(primals, tangents, *, computation, jaxpr,\nreducer = core.jaxpr_as_fun(core.ClosedJaxpr(jaxpr, consts))\nreturn _reduce_jvp(reducer, init_values, primal_xs, tangent_xs, dimensions)\n-def _masking_defreducer(prim, identity):\n- masking.masking_rules[prim] = partial(_reducer_masking_rule, prim, identity)\n-\n-def _reducer_masking_rule(prim, identity, padded_vals, logical_shapes,\n- axes, input_shape=None, **reduce_kwargs):\n- (padded_val,), (logical_shape,) = padded_vals, logical_shapes\n- padded_shape = masking.padded_shape_as_value(padded_val.shape)\n- masks = [broadcasted_iota(_dtype(d), padded_shape, i) < d\n- for i, d in enumerate(logical_shape) if i in axes]\n- mask = _reduce(operator.and_, masks)\n- masked_val = select(mask, padded_val, identity(padded_shape, padded_val.dtype))\n- prim_bind = partial(prim.bind, **reduce_kwargs)\n- bind = prim_bind if input_shape is None else partial(prim_bind, input_shape=padded_shape)\n- return bind(masked_val, axes=axes)\n-\ndef _reduce_named_shape_rule(*avals, computation, jaxpr, consts, dimensions):\n# TODO(mattjj,frostig): see the TODOs noting limitations/assumptions in\n# _reduce_batching_rule. We're making the same assumptions here for now.\n@@ -3644,8 +3564,6 @@ reduce_sum_p = standard_primitive(\n'reduce_sum')\nad.deflinear2(reduce_sum_p, _reduce_sum_transpose_rule)\nbatching.defreducer(reduce_sum_p)\n-_masking_defreducer(reduce_sum_p,\n- lambda shape, dtype: np.broadcast_to(np.array(0, dtype), shape))\npe.padding_rules[reduce_sum_p] = _reduce_sum_padding_rule\n@@ -3669,8 +3587,6 @@ reduce_prod_p = standard_primitive(\n'reduce_prod')\nad.primitive_jvps[reduce_prod_p] = _reduce_prod_jvp_rule\nbatching.defreducer(reduce_prod_p)\n-_masking_defreducer(reduce_prod_p,\n- lambda shape, dtype: np.broadcast_to(np.array(1, dtype), shape))\ndef _reduce_chooser_shape_rule(operand, *, axes):\n@@ -3689,17 +3605,12 @@ def _reduce_chooser_jvp_rule(g, ans, operand, *, axes):\nreduce_max_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n'reduce_max')\nad.defjvp2(reduce_max_p, _reduce_chooser_jvp_rule)\n-batching.defreducer(reduce_max_p)\n-_masking_defreducer(reduce_max_p,\n- lambda shape, dtype: np.broadcast_to(np.array(-np.inf, dtype), shape))\nreduce_min_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n'reduce_min')\nad.defjvp2(reduce_min_p, _reduce_chooser_jvp_rule)\nbatching.defreducer(reduce_min_p)\n-_masking_defreducer(reduce_min_p,\n- lambda shape, dtype: np.broadcast_to(np.array(np.inf, dtype), shape))\ndef _argminmax_shape_rule(operand, *, axes, index_dtype):\n@@ -3830,7 +3741,6 @@ reduce_precision_p = standard_primitive(\npartial(unop_dtype_rule, _identity, _float, 'reduce_precision'),\nname='reduce_precision')\nbatching.defvectorized(reduce_precision_p)\n-masking.defvectorized(reduce_precision_p)\ndef _reduce_precision_lower(ctx, operand, *, exponent_bits, mantissa_bits):\naval_out, = ctx.avals_out\n@@ -4365,7 +4275,6 @@ copy_p.def_abstract_eval(lambda x: x)\nmlir.register_lowering(copy_p, lambda ctx, x: [x])\nad.deflinear(copy_p, lambda t: [copy_p.bind(t)])\nbatching.defvectorized(copy_p)\n-masking.defvectorized(copy_p)\ndef rng_bit_generator(key, shape, dtype=np.uint32,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/slicing.py", "new_path": "jax/_src/lax/slicing.py", "diff": "@@ -26,7 +26,6 @@ from jax._src import dtypes\nfrom jax._src import source_info_util\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\n-from jax.interpreters import masking\nfrom jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\nfrom jax._src.lax.utils import (\n@@ -795,19 +794,9 @@ def _slice_batching_rule(batched_args, batch_dims, *, start_indices,\nout = slice(operand, new_start_indices, new_limit_indices, new_strides)\nreturn out, bdim\n-def _slice_masking_rule(\n- padded_vals, logical_shapes, start_indices, limit_indices, strides):\n- operand, = padded_vals\n- strides = masking.padded_shape_as_value(strides) if strides else None\n- return slice(operand,\n- start_indices=masking.padded_shape_as_value(start_indices),\n- limit_indices=masking.padded_shape_as_value(limit_indices),\n- strides=strides)\n-\nslice_p = standard_primitive(_slice_shape_rule, _input_dtype, 'slice')\nad.deflinear2(slice_p, _slice_transpose_rule)\nbatching.primitive_batchers[slice_p] = _slice_batching_rule\n-masking.masking_rules[slice_p] = _slice_masking_rule\ndef _slice_lower(ctx, x, *, start_indices, limit_indices, strides):\nstrides = strides or [1] * len(start_indices)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -512,7 +512,7 @@ from jax import custom_derivatives\nfrom jax._src import dtypes\nfrom jax import lax\nfrom jax.experimental import pjit\n-from jax.interpreters import ad, xla, batching, masking, pxla\n+from jax.interpreters import ad, xla, batching, pxla\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import mlir\nfrom jax._src import dispatch\n@@ -891,16 +891,6 @@ def _id_tap_dep_batching_rule(batched_args, batch_dims):\nbatching.primitive_batchers[id_tap_dep_p] = _id_tap_dep_batching_rule\n-\n-def _id_tap_dep_masking_rule(operands, operands_logical_shapes):\n- if FLAGS.jax_host_callback_ad_transforms:\n- assert False\n- arg_res, arg_tap = operands\n- return id_tap_dep_p.bind(arg_res, arg_tap)\n-\n-\n-masking.masking_rules[id_tap_dep_p] = _id_tap_dep_masking_rule\n-\n### The outside_call primitive\n\"\"\"\nThis primitive is used to implement the `call` and `id_tap` functions.\n@@ -1455,29 +1445,6 @@ def _outside_call_batching_rule(batched_args, batch_dims, **params):\nbatching.primitive_batchers[outside_call_p] = _outside_call_batching_rule\n-\n-def _outside_call_masking_rule(operands, operands_logical_shapes, **params):\n- if not params[\"identity\"]:\n- raise NotImplementedError(\"masking rules are implemented only for id_tap, not for call.\")\n- assert \"has_token\" not in params\n-\n- assert len(operands) == len(operands_logical_shapes)\n- arg_treedef = params[\"arg_treedef\"]\n- # We will send the pair of (arg, arg_logical_shapes)\n- packed_operands, packed_arg_tree = api.tree_flatten(\n- (api.tree_unflatten(arg_treedef, operands),\n- api.tree_unflatten(arg_treedef, operands_logical_shapes)))\n-\n- packed_results = outside_call_p.bind(\n- *packed_operands,\n- **dict(_add_transform(params, \"mask\"),\n- arg_treedef=packed_arg_tree))\n- return packed_results[:len(operands)] + packed_results[len(packed_operands):]\n-\n-\n-masking.masking_rules[outside_call_p] = _outside_call_masking_rule\n-\n-\n####\n#### Jaxpr rewriting logic to thread the tokens through stateful primitives.\n####\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/tf_test_util.py", "new_path": "jax/experimental/jax2tf/tests/tf_test_util.py", "diff": "@@ -30,7 +30,6 @@ from jax import tree_util\nfrom jax.config import config\nfrom jax.experimental import jax2tf\n-from jax.interpreters import masking\nfrom jax._src import util\nimport jax._src.lib.xla_bridge\nimport numpy as np\n@@ -409,22 +408,6 @@ class JaxToTfTestCase(jtu.JaxTestCase):\nself.assertEqual(tuple(expected.shape), tuple(found))\nreturn f_tf\n- def MakeInputSignature(self, *polymorphic_shapes):\n- \"\"\"From a pytree of in_shape string specification, make a pytree of tf.TensorSpec.\n-\n- Dimension variables are replaced with None.\n- \"\"\"\n-\n- def polymorphic_shape_to_tensorspec(poly_shape: str) -> tf.TensorSpec:\n- in_spec = masking.parse_spec(poly_shape)\n- return tf.TensorSpec(\n- tuple(\n- int(dim_spec) if dim_spec.is_constant else None\n- for dim_spec in in_spec),\n- dtype=tf.float32)\n-\n- return tree_util.tree_map(polymorphic_shape_to_tensorspec, polymorphic_shapes)\n-\ndef CountLargeTfConstants(self, tf_fun: Callable, *args,\nat_least=256):\n# A hacky way to count how many \"large\" constants are embedded in the\n" } ]
Python
Apache License 2.0
google/jax
Remove dependencies on masking.py
260,411
24.07.2022 12:03:34
-10,800
2fd46d13cdce0d418389475944af9f86c92a2804
Delete the masking.py
[ { "change_type": "MODIFY", "old_path": "docs/faq.rst", "new_path": "docs/faq.rst", "diff": "@@ -215,7 +215,7 @@ subsequent method call may return an incorrect result::\nWhat's happening here? The issue is that ``static_argnums`` relies on the hash of the object\nto determine whether it has changed between calls, and the default ``__hash__`` method\nfor a user-defined class will not take into account the values of class attributes. That means\n-that on the second function call, JAX has no way of knowing that the class attribues have\n+that on the second function call, JAX has no way of knowing that the class attributes have\nchanged, and uses the cached static value from the previous compilation.\nFor this reason, if you are marking ``self`` arguments as static, it is important that you\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/for_loop.py", "new_path": "jax/_src/lax/control_flow/for_loop.py", "diff": "@@ -22,7 +22,6 @@ from jax import lax\nfrom jax import linear_util as lu\nfrom jax.api_util import flatten_fun_nokwargs\nfrom jax.interpreters import ad\n-from jax.interpreters import masking\nfrom jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/loops.py", "new_path": "jax/_src/lax/control_flow/loops.py", "diff": "@@ -26,7 +26,6 @@ from jax.config import config\nfrom jax.core import ConcreteArray, ShapedArray, raise_to_shaped\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\n-from jax.interpreters import masking\nfrom jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n@@ -932,9 +931,8 @@ def _scan_typecheck(bind_time, *in_atoms, reverse, length, num_consts, num_carry\ntype(linear) is tuple and all(type(x) is bool for x in linear))\ntc(unroll, 'unroll', 'positive int', type(unroll) is int and unroll > 0)\n- length_types = (int, masking.Poly) if bind_time else (int,)\ntc(length, 'length', 'non-negative int',\n- type(length) in length_types and length >= 0)\n+ type(length) is int and length >= 0)\nif len(linear) != len(avals):\nraise core.JaxprTypeError(\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3605,7 +3605,7 @@ def _reduce_chooser_jvp_rule(g, ans, operand, *, axes):\nreduce_max_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n'reduce_max')\nad.defjvp2(reduce_max_p, _reduce_chooser_jvp_rule)\n-\n+batching.defreducer(reduce_max_p)\nreduce_min_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n'reduce_min')\n" }, { "change_type": "DELETE", "old_path": "jax/interpreters/masking.py", "new_path": null, "diff": "-# Copyright 2019 Google LLC\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-\"\"\"Masking is **DEPRECATED** and is being removed.\"\"\"\n-\n-from contextlib import contextmanager\n-from collections import Counter, namedtuple\n-from functools import partial, reduce\n-from itertools import chain, product\n-import operator as op\n-import string\n-from typing import Callable, Dict, Optional, Sequence, Union, Tuple\n-\n-import numpy as np\n-\n-from jax import core\n-from jax._src import dtypes\n-from jax.tree_util import tree_unflatten\n-from jax.core import ShapedArray, Trace, Tracer\n-from jax._src.util import safe_map, safe_zip, unzip2, prod, wrap_name\n-from jax import linear_util as lu\n-\n-map = safe_map\n-zip = safe_zip\n-\n-masking_rules: Dict[core.Primitive, Callable] = {}\n-\n-def defvectorized(prim):\n- masking_rules[prim] = partial(vectorized_masking_rule, prim)\n-\n-def defnaryop(prim):\n- masking_rules[prim] = partial(naryop_masking_rule, prim)\n-\n-def vectorized_masking_rule(prim, padded_vals, logical_shapes, **params):\n- del logical_shapes # Unused.\n- padded_val, = padded_vals\n- return prim.bind(padded_val, **params)\n-\n-def naryop_masking_rule(prim, padded_vals, logical_shapes):\n- del logical_shapes # Unused.\n- return prim.bind(*padded_vals)\n-\n-DimSize = core.DimSize\n-Shape = core.Shape\n-\n-ShapeEnvs = namedtuple(\"ShapeEnvs\", [\"logical\", \"padded\"])\n-shape_envs = ShapeEnvs({}, {}) # TODO(mattjj): make this a stack for efficiency\n-\n-def is_tracing():\n- return bool(shape_envs.padded)\n-\n-@contextmanager\n-def extend_shape_envs(logical_env, padded_env):\n- global shape_envs\n- new_logical = dict(chain(shape_envs.logical.items(), logical_env.items()))\n- new_padded = dict(chain(shape_envs.padded.items(), padded_env.items()))\n- shape_envs, prev = ShapeEnvs(new_logical, new_padded), shape_envs\n- try:\n- yield\n- finally:\n- shape_envs = prev\n-\n-def shape_as_value(shape):\n- assert is_tracing() or not is_polymorphic(shape)\n- return eval_poly_shape(shape, shape_envs.logical)\n-\n-def padded_shape_as_value(shape):\n- assert is_tracing() or not is_polymorphic(shape)\n- return eval_poly_shape(shape, shape_envs.padded)\n-\n-def mask_fun(fun, logical_env, padded_env, in_vals, polymorphic_shapes):\n- env_keys, padded_env_vals = unzip2(sorted(padded_env.items()))\n- logical_env_vals = [logical_env[k] for k in env_keys]\n- # Make padded_env hashable\n- padded_env = (env_keys, padded_env_vals)\n- with core.new_main(MaskTrace) as main:\n- fun, out_shapes = mask_subtrace(fun, main, polymorphic_shapes, padded_env)\n- out_vals = fun.call_wrapped(*(logical_env_vals + in_vals))\n- del main\n- return out_vals, out_shapes()\n-\n-@lu.transformation_with_aux\n-def mask_subtrace(main, shapes, padded_env, *in_vals):\n- env_keys, _ = padded_env\n- logical_env_vals, in_vals = in_vals[:len(env_keys)], in_vals[len(env_keys):]\n- logical_env = dict(zip(env_keys, logical_env_vals))\n- padded_env = dict(zip(*padded_env))\n- trace = MaskTrace(main, core.cur_sublevel())\n- in_tracers = [MaskTracer(trace, x, s).full_lower()\n- for x, s in zip(in_vals, shapes)]\n- with extend_shape_envs(logical_env, padded_env):\n- outs = yield in_tracers, {}\n- out_tracers = map(trace.full_raise, outs)\n- out_vals, out_shapes = unzip2((t.val, t.polymorphic_shape) for t in out_tracers)\n- yield out_vals, out_shapes\n-\n-def eval_poly_shape(shape, values_dict):\n- return tuple(eval_poly(dim, values_dict) for dim in shape)\n-\n-def eval_poly(poly, values_dict):\n- return poly.evaluate(values_dict) if type(poly) is Poly else poly\n-\n-def _ensure_poly(p: 'Size') -> 'Poly':\n- if isinstance(p, Poly): return p\n- return Poly({Mon(): p})\n-\n-def _polys_to_ints(shape):\n- return tuple(int(d) if type(d) is Poly and d.is_constant else d\n- for d in shape)\n-\n-def is_polymorphic(shape: Sequence['Size']):\n- return any(map(lambda d: type(d) is Poly, shape))\n-\n-class UndefinedPoly(core.InconclusiveDimensionOperation):\n- \"\"\"Exception raised when an operation involving polynomials is not defined.\n-\n- An operation `op` on polynomials `p1` and `p2` either raises this exception,\n- or produce a polynomial `res`, such that `op(Val(p1), Val(p2)) = Val(res)`,\n- for any `Val`, a non-negative integer valuation of the shape variables.\n- \"\"\"\n- pass\n-\n-class Poly(dict):\n- \"\"\"Polynomial with integer coefficients for polymorphic shapes.\n-\n- The shape variables are assumed to range over non-negative integers.\n-\n- We overload integer operations, but we do that soundly, raising\n- :class:`UndefinedPoly` when the result is not representable as a polynomial.\n-\n- The representation of a polynomial is as a dictionary mapping monomials to\n- integer coefficients. The special monomial `Mon()` is mapped to the\n- free integer coefficient of the polynomial.\n- \"\"\"\n-\n- def __init__(self, coeffs: Dict['Mon', int]):\n- # Makes sure Polynomials are always in canonical form\n- coeffs = {mon: op.index(coeff)\n- for mon, coeff in coeffs.items() if coeff != 0}\n- coeffs = coeffs or {Mon(): 0}\n- super().__init__(coeffs)\n-\n- def __hash__(self):\n- return hash(tuple(sorted(self.items())))\n-\n- def __add__(self, other: 'Size') -> 'Poly':\n- coeffs = self.copy()\n- for mon, coeff in _ensure_poly(other).items():\n- coeffs[mon] = coeffs.get(mon, 0) + coeff\n- return Poly(coeffs)\n-\n- def __sub__(self, other: 'Size') -> 'Poly':\n- return self + -other\n-\n- def __neg__(self) -> 'Poly':\n- return Poly({mon: -coeff for mon, coeff in self.items()})\n-\n- def __mul__(self, other: 'Size') -> 'Poly':\n- other = _ensure_poly(other)\n- coeffs: Dict[Mon, int] = {}\n- for (mon1, coeff1), (mon2, coeff2) in product(self.items(), other.items()):\n- mon = mon1 * mon2\n- coeffs[mon] = coeffs.get(mon, 0) + coeff1 * coeff2\n- return Poly(coeffs)\n-\n- def __rmul__(self, other: 'Size') -> 'Poly':\n- return self * other # multiplication commutes\n-\n- def __radd__(self, other: 'Size') -> 'Poly':\n- return self + other # addition commutes\n-\n- def __rsub__(self, other: 'Size') -> 'Poly':\n- return _ensure_poly(other) - self\n-\n- def __floordiv__(self, divisor: 'Size') -> 'Poly':\n- q, _ = divmod(self, divisor) # type: ignore\n- return q\n-\n- def __mod__(self, divisor: 'Size') -> int:\n- _, r = divmod(self, divisor) # type: ignore\n- return r\n-\n- def __divmod__(self, divisor: 'Size') -> Tuple['Poly', int]:\n- \"\"\"\n- Floor division with remainder (divmod) generalized to polynomials. To allow\n- ensuring '0 <= remainder < divisor' for consistency with integer divmod, the\n- divisor must divide the dividend (up to a constant for constant divisors).\n- :return: Quotient resulting from polynomial division and integer remainder.\n- \"\"\"\n- divisor = _ensure_poly(divisor)\n- dmon, dcount = divisor._leading_term\n- dividend, quotient, remainder = self, _ensure_poly(0), _ensure_poly(0)\n- while not dividend.is_constant or dividend != 0: # invariant: dividend == divisor*quotient + remainder\n- mon, count = dividend._leading_term\n- qcount, rcount = divmod(count, dcount)\n- try:\n- qmon = mon // dmon\n- except UndefinedPoly:\n- raise UndefinedPoly(f\"Stride {divisor} must divide size {self} \"\n- \"(up to a constant for constant divisors).\")\n- r = Poly({mon: rcount})\n- q = Poly({qmon: qcount})\n- quotient += q\n- remainder += r\n- dividend -= q * divisor + r\n- return quotient, int(remainder)\n-\n- def __rdivmod__(self, dividend: 'Size') -> Tuple['Poly', int]:\n- return divmod(_ensure_poly(dividend), self) # type: ignore\n-\n- def __eq__(self, other):\n- lb, ub = (self - other).bounds()\n- if lb == ub == 0:\n- return True\n- if lb is not None and lb > 0:\n- return False\n- if ub is not None and ub < 0:\n- return False\n- raise UndefinedPoly(f\"Polynomial comparison {self} == {other} is inconclusive\")\n-\n- def __ne__(self, other):\n- return not self == other\n-\n- def __ge__(self, other: 'Size'):\n- lb, ub = (self - other).bounds()\n- if lb is not None and lb >= 0:\n- return True\n- if ub is not None and ub < 0:\n- return False\n- raise UndefinedPoly(f\"Polynomial comparison {self} >= {other} is inconclusive\")\n-\n- def __le__(self, other: 'Size'):\n- return _ensure_poly(other) >= self\n-\n- def __lt__(self, other: 'Size'):\n- return not (self >= other)\n-\n- def __gt__(self, other: 'Size'):\n- return not (_ensure_poly(other) >= self)\n-\n- def __str__(self):\n- return ' + '.join(f'{c} {mon}' if c != 1 or mon.degree == 0 else str(mon)\n- for mon, c in sorted(self.items(), reverse=True)).strip()\n-\n- def __repr__(self):\n- return str(self)\n-\n- def __int__(self):\n- if self.is_constant:\n- return op.index(next(iter(self.values())))\n- else:\n- raise UndefinedPoly(f\"Polynomial {self} is not constant\")\n-\n- def bounds(self) -> Tuple[Optional[int], Optional[int]]:\n- \"\"\"Returns the lower and upper bounds, if defined.\"\"\"\n- lb = ub = self.get(Mon(), 0)\n- for mon, coeff in self.items():\n- if mon.degree > 0:\n- if coeff > 0:\n- ub = None\n- else:\n- lb = None\n- return lb, ub\n-\n- def evaluate(self, env):\n- prod = lambda xs: reduce(op.mul, xs) if xs else 1\n- terms = [mul(coeff, prod([pow(env[id], deg) for id, deg in mon.items()]))\n- for mon, coeff in self.items()]\n- return sum(terms) if len(terms) > 1 else terms[0]\n-\n- @property\n- def is_constant(self):\n- return len(self) == 1 and next(iter(self)).degree == 0\n-\n- @property\n- def _leading_term(self) -> Tuple['Mon', int]:\n- \"\"\"Returns the highest degree term that comes first lexicographically.\"\"\"\n- return max(self.items())\n-\n-Size = Union[int, Poly]\n-\n-def pow(x, deg):\n- try:\n- deg = int(deg)\n- except:\n- return x ** deg\n- else:\n- return 1 if deg == 0 else x if deg == 1 else x ** deg\n-\n-def mul(coeff, mon):\n- try:\n- coeff = int(coeff)\n- except:\n- return coeff * mon\n- else:\n- return 0 if coeff == 0 else mon if coeff == 1 else coeff * mon\n-\n-\n-class DimensionHandlerPoly(core.DimensionHandler):\n- \"\"\"See core.DimensionHandler.\n-\n- Most methods are inherited.\n- \"\"\"\n- def is_constant(self, d: DimSize) -> bool:\n- assert isinstance(d, Poly)\n- return False\n-\n- def symbolic_equal(self, d1: core.DimSize, d2: core.DimSize) -> bool:\n- try:\n- return d1 == d2\n- except UndefinedPoly:\n- return False\n-\n-\n-core._SPECIAL_DIMENSION_HANDLERS[Poly] = DimensionHandlerPoly()\n-dtypes.python_scalar_dtypes[Poly] = dtypes.python_scalar_dtypes[int]\n-\n-class Mon(dict):\n- # TODO: move this before Poly in the file\n- \"\"\"Represents a multivariate monomial, such as n^3 * m.\n-\n- The representation is a dictionary mapping var:exponent. The\n- exponent is >= 1.\n- \"\"\"\n- def __hash__(self):\n- return hash(frozenset(self.items()))\n-\n- def __str__(self):\n- return ' '.join(f'{key}^{exponent}' if exponent != 1 else str(key)\n- for key, exponent in sorted(self.items()))\n-\n- def __lt__(self, other: 'Mon'):\n- # TODO: do not override __lt__ for this\n- \"\"\"\n- Comparison to another monomial in graded reverse lexicographic order.\n- \"\"\"\n- self_key = -self.degree, tuple(sorted(self))\n- other_key = -other.degree, tuple(sorted(other))\n- return self_key > other_key\n-\n- def __mul__(self, other: 'Mon') -> 'Mon':\n- \"\"\"\n- Returns the product with another monomial. Example: (n^2*m) * n == n^3 * m.\n- \"\"\"\n- return Mon(Counter(self) + Counter(other))\n-\n- @property\n- def degree(self):\n- return sum(self.values())\n-\n- def __floordiv__(self, divisor: 'Mon') -> 'Mon':\n- \"\"\"\n- Divides by another monomial. Raises a ValueError if impossible.\n- For example, (n^3 * m) // n == n^2*m, but n // m fails.\n- \"\"\"\n- d = Counter(self)\n- for key, exponent in divisor.items():\n- diff = self.get(key, 0) - exponent\n- if diff < 0: raise UndefinedPoly(f\"Cannot divide {self} by {divisor}.\")\n- elif diff == 0: del d[key]\n- elif diff > 0: d[key] = diff\n- return Mon(d)\n-\n-class ShapeError(Exception): pass\n-\n-class ShapeSyntaxError(Exception): pass\n-\n-# To denote some shape expressions (for annotations) we use a small language.\n-#\n-# data ShapeSpec = ShapeSpec [Dim]\n-# data Dim = Id PyObj\n-# | Lit Int\n-# | Mul Dim Dim\n-# | Add Dim Dim\n-# | MonomorphicDim\n-#\n-# We'll also make a simple concrete syntax for annotation. The grammar is\n-#\n-# shape_spec ::= '(' dims ')'\n-# dims ::= dim ',' dims | ''\n-# dim ::= str | int | dim '*' dim | dim '+' dim | '_'\n-#\n-# ShapeSpecs can have some monomorphic dims inside them, which must be replaced\n-# with concrete shapes when known.\n-\n-class ShapeSpec(tuple):\n- def __str__(self):\n- return 'ShapeSpec({})'.format(', '.join(map(str, self)))\n-\n-def finalize_spec(polymorphic_shape, padded_shape):\n- # TODO: what if polymorphic_shape has a constant that does not match padded_shape?\n- return tuple(_parse_lit(d) if e is _monomorphic_dim else e\n- for e, d in zip(polymorphic_shape, padded_shape))\n-\n-def parse_spec(spec=''):\n- if not spec:\n- return ShapeSpec(())\n- if spec[0] == '(':\n- if spec[-1] != ')': raise ShapeSyntaxError(spec)\n- spec = spec[1:-1]\n- dims = map(_parse_dim, spec.replace(' ', '').strip(',').split(','))\n- return ShapeSpec(dims)\n-\n-def _parse_dim(spec):\n- if '+' in spec:\n- return np.sum(map(_parse_dim, spec.split('+')))\n- elif '*' in spec:\n- return prod(map(_parse_dim, spec.split('*')))\n- elif spec.isdigit() or spec.startswith('-') and spec[1:].isdigit():\n- return _parse_lit(spec)\n- elif spec[0] in _identifiers:\n- return _parse_id(spec)\n- elif spec == '_':\n- return _monomorphic_dim\n- else:\n- raise ShapeSyntaxError(spec)\n-\n-_identifiers = frozenset(string.ascii_lowercase)\n-\n-def _parse_id(name): return Poly({Mon({name: 1}): 1})\n-\n-def _parse_lit(val_str): return int(val_str)\n-\n-class MonomorphicDim:\n- def __str__(self): return '_'\n-\n-_monomorphic_dim = MonomorphicDim()\n-\n-# Two convenient ways to provide shape annotations:\n-# 1. '(m, n)'\n-# 2. s_['m', 'n']\n-\n-class S_:\n- def __getitem__(self, idx):\n- return parse_spec(('(' + ','.join(map(str, idx)) + ')')\n- if type(idx) is tuple else str(idx))\n-\n-s_ = S_()\n-\n-def _shape_spec_consistent(spec, expr):\n- return all(a == b for a, b in zip(spec, expr) if a is not _monomorphic_dim)\n-\n-class MaskTracer(Tracer):\n- __slots__ = [\"val\", \"polymorphic_shape\"]\n-\n- def __init__(self, trace, val, polymorphic_shape):\n- super().__init__(trace)\n- self.val = val\n- self.polymorphic_shape = polymorphic_shape\n-\n- @property\n- def aval(self):\n- return ShapedArray(self.polymorphic_shape,\n- dtypes.canonicalize_dtype(self.dtype))\n-\n- @property\n- def dtype(self):\n- return dtypes.dtype(self.val)\n-\n- def is_pure(self):\n- return all(type(poly) is not Poly or poly.is_constant\n- for poly in self.polymorphic_shape)\n-\n- def full_lower(self):\n- if self.is_pure():\n- return core.full_lower(self.val)\n- else:\n- return self\n-\n-\n-class MaskTrace(Trace):\n- def pure(self, val):\n- return MaskTracer(self, val, np.shape(val))\n-\n- def lift(self, val):\n- return MaskTracer(self, val, np.shape(val))\n-\n- def sublift(self, val):\n- return MaskTracer(self, val.val, val.polymorphic_shape)\n-\n- def process_primitive(self, primitive, tracers, params):\n- masking_rule = masking_rules.get(primitive)\n- if masking_rule is None:\n- raise NotImplementedError(\n- f'Masking rule for {primitive} not implemented yet.')\n- # Ignore effects for now.\n- out_aval, _ = primitive.abstract_eval(*(t.aval for t in tracers), **params)\n- vals, polymorphic_shapes = unzip2((t.val, t.polymorphic_shape) for t in tracers)\n- logical_shapes = map(shape_as_value, polymorphic_shapes)\n- # TODO(mattjj): generalize mask rule signature\n- if primitive.name == 'reshape': params['polymorphic_shapes'] = polymorphic_shapes\n- out = masking_rule(vals, logical_shapes, **params)\n- if primitive.multiple_results:\n- out_shapes = map(_polys_to_ints, [o.shape for o in out_aval])\n- return map(partial(MaskTracer, self), out, out_shapes)\n- else:\n- return MaskTracer(self, out, _polys_to_ints(out_aval.shape))\n-\n- def process_call(self, call_primitive, f, tracers, params):\n- assert call_primitive.multiple_results\n- params = dict(params, name=wrap_name(params.get('name', f.__name__), 'mask'))\n- vals, shapes = unzip2((t.val, t.polymorphic_shape) for t in tracers)\n- if not any(is_polymorphic(s) for s in shapes):\n- return call_primitive.bind(f, *vals, **params)\n- else:\n- logical_env, padded_env = shape_envs\n- env_keys, padded_env_vals = unzip2(sorted(padded_env.items()))\n- logical_env_vals = tuple(logical_env[k] for k in env_keys)\n- # Make padded_env hashable\n- padded_env = (env_keys, padded_env_vals)\n- f, shapes_out = mask_subtrace(f, self.main, shapes, padded_env)\n- if 'donated_invars' in params:\n- params = dict(params, donated_invars=((False,) * len(logical_env_vals) +\n- params['donated_invars']))\n- vals_out = call_primitive.bind(f, *(logical_env_vals + vals), **params)\n- return [MaskTracer(self, v, s) for v, s in zip(vals_out, shapes_out())]\n-\n- def post_process_call(self, call_primitive, out_tracers, params):\n- vals, shapes = unzip2((t.val, t.polymorphic_shape) for t in out_tracers)\n- main = self.main\n- def todo(vals):\n- trace = MaskTrace(main, core.cur_sublevel())\n- return map(partial(MaskTracer, trace), vals, shapes)\n- return vals, todo\n-\n-class UniqueId:\n- def __init__(self, name):\n- self.name = name\n-\n- def __repr__(self):\n- return self.name\n-\n- def __lt__(self, other):\n- return self.name < other.name\n-\n-class UniqueIds(dict):\n- def __missing__(self, key):\n- unique_id = UniqueId(key)\n- self[key] = unique_id\n- return unique_id\n-\n-def remap_ids(names, shape_spec):\n- return ShapeSpec(Poly({Mon({names[id] : deg for id, deg in mon.items()})\n- : coeff for mon, coeff in poly.items()})\n- if isinstance(poly, Poly) else\n- poly for poly in shape_spec)\n-\n-def bind_shapes(polymorphic_shapes, padded_shapes):\n- env = {}\n- for polymorphic_shape, padded_shape in zip(polymorphic_shapes, padded_shapes):\n- for poly, d in zip(polymorphic_shape, padded_shape):\n- if type(poly) is not Poly or poly.is_constant:\n- if int(poly) != d: raise ShapeError\n- else:\n- poly = poly.copy()\n- const_coeff = poly.pop(Mon({}), 0)\n- (mon, linear_coeff), = poly.items()\n- (id, index), = mon.items()\n- if index != 1: raise ShapeError\n- d, r = divmod(d - const_coeff, linear_coeff)\n- assert r == 0\n- if env.setdefault(id, d) != d: raise ShapeError\n- return env\n-\n-def check_shapes(specs, spec_tree, shapes, tree, message_prefix=\"Output\"):\n- if spec_tree != tree or not all(map(_shape_spec_consistent, specs, shapes)):\n- specs = tree_unflatten(spec_tree, specs)\n- shapes = tree_unflatten(tree, shapes)\n- raise ShapeError(f\"{message_prefix} shapes should be {specs} but are {shapes}.\")\n" } ]
Python
Apache License 2.0
google/jax
Delete the masking.py
260,424
25.07.2022 15:23:01
25,200
48a2abcb7203a00966abcd75b6b163e80c8c3f65
Fix linear_jvp for multiple_results primitives with Zero tangents.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -490,6 +490,8 @@ def deflinear(primitive, transpose_rule):\ndef linear_jvp(primitive, primals, tangents, **params):\nval_out = primitive.bind(*primals, **params)\nif all(type(tangent) is Zero for tangent in tangents):\n+ if primitive.multiple_results:\n+ return val_out, map(Zero.from_value, val_out)\nreturn val_out, Zero.from_value(val_out)\nelse:\ntangents = map(instantiate_zeros, tangents)\n" } ]
Python
Apache License 2.0
google/jax
Fix linear_jvp for multiple_results primitives with Zero tangents. PiperOrigin-RevId: 463190431
260,411
26.07.2022 12:41:40
-10,800
5b0b8ac58aa43b55de32eedd65c47e20e43db52b
[jax2tf] Improved documentation and tests for pjit
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -254,6 +254,16 @@ You have two options, either pass `enable_gradients=False` to `jax2tf.convert`,\nset `tf.saved_model.SaveOption(experimental_custom_gradients=False)`. In either case,\nyou will not be able to compute the gradients of the function loaded from the SavedModel.\n+## Support for partitioning\n+\n+jax2tf supports JAX functions that use `jax.pjit`, for single-host meshes.\n+The conversion is actually similar as for a `jax.jit`, except that the\n+arguments and results will be wrapped with\n+`tensorflow.compiler.xla.experimental.xla_sharding.XlaSharding` TensorFlow ops.\n+\n+Note that when saving a model, the parameters to the model are wrapped with\n+`tf.Variable` before calling the converted function (see [above](#saved_model_with_parameters)),\n+therefore outside of the `XlaSharding` wrapper.\n## Shape-polymorphic conversion\n@@ -318,7 +328,6 @@ specification for the argument `x` of a function, JAX will know that a condition\n`x.shape[-2] == x.shape[-1]` is `True`, and will also know that `x` and `jnp.sin(x)` have the\nsame shape of a batch of square matrices that can be passed to `jnp.matmul`.\n-\n### Correctness of shape-polymorphic tracing\nWe want to trust that the converted program produces the same results as the\n@@ -655,7 +664,7 @@ in [savedmodel_test.py](https://github.com/google/jax/blob/main/jax/experimental\n### Missing converter features\nThere is currently no support for `pmap` or`xmap`, nor for the collective\n-operations. There is support for `sharded_jit` and `pjit`.\n+operations. There is support for `pjit`.\n### SavedModel may be large\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/sharding_test.py", "new_path": "jax/experimental/jax2tf/tests/sharding_test.py", "diff": "import functools\nimport logging\n+import os\nimport re\nfrom typing import Any, Sequence\nimport unittest\n@@ -30,7 +31,7 @@ from jax.experimental import pjit\nfrom jax.experimental.jax2tf.tests import tf_test_util\nfrom jax.interpreters.pxla import PartitionSpec as P\nimport jax.numpy as jnp\n-import jax._src.lib.xla_bridge\n+from jax._src.lib import xla_bridge\nimport numpy as np\n@@ -38,15 +39,29 @@ import tensorflow as tf # type: ignore[import]\nconfig.parse_flags_with_absl()\n+prev_xla_flags = None\ndef setUpModule():\n+ global prev_xla_flags\n+ prev_xla_flags = os.getenv(\"XLA_FLAGS\")\n+ flags_str = prev_xla_flags or \"\"\n+ # Don't override user-specified device count, or other XLA flags.\n+ if \"xla_force_host_platform_device_count\" not in flags_str:\n+ os.environ[\"XLA_FLAGS\"] = (flags_str +\n+ \" --xla_force_host_platform_device_count=8\")\n+ # Clear any cached backends so new CPU backend will pick up the env var.\n+ xla_bridge.get_backend.cache_clear()\njtu.set_spmd_lowering_flag(True)\n+\ndef tearDownModule():\n+ if prev_xla_flags is None:\n+ del os.environ[\"XLA_FLAGS\"]\n+ else:\n+ os.environ[\"XLA_FLAGS\"] = prev_xla_flags\n+ xla_bridge.get_backend.cache_clear()\njtu.restore_spmd_lowering_flag()\n-LOG_HLO = True\n-\nclass ShardedJitHloTest(tf_test_util.JaxToTfTestCase):\n\"\"\"Tests that inspect the HLO for the sharding annotations.\n@@ -59,7 +74,8 @@ class ShardedJitHloTest(tf_test_util.JaxToTfTestCase):\n*,\nexpected: Sequence[str],\nexpected_opt: Sequence[str],\n- num_partitions=2):\n+ num_partitions=2,\n+ num_variables=0):\n\"\"\"Check expected patterns in the HLO generated from f_jax and its conversion.\nWe run this check on CPU also, which is useful for debugging locally.\n@@ -69,18 +85,20 @@ class ShardedJitHloTest(tf_test_util.JaxToTfTestCase):\nSee `self.AssertShardingAnnotations` for documentation of `expected`\nand `expected_opt`.\n+\n+ num_variables: the number of `args` to be wrapped with tf.Variable.\n\"\"\"\nif jtu.device_under_test() == \"gpu\":\nraise unittest.SkipTest(\"Sharding HLO tests not useful for GPU\")\njax_comp = f_jax.lower(*args).compiler_ir(dialect=\"hlo\")\njax_hlo = jax_comp.as_hlo_text()\n- if LOG_HLO:\nlogging.info(\"[%s] got JAX HLO %s\", self._testMethodName, jax_hlo)\n- self.AssertShardingAnnotations(\"JAX before optimizations\", jax_hlo, expected)\n+ self._assert_sharding_annotations(\"JAX before optimizations\", jax_hlo, expected)\n+ # We only dump JAX optimized code on the TPU\nif jtu.device_under_test() == \"tpu\":\n- backend = jax._src.lib.xla_bridge.get_backend()\n+ backend = xla_bridge.get_backend()\nnum_replicas = 1\ndevice_assignment = np.arange(num_partitions * num_replicas)\ndevice_assignment = np.reshape(device_assignment, (-1, num_partitions))\n@@ -93,29 +111,36 @@ class ShardedJitHloTest(tf_test_util.JaxToTfTestCase):\n)\njax_optimized_hlo = backend.compile(\njax_comp, compile_options).hlo_modules()[0].to_string()\n- if LOG_HLO:\nlogging.info(\"[%s] got JAX optimized HLO for platform %s %s\",\nself._testMethodName, backend.platform, jax_optimized_hlo)\n- self.AssertShardingAnnotations(\"JAX after optimizations\",\n+ self._assert_sharding_annotations(\"JAX after optimizations\",\njax_optimized_hlo, expected_opt)\n- f_tf = jax2tf.convert(f_jax)\n+ f_tf_base = jax2tf.convert(f_jax, with_gradient=False)\n+ if num_variables > 0:\n+ args_vars = [tf.Variable(a) for a in args[:num_variables]]\n+ args = args[:num_variables]\n+ f_tf = lambda *inputs: f_tf_base(*args_vars, *inputs)\n+ else:\n+ f_tf = f_tf_base\n+ f_tf_fun = tf.function(f_tf, jit_compile=True, autograph=False)\n+ logging.info(\"[%s] Got TF graph %s\",\n+ self._testMethodName,\n+ f_tf_fun.get_concrete_function(*args).graph.as_graph_def())\ndevice_name = f\"/device:{jtu.device_under_test().upper()}:0\"\n- tf_hlo = (tf.function(f_tf, jit_compile=True, autograph=False)\n+ tf_hlo = (f_tf_fun\n.experimental_get_compiler_ir(*args)(stage=\"hlo\",\ndevice_name=device_name))\n- if LOG_HLO:\nlogging.info(\"[%s] got TF HLO %s\", self._testMethodName, tf_hlo)\n- self.AssertShardingAnnotations(\"TF before optimizations\", tf_hlo, expected)\n+ self._assert_sharding_annotations(\"TF before optimizations\", tf_hlo, expected)\ntf_optimized_hlo = (\ntf.function(f_tf, jit_compile=True)\n.experimental_get_compiler_ir(*args)(stage=\"optimized_hlo\",\ndevice_name=device_name))\n- if LOG_HLO:\nlogging.info(\"[%s] got TF optimized HLO for %s: %s\", self._testMethodName,\ndevice_name, tf_optimized_hlo)\n- def AssertShardingAnnotations(self, what: str, hlo: str,\n+ def _assert_sharding_annotations(self, what: str, hlo: str,\nexpected: Sequence[str]):\n\"\"\"Args:\n@@ -153,8 +178,8 @@ class ShardedJitHloTest(tf_test_util.JaxToTfTestCase):\nshape = (8, 10)\nx = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\nhlo = jax_func.lower(x, x).compiler_ir(dialect=\"hlo\").as_hlo_text()\n- print(f\"HLO is {hlo}\")\n- print(f\"JAXPR is {jax.make_jaxpr(jax_func)(x, x)}\")\n+ logging.info(\"HLO is %s\", hlo)\n+ logging.info(\"JAXPR is %s\", jax.make_jaxpr(jax_func)(x, x))\nself._check_sharding_annotations(\njax_func, [x, x],\nexpected=[\n@@ -168,6 +193,34 @@ class ShardedJitHloTest(tf_test_util.JaxToTfTestCase):\n],\nnum_partitions=2)\n+ @jtu.with_mesh([(\"x\", 2)])\n+ def test_pjit_basic1D_variable(self):\n+ # The first argument is a tf.Variable\n+ @functools.partial(pjit.pjit,\n+ in_axis_resources=(P(\"x\"), P(\"x\")),\n+ out_axis_resources=None)\n+ def jax_func(x, y):\n+ return x + y\n+\n+ shape = (8, 10)\n+ x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n+ hlo = jax_func.lower(x, x).compiler_ir(dialect=\"hlo\").as_hlo_text()\n+ logging.info(\"HLO is %s\", hlo)\n+ logging.info(\"JAXPR is %s\", jax.make_jaxpr(jax_func)(x, x))\n+ self._check_sharding_annotations(\n+ jax_func, [x, x],\n+ expected=[\n+ r\"f32\\[8,10\\].*sharding={devices=\\[2,1\\]\", # x and y\n+ r\"f32\\[8,10\\].*sharding={replicated\", # output\n+ ],\n+ expected_opt=[\n+ r\"f32\\[4,10\\].*sharding={devices=\\[2,1\\]\", # x and y\n+ # TODO: why don't we see \"sharding={replicated\"\n+ r\"f32\\[8,10\\]\", # output\n+ ],\n+ num_partitions=2,\n+ num_variables=1)\n+\n@jtu.with_mesh([(\"x\", 2), (\"y\", 2)])\ndef test_pjit_basic2D(self):\n@functools.partial(pjit.pjit,\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Improved documentation and tests for pjit
260,411
25.07.2022 11:31:16
-10,800
a4f312d9c36510b858d98bbfc455ad0535d71809
[loops] Remove jax.experimental.loops. Has been deprecated since April 2022. See issue for an alternative API.
[ { "change_type": "DELETE", "old_path": "jax/experimental/loops.py", "new_path": null, "diff": "-# Copyright 2019 Google LLC\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# https://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-\"\"\"Loops is **DEPRECATED** and will be removed in August 2022.\n-\n-Here is a quick recipe for replacing usage of this module with standard\n-JAX APIs:\n-\n-Where you would be using::\n-\n- from jax.experimental import loops\n- with loops.Scope() as s:\n- s.arr = np.zeros(5) # Create the mutable state of the loop as `scope` fields.\n- s.other = 0\n- for i in s.range(s.arr.shape[0]):\n- s.arr = s.arr.at[i].set(s.arr[i] + 2.)\n- s.other += 1\n-\n-you can now create a dictionary (or any other Python container) to keep the\n-loop-carried state (`arr` and `other` in this case),\n-and use a :func:`lax.fori_loop` instead::\n-\n- def loop_body(i, s):\n- s[\"arr\"] = s[\"arr\"].at[i].set(s[\"arr\"][i] + 2.)\n- s[\"other\"] += 1\n- return s\n- init_s = dict(arr=np.zeros(5), other=0)\n- s = lax.fori_loop(0, s.arr.shape[0], loop_body, init_s)\n-\n-Below is the original documentation of the loops module:\n-\n-Loops is an **experimental** module for syntactic sugar for loops and control-flow.\n-\n-The current implementation should convert loops correctly to JAX internal\n-representation, and most transformations should work (see below), but we have\n-not yet fine-tuned the performance of the resulting XLA compilation!\n-\n-By default, loops and control-flow in JAX are executed and inlined during tracing.\n-For example, in the following code the `for` loop is unrolled during JAX tracing::\n-\n- arr = np.zeros(5)\n- for i in range(arr.shape[0]):\n- arr[i] += 2.\n- if i % 2 == 0:\n- arr[i] += 1.\n-\n-In order to capture the structured control-flow one can use the higher-order\n-JAX operations, which require you to express the body of the loops and\n-conditionals as functions, and the array updates using a functional style that\n-returns an updated array, e.g.::\n-\n- arr = np.zeros(5)\n- def loop_body(i, acc_arr):\n- arr1 = acc_arr.at[i].set(acc_arr[i] + 2.)\n- return lax.cond(i % 2 == 0,\n- arr1,\n- lambda arr1: arr1.at[i].set(arr1[i] + 1),\n- arr1,\n- lambda arr1: arr1)\n- arr = lax.fori_loop(0, arr.shape[0], loop_body, arr)\n-\n-This API quickly gets unreadable with deeper nested loops.\n-With the utilities in this module you can write loops and conditionals that\n-look closer to plain Python, as long as you keep the loop-carried state in a\n-special `loops.scope` object and use `for` loops over special\n-`scope.range` iterators::\n-\n- from jax.experimental import loops\n- with loops.Scope() as s:\n- s.arr = np.zeros(5) # Create the mutable state of the loop as `scope` fields.\n- for i in s.range(s.arr.shape[0]):\n- s.arr = s.arr.at[i].set(s.arr[i] + 2.)\n- for _ in s.cond_range(i % 2 == 0): # Conditionals as loops with 0 or 1 iterations\n- s.arr = s.arr.at[i].set(s.arr[i] + 1.)\n-\n-Loops constructed with `range` must have literal constant bounds. If you need\n-loops with dynamic bounds, you can use the more general `while_range` iterator.\n-However, in that case the `grad` transformation is not supported::\n-\n- s.idx = start\n- for _ in s.while_range(lambda: s.idx < end):\n- s.idx += 1\n-\n-Notes:\n- * Loops and conditionals to be functionalized can appear only inside scopes\n- constructed with `loops.Scope` and they must use one of the `Scope.range`\n- iterators. All other loops are unrolled during tracing, as usual in JAX.\n- * Only scope data (stored in fields of the scope object) is functionalized.\n- All other state, e.g., in other Python variables, will not be considered as\n- being part of the loop output. All references to the mutable state should be\n- through the scope, e.g., `s.arr`.\n- * The scope fields can be pytrees, and can themselves be mutable data structures.\n- * Conceptually, this model is still \"functional\" in the sense that a loop over\n- a `Scope.range` behaves as a function whose input and output is the scope data.\n- * Scopes should be passed down to callees that need to use loop\n- functionalization, or they may be nested.\n- * The programming model is that the loop body over a `scope.range` is traced\n- only once, using abstract shape values, similar to how JAX traces function\n- bodies.\n-\n-Restrictions:\n- * The tracing of the loop body should not exit prematurely with `return`,\n- `exception`, `break`. This would be detected and reported as errors when we\n- encounter unnested scopes.\n- * The loop index variable should not be used after the loop. Similarly, one\n- should not use outside the loop data computed in the loop body, except data\n- stored in fields of the scope object.\n- * No new mutable state can be created inside a loop to be functionalized.\n- All mutable state must be created outside all loops and conditionals.\n- * Once the loop starts all updates to loop state must be with new values of the\n- same abstract values as the values on loop start.\n- * For a `while` loop, the conditional function is not allowed to modify the\n- scope state. This is a checked error. Also, for `while` loops, the `grad`\n- transformation does not work. An alternative that allows `grad` is a bounded\n- loop (`range`).\n-\n-Transformations:\n- * All transformations are supported, except `grad` is not supported for\n- `Scope.while_range` loops.\n- * `vmap` is very useful for such loops because it pushes more work into the\n- inner-loops, which should help performance for accelerators.\n-\n-For usage example, see tests/loops_test.py.\n-\"\"\"\n-\n-from functools import partial\n-import itertools\n-import numpy as np\n-import traceback\n-from typing import Any, Dict, List, cast\n-from warnings import warn\n-\n-from jax import lax, core\n-from jax._src.lax import control_flow as lax_control_flow\n-from jax import tree_util\n-from jax.errors import UnexpectedTracerError\n-from jax.interpreters import partial_eval as pe\n-from jax._src import source_info_util\n-from jax._src.util import safe_map\n-\n-\n-class Scope:\n- \"\"\"A scope context manager to keep the state of loop bodies for functionalization.\n-\n- Usage::\n-\n- with Scope() as s:\n- s.data = 0.\n- for i in s.range(5):\n- s.data += 1.\n- return s.data\n-\n- \"\"\"\n-\n- def __init__(self):\n- warn(\"`jax.experimental.loops` is deprecated and will be removed in August 2022. \"\n- \"See https://jax.readthedocs.io/en/latest/jax.experimental.loops.html?highlight=deprecated#module-jax.experimental.loops.\",\n- DeprecationWarning)\n- # state to be functionalized, indexed by names, can be pytrees\n- self._mutable_state: Dict[str, Any] = {}\n- # the pytrees of abstract values; set when the loop starts.\n- self._mutable_state_aval: Dict[str, core.AbstractValue] = {}\n-\n- self._active_ranges = [] # stack of active ranges, last one is the innermost.\n- self._count_subtraces = 0 # How many net started subtraces, for error recovery\n-\n- def range(self, first, second=None, third=None):\n- \"\"\"Creates an iterator for bounded iterations to be functionalized.\n-\n- The body is converted to a `lax.scan`, for which all JAX transformations work.\n- The `first`, `second`, and `third` arguments must be integer literals.\n-\n- Usage::\n-\n- range(5) # start=0, end=5, step=1\n- range(1, 5) # start=1, end=5, step=1\n- range(1, 5, 2) # start=1, end=5, step=2\n-\n- s.out = 1.\n- for i in scope.range(5):\n- s.out += 1.\n- \"\"\"\n- if third is not None:\n- start = int(first)\n- stop = int(second)\n- step = int(third)\n- else:\n- step = 1\n- if second is not None:\n- start = int(first)\n- stop = int(second)\n- else:\n- start = 0\n- stop = int(first)\n- return _BodyTracer(self, _BoundedLoopBuilder(start, stop, step))\n-\n- def cond_range(self, pred):\n- \"\"\"Creates a conditional iterator with 0 or 1 iterations based on the boolean.\n-\n- The body is converted to a `lax.cond`. All JAX transformations work.\n-\n- Usage::\n-\n- for _ in scope.cond_range(s.field < 0.):\n- s.field = - s.field\n- \"\"\"\n- # TODO: share these checks with lax_control_flow.cond\n- if len(np.shape(pred)) != 0:\n- raise TypeError(\n- f\"Pred must be a scalar, got {pred} of shape {np.shape(pred)}.\")\n-\n- try:\n- pred_dtype = np.result_type(pred)\n- except TypeError as err:\n- msg = (\"Pred type must be either boolean or number, got {}.\")\n- raise TypeError(msg.format(pred)) from err\n-\n- if pred_dtype.kind != 'b':\n- if pred_dtype.kind in 'iuf':\n- pred = pred != 0\n- else:\n- msg = (\"Pred type must be either boolean or number, got {}.\")\n- raise TypeError(msg.format(pred_dtype))\n-\n- return _BodyTracer(self, _CondBuilder(pred))\n-\n- def while_range(self, cond_func):\n- \"\"\"Creates an iterator that continues as long as `cond_func` returns true.\n-\n- The body is converted to a `lax.while_loop`.\n- The `grad` transformation does not work.\n-\n- Usage::\n-\n- for _ in scope.while_range(lambda: s.loss > 1.e-5):\n- s.loss = loss(...)\n-\n- Args:\n- cond_func: a lambda with no arguments, the condition for the \"while\".\n- \"\"\"\n- return _BodyTracer(self, _WhileBuilder(cond_func))\n-\n- def _push_range(self, range_):\n- for ar in self._active_ranges:\n- if ar is range_:\n- raise ValueError(\"Range is reused nested inside itself.\")\n- self._active_ranges.append(range_)\n-\n- def _pop_range(self, range_):\n- if not (range_ is self._active_ranges[-1]):\n- self._error_premature_exit_range()\n- self._active_ranges.pop()\n-\n- def _error_premature_exit_range(self):\n- \"\"\"Raises error about premature exit from a range\"\"\"\n- msg = \"Some ranges have exited prematurely. The innermost such range is at\\n{}\"\n- raise ValueError(msg.format(self._active_ranges[-1].location()))\n-\n- def __getattr__(self, key):\n- \"\"\"Accessor for scope data.\n-\n- Called only if the attribute is not found, which will happen when we read\n- scope data that has been stored in self._mutable_state.\n- \"\"\"\n- mt_val = self._mutable_state.get(key)\n- if mt_val is None:\n- raise AttributeError(\n- f\"Reading uninitialized data '{key}' from the scope.\")\n- return mt_val\n-\n- def __setattr__(self, key, value):\n- \"\"\"Update scope data to be functionalized.\n-\n- Called for *all* attribute setting.\n- \"\"\"\n- if key in [\"_active_ranges\", \"_mutable_state\", \"_mutable_state_aval\", \"_count_subtraces\"]:\n- object.__setattr__(self, key, value)\n- else:\n- if self._active_ranges:\n- if key not in self._mutable_state:\n- raise ValueError(\n- f\"New mutable state '{key}' cannot be created inside a loop.\")\n- assert key in self._mutable_state_aval\n- old_aval = self._mutable_state_aval[key]\n- flat_values, flat_tree = tree_util.tree_flatten(value)\n- new_aval = flat_tree.unflatten(safe_map(_BodyTracer.abstractify, flat_values))\n- if old_aval != new_aval:\n- msg = (f\"Mutable state '{key}' is updated with new abstract value \"\n- f\"{new_aval}, which is different from previous one {old_aval}\")\n- raise TypeError(msg)\n- self._mutable_state[key] = value\n-\n- def __enter__(self):\n- return self\n-\n- def __exit__(self, exc_type, exc_val, exc_tb):\n- try:\n- if exc_type is None:\n- if self._active_ranges: # We have some ranges that we did not exit properly\n- self._error_premature_exit_range()\n- return True\n- else:\n- # The exception may come from inside one or more ranges. We let the current\n- # exception propagate, assuming it terminates the tracing. If not, the\n- # tracers may be left in an inconsistent state.\n- return 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_main.\n- level = core.thread_local_state.trace_state.trace_stack.next_level()\n- name_stack = source_info_util.current_name_stack()\n- main = core.MainTrace(level, pe.JaxprTrace, name_stack=name_stack)\n- core.thread_local_state.trace_state.trace_stack.push(main)\n- self._count_subtraces += 1\n- return pe.JaxprTrace(main, core.cur_sublevel(), name_stack=name_stack)\n-\n- def end_subtrace(self):\n- # TODO: This follows the __exit__ part of core.new_main\n- core.thread_local_state.trace_state.trace_stack.pop()\n- self._count_subtraces -= 1\n-\n-\n-class _BodyTracer:\n- \"\"\"Traces the body of the loop and builds a functional control-flow representation.\n-\n- This class is also an iterator, only the first iteration is traced.\n- \"\"\"\n-\n- def __init__(self, scope, loop_builder):\n- \"\"\"\n- Params:\n- scope: the current scope\n- loop_builder: instance of _LoopBuilder\n- \"\"\"\n- self.scope = scope\n- self.loop_builder = loop_builder\n- self.first_iteration = True # If we are tracing the first iteration\n- # Stack trace, without this line and the s.range function\n- self.stack = traceback.StackSummary.from_list(\n- cast(List[Any], traceback.extract_stack()[:-2]))\n-\n- # Next are state kept from the start of the first iteration to the end of the iteration.\n- # List of scope fields carried through the loop\n- self.carried_state_names: List[str] = None\n- self.carried_state_initial = {} # Copy of the initial values of state, before loop starts\n- # The parameters that were created for state upon entering an arbitrary iteration.\n- self.carried_state_vars = {} # For each state, the list of Tracer variables introduced\n- # when starting to trace the loop body.\n-\n- self.trace = None\n-\n- def location(self):\n- \"\"\"A multiline string representing the source location of the range.\"\"\"\n- if self.stack is not None:\n- return \" \".join(self.stack.format())\n- else:\n- return \"\"\n-\n- def __iter__(self):\n- \"\"\"Called before starting the first iteration.\"\"\"\n- self.first_iteration = True # In case we reuse the range\n- return self\n-\n- def __next__(self):\n- if self.first_iteration:\n- self.first_iteration = False\n- self.scope._push_range(self)\n- self.start_tracing_body()\n- return self._index_var\n- else:\n- self.end_tracing_body()\n- self.scope._pop_range(self)\n- raise StopIteration # Trace only one iteration.\n-\n- def next(self): # For PY2\n- return self.__next__()\n-\n- def start_tracing_body(self):\n- \"\"\"Called upon starting the tracing of the loop body.\"\"\"\n- # TODO: This is the first part of partial_eval.trace_to_subjaxpr. Share.\n- self.trace = self.scope.start_subtrace()\n- # The entire state is carried.\n- self.carried_state_names = sorted(self.scope._mutable_state.keys())\n- for key in self.carried_state_names:\n- init_val = self.scope._mutable_state[key]\n- flat_init_vals, init_tree = tree_util.tree_flatten(init_val)\n- flat_init_avals = safe_map(_BodyTracer.abstractify, flat_init_vals)\n- flat_init_pvals = safe_map(pe.PartialVal.unknown, flat_init_avals)\n- flat_init_vars = safe_map(self.trace.new_arg, flat_init_pvals)\n- self.carried_state_vars[key] = flat_init_vars\n- # Set the scope._mutable_state to new tracing variables.\n- self.scope._mutable_state[key] = init_tree.unflatten(flat_init_vars)\n- self.scope._mutable_state_aval[key] = init_tree.unflatten(flat_init_avals)\n- # Make a copy of the initial state by unflattening the flat_init_vals\n- self.carried_state_initial[key] = init_tree.unflatten(flat_init_vals)\n-\n- index_var_aval = _BodyTracer.abstractify(0)\n- index_var_pval = pe.PartialVal.unknown(index_var_aval)\n- self._index_var = self.trace.new_arg(index_var_pval)\n-\n- def end_tracing_body(self):\n- \"\"\"Called when we are done tracing one iteration of the body.\"\"\"\n- # We will turn the body of the loop into a function that takes some values\n- # for the scope state (carried_state_names) and returns the values for the\n- # same state fields after one execution of the body. For some of the ranges,\n- # e.g., scope.range, the function will also take the index_var as last parameter.\n- in_tracers = tuple(itertools.chain(*[self.carried_state_vars[ms] for ms in self.carried_state_names]))\n- if self.loop_builder.can_use_index_var():\n- in_tracers += (self._index_var,)\n-\n- # Make the jaxpr for the body of the loop\n- # TODO: See which mutable state was changed in the one iteration.\n- # For now, we assume all state changes.\n- body_out_tracers = []\n- for key in self.carried_state_names:\n- new_val = self.scope._mutable_state[key]\n- flat_new_values, flat_new_tree = tree_util.tree_flatten(new_val)\n- body_out_tracers.extend(flat_new_values)\n- assert key in self.scope._mutable_state_aval\n- old_aval = self.scope._mutable_state_aval[key]\n- new_aval = flat_new_tree.unflatten(safe_map(_BodyTracer.abstractify, flat_new_values))\n- if old_aval != new_aval:\n- msg = (f\"Mutable state '{key}' had at the end of the loop body new abstract value \"\n- f\"{new_aval}, which is different from initial one {old_aval}\")\n- raise TypeError(msg)\n-\n- try:\n- # If the body actually uses the index variable, and is not allowed to\n- # (e.g., cond_range and while_range), then in_tracers will not contain\n- # the tracer for the index_var, and trace_to_jaxpr_finalize will throw\n- # an assertion error.\n- body_closed_jaxpr, body_const_vals = _BodyTracer.trace_to_jaxpr_finalize(\n- in_tracers=in_tracers,\n- out_tracers=body_out_tracers,\n- trace=self.trace)\n- except UnexpectedTracerError as e:\n- if \"Tracer not among input tracers\" in str(e):\n- raise ValueError(\"Body of cond_range or while_range should not use the \"\n- \"index variable returned by iterator.\") from e\n- raise\n- # End the subtrace for the loop body, before we trace the condition\n- self.scope.end_subtrace()\n-\n- carried_init_val = tuple(self.carried_state_initial[ms]\n- for ms in self.carried_state_names)\n- carried_init_vals, carried_tree = tree_util.tree_flatten(carried_init_val)\n- assert len(carried_init_vals) == len(body_out_tracers)\n-\n- carried_out_vals = self.loop_builder.build_output_vals(\n- self.scope, self.carried_state_names, carried_tree,\n- carried_init_vals, body_closed_jaxpr, body_const_vals)\n- carried_mutable_state_unflattened = tree_util.tree_unflatten(carried_tree,\n- carried_out_vals)\n-\n- # Update the mutable state with the values of the changed vars, after the loop.\n- for ms, mv in zip(self.carried_state_names, carried_mutable_state_unflattened):\n- self.scope._mutable_state[ms] = mv\n-\n- @staticmethod\n- def abstractify(x):\n- return core.raise_to_shaped(core.get_aval(x), weak_type=False)\n-\n- @staticmethod\n- def trace_to_jaxpr_finalize(in_tracers, out_tracers, trace, instantiate=True):\n- # TODO: This is the final part of the partial_eval.trace_to_subjaxpr. Share.\n- instantiate = [instantiate] * len(out_tracers)\n- out_tracers = safe_map(trace.full_raise, safe_map(core.full_lower, out_tracers))\n- out_tracers = safe_map(partial(pe.instantiate_const_at, trace),\n- instantiate, out_tracers)\n- jaxpr, consts, env = pe.tracers_to_jaxpr(in_tracers, out_tracers)\n- assert not env # TODO: this is from partial_eval.trace_to_jaxpr. Share.\n- closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())\n- return closed_jaxpr, consts\n-\n-\n-class _LoopBuilder:\n- \"\"\"Abstract superclass for the loop builders\"\"\"\n-\n- def can_use_index_var(self):\n- \"\"\"Whether this kind of loop can use the index var returned by the range iterator.\"\"\"\n- raise NotImplementedError\n-\n- def build_output_vals(self, scope, carried_state_names, carried_tree,\n- init_vals, body_closed_jaxpr, body_const_vals):\n- \"\"\"Builds the output values for the loop carried state.\n-\n- Params:\n- scope: the current Scope object.\n- carried_state_names: the list of names of mutable state fields that is\n- carried through the body.\n- carried_tree: the PyTreeDef for the tuple of carried_state_names.\n- init_vals: the initial values on body entry corresponding to the init_tree.\n- body_closed_jaxpr: the Jaxpr for the body returning the new values of\n- carried_state_names.\n- body_const_vals: the constant values for the body.\n-\n- Returns:\n- the output tracer corresponding to the lax primitive representing the loop.\n- \"\"\"\n- raise NotImplementedError\n-\n- def __str__(self):\n- raise NotImplementedError\n-\n-\n-class _BoundedLoopBuilder(_LoopBuilder):\n- \"\"\"Builds a lax operation corresponding to a bounded range iteration.\"\"\"\n-\n- def __init__(self, start, stop, step):\n- self.start = start\n- self.stop = stop\n- self.step = step\n- self._index_var = None # The parameter for the index variable\n-\n- def can_use_index_var(self):\n- return True\n-\n- def build_output_vals(self, scope, carried_state_names, carried_tree,\n- init_vals, body_closed_jaxpr, body_const_vals):\n- arange_val = np.arange(self.start, stop=self.stop, step=self.step)\n- return lax_control_flow.scan_p.bind(*body_const_vals, *init_vals, arange_val,\n- reverse=False, length=arange_val.shape[0],\n- jaxpr=body_closed_jaxpr,\n- num_consts=len(body_const_vals),\n- num_carry=len(init_vals),\n- linear=(False,) * (len(body_const_vals) +\n- len(init_vals) + 1),\n- unroll=1)\n-\n-\n-class _CondBuilder(_LoopBuilder):\n- \"\"\"Builds a lax.cond operation.\"\"\"\n-\n- def __init__(self, pred):\n- self.index = lax.convert_element_type(pred, np.int32)\n-\n- def can_use_index_var(self):\n- return False\n-\n- def build_output_vals(self, scope, carried_state_names, carried_tree,\n- init_vals, body_closed_jaxpr, body_const_vals):\n- # Simulate a pass-through false branch\n- in_vals, in_tree = tree_util.tree_flatten(\n- (body_const_vals, tree_util.tree_unflatten(carried_tree, init_vals)))\n- in_avals = safe_map(_BodyTracer.abstractify, in_vals)\n- pass_through_closed_jaxpr, pass_through_const_vals, _ = (\n- lax_control_flow._initial_style_jaxpr(\n- lambda *args: args[1],\n- in_tree,\n- tuple(in_avals)))\n- assert len(pass_through_const_vals) == 0\n- args = [*body_const_vals, *init_vals]\n- return lax_control_flow.cond_p.bind(\n- self.index, *args,\n- branches=(pass_through_closed_jaxpr, body_closed_jaxpr),\n- linear=(False,) * len(args))\n-\n-\n-class _WhileBuilder(_LoopBuilder):\n- \"\"\"Builds a lax.while operation.\"\"\"\n-\n- def __init__(self, cond_func):\n- self.cond_func = cond_func # Function with 0 arguments (can reference the scope)\n-\n- def can_use_index_var(self):\n- return False\n-\n- def build_output_vals(self, scope, carried_state_names, carried_tree,\n- init_vals, body_closed_jaxpr, body_const_vals):\n- # Trace the conditional function. cond_func takes 0 arguments, but\n- # for lax.while we need a conditional function that takes the\n- # carried_state_names. _initial_style_jaxpr will start its own trace and\n- # will create tracers for all the carried state. We must put these values\n- # in the scope._mutable_state before we trace the conditional\n- # function.\n- def cond_func_wrapped(*args):\n- assert len(args) == len(carried_state_names)\n- for ms, init_ms in zip(carried_state_names, args):\n- scope._mutable_state[ms] = init_ms\n- res = self.cond_func()\n- # Conditional function is not allowed to modify the scope state\n- for ms, init_ms in zip(carried_state_names, args):\n- if not (scope._mutable_state[ms] is init_ms):\n- raise ValueError(f\"Conditional function modifies scope.{ms} field.\")\n- return res\n-\n- init_avals = safe_map(_BodyTracer.abstractify, init_vals)\n- cond_jaxpr, cond_consts, cond_tree = (\n- lax_control_flow._initial_style_jaxpr(cond_func_wrapped,\n- carried_tree,\n- tuple(init_avals)))\n- # TODO: share these checks with lax_control_flow.while\n- if not tree_util.treedef_is_leaf(cond_tree):\n- raise TypeError(f\"cond_fun must return a boolean scalar, but got pytree {cond_tree}.\")\n- if not safe_map(core.typecompat, cond_jaxpr.out_avals, [core.ShapedArray((), np.bool_)]):\n- raise TypeError(f\"cond_fun must return a boolean scalar, but got output type(s) \"\n- f\"{cond_jaxpr.out_avals}.\")\n-\n- return lax_control_flow.while_p.bind(*cond_consts, *body_const_vals, *init_vals,\n- cond_nconsts=len(cond_consts),\n- cond_jaxpr=cond_jaxpr,\n- body_nconsts=len(body_const_vals),\n- body_jaxpr=body_closed_jaxpr)\n" } ]
Python
Apache License 2.0
google/jax
[loops] Remove jax.experimental.loops. Has been deprecated since April 2022. See issue #10278 for an alternative API.
260,510
25.07.2022 17:01:20
25,200
436e9dd09b9ed8ab4ed7a50cc6b4456d11de2f68
Add help docstrings for debugger Refactor colab debugger to use more from base class
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugger/cli_debugger.py", "new_path": "jax/_src/debugger/cli_debugger.py", "diff": "from __future__ import annotations\nimport cmd\n+import pprint\nimport sys\nimport traceback\n@@ -46,62 +47,108 @@ class CliDebugger(cmd.Cmd):\nenv.update(curr_frame.locals)\nreturn eval(expr, {}, env)\n+ def default(self, arg):\n+ \"\"\"Evaluates an expression.\"\"\"\n+ try:\n+ print(repr(self.evaluate(arg)), file=self.stdout)\n+ except:\n+ self._error_message()\n+\ndef print_backtrace(self):\n- self.stdout.write('Traceback:\\n')\n+ print('Traceback:', file=self.stdout)\nfor frame in self.frames[::-1]:\nself.stdout.write(f' File \"{frame.filename}\", line {frame.lineno}\\n')\nif frame.offset is None:\n- self.stdout.write(' <no source>\\n')\n+ print(' <no source>', file=self.stdout)\nelse:\nline = frame.source[frame.offset]\n- self.stdout.write(f' {line}\\n')\n+ print(f' {line.strip()}', file=self.stdout)\ndef print_context(self, num_lines=2):\ncurr_frame = self.frames[self.frame_index]\n- self.stdout.write(f'> {curr_frame.filename}({curr_frame.lineno})\\n')\n+ print(f'> {curr_frame.filename}({curr_frame.lineno})', file=self.stdout)\nfor i, line in enumerate(curr_frame.source):\nassert curr_frame.offset is not None\nif (curr_frame.offset - 1 - num_lines <= i <=\ncurr_frame.offset + num_lines):\nif i == curr_frame.offset:\n- self.stdout.write(f'-> {line}\\n')\n+ print(f'-> {line}', file=self.stdout)\nelse:\n- self.stdout.write(f' {line}\\n')\n+ print(f' {line}', file=self.stdout)\n+\n+ def _error_message(self):\n+ exc_info = sys.exc_info()[:2]\n+ msg = traceback.format_exception_only(*exc_info)[-1].strip()\n+ print('***', msg, file=self.stdout)\ndef do_p(self, arg):\n+ \"\"\"p expression\n+ Evaluates and prints the value of an expression\n+ \"\"\"\ntry:\n- self.stdout.write(repr(self.evaluate(arg)) + \"\\n\")\n- except Exception:\n- traceback.print_exc(limit=1)\n-\n- def do_u(self, arg):\n+ print(repr(self.evaluate(arg)), file=self.stdout)\n+ except:\n+ self._error_message()\n+\n+ def do_pp(self, arg):\n+ \"\"\"pp expression\n+ Evaluates and pretty-prints the value of an expression\n+ \"\"\"\n+ try:\n+ print(pprint.pformat(self.evaluate(arg)), file=self.stdout)\n+ except:\n+ self._error_message()\n+\n+ def do_up(self, _):\n+ \"\"\"u(p)\n+ Move down a stack frame.\n+ \"\"\"\nif self.frame_index == len(self.frames) - 1:\n- self.stdout.write('At topmost frame.\\n')\n+ print('At topmost frame.', file=self.stdout)\nelse:\nself.frame_index += 1\nself.print_context()\n+ do_u = do_up\n- def do_d(self, arg):\n+ def do_down(self, _):\n+ \"\"\"d(own)\n+ Move down a stack frame.\n+ \"\"\"\nif self.frame_index == 0:\n- self.stdout.write('At bottommost frame.\\n')\n+ print('At bottommost frame.', file=self.stdout)\nelse:\nself.frame_index -= 1\nself.print_context()\n+ do_d = do_down\n- def do_l(self, arg):\n- self.print_context(num_lines=5)\n-\n- def do_ll(self, arg):\n+ def do_list(self, _):\n+ \"\"\"l(ist)\n+ List source code for the current file.\n+ \"\"\"\nself.print_context(num_lines=5)\n+ do_l = do_list\n- def do_c(self, arg):\n+ def do_continue(self, _):\n+ \"\"\"c(ont(inue))\n+ Continue the program's execution.\n+ \"\"\"\nreturn True\n+ do_c = do_cont = do_continue\n- def do_EOF(self, arg):\n+ def do_quit(self, _):\n+ \"\"\"q(uit)\\n(exit)\n+ Quit the debugger. The program is given an exit command.\n+ \"\"\"\nsys.exit(0)\n+ do_q = do_EOF = do_exit = do_quit\n- def do_bt(self, arg):\n+ def do_where(self, _):\n+ \"\"\"w(here)\n+ Prints a stack trace with the most recent frame on the bottom.\n+ 'bt' is an alias for this command.\n+ \"\"\"\nself.print_backtrace()\n+ do_w = do_bt = do_where\ndef run(self):\nwhile True:\n@@ -109,7 +156,7 @@ class CliDebugger(cmd.Cmd):\nself.cmdloop()\nbreak\nexcept KeyboardInterrupt:\n- self.stdout.write('--KeyboardInterrupt--\\n')\n+ print('--KeyboardInterrupt--', file=sys.stdout)\ndef run_debugger(frames: List[DebuggerFrame], thread_id: Optional[int],\n**kwargs: Any):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/colab_debugger.py", "new_path": "jax/_src/debugger/colab_debugger.py", "diff": "@@ -18,7 +18,7 @@ import html\nimport inspect\nimport traceback\n-from typing import List\n+from typing import IO, List\nimport uuid\n@@ -204,15 +204,23 @@ class DebuggerView(colab_lib.DynamicDOMElement):\ndef update_frame(self, frame):\nself._frame_preview.update_frame(frame)\n- def log(self, text):\n+ def write(self, text):\nself._interaction_log.append(colab_lib.pre(text))\ndef read(self):\n+ raise NotImplementedError()\n+\n+ def readline(self):\nwith output.use_tags([\"stdin\"]):\n- user_input = input()\n+ user_input = input() + \"\\n\"\noutput.clear(output_tags=[\"stdin\"])\nreturn user_input\n+ def isatty(self):\n+ return True\n+\n+ def flush(self):\n+ pass\nclass ColabDebugger(cli_debugger.CliDebugger):\n\"\"\"A JAX debugger for a Colab environment.\"\"\"\n@@ -222,84 +230,22 @@ class ColabDebugger(cli_debugger.CliDebugger):\nthread_id: int):\nsuper().__init__(frames, thread_id)\nself._debugger_view = DebuggerView(self.current_frame())\n+ self.stdout = self.stdin = self._debugger_view # type: ignore\n- def read(self):\n- return self._debugger_view.read()\n-\n- def cmdloop(self, intro=None):\n- self.preloop()\n- stop = None\n- while not stop:\n- if self.cmdqueue:\n- line = self.cmdqueue.pop(0)\n- else:\n- try:\n- line = self.read()\n- except EOFError:\n- line = \"EOF\"\n- line = self.precmd(line)\n- stop = self.onecmd(line)\n- stop = self.postcmd(stop, line)\n- self.postloop()\n-\n- def do_u(self, _):\n- if self.frame_index == len(self.frames) - 1:\n- self.log(\"At topmost frame.\")\n- return False\n- self.frame_index += 1\n+ def do_up(self, arg):\n+ super().do_up(arg)\nself._debugger_view.update_frame(self.current_frame())\nreturn False\n- def do_d(self, _):\n- if self.frame_index == 0:\n- self.log(\"At bottommost frame.\")\n- return False\n- self.frame_index -= 1\n+ def do_down(self, arg):\n+ super().do_down(arg)\nself._debugger_view.update_frame(self.current_frame())\nreturn False\n- def do_bt(self, _):\n- self.log(\"Traceback:\")\n- for frame in self.frames[::-1]:\n- filename = frame.filename.strip()\n- filename = filename or \"<no filename>\"\n- self.log(f\" File: {filename}, line ({frame.lineno})\")\n- if frame.offset < len(frame.source):\n- line = frame.source[frame.offset]\n- self.log(f\" {line.strip()}\")\n- else:\n- self.log(\" \")\n-\n- def do_c(self, _):\n- return True\n-\n- def do_q(self, _):\n- return True\n-\n- def do_EOF(self, _):\n- return True\n-\n- def do_p(self, arg):\n- try:\n- value = self.evaluate(arg)\n- self.log(repr(value))\n- except Exception: # pylint: disable=broad-except\n- self.log(traceback.format_exc(limit=1))\n- return False\n-\n- do_pp = do_p\n-\n- def log(self, text):\n- self._debugger_view.log(html.escape(text))\n-\ndef run(self):\nself._debugger_view.render()\n- try:\n+ while True:\nself.cmdloop()\n- except KeyboardInterrupt:\n- self.log(\"--Keyboard-Interrupt--\")\n- pass\n- self._debugger_view.clear()\ndef _run_debugger(frames, thread_id, **kwargs):\n" } ]
Python
Apache License 2.0
google/jax
Add help docstrings for debugger Refactor colab debugger to use more from base class
260,510
25.07.2022 14:48:02
25,200
80ec269223b6ddfb2cbb76649d9426dba491b9f2
Fix debugger linenumbers
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugger/core.py", "new_path": "jax/_src/debugger/core.py", "diff": "@@ -63,8 +63,15 @@ class DebuggerFrame:\ndef from_frameinfo(cls, frame_info) -> DebuggerFrame:\ntry:\n_, start = inspect.getsourcelines(frame_info.frame)\n- source = inspect.getsource(frame_info.frame).split('\\n')\n- offset = frame_info.lineno - start\n+ source = inspect.getsource(frame_info.frame).split(\"\\n\")\n+ # Line numbers begin at 1 but offsets begin at 0. `inspect.getsource` will\n+ # return a partial view of the file and a `start` indicating the line\n+ # number that the source code starts at. However, it's possible that\n+ # `start` is 0, indicating that we are at the beginning of the file. In\n+ # this case, `offset` is just the `lineno - 1`. If `start` is nonzero,\n+ # then we subtract it off from the `lineno` and don't need to subtract 1\n+ # since both start and lineno are 1-indexed.\n+ offset = frame_info.lineno - max(start, 1)\nexcept OSError:\nsource = []\noffset = None\n" } ]
Python
Apache License 2.0
google/jax
Fix debugger linenumbers
260,268
26.07.2022 14:29:31
14,400
31d2a74aebae7390f8ca75eeed9ca3353603e497
remove broken-main-notify
[ { "change_type": "DELETE", "old_path": ".github/workflows/broken-main-notify.yml", "new_path": null, "diff": "-name: Google Chat Broken Main Notification\n-on:\n- check_suite:\n- types:\n- - completed\n- branches:\n- - main\n-\n-jobs:\n- build:\n- runs-on: ubuntu-latest\n-\n- steps:\n- - name: Google Chat Notification\n- if: ${{ github.event.check_suite.conclusion == 'failure' }}\n- run: |\n- curl --location --request POST '${{ secrets.RELEASES_WEBHOOK }}' \\\n- --header 'Content-Type: application/json' \\\n- --data-raw '{\n- \"text\": \"Main is broken! @ ${{github.event.check_suite.created_at}} see <${{github.event.check_suite.url}}|[github]>\"\n- }'\n" } ]
Python
Apache License 2.0
google/jax
remove broken-main-notify
260,424
06.07.2022 13:58:16
-3,600
53dfe35f34e270e3346639fffe935bb9fe02fba5
Fix ConcretizationError in nested calls.
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -503,7 +503,7 @@ def escaped_tracer_error(tracer, detail=None):\nf'with shape {tracer.shape} and dtype {tracer.dtype} to escape.\\n'\n'JAX transformations require that functions explicitly return their '\n'outputs, and disallow saving intermediate values to global state.')\n- dbg = getattr(tracer._trace.main, 'debug_info', None)\n+ dbg = getattr(tracer, '_debug_info', None)\nif dbg is not None:\nmsg += ('\\nThe function being traced when the value leaked was '\nf'{dbg.func_src_info} traced for {dbg.traced_for}.')\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1526,11 +1526,13 @@ def move_binders_to_back(closed_jaxpr: ClosedJaxpr, to_move: Sequence[bool]\nreturn move_binders_to_front(closed_jaxpr, map(op.not_, to_move))\nclass DynamicJaxprTracer(core.Tracer):\n- __slots__ = ['aval']\n+ __slots__ = ['aval', '_debug_info']\ndef __init__(self, trace, aval, line_info=None):\nself._trace = trace\nself._line_info = line_info\n+ # Needed for UnexpectedTracerError.\n+ self._debug_info = self._trace.frame.debug_info\nself.aval = aval\ndef full_lower(self):\n@@ -1547,13 +1549,14 @@ class DynamicJaxprTracer(core.Tracer):\nf\"{source_info_util.summarize(self._line_info)}\")\nelse:\ninvar_pos, progenitor_eqns = self._trace.frame.find_progenitors(self)\n- dbg = self._trace.main.debug_info\n+ dbg = self._debug_info\nif dbg is None:\nreturn \"\"\n+\n+ origin = (f\"The error occurred while tracing the function {dbg.func_src_info} \"\n+ f\"for {dbg.traced_for}. \")\nif invar_pos:\n- origin = (f\"While tracing the function {dbg.func_src_info} \"\n- f\"for {dbg.traced_for}, \"\n- \"this concrete value was not available in Python because it \"\n+ origin += (\"This concrete value was not available in Python because it \"\nf\"depends on the value{'s' if len(invar_pos) > 1 else ''} \"\nf\"of {dbg.arg_info(invar_pos)}.\")\nelif progenitor_eqns:\n@@ -1561,15 +1564,10 @@ class DynamicJaxprTracer(core.Tracer):\nf\"{core.pp_eqn(eqn, core.JaxprPpContext(), core.JaxprPpSettings(print_shapes=True))}\\n\"\nf\" from line {source_info_util.summarize(eqn.source_info)}\"\nfor eqn in progenitor_eqns[:5]] # show at most 5\n- origin = (f\"While tracing the function {dbg.func_src_info} \"\n- f\"for {dbg.traced_for}, \"\n- \"this value became a tracer due to JAX operations on these lines:\"\n+ origin += (\"This value became a tracer due to JAX operations on these lines:\"\n\"\\n\\n\" + \"\\n\\n\".join(msts))\nif len(progenitor_eqns) > 5:\norigin += \"\\n\\n(Additional originating lines are not shown.)\"\n- else:\n- origin = (f\"The error occurred while tracing the function {dbg.func_src_info} \"\n- f\"for {dbg.traced_for}.\")\nreturn \"\\n\" + origin\ndef _assert_live(self) -> None:\n@@ -1591,6 +1589,7 @@ class JaxprStackFrame:\neqns: List[JaxprEqn]\ninvars: List[Var]\neffects: core.Effects\n+ debug_info: Optional[DebugInfo]\ndef __init__(self):\nself.gensym = core.gensym()\n@@ -1601,6 +1600,7 @@ class JaxprStackFrame:\nself.eqns = [] # cleared when we pop frame from main\nself.invars = []\nself.effects = set()\n+ self.debug_info = None\ndef add_eqn(self, eqn: core.JaxprEqn):\nself.eqns.append(eqn)\n@@ -1821,10 +1821,13 @@ class DynamicJaxprTrace(core.Trace):\n# TODO(mattjj): check in_tracers are consistent with f.in_type annotation\nwith core.new_sublevel():\nif config.jax_check_tracer_leaks or not config.jax_experimental_subjaxpr_lowering_cache:\n- jaxpr, out_type, consts = trace_to_subjaxpr_dynamic2(f, self.main)\n+ # TODO(lenamartens): Make call_primitive name -> API function name mapping.\n+ # (currently this will display eg. 'xla_call' instead of `jit`)\n+ dbg = debug_info_final(f, call_primitive.name)\n+ jaxpr, out_type, consts = trace_to_subjaxpr_dynamic2(f, self.main, debug_info=dbg)\nelse:\njaxpr, out_type, consts = trace_to_subjaxpr_dynamic2_memoized(\n- f, self.main).val\n+ f, self.main, call_primitive.name).val\nif params.get('inline', False):\nreturn core.eval_jaxpr(jaxpr, consts, *in_tracers)\nsource_info = source_info_util.current()\n@@ -1862,7 +1865,7 @@ class DynamicJaxprTrace(core.Trace):\nwith core.extend_axis_env(axis_name, axis_size, None): # type: ignore\nwith core.new_sublevel():\njaxpr, reduced_out_avals, consts = trace_to_subjaxpr_dynamic(\n- f, self.main, reduced_in_avals)\n+ f, self.main, reduced_in_avals, debug_info=debug_info_final(f, map_primitive.name))\nordered_effects = jaxpr.effects & core.ordered_effects\nif ordered_effects:\nraise ValueError(\"Ordered effects not supported for \"\n@@ -2069,19 +2072,20 @@ def trace_to_jaxpr_dynamic(fun: lu.WrappedFun,\n*,\nkeep_inputs: Optional[List[bool]] = None):\nwith core.new_main(DynamicJaxprTrace, dynamic=True) as main: # type: ignore\n- main.debug_info = debug_info # type: ignore\nmain.jaxpr_stack = () # type: ignore\njaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(\n- fun, main, in_avals, keep_inputs=keep_inputs)\n+ fun, main, in_avals, keep_inputs=keep_inputs, debug_info=debug_info)\ndel main, fun\nreturn jaxpr, out_avals, consts\ndef trace_to_subjaxpr_dynamic(fun: lu.WrappedFun, main: core.MainTrace,\nin_avals: Sequence[AbstractValue], *,\n- keep_inputs: Optional[Sequence[bool]] = None):\n+ keep_inputs: Optional[Sequence[bool]] = None,\n+ debug_info: Optional[DebugInfo] = None):\nkeep_inputs = [True] * len(in_avals) if keep_inputs is None else keep_inputs\nframe = JaxprStackFrame()\n+ frame.debug_info = debug_info\nwith extend_jaxpr_stack(main, frame), source_info_util.reset_name_stack():\ntrace = DynamicJaxprTrace(main, core.cur_sublevel())\nin_tracers = _input_type_to_tracers(trace.new_arg, in_avals)\n@@ -2099,17 +2103,18 @@ def trace_to_jaxpr_dynamic2(\nfun: lu.WrappedFun, debug_info: Optional[DebugInfo] = None\n) -> Tuple[Jaxpr, OutputType, List[Any]]:\nwith core.new_main(DynamicJaxprTrace, dynamic=True) as main: # type: ignore\n- main.debug_info = debug_info # type: ignore\nmain.jaxpr_stack = () # type: ignore\n- jaxpr, out_type, consts = trace_to_subjaxpr_dynamic2(fun, main)\n+ jaxpr, out_type, consts = trace_to_subjaxpr_dynamic2(fun, main, debug_info)\ndel main, fun\nreturn jaxpr, out_type, consts\ndef trace_to_subjaxpr_dynamic2(\n- fun: lu.WrappedFun, main: core.MainTrace\n+ fun: lu.WrappedFun, main: core.MainTrace,\n+ debug_info: Optional[DebugInfo] = None\n) -> Tuple[Jaxpr, OutputType, List[Any]]:\nin_avals, keep_inputs = unzip2(fun.in_type)\nframe = JaxprStackFrame()\n+ frame.debug_info = debug_info\nwith extend_jaxpr_stack(main, frame), source_info_util.reset_name_stack():\ntrace = DynamicJaxprTrace(main, core.cur_sublevel())\nin_tracers = _input_type_to_tracers(trace.new_arg, in_avals)\n@@ -2123,8 +2128,10 @@ def trace_to_subjaxpr_dynamic2(\n@lu.cache\ndef trace_to_subjaxpr_dynamic2_memoized(fun: lu.WrappedFun,\n- main: core.MainTrace):\n- return WrapperForWeakRef(trace_to_subjaxpr_dynamic2(fun, main))\n+ main: core.MainTrace,\n+ traced_for: str):\n+ dbg = debug_info_final(fun, traced_for)\n+ return WrapperForWeakRef(trace_to_subjaxpr_dynamic2(fun, main, dbg))\nclass WrapperForWeakRef:\n@@ -2148,11 +2155,10 @@ def trace_to_jaxpr_final(fun: lu.WrappedFun,\ndebug_info: Optional[DebugInfo] = None,\nkeep_inputs: Optional[Sequence[bool]] = None):\nwith core.new_base_main(DynamicJaxprTrace) as main: # type: ignore\n- main.debug_info = debug_info # type: ignore\nmain.jaxpr_stack = () # type: ignore\nwith core.new_sublevel():\njaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(\n- fun, main, in_avals, keep_inputs=keep_inputs)\n+ fun, main, in_avals, keep_inputs=keep_inputs, debug_info=debug_info)\ndel fun, main\nreturn jaxpr, out_avals, consts\n@@ -2161,10 +2167,9 @@ def trace_to_jaxpr_final2(\nfun: lu.WrappedFun, debug_info: Optional[DebugInfo] = None\n) -> Tuple[Jaxpr, OutputType, List[Any]]:\nwith core.new_base_main(DynamicJaxprTrace) as main: # type: ignore\n- main.debug_info = debug_info # type: ignore\nmain.jaxpr_stack = () # type: ignore\nwith core.new_sublevel():\n- jaxpr, out_type, consts = trace_to_subjaxpr_dynamic2(fun, main)\n+ jaxpr, out_type, consts = trace_to_subjaxpr_dynamic2(fun, main, debug_info)\ndel fun, main\nreturn jaxpr, out_type, consts\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3233,6 +3233,20 @@ class APITest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(core.ConcretizationTypeError, msg):\nf()\n+ def test_concrete_error_with_nested_call(self):\n+ @jax.jit\n+ def f(x, y):\n+ if y:\n+ return x\n+\n+ @jax.jit\n+ def g(x):\n+ return f(x, True)\n+\n+ msg = r\"on the value of the argument 'y'\"\n+ with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n+ g(1)\n+\ndef test_xla_computation_zeros_doesnt_device_put(self):\nwith jtu.count_device_put() as count:\napi.xla_computation(lambda: jnp.zeros(3))()\n" } ]
Python
Apache License 2.0
google/jax
Fix ConcretizationError in nested calls.
260,335
26.07.2022 01:02:00
25,200
c44dfce571f2445bcfa381d2356bbc2a96340d50
fix bug noticed by
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/loops.py", "new_path": "jax/_src/lax/control_flow/loops.py", "diff": "@@ -857,7 +857,7 @@ def _scan_partial_eval_custom(saveable, unks_in, inst_in, eqn):\nnum_const_known = len(const_uk) - sum(const_uk)\nnum_carry_known = len(carry_uk) - sum(carry_uk)\nnum_xs_known = len( xs_uk) - sum( xs_uk)\n- jaxpr_known_hoist, jaxpr_known_loop, loop_dep, _ = \\\n+ jaxpr_known_hoist, jaxpr_known_loop, loop_dep, consts_known_lp_avals = \\\npe.partial_eval_jaxpr_nounits(\njaxpr_known,\n[False] * num_const_known + [True] * (num_carry_known + num_xs_known),\n@@ -868,7 +868,7 @@ def _scan_partial_eval_custom(saveable, unks_in, inst_in, eqn):\njaxpr_staged = pe.move_binders_to_front(\njaxpr_staged, [False] * sum(inst_in) + _map(operator.not_, loop_dep_res))\nnum_intensive_res = len(loop_dep_res) - sum(loop_dep_res)\n- del loop_dep, num_carry_known, num_xs_known\n+ del loop_dep, num_carry_known, num_xs_known, const_uk\n# Create residual variables.\nintensive_avals, ext_avals_mapped = partition_list(loop_dep_res, res_avals)\n@@ -882,9 +882,13 @@ def _scan_partial_eval_custom(saveable, unks_in, inst_in, eqn):\n# jaxpr_known_hoist and a scan of jaxpr_known_loop.\nins_known, _ = partition_list(unks_in, eqn.invars)\nout_binders_known, _ = partition_list(unks_out, eqn.outvars)\n- linear_known = [l for l, uk in zip(eqn.params['linear'], unks_in) if not uk]\n+ # jaxpr_known_loop takes as input constants output as res by jaxpr_known_hoist\n+ # (corresponding to consts_known_lp_avals) followed by known carry and xs.\n+ linear_known_ = [l for l, uk in zip(eqn.params['linear'], unks_in) if not uk]\n+ _, linear_known_ = split_list(linear_known_, [num_const_known])\n+ linear_known = [False] * len(consts_known_lp_avals) + linear_known_\nparams_known = dict(eqn.params, jaxpr=jaxpr_known_loop,\n- num_consts=len(const_uk)-sum(const_uk),\n+ num_consts=len(consts_known_lp_avals),\nnum_carry=len(carry_uk)-sum(carry_uk),\nlinear=tuple(linear_known))\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -2511,6 +2511,23 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nreturn lax.cond(x < 0., lambda x: x, lambda x: x, x)\njax.vmap(jax.jacrev(lambda x: cond_id(cond_id(x))))(jnp.ones(1))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"impl={}\".format(scan_name), \"scan\": scan_impl}\n+ for scan_impl, scan_name in SCAN_IMPLS)\n+ def test_scan_hoisting_consts(self, scan):\n+ A = jnp.arange(4.).reshape(2, 2)\n+ B = jnp.arange(4.).reshape(2, 2) + 1.\n+\n+ def f(x):\n+ def body(c, _):\n+ c1, c2, c3 = c\n+ return (jnp.dot(A, c1), jnp.dot(B, c2), jnp.dot(jnp.sin(B), c3)), None\n+ init_carry = (x * jnp.ones(2), x * jnp.ones(2), x * jnp.ones(2))\n+ (c1, c2, c3), _ = scan(body, init_carry, None, length=3)\n+ return jnp.sum(c1) + jnp.sum(c2) + jnp.sum(c3)\n+\n+ jax.grad(f)(1.) # doesn't crash\n+\nclass ForLoopTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
fix bug noticed by @levskaya
260,510
12.07.2022 13:52:14
25,200
d57d6fcee503e02ef6acf45383cf1a88bec7aac9
Add webpdb option
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugger/__init__.py", "new_path": "jax/_src/debugger/__init__.py", "diff": "from jax._src.debugger.core import breakpoint\nfrom jax._src.debugger import cli_debugger\nfrom jax._src.debugger import colab_debugger\n+from jax._src.debugger import web_debugger\ndel cli_debugger # For registration only\ndel colab_debugger # For registration only\n+del web_debugger # For registration only\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/cli_debugger.py", "new_path": "jax/_src/debugger/cli_debugger.py", "diff": "@@ -45,6 +45,7 @@ class CliDebugger(cmd.Cmd):\nenv = {}\ncurr_frame = self.frames[self.frame_index]\nenv.update(curr_frame.locals)\n+ env.update(curr_frame.globals)\nreturn eval(expr, {}, env)\ndef default(self, arg):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/core.py", "new_path": "jax/_src/debugger/core.py", "diff": "from __future__ import annotations\nimport dataclasses\n+import functools\nimport inspect\nimport threading\n@@ -34,30 +35,31 @@ class DebuggerFrame:\n\"\"\"Encapsulates Python frame information.\"\"\"\nfilename: str\nlocals: Dict[str, Any]\n+ globals: Dict[str, Any]\ncode_context: str\nsource: List[str]\nlineno: int\noffset: Optional[int]\ndef tree_flatten(self):\n- flat_locals, locals_tree = tree_util.tree_flatten(self.locals)\n+ flat_vars, vars_tree = tree_util.tree_flatten((self.locals, self.globals))\nis_valid = [\nisinstance(l, (core.Tracer, jnp.ndarray, np.ndarray))\n- for l in flat_locals\n+ for l in flat_vars\n]\n- invalid_locals, valid_locals = util.partition_list(is_valid, flat_locals)\n- return valid_locals, (is_valid, invalid_locals, locals_tree, self.filename,\n+ invalid_vars, valid_vars = util.partition_list(is_valid, flat_vars)\n+ return valid_vars, (is_valid, invalid_vars, vars_tree, self.filename,\nself.code_context, self.source, self.lineno,\nself.offset)\n@classmethod\n- def tree_unflatten(cls, info, valid_locals):\n- (is_valid, invalid_locals, locals_tree, filename, code_context, source,\n+ def tree_unflatten(cls, info, valid_vars):\n+ (is_valid, invalid_vars, vars_tree, filename, code_context, source,\nlineno, offset) = info\n- flat_locals = util.merge_lists(is_valid, invalid_locals, valid_locals)\n- locals_ = tree_util.tree_unflatten(locals_tree, flat_locals)\n- return DebuggerFrame(filename, locals_, code_context, source, lineno,\n- offset)\n+ flat_vars = util.merge_lists(is_valid, invalid_vars, valid_vars)\n+ locals_, globals_ = tree_util.tree_unflatten(vars_tree, flat_vars)\n+ return DebuggerFrame(filename, locals_, globals_, code_context, source,\n+ lineno, offset)\n@classmethod\ndef from_frameinfo(cls, frame_info) -> DebuggerFrame:\n@@ -78,6 +80,7 @@ class DebuggerFrame:\nreturn DebuggerFrame(\nfilename=frame_info.filename,\nlocals=frame_info.frame.f_locals,\n+ globals=frame_info.frame.f_globals,\ncode_context=frame_info.code_context,\nsource=source,\nlineno=frame_info.lineno,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/debugger/web_debugger.py", "diff": "+# Copyright 2022 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+from __future__ import annotations\n+import os\n+import weakref\n+\n+from typing import Any, Dict, List, Optional, Tuple\n+\n+from jax._src.debugger import cli_debugger\n+from jax._src.debugger import core as debugger_core\n+\n+try:\n+ import web_pdb # pytype: disable=import-error\n+ WEB_PDB_ENABLED = True\n+except:\n+ WEB_PDB_ENABLED = False\n+\n+\n+_web_consoles: Dict[Tuple[str, int], web_pdb.WebConsole] = {}\n+\n+class WebDebugger(cli_debugger.CliDebugger):\n+ \"\"\"A web-based debugger.\"\"\"\n+ prompt = '(jaxdb) '\n+ use_rawinput: bool = False\n+\n+ def __init__(self, frames: List[debugger_core.DebuggerFrame], thread_id,\n+ completekey: str = \"tab\", host: str = \"0.0.0.0\", port: int = 5555):\n+ if (host, port) not in _web_consoles:\n+ _web_consoles[host, port] = web_pdb.WebConsole(host, port, self)\n+ # Clobber the debugger in the web console\n+ _web_console = _web_consoles[host, port]\n+ _web_console._debugger = weakref.proxy(self)\n+ super().__init__(frames, thread_id, stdin=_web_console, stdout=_web_console,\n+ completekey=completekey)\n+\n+ def get_current_frame_data(self):\n+ # Constructs the info needed for the web console to display info\n+ current_frame = self.current_frame()\n+ filename = current_frame.filename\n+ lines = current_frame.source\n+ locals = \"\\n\".join([f\"{key} = {value}\" for key, value in\n+ sorted(current_frame.locals.items())])\n+ globals = \"\\n\".join([f\"{key} = {value}\" for key, value in\n+ sorted(current_frame.globals.items())])\n+ current_line = None\n+ if current_frame.offset is not None:\n+ current_line = current_frame.offset + 1\n+ return {\n+ 'dirname': os.path.dirname(os.path.abspath(filename)) + os.path.sep,\n+ 'filename': os.path.basename(filename),\n+ 'file_listing': '\\n'.join(lines),\n+ 'current_line': current_line,\n+ 'breakpoints': [],\n+ 'globals': globals,\n+ 'locals': locals,\n+ }\n+\n+ def run(self):\n+ return self.cmdloop()\n+\n+def run_debugger(frames: List[debugger_core.DebuggerFrame],\n+ thread_id: Optional[int], **kwargs: Any):\n+ WebDebugger(frames, thread_id, **kwargs).run()\n+\n+if WEB_PDB_ENABLED:\n+ debugger_core.register_debugger(\"web\", run_debugger, 0)\n" } ]
Python
Apache License 2.0
google/jax
Add webpdb option
260,335
27.07.2022 10:54:54
25,200
148173630f47c2e4a3aea8bade08eb6e6ea96bae
add an optional fastpath for api_util.shaped_abstractify also add a benchmark for it, 8.7ms -> 0.2ms on my machine
[ { "change_type": "MODIFY", "old_path": "benchmarks/api_benchmark.py", "new_path": "benchmarks/api_benchmark.py", "diff": "@@ -20,6 +20,7 @@ import google_benchmark\nimport jax\nfrom jax import lax\nfrom jax.experimental import sparse\n+from jax._src.api_util import shaped_abstractify # technically not an api fn\nimport jax.numpy as jnp\nimport numpy as np\n@@ -461,6 +462,15 @@ def sparse_bcoo_matvec_compile(state):\nreturn _sparse_bcoo_matvec(state, compile=True)\n+@google_benchmark.register\n+@google_benchmark.option.unit(google_benchmark.kMillisecond)\n+def bench_shaped_abstractify(state):\n+ device, *_ = jax.devices()\n+ args = [jax.device_put_replicated(1, [device])] * 1000\n+ while state:\n+ _ = [shaped_abstractify(x) for x in args]\n+\n+\ndef swap(a, b):\nreturn b, a\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api_util.py", "new_path": "jax/_src/api_util.py", "diff": "import inspect\nimport operator\nfrom functools import partial\n-from typing import Any, Dict, Iterable, Sequence, Set, Tuple, Union, Optional\n+from typing import (Any, Dict, Iterable, Sequence, Set, Tuple, Union, Optional,\n+ Callable)\nimport warnings\nimport numpy as np\n@@ -425,7 +426,7 @@ def _dtype(x):\nexcept ValueError:\nreturn dtypes.result_type(getattr(x, 'dtype'))\n-def shaped_abstractify(x):\n+def _shaped_abstractify_slow(x):\ntry:\nreturn core.raise_to_shaped(\nx if isinstance(x, core.AbstractValue) else core.get_aval(x))\n@@ -437,6 +438,14 @@ def shaped_abstractify(x):\nreturn core.ShapedArray(np.shape(x), _dtype(x), weak_type=weak_type,\nnamed_shape=named_shape)\n+# TODO(mattjj,yashkatariya): replace xla.abstractify with this, same behavior\n+def shaped_abstractify(x):\n+ try:\n+ return _shaped_abstractify_handlers[type(x)](x)\n+ except KeyError:\n+ return _shaped_abstractify_slow(x)\n+_shaped_abstractify_handlers: Dict[Any, Callable[[Any], core.ShapedArray]] = {}\n+\n# This decorator exists to make it easier to monkey-patch APIs in JAX.\n# By default it does nothing, but it can be monkey-patched to do other things.\ndef api_hook(fun, tag: str):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/array.py", "new_path": "jax/experimental/array.py", "diff": "@@ -18,6 +18,7 @@ import numpy as np\nfrom typing import Sequence, Tuple, Callable, Union, Optional, cast, List\nfrom jax import core\n+from jax._src import api_util\nfrom jax._src import dispatch\nfrom jax._src.config import config\nfrom jax._src.util import prod\n@@ -242,6 +243,8 @@ def make_array_from_callback(shape: Shape, sharding: Sharding,\ncore.pytype_aval_mappings[Array] = lambda x: core.ShapedArray(x.shape, x.dtype)\nxla.pytype_aval_mappings[Array] = lambda x: core.ShapedArray(x.shape, x.dtype)\nxla.canonicalize_dtype_handlers[Array] = pxla.identity\n+api_util._shaped_abstractify_handlers[Array] = \\\n+ lambda x: core.ShapedArray(x.shape, x.dtype)\ndef _device_put_array(x, device: Optional[Device]):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/global_device_array.py", "new_path": "jax/experimental/global_device_array.py", "diff": "@@ -19,6 +19,7 @@ import numpy as np\nfrom typing import Callable, Sequence, Tuple, Union, Mapping, Optional, List, Dict, NamedTuple\nfrom jax import core\n+from jax._src import api_util\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\nfrom jax._src.config import config\n@@ -557,6 +558,8 @@ core.pytype_aval_mappings[GlobalDeviceArray] = lambda x: core.ShapedArray(\nxla.pytype_aval_mappings[GlobalDeviceArray] = lambda x: core.ShapedArray(\nx.shape, x.dtype)\nxla.canonicalize_dtype_handlers[GlobalDeviceArray] = pxla.identity\n+api_util._shaped_abstractify_handlers[GlobalDeviceArray] = \\\n+ lambda x: core.ShapedArray(x.shape, x.dtype)\ndef _gda_shard_arg(x, devices, indices):\nreturn x._device_buffers\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -27,8 +27,9 @@ from weakref import ref\nimport numpy as np\nfrom jax import core\n-from jax._src import dtypes\nfrom jax import linear_util as lu\n+from jax._src import api_util\n+from jax._src import dtypes\nfrom jax._src import profiler\nfrom jax._src.ad_util import Zero\nfrom jax._src.api_util import flattened_fun_in_tree, flatten_fun_nokwargs\n@@ -1580,6 +1581,7 @@ class DynamicJaxprTracer(core.Tracer):\nframe = self._trace.frame\nval = frame.constvar_to_val.get(frame.tracer_to_var.get(id(self)))\nreturn self if val is None else get_referent(val)\n+api_util._shaped_abstractify_handlers[DynamicJaxprTracer] = op.attrgetter(\"aval\")\nclass JaxprStackFrame:\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -59,6 +59,7 @@ from jax.interpreters import xla\nfrom jax.tree_util import tree_flatten, tree_map\nfrom jax._src import abstract_arrays\n+from jax._src import api_util\nfrom jax._src import device_array\nfrom jax._src import source_info_util\nfrom jax._src import util\n@@ -808,6 +809,7 @@ def _register_handlers_for_sharded_device_array(sda):\ndispatch.device_put_handlers[sda] = dispatch._device_put_array\nxla.pytype_aval_mappings[sda] = op.attrgetter(\"aval\")\nxla.canonicalize_dtype_handlers[sda] = identity\n+ api_util._shaped_abstractify_handlers[sda] = op.attrgetter(\"aval\")\n_register_handlers_for_sharded_device_array(_ShardedDeviceArray)\n_register_handlers_for_sharded_device_array(pmap_lib.ShardedDeviceArray)\n" } ]
Python
Apache License 2.0
google/jax
add an optional fastpath for api_util.shaped_abstractify also add a benchmark for it, 8.7ms -> 0.2ms on my machine Co-authored-by: Yash Katariya <yashkatariya@google.com>
260,510
27.07.2022 18:01:34
25,200
547d021157e44e2b5ef724977244a2e24c332c68
Enable compatibility with older versions of web_pdb
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugger/cli_debugger.py", "new_path": "jax/_src/debugger/cli_debugger.py", "diff": "@@ -56,26 +56,30 @@ class CliDebugger(cmd.Cmd):\nself._error_message()\ndef print_backtrace(self):\n- print('Traceback:', file=self.stdout)\n+ backtrace = []\n+ backtrace.append('Traceback:')\nfor frame in self.frames[::-1]:\n- self.stdout.write(f' File \"{frame.filename}\", line {frame.lineno}\\n')\n+ backtrace.append(f' File \"{frame.filename}\", line {frame.lineno}')\nif frame.offset is None:\n- print(' <no source>', file=self.stdout)\n+ backtrace.append(' <no source>')\nelse:\nline = frame.source[frame.offset]\n- print(f' {line.strip()}', file=self.stdout)\n+ backtrace.append(f' {line.strip()}')\n+ print(\"\\n\".join(backtrace), file=self.stdout)\ndef print_context(self, num_lines=2):\ncurr_frame = self.frames[self.frame_index]\n- print(f'> {curr_frame.filename}({curr_frame.lineno})', file=self.stdout)\n+ context = []\n+ context.append(f'> {curr_frame.filename}({curr_frame.lineno})')\nfor i, line in enumerate(curr_frame.source):\nassert curr_frame.offset is not None\nif (curr_frame.offset - 1 - num_lines <= i <=\ncurr_frame.offset + num_lines):\nif i == curr_frame.offset:\n- print(f'-> {line}', file=self.stdout)\n+ context.append(f'-> {line}')\nelse:\n- print(f' {line}', file=self.stdout)\n+ context.append(f' {line}')\n+ print(\"\\n\".join(context), file=self.stdout)\ndef _error_message(self):\nexc_info = sys.exc_info()[:2]\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/colab_debugger.py", "new_path": "jax/_src/debugger/colab_debugger.py", "diff": "@@ -245,7 +245,8 @@ class ColabDebugger(cli_debugger.CliDebugger):\ndef run(self):\nself._debugger_view.render()\nwhile True:\n- self.cmdloop()\n+ if not self.cmdloop():\n+ return\ndef _run_debugger(frames, thread_id, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/web_debugger.py", "new_path": "jax/_src/debugger/web_debugger.py", "diff": "@@ -20,8 +20,10 @@ from typing import Any, Dict, List, Optional, Tuple\nfrom jax._src.debugger import cli_debugger\nfrom jax._src.debugger import core as debugger_core\n+web_pdb_version: Optional[Tuple[int, ...]] = None\ntry:\nimport web_pdb # pytype: disable=import-error\n+ web_pdb_version = tuple(map(int, web_pdb.__version__.split(\".\")))\nWEB_PDB_ENABLED = True\nexcept:\nWEB_PDB_ENABLED = False\n@@ -35,7 +37,7 @@ class WebDebugger(cli_debugger.CliDebugger):\nuse_rawinput: bool = False\ndef __init__(self, frames: List[debugger_core.DebuggerFrame], thread_id,\n- completekey: str = \"tab\", host: str = \"0.0.0.0\", port: int = 5555):\n+ completekey: str = \"tab\", host: str = \"\", port: int = 5555):\nif (host, port) not in _web_consoles:\n_web_consoles[host, port] = web_pdb.WebConsole(host, port, self)\n# Clobber the debugger in the web console\n@@ -49,23 +51,39 @@ class WebDebugger(cli_debugger.CliDebugger):\ncurrent_frame = self.current_frame()\nfilename = current_frame.filename\nlines = current_frame.source\n- locals = \"\\n\".join([f\"{key} = {value}\" for key, value in\n- sorted(current_frame.locals.items())])\n- globals = \"\\n\".join([f\"{key} = {value}\" for key, value in\n- sorted(current_frame.globals.items())])\ncurrent_line = None\nif current_frame.offset is not None:\ncurrent_line = current_frame.offset + 1\n+ if web_pdb_version and web_pdb_version < (1, 4, 4):\n+ return {\n+ 'filename': filename,\n+ 'listing': '\\n'.join(lines),\n+ 'curr_line': current_line,\n+ 'total_lines': len(lines),\n+ 'breaklist': [],\n+ }\nreturn {\n'dirname': os.path.dirname(os.path.abspath(filename)) + os.path.sep,\n'filename': os.path.basename(filename),\n'file_listing': '\\n'.join(lines),\n'current_line': current_line,\n'breakpoints': [],\n- 'globals': globals,\n- 'locals': locals,\n+ 'globals': self.get_globals(),\n+ 'locals': self.get_locals(),\n}\n+ def get_globals(self):\n+ current_frame = self.current_frame()\n+ globals = \"\\n\".join([f\"{key} = {value}\" for key, value in\n+ sorted(current_frame.globals.items())])\n+ return globals\n+\n+ def get_locals(self):\n+ current_frame = self.current_frame()\n+ locals = \"\\n\".join([f\"{key} = {value}\" for key, value in\n+ sorted(current_frame.locals.items())])\n+ return locals\n+\ndef run(self):\nreturn self.cmdloop()\n" } ]
Python
Apache License 2.0
google/jax
Enable compatibility with older versions of web_pdb
260,335
27.07.2022 19:38:27
25,200
f56ce8a01cd395440f3edd3b4f01f0fc2c8505db
update cond partial eval to so eqn effects match branch jaxprs' Also add some new tests, including some skipped ones, for how effects should interact with jax.linearize (I think...).
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/conditionals.py", "new_path": "jax/_src/lax/control_flow/conditionals.py", "diff": "@@ -429,7 +429,7 @@ def _cond_partial_eval(trace, *tracers, branches, linear):\nsource = source_info_util.current().replace(name_stack=name_stack)\neqn = pe.new_eqn_recipe(\n[index_tracer] + res_tracers + ops_tracers, out_tracers, cond_p, params,\n- core.no_effects, source)\n+ core.join_effects(*(j.effects for j in branches_unknown)), source)\nfor t in out_tracers: t.recipe = eqn\nreturn util.merge_lists(out_uks, out_consts, out_tracers)\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -214,9 +214,40 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\nwith capture_stdout() as output:\nx = jnp.array(1., jnp.float32)\n- jax.jvp(f, (x,), (x,)) # should print out cos(1.)\n+ jax.jvp(f, (x,), (x,))\njax.effects_barrier()\n- self.assertEqual(output(), \"x_tangent: 0.5403022766113281\\n\")\n+ expected = jnp.cos(jnp.array(1., jnp.float32))\n+ self.assertEqual(output(), f\"x_tangent: {expected}\\n\")\n+\n+ @unittest.skip(\"doesn't work yet!\") # TODO(mattjj,sharadmv)\n+ def test_debug_print_in_custom_jvp_linearize(self):\n+\n+ @jax.custom_jvp\n+ def print_tangent(x):\n+ return x\n+\n+ @print_tangent.defjvp\n+ def _(primals, tangents):\n+ (x,), (t,) = primals, tangents\n+ debug_print(\"x_tangent: {}\", t)\n+ return x, t\n+\n+ def f(x):\n+ x = jnp.sin(x)\n+ x = print_tangent(x)\n+ return x\n+\n+ with capture_stdout() as output:\n+ x = jnp.array(1., jnp.float32)\n+ y, f_lin = jax.linearize(f, x)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"\")\n+\n+ with capture_stdout() as output:\n+ _ = f_lin(x)\n+ jax.effects_barrier()\n+ expected = jnp.cos(jnp.array(1., jnp.float32))\n+ self.assertEqual(output(), f\"x_tangent: {expected}\\n\")\ndef test_debug_print_grad_with_custom_vjp_rule(self):\n@jax.custom_vjp\n@@ -239,7 +270,8 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\nwith capture_stdout() as output:\njax.grad(f)(jnp.array(1., jnp.float32))\njax.effects_barrier()\n- self.assertEqual(output(), \"x: 1.0\\nx_grad: 0.5403022766113281\\n\")\n+ expected = jnp.cos(jnp.array(1., jnp.float32))\n+ self.assertEqual(output(), f\"x: 1.0\\nx_grad: {expected}\\n\")\ndef test_debug_print_transpose_rule(self):\ndef f(x):\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -724,6 +724,52 @@ class ControlFlowEffectsTest(jtu.JaxTestCase):\nreturn lax.cond(x, true_fun, false_fun, x)\nf(2)\n+ def test_allowed_effect_in_cond_jvp(self):\n+ def f(x):\n+ def true_fun(x):\n+ effect_p.bind(effect='while')\n+ return x\n+ def false_fun(x):\n+ effect_p.bind(effect='while')\n+ return x\n+ return lax.cond(True, true_fun, false_fun, x)\n+\n+ # test primal side gets effect\n+ primal_jaxpr = jax.make_jaxpr(lambda x: jax.linearize(f, x)[0])(2.)\n+ self.assertEqual(primal_jaxpr.effects, {'while'})\n+ # and tangent side does not\n+ _, f_lin = jax.linearize(f, 2.)\n+ lin_jaxpr = f_lin.func.fun.args[0]\n+ self.assertEqual(lin_jaxpr.effects, set())\n+\n+ def test_allowed_effect_in_cond_jvp2(self):\n+ @jax.custom_jvp\n+ def print_tangents(x):\n+ return x\n+ @print_tangents.defjvp\n+ def foo_jvp(primals, tangents):\n+ x, = primals\n+ t, = tangents\n+ # TODO(mattjj,sharadmv): don't require data dependence for jax.linearize!\n+ # effect_p.bind(t, effect='while')\n+ t, = effect_p.bind(t, effect='while') # data dep only on tangents\n+ return x, t\n+\n+ def f(x):\n+ def true_fun(x):\n+ return print_tangents(x)\n+ def false_fun(x):\n+ return print_tangents(x)\n+ return lax.cond(True, true_fun, false_fun, x)\n+\n+ # test primal side does not get effect\n+ primal_jaxpr = jax.make_jaxpr(lambda x: jax.linearize(f, x)[0])(2.)\n+ self.assertEqual(primal_jaxpr.effects, set())\n+ # and tangent side does\n+ _, f_lin = jax.linearize(f, 2.)\n+ lin_jaxpr = f_lin.func.fun.args[0]\n+ self.assertEqual(lin_jaxpr.effects, {'while'})\n+\ndef test_allowed_ordered_effect_in_cond(self):\ndef f(x):\ndef true_fun(x):\n" } ]
Python
Apache License 2.0
google/jax
update cond partial eval to so eqn effects match branch jaxprs' Also add some new tests, including some skipped ones, for how effects should interact with jax.linearize (I think...).
260,424
28.07.2022 11:33:01
25,200
8ca5ecc7f33e1b9057118b1cdc1b576ff7fa1b6e
Re-land after internal fixes. maintain an alias to `jax.tree_util.tree_map` in the top level `jax` module
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -31,12 +31,12 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* Binary operations between JAX arrays and built-in collections (`dict`, `list`, `set`, `tuple`)\nnow raise a `TypeError` in all cases. Previously some cases (particularly equality and inequality)\nwould return boolean scalars inconsistent with similar operations in NumPy ({jax-issue}`#11234`).\n- * {mod}`jax.tree_util` routines accessed as top-level JAX package imports are now deprecated, and\n- will be removed in a future JAX release in accordance with the {ref}`api-compatibility` policy:\n+ * Several {mod}`jax.tree_util` routines accessed as top-level JAX package imports are now\n+ deprecated, and will be removed in a future JAX release in accordance with the\n+ {ref}`api-compatibility` policy:\n* {func}`jax.treedef_is_leaf` is deprecated in favor of {func}`jax.tree_util.treedef_is_leaf`\n* {func}`jax.tree_flatten` is deprecated in favor of {func}`jax.tree_util.tree_flatten`\n* {func}`jax.tree_leaves` is deprecated in favor of {func}`jax.tree_util.tree_leaves`\n- * {func}`jax.tree_map` is deprecated in favor of {func}`jax.tree_util.tree_map`\n* {func}`jax.tree_structure` is deprecated in favor of {func}`jax.tree_util.tree_structure`\n* {func}`jax.tree_transpose` is deprecated in favor of {func}`jax.tree_util.tree_transpose`\n* {func}`jax.tree_unflatten` is deprecated in favor of {func}`jax.tree_util.tree_unflatten`\n" }, { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -114,12 +114,12 @@ from jax.experimental.maps import soft_pmap as soft_pmap\nfrom jax.version import __version__ as __version__\nfrom jax.version import __version_info__ as __version_info__\n-# TODO(jakevdp): remove these deprecated routines after October 2022\nfrom jax._src.tree_util import (\n+ tree_map as tree_map,\n+ # TODO(jakevdp): remove these deprecated routines after October 2022\n_deprecated_treedef_is_leaf as treedef_is_leaf,\n_deprecated_tree_flatten as tree_flatten,\n_deprecated_tree_leaves as tree_leaves,\n- _deprecated_tree_map as tree_map,\n_deprecated_tree_structure as tree_structure,\n_deprecated_tree_transpose as tree_transpose,\n_deprecated_tree_unflatten as tree_unflatten,\n" } ]
Python
Apache License 2.0
google/jax
Re-land #11498 after internal fixes. maintain an alias to `jax.tree_util.tree_map` in the top level `jax` module PiperOrigin-RevId: 463885774
260,335
28.07.2022 18:04:49
25,200
7f3aa12142546a06aca87b3c33da1b64a42a2bf0
add while_loop custom-policy partial eval rule
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/conditionals.py", "new_path": "jax/_src/lax/control_flow/conditionals.py", "diff": "@@ -446,7 +446,7 @@ def _cond_partial_eval_custom(saveable, unks_in, inst_in, eqn):\nunks_out: List[bool] = [False] * len(eqn.outvars)\nfor jaxpr in branches:\n_, _, unks_out_, _, _ = pe.partial_eval_jaxpr_custom(\n- jaxpr.jaxpr, in_unknowns=ops_uk, in_inst=[True] * len(ops_uk),\n+ jaxpr.jaxpr, in_unknowns=ops_uk, in_inst=True,\nensure_out_unknowns=False, ensure_out_inst=True, saveable=saveable)\nunks_out = map(operator.or_, unks_out, unks_out_)\n@@ -458,7 +458,7 @@ def _cond_partial_eval_custom(saveable, unks_in, inst_in, eqn):\nfor jaxpr in branches:\njaxpr_known, jaxpr_staged, _, inst_out, num_res = \\\npe.partial_eval_jaxpr_custom(\n- jaxpr.jaxpr, in_unknowns=ops_uk, in_inst=[True] * len(ops_uk),\n+ jaxpr.jaxpr, in_unknowns=ops_uk, in_inst=True,\nensure_out_unknowns=unks_out, ensure_out_inst=True,\nsaveable=saveable)\nbranches_known_.append( core.ClosedJaxpr(jaxpr_known, jaxpr.consts))\n@@ -481,7 +481,7 @@ def _cond_partial_eval_custom(saveable, unks_in, inst_in, eqn):\n# passing in_inst argument to partial_eval_jaxpr_custom above).\nnew_inst = [x for x, inst in zip(eqn.invars, inst_in)\nif type(x) is core.Var and not inst]\n- inst_in = [True] * len(inst_in)\n+ del inst_in\n# Create residual variables.\nnewvar = core.gensym()\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/loops.py", "new_path": "jax/_src/lax/control_flow/loops.py", "diff": "@@ -828,7 +828,7 @@ def _scan_partial_eval_custom(saveable, unks_in, inst_in, eqn):\nunks_in = const_uk + carry_uk + xs_uk\njaxpr_known_, jaxpr_staged_, unks_out, inst_out, num_res = \\\npe.partial_eval_jaxpr_custom(\n- jaxpr.jaxpr, in_unknowns=unks_in, in_inst=[True] * len(unks_in),\n+ jaxpr.jaxpr, in_unknowns=unks_in, in_inst=True,\nensure_out_unknowns=carry_uk + [False] * num_ys,\nensure_out_inst=True, saveable=saveable)\ncarry_uk_out, ys_uk = split_list(unks_out, [num_carry])\n@@ -1309,6 +1309,70 @@ def _while_partial_eval(trace: pe.JaxprTrace, *tracers: pe.Tracer, cond_nconsts:\nout_tracers = [t for t, uk in zip(out_tracers_, carry_uk) if uk]\nreturn util.merge_lists(carry_uk, out_known, out_tracers)\n+# TODO(mattjj): de-duplicate code with _while_partial_eval\n+def _while_partial_eval_custom(saveable, unks_in, inst_in, eqn):\n+ del saveable # We can't save any residuals anyway (w/o dynamic shapes)!\n+ cond_jaxpr = eqn.params['cond_jaxpr']\n+ cond_nconsts = eqn.params['cond_nconsts']\n+ body_jaxpr = eqn.params['body_jaxpr']\n+ body_nconsts = eqn.params['body_nconsts']\n+\n+ cond_consts_uk, body_consts_uk, carry_init_uk = \\\n+ split_list(unks_in, [cond_nconsts, body_nconsts])\n+\n+ # Fixpoint to compute known part of the body (trivial on 'inst_in', since we\n+ # make all inputs available as DCE can subsequently prune any unused ones)\n+ carry_uk = carry_init_uk\n+ for _ in range(1 + len(carry_uk)):\n+ body_unks_in = body_consts_uk + carry_uk\n+ jaxpr_known_, _, carry_uk_out, _, num_res = \\\n+ pe.partial_eval_jaxpr_custom(\n+ body_jaxpr.jaxpr, in_unknowns=body_unks_in, in_inst=True,\n+ ensure_out_unknowns=carry_uk, ensure_out_inst=True,\n+ saveable=ad_checkpoint.nothing_saveable)\n+ if carry_uk_out == carry_uk:\n+ break\n+ else:\n+ carry_uk = _map(operator.or_, carry_uk, carry_uk_out)\n+ else:\n+ assert False, \"Fixpoint not reached\"\n+ assert not num_res\n+ body_jaxpr_known = core.ClosedJaxpr(jaxpr_known_, body_jaxpr.consts)\n+ del jaxpr_known_, carry_uk_out, num_res\n+\n+ # Compute the known part of cond_fun (basically pruning inputs on known side).\n+ cond_unks_in = cond_consts_uk + carry_uk\n+ cond_jaxpr_known_, _, [cond_uk], _, _ = \\\n+ pe.partial_eval_jaxpr_custom(\n+ cond_jaxpr.jaxpr, cond_unks_in, in_inst=True,\n+ ensure_out_unknowns=False, ensure_out_inst=True,\n+ saveable=ad_checkpoint.nothing_saveable)\n+ assert not cond_uk # only possible with old-style remat\n+ cond_jaxpr_known = core.ClosedJaxpr(cond_jaxpr_known_, cond_jaxpr.consts)\n+ del cond_uk\n+\n+ # Build the known eqn.\n+ ins_known, _ = partition_list(unks_in, eqn.invars)\n+ out_binders_known, _ = partition_list(carry_uk, eqn.outvars)\n+ params_known = dict(cond_jaxpr=cond_jaxpr_known, body_jaxpr=body_jaxpr_known,\n+ cond_nconsts=len(cond_consts_uk) - sum(cond_consts_uk),\n+ body_nconsts=len(body_consts_uk) - sum(body_consts_uk))\n+ effects_known = core.join_effects(cond_jaxpr_known.effects,\n+ body_jaxpr_known.effects)\n+ eqn_known = pe.new_jaxpr_eqn(ins_known, out_binders_known, while_p,\n+ params_known, effects_known, eqn.source_info)\n+\n+ # Staged eqn is same as input eqn.\n+ eqn_staged = eqn\n+\n+ # Instantiate all inputs (b/c jaxpr_staged takes all inputs).\n+ new_inst = [x for x, inst in zip(eqn.invars, inst_in)\n+ if type(x) is core.Var and not inst]\n+\n+ unks_out = carry_uk\n+ inst_out = [True] * len(unks_out)\n+ return eqn_known, eqn_staged, unks_out, inst_out, new_inst\n+\ndef _while_transpose_error(*_, **kwargs):\nraise ValueError(\"Reverse-mode differentiation does not work for \"\n\"lax.while_loop or lax.fori_loop. \"\n@@ -1323,8 +1387,7 @@ pe.custom_partial_eval_rules[while_p] = _while_partial_eval\nxla.register_initial_style_primitive(while_p)\nad.primitive_transposes[while_p] = _while_transpose_error\nbatching.axis_primitive_batchers[while_p] = _while_loop_batching_rule\n-pe.partial_eval_jaxpr_custom_rules[while_p] = \\\n- partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'while_loop')\n+pe.partial_eval_jaxpr_custom_rules[while_p] = _while_partial_eval_custom\ndef _pred_bcast_select_mhlo(\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1241,11 +1241,13 @@ call_partial_eval_rules[remat_call_p] = _remat_partial_eval\ndef partial_eval_jaxpr_custom(\njaxpr: Jaxpr,\nin_unknowns: Sequence[bool],\n- in_inst: Sequence[bool],\n+ in_inst: Union[bool, Sequence[bool]],\nensure_out_unknowns: Union[bool, Sequence[bool]],\nensure_out_inst: Union[bool, Sequence[bool]],\nsaveable: Callable[..., bool],\n) -> Tuple[Jaxpr, Jaxpr, List[bool], List[bool], int]:\n+ if type(in_inst) is bool:\n+ in_inst = (in_inst,) * len(jaxpr.invars)\nif type(ensure_out_unknowns) is bool:\nensure_out_unknowns = (ensure_out_unknowns,) * len(jaxpr.outvars)\nif type(ensure_out_inst) is bool:\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -5207,6 +5207,50 @@ class RematTest(jtu.JaxTestCase):\nself.assertEqual(jaxpr_text.count(' sin '), 1)\nself.assertEqual(jaxpr_text.count(' cos '), 2)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', api.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_remat_of_while_loop(self, remat):\n+ def cond_fn(carry):\n+ i, _ = carry\n+ return i < 3\n+ def body_fn(carry):\n+ i, x = carry\n+ return i + 1, jnp.sin(x)\n+ def f(x):\n+ _, y = lax.while_loop(cond_fn, body_fn, (0, x))\n+ return y\n+\n+ _, f_lin = jax.linearize(remat(f), 3.)\n+ y_dot = f_lin(1.0)\n+ expected = jax.grad(lambda x: jnp.sin(jnp.sin(jnp.sin(x))))(3.)\n+ self.assertArraysAllClose(y_dot, expected, check_dtypes=False)\n+\n+ jaxpr = api.make_jaxpr(jax.linearize(remat(f), 4.)[1])(1.)\n+ self.assertIn(' sin ', str(jaxpr))\n+ self.assertIn(' cos ', str(jaxpr))\n+\n+ def test_remat_of_while_loop_policy(self):\n+ def cond_fn(carry):\n+ i, _ = carry\n+ return i < 3\n+ def body_fn(carry):\n+ i, x = carry\n+ return i + 1, jnp.sin(x)\n+ def f(x):\n+ _, y = lax.while_loop(cond_fn, body_fn, (0, x))\n+ return y\n+\n+ # even with a policy, we can't save residuals (w/o dynamic shapes)!\n+ save_cos = lambda prim, *_, **__: str(prim) == 'cos'\n+ g = new_checkpoint(f, policy=save_cos)\n+ jaxpr = api.make_jaxpr(jax.linearize(g, 4.)[1])(1.)\n+ self.assertIn(' sin ', str(jaxpr))\n+ self.assertIn(' cos ', str(jaxpr))\n+\nclass JaxprTest(jtu.JaxTestCase):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -105,6 +105,15 @@ SCAN_IMPLS_WITH_FOR = [\n]\n+def while_loop_new_checkpoint(cond_fun, body_fun, init_val):\n+ return new_checkpoint(partial(lax.while_loop, cond_fun, body_fun))(init_val)\n+\n+WHILE_LOOP_IMPLS = [\n+ (lax.while_loop, 'while_loop'),\n+ (while_loop_new_checkpoint, 'new_checkpoint'),\n+]\n+\n+\ndef while_loop_reference(cond, body, carry):\nwhile cond(carry):\ncarry = body(carry)\n@@ -2007,13 +2016,16 @@ class LaxControlFlowTest(jtu.JaxTestCase):\njtu.check_grads(loop, (x,), order=2, modes=[\"fwd\"])\n@parameterized.named_parameters(\n- {\"testcase_name\": \"_jit_loop={}_jit_body={}_jit_cond={}\".format(\n- jit_loop, jit_body, jit_cond),\n- \"jit_loop\": jit_loop, \"jit_body\": jit_body, \"jit_cond\": jit_cond}\n+ {\"testcase_name\": \"_jit_loop={}_jit_body={}_jit_cond={}_impl={}\".format(\n+ jit_loop, jit_body, jit_cond, while_name),\n+ \"jit_loop\": jit_loop, \"jit_body\": jit_body, \"jit_cond\": jit_cond,\n+ \"while_loop\": while_impl}\nfor jit_loop in [False, True]\nfor jit_body in [False, True]\n- for jit_cond in [False, True])\n- def testWhileLinearize(self, jit_loop=True, jit_body=False, jit_cond=True):\n+ for jit_cond in [False, True]\n+ for while_impl, while_name in WHILE_LOOP_IMPLS)\n+ def testWhileLinearize(self, while_loop, jit_loop=True, jit_body=False,\n+ jit_cond=True):\ncond = lambda x: x[0, 2] <= 8\nbody = lambda x: x * x\n@@ -2022,7 +2034,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nif jit_body:\nbody = jax.jit(body)\n- loop = partial(lax.while_loop, cond, body)\n+ loop = partial(while_loop, cond, body)\nif jit_loop:\nloop = jax.jit(loop)\n" } ]
Python
Apache License 2.0
google/jax
add while_loop custom-policy partial eval rule
260,335
28.07.2022 20:47:26
25,200
e0c1e6c2ffacb7ae3a4bd98df94d8afda84b3c12
add custom-policy partial eval and dce rules for pmap Also add a failing test for xmap.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -1428,7 +1428,8 @@ def zeros_like_array(x: Array) -> Array:\nfor t in itertools.chain(\ndtypes.python_scalar_dtypes.keys(), array_types,\ndevice_array.device_array_types,\n- [pxla.ShardedDeviceArray, pxla.pmap_lib.ShardedDeviceArray]):\n+ [pxla.ShardedDeviceArray, pxla._ShardedDeviceArray,\n+ pxla.pmap_lib.ShardedDeviceArray]):\nad_util.jaxval_adders[t] = add\nad_util.jaxval_zeros_likers[device_array._DeviceArray] = zeros_like_array\nad_util.jaxval_zeros_likers[device_array.Buffer] = zeros_like_array\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1075,7 +1075,7 @@ def _xmap_partial_eval_custom_params_updater(\nassert params_known['spmd_in_axes'] is None is params_known['spmd_out_axes']\nassert params_staged['spmd_in_axes'] is None is params_staged['spmd_out_axes']\n- # pruned inputs to jaxpr_known according to unks_in\n+ # prune inputs to jaxpr_known according to unks_in\ndonated_invars_known, _ = pe.partition_list(unks_in, params_known['donated_invars'])\nin_axes_known, _ = pe.partition_list(unks_in, params_known['in_axes'])\nif num_res == 0:\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -374,6 +374,7 @@ class JaxprTrace(Trace):\nstaged_params = update_params(params, map(op.not_, in_knowns), num_new_args)\nstaged_params = dict(staged_params, in_axes=staged_in_axes,\nout_axes=tuple(staged_out_axes), call_jaxpr=call_jaxpr)\n+ del staged_params['out_axes_thunk']\n# The outputs of the staged-out call are Tracers with the new eqn as recipe.\nout_avals = [unmapped_aval(params['axis_size'], params['axis_name'], ax, a)\nfor ax, a in zip(staged_out_axes, out_avals_mapped)]\n@@ -1357,11 +1358,15 @@ def partial_eval_jaxpr_custom_rule_not_implemented(\nParamsUpdater = Callable[[Sequence[bool], Sequence[bool], Sequence[bool],\nSequence[bool], int, dict, dict],\nTuple[dict, dict]]\n+ResAvalUpdater = Callable[[Dict[str, Any], AbstractValue], AbstractValue]\n+def _default_res_aval_updater(\n+ params: Dict[str, Any], aval: AbstractValue) -> AbstractValue:\n+ return aval\ndef call_partial_eval_custom_rule(\njaxpr_param_name: str, params_updater: ParamsUpdater,\nsaveable: Callable[..., bool], unks_in: List[bool], inst_in: List[bool],\n- eqn: JaxprEqn\n+ eqn: JaxprEqn, *, res_aval: ResAvalUpdater = _default_res_aval_updater,\n) -> Tuple[JaxprEqn, JaxprEqn, Sequence[bool], Sequence[bool], List[Var]]:\njaxpr = eqn.params[jaxpr_param_name]\njaxpr_known, jaxpr_staged, unks_out, inst_out, num_res = \\\n@@ -1371,12 +1376,13 @@ def call_partial_eval_custom_rule(\n_, ins_staged = partition_list(inst_in, eqn.invars)\n_, out_binders_staged = partition_list(inst_out, eqn.outvars)\nnewvar = core.gensym([jaxpr_known, jaxpr_staged])\n- residuals = [newvar(v.aval) for v in jaxpr_staged.invars[:num_res]]\nparams_known = {**eqn.params, jaxpr_param_name: jaxpr_known}\nparams_staged = {**eqn.params, jaxpr_param_name: jaxpr_staged}\nparams_known, params_staged = params_updater(\nunks_in, inst_in, map(op.not_, unks_out), inst_out, num_res, params_known,\nparams_staged)\n+ residuals = [newvar(res_aval(params_known, var.aval))\n+ for var in jaxpr_staged.invars[:num_res]]\neqn_known = new_jaxpr_eqn(ins_known, [*out_binders_known, *residuals],\neqn.primitive, params_known, jaxpr_known.effects, eqn.source_info)\neqn_staged = new_jaxpr_eqn([*residuals, *ins_staged], out_binders_staged,\n@@ -1891,7 +1897,7 @@ class DynamicJaxprTrace(core.Trace):\nif update_params:\nnew_params = update_params(new_params, [True] * len(tracers), len(consts))\neqn = new_jaxpr_eqn([*constvars, *invars], outvars, map_primitive,\n- new_params, new_params['call_jaxpr'].effects, source_info)\n+ new_params, jaxpr.effects, source_info)\nself.frame.add_eqn(eqn)\nreturn out_tracers\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -73,7 +73,7 @@ from jax._src.lib import xla_client as xc\nfrom jax._src.lib import pmap_lib\nfrom jax._src.lib.mlir import ir\nfrom jax._src.lib.mlir.dialects import mhlo\n-from jax._src.util import (unzip3, prod, safe_map, safe_zip,\n+from jax._src.util import (unzip3, prod, safe_map, safe_zip, partition_list,\nnew_name_stack, wrap_name, assert_unreachable,\ntuple_insert, tuple_delete, distributed_debug_log)\n@@ -1671,10 +1671,56 @@ xla_pmap_p = core.MapPrimitive('xla_pmap')\nxla_pmap = xla_pmap_p.bind\nxla_pmap_p.def_impl(xla_pmap_impl)\n+def _pmap_partial_eval_custom_params_updater(\n+ unks_in, inst_in, kept_outs_known, kept_outs_staged, num_res, params_known,\n+ params_staged):\n+ # prune inputs to jaxpr_known according to unks_in\n+ donated_invars_known, _ = partition_list(unks_in, params_known['donated_invars'])\n+ in_axes_known, _ = partition_list(unks_in, params_known['in_axes'])\n+ _, out_axes_known = partition_list(kept_outs_known, params_known['out_axes'])\n+ out_axes_known = out_axes_known + [0] * num_res\n+ new_params_known = dict(params_known, in_axes=tuple(in_axes_known),\n+ out_axes=tuple(out_axes_known),\n+ donated_invars=tuple(donated_invars_known))\n+\n+ # added num_res new inputs to jaxpr_staged, pruning according to inst_in\n+ _, donated_invars_staged = partition_list(inst_in, params_staged['donated_invars'])\n+ donated_invars_staged = [False] * num_res + donated_invars_staged\n+ _, in_axes_staged = partition_list(inst_in, params_staged['in_axes'])\n+ in_axes_staged = [0] * num_res + in_axes_staged\n+ _, out_axes_staged = partition_list(kept_outs_staged, params_staged['out_axes'])\n+ new_params_staged = dict(params_staged, in_axes=tuple(in_axes_staged),\n+ out_axes=tuple(out_axes_staged),\n+ donated_invars=tuple(donated_invars_staged))\n+ return new_params_known, new_params_staged\n+\n+def _pmap_partial_eval_custom_res_maker(params_known, aval):\n+ return core.unmapped_aval(params_known['axis_size'], core.no_axis_name, 0, aval)\n+\n+def _pmap_dce_rule(used_outputs, eqn):\n+ # just like pe.dce_jaxpr_call_rule, except handles in_axes / out_axes\n+ new_jaxpr, used_inputs = pe.dce_jaxpr(eqn.params['call_jaxpr'], used_outputs)\n+ _, in_axes = partition_list(used_inputs, eqn.params['in_axes'])\n+ _, out_axes = partition_list(used_outputs, eqn.params['out_axes'])\n+ new_params = dict(eqn.params, call_jaxpr=new_jaxpr, in_axes=tuple(in_axes),\n+ out_axes=tuple(out_axes))\n+ if not any(used_inputs) and not any(used_outputs) and not new_jaxpr.effects:\n+ return used_inputs, None\n+ else:\n+ new_eqn = pe.new_jaxpr_eqn(\n+ [v for v, used in zip(eqn.invars, used_inputs) if used],\n+ [v for v, used in zip(eqn.outvars, used_outputs) if used],\n+ eqn.primitive, new_params, new_jaxpr.effects, eqn.source_info)\n+ return used_inputs, new_eqn\n+\n+\n# Set param update handlers to update `donated_invars` just like xla_call_p\npe.call_param_updaters[xla_pmap_p] = pe.call_param_updaters[xla.xla_call_p]\npe.partial_eval_jaxpr_custom_rules[xla_pmap_p] = \\\n- partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'pmap')\n+ partial(pe.call_partial_eval_custom_rule,\n+ 'call_jaxpr', _pmap_partial_eval_custom_params_updater,\n+ res_aval=_pmap_partial_eval_custom_res_maker)\n+pe.dce_rules[xla_pmap_p] = _pmap_dce_rule\nad.call_param_updaters[xla_pmap_p] = ad.call_param_updaters[xla.xla_call_p]\nad.call_transpose_param_updaters[xla_pmap_p] = \\\nad.call_transpose_param_updaters[xla.xla_call_p]\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -1999,6 +1999,55 @@ class PythonPmapTest(jtu.JaxTestCase):\nreturn x\njax.grad(f)(3.) # doesn't fail\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', jax.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_remat_of_pmap(self, remat):\n+ f = remat(jax.pmap(lambda x: jnp.sin(jnp.sin(x))))\n+ jtu.check_grads(f, (jnp.arange(1.),), order=2, modes=[\"rev\"])\n+\n+ x = jnp.arange(1.)\n+ jaxpr = jax.make_jaxpr(jax.linearize(f, x)[1])(x)\n+ self.assertIn(' sin ', str(jaxpr))\n+ self.assertIn(' cos ', str(jaxpr))\n+\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n+ for suffix, remat in [\n+ ('', jax.remat),\n+ ('_new', new_checkpoint),\n+ ])\n+ def test_remat_of_pmap_policy(self, remat):\n+ g = jax.pmap(lambda x: jnp.sin(jnp.sin(x)))\n+ x = jnp.arange(1.)\n+\n+ save_cos = lambda prim, *_, **__: str(prim) == 'cos'\n+ f = remat(g, policy=save_cos)\n+ _, f_vjp = jax.vjp(f, x)\n+ jaxpr = f_vjp.args[0].func.args[1]\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 0)\n+ self.assertEqual(jaxpr_text.count(' cos '), 0)\n+\n+ save_sin = lambda prim, *_, **__: str(prim) == 'sin'\n+ f = remat(g, policy=save_sin)\n+ _, f_vjp = jax.vjp(f, x)\n+ jaxpr = f_vjp.args[0].func.args[1]\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 0)\n+ self.assertEqual(jaxpr_text.count(' cos '), 2)\n+\n+ save_nothing = lambda prim, *_, **__: False\n+ f = remat(g, policy=save_nothing)\n+ _, f_vjp = jax.vjp(f, x)\n+ jaxpr = f_vjp.args[0].func.args[1]\n+ jaxpr_text = str(jaxpr)\n+ self.assertEqual(jaxpr_text.count(' sin '), 1)\n+ self.assertEqual(jaxpr_text.count(' cos '), 2)\n+\nclass CppPmapTest(PythonPmapTest):\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -728,6 +728,13 @@ class XMapTest(XMapTestCase):\nf = checkpoint(xmap(lambda x: x, in_axes=['i', ...], out_axes=['i', ...]))\nself.assertAllClose(jax.grad(lambda x: f(x).sum())(jnp.arange(3.)), jnp.ones(3))\n+ def testNewCheckpointNonlinearWithPolicy(self):\n+ raise SkipTest(\"fails!\") # TODO(mattjj,apaszke): residual outvars problem\n+ f = checkpoint(xmap(lambda x: jnp.sin(jnp.sin(x)), in_axes=['i', ...],\n+ out_axes=['i', ...]),\n+ policy=lambda prim, *_, **__: str(prim) == 'sin')\n+ jax.grad(lambda x: f(x).sum())(jnp.arange(3.)) # TODO crashes!\n+\nclass XMapTestSPMD(SPMDTestMixin, XMapTest):\n\"\"\"Re-executes all basic tests with the SPMD partitioner enabled\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
add custom-policy partial eval and dce rules for pmap Also add a failing test for xmap.
260,335
28.07.2022 21:37:23
25,200
aa043a60b626bdfd025c7abe726068391a10a906
add test for custom_linear_solve + new remat
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/solves.py", "new_path": "jax/_src/lax/control_flow/solves.py", "diff": "@@ -466,5 +466,3 @@ mlir.register_lowering(\nmultiple_results=True))\nad.primitive_transposes[linear_solve_p] = _linear_solve_transpose_rule\nbatching.axis_primitive_batchers[linear_solve_p] = _linear_solve_batching_rule\n-pe.partial_eval_jaxpr_custom_rules[linear_solve_p] = \\\n- partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'linear_solve')\n" }, { "change_type": "MODIFY", "old_path": "tests/custom_linear_solve_test.py", "new_path": "tests/custom_linear_solve_test.py", "diff": "@@ -23,6 +23,7 @@ import numpy as np\nimport jax\nfrom jax import lax\n+from jax.ad_checkpoint import checkpoint\nfrom jax._src import test_util as jtu\nfrom jax import tree_util\nimport jax.numpy as jnp # scan tests use numpy\n@@ -414,6 +415,32 @@ class CustomLinearSolveTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, re.escape(\"matvec() output shapes\")):\njax.jvp(bad_matvec_usage, (1.0,), (1.0,))\n+ def test_custom_linear_solve_new_remat(self):\n+\n+ def explicit_jacobian_solve(matvec, b):\n+ return lax.stop_gradient(jnp.linalg.solve(jax.jacobian(matvec)(b), b))\n+\n+ def matrix_free_solve(matvec, b):\n+ return lax.custom_linear_solve(\n+ matvec, b, explicit_jacobian_solve, explicit_jacobian_solve,\n+ symmetric=True)\n+\n+ @checkpoint\n+ def linear_solve(a, b):\n+ return matrix_free_solve(partial(high_precision_dot, a), b)\n+\n+ rng = self.rng()\n+ a = rng.randn(3, 3)\n+ if True:\n+ a = a + a.T\n+ b = rng.randn(3)\n+ jtu.check_grads(linear_solve, (a, b), order=1, rtol=3e-3, modes=['rev'])\n+\n+ @partial(checkpoint, policy=lambda *_, **__: True)\n+ def linear_solve(a, b):\n+ return matrix_free_solve(partial(high_precision_dot, a), b)\n+ jtu.check_grads(linear_solve, (a, b), order=1, rtol=3e-3, modes=['rev'])\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
add test for custom_linear_solve + new remat
260,510
28.07.2022 21:47:25
25,200
fb0cf668b8165eb66832d7d32c8f6621f35f2ffa
Update debugging docs to mention pjit
[ { "change_type": "MODIFY", "old_path": "docs/debugging/index.md", "new_path": "docs/debugging/index.md", "diff": "@@ -4,7 +4,7 @@ Do you have exploding gradients? Are nans making you gnash your teeth? Just want\n## [Interactive inspection with `jax.debug`](print_breakpoint)\n- **TL;DR** Use {func}`jax.debug.print` to print values to stdout in `jax.jit`- or `jax.pmap`-decorated functions\n+ **TL;DR** Use {func}`jax.debug.print` to print values to stdout in `jax.jit`-,`jax.pmap`-, and `pjit`-decorated functions\nand use {func}`jax.debug.breakpoint` to pause execution of your compiled function to inspect values in the call stack:\n```python\n" }, { "change_type": "MODIFY", "old_path": "docs/debugging/print_breakpoint.md", "new_path": "docs/debugging/print_breakpoint.md", "diff": "@@ -5,7 +5,7 @@ inside of JIT-ted functions.\n## Debugging with `jax.debug.print` and other debugging callbacks\n-**TL;DR** Use {func}`jax.debug.print` to print values to stdout in `jax.jit`- or `jax.pmap`-decorated functions:\n+**TL;DR** Use {func}`jax.debug.print` to print values to stdout in `jax.jit`-,`jax.pmap`-, and `pjit`-decorated functions:\n```python\nimport jax\n@@ -65,7 +65,6 @@ Notice that the printed results are in different orders!\nBy revealing these inner-workings, the output of `jax.debug.print` doesn't respect JAX's usual semantics guarantees, like that `jax.vmap(f)(xs)` and `jax.lax.map(f, xs)` compute the same thing (in different ways). Yet these evaluation order details are exactly what we might want to see when debugging!\n-<!-- mattjj tweaked this line -->\nSo use `jax.debug.print` for debugging, and not when semantics guarantees are important.\n### More examples of `jax.debug.print`\n@@ -101,7 +100,6 @@ jax.grad(f)(1.)\n# Prints: x: 1.0\n```\n-<!-- mattjj added this line -->\nThis behavior is similar to how Python's builtin `print` works under a `jax.grad`. But by using `jax.debug.print` here, the behavior is the same even if the caller applies a `jax.jit`.\nTo print on the backward pass, just use a `jax.custom_vjp`:\n@@ -128,6 +126,11 @@ jax.grad(f)(1.)\n# Prints: x_grad: 2.0\n```\n+#### Printing in other transformations\n+\n+`jax.debug.print` also works in other transformations like `xmap` and `pjit`\n+(but `pjit` only works on TPUs for now).\n+\n### More control with `jax.debug.callback`\nIn fact, `jax.debug.print` is a thin convenience wrapper around `jax.debug.callback`, which can be used directly for greater control over string formatting, or even the kind of output.\n" } ]
Python
Apache License 2.0
google/jax
Update debugging docs to mention pjit
260,424
29.07.2022 17:27:40
-3,600
1ace5d351b3e42acc1ec4d2e805224ec9d810e63
Checkify: support checkify-of-pjit.
[ { "change_type": "MODIFY", "old_path": "jax/_src/checkify.py", "new_path": "jax/_src/checkify.py", "diff": "@@ -16,7 +16,7 @@ import enum\nfrom dataclasses import dataclass\nfrom functools import partial\nimport itertools as it\n-from typing import Union, Optional, Callable, Dict, Tuple, TypeVar, FrozenSet\n+from typing import Union, Optional, Callable, Dict, Tuple, TypeVar, FrozenSet, Iterable\nimport numpy as np\n@@ -25,9 +25,12 @@ import jax.numpy as jnp\nfrom jax import core\nfrom jax import linear_util as lu\nfrom jax.api_util import flatten_fun\n+from jax.experimental import pjit\n+from jax.experimental import maps\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\n+from jax.interpreters import pxla\nfrom jax.tree_util import tree_flatten, tree_unflatten, register_pytree_node\nfrom jax._src import source_info_util, traceback_util\nfrom jax._src.lax import control_flow as cf\n@@ -669,6 +672,40 @@ def while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\nreturn out, Error(err, code, new_msgs, payload)\nerror_checks[lax.while_p] = while_loop_error_check\n+\n+def pjit_error_check(error, enabled_errors, *vals_in, jaxpr,\n+ in_shardings, out_shardings, resource_env,\n+ donated_invars, name,\n+ in_positional_semantics, out_positional_semantics):\n+ checked_jaxpr, msgs = checkify_jaxpr(jaxpr, error, enabled_errors)\n+ new_vals_in = [error.err, error.code, error.payload, *vals_in]\n+ # TODO(lenamartens, yashkatariya): replace with OpShardingSharding.\n+ sharding = pxla._create_mesh_pspec_sharding(pxla.thread_resources.env.physical_mesh,\n+ pxla.PartitionSpec(None))\n+ pos_sem = maps._positional_semantics.val\n+ new_in_shardings = (*[sharding]*3, *in_shardings)\n+ new_out_shardings = (*[sharding]*3, *out_shardings)\n+ if not isinstance(in_positional_semantics, Iterable):\n+ in_positional_semantics = (in_positional_semantics,)\n+ if not isinstance(out_positional_semantics, Iterable):\n+ out_positional_semantics = (out_positional_semantics,)\n+ new_positional_sems_in = (*[pos_sem]*3, *in_positional_semantics)\n+ new_positional_sems_out = (*[pos_sem]*3, *out_positional_semantics)\n+ new_donated_invars = (*[False]*3, *donated_invars)\n+ err, code, payload, *vals_out = pjit.pjit_p.bind(\n+ *new_vals_in,\n+ jaxpr=checked_jaxpr,\n+ in_shardings=new_in_shardings,\n+ out_shardings=new_out_shardings,\n+ resource_env=resource_env,\n+ donated_invars=new_donated_invars,\n+ name=name,\n+ in_positional_semantics=new_positional_sems_in,\n+ out_positional_semantics=new_positional_sems_out)\n+ return vals_out, Error(err, code, msgs, payload)\n+error_checks[pjit.pjit_p] = pjit_error_check\n+\n+\ndef add_nan_check(prim):\nerror_checks[prim] = partial(nan_error_check, prim)\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -24,6 +24,8 @@ from jax import lax\nimport jax._src.test_util as jtu\nfrom jax.config import config\nfrom jax.experimental import checkify\n+from jax.experimental import pjit\n+from jax.experimental import maps\nfrom jax._src.checkify import CheckEffect\nimport jax.numpy as jnp\n@@ -410,6 +412,30 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n# first error which occurs is in cond\nself.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ def test_pjit(self):\n+ def f(x):\n+ # unary func\n+ return x / x\n+\n+ def g(x, y):\n+ # binary func\n+ return x / y\n+\n+ ps = pjit.PartitionSpec(\"dev\")\n+ f = pjit.pjit(f, in_axis_resources=ps, out_axis_resources=ps)\n+ f = checkify.checkify(f, errors=checkify.float_checks)\n+ g = pjit.pjit(g, in_axis_resources=ps, out_axis_resources=ps)\n+ g = checkify.checkify(g, errors=checkify.float_checks)\n+ with maps.Mesh(np.array(jax.devices()), [\"dev\"]):\n+ x = jnp.arange(8)\n+ u_err, _ = f(x)\n+ b_err, _ = g(x, x)\n+\n+ self.assertIsNotNone(u_err.get())\n+ self.assertStartsWith(u_err.get(), \"divided by zero\")\n+ self.assertIsNotNone(b_err.get())\n+ self.assertStartsWith(b_err.get(), \"divided by zero\")\n+\ndef test_empty_enabled_errors(self):\ndef multi_errors(x):\nx = x/0 # DIV\n" } ]
Python
Apache License 2.0
google/jax
Checkify: support checkify-of-pjit.
260,510
29.07.2022 12:00:26
25,200
decdca60c84c9b136eba246e7a6bbcb1d5daa4aa
Change jaxdb->jdb and add option to force a backend
[ { "change_type": "MODIFY", "old_path": "docs/debugging/flags.md", "new_path": "docs/debugging/flags.md", "diff": "# JAX debugging flags\n-JAX offers flags and context managers.\n+JAX offers flags and context managers that enable catching errors more easily.\n## `jax_debug_nans` configuration option and context manager\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/cli_debugger.py", "new_path": "jax/_src/debugger/cli_debugger.py", "diff": "@@ -26,7 +26,7 @@ DebuggerFrame = debugger_core.DebuggerFrame\nclass CliDebugger(cmd.Cmd):\n\"\"\"A text-based debugger.\"\"\"\n- prompt = '(jaxdb) '\n+ prompt = '(jdb) '\nuse_rawinput: bool = False\ndef __init__(self, frames: List[DebuggerFrame], thread_id,\n@@ -36,7 +36,7 @@ class CliDebugger(cmd.Cmd):\nself.frames = frames\nself.frame_index = 0\nself.thread_id = thread_id\n- self.intro = 'Entering jaxdb:'\n+ self.intro = 'Entering jdb:'\ndef current_frame(self):\nreturn self.frames[self.frame_index]\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/core.py", "new_path": "jax/_src/debugger/core.py", "diff": "@@ -95,7 +95,9 @@ class Debugger(Protocol):\n_debugger_registry: Dict[str, Tuple[int, Debugger]] = {}\n-def get_debugger() -> Debugger:\n+def get_debugger(backend: Optional[str] = None) -> Debugger:\n+ if backend is not None and backend in _debugger_registry:\n+ return _debugger_registry[backend][1]\ndebuggers = sorted(_debugger_registry.values(), key=lambda x: -x[0])\nif not debuggers:\nraise ValueError(\"No debuggers registered!\")\n@@ -111,7 +113,7 @@ def register_debugger(name: str, debugger: Debugger, priority: int) -> None:\ndebug_lock = threading.Lock()\n-def breakpoint(*, ordered: bool = False, **kwargs): # pylint: disable=redefined-builtin\n+def breakpoint(*, ordered: bool = False, backend=None, **kwargs): # pylint: disable=redefined-builtin\n\"\"\"Enters a breakpoint at a point in a program.\"\"\"\nframe_infos = inspect.stack()\n# Filter out internal frames\n@@ -131,7 +133,7 @@ def breakpoint(*, ordered: bool = False, **kwargs): # pylint: disable=redefined\nthread_id = None\nif threading.current_thread() is not threading.main_thread():\nthread_id = threading.get_ident()\n- debugger = get_debugger()\n+ debugger = get_debugger(backend=backend)\n# Lock here because this could be called from multiple threads at the same\n# time.\nwith debug_lock:\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/debugger/web_debugger.py", "new_path": "jax/_src/debugger/web_debugger.py", "diff": "@@ -31,7 +31,7 @@ _web_consoles: Dict[Tuple[str, int], web_pdb.WebConsole] = {}\nclass WebDebugger(cli_debugger.CliDebugger):\n\"\"\"A web-based debugger.\"\"\"\n- prompt = '(jaxdb) '\n+ prompt = '(jdb) '\nuse_rawinput: bool = False\ndef __init__(self, frames: List[debugger_core.DebuggerFrame], thread_id,\n" }, { "change_type": "MODIFY", "old_path": "tests/debugger_test.py", "new_path": "tests/debugger_test.py", "diff": "@@ -67,7 +67,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndef f(x):\ny = jnp.sin(x)\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\nwith self.assertRaises(SystemExit):\nf(2.)\n@@ -79,13 +79,13 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndef f(x):\ny = jnp.sin(x)\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\nf(2.)\njax.effects_barrier()\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- (jaxdb) \"\"\")\n+ Entering jdb:\n+ (jdb) \"\"\")\nself.assertEqual(stdout.getvalue(), expected)\n@jtu.skip_on_devices(*disabled_backends)\n@@ -94,12 +94,12 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndef f(x):\ny = jnp.sin(x)\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- (jaxdb) DeviceArray(2., dtype=float32)\n- (jaxdb) \"\"\")\n+ Entering jdb:\n+ (jdb) DeviceArray(2., dtype=float32)\n+ (jdb) \"\"\")\nf(jnp.array(2., jnp.float32))\njax.effects_barrier()\nself.assertEqual(stdout.getvalue(), expected)\n@@ -111,12 +111,12 @@ class CliDebuggerTest(jtu.JaxTestCase):\n@jax.jit\ndef f(x):\ny = jnp.sin(x)\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- (jaxdb) array(2., dtype=float32)\n- (jaxdb) \"\"\")\n+ Entering jdb:\n+ (jdb) array(2., dtype=float32)\n+ (jdb) \"\"\")\nf(jnp.array(2., jnp.float32))\njax.effects_barrier()\nself.assertEqual(stdout.getvalue(), expected)\n@@ -128,12 +128,12 @@ class CliDebuggerTest(jtu.JaxTestCase):\n@jax.jit\ndef f(x):\ny = x + 1.\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- (jaxdb) (array(2., dtype=float32), array(3., dtype=float32))\n- (jaxdb) \"\"\")\n+ Entering jdb:\n+ (jdb) (array(2., dtype=float32), array(3., dtype=float32))\n+ (jdb) \"\"\")\nf(jnp.array(2., jnp.float32))\njax.effects_barrier()\nself.assertEqual(stdout.getvalue(), expected)\n@@ -145,20 +145,20 @@ class CliDebuggerTest(jtu.JaxTestCase):\n@jax.jit\ndef f(x):\ny = jnp.sin(x)\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\nf(2.)\njax.effects_barrier()\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- \\(jaxdb\\) > .*debugger_test\\.py\\([0-9]+\\)\n+ Entering jdb:\n+ \\(jdb\\) > .*debugger_test\\.py\\([0-9]+\\)\n@jax\\.jit\ndef f\\(x\\):\ny = jnp\\.sin\\(x\\)\n- -> debugger\\.breakpoint\\(stdin=stdin, stdout=stdout\\)\n+ -> debugger\\.breakpoint\\(stdin=stdin, stdout=stdout, backend=\"cli\"\\)\nreturn y\n.*\n- \\(jaxdb\\) \"\"\")\n+ \\(jdb\\) \"\"\")\nself.assertRegex(stdout.getvalue(), expected)\n@jtu.skip_on_devices(*disabled_backends)\n@@ -168,11 +168,11 @@ class CliDebuggerTest(jtu.JaxTestCase):\n@jax.jit\ndef f(x):\ny = jnp.sin(x)\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:.*\n- \\(jaxdb\\) Traceback:.*\n+ Entering jdb:.*\n+ \\(jdb\\) Traceback:.*\n\"\"\")\nf(2.)\njax.effects_barrier()\n@@ -184,7 +184,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndef f(x):\ny = jnp.sin(x)\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\n@jax.jit\n@@ -192,27 +192,27 @@ class CliDebuggerTest(jtu.JaxTestCase):\ny = f(x)\nreturn jnp.exp(y)\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- \\(jaxdb\\) > .*debugger_test\\.py\\([0-9]+\\)\n+ Entering jdb:\n+ \\(jdb\\) > .*debugger_test\\.py\\([0-9]+\\)\ndef f\\(x\\):\ny = jnp\\.sin\\(x\\)\n- -> debugger\\.breakpoint\\(stdin=stdin, stdout=stdout\\)\n+ -> debugger\\.breakpoint\\(stdin=stdin, stdout=stdout, backend=\"cli\"\\)\nreturn y\n.*\n- \\(jaxdb\\) > .*debugger_test\\.py\\([0-9]+\\).*\n+ \\(jdb\\) > .*debugger_test\\.py\\([0-9]+\\).*\n@jax\\.jit\ndef g\\(x\\):\n-> y = f\\(x\\)\nreturn jnp\\.exp\\(y\\)\n.*\n- \\(jaxdb\\) array\\(2\\., dtype=float32\\)\n- \\(jaxdb\\) > .*debugger_test\\.py\\([0-9]+\\)\n+ \\(jdb\\) array\\(2\\., dtype=float32\\)\n+ \\(jdb\\) > .*debugger_test\\.py\\([0-9]+\\)\ndef f\\(x\\):\ny = jnp\\.sin\\(x\\)\n- -> debugger\\.breakpoint\\(stdin=stdin, stdout=stdout\\)\n+ -> debugger\\.breakpoint\\(stdin=stdin, stdout=stdout, backend=\"cli\"\\)\nreturn y\n.*\n- \\(jaxdb\\) \"\"\")\n+ \\(jdb\\) \"\"\")\ng(jnp.array(2., jnp.float32))\njax.effects_barrier()\nself.assertRegex(stdout.getvalue(), expected)\n@@ -223,20 +223,22 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndef f(x):\ny = x + 1.\n- debugger.breakpoint(stdin=stdin, stdout=stdout, ordered=True)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, ordered=True,\n+ backend=\"cli\")\nreturn y\n@jax.jit\ndef g(x):\ny = f(x) * 2.\n- debugger.breakpoint(stdin=stdin, stdout=stdout, ordered=True)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, ordered=True,\n+ backend=\"cli\")\nreturn jnp.exp(y)\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- (jaxdb) array(3., dtype=float32)\n- (jaxdb) Entering jaxdb:\n- (jaxdb) array(6., dtype=float32)\n- (jaxdb) \"\"\")\n+ Entering jdb:\n+ (jdb) array(3., dtype=float32)\n+ (jdb) Entering jdb:\n+ (jdb) array(6., dtype=float32)\n+ (jdb) \"\"\")\ng(jnp.array(2., jnp.float32))\njax.effects_barrier()\nself.assertEqual(stdout.getvalue(), expected)\n@@ -251,7 +253,8 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndef f(x):\ny = x + 1.\n- debugger.breakpoint(stdin=stdin, stdout=stdout, ordered=ordered)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, ordered=ordered,\n+ backend=\"cli\")\nreturn 2. * y\n@jax.jit\n@@ -260,11 +263,11 @@ class CliDebuggerTest(jtu.JaxTestCase):\ny = f(x)\nreturn jnp.exp(y)\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- (jaxdb) array(1., dtype=float32)\n- (jaxdb) Entering jaxdb:\n- (jaxdb) array(2., dtype=float32)\n- (jaxdb) \"\"\")\n+ Entering jdb:\n+ (jdb) array(1., dtype=float32)\n+ (jdb) Entering jdb:\n+ (jdb) array(2., dtype=float32)\n+ (jdb) \"\"\")\ng(jnp.arange(2., dtype=jnp.float32))\njax.effects_barrier()\nself.assertEqual(stdout.getvalue(), expected)\n@@ -277,7 +280,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndef f(x):\ny = jnp.sin(x)\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\n@jax.pmap\n@@ -285,11 +288,11 @@ class CliDebuggerTest(jtu.JaxTestCase):\ny = f(x)\nreturn jnp.exp(y)\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- \\(jaxdb\\) array\\(.*, dtype=float32\\)\n- \\(jaxdb\\) Entering jaxdb:\n- \\(jaxdb\\) array\\(.*, dtype=float32\\)\n- \\(jaxdb\\) \"\"\")\n+ Entering jdb:\n+ \\(jdb\\) array\\(.*, dtype=float32\\)\n+ \\(jdb\\) Entering jdb:\n+ \\(jdb\\) array\\(.*, dtype=float32\\)\n+ \\(jdb\\) \"\"\")\ng(jnp.arange(2., dtype=jnp.float32))\njax.effects_barrier()\nself.assertRegex(stdout.getvalue(), expected)\n@@ -302,7 +305,7 @@ class CliDebuggerTest(jtu.JaxTestCase):\ndef f(x):\ny = x + 1\n- debugger.breakpoint(stdin=stdin, stdout=stdout)\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\nreturn y\ndef g(x):\n@@ -313,9 +316,9 @@ class CliDebuggerTest(jtu.JaxTestCase):\nwith maps.Mesh(np.array(jax.devices()), [\"dev\"]):\narr = (1 + np.arange(8)).astype(np.int32)\nexpected = _format_multiline(r\"\"\"\n- Entering jaxdb:\n- \\(jaxdb\\) {}\n- \\(jaxdb\\) \"\"\".format(re.escape(repr(arr))))\n+ Entering jdb:\n+ \\(jdb\\) {}\n+ \\(jdb\\) \"\"\".format(re.escape(repr(arr))))\ng(jnp.arange(8, dtype=jnp.int32))\njax.effects_barrier()\nprint(stdout.getvalue())\n" } ]
Python
Apache License 2.0
google/jax
Change jaxdb->jdb and add option to force a backend
260,335
29.07.2022 15:23:29
25,200
cbcfe95e800e3bcc6165484b0f46c78764cd2296
fix ad_checkpoint.checkpoint caching issue Also add a config option to switch to the new checkpoint implementation globally (default False for now), as the first step in replacing and then deleting old remat.
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_checkpoint.py", "new_path": "jax/_src/ad_checkpoint.py", "diff": "from functools import partial\nimport operator as op\n-from typing import Callable, Optional, List, Tuple\n+from typing import Callable, Optional, List, Tuple, Sequence, Union\nimport types\nimport jax\n@@ -27,16 +27,15 @@ from jax.interpreters import mlir\nfrom jax.tree_util import tree_flatten, tree_unflatten\nfrom jax._src import ad_util\nfrom jax._src import source_info_util\n-from jax._src.api_util import flatten_fun\n+from jax._src.api_util import flatten_fun, shaped_abstractify\nfrom jax._src.traceback_util import api_boundary\nfrom jax._src.util import (unzip2, wraps, split_list, partition_list, safe_map,\n- safe_zip, merge_lists)\n+ safe_zip, merge_lists, weakref_lru_cache)\nsource_info_util.register_exclusion(__file__)\n# TODO(mattjj): before this can be the standard remat implementation, we must:\n# [ ] fix up callers who use the 'concrete' option (now removed)\n-# [ ] implement remat-of-control-flow-primitives (passing through the policy)\nmap = safe_map\nzip = safe_zip\n@@ -209,18 +208,23 @@ def checkpoint(fun: Callable, prevent_cse: bool = True,\n@api_boundary\ndef fun_remat(*args, **kwargs):\nargs_flat, in_tree = tree_flatten((args, kwargs))\n- flat_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n- in_avals = [core.raise_to_shaped(core.get_aval(x)) for x in args_flat]\n- debug = pe.debug_info(fun, in_tree, False, \"checkpoint\")\n- jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(flat_fun, in_avals, debug)\n+ in_avals = [shaped_abstractify(x) for x in args_flat]\n+ jaxpr, consts, out_tree = _trace_to_jaxpr(fun, in_tree, tuple(in_avals))\nout_flat = remat_p.bind(\n- *consts, *args_flat, jaxpr=pe.convert_constvars_jaxpr(jaxpr),\n- prevent_cse=prevent_cse, differentiated=False, policy=policy)\n- return tree_unflatten(out_tree(), out_flat)\n+ *consts, *args_flat, jaxpr=jaxpr, prevent_cse=prevent_cse,\n+ differentiated=False, policy=policy)\n+ return tree_unflatten(out_tree, out_flat)\nreturn fun_remat\nremat = checkpoint # alias\n+@weakref_lru_cache\n+def _trace_to_jaxpr(fun, in_tree, in_avals):\n+ debug = pe.debug_info(fun, in_tree, False, \"checkpoint\")\n+ flat_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n+ jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(flat_fun, in_avals, debug)\n+ return pe.convert_constvars_jaxpr(jaxpr), consts, out_tree()\n+\n### Utilities\n@@ -285,8 +289,7 @@ def remat_abstract_eval(*args, jaxpr, prevent_cse, differentiated, policy):\ndef remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\nassert not jaxpr.constvars\nin_nonzeros = [type(t) is not ad_util.Zero for t in tangents]\n- jaxpr_ = core.ClosedJaxpr(jaxpr, ())\n- jaxpr_jvp_, out_nonzeros = ad.jvp_jaxpr(jaxpr_, in_nonzeros, False)\n+ jaxpr_jvp_, out_nz = ad.jvp_jaxpr(pe.close_jaxpr(jaxpr), in_nonzeros, False)\nnonzero_tangents = [t for t in tangents if type(t) is not ad_util.Zero]\njaxpr_jvp = pe.convert_constvars_jaxpr(jaxpr_jvp_.jaxpr)\nouts = remat_p.bind(\n@@ -295,7 +298,7 @@ def remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\nout_primals, out_tangents_ = split_list(outs, [len(jaxpr.outvars)])\nout_tangents_ = iter(out_tangents_)\nout_tangents = [next(out_tangents_) if nz else ad_util.Zero.from_value(p)\n- for p, nz in zip(out_primals, out_nonzeros)]\n+ for p, nz in zip(out_primals, out_nz)]\nreturn out_primals, out_tangents\nad.primitive_jvps[remat_p] = remat_jvp\n@@ -351,45 +354,82 @@ pe.partial_eval_jaxpr_custom_rules[remat_p] = \\\ndef remat_transpose(reduce_axes, out_cts, *in_primals, jaxpr, **params):\nassert not jaxpr.constvars\n+ in_linear = [ad.is_undefined_primal(x) for x in in_primals]\n+ out_zeros = [type(ct) is ad_util.Zero for ct in out_cts]\n+ transposed_jaxpr_, in_zeros = transpose_jaxpr(\n+ pe.close_jaxpr(jaxpr), in_linear, out_zeros, reduce_axes)\n+ transposed_jaxpr, consts = transposed_jaxpr_.jaxpr, transposed_jaxpr_.consts\n+ transposed_jaxpr = pe.convert_constvars_jaxpr(transposed_jaxpr)\n+ args, _ = tree_flatten((in_primals, out_cts))\n+ in_cts_nz = remat_p.bind(*consts, *args, jaxpr=transposed_jaxpr, **params)\n+ in_cts_nz_, in_zeros_ = iter(in_cts_nz), iter(in_zeros)\n+ in_cts = [None if not ad.is_undefined_primal(x) else\n+ ad_util.Zero(x.aval) if next(in_zeros_) else next(in_cts_nz_)\n+ for x in in_primals]\n+ assert next(in_cts_nz_, None) is next(in_zeros_, None) is None\n+ return in_cts\n+ad.reducing_transposes[remat_p] = remat_transpose\n+\n+# TODO(mattjj): move this to ad.py\n+def transpose_jaxpr(jaxpr: core.ClosedJaxpr, in_linear: Union[bool, Sequence[bool]],\n+ out_zeros: Union[bool, Sequence[bool]],\n+ reduce_axes: Sequence[core.AxisName],\n+ ) -> Tuple[core.ClosedJaxpr, List[bool]]:\n+ if type(in_linear) is bool:\n+ in_linear = (in_linear,) * len(jaxpr.in_avals)\n+ if type(out_zeros) is bool:\n+ out_zeros = (out_zeros,) * len(jaxpr.out_avals)\n+ return _transpose_jaxpr(jaxpr, tuple(in_linear), tuple(out_zeros),\n+ tuple(reduce_axes))\n+\n+@weakref_lru_cache\n+def _transpose_jaxpr(jaxpr, in_lin, out_zeros, reduce_axes):\n+ in_avals = ([a for a, lin in zip(jaxpr.in_avals, in_lin ) if not lin] +\n+ [a for a, zero in zip(jaxpr.out_avals, out_zeros) if not zero])\ncell = lambda: None\n@lu.wrap_init\n- def transposed(*args):\n- in_primals, out_cts = tree_unflatten(treedef, args)\n- in_pvals = [pe.PartialVal.unknown(x.aval) if ad.is_undefined_primal(x) else\n- pe.PartialVal.known(x) for x in in_primals]\n- primal_fun = lu.wrap_init(partial(core.eval_jaxpr, jaxpr, ()))\n- t_jaxpr, _, consts = pe.trace_to_jaxpr_nounits(primal_fun, in_pvals, False)\n- dummy_args = [ad.UndefinedPrimal(v.aval) for v in t_jaxpr.invars]\n- in_cts = ad.backward_pass(t_jaxpr, reduce_axes, False, consts, dummy_args,\n+ def transposed(*args_flat):\n+ ins_flat, out_cts_flat = split_list(args_flat, [len(in_lin) - sum(in_lin)])\n+\n+ # Evaluate nonlinear parts using partial evaluation to get a linear jaxpr.\n+ ins_iter = iter(ins_flat)\n+ in_pvals = [pe.PartialVal.unknown(aval) if lin else\n+ pe.PartialVal.known(next(ins_iter))\n+ for aval, lin in zip(jaxpr.in_avals, in_lin)]\n+ assert next(ins_iter, None) is None\n+ lin_jaxpr, _, consts = pe.trace_to_jaxpr_nounits(\n+ lu.wrap_init(core.jaxpr_as_fun(jaxpr)), in_pvals, False)\n+\n+ # Transpose the linear jaxpr (which only has linear inputs).\n+ out_cts_iter = iter(out_cts_flat)\n+ out_cts = [ad_util.Zero(aval) if zero else next(out_cts_iter)\n+ for aval, zero in zip(jaxpr.out_avals, out_zeros)]\n+ assert next(out_cts_iter, None) is None\n+ dummy_args = [ad.UndefinedPrimal(v.aval) for v in lin_jaxpr.invars]\n+ in_cts = ad.backward_pass(lin_jaxpr, reduce_axes, False, consts, dummy_args,\nout_cts)\n- in_cts_ = iter(in_cts)\n- in_cts = [next(in_cts_) if ad.is_undefined_primal(x)\n- else ad_util.Zero(x.aval) for x in in_primals]\n- assert next(in_cts_, None) is None\n- in_cts, cell.treedef = tree_flatten(in_cts)\n- return in_cts\n- args, treedef = tree_flatten((in_primals, out_cts))\n- in_avals = [core.raise_to_shaped(core.get_aval(x)) for x in args]\n+ # Identify symbolic zeros in the resulting cotangents, and return nonzeros.\n+ in_zeros = cell.in_cts_zero = [type(ct) is ad_util.Zero for ct in in_cts]\n+ in_cts_nz, _ = partition_list(in_zeros, in_cts)\n+ return in_cts_nz\n+\ntransposed_jaxpr_, _, consts = pe.trace_to_jaxpr_dynamic(transposed, in_avals)\n- transposed_jaxpr = pe.convert_constvars_jaxpr(transposed_jaxpr_)\n- in_cts = remat_p.bind(*consts, *args, jaxpr=transposed_jaxpr, **params)\n- return tree_unflatten(cell.treedef, in_cts) # type: ignore\n-ad.reducing_transposes[remat_p] = remat_transpose\n+ transposed_jaxpr = core.ClosedJaxpr(transposed_jaxpr_, consts)\n+ return transposed_jaxpr, cell.in_cts_zero # type: ignore\ndef remat_vmap(axis_size, axis_name, main_type, args, dims, *, jaxpr, **params):\nassert not jaxpr.constvars\n- jaxpr_ = core.ClosedJaxpr(jaxpr, ())\njaxpr_batched_, out_batched = batching.batch_jaxpr_axes(\n- jaxpr_, axis_size, dims, [batching.zero_if_mapped] * len(jaxpr.outvars),\n+ pe.close_jaxpr(jaxpr), axis_size, dims,\n+ [batching.zero_if_mapped] * len(jaxpr.outvars),\naxis_name=axis_name, main_type=main_type)\njaxpr_batched, consts = jaxpr_batched_.jaxpr, jaxpr_batched_.consts\nout_dims = [0 if b else None for b in out_batched]\nreturn remat_p.bind(*consts, *args, jaxpr=jaxpr_batched, **params), out_dims\nbatching.axis_primitive_batchers[remat_p] = remat_vmap\n-# TODO(mattjj,sharadmv): test this more\n# TODO(mattjj,sharadmv): de-duplicate with pe.dce_jaxpr_call_rule\ndef remat_dce(used_outputs: List[bool], eqn: core.JaxprEqn\n) -> Tuple[List[bool], Optional[core.JaxprEqn]]:\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -70,7 +70,7 @@ from jax._src.lib.xla_bridge import (device_count, local_device_count, devices,\nlocal_devices, process_index,\nprocess_count, host_id, host_ids,\nhost_count, default_backend)\n-from jax.ad_checkpoint import checkpoint_policies\n+from jax.ad_checkpoint import checkpoint_policies, checkpoint as new_checkpoint\nfrom jax.core import ShapedArray, raise_to_shaped\nfrom jax.custom_batching import custom_vmap\nfrom jax.custom_derivatives import (closure_convert, custom_gradient, custom_jvp,\n@@ -3095,12 +3095,12 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\n``pmap``, CSE can defeat the purpose of this decorator. But in some\nsettings, like when used inside a ``scan``, this CSE prevention mechanism\nis unnecessary, in which case ``prevent_cse`` can be set to False.\n- policy: This is an experimental feature and the API is likely to change.\n- Optional callable, one of the attributes of ``jax.checkpoint_policies``,\n- which takes as input a type-level specification of a first-order primitive\n- application and returns a boolean indicating whether the corresponding\n- output value(s) can be saved as a residual (or, if not, instead must be\n- recomputed in the (co)tangent computation).\n+ policy: Optional callable, one of the attributes of\n+ ``jax.checkpoint_policies``, which takes as input a type-level\n+ specification of a first-order primitive application and returns a boolean\n+ indicating whether the corresponding output value(s) can be saved as a\n+ residual (or instead must be recomputed in the (co)tangent computation if\n+ needed).\nReturns:\nA function (callable) with the same input/output behavior as ``fun`` but\n@@ -3155,6 +3155,9 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\n... return lambda x: f1(jax.checkpoint(f2)(x))\n...\n\"\"\"\n+ if config.jax_new_checkpoint and not concrete:\n+ return new_checkpoint(fun, prevent_cse=prevent_cse, policy=policy)\n+\n@wraps(fun)\n@api_boundary\ndef remat_f(*args, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -875,12 +875,12 @@ config.define_bool_state(\ndefault=(lib.version >= (0, 3, 6)),\nhelp=('Enables using optimization-barrier op for lowering remat.'))\n-# TODO(mattjj): remove after May 19 2022, NeurIPS submission deadline\n+# TODO(mattjj): set default to True, then remove\nconfig.define_bool_state(\n- name='after_neurips',\n- default=True,\n+ name='jax_new_checkpoint',\n+ default=False,\nupgrade=True,\n- help='Gate changes until after NeurIPS 2022 deadline.')\n+ help='Whether to use the new jax.checkpoint implementation.')\n# TODO(b/205307544): Remove flag once coordination service has rolled out.\nconfig.define_bool_state(\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/conditionals.py", "new_path": "jax/_src/lax/control_flow/conditionals.py", "diff": "@@ -593,8 +593,6 @@ def _ordered_unique(xs):\ndef _cond_dce_rule(used_outputs: List[bool], eqn: core.JaxprEqn,\n) -> Tuple[List[bool], core.JaxprEqn]:\n- if not config.after_neurips:\n- return [True] * len(eqn.params['jaxpr'].in_avals), eqn\nclosed_branches = eqn.params['branches']\nbranches = [closed_jaxpr.jaxpr for closed_jaxpr in closed_branches]\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow/loops.py", "new_path": "jax/_src/lax/control_flow/loops.py", "diff": "@@ -781,8 +781,6 @@ def _scan_padding_rule(in_avals, out_avals, *args, jaxpr, **params):\ndef _scan_dce_rule(used_outputs: List[bool], eqn: core.JaxprEqn\n) -> Tuple[List[bool], core.JaxprEqn]:\n- if not config.after_neurips:\n- return [True] * len(eqn.params['jaxpr'].in_avals), eqn\njaxpr = eqn.params['jaxpr']\nnum_consts, num_carry = eqn.params['num_consts'], eqn.params['num_carry']\nnum_xs = len(jaxpr.in_avals) - num_consts - num_carry\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -515,6 +515,7 @@ from jax.experimental import pjit\nfrom jax.interpreters import ad, xla, batching, pxla\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import mlir\n+from jax._src import ad_checkpoint\nfrom jax._src import dispatch\nfrom jax._src import pretty_printer as pp\nfrom jax._src import source_info_util\n@@ -1675,6 +1676,16 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\nout_axis_resources=(eqn.params[\"out_axis_resources\"] +\n(pjit.REPLICATED, pjit.REPLICATED)),\n)))\n+ elif eqn.primitive is ad_checkpoint.remat_p:\n+ jaxpr_ = cast(core.Jaxpr, eqn.params[\"jaxpr\"])\n+ eqns.append(\n+ eqn.replace(\n+ invars=eqn.invars + [input_token_var, input_itoken_var],\n+ outvars=eqn.outvars + [output_token_var, output_itoken_var],\n+ params=dict(\n+ eqn.params,\n+ jaxpr=_rewrite_jaxpr(jaxpr_, True, True),\n+ )))\nelse:\nraise NotImplementedError(f\"outfeed rewrite {eqn.primitive}\")\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -16,8 +16,7 @@ import contextlib\nimport functools\nfrom functools import partial\nimport itertools as it\n-from typing import Any, Callable, Dict, List, Tuple, Optional\n-\n+from typing import Any, Callable, Dict, List, Tuple, Sequence, Optional, Union\nimport jax\nfrom jax.interpreters import partial_eval as pe\nfrom jax.config import config\n@@ -642,8 +641,8 @@ def remat_transpose(params, call_jaxpr, primals_in, cotangents_in,\ncotangent_in_avals, reduce_axes):\nunknowns = map(is_undefined_primal, primals_in)\nprimal_jaxpr, tangent_jaxpr, _, _ = \\\n- pe.partial_eval_jaxpr_nounits(_close_jaxpr(call_jaxpr), unknowns=unknowns,\n- instantiate=True) # type: ignore\n+ pe.partial_eval_jaxpr_nounits(pe.close_jaxpr(call_jaxpr),\n+ unknowns=unknowns, instantiate=True) # type: ignore\nargs, in_tree = tree_flatten((primals_in, cotangents_in))\ntranspose = lu.hashable_partial(lu.wrap_init(_remat_transpose), primal_jaxpr,\ntangent_jaxpr, reduce_axes)\n@@ -665,10 +664,6 @@ def _remat_transpose(primal_jaxpr, tangent_jaxpr, reduce_axes,\nassert next(cotangents_out, None) is None\nreturn outs\n-@weakref_lru_cache\n-def _close_jaxpr(jaxpr: core.Jaxpr) -> core.ClosedJaxpr:\n- return core.ClosedJaxpr(jaxpr, [])\n-\n@lu.transformation_with_aux\ndef nonzero_outputs(*args, **kwargs):\nresults = yield args, kwargs\n@@ -717,9 +712,12 @@ def map_transpose(primitive, params, call_jaxpr, args, ct, _, reduce_axes):\nreturn tuple(arg_cts)\n-def jvp_jaxpr(jaxpr, nonzeros, instantiate):\n- inst = tuple(instantiate) if isinstance(instantiate, list) else instantiate\n- return _jvp_jaxpr(jaxpr, tuple(nonzeros), inst)\n+def jvp_jaxpr(jaxpr: core.ClosedJaxpr, nonzeros: Sequence[bool],\n+ instantiate: Union[bool, Sequence[bool]]\n+ ) -> Tuple[core.ClosedJaxpr, List[bool]]:\n+ if type(instantiate) is bool:\n+ instantiate = (instantiate,) * len(jaxpr.out_avals)\n+ return _jvp_jaxpr(jaxpr, tuple(nonzeros), tuple(instantiate))\n@weakref_lru_cache\ndef _jvp_jaxpr(jaxpr, nonzeros, instantiate):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1509,6 +1509,10 @@ def dce_jaxpr_closed_call_rule(used_outputs: List[bool], eqn: JaxprEqn\nreturn used_inputs, new_eqn\ndce_rules[core.closed_call_p] = dce_jaxpr_closed_call_rule\n+@weakref_lru_cache\n+def close_jaxpr(jaxpr: Jaxpr) -> ClosedJaxpr:\n+ return ClosedJaxpr(jaxpr, ())\n+\ndef move_binders_to_front(closed_jaxpr: ClosedJaxpr, to_move: Sequence[bool]\n) -> ClosedJaxpr:\n\"\"\"Reorder `invars` by moving those indicated in `to_move` to the front.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4784,6 +4784,16 @@ class RematTest(jtu.JaxTestCase):\nf_vjp(1.)[0].block_until_ready()\nself.assertEqual(count[0], 1) # fwd execute_trivial, backward_pass on bwd\n+ @unittest.skipIf(not config.jax_new_checkpoint, \"old remat recompiles here\")\n+ def test_fwd_caching(self):\n+ # see above test also\n+ identity = jax.checkpoint(jax.jit(lambda x: 2 * x))\n+ with jtu.count_jit_and_pmap_compiles() as count: # noqa: F841\n+ for _ in range(20):\n+ y, _ = jax.vjp(identity, 1.)\n+ y.block_until_ready()\n+ self.assertEqual(count[0], 1)\n+\n@parameterized.named_parameters(\n{\"testcase_name\": f\"{suffix}\", \"remat\": remat}\nfor suffix, remat in [\n@@ -4851,7 +4861,6 @@ class RematTest(jtu.JaxTestCase):\njtu.check_grads(api.jit(f), (jnp.ones((5, 5)),), order=2,\nmodes=['fwd', 'rev'])\n- @unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\ndef test_remat_of_scan_policy(self):\nsave_cos = lambda prim, *_, **__: str(prim) == 'cos'\nto_scan = lambda c, _: (jnp.sin(c), jnp.sin(c))\n@@ -4864,7 +4873,6 @@ class RematTest(jtu.JaxTestCase):\nself.assertEqual(jaxpr_text.count(' sin '), 0)\nself.assertEqual(jaxpr_text.count(' cos '), 0)\n- @unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\ndef test_remat_of_scan_funky_custom_jvp(self):\ndef scan_apply(f, x):\ny, _ = lax.scan(lambda x, _: (f(x), None), x, None, length=1)\n@@ -4921,7 +4929,6 @@ class RematTest(jtu.JaxTestCase):\nself.assertEqual(jaxpr_text.count(' sin '), 2) # +1 b/c dce fixed point\nself.assertEqual(jaxpr_text.count(' cos '), 2)\n- @unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\ndef test_remat_of_scan_funky_custom_jvp2(self):\n# Like the above test but instead of using jit inside custom_jvp, use scan.\n@@ -5081,7 +5088,6 @@ class RematTest(jtu.JaxTestCase):\njtu.check_grads(api.jit(f), (jnp.ones((5, 5)),), order=2,\nmodes=['fwd', 'rev'])\n- @unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\ndef test_remat_of_cond_policy(self):\nsave_cos = lambda prim, *_, **__: str(prim) == 'cos'\nf = new_checkpoint(lambda x: lax.cond(x > 0, jnp.sin, lambda x: x, x),\n@@ -5093,7 +5099,6 @@ class RematTest(jtu.JaxTestCase):\nself.assertEqual(jaxpr_text.count(' sin '), 0)\nself.assertEqual(jaxpr_text.count(' cos '), 0)\n- @unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\ndef test_remat_of_cond_funky_custom_jvp(self):\ndef cond_apply(f, x):\nreturn lax.cond(x.sum() > -jnp.inf, f, lambda x: x, x)\n@@ -5149,7 +5154,6 @@ class RematTest(jtu.JaxTestCase):\nself.assertEqual(jaxpr_text.count(' sin '), 1)\nself.assertEqual(jaxpr_text.count(' cos '), 2)\n- @unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\ndef test_remat_of_cond_funky_custom_jvp2(self):\n# Like the above test but instead of using jit inside custom_jvp, use cond.\n@@ -5395,7 +5399,6 @@ class JaxprTest(jtu.JaxTestCase):\nself.assertLen(jaxpr.eqns, 0)\n-@unittest.skipIf(not config.after_neurips, \"skip until neurips deadline\")\nclass DCETest(jtu.JaxTestCase):\ndef assert_dce_result(self, jaxpr: core.Jaxpr, used_outputs: List[bool],\n@@ -5580,9 +5583,9 @@ class DCETest(jtu.JaxTestCase):\nreturn out, out\ndef f(xs):\n- return lax.scan(scanned_f, 1., xs)\n+ return lax.scan(scanned_f, jnp.array(1., 'float32'), xs)\n- xs = jnp.arange(10.)\n+ xs = jnp.arange(10., dtype='float32')\njaxpr = api.make_jaxpr(lambda xs: api.linearize(f, xs)[1])(xs).jaxpr\njaxpr, used_inputs = pe.dce_jaxpr(jaxpr, [True] * len(jaxpr.outvars))\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -1979,6 +1979,8 @@ class HostCallbackTapTest(jtu.JaxTestCase):\nfor grad_func in [\"grad\", \"value_and_grad\"]\nfor use_remat in [\"old\", \"new\", \"none\"]))\ndef test_tap_remat(self, use_result=False, grad_func=\"grad\", use_remat=\"new\"):\n+ if config.jax_new_checkpoint and use_remat == \"old\": raise SkipTest()\n+\ndef f(x):\nid_print_result = hcb.id_print(x, output_stream=testing_stream)\nif use_result:\n" } ]
Python
Apache License 2.0
google/jax
fix ad_checkpoint.checkpoint caching issue Also add a config option to switch to the new checkpoint implementation globally (default False for now), as the first step in replacing and then deleting old remat.
260,510
29.07.2022 20:10:01
25,200
11b206a18ac3c118602b815bd19a8aca93031849
Enable debugging primitives in `pjit` on CPU/GPU
[ { "change_type": "MODIFY", "old_path": "docs/debugging/print_breakpoint.md", "new_path": "docs/debugging/print_breakpoint.md", "diff": "@@ -128,8 +128,7 @@ jax.grad(f)(1.)\n#### Printing in other transformations\n-`jax.debug.print` also works in other transformations like `xmap` and `pjit`\n-(but `pjit` only works on TPUs for now).\n+`jax.debug.print` also works in other transformations like `xmap` and `pjit`.\n### More control with `jax.debug.callback`\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -1430,12 +1430,6 @@ def emit_python_callback(\n[xla.aval_to_xla_shapes(result_aval) for result_aval in result_avals])\noperand_shapes = util.flatten(\n[xla.aval_to_xla_shapes(op_aval) for op_aval in operand_avals])\n- if platform == \"tpu\":\n- if result_avals:\n- raise NotImplementedError(\n- \"Callback with return values not supported on TPU.\")\n- token = token or mhlo.CreateTokenOp(mhlo.TokenType.get()).result\n- send_channels = []\nif isinstance(ctx.module_context.axis_context,\n(SPMDAxisContext, ShardingContext)):\n# Apply maximal sharding so pjit only executes the callback on device 0.\n@@ -1445,6 +1439,12 @@ def emit_python_callback(\nsharding.tile_assignment_devices = [0]\nelse:\nsharding = None\n+ if platform == \"tpu\":\n+ if result_avals:\n+ raise NotImplementedError(\n+ \"Callback with return values not supported on TPU.\")\n+ token = token or mhlo.CreateTokenOp(mhlo.TokenType.get()).result\n+ send_channels = []\nfor operand, operand_aval in zip(operands, operand_avals):\nchannel = ctx.module_context.new_channel()\ntoken = send_to_host(channel, token, operand, operand_aval,\n@@ -1509,6 +1509,8 @@ def emit_python_callback(\nbackend_config=ir.StringAttr.get(str(callback_descriptor)),\noperand_layouts=None,\nresult_layouts=None)\n+ if sharding is not None:\n+ set_sharding(result, sharding)\nresults = [\nmhlo.GetTupleElementOp(result, i32_attr(i)).result\nfor i in range(len(result_types))\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -504,8 +504,6 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_unordered_print_with_pjit(self):\n- if jax.default_backend() != \"tpu\":\n- raise unittest.SkipTest(\"`pjit` doesn't work with CustomCall.\")\ndef f(x):\ndebug_print(\"{}\", x, ordered=False)\n@@ -532,8 +530,6 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_unordered_print_of_pjit_of_while(self):\n- if jax.default_backend() != \"tpu\":\n- raise unittest.SkipTest(\"`pjit` doesn't work with CustomCall.\")\ndef f(x):\ndef cond(carry):\n@@ -560,8 +556,6 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_unordered_print_of_pjit_of_xmap(self):\n- if jax.default_backend() != \"tpu\":\n- raise unittest.SkipTest(\"`pjit` doesn't work with CustomCall.\")\ndef f(x):\ndef foo(x):\n" } ]
Python
Apache License 2.0
google/jax
Enable debugging primitives in `pjit` on CPU/GPU PiperOrigin-RevId: 464208326
260,510
31.07.2022 21:22:53
25,200
c08b4ee6d9a13787c16bcf867d04e04d81fca063
Add jaxlib guards for debugging_primitives_test
[ { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -505,6 +505,9 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_unordered_print_with_pjit(self):\n+ if jax.default_backend() in {\"cpu\", \"gpu\"} and jaxlib.version < (0, 3, 16):\n+ raise unittest.SkipTest(\"`pjit` of callback not supported.\")\n+\ndef f(x):\ndebug_print(\"{}\", x, ordered=False)\nreturn x\n@@ -531,6 +534,10 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_unordered_print_of_pjit_of_while(self):\n+ if (jax.default_backend() in {\"cpu\", \"gpu\"}\n+ and jaxlib.xla_extension_version < 81):\n+ raise unittest.SkipTest(\"`pjit` of callback not supported.\")\n+\ndef f(x):\ndef cond(carry):\ni, *_ = carry\n@@ -557,6 +564,10 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\ndef test_unordered_print_of_pjit_of_xmap(self):\n+ if (jax.default_backend() in {\"cpu\", \"gpu\"}\n+ and jaxlib.xla_extension_version < 81):\n+ raise unittest.SkipTest(\"`pjit` of callback not supported.\")\n+\ndef f(x):\ndef foo(x):\nidx = lax.axis_index('foo')\n" } ]
Python
Apache License 2.0
google/jax
Add jaxlib guards for debugging_primitives_test PiperOrigin-RevId: 464453175
260,443
01.08.2022 15:48:40
25,200
1987ca73894d6d4c534a02fb4ef56c4c2adfb434
Add dtype arg to jnp.concatenate and update tests
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1650,9 +1650,9 @@ def tile(A, reps):\n[k for pair in zip(reps, A_shape) for k in pair])\nreturn reshape(result, tuple(np.multiply(A_shape, reps)))\n-def _concatenate_array(arr, axis: int):\n+def _concatenate_array(arr, axis: int, dtype=None):\n# Fast path for concatenation when the input is an ndarray rather than a list.\n- arr = asarray(arr)\n+ arr = asarray(arr, dtype=dtype)\nif arr.ndim == 0 or arr.shape[0] == 0:\nraise ValueError(\"Need at least one array to concatenate.\")\nif axis is None:\n@@ -1665,26 +1665,29 @@ def _concatenate_array(arr, axis: int):\nreturn lax.reshape(arr, shape, dimensions)\n@_wraps(np.concatenate)\n-def concatenate(arrays, axis: int = 0):\n+def concatenate(arrays, axis: int = 0, dtype=None):\nif isinstance(arrays, (np.ndarray, ndarray)):\n- return _concatenate_array(arrays, axis)\n+ return _concatenate_array(arrays, axis, dtype=dtype)\n_stackable(*arrays) or _check_arraylike(\"concatenate\", *arrays)\nif not len(arrays):\nraise ValueError(\"Need at least one array to concatenate.\")\nif ndim(arrays[0]) == 0:\nraise ValueError(\"Zero-dimensional arrays cannot be concatenated.\")\nif axis is None:\n- return concatenate([ravel(a) for a in arrays], axis=0)\n+ return concatenate([ravel(a) for a in arrays], axis=0, dtype=dtype)\nif hasattr(arrays[0], \"concatenate\"):\n- return arrays[0].concatenate(arrays[1:], axis)\n+ return arrays[0].concatenate(arrays[1:], axis, dtype=dtype)\naxis = _canonicalize_axis(axis, ndim(arrays[0]))\n+ if dtype is None:\narrays = _promote_dtypes(*arrays)\n+ else:\n+ arrays = [asarray(arr, dtype=dtype) for arr in arrays]\n# lax.concatenate can be slow to compile for wide concatenations, so form a\n# tree of concatenations as a workaround especially for op-by-op mode.\n# (https://github.com/google/jax/issues/653).\nk = 16\nif len(arrays) == 1:\n- return asarray(arrays[0])\n+ return asarray(arrays[0], dtype=dtype)\nelse:\nwhile len(arrays) > 1:\narrays = [lax.concatenate(arrays[i:i+k], axis)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/prng.py", "new_path": "jax/_src/prng.py", "diff": "@@ -203,7 +203,9 @@ class PRNGKeyArray:\nreshaped_keys = jnp.reshape(self._keys, (*newshape, -1), order=order)\nreturn PRNGKeyArray(self.impl, reshaped_keys)\n- def concatenate(self, key_arrs, axis):\n+ def concatenate(self, key_arrs, axis, dtype=None):\n+ if dtype is not None:\n+ raise ValueError('dtype argument not supported for concatenating PRNGKeyArray')\naxis = canonicalize_axis(axis, self.ndim)\narrs = [self._keys, *[k._keys for k in key_arrs]]\nreturn PRNGKeyArray(self.impl, jnp.concatenate(arrs, axis))\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -2299,15 +2299,16 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_axis={}_baseshape=[{}]_dtypes=[{}]\".format(\n- axis, \",\".join(str(d) for d in base_shape),\n+ {\"testcase_name\": \"_axis={}_dtype={}_baseshape=[{}]_argdtypes=[{}]\".format(\n+ axis, dtype and np.dtype(dtype).name, \",\".join(str(d) for d in base_shape),\n\",\".join(np.dtype(dtype).name for dtype in arg_dtypes)),\n- \"axis\": axis, \"base_shape\": base_shape, \"arg_dtypes\": arg_dtypes}\n+ \"axis\": axis, \"dtype\": dtype, \"base_shape\": base_shape, \"arg_dtypes\": arg_dtypes}\nfor num_arrs in [3]\nfor arg_dtypes in itertools.combinations_with_replacement(default_dtypes, num_arrs)\nfor base_shape in [(4,), (3, 4), (2, 3, 4)]\n+ for dtype in [None] + default_dtypes\nfor axis in range(-len(base_shape)+1, len(base_shape))))\n- def testConcatenate(self, axis, base_shape, arg_dtypes):\n+ def testConcatenate(self, axis, dtype, base_shape, arg_dtypes):\nrng = jtu.rand_default(self.rng())\nwrapped_axis = axis % len(base_shape)\nshapes = [base_shape[:wrapped_axis] + (size,) + base_shape[wrapped_axis+1:]\n@@ -2315,9 +2316,11 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ndef np_fun(*args):\nargs = [x if x.dtype != jnp.bfloat16 else x.astype(np.float32)\nfor x in args]\n- dtype = functools.reduce(jnp.promote_types, arg_dtypes)\n- return np.concatenate(args, axis=axis).astype(dtype)\n- jnp_fun = lambda *args: jnp.concatenate(args, axis=axis)\n+ if numpy_version < (1, 20):\n+ _dtype = dtype or jnp.result_type(*arg_dtypes)\n+ return np.concatenate(args, axis=axis).astype(_dtype)\n+ return np.concatenate(args, axis=axis, dtype=dtype, casting='unsafe')\n+ jnp_fun = lambda *args: jnp.concatenate(args, axis=axis, dtype=dtype)\ndef args_maker():\nreturn [rng(shape, dtype) for shape, dtype in zip(shapes, arg_dtypes)]\n" } ]
Python
Apache License 2.0
google/jax
Add dtype arg to jnp.concatenate and update tests
260,510
02.08.2022 10:24:26
25,200
9a989573fca14ec05ceda8b1fb78d4cba7dc56ae
Fix debugger scope issue
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugger/cli_debugger.py", "new_path": "jax/_src/debugger/cli_debugger.py", "diff": "@@ -44,8 +44,8 @@ class CliDebugger(cmd.Cmd):\ndef evaluate(self, expr):\nenv = {}\ncurr_frame = self.frames[self.frame_index]\n- env.update(curr_frame.locals)\nenv.update(curr_frame.globals)\n+ env.update(curr_frame.locals)\nreturn eval(expr, {}, env)\ndef default(self, arg):\n" }, { "change_type": "MODIFY", "old_path": "tests/debugger_test.py", "new_path": "tests/debugger_test.py", "diff": "@@ -325,5 +325,29 @@ class CliDebuggerTest(jtu.JaxTestCase):\nprint(expected)\nself.assertRegex(stdout.getvalue(), expected)\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_uses_local_before_global_scope(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"p foo\", \"c\"])\n+\n+ foo = \"outer\"\n+\n+ def f(x):\n+ foo = \"inner\"\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\n+ del foo\n+ return x\n+\n+ del foo\n+ expected = _format_multiline(r\"\"\"\n+ Entering jdb:\n+ \\(jdb\\) 'inner'\n+ \\(jdb\\) \"\"\")\n+ f(2.)\n+ jax.effects_barrier()\n+ print(stdout.getvalue())\n+ print(expected)\n+ self.assertRegex(stdout.getvalue(), expected)\n+\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Fix debugger scope issue
260,510
03.08.2022 10:51:29
25,200
8fa4f7f2666185138994c94aa26f2239554b8059
Fix issue where input/output tokens did not play nicely with donate_argnums
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -779,6 +779,9 @@ def lower_jaxpr_to_fun(\nif input_output_aliases:\ntoken_input_output_aliases = [None] * num_tokens\ninput_output_aliases = [*token_input_output_aliases, *input_output_aliases]\n+ # Update the existing aliases to account for the new output values\n+ input_output_aliases = [None if a is None else a + num_output_tokens +\n+ num_tokens for a in input_output_aliases]\nif arg_shardings:\ntoken_shardings = [None] * num_tokens\narg_shardings = [*token_shardings, *arg_shardings]\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -105,6 +105,19 @@ class DebugPrintTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_can_stage_out_debug_print_with_donate_argnums(self):\n+ if jax.default_backend() not in {\"gpu\", \"tpu\"}:\n+ raise unittest.SkipTest(\"Donate argnums not supported.\")\n+ def f(x, y):\n+ debug_print('x: {x}', x=x)\n+ return x + y\n+ f = jax.jit(f, donate_argnums=0)\n+ with capture_stdout() as output:\n+ f(2, 3)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"x: 2\\n\")\n+\n@jtu.skip_on_devices(*disabled_backends)\ndef test_can_stage_out_ordered_print(self):\n@jax.jit\n@@ -115,6 +128,33 @@ class DebugPrintTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertEqual(output(), \"x: 2\\n\")\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_can_stage_out_ordered_print_with_donate_argnums(self):\n+ if jax.default_backend() not in {\"gpu\", \"tpu\"}:\n+ raise unittest.SkipTest(\"Donate argnums not supported.\")\n+ def f(x, y):\n+ debug_print('x: {x}', x=x, ordered=True)\n+ return x + y\n+ f = jax.jit(f, donate_argnums=0)\n+ with capture_stdout() as output:\n+ f(2, 3)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"x: 2\\n\")\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_can_stage_out_prints_with_donate_argnums(self):\n+ if jax.default_backend() not in {\"gpu\", \"tpu\"}:\n+ raise unittest.SkipTest(\"Donate argnums not supported.\")\n+ def f(x, y):\n+ debug_print('x: {x}', x=x, ordered=True)\n+ debug_print('x: {x}', x=x)\n+ return x + y\n+ f = jax.jit(f, donate_argnums=0)\n+ with capture_stdout() as output:\n+ f(2, 3)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"x: 2\\nx: 2\\n\")\n+\n@jtu.skip_on_devices(*disabled_backends)\ndef test_can_double_stage_out_ordered_print(self):\n@jax.jit\n" } ]
Python
Apache License 2.0
google/jax
Fix issue where input/output tokens did not play nicely with donate_argnums PiperOrigin-RevId: 465094684
260,510
03.08.2022 11:02:32
25,200
375ef0bc63d6ca5c1a189a2650468e3ecf1f6aa4
Making sharding an arg to MHLO callback lowering
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugging.py", "new_path": "jax/_src/debugging.py", "diff": "@@ -27,6 +27,7 @@ from jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax._src.lax import control_flow as lcf\n+from jax._src.lib import xla_client as xc\nimport jax.numpy as jnp\nDebugEffect = enum.Enum('DebugEffect', ['PRINT', 'ORDERED_PRINT'])\n@@ -88,6 +89,16 @@ ad.primitive_transposes[debug_callback_p] = debug_callback_transpose_rule\ndef debug_callback_lowering(ctx, *args, effect, callback, **params):\n+ if isinstance(ctx.module_context.axis_context,\n+ (mlir.SPMDAxisContext, mlir.ShardingContext)):\n+ # Apply maximal sharding so pjit only executes the callback on device 0.\n+ sharding = xc.OpSharding()\n+ sharding.type = xc.OpSharding.Type.MAXIMAL\n+ sharding.tile_assignment_dimensions = [1]\n+ sharding.tile_assignment_devices = [0]\n+ else:\n+ sharding = None\n+\ndef _callback(*flat_args):\nreturn tuple(\ndebug_callback_p.impl(\n@@ -99,7 +110,8 @@ def debug_callback_lowering(ctx, *args, effect, callback, **params):\nctx.set_tokens_out(mlir.TokenSet({effect: (token,)}))\nelse:\nresult, token, keepalive = mlir.emit_python_callback(\n- ctx, _callback, None, list(args), ctx.avals_in, ctx.avals_out, True)\n+ ctx, _callback, None, list(args), ctx.avals_in, ctx.avals_out, True,\n+ sharding=sharding)\nctx.module_context.add_keepalive(keepalive)\nreturn result\nmlir.register_lowering(debug_callback_p, debug_callback_lowering,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -1173,10 +1173,19 @@ def _outside_call_lowering(\nresult_arrays = ()\nreturn result_arrays\n+ if isinstance(ctx.module_context.axis_context,\n+ (mlir.SPMDAxisContext, mlir.ShardingContext)):\n+ # Apply maximal sharding so pjit only executes the callback on device 0.\n+ sharding = xla_client.OpSharding()\n+ sharding.type = xla_client.OpSharding.Type.MAXIMAL\n+ sharding.tile_assignment_dimensions = [1]\n+ sharding.tile_assignment_devices = [0]\n+ else:\n+ sharding = None\nresults, next_token, keep_alive = mlir.emit_python_callback(ctx,\nwrapped_callback, current_token, callback_operands,\ncallback_operand_avals, callback_flat_results_aval, # type: ignore[arg-type]\n- has_side_effect=True)\n+ has_side_effect=True, sharding=sharding)\n_callback_handler_data.keep_alives.append(keep_alive)\n# We must put the two tokens at the end\nif identity:\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -1419,7 +1419,8 @@ def emit_python_callback(\nctx: LoweringRuleContext, callback, token: Optional[Any],\noperands: List[ir.Value], operand_avals: List[core.AbstractValue],\nresult_avals: List[core.AbstractValue],\n- has_side_effect: bool) -> Tuple[List[ir.Value], Any, Any]:\n+ has_side_effect: bool, *, sharding: Optional[xc.OpSharding] = None\n+ ) -> Tuple[List[ir.Value], Any, Any]:\n\"\"\"Creates an MHLO `CustomCallOp` that calls back to the provided function.\"\"\"\nplatform = ctx.module_context.platform\nif platform in {\"tpu\"} and jax._src.lib.version < (0, 3, 15):\n@@ -1433,15 +1434,6 @@ def emit_python_callback(\n[xla.aval_to_xla_shapes(result_aval) for result_aval in result_avals])\noperand_shapes = util.flatten(\n[xla.aval_to_xla_shapes(op_aval) for op_aval in operand_avals])\n- if isinstance(ctx.module_context.axis_context,\n- (SPMDAxisContext, ShardingContext)):\n- # Apply maximal sharding so pjit only executes the callback on device 0.\n- sharding = xc.OpSharding()\n- sharding.type = xc.OpSharding.Type.MAXIMAL\n- sharding.tile_assignment_dimensions = [1]\n- sharding.tile_assignment_devices = [0]\n- else:\n- sharding = None\nif platform == \"tpu\":\nif result_avals:\nraise NotImplementedError(\n" } ]
Python
Apache License 2.0
google/jax
Making sharding an arg to MHLO callback lowering
260,510
03.08.2022 19:03:41
25,200
5f618e706dccc5bb3869d2618c023eedf6eb273b
Throw error earlier for misformatted string in jax.debug.print
[ { "change_type": "MODIFY", "old_path": "jax/_src/debugging.py", "new_path": "jax/_src/debugging.py", "diff": "@@ -156,5 +156,6 @@ def debug_print(fmt: str, *args, ordered: bool = False, **kwargs) -> None:\nw.r.t. other ordered ``debug_print`` calls.\n**kwargs: Additional keyword arguments to be formatted.\n\"\"\"\n+ fmt.format(*args, **kwargs)\ndebug_callback(functools.partial(_format_print_callback, fmt), *args,\n**kwargs, ordered=ordered)\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -663,5 +663,26 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\noutput(), \"hello: 0\\nhello: 1\\nhello: 2\\n\"\n\"hello: 1\\nhello: 2\\n\")\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_incorrectly_formatted_string(self):\n+\n+ @jax.jit\n+ def f(x):\n+ debug_print(\"hello: {x}\", x)\n+ return x\n+\n+ with self.assertRaises(KeyError):\n+ f(jnp.arange(2))\n+ jax.effects_barrier()\n+\n+ @jax.jit\n+ def f(x):\n+ debug_print(\"hello: {}\", x=x)\n+ return x\n+\n+ with self.assertRaises(IndexError):\n+ f(jnp.arange(2))\n+ jax.effects_barrier()\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Throw error earlier for misformatted string in jax.debug.print
260,335
04.08.2022 08:22:20
25,200
7ed4fa550e8a1e6187070d4b4893c486ff1bdf63
in sharp bits notebook, add back iaml blog post link
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb", "new_path": "docs/notebooks/Common_Gotchas_in_JAX.ipynb", "diff": "\"source\": [\n\"*levskaya@ mattjj@*\\n\",\n\"\\n\",\n- \"When walking about the countryside of Italy, the people will not hesitate to tell you that __JAX__ has _\\\"una anima di pura programmazione funzionale\\\"_.\\n\",\n+ \"When walking about the countryside of Italy, the people will not hesitate to tell you that __JAX__ has [_\\\"una anima di pura programmazione funzionale\\\"_](https://www.sscardapane.it/iaml-backup/jax-intro/).\\n\",\n\"\\n\",\n\"__JAX__ is a language for __expressing__ and __composing__ __transformations__ of numerical programs. __JAX__ is also able to __compile__ numerical programs for CPU or accelerators (GPU/TPU). \\n\",\n\"JAX works great for many numerical and scientific programs, but __only if they are written with certain constraints__ that we describe below.\"\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/Common_Gotchas_in_JAX.md", "new_path": "docs/notebooks/Common_Gotchas_in_JAX.md", "diff": "@@ -22,7 +22,7 @@ kernelspec:\n*levskaya@ mattjj@*\n-When walking about the countryside of Italy, the people will not hesitate to tell you that __JAX__ has _\"una anima di pura programmazione funzionale\"_.\n+When walking about the countryside of Italy, the people will not hesitate to tell you that __JAX__ has [_\"una anima di pura programmazione funzionale\"_](https://www.sscardapane.it/iaml-backup/jax-intro/).\n__JAX__ is a language for __expressing__ and __composing__ __transformations__ of numerical programs. __JAX__ is also able to __compile__ numerical programs for CPU or accelerators (GPU/TPU).\nJAX works great for many numerical and scientific programs, but __only if they are written with certain constraints__ that we describe below.\n" } ]
Python
Apache License 2.0
google/jax
in sharp bits notebook, add back iaml blog post link
260,510
04.08.2022 13:23:02
25,200
c5d4eb54519d949ecbdbfc3c3c742426e22de064
Use XLA extension tokens instead of output tokens
[ { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -50,6 +50,7 @@ from jax._src.config import config, flags\nfrom jax._src.lib.mlir import ir\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\n+from jax._src.lib import xla_extension_version\nimport jax._src.util as util\nfrom jax._src.util import flatten, unflatten\nfrom etils import epath\n@@ -107,10 +108,14 @@ RuntimeToken = Any\nclass RuntimeTokenSet(threading.local):\ntokens: Dict[core.Effect, Tuple[RuntimeToken, Device]]\noutput_tokens: Dict[Device, RuntimeToken]\n+ output_runtime_tokens: Dict[Device, RuntimeToken]\ndef __init__(self):\nself.tokens = {}\n+ # TODO(sharadmv): remove redundant output token dictionary when minimum\n+ # jaxlib version is bumped to 0.3.16.\nself.output_tokens = {}\n+ self.output_runtime_tokens = {}\ndef get_token(self, eff: core.Effect, device: Device) -> RuntimeToken:\nif eff not in self.tokens:\n@@ -131,17 +136,22 @@ class RuntimeTokenSet(threading.local):\n# we'd need to store a set of output tokens.\nself.output_tokens[device] = token\n+ def set_output_runtime_token(self, device: Device, token: RuntimeToken):\n+ # TODO(sharadmv): remove this method when minimum jaxlib version is bumped\n+ self.output_runtime_tokens[device] = token\n+\ndef clear(self):\nself.tokens = {}\nself.output_tokens = {}\n+ self.output_runtime_tokens = {}\ndef block_until_ready(self):\n- for t, _ in self.tokens.values():\n- t[0].block_until_ready()\n- # TODO(sharadmv): use a runtime mechanism to block on computations instead\n- # of using output tokens.\n- for t in self.output_tokens.values():\n- t[0].block_until_ready()\n+ for token, _ in self.tokens.values():\n+ token[0].block_until_ready()\n+ for token in self.output_tokens.values():\n+ token[0].block_until_ready()\n+ for token in self.output_runtime_tokens.values():\n+ token.block_until_ready()\nruntime_tokens: RuntimeTokenSet = RuntimeTokenSet()\n@@ -703,10 +713,15 @@ def _add_tokens(has_unordered_effects: bool, ordered_effects: List[core.Effect],\ntokens = [runtime_tokens.get_token(eff, device) for eff in ordered_effects]\ntokens_flat = flatten(tokens)\ninput_bufs = [*tokens_flat, *input_bufs]\n- def _remove_tokens(output_bufs):\n- token_bufs, output_bufs = util.split_list(\n- output_bufs, [has_unordered_effects + len(ordered_effects)])\n+ def _remove_tokens(output_bufs, runtime_token):\n+ # TODO(sharadmv): simplify when minimum jaxlib version is bumped\n+ num_output_tokens = len(ordered_effects) + (xla_extension_version < 81 and\n+ has_unordered_effects)\n+ token_bufs, output_bufs = util.split_list(output_bufs, [num_output_tokens])\nif has_unordered_effects:\n+ if xla_extension_version >= 81:\n+ runtime_tokens.set_output_runtime_token(device, runtime_token)\n+ else:\noutput_token_buf, *token_bufs = token_bufs\nruntime_tokens.set_output_token(device, output_token_buf)\nfor eff, token_buf in zip(ordered_effects, token_bufs):\n@@ -727,13 +742,19 @@ def _execute_compiled(name: str, compiled: XlaExecutable,\nin_flat = flatten(device_put(x, device) for i, x in enumerate(args)\nif i in kept_var_idx)\nif has_unordered_effects or ordered_effects:\n- in_flat, token_handler = _add_tokens(has_unordered_effects, ordered_effects,\n- device, in_flat)\n+ in_flat, token_handler = _add_tokens(\n+ has_unordered_effects, ordered_effects, device, in_flat)\n+ if xla_extension_version >= 81:\n+ out_flat, runtime_token = compiled.execute_with_token(in_flat)\n+ else:\n+ out_flat = compiled.execute(in_flat)\n+ runtime_token = None\n+ else:\nout_flat = compiled.execute(in_flat)\ncheck_special(name, out_flat)\nout_bufs = unflatten(out_flat, output_buffer_counts)\nif ordered_effects or has_unordered_effects:\n- out_bufs = token_handler(out_bufs)\n+ out_bufs = token_handler(out_bufs, runtime_token)\nreturn result_handler(env, out_bufs)\n@@ -934,7 +955,10 @@ class XlaCompiledComputation(stages.XlaExecutable):\nhost_callbacks)\nbuffer_counts = [aval_to_num_buffers(aval) for aval in out_avals]\nif ordered_effects or has_unordered_effects:\n- num_output_tokens = len(ordered_effects) + has_unordered_effects\n+ num_output_tokens = len(ordered_effects)\n+ # TODO(sharadmv): remove check when minimum jaxlib version is bumped\n+ if xla_extension_version < 81:\n+ num_output_tokens += has_unordered_effects\nbuffer_counts = ([1] * num_output_tokens) + buffer_counts\nexecute = _execute_compiled if nreps == 1 else _execute_replicated\nunsafe_call = partial(execute, name, compiled, input_handler, buffer_counts, # type: ignore # noqa: F811\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -41,6 +41,7 @@ from jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.lib.mlir.dialects import func as func_dialect\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\n+from jax._src.lib import xla_extension_version\nfrom jax._src import source_info_util\nimport jax._src.util as util\nfrom jax.config import config\n@@ -615,7 +616,8 @@ def lower_jaxpr_to_module(\nlower_jaxpr_to_fun(\nctx, \"main\", jaxpr, ordered_effects, public=True, create_tokens=True,\nreplace_tokens_with_dummy=True,\n- num_output_tokens=1 if unordered_effects else 0,\n+ num_output_tokens=(\n+ 1 if (unordered_effects and xla_extension_version < 81) else 0),\nreplicated_args=replicated_args,\narg_shardings=arg_shardings, result_shardings=result_shardings,\ninput_output_aliases=input_output_aliases)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1707,12 +1707,26 @@ class ExecuteReplicated:\n@profiler.annotate_function\ndef __call__(self, *args):\ninput_bufs = self.in_handler(args)\n- out_bufs = self.xla_executable.execute_sharded_on_local_devices(input_bufs)\nif self.has_unordered_effects:\n+ # TODO(sharadmv): simplify this logic when minimum jaxlib version is\n+ # bumped\n+ if xla_extension_version >= 81:\n+ out_bufs, runtime_tokens = (\n+ self.xla_executable.execute_sharded_on_local_devices_with_tokens(\n+ input_bufs))\n+ for device, token in zip(\n+ self.xla_executable.local_devices(), runtime_tokens):\n+ dispatch.runtime_tokens.set_output_runtime_token(device, token)\n+ else:\n+ out_bufs = self.xla_executable.execute_sharded_on_local_devices(\n+ input_bufs)\ntoken_bufs, *out_bufs = out_bufs\nfor i, device in enumerate(self.xla_executable.local_devices()):\ntoken = (token_bufs[i],)\ndispatch.runtime_tokens.set_output_token(device, token)\n+ else:\n+ out_bufs = self.xla_executable.execute_sharded_on_local_devices(\n+ input_bufs)\nif dispatch.needs_check_special():\nfor bufs in out_bufs:\ndispatch.check_special(\"parallel computation\", bufs)\n" }, { "change_type": "MODIFY", "old_path": "tests/debugging_primitives_test.py", "new_path": "tests/debugging_primitives_test.py", "diff": "@@ -29,6 +29,7 @@ from jax.config import config\nfrom jax.experimental import maps\nfrom jax.experimental import pjit\nfrom jax._src import debugging\n+from jax._src import dispatch\nfrom jax._src import lib as jaxlib\nfrom jax._src import test_util as jtu\nimport jax.numpy as jnp\n@@ -67,6 +68,10 @@ if jaxlib.version < (0, 3, 15):\nclass DebugPrintTest(jtu.JaxTestCase):\n+ def tearDown(self):\n+ super().tearDown()\n+ dispatch.runtime_tokens.clear()\n+\n@jtu.skip_on_devices(*disabled_backends)\ndef test_simple_debug_print_works_in_eager_mode(self):\ndef f(x):\n" }, { "change_type": "MODIFY", "old_path": "tests/jaxpr_effects_test.py", "new_path": "tests/jaxpr_effects_test.py", "diff": "@@ -456,10 +456,14 @@ class EffectfulJaxprLoweringTest(jtu.JaxTestCase):\n# First output should be output token\nresult_types = mhlo.body.operations[0].type.results\n+ if jaxlib.version < (0, 3, 16):\nself.assertLen(list(result_types), 2)\nself.assertEqual(str(result_types[0]), 'tensor<0xi1>')\nself.assertLen(list(result_types), 2)\nself.assertEqual(str(result_types[1]), 'tensor<f32>')\n+ else:\n+ self.assertLen(list(result_types), 1)\n+ self.assertEqual(str(result_types[0]), 'tensor<f32>')\ndef test_lowered_jaxpr_with_ordered_effects_takes_in_dummy_inputs(self):\n@jax.jit\n" } ]
Python
Apache License 2.0
google/jax
Use XLA extension tokens instead of output tokens PiperOrigin-RevId: 465389589