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,447 | 04.08.2022 14:29:34 | 25,200 | 07da50232371837a80c27a7b69f801290d6e99f4 | [sparse] Enable batch mode of COO matmat from cusparse kernels. | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusparse.cc",
"new_path": "jaxlib/cuda/cusparse.cc",
"diff": "@@ -487,18 +487,38 @@ std::pair<size_t, py::bytes> BuildCooMatmatDescriptor(\ncusparseDnMatDescr_t mat_b = 0;\ncusparseDnMatDescr_t mat_c = 0;\n+ // All three matrices A, B, and C must have the same batch_count.\n+ // TODO(tianjianlu): use batch_count from matrix descriptor.\n+ int batch_count = 1;\n+\n+ // Three batch modes are supported, C_i = A_i B, C_i = A B_i, and\n+ // Ci = A_i B_i, where `i` denotes the batch dimension. Use `batch_stride` to\n+ // trigger individual mode, e.g., using `batch_stride_B = 0` in C_i = A_i B.\n+ int batch_stride_A = A.rows * A.cols;\n+ int batch_stride_B = B.rows * B.cols;\n+ int batch_stride_C = C.rows * C.cols;\n+\n// bufferSize does not reference these pointers, but does error on NULL.\nint val = 0;\nvoid* empty = &val;\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(\ncusparseCreateCoo(&mat_a, A.rows, A.cols, A.nnz, empty, empty, empty,\nA.index_type, CUSPARSE_INDEX_BASE_ZERO, A.value_type)));\n+ JAX_THROW_IF_ERROR(JAX_AS_STATUS(\n+ cusparseCooSetStridedBatch(\n+ mat_a, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_A)));\nJAX_THROW_IF_ERROR(\nJAX_AS_STATUS(cusparseCreateDnMat(&mat_b, B.rows, B.cols, /*ld=*/B.cols,\nempty, B.type, CUSPARSE_ORDER_ROW)));\n+ JAX_THROW_IF_ERROR(JAX_AS_STATUS(\n+ cusparseDnMatSetStridedBatch(\n+ mat_b, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_B)));\nJAX_THROW_IF_ERROR(\nJAX_AS_STATUS(cusparseCreateDnMat(&mat_c, C.rows, C.cols, /*ld=*/C.cols,\nempty, C.type, CUSPARSE_ORDER_ROW)));\n+ JAX_THROW_IF_ERROR(JAX_AS_STATUS(\n+ cusparseDnMatSetStridedBatch(\n+ mat_c, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_C)));\nsize_t buffer_size;\nCudaConst alpha = CudaOne(C.type);\nCudaConst beta = CudaZero(C.type);\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusparse_kernels.cc",
"new_path": "jaxlib/cuda/cusparse_kernels.cc",
"diff": "@@ -509,15 +509,35 @@ static absl::Status CooMatmat_(cudaStream_t stream, void** buffers,\ncusparseDnMatDescr_t mat_b = 0;\ncusparseDnMatDescr_t mat_c = 0;\n+ // All three matrices A, B, and C must have the same batch_count.\n+ // TODO(tianjianlu): use batch_count from matrix descriptor.\n+ int batch_count = 1;\n+\n+ // Three batch modes are supported, C_i = A_i B, C_i = A B_i, and\n+ // Ci = A_i B_i, where `i` denotes the batch dimension. Use `batch_stride` to\n+ // trigger individual mode, e.g., using `batch_stride_B = 0` in C_i = A_i B.\n+ int batch_stride_A = d.A.rows * d.A.cols;\n+ int batch_stride_B = d.B.rows * d.B.cols;\n+ int batch_stride_C = d.C.rows * d.C.cols;\n+\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseCreateCoo(\n&mat_a, d.A.rows, d.A.cols, d.A.nnz, coo_row_ind, coo_col_ind, coo_values,\nd.A.index_type, CUSPARSE_INDEX_BASE_ZERO, d.A.value_type)));\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(\n+ cusparseCooSetStridedBatch(\n+ mat_a, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_A)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseCreateDnMat(\n&mat_b, d.B.rows, d.B.cols,\n/*ld=*/d.B.cols, Bbuf, d.B.type, CUSPARSE_ORDER_ROW)));\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(\n+ cusparseDnMatSetStridedBatch(\n+ mat_b, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_B)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseCreateDnMat(\n&mat_c, d.C.rows, d.C.cols,\n/*ld=*/d.C.cols, Cbuf, d.C.type, CUSPARSE_ORDER_ROW)));\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(\n+ cusparseDnMatSetStridedBatch(\n+ mat_c, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_C)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseSpMM(\nhandle.get(), d.op_A, /*opB=*/CUSPARSE_OPERATION_NON_TRANSPOSE, &alpha,\nmat_a, mat_b, &beta, mat_c, d.C.type, CUSPARSE_SPMM_ALG_DEFAULT, buf)));\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Enable batch mode of COO matmat from cusparse kernels.
PiperOrigin-RevId: 465405490 |
260,335 | 05.08.2022 07:37:55 | 25,200 | fbf6aa2a16d06caab6285b810fd09750a86cd068 | small tweaks for bint ad | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -1461,7 +1461,7 @@ 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- pe.padding_rules[prim] = lambda _, __, x, **kw: [prim.bind(x, **kw)]\n+ pe.def_trivial_padding(prim)\nreturn prim\nstandard_unop = partial(unop, _identity)\n_attrgetter = lambda name: lambda x, **kwargs: getattr(x, name)\n@@ -1536,7 +1536,7 @@ 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- pe.padding_rules[prim] = lambda _, __, *xs, **kw: [prim.bind(*xs, **kw)]\n+ pe.def_trivial_padding(prim)\nreturn prim\nstandard_naryop = partial(naryop, _input_dtype)\n@@ -2015,7 +2015,7 @@ integer_pow_p = standard_primitive(\n_attrgetter('shape'), _integer_pow_dtype_rule, 'integer_pow')\nbatching.defvectorized(integer_pow_p)\nad.defjvp(integer_pow_p, _integer_pow_jvp)\n-pe.padding_rules[integer_pow_p] = lambda _, __, x, y: [integer_pow_p.bind(x, y=y)]\n+pe.def_trivial_padding(integer_pow_p)\ndef _integer_pow(x, *, y):\n# This should be kept in sync with the jax2tf translation rule.\n@@ -2927,7 +2927,7 @@ if jax._src.lib.mlir_api_version < 30:\nelse:\nmlir.register_lowering(\nclamp_p, partial(_nary_lower_mhlo, mhlo.ClampOp))\n-pe.padding_rules[clamp_p] = lambda _, __, a, x, b: [clamp(a, x, b)]\n+pe.def_trivial_padding(clamp_p)\ndef _concatenate_shape_rule(*operands, **kwargs):\ndimension = kwargs.pop('dimension')\n@@ -3285,16 +3285,17 @@ 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_lower(ctx, x, *, permutation):\n+ aval_out, = ctx.avals_out\n+ return mhlo.TransposeOp(x, mlir.dense_int_elements(permutation)).results\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-\n-def _transpose_lower(ctx, x, *, permutation):\n- aval_out, = ctx.avals_out\n- return mhlo.TransposeOp(x, mlir.dense_int_elements(permutation)).results\nmlir.register_lowering(transpose_p, _transpose_lower)\n+pe.def_trivial_padding(transpose_p)\ndef _select_shape_rule(which, *cases):\n@@ -3386,7 +3387,6 @@ def _select_jvp(primals, tangents):\nout_dot = select_n(which, *case_tangents)\nreturn out, out_dot\n-\ndef _select_mhlo_lowering(ctx, which, *cases):\nwhich_aval = ctx.avals_in[0]\nif which_aval.dtype == np.dtype(np.bool_):\n@@ -3420,6 +3420,7 @@ ad.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\nmlir.register_lowering(select_n_p, _select_mhlo_lowering)\n+pe.def_trivial_padding(select_n_p)\ndef _reduce_shape_rule(*avals, computation, jaxpr, consts, dimensions):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1417,7 +1417,7 @@ class DShapedArray(UnshapedArray):\nshape: Tuple[AxisSize, ...] # noqa: F821\narray_abstraction_level: int = 3\n- def __init__(self, shape, dtype, weak_type):\n+ def __init__(self, shape, dtype, weak_type=False):\nself.shape = shape\nself.dtype = dtype\nself.weak_type = weak_type\n@@ -1474,6 +1474,7 @@ class DConcreteArray(DShapedArray):\npytype_aval_mappings: Dict[type, Callable[[Any], AbstractValue]] = {}\n+# TODO(mattjj): remove this, replace with arrays of bints\nclass AbstractBInt(AbstractValue):\n__slots__ = ['bound']\nbound: int\n@@ -1486,11 +1487,16 @@ class AbstractBInt(AbstractValue):\nreturn type(other) is AbstractBInt and self.bound == other.bound\ndef __hash__(self) -> int:\nreturn hash((type(self), self.bound))\n+ def at_least_vspace(self):\n+ return self # should return float0 array\n+ def join(self, other):\n+ return self\nclass BInt:\nval: Any # Union[int, Array]\nbound: int\ndef __init__(self, val, bound):\n+ assert 0 <= val <= bound\nself.val = val\nself.bound = bound\ndef __repr__(self) -> str:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -2497,6 +2497,18 @@ def _substitute_axis_sizes(env: Dict, aval: AbstractValue) -> AbstractValue:\npadding_rules: Dict[Primitive, Callable] = {}\n+def def_trivial_padding(prim: Primitive) -> None:\n+ if prim.multiple_results:\n+ padding_rules[prim] = partial(_trivial_padding_rule_multi, prim)\n+ else:\n+ padding_rules[prim] = partial(_trivial_padding_rule, prim)\n+\n+def _trivial_padding_rule(prim, _, __, *args, **params):\n+ return [prim.bind(*args, **params)]\n+\n+def _trivial_padding_rule_multi(prim, _, __, *args, **params):\n+ return prim.bind(*args, **params)\n+\ndef call_padding_rule(prim, in_avals, out_avals, *args, call_jaxpr, **params):\nif call_jaxpr.constvars: raise NotImplementedError\npadded_jaxpr, padded_consts = pad_jaxpr(call_jaxpr, ())\n"
}
] | Python | Apache License 2.0 | google/jax | small tweaks for bint ad |
260,335 | 05.08.2022 09:12:32 | 25,200 | f159cdfec96b77d29108204f9aa87b9535b972a3 | add trivial convert_element_type padding rule | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -2343,6 +2343,7 @@ ad.primitive_transposes[convert_element_type_p] = _convert_element_type_transpos\nbatching.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+pe.def_trivial_padding(convert_element_type_p)\n# TODO(mattjj): un-comment the next line (see #9456)\n# core.pp_eqn_rules[convert_element_type_p] = _convert_elt_type_pp_rule\n"
}
] | Python | Apache License 2.0 | google/jax | add trivial convert_element_type padding rule |
260,510 | 05.08.2022 10:58:48 | 25,200 | 89150eef1d114ff3015e238b138d4687c6523427 | Enable debug callbacks in checkpoint | [
{
"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, Sequence, Union, Any\n+from typing import Callable, Optional, List, Tuple, Sequence, Set, Union, Any\nimport types\nimport jax\n@@ -419,11 +419,16 @@ def remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\nreturn out_primals, out_tangents\nad.primitive_jvps[remat_p] = remat_jvp\n+remat_allowed_effects: Set[core.Effect] = set()\n+\ndef remat_partial_eval(trace, *tracers, jaxpr, **params):\nassert not jaxpr.constvars\n- if jaxpr.effects:\n+ disallowed_effects = {eff for eff in jaxpr.effects\n+ if eff not in remat_allowed_effects}\n+ if disallowed_effects:\nraise NotImplementedError(\n- 'Effects not supported in partial-eval of `checkpoint`/`remat`.')\n+ 'Effects not supported in partial-eval of `checkpoint`/`remat`: '\n+ f'{disallowed_effects}')\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/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "@@ -21,11 +21,13 @@ from typing import Callable, Any\nfrom jax import core\nfrom jax import tree_util\nfrom jax import lax\n+from jax._src import ad_checkpoint\nfrom jax._src import lib as jaxlib\nfrom jax._src import util\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\n+from jax.interpreters import partial_eval as pe\nfrom jax._src.lax import control_flow as lcf\nfrom jax._src.lib import xla_client as xc\nimport jax.numpy as jnp\n@@ -37,6 +39,8 @@ mlir.lowerable_effects.add(DebugEffect.PRINT)\nmlir.lowerable_effects.add(DebugEffect.ORDERED_PRINT)\nlcf.allowed_effects.add(DebugEffect.PRINT)\nlcf.allowed_effects.add(DebugEffect.ORDERED_PRINT)\n+ad_checkpoint.remat_allowed_effects.add(DebugEffect.PRINT)\n+ad_checkpoint.remat_allowed_effects.add(DebugEffect.ORDERED_PRINT)\n# `debug_callback_p` is the main primitive for staging out Python callbacks.\ndebug_callback_p = core.Primitive('debug_callback')\n@@ -122,6 +126,37 @@ if jaxlib.version >= (0, 3, 15):\nmlir.register_lowering(\ndebug_callback_p, debug_callback_lowering, platform=\"tpu\")\n+def _debug_callback_partial_eval_custom(saveable, unks_in, inst_in, eqn):\n+ # The default behavior for effectful primitives is to not stage them if\n+ # possible. For debug callback, we actually want it to be staged to\n+ # provide more information to the user. This rule bypasses partial_eval's\n+ # regular behavior to do that. Specifically, we will stage the callback\n+ # if:\n+ # 1) the policy says debug_callbacks are not saveable\n+ # 2) the policy says debug_callbacks are saveable BUT all of the input\n+ # values are instantiated.\n+ # The purpose is to call back with as much information as possible while\n+ # avoiding unnecessarily staging out other values.\n+ if any(unks_in):\n+ # The usual case (if we have any unknowns, we need to stage it out)\n+ res = [v for v, inst in zip(eqn.invars, inst_in) if not inst]\n+ return None, eqn, [], [], res\n+ if saveable(debug_callback_p, *[v.aval for v in eqn.invars], **eqn.params):\n+ # The policy is telling us we can save the debug callback.\n+ if all(inst_in):\n+ # If all of the inputs are instantiated, we also stage out the\n+ # debug_callback.\n+ return eqn, eqn, [], [], []\n+ else:\n+ # If any are not instantiated, we don't do any extra staging to avoid\n+ # affecting the computation.\n+ return eqn, None, [], [], []\n+ # If we can't save the debug callback (thanks to the policy) we listen to\n+ # the policy and stage out the debug callback.\n+ return eqn, eqn, [], [], []\n+pe.partial_eval_jaxpr_custom_rules[debug_callback_p] = (\n+ _debug_callback_partial_eval_custom)\n+\ndef debug_callback(callback: Callable[..., Any], *args: Any,\nordered: bool = False, **kwargs: Any):\n\"\"\"Calls a stageable Python callback.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1300,7 +1300,9 @@ def _partial_eval_jaxpr_custom_cached(\nmap(partial(write, True, True), eqn.outvars)\nelse:\nknown_eqns.append(eqn)\n- if saveable(eqn.primitive, *[x.aval for x in eqn.invars], **eqn.params):\n+ # If it's an effectful primitive, we always to run and avoid staging it.\n+ if eqn.effects or saveable(\n+ eqn.primitive, *[x.aval for x in eqn.invars], **eqn.params):\nmap(partial(write, False, False), eqn.outvars)\nelse:\ninputs = map(ensure_instantiated, inst_in, eqn.invars)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/debugging_primitives_test.py",
"new_path": "tests/debugging_primitives_test.py",
"diff": "@@ -28,6 +28,7 @@ from jax import lax\nfrom jax.config import config\nfrom jax.experimental import maps\nfrom jax.experimental import pjit\n+from jax._src import ad_checkpoint\nfrom jax._src import debugging\nfrom jax._src import dispatch\nfrom jax._src import lib as jaxlib\n@@ -329,6 +330,78 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\n# output data-dependence.\nself.assertEqual(output(), \"\")\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=\"_ordered\" if ordered else \"\", ordered=ordered)\n+ for ordered in [False, True]))\n+ def test_remat_of_debug_print(self, ordered):\n+ def f_(x):\n+ y = ad_checkpoint.checkpoint_name(x + 1., \"y\")\n+ z = ad_checkpoint.checkpoint_name(y * 2., \"z\")\n+ debug_print('y: {}, z: {}', y, z, ordered=ordered)\n+ return ad_checkpoint.checkpoint_name(jnp.exp(z), \"w\")\n+\n+ # Policy that saves everything so the debug callback will be saved\n+ f = ad_checkpoint.checkpoint(f_, policy=ad_checkpoint.everything_saveable)\n+\n+ with capture_stdout() as output:\n+ jax.grad(f)(2.)\n+ jax.effects_barrier()\n+ # We expect the print to happen once since it gets saved and isn't\n+ # rematerialized.\n+ self.assertEqual(output(), \"y: 3.0, z: 6.0\\n\")\n+\n+ # Policy that saves nothing so everything gets rematerialized, including the\n+ # debug callback\n+ f = ad_checkpoint.checkpoint(f_, policy=ad_checkpoint.nothing_saveable)\n+\n+ with capture_stdout() as output:\n+ jax.grad(f)(2.)\n+ jax.effects_barrier()\n+ # We expect the print to happen twice since it is rematerialized.\n+ self.assertEqual(output(), \"y: 3.0, z: 6.0\\n\" * 2)\n+\n+ # Policy that does not save `z` so we will need to rematerialize the print\n+ f = ad_checkpoint.checkpoint(\n+ f_, policy=ad_checkpoint.save_any_names_but_these(\"z\"))\n+\n+ with capture_stdout() as output:\n+ jax.grad(f)(2.)\n+ jax.effects_barrier()\n+ # We expect the print to happen twice since it is rematerialized.\n+ self.assertEqual(output(), \"y: 3.0, z: 6.0\\n\" * 2)\n+\n+ def save_everything_but_these_names(*names_not_to_save):\n+ names_not_to_save = frozenset(names_not_to_save)\n+ def policy(prim, *_, **params):\n+ if prim is ad_checkpoint.name_p:\n+ return params['name'] not in names_not_to_save\n+ return True # Save everything else\n+ return policy\n+\n+ # Policy that saves everything but `y`\n+ f = ad_checkpoint.checkpoint(\n+ f_, policy=save_everything_but_these_names(\"y\"))\n+\n+ with capture_stdout() as output:\n+ jax.grad(f)(2.)\n+ jax.effects_barrier()\n+ # We expect the print to happen once because `y` is not rematerialized and\n+ # we won't do extra materialization.\n+ self.assertEqual(output(), \"y: 3.0, z: 6.0\\n\")\n+\n+ # Policy that saves everything but `y` and `z`\n+ f = ad_checkpoint.checkpoint(\n+ f_, policy=save_everything_but_these_names(\"y\", \"z\"))\n+\n+ with capture_stdout() as output:\n+ jax.grad(f)(2.)\n+ jax.effects_barrier()\n+ # We expect the print to happen twice because both `y` and `z` have been\n+ # rematerialized and we don't have to do any extra rematerialization to\n+ # print.\n+ self.assertEqual(output(), \"y: 3.0, z: 6.0\\n\" * 2)\n+\n+\nclass DebugPrintControlFlowTest(jtu.JaxTestCase):\ndef _assertLinesEqual(self, text1, text2):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/jaxpr_effects_test.py",
"new_path": "tests/jaxpr_effects_test.py",
"diff": "@@ -20,7 +20,6 @@ from absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\nimport jax.numpy as jnp\n-from jax import ad_checkpoint\nfrom jax import core\nfrom jax import lax\nfrom jax import linear_util as lu\n@@ -29,6 +28,7 @@ from jax.interpreters import ad\nfrom jax.experimental import maps\nfrom jax.experimental import pjit\nfrom jax.interpreters import mlir\n+from jax._src import ad_checkpoint\nfrom jax._src import lib as jaxlib\nfrom jax._src import dispatch\nfrom jax._src import test_util as jtu\n@@ -64,6 +64,8 @@ lcf.allowed_effects.add('while')\nlcf.allowed_effects.add('while1')\nlcf.allowed_effects.add('while2')\n+ad_checkpoint.remat_allowed_effects.add('remat')\n+\n# TODO(sharadmv): remove jaxlib guards for TPU tests when jaxlib minimum\n# version is >= 0.3.15\ndisabled_backends = []\n@@ -220,6 +222,14 @@ class HigherOrderPrimitiveTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(NotImplementedError, \"Effects not supported\"):\njax.make_jaxpr(lambda x: jax.linearize(f, x)[1](x))(2.)\n+ def test_new_remat_allows_certain_effects(self):\n+ @ad_checkpoint.checkpoint\n+ def f(x):\n+ x, = effect_p.bind(x, effect='remat')\n+ return x\n+ jaxpr = jax.make_jaxpr(f)(2.)\n+ self.assertSetEqual(jaxpr.effects, {\"remat\"})\n+\ndef test_custom_jvp_primitive_inherits_effects(self):\n@jax.custom_jvp\n"
}
] | Python | Apache License 2.0 | google/jax | Enable debug callbacks in checkpoint
PiperOrigin-RevId: 465601044 |
260,287 | 05.08.2022 18:27:11 | 0 | bfb0814ce864f6d15c54ed70689ce5a95fbf149a | Remove experimental warning from xmap
It doesn't have bugs, or at least not noticeably more than the rest of our code :) | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/maps.py",
"new_path": "jax/experimental/maps.py",
"diff": "@@ -457,7 +457,6 @@ def xmap(fun: Callable,\nspecified. This is in line with the current multi-host :py:func:`pmap`\nprogramming model.\n\"\"\"\n- warn(\"xmap is an experimental feature and probably has bugs!\")\n_check_callable(fun)\nif isinstance(in_axes, list) and not _is_axes_leaf(in_axes):\n"
}
] | Python | Apache License 2.0 | google/jax | Remove experimental warning from xmap
It doesn't have bugs, or at least not noticeably more than the rest of our code :) |
260,342 | 05.08.2022 10:15:26 | 25,200 | 736bed0344dd75b73b9ba588fe7dcfdbe0beddff | Fix jax numpy norm bug where passing ord=inf always returns one | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/linalg.py",
"new_path": "jax/_src/numpy/linalg.py",
"diff": "@@ -469,6 +469,13 @@ def norm(x, ord=None, axis : Union[None, Tuple[int, ...], int] = None,\n# code has slightly different type promotion semantics, so we need a\n# special case too.\nreturn jnp.sum(jnp.abs(x), axis=axis, keepdims=keepdims)\n+ elif isinstance(ord, str):\n+ msg = f\"Invalid order '{ord}' for vector norm.\"\n+ if ord == \"inf\":\n+ msg += \"Use 'jax.numpy.inf' instead.\"\n+ if ord == \"-inf\":\n+ msg += \"Use '-jax.numpy.inf' instead.\"\n+ raise ValueError(msg)\nelse:\nabs_x = jnp.abs(x)\nord = lax_internal._const(abs_x, ord)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/linalg_test.py",
"new_path": "tests/linalg_test.py",
"diff": "@@ -539,6 +539,11 @@ class NumpyLinalgTest(jtu.JaxTestCase):\ntol=1e-3)\nself._CompileAndCheck(jnp_fn, args_maker)\n+ def testStringInfNorm(self):\n+ err, msg = ValueError, r\"Invalid order 'inf' for vector norm.\"\n+ with self.assertRaisesRegex(err, msg):\n+ jnp.linalg.norm(jnp.array([1.0, 2.0, 3.0]), ord=\"inf\")\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_n={}_full_matrices={}_compute_uv={}_hermitian={}\".format(\njtu.format_shape_dtype_string(b + (m, n), dtype), full_matrices,\n"
}
] | Python | Apache License 2.0 | google/jax | Fix jax numpy norm bug where passing ord=inf always returns one |
260,510 | 05.08.2022 16:45:56 | 25,200 | 7c49f9a6035293436ab83c1aacc74515ed46a3be | Error in debug print if unused arguments are provided | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "\"\"\"Module for JAX debugging primitives and related functionality.\"\"\"\nimport enum\nimport functools\n+import string\nimport sys\nfrom typing import Callable, Any\n@@ -188,6 +189,22 @@ def debug_callback(callback: Callable[..., Any], *args: Any,\nreturn debug_callback_p.bind(*flat_args, callback=callback, effect=effect,\nin_tree=in_tree)\n+class _DebugPrintFormatChecker(string.Formatter):\n+\n+ def check_unused_args(self, used_args, args, kwargs):\n+ unused_args = [arg for i, arg in enumerate(args) if i not in used_args]\n+ unused_kwargs = [k for k in kwargs if k not in used_args]\n+ if unused_args:\n+ raise ValueError(\n+ f\"Unused positional arguments to `jax.debug.print`: {unused_args}\")\n+ if unused_kwargs:\n+ raise ValueError(\n+ f\"Unused keyword arguments to `jax.debug.print`: {unused_kwargs}. \"\n+ \"You may be passing an f-string (i.e, `f\\\"{x}\\\"`) into \"\n+ \"`jax.debug.print` and instead should pass in a regular string.\")\n+\n+formatter = _DebugPrintFormatChecker()\n+\ndef _format_print_callback(fmt: str, *args, **kwargs):\nsys.stdout.write(fmt.format(*args, **kwargs) + \"\\n\")\n@@ -203,6 +220,8 @@ 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)\n+ # Check that we provide the correct arguments to be formatted\n+ formatter.format(fmt, *args, **kwargs)\n+\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": "@@ -762,5 +762,38 @@ class DebugPrintParallelTest(jtu.JaxTestCase):\nf(jnp.arange(2))\njax.effects_barrier()\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_format_string_errors_with_unused_args(self):\n+\n+ @jax.jit\n+ def f(x):\n+ debug_print(\"hello: {x}\", x=x, y=x)\n+ return x\n+\n+ with self.assertRaisesRegex(ValueError, \"Unused keyword arguments\"):\n+ f(jnp.arange(2))\n+ jax.effects_barrier()\n+\n+ @jax.jit\n+ def g(x):\n+ debug_print(\"hello\", x)\n+ return x\n+\n+ with self.assertRaisesRegex(ValueError, \"Unused positional arguments\"):\n+ g(jnp.arange(2))\n+ jax.effects_barrier()\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_accidental_fstring(self):\n+\n+ @jax.jit\n+ def f(x):\n+ debug_print(f\"hello: {x}\", x=x)\n+ return x\n+\n+ with self.assertRaisesRegex(ValueError, \"You may be passing an f-string\"):\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 | Error in debug print if unused arguments are provided |
260,335 | 05.08.2022 20:55:27 | 25,200 | e2c1df6c5175b7cf29eaadc5a020f256a160e9a7 | add api_boundary, fix flax failure with new-remat-by-default | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -96,6 +96,7 @@ checkpoint_policies = types.SimpleNamespace(\n### Main API\n+@api_boundary\ndef checkpoint(fun: Callable, *, prevent_cse: bool = True,\npolicy: Optional[Callable[..., bool]] = None,\nstatic_argnums: Union[int, Tuple[int, ...]] = (),\n"
}
] | Python | Apache License 2.0 | google/jax | add api_boundary, fix flax failure with new-remat-by-default |
260,335 | 05.08.2022 22:18:53 | 25,200 | 81b6263ed0a9e0f5d97c97a93d58be0aea1f0dd3 | Rolling forward after test failures caused roll-back (from use of np.empty). | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -2938,7 +2938,7 @@ def _valid_jaxtype(arg):\ntry:\nxla.abstractify(arg) # faster than core.get_aval\nexcept TypeError:\n- return False\n+ return core.valid_jaxtype(arg)\nelse:\nreturn True\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/api_util.py",
"new_path": "jax/_src/api_util.py",
"diff": "@@ -435,7 +435,11 @@ def _shaped_abstractify_slow(x):\nweak_type = getattr(x, 'weak_type', False)\nnamed_shape = getattr(x, 'named_shape', {})\n- return core.ShapedArray(np.shape(x), _dtype(x), weak_type=weak_type,\n+ if hasattr(x, 'dtype'):\n+ dtype = dtypes.canonicalize_dtype(x.dtype)\n+ else:\n+ dtype = dtypes.result_type(x) # TODO(frostig,mattjj): why this case?\n+ return core.ShapedArray(np.shape(x), dtype, weak_type=weak_type,\nnamed_shape=named_shape)\n# TODO(mattjj,yashkatariya): replace xla.abstractify with this, same behavior\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -651,6 +651,8 @@ def array_result_handler(sticky_device: Optional[Device],\nif aval.dtype == dtypes.float0:\nreturn lambda _, __: np.zeros(aval.shape, dtypes.float0)\naval = core.raise_to_shaped(aval)\n+ if type(aval.dtype) in core.custom_eltypes:\n+ return aval.dtype.result_handler(sticky_device, aval)\nhandler = lambda _, b: _maybe_create_array_from_da(b, aval, sticky_device)\nhandler.args = aval, sticky_device # for C++ dispatch path in api.py\nreturn handler\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dtypes.py",
"new_path": "jax/_src/dtypes.py",
"diff": "@@ -25,6 +25,7 @@ from typing import Any, Dict, List\nimport numpy as np\n+import jax\nfrom jax._src.config import flags, config\nfrom jax._src.lib import xla_client\n@@ -85,6 +86,8 @@ def _to_complex_dtype(dtype):\n@functools.lru_cache(maxsize=None)\ndef _canonicalize_dtype(x64_enabled, dtype):\n\"\"\"Convert from a dtype to a canonical dtype based on config.x64_enabled.\"\"\"\n+ if type(dtype) in jax.core.custom_eltypes:\n+ return dtype\ntry:\ndtype = np.dtype(dtype)\nexcept TypeError as e:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/loops.py",
"new_path": "jax/_src/lax/control_flow/loops.py",
"diff": "@@ -29,11 +29,13 @@ from jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n+import jax._src.pretty_printer as pp\nfrom jax.tree_util import (tree_flatten, tree_unflatten, treedef_is_leaf,\ntree_map)\nfrom jax._src import ad_checkpoint\nfrom jax._src import ad_util\nfrom jax._src import api\n+from jax._src import api_util\nfrom jax._src import dtypes\nfrom jax._src import source_info_util\nfrom jax._src import util\n@@ -232,9 +234,8 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\nstacked_y = tree_map(stack, *maybe_reversed(ys))\nreturn carry, stacked_y\n- x_shapes = [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(ShapedArray, x_shapes, x_dtypes))\n+ xs_avals = [core.raise_to_shaped(core.get_aval(x)) for x in xs_flat]\n+ x_avals = [core.mapped_aval(length, 0, aval) for aval in xs_avals]\ndef _create_jaxpr(init):\ninit_flat, init_tree = tree_flatten(init)\n@@ -242,7 +243,7 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\ncarry_avals = tuple(_map(_abstractify, init_flat))\njaxpr, consts, out_tree = _initial_style_jaxpr(\n- f, in_tree, carry_avals + x_avals, \"scan\")\n+ f, in_tree, (*carry_avals, *x_avals), \"scan\")\nout_tree_children = out_tree.children()\nif len(out_tree_children) != 2:\nmsg = \"scan body output must be a pair, got {}.\"\n@@ -414,7 +415,7 @@ def _index_array(i, aval, x):\nreturn slicing.index_in_dim(x, i, keepdims=False)\ndef _empty_array(sz, aval):\n- return lax.full((sz,) + aval.shape, 0, aval.dtype)\n+ return lax.broadcast(lax.empty(aval.dtype), (sz, *aval.shape))\ndef _update_array(i, aval, xs, x):\nreturn slicing.dynamic_update_index_in_dim(xs, x, i, 0)\n@@ -968,6 +969,28 @@ def _scan_typecheck(bind_time, *in_atoms, reverse, length, num_consts, num_carry\nf'called with sequence of type\\n{_avals_short(x_avals)}')\nreturn [*init_avals, *y_avals], jaxpr.effects\n+def _scan_pp_rule(eqn, context, settings):\n+ printed_params = dict(eqn.params)\n+ del printed_params['linear']\n+ if eqn.params['num_consts'] + eqn.params['num_carry'] == len(eqn.invars):\n+ del printed_params['length']\n+ if printed_params['unroll'] == 1:\n+ del printed_params['unroll']\n+ if printed_params['num_carry'] == 0:\n+ del printed_params['num_carry']\n+ if printed_params['num_consts'] == 0:\n+ del printed_params['num_consts']\n+ if not printed_params['reverse']:\n+ del printed_params['reverse']\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+\n+\ndef scan_bind(*args, **params):\nif config.jax_enable_checks:\navals = _map(core.get_aval, args)\n@@ -992,6 +1015,8 @@ core.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\npe.dce_rules[scan_p] = _scan_dce_rule\n+# TODO(mattjj,frostig): un-comment this pp rule\n+# core.pp_eqn_rules[scan_p] = _scan_pp_rule\n### while_loop\n@@ -1380,45 +1405,6 @@ def _while_transpose_error(*_, **kwargs):\n\"lax.while_loop or lax.fori_loop. \"\n\"Try using lax.scan instead.\")\n-while_p = core.AxisPrimitive('while')\n-while_p.multiple_results = True\n-while_p.def_impl(partial(xla.apply_primitive, while_p))\n-while_p.def_effectful_abstract_eval(_while_loop_abstract_eval)\n-ad.primitive_jvps[while_p] = _while_loop_jvp\n-pe.custom_partial_eval_rules[while_p] = _while_partial_eval\n-xla.register_initial_style_primitive(while_p)\n-ad.primitive_transposes[while_p] = _while_transpose_error\n-batching.axis_primitive_batchers[while_p] = _while_loop_batching_rule\n-pe.partial_eval_jaxpr_custom_rules[while_p] = _while_partial_eval_custom\n-\n-\n-def _pred_bcast_select_mhlo(\n- pred_aval: core.ShapedArray, pred: ir.Value, xs: Sequence[ir.Value],\n- ys: Sequence[ir.Value], x_y_aval: core.AbstractValue) -> Sequence[ir.Value]:\n- if x_y_aval is core.abstract_token:\n- x, = xs\n- y, = ys\n- return [mhlo.AfterAllOp(mlir.aval_to_ir_type(x_y_aval), [x, y]).result]\n- else:\n- assert isinstance(x_y_aval, core.ShapedArray), x_y_aval\n- x, = xs\n- y, = ys\n- assert x.type == y.type, (x.type, y.type)\n- assert (pred_aval.shape == x_y_aval.shape[:len(pred_aval.shape)]), (\n- pred_aval.shape, x_y_aval)\n- bcast_pred = mhlo.BroadcastInDimOp(\n- mlir.aval_to_ir_type(x_y_aval.update(dtype=np.dtype(np.bool_))),\n- pred, mlir.dense_int_elements(list(range(len(pred_aval.shape))))).result\n- return mhlo.SelectOp(bcast_pred, x, y).results\n-\n-\n-def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\n- body_nconsts):\n- pred_aval = cond_jaxpr.out_avals[0]\n- batched = bool(pred_aval.shape)\n- cond_ordered_effects = [eff for eff in cond_jaxpr.effects if eff in\n- core.ordered_effects]\n- if cond_ordered_effects:\n# For a while loop with ordered effects in the cond, we need a special\n# lowering. Fundamentally, we'd like to rewrite a while loop that looks like\n# this:\n@@ -1445,6 +1431,13 @@ def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\n# token, x = body(token, x)\n# token, pred = cond(token, x)\n# ```\n+def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\n+ body_nconsts):\n+ pred_aval = cond_jaxpr.out_avals[0]\n+ batched = bool(pred_aval.shape)\n+ cond_ordered_effects = [eff for eff in cond_jaxpr.effects if eff in\n+ core.ordered_effects]\n+ if cond_ordered_effects:\ndef cond(args):\nreturn core.eval_jaxpr(cond_jaxpr.jaxpr, cond_jaxpr.consts, *args)[0]\ndef body(args):\n@@ -1544,7 +1537,47 @@ def _while_lowering(ctx, *args, cond_jaxpr, body_jaxpr, cond_nconsts,\nctx.set_tokens_out(mlir.TokenSet(zip(body_effects, tokens)))\nreturn z\n+def _while_typecheck(*in_atoms, cond_jaxpr, body_jaxpr, cond_nconsts,\n+ body_nconsts):\n+ # TODO(frostig,mattjj): check cond_jaxpr, body_jaxpr types\n+ joined_effects = core.join_effects(cond_jaxpr.effects, body_jaxpr.effects)\n+ if joined_effects - allowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `while`: {joined_effects - allowed_effects}')\n+ return body_jaxpr.out_avals, joined_effects\n+\n+while_p = core.AxisPrimitive('while')\n+while_p.multiple_results = True\n+while_p.def_impl(partial(xla.apply_primitive, while_p))\n+while_p.def_effectful_abstract_eval(_while_loop_abstract_eval)\n+ad.primitive_jvps[while_p] = _while_loop_jvp\n+pe.custom_partial_eval_rules[while_p] = _while_partial_eval\n+xla.register_initial_style_primitive(while_p)\n+ad.primitive_transposes[while_p] = _while_transpose_error\n+batching.axis_primitive_batchers[while_p] = _while_loop_batching_rule\n+pe.partial_eval_jaxpr_custom_rules[while_p] = _while_partial_eval_custom\nmlir.register_lowering(while_p, _while_lowering)\n+core.custom_typechecks[while_p] = _while_typecheck\n+\n+\n+def _pred_bcast_select_mhlo(\n+ pred_aval: core.ShapedArray, pred: ir.Value, xs: Sequence[ir.Value],\n+ ys: Sequence[ir.Value], x_y_aval: core.AbstractValue) -> Sequence[ir.Value]:\n+ if x_y_aval is core.abstract_token:\n+ x, = xs\n+ y, = ys\n+ return [mhlo.AfterAllOp(mlir.aval_to_ir_type(x_y_aval), [x, y]).result]\n+ else:\n+ assert isinstance(x_y_aval, core.ShapedArray), x_y_aval\n+ x, = xs\n+ y, = ys\n+ assert x.type == y.type, (x.type, y.type)\n+ assert (pred_aval.shape == x_y_aval.shape[:len(pred_aval.shape)]), (\n+ pred_aval.shape, x_y_aval)\n+ bcast_pred = mhlo.BroadcastInDimOp(\n+ mlir.aval_to_ir_type(x_y_aval.update(dtype=np.dtype(np.bool_))),\n+ pred, mlir.dense_int_elements(list(range(len(pred_aval.shape))))).result\n+ return mhlo.SelectOp(bcast_pred, x, y).results\n### fori_loop\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -2808,6 +2808,10 @@ def _broadcast_in_dim_partial_eval(\ndef _broadcast_in_dim_lower(ctx, x, *dyn_shape, shape, broadcast_dimensions):\naval_out, = ctx.avals_out\n+ if type(aval_out.dtype) in core.custom_eltypes:\n+ return aval_out.dtype.broadcast_in_dim_mlir(\n+ ctx, x, *dyn_shape, shape=shape,\n+ broadcast_dimensions=broadcast_dimensions)\nif dyn_shape:\nshape = _merge_dyn_shape(shape, dyn_shape)\nreturn mhlo.DynamicBroadcastInDimOp(\n@@ -3288,6 +3292,8 @@ def _transpose_batch_rule(batched_args, batch_dims, *, permutation):\ndef _transpose_lower(ctx, x, *, permutation):\naval_out, = ctx.avals_out\n+ if type(aval_out.dtype) in core.custom_eltypes:\n+ return aval_out.dtype.transpose_mlir(ctx, x, permutation=permutation)\nreturn mhlo.TransposeOp(x, mlir.dense_int_elements(permutation)).results\ntranspose_p = standard_primitive(_transpose_shape_rule, _input_dtype,\n@@ -4532,6 +4538,8 @@ def _check_same_dtypes(name, ignore_fp_precision, *ttypes):\n\"\"\"Check that dtypes agree, possibly ignoring float precision.\"\"\"\n# the `ignore_fp_precision` flag exists because the XLA shape inference logic\n# allows mixed floating point precision, but the HLO verifier often rejects it\n+ if any(type(t) in core.custom_eltypes for t in ttypes):\n+ return # TODO(mattjj,frostig): do some checking, friend\ntypes = map(np.dtype, ttypes) # canonicalize\nif ignore_fp_precision:\ntypes = [\n@@ -4691,3 +4699,14 @@ def _check_user_dtype_supported(dtype, fun_name=None):\nfun_name = f\"requested in {fun_name}\" if fun_name else \"\"\ntruncated_dtype = dtypes.canonicalize_dtype(dtype).name\nwarnings.warn(msg.format(dtype, fun_name , truncated_dtype), stacklevel=3)\n+\n+\n+def empty(eltype):\n+ return empty_p.bind(eltype=eltype)\n+empty_p = core.Primitive('empty')\n+empty_p.def_abstract_eval(lambda *, eltype: core.ShapedArray((), eltype))\n+def _empty_lower(ctx, *, eltype):\n+ if type(eltype) in core.custom_eltypes:\n+ return eltype.empty_mlir(ctx)\n+ return mlir.ir_constants(np.zeros((), np.dtype(eltype)))\n+mlir.register_lowering(empty_p, _empty_lower)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/slicing.py",
"new_path": "jax/_src/lax/slicing.py",
"diff": "@@ -897,6 +897,9 @@ 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+ aval_out, = ctx.avals_out\n+ if type(aval_out.dtype) in core.custom_eltypes:\n+ return aval_out.dtype.dynamic_slice_mlir(ctx, x, start_indices, slice_sizes)\nreturn mhlo.DynamicSliceOp(x, start_indices,\nmlir.dense_int_elements(slice_sizes)).results\n@@ -993,6 +996,9 @@ batching.primitive_batchers[dynamic_update_slice_p] = \\\ndef _dynamic_update_slice_lower(ctx, x, update, *start_indices):\naval_out, = ctx.avals_out\n+ if type(aval_out.dtype) in core.custom_eltypes:\n+ return aval_out.dtype.dynamic_update_slice_mlir(\n+ ctx, x, update, *start_indices)\nreturn mhlo.DynamicUpdateSliceOp(mlir.aval_to_ir_type(aval_out), x, update,\nstart_indices).results\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1132,7 +1132,7 @@ def lattice_join(x: Optional[AbstractValue],\n# For use in typing annotations to denote either a Tracer or a `valid_jaxtype`.\nValue = Any\n-def valid_jaxtype(x):\n+def valid_jaxtype(x) -> bool:\ntry:\nconcrete_aval(x)\nexcept TypeError:\n@@ -1187,16 +1187,25 @@ def concrete_or_error(force: Any, val: Any, context=\"\"):\nreturn force(val)\n-def _short_dtype_name(dtype):\n+# TODO(frostig,mattjj): achieve this w/ a protocol instead of registry?\n+custom_eltypes: Set[Any] = set()\n+\n+def _short_dtype_name(dtype) -> str:\n+ if type(dtype) in custom_eltypes:\n+ return str(dtype)\n+ else:\nreturn (dtype.name.replace('float', 'f').replace('uint' , 'u')\n.replace('int' , 'i').replace('complex', 'c'))\n+def _dtype_object(dtype):\n+ return dtype if type(dtype) in custom_eltypes else np.dtype(dtype)\n+\nclass UnshapedArray(AbstractValue):\n__slots__ = ['dtype', 'weak_type']\narray_abstraction_level = 4\ndef __init__(self, dtype, weak_type=False):\n- self.dtype = np.dtype(dtype)\n+ self.dtype = _dtype_object(dtype)\nself.weak_type = weak_type\ndef update(self, dtype=None, weak_type=None):\n@@ -1264,7 +1273,7 @@ class ShapedArray(UnshapedArray):\ndef __init__(self, shape, dtype, weak_type=False, named_shape=None):\nself.shape = canonicalize_shape(shape)\n- self.dtype = np.dtype(dtype)\n+ self.dtype = _dtype_object(dtype)\nself.weak_type = weak_type\nself.named_shape = {} if named_shape is None else dict(named_shape)\n@@ -1885,6 +1894,9 @@ class NamedShape:\nreturn total\ndef __str__(self):\n+ # TODO(mattjj,frostig): revise not to miss commas\n+ if not self.__named:\n+ return str(self.__positional)\nreturn (f\"({', '.join(map(str, self.__positional))}{', ' if self.__named else ''}\"\nf\"{', '.join(f'{k}={v}' for k, v in self.__named.items())})\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1791,6 +1791,15 @@ def _broadcast_in_dim(operand, *, shape, broadcast_dimensions,\ntf_impl_with_avals[lax.broadcast_in_dim_p] = _broadcast_in_dim\n+def _empty(*, eltype):\n+ if type(eltype) in core.custom_eltypes:\n+ raise NotImplementedError # TODO(frostig,mattjj): jax2tf handlers\n+ return tf.constant(np.array(0, dtype=eltype))\n+\n+\n+tf_impl[lax_internal.empty_p] = _empty\n+\n+\ndef _reshape(operand, *, new_sizes, dimensions):\nif dimensions is None:\ndimensions = tf.range(tf.rank(operand))\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": "@@ -917,7 +917,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4)))\nwith self.assertRaisesRegex(TypeError,\n- \"Argument 'b' of type <class 'jax.experimental.jax2tf.shape_poly._DimPolynomial'> is not a valid JAX type\"):\n+ \"Argument 'b' .*DimPoly.*not a valid JAX type\"):\njax2tf.convert(lambda x: jnp.prod(x.shape),\npolymorphic_shapes=[\"(b, 4)\"])(np.ones((3, 4)))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -129,6 +129,8 @@ def dtype_to_ir_type(dtype: Union[np.dtype, np.generic]) -> ir.Type:\ndef _array_ir_types(aval: Union[core.ShapedArray, core.DShapedArray]\n) -> Sequence[ir.Type]:\n+ if type(aval.dtype) in core.custom_eltypes:\n+ return aval.dtype.aval_to_ir_types(aval)\nreturn (ir.RankedTensorType.get(aval.shape, dtype_to_ir_type(aval.dtype)),)\ndef _dynamic_array_ir_types(aval: core.ShapedArray) -> Sequence[ir.Type]:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.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-\n+from __future__ import annotations\nimport collections\nfrom functools import partial\nimport itertools\nimport operator\n+import types\nimport unittest\nfrom unittest import SkipTest\n+from typing import Tuple\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n@@ -33,13 +35,17 @@ from jax.test_util import check_grads\nfrom jax import tree_util\nimport jax.util\n+from jax.interpreters import xla\n+from jax.interpreters import mlir\n+from jax.interpreters import batching\n+from jax._src.lib.mlir.dialects import mhlo\n+from jax._src import dispatch\nfrom jax._src import dtypes\nfrom jax._src import test_util as jtu\nfrom jax._src import lax_reference\nfrom jax._src.util import prod\nfrom jax._src.lax import lax as lax_internal\n-\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -2970,5 +2976,288 @@ class LaxNamedShapeTest(jtu.JaxTestCase):\n(out,), _ = lax.psum_p.abstract_eval(aval1, axes=('i',), axis_index_groups=None)\nself.assertEqual(out, expected)\n+\n+class FooTy:\n+ name = 'foo'\n+ def __hash__(self) -> int:\n+ return hash(FooTy)\n+ def __eq__(self, other) -> bool:\n+ return type(other) is FooTy\n+ def __repr__(self) -> str:\n+ return self.name\n+ __str__ = __repr__\n+\n+ # handlers\n+\n+ @staticmethod\n+ def aval_to_ir_types(aval):\n+ aval2 = core.ShapedArray((*aval.shape, 2), jnp.dtype('uint32'))\n+ return mlir.aval_to_ir_types(aval2)\n+\n+ @staticmethod\n+ def result_handler(sticky_device, aval):\n+ def handler(_, buf):\n+ buf.aval = core.ShapedArray(buf.shape, buf.dtype)\n+ return FooArray(aval.shape, buf)\n+ return handler\n+\n+ # eltype-polymorphic primitive lowering rules\n+\n+ @staticmethod\n+ def empty_mlir(ctx):\n+ return mlir.ir_constants(np.zeros((2,), dtype=np.dtype('uint32')))\n+\n+ @staticmethod\n+ def dynamic_slice_mlir(ctx, x, start_indices, slice_sizes):\n+ dtype = dtypes.canonicalize_dtype(np.dtype('int64'))\n+ start_indices = (*start_indices, mlir.ir_constant(np.array(0, dtype=dtype)))\n+ slice_sizes_ = mlir.dense_int_elements((*slice_sizes, 2))\n+ return mhlo.DynamicSliceOp(x, start_indices, slice_sizes_).results\n+\n+ @staticmethod\n+ def dynamic_update_slice_mlir(ctx, x, update, *start_indices):\n+ aval_out, = ctx.avals_out\n+ dtype = dtypes.canonicalize_dtype(np.dtype('int64'))\n+ start_indices = (*start_indices, mlir.ir_constant(np.array(0, dtype=dtype)))\n+ return mhlo.DynamicUpdateSliceOp(mlir.aval_to_ir_type(aval_out), x, update,\n+ start_indices).results\n+\n+ @staticmethod\n+ def broadcast_in_dim_mlir(ctx, x, *dyn_shape, shape, broadcast_dimensions):\n+ if dyn_shape: raise NotImplementedError\n+ aval_out, = ctx.avals_out\n+ broadcast_dimensions = [*broadcast_dimensions, aval_out.ndim]\n+ return mhlo.BroadcastInDimOp(\n+ mlir.aval_to_ir_type(aval_out), x,\n+ mlir.dense_int_elements(broadcast_dimensions)).results\n+\n+ @staticmethod\n+ def transpose_mlir(ctx, x, *, permutation):\n+ perm = [*permutation, len(permutation)]\n+ return mhlo.TransposeOp(x, mlir.dense_int_elements(perm)).results\n+\n+# primitives\n+\n+make_p = core.Primitive('make')\n+bake_p = core.Primitive('bake')\n+take_p = core.Primitive('take')\n+\n+def make(shape): return make_p.bind(shape=tuple(shape))\n+def bake(k): return bake_p.bind(k)\n+def take(k): return take_p.bind(k)\n+\n+@make_p.def_abstract_eval\n+def make_abstract_eval(*, shape):\n+ return core.ShapedArray(shape, FooTy())\n+\n+@bake_p.def_abstract_eval\n+def bake_abstract_eval(x):\n+ if type(x.dtype) != FooTy: raise TypeError\n+ return core.ShapedArray(tuple(reversed(x.shape)), FooTy())\n+\n+@take_p.def_abstract_eval\n+def take_abstract_eval(x):\n+ return core.ShapedArray(x.shape, jnp.dtype('float32'))\n+\n+# runtime ('outside jit') data types\n+\n+class FooArray:\n+ shape: Tuple[int, ...]\n+ data: jnp.ndarray\n+\n+ def __init__(self, shape, data):\n+ assert data.shape == (*shape, 2)\n+ self.shape = shape\n+ self.data = data\n+\n+ def __repr__(self) -> str:\n+ shape = ','.join(map(str, self.shape))\n+ return f'foo[{shape}] with value\\n{self.data}'\n+\n+ size = property(lambda self: self.data.size // 2)\n+ ndim = property(lambda self: self.data.ndim - 1)\n+\n+def device_put_foo_array(x: FooArray, device):\n+ return dispatch._device_put_array(x.data, device)\n+\n+def foo_array_constant_handler(x, c):\n+ return mlir._device_array_constant_handler(x.data, c)\n+\n+def make_lowering(*, shape):\n+ return jnp.zeros((*shape, 2), 'uint32')\n+\n+def bake_lowering(k):\n+ return k.T\n+\n+def take_lowering(k):\n+ return jnp.broadcast_to(jnp.float32(k.size), k.shape)\n+\n+\n+def bake_vmap(batched_args, batch_dims):\n+ xs, = batched_args\n+ bdim_in, = batch_dims\n+ ys = bake(xs)\n+ perm = list(reversed(range(xs.ndim)))\n+ bdim_out = perm[bdim_in]\n+ return ys, bdim_out\n+\n+\n+class CustomElementTypesTest(jtu.JaxTestCase):\n+\n+ def setUp(self):\n+ core.custom_eltypes.add(FooTy)\n+ core.pytype_aval_mappings[FooArray] = \\\n+ lambda x: core.ShapedArray(x.shape, FooTy())\n+ xla.canonicalize_dtype_handlers[FooArray] = lambda x: x\n+ xla.pytype_aval_mappings[FooArray] = \\\n+ lambda x: core.ShapedArray(x.shape, FooTy())\n+ dispatch.device_put_handlers[FooArray] = device_put_foo_array\n+ mlir._constant_handlers[FooArray] = foo_array_constant_handler\n+ mlir.register_lowering(make_p, mlir.lower_fun(make_lowering, False))\n+ mlir.register_lowering(bake_p, mlir.lower_fun(bake_lowering, False))\n+ mlir.register_lowering(take_p, mlir.lower_fun(take_lowering, False))\n+ batching.defvectorized(take_p)\n+ batching.primitive_batchers[bake_p] = bake_vmap\n+\n+ def tearDown(self):\n+ core.custom_eltypes.remove(FooTy)\n+ del core.pytype_aval_mappings[FooArray]\n+ del xla.canonicalize_dtype_handlers[FooArray]\n+ del xla.pytype_aval_mappings[FooArray]\n+ del dispatch.device_put_handlers[FooArray]\n+ del mlir._constant_handlers[FooArray]\n+ del mlir._lowerings[make_p]\n+ del mlir._lowerings[bake_p]\n+ del mlir._lowerings[take_p]\n+ del batching.primitive_batchers[take_p]\n+ del batching.primitive_batchers[bake_p]\n+\n+ def test_shaped_array_construction(self):\n+ aval = core.ShapedArray((), FooTy())\n+ self.assertEqual(aval.str_short(), 'foo[]')\n+ aval = core.ShapedArray((3, 4), FooTy())\n+ self.assertEqual(aval.str_short(), 'foo[3,4]')\n+\n+ def test_make_jaxpr_identity(self):\n+ x = types.SimpleNamespace(shape=(3,), dtype=FooTy())\n+ jaxpr = jax.make_jaxpr(lambda x: x)(x).jaxpr\n+ # { lambda ; a:foo[3]. let in (a,) }\n+ self.assertLen(jaxpr.invars, 1)\n+ a, = jaxpr.invars\n+ self.assertEqual(a.aval, core.ShapedArray((3,), FooTy()))\n+ self.assertLen(jaxpr.outvars, 1)\n+ a, = jaxpr.outvars\n+ self.assertEqual(a.aval, core.ShapedArray((3,), FooTy()))\n+\n+ # tests after here need the primitives\n+\n+ def test_make_jaxpr_with_primitives(self):\n+ def f():\n+ k1 = make((3, 4))\n+ k2 = bake(k1)\n+ x = take(k2)\n+ return x\n+\n+ jaxpr = jax.make_jaxpr(f)().jaxpr\n+ # { lambda ; . let\n+ # a:foo[3,4] = make[shape=(3, 4)]\n+ # b:foo[4,3] = bake a\n+ # c:f32[4,3] = take b\n+ # in (c,) }\n+ self.assertLen(jaxpr.invars, 0)\n+ self.assertLen(jaxpr.eqns, 3)\n+ e1, e2, e3 = jaxpr.eqns\n+\n+ self.assertIs(e1.primitive, make_p)\n+ self.assertLen(e1.outvars, 1)\n+ a, = e1.outvars\n+ self.assertEqual(a.aval, core.ShapedArray((3, 4), FooTy()))\n+\n+ self.assertIs(e2.primitive, bake_p)\n+ self.assertLen(e2.outvars, 1)\n+ b, = e2.outvars\n+ self.assertEqual(b.aval, core.ShapedArray((4, 3), FooTy()))\n+\n+ self.assertIs(e3.primitive, take_p)\n+ self.assertLen(e3.outvars, 1)\n+ c, = e3.outvars\n+ self.assertEqual(c.aval, core.ShapedArray((4, 3), np.dtype('float32')))\n+\n+ # tests after here need FooArray and lowerings\n+\n+ def test_jit_closure(self):\n+ k = FooArray((), jnp.arange(2, dtype='uint32'))\n+\n+ @jax.jit\n+ def f():\n+ jnp.add(1, 1) # make jit not hit trivial dispatch path\n+ return k\n+\n+ y = f() # doesn't crash\n+ self.assertIsInstance(y, FooArray)\n+ self.assertEqual(y.shape, ())\n+\n+ def test_jit_identity(self):\n+ k = FooArray((), jnp.arange(2, dtype='uint32'))\n+\n+ @jax.jit\n+ def f(k):\n+ jnp.add(1, 1) # make jit not hit trivial dispatch path\n+ return k\n+\n+ y = f(k) # doesn't crash\n+ self.assertIsInstance(y, FooArray)\n+ self.assertEqual(y.shape, ())\n+\n+ def test_jit_multiple_primitives(self):\n+ @jax.jit\n+ def f():\n+ k1 = make((3,))\n+ k2 = bake(k1)\n+ y = take(k2)\n+ return y\n+\n+ y = f()\n+ self.assertArraysAllClose(y, jnp.array([3., 3., 3.]), check_dtypes=False)\n+\n+ def test_scan_jaxpr(self):\n+ ks = jax.jit(lambda: make((3, 4)))()\n+ f = lambda ks: jax.lax.scan(lambda _, k: (None, bake(k)), None, ks)\n+ jaxpr = jax.make_jaxpr(f)(ks).jaxpr\n+ # { lambda ; a:foo[3,4]. let\n+ # b:foo[3,4] = scan[\n+ # jaxpr={ lambda ; c:foo[4]. let d:foo[4] = bake c in (d,) }\n+ # ] a\n+ # in (b,) }\n+ self.assertLen(jaxpr.invars, 1)\n+ a, = jaxpr.invars\n+ self.assertEqual(a.aval, core.ShapedArray((3, 4), FooTy()))\n+ self.assertLen(jaxpr.eqns, 1)\n+ e, = jaxpr.eqns\n+ self.assertLen(e.outvars, 1)\n+ b, = e.outvars\n+ self.assertEqual(b.aval, core.ShapedArray((3, 4), FooTy()))\n+\n+ def test_scan_lowering(self):\n+ ks = jax.jit(lambda: make((3, 4)))()\n+ f = lambda ks: jax.lax.scan(lambda _, k: (None, bake(k)), None, ks)\n+ _, out = jax.jit(f)(ks) # doesn't crash\n+ self.assertIsInstance(out, FooArray)\n+ self.assertEqual(out.shape, (3, 4))\n+\n+ def test_vmap(self):\n+ ks = jax.jit(lambda: make((3, 4, 5)))()\n+ ys = jax.vmap(jax.jit(lambda k: take(bake(k))))(ks)\n+ expected = jnp.broadcast_to(3 * 4 * 5, (3, 5, 4)).astype('float32')\n+ self.assertAllClose(ys, expected)\n+\n+ def test_transpose(self):\n+ ks = jax.jit(lambda: make((3, 4)))()\n+ ys = jax.jit(lambda x: x.T)(ks)\n+ self.assertIsInstance(ys, FooArray)\n+ self.assertEqual(ys.shape, (4, 3))\n+\n+ # TODO(frostig,mattjj): more polymorphic primitives tests\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Rolling forward #11768 after test failures caused roll-back (from use of np.empty).
PiperOrigin-RevId: 465712458 |
260,631 | 08.08.2022 08:39:20 | 25,200 | 8e2c68cbe40c3ac7db204a19e32d0479df641212 | MHLO CompareOp pretty printing | [
{
"change_type": "MODIFY",
"old_path": "tests/filecheck/math.filecheck.py",
"new_path": "tests/filecheck/math.filecheck.py",
"diff": "@@ -197,30 +197,26 @@ def main(_):\nprint_ir(np.float32(1), np.float32(2))(lax.div)\n# CHECK-LABEL: TEST: eq float32[] float32[]\n- # CHECK: mhlo.compare\n- # CHECK-SAME: compare_type = #mhlo<comparison_type FLOAT>\n- # CHECK-SAME: comparison_direction = #mhlo<comparison_direction EQ>\n+ # CHECK: mhlo.compare EQ\n+ # CHECK-SAME: FLOAT\n# CHECK-SAME: tensor<f32>\nprint_ir(np.float32(1), np.float32(2))(lax.eq)\n# CHECK-LABEL: TEST: eq complex128[] complex128[]\n- # CHECK: mhlo.compare\n- # CHECK-SAME: compare_type = #mhlo<comparison_type FLOAT>\n- # CHECK-SAME: comparison_direction = #mhlo<comparison_direction EQ>\n+ # CHECK: mhlo.compare EQ\n+ # CHECK-SAME: FLOAT\n# CHECK-SAME: tensor<complex<f64>>\nprint_ir(np.complex128(1), np.complex128(2))(lax.eq)\n# CHECK-LABEL: TEST: eq int64[] int64[]\n- # CHECK: mhlo.compare\n- # CHECK-SAME: compare_type = #mhlo<comparison_type SIGNED>\n- # CHECK-SAME: comparison_direction = #mhlo<comparison_direction EQ>\n+ # CHECK: mhlo.compare EQ\n+ # CHECK-SAME: SIGNED\n# CHECK-SAME: tensor<i64>\nprint_ir(np.int64(1), np.int64(2))(lax.eq)\n# CHECK-LABEL: TEST: eq uint16[] uint16[]\n- # CHECK: mhlo.compare\n- # CHECK-SAME: compare_type = #mhlo<comparison_type UNSIGNED>\n- # CHECK-SAME: comparison_direction = #mhlo<comparison_direction EQ>\n+ # CHECK: mhlo.compare EQ\n+ # CHECK-SAME: UNSIGNED\n# CHECK-SAME: tensor<ui16>\nprint_ir(np.uint16(1), np.uint16(2))(lax.eq)\n@@ -255,16 +251,14 @@ def main(_):\nprint_ir(np.empty((2, 3), jnp.bfloat16))(lax.floor)\n# CHECK-LABEL: TEST: ge float32[] float32[]\n- # CHECK: mhlo.compare\n- # CHECK-SAME: compare_type = #mhlo<comparison_type FLOAT>\n- # CHECK-SAME: comparison_direction = #mhlo<comparison_direction GE>\n+ # CHECK: mhlo.compare GE\n+ # CHECK-SAME: FLOAT\n# CHECK-SAME: tensor<f32>\nprint_ir(np.float32(1), np.float32(2))(lax.ge)\n# CHECK-LABEL: TEST: gt float32[] float32[]\n- # CHECK: mhlo.compare\n- # CHECK-SAME: compare_type = #mhlo<comparison_type FLOAT>\n- # CHECK-SAME: comparison_direction = #mhlo<comparison_direction GT>\n+ # CHECK: mhlo.compare GT\n+ # CHECK-SAME: FLOAT\n# CHECK-SAME: tensor<f32>\nprint_ir(np.float32(1), np.float32(2))(lax.gt)\n@@ -300,9 +294,8 @@ def main(_):\nprint_ir(np.float64(0))(lax.is_finite)\n# CHECK-LABEL: TEST: le float32[] float32[]\n- # CHECK: mhlo.compare\n- # CHECK-SAME: compare_type = #mhlo<comparison_type FLOAT>\n- # CHECK-SAME: comparison_direction = #mhlo<comparison_direction LE>\n+ # CHECK: mhlo.compare LE\n+ # CHECK-SAME: FLOAT\n# CHECK-SAME: tensor<f32>\nprint_ir(np.float32(1), np.float32(2))(lax.le)\n@@ -322,9 +315,8 @@ def main(_):\nprint_ir(np.float32(0))(lax.log1p)\n# CHECK-LABEL: TEST: lt float32[] float32[]\n- # CHECK: mhlo.compare\n- # CHECK-SAME: compare_type = #mhlo<comparison_type FLOAT>\n- # CHECK-SAME: comparison_direction = #mhlo<comparison_direction LT>\n+ # CHECK: mhlo.compare LT\n+ # CHECK-SAME: FLOAT\n# CHECK-SAME: tensor<f32>\nprint_ir(np.float32(1), np.float32(2))(lax.lt)\n@@ -344,9 +336,8 @@ def main(_):\nprint_ir(np.float32(1), np.float32(2))(lax.mul)\n# CHECK-LABEL: TEST: ne float32[] float32[]\n- # CHECK: mhlo.compare\n- # CHECK-SAME: compare_type = #mhlo<comparison_type FLOAT>\n- # CHECK-SAME: comparison_direction = #mhlo<comparison_direction NE>\n+ # CHECK: mhlo.compare NE\n+ # CHECK-SAME: FLOAT\n# CHECK-SAME: tensor<f32>\nprint_ir(np.float32(1), np.float32(2))(lax.ne)\n"
}
] | Python | Apache License 2.0 | google/jax | MHLO CompareOp pretty printing
PiperOrigin-RevId: 466051458 |
260,510 | 08.08.2022 11:41:46 | 25,200 | 2d72dc899b5609ea9dd65fec4328590ac9061b5e | Enable receives in TPU callbacks and add tests | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "@@ -50,17 +50,15 @@ debug_callback_p.multiple_results = True\nmap, unsafe_map = util.safe_map, map\n@debug_callback_p.def_impl\n-def debug_callback_impl(*flat_args, callback: Callable[..., Any],\n- effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n+def debug_callback_impl(*args, callback: Callable[..., Any],\n+ effect: DebugEffect):\ndel effect\n- args, kwargs = tree_util.tree_unflatten(in_tree, flat_args)\n- out = callback(*args, **kwargs)\n- return tree_util.tree_leaves(out)\n+ return callback(*args)\n@debug_callback_p.def_effectful_abstract_eval\ndef debug_callback_abstract_eval(*flat_avals, callback: Callable[..., Any],\n- effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n- del flat_avals, callback, in_tree\n+ effect: DebugEffect):\n+ del flat_avals, callback\nreturn [], {effect}\ndef debug_callback_batching_rule(args, dims, **params):\n@@ -87,8 +85,8 @@ def debug_callback_jvp_rule(primals, tangents, **params):\nad.primitive_jvps[debug_callback_p] = debug_callback_jvp_rule\ndef debug_callback_transpose_rule(*flat_args, callback: Callable[..., Any],\n- effect: DebugEffect, in_tree: tree_util.PyTreeDef):\n- del flat_args, callback, effect, in_tree\n+ effect: DebugEffect):\n+ del flat_args, callback, effect\nraise ValueError(\"Transpose doesn't support debugging callbacks.\")\nad.primitive_transposes[debug_callback_p] = debug_callback_transpose_rule\n@@ -175,19 +173,23 @@ def debug_callback(callback: Callable[..., Any], *args: Any,\nof the computation are duplicated or dropped.\nArgs:\n- callback: A Python callable.\n+ callback: A Python callable. Its return value will be ignored.\n*args: The positional arguments to the callback.\nordered: A keyword only argument used to indicate whether or not the\nstaged out computation will enforce ordering of this callback w.r.t.\nother ordered callbacks.\n- **kwargs: The positional arguments to the callback.\n+ **kwargs: The keyword arguments to the callback.\nReturns:\nThe value of `callback(*args, **kwargs)`.\n\"\"\"\nflat_args, in_tree = tree_util.tree_flatten((args, kwargs))\neffect = DebugEffect.ORDERED_PRINT if ordered else DebugEffect.PRINT\n- return debug_callback_p.bind(*flat_args, callback=callback, effect=effect,\n- in_tree=in_tree)\n+ def _flat_callback(*flat_args):\n+ args, kwargs = tree_util.tree_unflatten(in_tree, flat_args)\n+ callback(*args, **kwargs)\n+ return []\n+ return debug_callback_p.bind(*flat_args, callback=_flat_callback,\n+ effect=effect)\nclass _DebugPrintFormatChecker(string.Formatter):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -1419,39 +1419,47 @@ def receive_from_host(channel: int, token: mhlo.TokenType,\nreturn token, result\n-def emit_python_callback(\n- ctx: LoweringRuleContext, callback, token: Optional[Any],\n- operands: List[ir.Value], operand_avals: List[core.AbstractValue],\n- result_avals: List[core.AbstractValue],\n- has_side_effect: bool, *, sharding: Optional[xc.OpSharding] = None\n+def _emit_tpu_python_callback(backend: xb.XlaBackend, ctx: LoweringRuleContext,\n+ callback, token: Optional[Any], operands: List[ir.Value],\n+ operand_avals: List[core.ShapedArray],\n+ operand_shapes: List[xc.Shape],\n+ result_avals: List[core.ShapedArray],\n+ result_shapes: List[xc.Shape], *,\n+ sharding: Optional[xc.OpSharding] = None\n) -> Tuple[List[ir.Value], Any, Any]:\n- \"\"\"Creates an MHLO `CustomCallOp` that calls back to the provided function.\"\"\"\n- platform = ctx.module_context.platform\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\"}:\n- raise ValueError(\n- f\"`EmitPythonCallback` not supported on {platform} backend.\")\n- backend = xb.get_backend(platform)\n- result_shapes = util.flatten(\n- [xla.aval_to_xla_shapes(result_aval) for result_aval in result_avals])\n- operand_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.\")\ntoken = token or mhlo.CreateTokenOp(mhlo.TokenType.get()).result\n+ _wrapped_callback = callback\n+\nsend_channels = []\n+ if not operand_avals:\n+ # If there are no operands to the callback, we need to insert a dummy send\n+ # op or the callback will never be triggered!\n+ # TODO(sharadmv,chky): Enable this fix in the runtime as opposed to in\n+ # MHLO builder.\n+ callback_without_args = _wrapped_callback\n+ def _wrapped_callback(*args): # pylint: disable=function-redefined\n+ del args\n+ return callback_without_args()\n+ send_channel = ctx.module_context.new_channel()\n+ dummy_send_aval = core.ShapedArray((1,), np.float32)\n+ dummy_send_val = ir_constant(np.zeros(1, np.float32))\n+ operand_shapes = [*operand_shapes,\n+ xla.aval_to_xla_shapes(dummy_send_aval)[0]]\n+ token = send_to_host(send_channel, token, dummy_send_val, dummy_send_aval,\n+ callback.__name__, sharding=sharding)\n+ send_channels.append(send_channel)\n+ else:\nfor operand, operand_aval in zip(operands, operand_avals):\n+ if any(s == 0 for s in operand_aval.shape):\n+ raise NotImplementedError(\n+ \"Callbacks with zero-dimensional values not supported on TPU.\")\nchannel = ctx.module_context.new_channel()\ntoken = send_to_host(channel, token, operand, operand_aval,\ncallback.__name__, sharding=sharding)\nsend_channels.append(channel)\n- recv_channels = []\n- recv_channel = ctx.module_context.new_channel()\n+ recv_channels = []\n+ outputs = []\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@@ -1459,26 +1467,85 @@ def emit_python_callback(\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+ if not result_avals:\n+ callback_without_return_values = _wrapped_callback\n+ def _wrapped_callback(*args): # pylint: disable=function-redefined\n+ callback_without_return_values(*args)\nreturn (np.zeros(1, np.float32),)\n-\n+ recv_channel = ctx.module_context.new_channel()\ndummy_recv_aval = core.ShapedArray((1,), np.float32)\n- result_shapes = [*result_shapes, xla.aval_to_xla_shapes(dummy_recv_aval)[0]]\n+ result_shapes = [*result_shapes,\n+ xla.aval_to_xla_shapes(dummy_recv_aval)[0]]\ntoken, _ = receive_from_host(recv_channel, token, dummy_recv_aval,\ncallback.__name__, sharding=sharding)\nrecv_channels.append(recv_channel)\n+ else:\n+ for result_aval in result_avals:\n+ if any(s == 0 for s in result_aval.shape):\n+ raise NotImplementedError(\n+ \"Callbacks with zero-dimensional values not supported on TPU.\")\n+ channel = ctx.module_context.new_channel()\n+ assert isinstance(result_aval, core.ShapedArray)\n+ token, out = receive_from_host(channel, token, result_aval,\n+ callback.__name__, sharding=sharding)\n+ outputs.append(out)\n+ recv_channels.append(channel)\nopaque = backend.make_python_callback_from_host_send_and_recv(\n_wrapped_callback, operand_shapes, result_shapes, send_channels,\nrecv_channels)\nctx.module_context.add_host_callback(opaque)\n- return [], token, opaque\n+ return outputs, token, opaque\n+\n+\n+def emit_python_callback(\n+ ctx: LoweringRuleContext, callback, token: Optional[Any],\n+ operands: List[ir.Value], operand_avals: List[core.ShapedArray],\n+ result_avals: List[core.ShapedArray],\n+ has_side_effect: bool, *, sharding: Optional[xc.OpSharding] = None\n+ ) -> Tuple[List[ir.Value], Any, Any]:\n+ \"\"\"Emits MHLO that calls back to a provided Python function.\"\"\"\n+ platform = ctx.module_context.platform\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\"}:\n+ raise ValueError(\n+ f\"`EmitPythonCallback` not supported on {platform} backend.\")\n+ backend = xb.get_backend(platform)\n+ result_shapes = util.flatten(\n+ [xla.aval_to_xla_shapes(result_aval) for result_aval in result_avals])\n+ operand_shapes = util.flatten(\n+ [xla.aval_to_xla_shapes(op_aval) for op_aval in operand_avals])\n+\n+ # First we apply checks to ensure output shapes and dtypes match the expected\n+ # ones.\n+ def _wrapped_callback(*args):\n+ out_vals = callback(*args)\n+ if len(out_vals) != len(result_avals):\n+ raise RuntimeError(\n+ \"Mismatched number of outputs from callback. \"\n+ \"Expected: {}, Actual: {}\".format(len(result_avals), len(out_vals)))\n+ for i, (out_val, out_aval) in enumerate(zip(out_vals, result_avals)):\n+ if out_val.shape != out_aval.shape:\n+ raise RuntimeError(\n+ f\"Incorrect output shape for return value {i}: \"\n+ \"Expected: {}, Actual: {}\".format(out_aval.shape, out_val.shape))\n+ if out_val.dtype != out_aval.dtype:\n+ raise RuntimeError(\n+ f\"Incorrect output dtype for return value {i}: \"\n+ \"Expected: {}, Actual: {}\".format(out_aval.dtype, out_val.dtype))\n+ return out_vals\n+\n+ if platform == \"tpu\":\n+ return _emit_tpu_python_callback(backend, ctx, _wrapped_callback, token,\n+ operands, operand_avals, operand_shapes, result_avals, result_shapes,\n+ sharding=sharding)\nresult_types = util.flatten([aval_to_ir_types(aval) for aval in result_avals])\n- wrapped_callback = callback\nif token:\n- def wrapped_callback(token, *args): # type: ignore\n- return tuple((token, *callback(*args)))\n+ callback_without_token = _wrapped_callback\n+ def _wrapped_callback(token, *args): # type: ignore # pylint: disable=function-redefined\n+ return (token, *callback_without_token(*args))\noperand_shapes = [\nxla.aval_to_xla_shapes(core.abstract_token)[0], *operand_shapes\n@@ -1489,7 +1556,7 @@ def emit_python_callback(\noperands = [token, *operands]\nresult_types = [token_type()[0], *result_types]\ncallback_descriptor, keepalive = (\n- backend.get_emit_python_callback_descriptor(wrapped_callback,\n+ backend.get_emit_python_callback_descriptor(_wrapped_callback,\noperand_shapes,\nresult_shapes))\ndescriptor_operand = ir_constant(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -873,6 +873,11 @@ jax_test(\n],\n)\n+jax_test(\n+ name = \"python_callback_test\",\n+ srcs = [\"python_callback_test.py\"],\n+)\n+\njax_test(\nname = \"debugger_test\",\nsrcs = [\"debugger_test.py\"],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/python_callback_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 contextlib\n+import io\n+import textwrap\n+from unittest import mock\n+\n+from typing import Any, Callable, Generator, Sequence\n+\n+from absl.testing import absltest\n+import jax\n+from jax import core\n+from jax import lax\n+from jax import tree_util\n+from jax._src import debugging\n+from jax._src import lib as jaxlib\n+from jax._src import test_util as jtu\n+from jax._src import util\n+from jax.config import config\n+from jax.interpreters import mlir\n+import jax.numpy as jnp\n+import numpy as np\n+\n+\n+config.parse_flags_with_absl()\n+\n+debug_print = debugging.debug_print\n+\n+\n+@contextlib.contextmanager\n+def capture_stdout() -> Generator[Callable[[], str], None, None]:\n+ with mock.patch(\"sys.stdout\", new_callable=io.StringIO) as fp:\n+\n+ def _read() -> str:\n+ return fp.getvalue()\n+\n+ yield _read\n+\n+\n+def _format_multiline(text):\n+ return textwrap.dedent(text).lstrip()\n+\n+\n+prev_xla_flags = None\n+\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+\n+# Reset to previous configuration in case other test modules will be run.\n+def tearDownModule():\n+ prev_xla_flags()\n+\n+\n+# TODO(sharadmv): remove jaxlib guards for TPU tests when jaxlib minimum\n+# version is >= 0.3.15\n+disabled_backends = []\n+if jaxlib.version < (0, 3, 15):\n+ disabled_backends.append(\"tpu\")\n+\n+callback_p = core.Primitive(\"callback\")\n+callback_p.multiple_results = True\n+\n+map, unsafe_map = util.safe_map, map\n+\n+\n+@callback_p.def_impl\n+def callback_impl(*args, callback: Callable[..., Any], result_avals,\n+ effect: debugging.DebugEffect):\n+ del result_avals, effect\n+ return callback(*args)\n+\n+\n+@callback_p.def_effectful_abstract_eval\n+def callback_abstract_eval(*flat_avals, callback: Callable[..., Any],\n+ effect: debugging.DebugEffect,\n+ result_avals: Sequence[core.ShapedArray]):\n+ del flat_avals, callback\n+ return result_avals, {effect}\n+\n+\n+def callback(f, result_shape, *args, ordered: bool = False, **kwargs):\n+ flat_result_shapes, out_tree = tree_util.tree_flatten(result_shape)\n+ flat_args, in_tree = tree_util.tree_flatten((args, kwargs))\n+ flat_result_avals = [\n+ core.ShapedArray(s.shape, s.dtype) for s in flat_result_shapes\n+ ]\n+ effect = (\n+ debugging.DebugEffect.ORDERED_PRINT\n+ if ordered else debugging.DebugEffect.PRINT)\n+ flat_args, in_tree = tree_util.tree_flatten((args, kwargs))\n+ def _flat_callback(*flat_args):\n+ args, kwargs = tree_util.tree_unflatten(in_tree, flat_args)\n+ return tree_util.tree_leaves(f(*args, **kwargs))\n+ out_flat = callback_p.bind(\n+ *flat_args,\n+ callback=_flat_callback,\n+ effect=effect,\n+ result_avals=flat_result_avals)\n+ return tree_util.tree_unflatten(out_tree, out_flat)\n+\n+\n+def callback_lowering(ctx, *args, effect, callback, **params):\n+\n+ def _callback(*flat_args):\n+ return tuple(\n+ callback_p.impl(*flat_args, effect=effect, callback=callback, **params))\n+\n+ if effect in core.ordered_effects:\n+ token = ctx.tokens_in.get(effect)[0]\n+ result, token, keepalive = mlir.emit_python_callback(\n+ ctx, _callback, token, list(args), ctx.avals_in, ctx.avals_out, True)\n+ ctx.set_tokens_out(mlir.TokenSet({effect: (token,)}))\n+ else:\n+ result, token, keepalive = mlir.emit_python_callback(\n+ ctx, _callback, None, list(args), ctx.avals_in, ctx.avals_out, True)\n+ ctx.module_context.add_keepalive(keepalive)\n+ return result\n+\n+\n+mlir.register_lowering(callback_p, callback_lowering, platform=\"cpu\")\n+mlir.register_lowering(callback_p, callback_lowering, platform=\"gpu\")\n+if jaxlib.version >= (0, 3, 15):\n+ mlir.register_lowering(callback_p, callback_lowering, platform=\"tpu\")\n+\n+\n+class PythonCallbackTest(jtu.JaxTestCase):\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_scalar_values(self):\n+\n+ @jax.jit\n+ def f(x):\n+ return callback(lambda x: x + np.float32(1.),\n+ core.ShapedArray(x.shape, x.dtype), x)\n+\n+ out = f(0.)\n+ self.assertEqual(out, 1.)\n+\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_wrong_number_of_args(self):\n+\n+ @jax.jit\n+ def f():\n+ # Calling a function that expects `x` with no arguments\n+ return callback(lambda x: np.ones(4, np.float32),\n+ core.ShapedArray((4,), np.float32))\n+\n+ with self.assertRaises(RuntimeError):\n+ f()\n+ jax.effects_barrier()\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_wrong_number_of_returned_values(self):\n+\n+ @jax.jit\n+ def f():\n+ # Calling a function with a return value that expects no return values\n+ return callback(lambda: np.ones(4, np.float32), ())\n+\n+ with self.assertRaises(RuntimeError):\n+ f()\n+ jax.effects_barrier()\n+\n+ @jax.jit\n+ def g():\n+ # Calling a function with a return value that expects no return values\n+ return callback(lambda: None, (core.ShapedArray(\n+ (1,), np.float32), core.ShapedArray((2,), np.float32)))\n+\n+ with self.assertRaises(RuntimeError):\n+ g()\n+ jax.effects_barrier()\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_wrong_shape_outputs(self):\n+\n+ @jax.jit\n+ def f():\n+ # Calling a function expected a (1,) shaped return value but getting ()\n+ return callback(lambda: np.float32(1.), core.ShapedArray((1,),\n+ np.float32))\n+\n+ with self.assertRaises(RuntimeError):\n+ f()\n+ jax.effects_barrier()\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_wrong_dtype_outputs(self):\n+\n+ def _cb():\n+ return np.array([1], np.float64)\n+\n+ @jax.jit\n+ def f():\n+ # Calling a function expected a f32 return value but getting f64\n+ return callback(_cb, core.ShapedArray((1,), np.float32))\n+\n+ with self.assertRaises(RuntimeError):\n+ f()\n+ jax.effects_barrier()\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_single_return_value(self):\n+\n+ @jax.jit\n+ def f():\n+ return callback(lambda: np.ones(4, np.float32),\n+ core.ShapedArray((4,), np.float32))\n+\n+ out = f()\n+ jax.effects_barrier()\n+ np.testing.assert_allclose(out, np.ones(4, np.float32))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_multiple_return_values(self):\n+\n+ @jax.jit\n+ def f():\n+ return callback(lambda: (np.ones(4, np.float32), np.ones(5, np.int32)),\n+ (core.ShapedArray(\n+ (4,), np.float32), core.ShapedArray((5,), np.int32)))\n+\n+ x, y = f()\n+ jax.effects_barrier()\n+ np.testing.assert_allclose(x, np.ones(4, np.float32))\n+ np.testing.assert_allclose(y, np.ones(5, np.int32))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_multiple_arguments_and_return_values(self):\n+\n+ def _callback(x, y, z):\n+ return (x, y + z)\n+\n+ @jax.jit\n+ def f(x, y, z):\n+ return callback(_callback, (core.ShapedArray(\n+ (3,), x.dtype), core.ShapedArray((3,), x.dtype)), x, y, z)\n+\n+ x, y = f(jnp.ones(3), jnp.arange(3.), jnp.arange(3.) + 1.)\n+ np.testing.assert_allclose(x, np.ones(3))\n+ np.testing.assert_allclose(y, np.array([1., 3., 5]))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_send_recv_zero_dim_arrays(self):\n+\n+ def _callback(x):\n+ return x\n+\n+ @jax.jit\n+ def f(x):\n+ return callback(_callback, core.ShapedArray((0,), np.float32), x)\n+\n+ if jax.default_backend() == \"tpu\":\n+ with self.assertRaisesRegex(\n+ NotImplementedError,\n+ \"Callbacks with zero-dimensional values not supported on TPU.\"):\n+ f(jnp.zeros(0, jnp.float32))\n+ jax.effects_barrier()\n+ else:\n+ np.testing.assert_allclose(\n+ f(jnp.zeros(0, jnp.float32)), np.zeros(0, np.float32))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_pytree_arguments_and_return_values(self):\n+\n+ def _callback(x):\n+ return dict(y=[x])\n+\n+ @jax.jit\n+ def f(x):\n+ return callback(_callback, dict(y=[core.ShapedArray((), np.float32)]),\n+ [x])\n+\n+ out = f(jnp.float32(2.))\n+ jax.effects_barrier()\n+ self.assertEqual(out, dict(y=[2.]))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_while_loop_of_scalars(self):\n+\n+ def _callback(x):\n+ return (x + 1.).astype(x.dtype)\n+\n+ @jax.jit\n+ def f(x):\n+ def cond(x):\n+ return x < 10\n+ def body(x):\n+ return callback(_callback, core.ShapedArray((), x.dtype), x)\n+ return lax.while_loop(cond, body, x)\n+\n+ out = f(0.)\n+ jax.effects_barrier()\n+ self.assertEqual(out, 10.)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_while_loop(self):\n+\n+ def _callback(x):\n+ return (x + 1.).astype(x.dtype)\n+\n+ @jax.jit\n+ def f(x):\n+\n+ def cond(x):\n+ return jnp.any(x < 10)\n+\n+ def body(x):\n+ return callback(_callback, core.ShapedArray(x.shape, x.dtype), x)\n+\n+ return lax.while_loop(cond, body, x)\n+\n+ out = f(jnp.arange(5.))\n+ jax.effects_barrier()\n+ np.testing.assert_allclose(out, jnp.arange(10., 15.))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_cond_of_scalars(self):\n+\n+ def _callback1(x):\n+ return (x + 1.).astype(x.dtype)\n+\n+ def _callback2(x):\n+ return (x - 1.).astype(x.dtype)\n+\n+ @jax.jit\n+ def f(pred, x):\n+\n+ def true_fun(x):\n+ return callback(_callback1, core.ShapedArray((), x.dtype), x)\n+\n+ def false_fun(x):\n+ return callback(_callback2, core.ShapedArray((), x.dtype), x)\n+\n+ return lax.cond(pred, true_fun, false_fun, x)\n+\n+ out = f(True, 1.)\n+ jax.effects_barrier()\n+ self.assertEqual(out, 2.)\n+ out = f(False, 1.)\n+ jax.effects_barrier()\n+ self.assertEqual(out, 0.)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_cond(self):\n+\n+ def _callback1(x):\n+ return x + 1.\n+\n+ def _callback2(x):\n+ return x - 1.\n+\n+ @jax.jit\n+ def f(pred, x):\n+\n+ def true_fun(x):\n+ return callback(_callback1, core.ShapedArray(x.shape, x.dtype), x)\n+\n+ def false_fun(x):\n+ return callback(_callback2, core.ShapedArray(x.shape, x.dtype), x)\n+\n+ return lax.cond(pred, true_fun, false_fun, x)\n+\n+ out = f(True, jnp.ones(2))\n+ jax.effects_barrier()\n+ np.testing.assert_allclose(out, jnp.ones(2) * 2.)\n+ out = f(False, jnp.ones(2))\n+ jax.effects_barrier()\n+ np.testing.assert_allclose(out, jnp.zeros(2))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_scan_of_scalars(self):\n+\n+ def _callback(x):\n+ return (x + 1.).astype(x.dtype)\n+\n+ @jax.jit\n+ def f(x):\n+\n+ def body(x, _):\n+ x = callback(_callback, core.ShapedArray(x.shape, x.dtype), x)\n+ return x, ()\n+\n+ return lax.scan(body, x, jnp.arange(10))[0]\n+\n+ out = f(0.)\n+ jax.effects_barrier()\n+ self.assertEqual(out, 10.)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_scan(self):\n+\n+ def _callback(x):\n+ return x + 1.\n+\n+ @jax.jit\n+ def f(x):\n+\n+ def body(x, _):\n+ x = callback(_callback, core.ShapedArray(x.shape, x.dtype), x)\n+ return x, ()\n+\n+ return lax.scan(body, x, jnp.arange(10))[0]\n+\n+ out = f(jnp.arange(2.))\n+ jax.effects_barrier()\n+ np.testing.assert_allclose(out, jnp.arange(2.) + 10.)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_pmap_of_scalars(self):\n+\n+ def _callback(x):\n+ return (x + 1.).astype(x.dtype)\n+\n+ @jax.pmap\n+ def f(x):\n+ return callback(_callback, core.ShapedArray(x.shape, x.dtype), x)\n+\n+ out = f(jnp.arange(jax.local_device_count(), dtype=jnp.float32))\n+ jax.effects_barrier()\n+ np.testing.assert_allclose(\n+ out, np.arange(jax.local_device_count(), dtype=np.float32) + 1.)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_pmap(self):\n+\n+ def _callback(x):\n+ return x + 1.\n+\n+ @jax.pmap\n+ def f(x):\n+ return callback(_callback, core.ShapedArray(x.shape, x.dtype), x)\n+\n+ out = f(\n+ jnp.arange(2 * jax.local_device_count(),\n+ dtype=jnp.float32).reshape([-1, 2]))\n+ jax.effects_barrier()\n+ np.testing.assert_allclose(\n+ out,\n+ np.arange(2 * jax.local_device_count()).reshape([-1, 2]) + 1.)\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Enable receives in TPU callbacks and add tests
PiperOrigin-RevId: 466103306 |
260,631 | 08.08.2022 16:56:14 | 25,200 | c4192dca655aae3556450abaac722570aa6ac010 | Ensure PartitionSpec is picklable.
PartitionSpec instances currently don't roundtrip correctly through pickle, wrapping any value in an extra tuple, e.g.
```
> pickle.loads(pickle.dumps(PartitionSpec('model', 'batch')))
> PartitionSpec(('model', 'batch'),)
``` | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -2332,6 +2332,9 @@ class PartitionSpec(tuple):\ndef __repr__(self):\nreturn \"PartitionSpec%s\" % tuple.__repr__(self)\n+ def __reduce__(self):\n+ return (PartitionSpec, tuple(self))\n+\n\"\"\"A sentinel value representing a dim is unconstrained.\"\"\"\nUNCONSTRAINED = _UNCONSTRAINED_PARTITION\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pickle_test.py",
"new_path": "tests/pickle_test.py",
"diff": "@@ -17,6 +17,7 @@ import pickle\nimport unittest\nfrom absl.testing import absltest\n+from absl.testing import parameterized\ntry:\nimport cloudpickle\n@@ -27,6 +28,7 @@ import jax\nfrom jax import core\nfrom jax import numpy as jnp\nfrom jax.config import config\n+from jax.interpreters import pxla\nfrom jax._src import test_util as jtu\nimport jax._src.lib\n@@ -93,6 +95,19 @@ class PickleTest(jtu.JaxTestCase):\nself.assertIsInstance(y, type(x))\nself.assertEqual(x.aval, y.aval)\n+ @parameterized.parameters(\n+ (pxla.PartitionSpec(),),\n+ (pxla.PartitionSpec(None),),\n+ (pxla.PartitionSpec('x', None),),\n+ (pxla.PartitionSpec(None, 'y'),),\n+ (pxla.PartitionSpec('x', 'y'),),\n+ (pxla.PartitionSpec(('x', 'y'),),),\n+ )\n+ def testPickleOfPartitionSpecs(self, partition_spec):\n+ restored_partition_spec = pickle.loads(pickle.dumps(partition_spec))\n+ self.assertIsInstance(restored_partition_spec, pxla.PartitionSpec)\n+ self.assertTupleEqual(partition_spec, restored_partition_spec)\n+\ndef testPickleX64(self):\nwith jax.experimental.enable_x64():\nx = jnp.array(4.0, dtype='float64')\n"
}
] | Python | Apache License 2.0 | google/jax | Ensure PartitionSpec is picklable.
PartitionSpec instances currently don't roundtrip correctly through pickle, wrapping any value in an extra tuple, e.g.
```
> pickle.loads(pickle.dumps(PartitionSpec('model', 'batch')))
> PartitionSpec(('model', 'batch'),)
```
PiperOrigin-RevId: 466188998 |
260,510 | 08.08.2022 15:36:26 | 25,200 | c34aa3933f8224134908c7e0addfb7bfd1439a67 | Various debugger improvements
disables globals
can opt out of filtering frames
can limit number of frames | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugger/core.py",
"new_path": "jax/_src/debugger/core.py",
"diff": "@@ -80,7 +80,7 @@ class DebuggerFrame:\nreturn DebuggerFrame(\nfilename=frame_info.filename,\nlocals=frame_info.frame.f_locals,\n- globals=frame_info.frame.f_globals,\n+ globals={},\ncode_context=frame_info.code_context,\nsource=source,\nlineno=frame_info.lineno,\n@@ -113,19 +113,45 @@ def register_debugger(name: str, debugger: Debugger, priority: int) -> None:\ndebug_lock = threading.Lock()\n-def breakpoint(*, ordered: bool = False, backend=None, **kwargs): # pylint: disable=redefined-builtin\n- \"\"\"Enters a breakpoint at a point in a program.\"\"\"\n+def breakpoint(*, backend: Optional[str] = None, filter_frames: bool = True,\n+ num_frames: Optional[int] = None, ordered: bool = False,\n+ **kwargs): # pylint: disable=redefined-builtin\n+ \"\"\"Enters a breakpoint at a point in a program.\n+\n+ Args:\n+ backend: The debugger backend to use. By default, picks the highest priority\n+ debugger and in the absence of other registered debuggers, falls back to\n+ the CLI debugger.\n+ filter_frames: Whether or not to filter out JAX-internal stack frames from\n+ the traceback. Since some libraries, like Flax, also make user of JAX's\n+ stack frame filtering system, this option can also affect whether stack\n+ frames from libraries are filtered.\n+ num_frames: The number of frames above the current stack frame to make\n+ available for inspection in the interactive debugger.\n+ ordered: A keyword only argument used to indicate whether or not the\n+ staged out computation will enforce ordering of this ``debug_print``\n+ with respect to other ordered ``debug_print`` calls.\n+\n+ Returns:\n+ None.\n+ \"\"\"\nframe_infos = inspect.stack()\n+ # Throw out first frame corresponding to this function\n+ frame_infos = frame_infos[1:]\n+ if num_frames is not None:\n+ frame_infos = frame_infos[:num_frames]\n# Filter out internal frames\n- frame_infos = [\n- frame_info for frame_info in frame_infos\n+ if filter_frames:\n+ frames = [\n+ DebuggerFrame.from_frameinfo(frame_info)\n+ for frame_info in frame_infos\nif traceback_util.include_frame(frame_info.frame)\n]\n+ else:\nframes = [\n- DebuggerFrame.from_frameinfo(frame_info) for frame_info in frame_infos\n+ DebuggerFrame.from_frameinfo(frame_info)\n+ for frame_info in frame_infos\n]\n- # Throw out first frame corresponding to this function\n- frames = frames[1:]\nflat_args, frames_tree = tree_util.tree_flatten(frames)\ndef _breakpoint_callback(*flat_args):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/debugger_test.py",
"new_path": "tests/debugger_test.py",
"diff": "@@ -59,6 +59,8 @@ disabled_backends = []\nif jaxlib.version < (0, 3, 15):\ndisabled_backends.append(\"tpu\")\n+foo = 2\n+\nclass CliDebuggerTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(*disabled_backends)\n@@ -321,8 +323,6 @@ class CliDebuggerTest(jtu.JaxTestCase):\n\\(jdb\\) \"\"\".format(re.escape(repr(arr))))\ng(jnp.arange(8, dtype=jnp.int32))\njax.effects_barrier()\n- print(stdout.getvalue())\n- print(expected)\nself.assertRegex(stdout.getvalue(), expected)\n@jtu.skip_on_devices(*disabled_backends)\n@@ -344,10 +344,70 @@ class CliDebuggerTest(jtu.JaxTestCase):\n\\(jdb\\) \"\"\")\nf(2.)\njax.effects_barrier()\n- print(stdout.getvalue())\n- print(expected)\nself.assertRegex(stdout.getvalue(), expected)\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debugger_accesses_globals(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"p foo\", \"c\"])\n+\n+ @jax.jit\n+ def g():\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\n+\n+ expected = _format_multiline(r\"\"\"\n+ Entering jdb:\n+ \\(jdb\\) \\*\\*\\* NameError: name 'foo' is not defined\n+ \\(jdb\\) \"\"\")\n+ g()\n+ jax.effects_barrier()\n+ self.assertRegex(stdout.getvalue(), expected)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_can_limit_num_frames(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"u\", \"p x\", \"c\"])\n+\n+ def g():\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\",\n+ num_frames=2)\n+\n+ @jax.jit\n+ def f():\n+ x = 2\n+ g()\n+ return x\n+\n+ _ = f()\n+ expected = _format_multiline(r\"\"\"\n+ Entering jdb:\n+ \\(jdb\\) .*\n+ .*\n+ .*\n+ .*\n+ .*\n+ .*\n+ .*\n+ \\(jdb\\) 2\n+ \\(jdb\\) \"\"\")\n+ jax.effects_barrier()\n+ self.assertRegex(stdout.getvalue(), expected)\n+\n+ stdin, stdout = make_fake_stdin_stdout([\"u\", \"u\", \"c\"])\n+\n+ def g2():\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\",\n+ num_frames=2)\n+\n+ @jax.jit\n+ def f2():\n+ x = 2\n+ g2()\n+ return x\n+\n+ expected = \".*At topmost frame.*\"\n+ _ = f2()\n+ jax.effects_barrier()\n+ self.assertRegex(stdout.getvalue(), expected)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Various debugger improvements
- disables globals
- can opt out of filtering frames
- can limit number of frames |
260,335 | 09.08.2022 12:22:10 | 25,200 | 666f4f838f011bb61958d7430732a3458809b22b | fix diffrax with new remat, do for cond what did for while_loop | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/conditionals.py",
"new_path": "jax/_src/lax/control_flow/conditionals.py",
"diff": "@@ -438,9 +438,20 @@ def _cond_partial_eval(trace, *tracers, branches, linear):\n# TODO(mattjj): de-duplicate with _cond_partial_eval\ndef _cond_partial_eval_custom(saveable, unks_in, inst_in, eqn):\nindex_uk, *ops_uk = unks_in\n- assert not index_uk # only possible with old-style remat\nbranches = eqn.params['branches']\n+ # Instantiate all inputs (b/c jaxpr_staged will take 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+ del inst_in\n+\n+ # NOTE(mattjj): I think it should be impossible for the index to be unknown,\n+ # but asserting that caused a test failure in diffrax. So we handle it: if it\n+ # is unknown, stage out the whole cond.\n+ if index_uk:\n+ all_true = [True] * len(branches[0].out_avals)\n+ return None, eqn, all_true, all_true, new_inst\n+\n# First, compute output unknowns (unks_out), where an output of the cond is\n# unknown if it would be unknown on any of the branches.\nunks_out: List[bool] = [False] * len(eqn.outvars)\n@@ -477,12 +488,6 @@ def _cond_partial_eval_custom(saveable, unks_in, inst_in, eqn):\nassert all(all(map(core.typematch, j.out_avals, branches_known[0].out_avals))\nfor j in branches_known[1:])\n- # Instantiate all inputs (b/c jaxpr_staged takes all inputs, corresponding to\n- # passing in_inst argument to partial_eval_jaxpr_custom above).\n- new_inst = [x for x, inst in zip(eqn.invars, inst_in)\n- if type(x) is core.Var and not inst]\n- del inst_in\n-\n# Create residual variables.\nnewvar = core.gensym()\nres_binders = map(newvar, all_res_avals)\n"
}
] | Python | Apache License 2.0 | google/jax | fix diffrax with new remat, do for cond what #11773 did for while_loop |
260,510 | 08.08.2022 22:18:24 | 25,200 | 18f164ff1cf8b7e04812390047c01c8b75af296a | Try flattening the locals/globals dict in the debugger and have a
fallback if it fails | [
{
"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-from typing import Any, Dict, List, Optional, Tuple\n+from typing import Any, Dict, Hashable, List, Optional, Tuple\nfrom typing_extensions import Protocol\nimport jax.numpy as jnp\n@@ -29,6 +28,46 @@ from jax._src import traceback_util\nfrom jax._src import util\nimport numpy as np\n+\n+@tree_util.register_pytree_node_class\n+class _DictWrapper:\n+ keys: list[Hashable]\n+ values: list[Any]\n+\n+ def __init__(self, keys, values):\n+ self._keys = keys\n+ self._values = values\n+\n+ def to_dict(self):\n+ return dict(zip(self._keys, self._values))\n+\n+ def tree_flatten(self):\n+ return self._values, self._keys\n+\n+ @classmethod\n+ def tree_unflatten(cls, keys, values):\n+ return _DictWrapper(keys, values)\n+\n+\n+class _CantFlatten:\n+ __repr__ = lambda _: \"<cant_flatten>\"\n+cant_flatten = _CantFlatten()\n+\n+def _safe_flatten_dict(dct: dict[Any, Any]\n+ ) -> tuple[list[Any], tree_util.PyTreeDef]:\n+ # We avoid comparison between keys by just using the original order\n+ keys, values = [], []\n+ for key, value in dct.items():\n+ try:\n+ tree_util.tree_leaves(value)\n+ except:\n+ # If flattening fails, we substitute a sentinel object.\n+ value = cant_flatten\n+ keys.append(key)\n+ values.append(value)\n+ return tree_util.tree_flatten(_DictWrapper(keys, values))\n+\n+\n@tree_util.register_pytree_node_class\n@dataclasses.dataclass(frozen=True)\nclass DebuggerFrame:\n@@ -42,22 +81,26 @@ class DebuggerFrame:\noffset: Optional[int]\ndef tree_flatten(self):\n- flat_vars, vars_tree = tree_util.tree_flatten((self.locals, self.globals))\n+ flat_locals, locals_tree = _safe_flatten_dict(self.locals)\n+ flat_globals, globals_tree = _safe_flatten_dict(self.globals)\n+ flat_vars = flat_locals + flat_globals\nis_valid = [\nisinstance(l, (core.Tracer, jnp.ndarray, np.ndarray))\nfor l in flat_vars\n]\ninvalid_vars, valid_vars = util.partition_list(is_valid, flat_vars)\n- return valid_vars, (is_valid, invalid_vars, vars_tree, self.filename,\n- self.code_context, self.source, self.lineno,\n- self.offset)\n+ return valid_vars, (is_valid, invalid_vars, locals_tree, globals_tree,\n+ len(flat_locals), self.filename, self.code_context,\n+ self.source, self.lineno, self.offset)\n@classmethod\ndef tree_unflatten(cls, info, valid_vars):\n- (is_valid, invalid_vars, vars_tree, filename, code_context, source,\n- lineno, offset) = info\n+ (is_valid, invalid_vars, locals_tree, globals_tree, num_locals, filename,\n+ code_context, source, lineno, offset) = info\nflat_vars = util.merge_lists(is_valid, invalid_vars, valid_vars)\n- locals_, globals_ = tree_util.tree_unflatten(vars_tree, flat_vars)\n+ flat_locals, flat_globals = util.split_list(flat_vars, [num_locals])\n+ locals_ = tree_util.tree_unflatten(locals_tree, flat_locals).to_dict()\n+ globals_ = tree_util.tree_unflatten(globals_tree, flat_globals).to_dict()\nreturn DebuggerFrame(filename, locals_, globals_, code_context, source,\nlineno, offset)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/debugger_test.py",
"new_path": "tests/debugger_test.py",
"diff": "@@ -376,7 +376,6 @@ class CliDebuggerTest(jtu.JaxTestCase):\nx = 2\ng()\nreturn x\n-\n_ = f()\nexpected = _format_multiline(r\"\"\"\nEntering jdb:\n@@ -409,5 +408,27 @@ class CliDebuggerTest(jtu.JaxTestCase):\njax.effects_barrier()\nself.assertRegex(stdout.getvalue(), expected)\n+ def test_can_handle_dictionaries_with_unsortable_keys(self):\n+ stdin, stdout = make_fake_stdin_stdout([\"p x\", \"p weird_dict\",\n+ \"p weirder_dict\", \"c\"])\n+\n+ @jax.jit\n+ def f():\n+ weird_dict = {(lambda x: x): 2., (lambda x: x * 2): 3}\n+ weirder_dict = {(lambda x: x): weird_dict}\n+ x = 2.\n+ debugger.breakpoint(stdin=stdin, stdout=stdout, backend=\"cli\")\n+ del weirder_dict\n+ return x\n+ expected = _format_multiline(r\"\"\"\n+ Entering jdb:\n+ \\(jdb\\) 2.0\n+ \\(jdb\\) <cant_flatten>\n+ \\(jdb\\) <cant_flatten>\n+ \\(jdb\\) \"\"\")\n+ _ = f()\n+ jax.effects_barrier()\n+ self.assertRegex(stdout.getvalue(), expected)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Try flattening the locals/globals dict in the debugger and have a
fallback if it fails |
260,335 | 09.08.2022 12:42:50 | 25,200 | 580e7f39d5a3a911637ffa118bc9fbc827ff89ad | fix traceback exclusion on new checkpoint | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -27,12 +27,14 @@ 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 import traceback_util\nfrom 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,\nsafe_zip, merge_lists, weakref_lru_cache)\nsource_info_util.register_exclusion(__file__)\n+traceback_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"
}
] | Python | Apache License 2.0 | google/jax | fix traceback exclusion on new checkpoint |
260,510 | 09.08.2022 14:34:30 | 25,200 | 3ec1b1b9878bd6ac48f07ec66160a52346c3e14e | Check if XLA Executable has `execute_with_token` before using it | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -48,9 +48,9 @@ from jax._src import traceback_util\nfrom jax._src.abstract_arrays import array_types\nfrom jax._src.config import config, flags\nfrom jax._src.lib.mlir import ir\n+from jax._src.lib import can_execute_with_token\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@@ -717,11 +717,11 @@ def _add_tokens(has_unordered_effects: bool, ordered_effects: List[core.Effect],\ninput_bufs = [*tokens_flat, *input_bufs]\ndef _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+ num_output_tokens = len(ordered_effects) + (not can_execute_with_token and\nhas_unordered_effects)\ntoken_bufs, output_bufs = util.split_list(output_bufs, [num_output_tokens])\nif has_unordered_effects:\n- if xla_extension_version >= 81:\n+ if can_execute_with_token:\nruntime_tokens.set_output_runtime_token(device, runtime_token)\nelse:\noutput_token_buf, *token_bufs = token_bufs\n@@ -746,7 +746,7 @@ def _execute_compiled(name: str, compiled: XlaExecutable,\nif has_unordered_effects or ordered_effects:\nin_flat, token_handler = _add_tokens(\nhas_unordered_effects, ordered_effects, device, in_flat)\n- if xla_extension_version >= 81:\n+ if can_execute_with_token:\nout_flat, runtime_token = compiled.execute_with_token(in_flat)\nelse:\nout_flat = compiled.execute(in_flat)\n@@ -959,7 +959,7 @@ class XlaCompiledComputation(stages.XlaExecutable):\nif ordered_effects or has_unordered_effects:\nnum_output_tokens = len(ordered_effects)\n# TODO(sharadmv): remove check when minimum jaxlib version is bumped\n- if xla_extension_version < 81:\n+ if not can_execute_with_token:\nnum_output_tokens += has_unordered_effects\nbuffer_counts = ([1] * num_output_tokens) + buffer_counts\nexecute = _execute_compiled if nreps == 1 else _execute_replicated\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lib/__init__.py",
"new_path": "jax/_src/lib/__init__.py",
"diff": "@@ -117,6 +117,10 @@ import jaxlib.gpu_linalg as gpu_linalg # pytype: disable=import-error\n# branch on the Jax github.\nxla_extension_version = getattr(xla_client, '_version', 0)\n+can_execute_with_token = (\n+ xla_extension_version >= 81 and\n+ hasattr(xla_client.Executable, \"execute_with_token\"))\n+\n# Version number for MLIR:Python APIs, provided by jaxlib.\nmlir_api_version = xla_client.mlir_api_version\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -39,9 +39,9 @@ from jax._src.lib.mlir import ir\nfrom jax._src.lib.mlir.dialects import chlo\nfrom jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.lib.mlir.dialects import func as func_dialect\n+from jax._src.lib import can_execute_with_token\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@@ -619,7 +619,7 @@ def lower_jaxpr_to_module(\nctx, \"main\", jaxpr, ordered_effects, public=True, create_tokens=True,\nreplace_tokens_with_dummy=True,\nnum_output_tokens=(\n- 1 if (unordered_effects and xla_extension_version < 81) else 0),\n+ 1 if (unordered_effects and not can_execute_with_token) 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": "@@ -68,6 +68,7 @@ from jax._src import profiler\nfrom jax._src import stages\nfrom jax._src.abstract_arrays import array_types\nfrom jax._src.config import config\n+from jax._src.lib import can_execute_with_token\nfrom jax._src.lib import xla_bridge as xb\nfrom jax._src.lib import xla_client as xc\nfrom jax._src.lib import xla_extension_version\n@@ -1724,7 +1725,7 @@ class ExecuteReplicated:\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+ if can_execute_with_token:\nout_bufs, runtime_tokens = (\nself.xla_executable.execute_sharded_on_local_devices_with_tokens(\ninput_bufs))\n"
}
] | Python | Apache License 2.0 | google/jax | Check if XLA Executable has `execute_with_token` before using it
PiperOrigin-RevId: 466470801 |
260,335 | 09.08.2022 19:57:40 | 25,200 | d76754e40eaf8b6ce2ddd8e2922323f2189a0218 | fix type annotation on remat | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -3051,7 +3051,7 @@ def eval_shape(fun: Callable, *args, **kwargs):\ndef checkpoint(fun: Callable, *,\nconcrete: bool = False,\nprevent_cse: bool = True,\n- static_argnums: Union[int, Tuple[int, ...], bool] = (),\n+ static_argnums: Union[int, Tuple[int, ...]] = (),\npolicy: Optional[Callable[..., bool]] = None,\n) -> Callable:\nif concrete:\n"
}
] | Python | Apache License 2.0 | google/jax | fix type annotation on remat |
260,335 | 10.08.2022 08:26:47 | 25,200 | be6f6bfe9fc2eb19573bccb74ac27930838e39bb | set new jax.remat / jax.checkpoint to be on-by-default | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -28,6 +28,9 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n{mod}`jax.example_libraries.stax`.\n* Removed `jax.experimental.optimizers`; it has long been a deprecated alias of\n{mod}`jax.example_libraries.optimizers`.\n+ * {func}`jax.checkpoint`, also known as {func}`jax.remat`, has a new\n+ implementation switched on by default, meaning the old implementation is\n+ deprecated; see [JEP 11830](https://jax.readthedocs.io/en/latest/jep/11830-new-remat-checkpoint.html).\n## jaxlib 0.3.16 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jaxlib-v0.3.15...main).\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jep/index.rst",
"new_path": "docs/jep/index.rst",
"diff": "@@ -43,7 +43,6 @@ Then create a pull request that adds a file named\n9407: Design of Type Promotion Semantics for JAX <9407-type-promotion>\n9419: Jax and Jaxlib versioning <9419-jax-versioning>\n10657: Sequencing side-effects in JAX <10657-sequencing-effects>\n-\n-\n+ 11830: `jax.remat` / `jax.checkpoint` new implementation <11830-new-remat-checkpoint>\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/config.py",
"new_path": "jax/_src/config.py",
"diff": "@@ -878,7 +878,7 @@ config.define_bool_state(\n# TODO(mattjj): set default to True, then remove\nconfig.define_bool_state(\nname='jax_new_checkpoint',\n- default=False,\n+ default=True,\nupgrade=True,\nhelp='Whether to use the new jax.checkpoint implementation.')\n"
}
] | Python | Apache License 2.0 | google/jax | set new jax.remat / jax.checkpoint to be on-by-default |
260,408 | 11.08.2022 15:22:02 | -3,600 | 4ce88ec71f5de75a1c81c6bf5ec3380ee4cf3c74 | Fix bug with integer typed-Gelu
Certain lines in gelu() would round down constants if called with integer types (sqrt_2_over_pi = np.sqrt(2 / np.pi).astype(x.dtype))
Cast the input array to the nearest float-like type to avoid this, as done for trigonometic functions. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/nn/functions.py",
"new_path": "jax/_src/nn/functions.py",
"diff": "@@ -252,6 +252,10 @@ def gelu(x: Array, approximate: bool = True) -> Array:\nx : input array\napproximate: whether to use the approximate or exact formulation.\n\"\"\"\n+\n+ # Promote to nearest float-like dtype.\n+ x = x.astype(dtypes._to_inexact_dtype(x.dtype))\n+\nif approximate:\nsqrt_2_over_pi = np.sqrt(2 / np.pi).astype(x.dtype)\ncdf = 0.5 * (1.0 + jnp.tanh(sqrt_2_over_pi * (x + 0.044715 * (x ** 3))))\n"
}
] | Python | Apache License 2.0 | google/jax | Fix bug with integer typed-Gelu
Certain lines in gelu() would round down constants if called with integer types (sqrt_2_over_pi = np.sqrt(2 / np.pi).astype(x.dtype))
Cast the input array to the nearest float-like type to avoid this, as done for trigonometic functions. |
260,408 | 11.08.2022 15:41:07 | -3,600 | 32b2a8ff006ba7057c9e8922f48fa772a076951d | Update nn_test.py
Add test for fixed integer-type Gelu behaviour. | [
{
"change_type": "MODIFY",
"old_path": "tests/nn_test.py",
"new_path": "tests/nn_test.py",
"diff": "@@ -84,6 +84,11 @@ class NNFunctionsTest(jtu.JaxTestCase):\nval = nn.glu(jnp.array([1.0, 0.0]), axis=0)\nself.assertAllClose(val, jnp.array([0.5]))\n+ def testGeluIntType(self):\n+ val_float = nn.gelu(jnp.array(-1.0))\n+ val_int = nn.gelu(jnp.array(-1))\n+ self.assertAllClose(val_float, val_int)\n+\n@parameterized.parameters(False, True)\ndef testGelu(self, approximate):\ndef gelu_reference(x):\n"
}
] | Python | Apache License 2.0 | google/jax | Update nn_test.py
Add test for fixed integer-type Gelu behaviour. |
260,408 | 11.08.2022 15:46:34 | -3,600 | 5026a810a4e331f38025c66e87500318839d2e0a | Update nn_test.py
Add parameter to sweep over `approximate` kwarg. | [
{
"change_type": "MODIFY",
"old_path": "tests/nn_test.py",
"new_path": "tests/nn_test.py",
"diff": "@@ -84,9 +84,10 @@ class NNFunctionsTest(jtu.JaxTestCase):\nval = nn.glu(jnp.array([1.0, 0.0]), axis=0)\nself.assertAllClose(val, jnp.array([0.5]))\n- def testGeluIntType(self):\n- val_float = nn.gelu(jnp.array(-1.0))\n- val_int = nn.gelu(jnp.array(-1))\n+ @parameterized.parameters(False, True)\n+ def testGeluIntType(self, approximate):\n+ val_float = nn.gelu(jnp.array(-1.0), approximate=approximate)\n+ val_int = nn.gelu(jnp.array(-1), approximate=approximate)\nself.assertAllClose(val_float, val_int)\n@parameterized.parameters(False, True)\n"
}
] | Python | Apache License 2.0 | google/jax | Update nn_test.py
Add parameter to sweep over `approximate` kwarg. |
260,510 | 11.08.2022 15:51:41 | 25,200 | b0309dc33a34473584e723c6d0819d70e3838e69 | Bump libtpu nightly version | [
{
"change_type": "MODIFY",
"old_path": "setup.py",
"new_path": "setup.py",
"diff": "@@ -26,7 +26,7 @@ _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.dev20220722'\n+_libtpu_version = '0.1.dev20220723'\n_dct = {}\nwith open('jax/version.py') as f:\n"
}
] | Python | Apache License 2.0 | google/jax | Bump libtpu nightly version |
260,510 | 12.08.2022 12:39:22 | 25,200 | 88f2b5e86d36fbc9e0dcfba3eab5b56975148c20 | Add functionality for "pure" callbacks
Also avoids using CPP dispatch path when host callbacks are involved | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -548,6 +548,8 @@ def _cpp_jit(\n# No effects in computation\nnot execute.args[5] and\nnot execute.args[6] and\n+ # Has no host callbacks\n+ not execute.args[8] and\n# Not supported: ShardedDeviceArray\nall(device_array.type_is_device_array(x) for x in out_flat) and\n# Not supported: dynamic shapes\n@@ -557,7 +559,7 @@ def _cpp_jit(\n### If we can use the fastpath, we return required info to the caller.\nif use_fastpath:\n(_, xla_executable,\n- _, _, result_handlers, _, _, kept_var_idx) = execute.args\n+ _, _, result_handlers, _, _, kept_var_idx, _) = execute.args\nsticky_device = None\navals = []\nlazy_exprs = [None] * len(result_handlers)\n@@ -2168,6 +2170,7 @@ def _cpp_pmap(\nisinstance(execute[0], pxla.ExecuteReplicated) and\n# TODO(sharadmv): Enable effects in replicated computation\nnot execute[0].has_unordered_effects and\n+ not execute[0].has_host_callbacks and\n# No tracers in the outputs. Checking for ShardedDeviceArray should be\n# sufficient, but we use the more general `DeviceArray`.\nall(isinstance(x, device_array.DeviceArray) for x in out_flat))\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/_src/callback.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 JAX callbacks.\"\"\"\n+import functools\n+\n+from typing import Any, Callable\n+\n+from jax import core\n+from jax import lax\n+from jax import tree_util\n+from jax._src import lib as jaxlib\n+from jax._src import util\n+from jax.interpreters import ad\n+from jax.interpreters import batching\n+from jax.interpreters import mlir\n+import jax.numpy as jnp\n+\n+\n+# `pure_callback_p` is the main primitive for staging out Python pure callbacks.\n+pure_callback_p = core.Primitive(\"pure_callback\")\n+pure_callback_p.multiple_results = True\n+\n+map, unsafe_map = util.safe_map, map\n+\n+\n+@pure_callback_p.def_impl\n+def pure_callback_impl(*args, result_avals, callback: Callable[..., Any]):\n+ del result_avals\n+ return callback(*args)\n+\n+\n+@pure_callback_p.def_abstract_eval\n+def pure_callback_abstract_eval(*avals, callback: Callable[..., Any],\n+ result_avals):\n+ del avals, callback\n+ return result_avals\n+\n+\n+def pure_callback_jvp_rule(*args, **kwargs):\n+ del args, kwargs\n+ raise ValueError(\n+ \"Pure callbacks do not support JVP. \"\n+ \"Please use `jax.custom_jvp` to use callbacks while taking gradients.\")\n+\n+\n+ad.primitive_jvps[pure_callback_p] = pure_callback_jvp_rule\n+\n+\n+def pure_callback_transpose_rule(*args, **kwargs):\n+ del args, kwargs\n+ raise ValueError(\n+ \"Pure callbacks do not support transpose. \"\n+ \"Please use `jax.custom_vjp` to use callbacks while taking gradients.\")\n+\n+ad.primitive_transposes[pure_callback_p] = pure_callback_transpose_rule\n+\n+\n+def pure_callback_batching_rule(args, dims, *, callback, **params):\n+ new_args = []\n+ for arg, dim in zip(args, dims):\n+ new_args.append(jnp.rollaxis(arg, dim))\n+ outvals = lax.map(\n+ functools.partial(pure_callback_p.bind, callback=callback, **params),\n+ *new_args)\n+ return tuple(outvals), (0,) * len(outvals)\n+\n+\n+batching.primitive_batchers[pure_callback_p] = pure_callback_batching_rule\n+\n+\n+def pure_callback_lowering(ctx, *args, callback, **params):\n+\n+ if ctx.module_context.platform == \"TPU\" and jaxlib.version < (0, 3, 15):\n+ raise NotImplementedError(\"Pure callbacks on TPU not supported. \"\n+ \"Please upgrade to a jaxlib >= 0.3.15.\")\n+ if isinstance(ctx.module_context.axis_context,\n+ (mlir.SPMDAxisContext, mlir.ShardingContext)):\n+ raise NotImplementedError(\"Sharding for pure callback not implemented.\")\n+\n+ def _callback(*flat_args):\n+ return tuple(pure_callback_p.impl(*flat_args, callback=callback, **params))\n+\n+ result, _, keepalive = mlir.emit_python_callback(\n+ ctx, _callback, None, list(args), ctx.avals_in, ctx.avals_out, False,\n+ sharding=None)\n+ ctx.module_context.add_keepalive(keepalive)\n+ return result\n+\n+mlir.register_lowering(pure_callback_p, pure_callback_lowering)\n+\n+\n+def pure_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\n+ *args: Any, **kwargs: Any):\n+ \"\"\"Calls a pure Python callback function from staged out JAX programs.\n+\n+ ``pure_callback`` enables calling a Python function in JIT-ed JAX functions.\n+ The input ``callback`` will be passed NumPy arrays in place of JAX arrays and\n+ should also return NumPy arrays. Execution takes place on the CPU host.\n+\n+ The callback is treated as \"pure\" meaning it can be called multiple times when\n+ transformed (for example in a ``vmap`` or ``pmap``), and it can also\n+ potentially be removed from JAX programs via dead-code elimination. Pure\n+ callbacks can also be reordered if data-dependence allows.\n+\n+ When both `pmap` and `vmap`-ed, the pure callback will be called several times\n+ (one on each axis of the map). In the `pmap` case, these calls will happen\n+ across several threads whereas in the `vmap` case, they will happen serially.\n+\n+ Args:\n+ callback: A Python callable. The callable will be passed in NumPy arrays and\n+ should return a PyTree of NumPy arrays that matches\n+ ``result_shape_dtypes``.\n+ result_shape_dtypes: A PyTree of Python objects that have ``shape`` and\n+ ``dtype`` properties that correspond to the shape and dtypes of the\n+ outputs of ``callback``.\n+ *args: The positional arguments to the callback. Must be PyTrees of JAX\n+ types.\n+ **kwargs: The keyword arguments to the callback. Must be PyTrees of JAX\n+ types.\n+\n+ Returns:\n+ The value of ``callback(*args, **kwargs)``.\n+ \"\"\"\n+\n+ def _flat_callback(*flat_args):\n+ args, kwargs = tree_util.tree_unflatten(in_tree, flat_args)\n+ return tree_util.tree_leaves(callback(*args, **kwargs))\n+\n+ flat_args, in_tree = tree_util.tree_flatten((args, kwargs))\n+ result_avals = tree_util.tree_map(\n+ lambda x: core.ShapedArray(x.shape, x.dtype), result_shape_dtypes)\n+ flat_result_avals, out_tree = tree_util.tree_flatten(result_avals)\n+ out_flat = pure_callback_p.bind(\n+ *flat_args, callback=_flat_callback, result_avals=flat_result_avals)\n+ return tree_util.tree_unflatten(out_tree, out_flat)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -738,7 +738,7 @@ def _execute_compiled(name: str, compiled: XlaExecutable,\nresult_handler: Callable,\nhas_unordered_effects: bool,\nordered_effects: List[core.Effect],\n- kept_var_idx, *args):\n+ kept_var_idx, host_callbacks, *args):\ndevice, = compiled.local_devices()\nargs, env = input_handler(args) if input_handler else (args, None)\nin_flat = flatten(device_put(x, device) for i, x in enumerate(args)\n@@ -766,7 +766,7 @@ def _execute_replicated(name: str, compiled: XlaExecutable,\nresult_handler: Callable,\nhas_unordered_effects: bool,\nordered_effects: List[core.Effect],\n- kept_var_idx, *args):\n+ kept_var_idx, host_callbacks, *args):\nif has_unordered_effects or ordered_effects:\n# TODO(sharadmv): support jit-of-pmap with effects\nraise NotImplementedError(\n@@ -965,7 +965,7 @@ class XlaCompiledComputation(stages.XlaExecutable):\nexecute = _execute_compiled if nreps == 1 else _execute_replicated\nunsafe_call = partial(execute, name, compiled, input_handler, buffer_counts, # type: ignore # noqa: F811\nresult_handler, has_unordered_effects,\n- ordered_effects, kept_var_idx)\n+ ordered_effects, kept_var_idx, host_callbacks)\nreturn XlaCompiledComputation(compiled, in_avals, kept_var_idx, unsafe_call,\nkeepalive)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1349,7 +1349,8 @@ class PmapExecutable(stages.XlaExecutable):\nhandle_args = InputsHandler(\ncompiled.local_devices(), in_shardings, input_indices, InputsHandlerMode.pmap)\nexecute_fun = ExecuteReplicated(compiled, pci.backend, handle_args,\n- handle_outs, unordered_effects, keepalive)\n+ handle_outs, unordered_effects, keepalive,\n+ bool(host_callbacks))\nfingerprint = getattr(compiled, \"fingerprint\", None)\nreturn PmapExecutable(compiled, execute_fun, fingerprint, pci.avals)\n@@ -1706,17 +1707,19 @@ def partitioned_sharding_spec(num_partitions: int,\nclass ExecuteReplicated:\n\"\"\"The logic to shard inputs, execute a replicated model, returning outputs.\"\"\"\n__slots__ = ['xla_executable', 'backend', 'in_handler', 'out_handler',\n- 'has_unordered_effects', 'keepalive']\n+ 'has_unordered_effects', 'keepalive', 'has_host_callbacks']\ndef __init__(self, xla_executable, backend, in_handler: InputsHandler,\nout_handler: ResultsHandler,\n- unordered_effects: List[core.Effect], keepalive: Any):\n+ unordered_effects: List[core.Effect], keepalive: Any,\n+ has_host_callbacks: bool):\nself.xla_executable = xla_executable\nself.backend = backend\nself.in_handler = in_handler\nself.out_handler = out_handler\nself.has_unordered_effects = bool(unordered_effects)\nself.keepalive = keepalive\n+ self.has_host_callbacks = has_host_callbacks\n@profiler.annotate_function\ndef __call__(self, *args):\n@@ -2787,7 +2790,8 @@ class MeshExecutable(stages.XlaExecutable):\nhandle_args = InputsHandler(xla_executable.local_devices(), in_shardings,\ninput_indices, InputsHandlerMode.pjit_or_xmap)\nunsafe_call = ExecuteReplicated(xla_executable, backend, handle_args,\n- handle_outs, unordered_effects, keepalive)\n+ handle_outs, unordered_effects, keepalive,\n+ bool(host_callbacks))\nreturn MeshExecutable(xla_executable, unsafe_call, input_avals,\nin_shardings, out_shardings, auto_spmd_lowering)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/python_callback_test.py",
"new_path": "tests/python_callback_test.py",
"diff": "import contextlib\nimport io\nimport textwrap\n+import unittest\nfrom unittest import mock\nfrom typing import Any, Callable, Generator, Sequence\n@@ -23,6 +24,7 @@ import jax\nfrom jax import core\nfrom jax import lax\nfrom jax import tree_util\n+from jax._src import callback as jc\nfrom jax._src import debugging\nfrom jax._src import lib as jaxlib\nfrom jax._src import test_util as jtu\n@@ -455,6 +457,171 @@ class PythonCallbackTest(jtu.JaxTestCase):\nout,\nnp.arange(2 * jax.local_device_count()).reshape([-1, 2]) + 1.)\n+class PurePythonCallbackTest(jtu.JaxTestCase):\n+\n+ def test_simple_pure_callback(self):\n+\n+ @jax.jit\n+ def f(x):\n+ return jc.pure_callback(lambda x: (x * 2.).astype(x.dtype), x, x)\n+ self.assertEqual(f(2.), 4.)\n+\n+ def test_can_dce_pure_callback(self):\n+\n+ if jax.default_backend() == \"tpu\":\n+ raise unittest.SkipTest(\"DCE doesn't currently happen on TPU\")\n+\n+ log = []\n+ def _callback(x):\n+ # Should never happen!\n+ log.append(\"hello world\")\n+ return (x * 2.).astype(x.dtype)\n+\n+ @jax.jit\n+ def f(x):\n+ _ = jc.pure_callback(_callback, x, x)\n+ return x * 2.\n+ _ = f(2.)\n+ self.assertEmpty(log)\n+\n+ def test_can_vmap_pure_callback(self):\n+\n+ @jax.jit\n+ @jax.vmap\n+ def f(x):\n+ return jc.pure_callback(np.sin, x, x)\n+ out = f(jnp.arange(4.))\n+ np.testing.assert_allclose(out, np.sin(np.arange(4.)))\n+\n+ @jax.jit\n+ def g(x):\n+ return jc.pure_callback(np.sin, x, x)\n+ out = jax.vmap(g, in_axes=1)(jnp.arange(8.).reshape((4, 2)))\n+ np.testing.assert_allclose(out, np.sin(np.arange(8.).reshape((4, 2))).T)\n+\n+ def test_can_pmap_pure_callback(self):\n+\n+ @jax.jit\n+ @jax.pmap\n+ def f(x):\n+ return jc.pure_callback(np.sin, x, x)\n+ out = f(jnp.arange(float(jax.local_device_count())))\n+ np.testing.assert_allclose(out, np.sin(np.arange(jax.local_device_count())))\n+\n+ def test_cant_take_grad_of_pure_callback(self):\n+\n+ def sin(x):\n+ return np.sin(x)\n+\n+ @jax.jit\n+ @jax.grad\n+ def f(x):\n+ return jc.pure_callback(sin, x, x)\n+ with self.assertRaisesRegex(\n+ ValueError, \"Pure callbacks do not support JVP.\"):\n+ f(2.)\n+\n+ def test_can_take_grad_of_pure_callback_with_custom_jvp(self):\n+\n+ @jax.custom_jvp\n+ def sin(x):\n+ return jc.pure_callback(np.sin, x, x)\n+\n+ @sin.defjvp\n+ def sin_jvp(xs, ts):\n+ (x,), (t,), = xs, ts\n+ return sin(x), jc.pure_callback(np.cos, x, x) * t\n+\n+ @jax.jit\n+ @jax.grad\n+ def f(x):\n+ return sin(x)\n+ out = f(2.)\n+ np.testing.assert_allclose(out, jnp.cos(2.))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_cond(self):\n+\n+ def _callback1(x):\n+ return x + 1.\n+\n+ def _callback2(x):\n+ return x - 1.\n+\n+ @jax.jit\n+ def f(pred, x):\n+\n+ def true_fun(x):\n+ return jc.pure_callback(_callback1, x, x)\n+\n+ def false_fun(x):\n+ return jc.pure_callback(_callback2, x, x)\n+\n+ return lax.cond(pred, true_fun, false_fun, x)\n+\n+ out = f(True, jnp.ones(2))\n+ np.testing.assert_allclose(out, jnp.ones(2) * 2.)\n+ out = f(False, jnp.ones(2))\n+ np.testing.assert_allclose(out, jnp.zeros(2))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_scan(self):\n+\n+ def _callback(x):\n+ return x + 1.\n+\n+ @jax.jit\n+ def f(x):\n+\n+ def body(x, _):\n+ x = jc.pure_callback(_callback, x, x)\n+ return x, ()\n+\n+ return lax.scan(body, x, jnp.arange(10))[0]\n+\n+ out = f(jnp.arange(2.))\n+ np.testing.assert_allclose(out, jnp.arange(2.) + 10.)\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_while_loop(self):\n+\n+ def _cond_callback(x):\n+ return np.any(x < 10)\n+\n+ def _callback(x):\n+ return (x + 1.).astype(x.dtype)\n+\n+ @jax.jit\n+ def f(x):\n+\n+ def cond(x):\n+ return jc.pure_callback(\n+ _cond_callback, jax.ShapeDtypeStruct((), np.bool_), x)\n+\n+ def body(x):\n+ return jc.pure_callback(_callback, x, x)\n+\n+ return lax.while_loop(cond, body, x)\n+\n+ out = f(jnp.arange(5.))\n+ np.testing.assert_allclose(out, jnp.arange(10., 15.))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_of_pmap(self):\n+\n+ def _callback(x):\n+ return x + 1.\n+\n+ @jax.pmap\n+ def f(x):\n+ return jc.pure_callback(_callback, x, x)\n+\n+ out = f(\n+ jnp.arange(2 * jax.local_device_count(),\n+ dtype=jnp.float32).reshape([-1, 2]))\n+ np.testing.assert_allclose(\n+ out,\n+ np.arange(2 * jax.local_device_count()).reshape([-1, 2]) + 1.)\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add functionality for "pure" callbacks
Also avoids using CPP dispatch path when host callbacks are involved
PiperOrigin-RevId: 467270949 |
260,631 | 12.08.2022 14:42:03 | 25,200 | 56440c35a2c7d7cdc61e3dbff18f26d558902207 | Pass host callbacks to `backend.compile_replicated` | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1337,8 +1337,8 @@ class PmapExecutable(stages.XlaExecutable):\nif hasattr(pci.backend, \"compile_replicated\"):\nexecute_fun = pci.backend.compile_replicated(\n- xla_computation, compile_options, pci.avals, input_indices,\n- in_shardings, InputsHandlerMode.pmap, handle_outs)\n+ xla_computation, compile_options, host_callbacks, pci.avals,\n+ input_indices, in_shardings, InputsHandlerMode.pmap, handle_outs)\n# TODO(frostig): need `compile_replicated` to give us the XLA executable\nreturn PmapExecutable(None, execute_fun, None, pci.avals)\n@@ -2763,9 +2763,11 @@ class MeshExecutable(stages.XlaExecutable):\nglobal_in_avals, in_shardings, in_is_global) # type: ignore\nhandle_outs = global_avals_to_results_handler(\nglobal_out_avals, out_shardings) # type: ignore # arg-type\n- unsafe_call = backend.compile_replicated(\n- computation, compile_options, input_avals, input_indices,\n- in_shardings, InputsHandlerMode.pjit_or_xmap, handle_outs)\n+ unsafe_call = backend.compile_replicated(computation, compile_options,\n+ host_callbacks, input_avals,\n+ input_indices, in_shardings,\n+ InputsHandlerMode.pjit_or_xmap,\n+ handle_outs)\nxla_executable = None\nelse:\nwith dispatch.log_elapsed_time(f\"Finished XLA compilation of {name} \"\n"
}
] | Python | Apache License 2.0 | google/jax | Pass host callbacks to `backend.compile_replicated`
PiperOrigin-RevId: 467299712 |
260,510 | 12.08.2022 19:48:40 | 25,200 | 7cd81ca1a8118a821036c5daad073066da94515d | Allow debug prints in staged out custom derivative functions | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/custom_derivatives.py",
"new_path": "jax/_src/custom_derivatives.py",
"diff": "from functools import update_wrapper, reduce, partial\nimport inspect\nimport operator as op\n-from typing import (Callable, Generic, Optional, Sequence, Tuple, List, TypeVar,\n- Any)\n+from typing import (Any, Callable, Generic, List, Optional, Sequence, Set,\n+ Tuple, TypeVar)\nfrom jax import core\nfrom jax import linear_util as lu\n@@ -320,6 +320,8 @@ def _apply_todos(todos, outs):\nouts = map(core.full_lower, todos_list.pop()(outs))\nreturn outs\n+\n+allowed_effects: Set[core.Effect] = set()\ncustom_jvp_call_p = CustomJVPCallPrimitive('custom_jvp_call')\n@@ -329,8 +331,11 @@ def _custom_jvp_call_jaxpr_impl(*args, fun_jaxpr: core.ClosedJaxpr, **params):\ndef _custom_jvp_call_jaxpr_abstract_eval(*args, fun_jaxpr: core.ClosedJaxpr, **params):\ndel args, params\n- if fun_jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `custom_jvp`.')\n+ disallowed_effects = {eff for eff in fun_jaxpr.effects if eff not in\n+ allowed_effects}\n+ if disallowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `custom_jvp`: {disallowed_effects}')\nreturn fun_jaxpr.out_avals, fun_jaxpr.effects\ncustom_jvp_call_jaxpr_p = core.AxisPrimitive('custom_jvp_call_jaxpr')\n@@ -690,8 +695,11 @@ def _custom_vjp_call_jaxpr_impl(*args, fun_jaxpr, **_):\nreturn core.jaxpr_as_fun(fun_jaxpr)(*args)\ndef _custom_vjp_call_jaxpr_abstract_eval(*_, fun_jaxpr, **__):\n- if fun_jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `custom_vjp`.')\n+ disallowed_effects = {eff for eff in fun_jaxpr.effects if eff not in\n+ allowed_effects}\n+ if disallowed_effects:\n+ raise NotImplementedError(\n+ f'Effects not supported in `custom_vjp`: {disallowed_effects}')\nreturn fun_jaxpr.out_avals, fun_jaxpr.effects\ncustom_vjp_call_jaxpr_p = core.AxisPrimitive('custom_vjp_call_jaxpr')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/debugging.py",
"new_path": "jax/_src/debugging.py",
"diff": "@@ -23,6 +23,7 @@ from jax import core\nfrom jax import tree_util\nfrom jax import lax\nfrom jax._src import ad_checkpoint\n+from jax._src import custom_derivatives\nfrom jax._src import lib as jaxlib\nfrom jax._src import util\nfrom jax.interpreters import ad\n@@ -42,6 +43,8 @@ lcf.allowed_effects.add(DebugEffect.PRINT)\nlcf.allowed_effects.add(DebugEffect.ORDERED_PRINT)\nad_checkpoint.remat_allowed_effects.add(DebugEffect.PRINT)\nad_checkpoint.remat_allowed_effects.add(DebugEffect.ORDERED_PRINT)\n+custom_derivatives.allowed_effects.add(DebugEffect.PRINT)\n+custom_derivatives.allowed_effects.add(DebugEffect.ORDERED_PRINT)\n# `debug_callback_p` is the main primitive for staging out Python callbacks.\ndebug_callback_p = core.Primitive('debug_callback')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1914,8 +1914,6 @@ class DynamicJaxprTrace(core.Trace):\nin_avals = [t.aval for t in tracers]\nwith core.new_sublevel():\nfun_jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, self.main, in_avals)\n- if fun_jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `custom_jvp`.')\nclosed_fun_jaxpr = core.ClosedJaxpr(convert_constvars_jaxpr(fun_jaxpr), ())\nmain_ = ref(self.main)\njvp_jaxpr_thunk = _memoize(\n@@ -1940,8 +1938,6 @@ class DynamicJaxprTrace(core.Trace):\nin_avals = [t.aval for t in tracers]\nwith core.new_sublevel():\nfun_jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, self.main, in_avals)\n- if fun_jaxpr.effects:\n- raise NotImplementedError('Effects not supported in `custom_vjp`.')\nclosed_fun_jaxpr = core.ClosedJaxpr(convert_constvars_jaxpr(fun_jaxpr), ())\nmain_ = ref(self.main)\nfwd_jaxpr_thunk = _memoize(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/debugging_primitives_test.py",
"new_path": "tests/debugging_primitives_test.py",
"diff": "@@ -401,6 +401,64 @@ class DebugPrintTransformationTest(jtu.JaxTestCase):\n# print.\nself.assertEqual(output(), \"y: 3.0, z: 6.0\\n\" * 2)\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debug_print_in_staged_out_custom_jvp(self):\n+\n+ @jax.jit\n+ def f(x):\n+ @jax.custom_jvp\n+ def g(x):\n+ debug_print(\"hello: {x}\", x=x)\n+ return x\n+ def g_jvp(primals, tangents):\n+ (x,), (t,) = primals, tangents\n+ debug_print(\"goodbye: {x} {t}\", x=x, t=t)\n+ return x, t\n+ g.defjvp(g_jvp)\n+ return g(x)\n+\n+ with capture_stdout() as output:\n+ f(2.)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"hello: 2.0\\n\")\n+\n+ with capture_stdout() as output:\n+ jax.jvp(f, (2.,), (3.,))\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"goodbye: 2.0 3.0\\n\")\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_debug_print_in_staged_out_custom_vjp(self):\n+\n+ @jax.jit\n+ def f(x):\n+ @jax.custom_vjp\n+ def g(x):\n+ debug_print(\"hello: {x}\", x=x)\n+ return x\n+ def g_fwd(x):\n+ debug_print(\"hello fwd: {x}\", x=x)\n+ return x, x\n+ def g_bwd(x, g):\n+ debug_print(\"hello bwd: {x} {g}\", x=x, g=g)\n+ return (g,)\n+ g.defvjp(fwd=g_fwd, bwd=g_bwd)\n+ return g(x)\n+\n+ with capture_stdout() as output:\n+ f(2.)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"hello: 2.0\\n\")\n+\n+ with capture_stdout() as output:\n+ _, f_vjp = jax.vjp(f, 2.)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"hello fwd: 2.0\\n\")\n+\n+ with capture_stdout() as output:\n+ f_vjp(3.0)\n+ jax.effects_barrier()\n+ self.assertEqual(output(), \"hello bwd: 2.0 3.0\\n\")\nclass DebugPrintControlFlowTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Allow debug prints in staged out custom derivative functions
PiperOrigin-RevId: 467344265 |
260,335 | 11.08.2022 19:39:50 | 25,200 | 42dd7cac43fd5f971ed314c0b9d8817dfbc2273b | simplify slicing jaxprs a little | [
{
"change_type": "MODIFY",
"old_path": "benchmarks/api_benchmark.py",
"new_path": "benchmarks/api_benchmark.py",
"diff": "@@ -539,5 +539,13 @@ def bench_remat_eager_retracing_overheads_static_argnums(state):\ny.block_until_ready()\n+@google_benchmark.register\n+@google_benchmark.option.unit(google_benchmark.kMillisecond)\n+def bench_slicing_compilation(state):\n+ x = jnp.arange(3)\n+ while state:\n+ jax.jit(lambda x: (x[0], x[1], x[2])).lower(x).compile()\n+\n+\nif __name__ == \"__main__\":\ngoogle_benchmark.main()\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/slicing.py",
"new_path": "jax/_src/lax/slicing.py",
"diff": "@@ -50,6 +50,8 @@ Shape = core.Shape\nmap, unsafe_map = safe_map, map\nzip, unsafe_zip = safe_zip, zip\n+_dtype = partial(dtypes.dtype, canonicalize=True)\n+\ndef slice(operand: Array, start_indices: Sequence[int],\nlimit_indices: Sequence[int],\n@@ -263,7 +265,7 @@ def gather(operand: Array, start_indices: Array,\nparsed_mode = GatherScatterMode.from_any(mode)\nif parsed_mode == GatherScatterMode.FILL_OR_DROP:\nif fill_value is None:\n- dtype = lax._dtype(operand)\n+ dtype = _dtype(operand)\nif dtypes.issubdtype(dtype, np.inexact):\nfill_value = np.nan\nelif dtypes.issubdtype(dtype, np.signedinteger):\n@@ -2042,14 +2044,15 @@ def _dynamic_slice_indices(operand, start_indices: Any):\nif start_indices.ndim != 1:\nraise ValueError(\"Slice indices must be a 1D sequence, got {}\"\n.format(start_indices.shape))\n- start_indices = [i for i in start_indices]\n- return [np.asarray(i + d if i < 0 else i, lax._dtype(i))\n- if isinstance(i, (int, np.integer)) and core.is_constant_dim(d)\n- else lax.select(\n- lax.lt(i, lax._const(i, 0)),\n- lax.add(i, lax.convert_element_type(core.dimension_as_value(d), lax._dtype(i))),\n- i)\n- for i, d in zip(start_indices, operand.shape)]\n+ start_indices = list(start_indices)\n+ result = []\n+ for i, d in zip(start_indices, operand.shape):\n+ if isinstance(i, (int, np.integer)) and core.is_constant_dim(d):\n+ result.append(lax.convert_element_type(i + d, _dtype(i)) if i < 0 else i)\n+ else:\n+ d = lax.convert_element_type(core.dimension_as_value(d), _dtype(i))\n+ result.append(lax.select(i < 0, i + d, i))\n+ return result\n# TODO(mattjj): getslice is a prototype for dynamic shapes, revise or remove it\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3485,10 +3485,10 @@ def _normalize_index(index, axis_size):\nelse:\naxis_size_val = lax.convert_element_type(core.dimension_as_value(axis_size),\n_dtype(index))\n- return lax.select(\n- lax.lt(index, _lax_const(index, 0)),\n- lax.add(index, axis_size_val),\n- index)\n+ if isinstance(index, (int, np.integer)):\n+ return lax.add(index, axis_size_val) if index < 0 else index\n+ else:\n+ return lax.select(index < 0, lax.add(index, axis_size_val), index)\nTAKE_ALONG_AXIS_DOC = \"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | simplify slicing jaxprs a little
Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com> |
260,335 | 03.08.2022 16:02:29 | 25,200 | 5310515c80f4d786d7067d0c5cafb2c96cd502f9 | Initial implementation of eager pmap | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -113,12 +113,12 @@ zip, unsafe_zip = safe_zip, zip\nFLAGS = flags.FLAGS\nflags.DEFINE_bool(\n- \"experimental_cpp_jit\", bool_env(\"JAX_CPP_JIT\", True),\n+ \"experimental_cpp_jit\", bool_env(\"JAX_CPP_JIT\", False),\n\"A flag enabling the C++ jax.jit fast path.\"\n\"Set this to `False` only if it crashes otherwise and report \"\n\"the error to the jax-team.\")\nflags.DEFINE_bool(\n- \"experimental_cpp_pmap\", bool_env(\"JAX_CPP_PMAP\", True),\n+ \"experimental_cpp_pmap\", bool_env(\"JAX_CPP_PMAP\", False),\n\"A flag enabling the C++ jax.pmap fast path. Until the default \"\n\"is switched to True, the feature is not supported and possibly broken \"\n\"(e.g. it may use unreleased code from jaxlib.\")\n@@ -660,7 +660,7 @@ def _jit_lower(fun, static_argnums, static_argnames, device, backend,\n@contextmanager\n-def disable_jit():\n+def disable_jit(disable: bool = True):\n\"\"\"Context manager that disables :py:func:`jit` behavior under its dynamic context.\nFor debugging it is useful to have a mechanism that disables :py:func:`jit`\n@@ -704,7 +704,7 @@ def disable_jit():\nValue of y is [2 4 6]\n[5 7 9]\n\"\"\"\n- with _disable_jit(True):\n+ with _disable_jit(disable):\nyield\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -37,13 +37,15 @@ import dataclasses\nfrom functools import partial, lru_cache\nimport itertools as it\nimport operator as op\n+import sys\nimport threading\n+import types\nfrom typing import (Any, Callable, Dict, List, NamedTuple, Optional, FrozenSet,\nSequence, Set, Tuple, Type, Union, Iterable, Mapping, cast,\nTYPE_CHECKING)\n-import sys\nfrom absl import logging\n+\nimport numpy as np\nimport jax\n@@ -61,6 +63,7 @@ from jax.tree_util import tree_flatten, tree_map\nfrom jax._src import abstract_arrays\nfrom jax._src import api_util\nfrom jax._src import device_array\n+from jax._src import dtypes\nfrom jax._src import source_info_util\nfrom jax._src import util\nfrom jax._src import dispatch\n@@ -77,7 +80,8 @@ from jax._src.lib.mlir import ir\nfrom jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.util import (unzip3, prod, safe_map, safe_zip, partition_list,\nnew_name_stack, wrap_name, assert_unreachable,\n- tuple_insert, tuple_delete, distributed_debug_log)\n+ tuple_insert, tuple_delete, distributed_debug_log,\n+ split_dict, unzip2)\nif TYPE_CHECKING:\nfrom jax.experimental.sharding import MeshPspecSharding, XLACompatibleSharding\n@@ -903,6 +907,13 @@ def xla_pmap_impl(fun: lu.WrappedFun, *args,\nout_axes_thunk: Callable[[], Sequence[Optional[int]]],\ndonated_invars: Sequence[bool],\nglobal_arg_shapes: Sequence[Optional[Tuple[int, ...]]]):\n+ if config.jax_disable_jit:\n+ return _emap_impl(fun, *args, backend=backend, axis_name=axis_name,\n+ axis_size=axis_size, global_axis_size=global_axis_size,\n+ devices=devices, name=name, in_axes=in_axes,\n+ out_axes_thunk=out_axes_thunk,\n+ donated_invars=donated_invars,\n+ global_arg_shapes=global_arg_shapes)\nabstract_args = unsafe_map(xla.abstractify, args)\ncompiled_fun, fingerprint = parallel_callable(\nfun, backend, axis_name, axis_size, global_axis_size, devices, name,\n@@ -918,6 +929,230 @@ def xla_pmap_impl(fun: lu.WrappedFun, *args,\n(\"fingerprint\", fingerprint))\nreturn compiled_fun(*args)\n+def _emap_impl(fun: lu.WrappedFun, *args,\n+ backend: Optional[str],\n+ axis_name: core.AxisName,\n+ axis_size: int,\n+ global_axis_size: Optional[int],\n+ devices: Optional[Sequence[Any]],\n+ name: str,\n+ in_axes: Sequence[Optional[int]],\n+ out_axes_thunk: Callable[[], Sequence[Optional[int]]],\n+ donated_invars: Sequence[bool],\n+ global_arg_shapes: Sequence[Optional[Tuple[int, ...]]]):\n+ if global_axis_size is not None: raise NotImplementedError\n+ del global_axis_size, global_arg_shapes\n+ if devices is not None:\n+ if len(devices) == 0:\n+ raise ValueError(\"'devices' argument to pmap must be non-empty, or None.\")\n+ if len(devices) != axis_size:\n+ raise ValueError(\n+ f\"Leading axis size of input to pmapped function must equal the \"\n+ f\"number of local devices passed to pmap. Got axis_size=\"\n+ f\"{axis_size}, num_local_devices={len(devices)}.\")\n+ else:\n+ devices = xb.devices(backend=backend)[:axis_size]\n+ if len(devices) != axis_size:\n+ msg = (\"compiling computation that requires {} logical devices, but only {} XLA \"\n+ \"devices are available (num_replicas={}, num_partitions={})\")\n+ raise ValueError(msg.format(axis_size,\n+ xb.device_count(backend),\n+ None,\n+ None))\n+ sharded_args = []\n+ shard_axes = []\n+ for arg, in_axis in zip(args, in_axes):\n+ if in_axis == 0:\n+ sharded_args.append(jax.device_put_sharded(list(arg), devices))\n+ shard_axes.append({axis_name: 0})\n+ elif in_axis is None:\n+ sharded_args.append(arg)\n+ shard_axes.append({})\n+ else:\n+ perm = list(range(arg.ndim))\n+ a = perm.pop(in_axis)\n+ perm.insert(0, a)\n+ new_arg = arg.transpose(perm)\n+ sharded_args.append(jax.device_put_sharded(list(new_arg), devices))\n+ shard_axes.append({axis_name: 0})\n+ with core.new_base_main(MapTrace) as main:\n+ with core.new_sublevel(), core.extend_axis_env(axis_name, axis_size, main):\n+ t = main.with_cur_sublevel()\n+ tracers = [\n+ MapTracer(t, arg, s) for arg, s in zip(sharded_args, shard_axes)]\n+ ans = fun.call_wrapped(*tracers)\n+ out_tracers = map(t.full_raise, ans)\n+ outvals, out_axes_src = unzip2((t.val, t.shard_axes) for t in out_tracers)\n+ del main\n+ out_axes = out_axes_thunk()\n+\n+ # This next bit is like matchaxis in batching.py (for the end of a vmap)\n+ new_outvals = []\n+ for out_axis_src, out_axis, outval in zip(out_axes_src, out_axes, outvals):\n+ if out_axis is None:\n+ if src := out_axis_src.get(axis_name) is None:\n+ new_outvals.append(outval)\n+ else:\n+ idx = [slice(None)] * len(outval.shape)\n+ idx[src] = 0\n+ new_outvals.append(outval[tuple(idx)])\n+ elif out_axis == 0 == out_axis_src.get(axis_name):\n+ new_outvals.append(outval)\n+ else:\n+ # TODO maybe just a transpose/broadcast here?\n+ with jax._src.config.disable_jit(False):\n+ new_outvals.append(\n+ jax.pmap(lambda _, x: x, in_axes=(0, out_axis_src.get(axis_name)),\n+ out_axes=out_axis)(np.arange(axis_size), outval))\n+ return new_outvals\n+\n+\n+def _map_indices_to_map_schedule(idx: Tuple[Optional[int], ...]):\n+ return tuple(None if i is None else i - sum(j is not None and j < i for j in idx[:l]) for l, i in enumerate(idx))\n+\n+class MapTrace(core.Trace):\n+\n+ def _get_frames(self):\n+ frames = [f for f in core.thread_local_state.trace_state.axis_env\n+ if f.main_trace is self.main]\n+ return frames\n+\n+ def pure(self, val):\n+ return MapTracer(self, val, {})\n+\n+ def sublift(self, tracer):\n+ return MapTracer(self, tracer.val, tracer.shard_axes)\n+\n+ def process_primitive(self, primitive, tracers, params):\n+ vals = [t.val for t in tracers]\n+ names = [f.name for f in self._get_frames()]\n+ f = lambda *args: primitive.bind(*args, **params)\n+ used_names = []\n+ all_axes = []\n+ for t in tracers:\n+ arg_axes = tuple(t.shard_axes.get(name, None) for name in names)\n+ arg_axes = _map_indices_to_map_schedule(arg_axes)\n+ all_axes.append(arg_axes)\n+ for i, name in reversed(list(enumerate(names))):\n+ in_axes = tuple(arg_axis[i] for arg_axis in all_axes)\n+ if any(in_axis is not None for in_axis in in_axes):\n+ f = jax.pmap(f, in_axes=in_axes, axis_name=name)\n+ used_names.append(name)\n+ with core.eval_context(), jax._src.config.disable_jit(False):\n+ outvals = f(*vals)\n+ out_shard_axes = {name: i for i, name in enumerate(reversed(used_names))}\n+ if primitive.multiple_results:\n+ return [MapTracer(self, val, out_shard_axes) for val in outvals]\n+ return MapTracer(self, outvals, out_shard_axes)\n+\n+ def process_call(self, call_primitive, fun, tracers, params):\n+ if call_primitive is not xla.xla_call_p: raise NotImplementedError\n+ fake_primitive = types.SimpleNamespace(\n+ multiple_results=True, bind=partial(call_primitive.bind, fun))\n+ return self.process_primitive(fake_primitive, tracers, params)\n+\n+ def process_map(self, call_primitive, fun, tracers, params):\n+ if params['devices'] is not None:\n+ raise ValueError(\"Nested pmap with explicit devices argument.\")\n+ if config.jax_disable_jit:\n+ axis_name, in_axes, out_axes_thunk, axis_size = (params[\"axis_name\"],\n+ params[\"in_axes\"], params[\"out_axes_thunk\"], params[\"axis_size\"])\n+ invals = [t.val for t in tracers]\n+ shard_axes_src = [t.shard_axes for t in tracers]\n+ shard_axes = []\n+ for inval, in_axis, shard_axis_src in zip(invals, in_axes, shard_axes_src):\n+ new_shard_axis_src = dict(shard_axis_src)\n+ if in_axis is not None:\n+ idx = [i for i in range(inval.ndim) if i not in shard_axis_src.values()]\n+ new_idx = idx[in_axis]\n+ new_shard_axis_src = {axis_name: new_idx, **shard_axis_src}\n+ shard_axes.append(new_shard_axis_src)\n+ with core.new_sublevel(), core.extend_axis_env(axis_name, axis_size, self.main):\n+ t = self.main.with_cur_sublevel()\n+ in_tracers = [MapTracer(t, val, shard_axis) for val, shard_axis in\n+ zip(invals, shard_axes)]\n+ ans = fun.call_wrapped(*in_tracers)\n+ out_axes_dest = out_axes_thunk()\n+ out_tracers = map(t.full_raise, ans)\n+ outvals, shard_axes_src = util.unzip2([(t.val, t.shard_axes) for t in\n+ out_tracers])\n+ new_out_tracers = map(\n+ partial(self._make_output_tracer, axis_name, axis_size), outvals,\n+ shard_axes_src, out_axes_dest)\n+ return new_out_tracers\n+ else:\n+ fake_primitive = types.SimpleNamespace(\n+ multiple_results=True, bind=partial(call_primitive.bind, fun))\n+ return self.process_primitive(fake_primitive, tracers, params)\n+\n+ def _make_output_tracer(self, axis_name, axis_size, val, shard_axis_src,\n+ dst_annotation):\n+ shard_axis_out = dict(shard_axis_src)\n+ src = shard_axis_out.pop(axis_name, None)\n+ dst = annotation_to_flat(np.ndim(val), shard_axis_out.values(),\n+ src, dst_annotation)\n+ with core.eval_context():\n+ if src == dst:\n+ outval = val\n+ elif type(src) == type(dst) == int:\n+ outval = batching.moveaxis(val, src, dst)\n+ shard_axis_out = moveaxis(np.ndim(val), shard_axis_src, src, dst)\n+ elif src is None and dst is not None:\n+ outval = batching.broadcast(val, axis_size, dst)\n+ shard_axis_out = {n: d + (dst <= d) for n, d in shard_axis_out.items()}\n+ else:\n+ assert False\n+ return MapTracer(self, outval, shard_axis_out)\n+\n+ def process_axis_index(self, frame):\n+ assert frame.size is not None\n+ with core.eval_context():\n+ range = jax.lax.iota(np.int32, frame.size)\n+ return MapTracer(self, range, {frame.name: 0})\n+\n+def annotation_to_flat(ndim: int, mapped_axes: Sequence[int],\n+ src_flat: Optional[int], dst_annotation: Optional[int]\n+ ) -> Optional[int]:\n+ if dst_annotation is None:\n+ return None\n+ ndim_ = ndim - len(mapped_axes) + (src_flat is None)\n+ dst_annotation = batching.canonicalize_axis(dst_annotation, ndim_)\n+ idx = [i for i in range(ndim + (src_flat is None)) if i not in mapped_axes]\n+ out = idx[dst_annotation]\n+ return out\n+\n+def moveaxis(ndim: int, shard_axes: Dict[core.AxisName, int],\n+ src: int, dst: int):\n+ lst: List[Optional[core.AxisName]] = [None] * ndim\n+ for k, v in shard_axes.items():\n+ lst[v] = k\n+ name = lst.pop(src)\n+ lst.insert(dst - (src < dst), name)\n+ return {name: i for i, name in enumerate(lst) if name is not None}\n+\n+class MapTracer(core.Tracer):\n+ __slots__ = [\"val\", \"shard_axes\"]\n+\n+ def __init__(self, trace: MapTrace, val, shard_axes: Dict[core.AxisName, int]):\n+ self._trace = trace\n+ self.val = val\n+ self.shard_axes = shard_axes\n+ assert all(val < self.val.ndim for val in self.shard_axes.values())\n+\n+ @property\n+ def aval(self):\n+ aval = xla.abstractify(self.val)\n+ shard_axes = dict(self.shard_axes)\n+ for axis_idx in sorted(shard_axes.values())[::-1]:\n+ aval = core.mapped_aval(aval.shape[axis_idx], axis_idx, aval)\n+ return aval\n+\n+ def full_lower(self):\n+ return self\n+\n+ def __str__(self):\n+ named_axes = [f\"{k}={v}\" for k, v in self.shard_axes.items()]\n+ return f\"{self.val}{{{','.join(named_axes)}}}\"\n@lu.cache\ndef parallel_callable(fun: lu.WrappedFun,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "matt.py",
"diff": "+import pdb, sys, traceback\n+def info(type, value, tb):\n+ traceback.print_exception(type, value, tb)\n+ pdb.pm()\n+sys.excepthook = info\n+\n+import os\n+import functools\n+import re\n+\n+import jax\n+import jax.numpy as jnp\n+from jax.config import config\n+import numpy as np\n+\n+config.update(\"jax_new_checkpoint\", True)\n+config.update(\"jax_traceback_filtering\", \"off\")\n+config.update(\"jax_platform_name\", \"cpu\")\n+\n+def set_host_device_count(n):\n+ xla_flags = os.getenv(\"XLA_FLAGS\", \"\")\n+ xla_flags = re.sub(\n+ r\"--xla_force_host_platform_device_count=\\S+\", \"\", xla_flags\n+ ).split()\n+ os.environ[\"XLA_FLAGS\"] = \" \".join(\n+ [\"--xla_force_host_platform_device_count={}\".format(n)] + xla_flags\n+ )\n+\n+set_host_device_count(8)\n+\n+# @functools.partial(jax.pmap, axis_name=\"foo\")\n+# def f(x):\n+# def cond(i):\n+# return i < 10\n+# def body(i):\n+# return i + 1\n+# return jax.lax.while_loop(cond, body, x)\n+\n+# @functools.partial(jax.pmap, axis_name=\"foo\")\n+# def f(x):\n+# def cond(i):\n+# return i < 10\n+# def body(i):\n+# return i + 1\n+# return jax.lax.while_loop(cond, body, x)\n+\n+# print(f(jnp.arange(4.)))\n+\n+# with jax.disable_jit():\n+# print(f(jnp.arange(4.)))\n+\n+\n+# @jax.pmap\n+# def g(x):\n+# with jax._src.config.disable_jit(False):\n+# return jax.jit(jnp.sin)(x)\n+\n+# print(g(jnp.arange(4.)))\n+\n+# with jax.disable_jit():\n+# print(g(jnp.arange(4.)))\n+\n+# @functools.partial(jax.pmap, in_axes=(0, None, 0, None), axis_name='i')\n+# @functools.partial(jax.pmap, in_axes=(None, 0, 0, None), axis_name='j')\n+# def f(x, y, z, w):\n+# return jax.lax.axis_index(['i', 'j']) + x * y + z + w\n+\n+# print(f(jnp.arange(4.), jnp.arange(2.), jnp.arange(8.).reshape((4, 2)), 100.))\n+\n+# with jax.disable_jit():\n+# print(f(jnp.arange(4.), jnp.arange(2.), jnp.arange(8.).reshape((4, 2)), 100.))\n+\n+device_count = jax.device_count()\n+\n+# @functools.partial(jax.pmap, axis_name='i')\n+# def f(x):\n+# @functools.partial(jax.pmap, axis_name='j')\n+# def g(y):\n+# a = jax.lax.psum(1, 'i')\n+# b = jax.lax.psum(1, 'j')\n+# c = jax.lax.psum(1, ('i', 'j'))\n+# return a, b, c\n+# return g(x)\n+\n+# import numpy as np\n+# shape = (device_count, 1, 4)\n+# x = jnp.arange(np.prod(shape)).reshape(shape)\n+# a, b, c = f(x)\n+# print(a)\n+# print(b)\n+# print(c)\n+\n+# with jax.disable_jit():\n+# a, b, c = f(x)\n+# print(a)\n+# print(b)\n+# print(c)\n+\n+# f = lambda axis: jax.pmap(jax.pmap(lambda x: x + jax.lax.axis_index(axis), 'j'), 'i')\n+# x = jnp.ones((2, 2), dtype='int32')\n+# print(f('i')(x))\n+# print(f('j')(x))\n+\n+# with jax.disable_jit():\n+# print(f('i')(x))\n+ # print(f('j')(x))\n+\n+\n+# def f(key):\n+# key = jax.random.fold_in(key, jax.lax.axis_index('i'))\n+# return jax.random.bernoulli(key, p=0.5)\n+\n+# keys = jax.random.split(jax.random.PRNGKey(0), len(jax.devices()))\n+\n+# print(jax.pmap(jax.remat(f), axis_name='i')(keys))\n+\n+# with jax.disable_jit():\n+# print(jax.pmap(jax.remat(f), axis_name='i')(keys))\n+\n+\n+# jax.pmap(lambda x: x)(jnp.zeros(jax.device_count() + 1))\n+# with jax.disable_jit():\n+# jax.pmap(lambda x: x)(jnp.zeros(jax.device_count() + 1))\n+\n+# jax.pmap(lambda x: x)(jnp.zeros(jax.device_count() + 1))\n+# with jax.disable_jit():\n+# jax.pmap(jax.pmap(jnp.square))(jnp.arange(16).reshape((4, 4)))\n+\n+# f = jax.pmap(lambda x: jax.pmap(lambda x: x)(x))\n+# x = jnp.ones((jax.device_count(), 2, 10))\n+# f(x)\n+# with jax.disable_jit():\n+# print(f(x))\n+\n+f = jax.pmap(jax.pmap(lambda x: 3))\n+shape = (2, jax.device_count() // 2, 3)\n+x = jnp.arange(np.prod(shape)).reshape(shape)\n+print(f(x))\n+with jax.disable_jit():\n+ print(f(x))\n+# TODO:\n+# * [x] process_call\n+# * jit-of-emap = pmap (already, b/c we're only changing the pmap impl)\n+# * emap-of-jit = our processs_call rule should act same as initial style HOPs\n+# * emap-of-core.call = do a subtrace like thing where we turn around and stay\n+# in python\n+# * [ ] collectives\n+# * [ ] testing\n+# * [ ] nesting (process_map, sublift, etc)\n+# * [ ] shadowing of names\n+\n+# * delete process_call and core.call, just have an xla_call rule\n+# * no call updaters!\n+# * blocked on delete old remat\n+# * first just make xla_call have its own rule\n+# * then make it INITIAL STYLE\n+# * make it take closed jaxprs, so we can delete core.closed_call\n+# * delete all updaters\n+\n+\n+\n+\n+\n+\n+# brainstorming process_map\n+ # assert map_primitive is xla_pmap_p\n+ # backend, axis_size, axis_name = (\n+ # params['backend'], params['axis_size'], params['axis_name'])\n+ # if config.jax_disable_jit:\n+ # shape = [f.size for f in self._get_frames()]\n+ # devices = xb.devices(backend=backend)[:prod(shape) * axis_size]\n+ # breakpoint()\n+ # # def reshard(x: jnp.ndarray, devices: Array[devices]):\n+ # # assert x.ndim == devices.ndim\n+ # # e.g . x.shape = (4, 3, 2)\n+ # # devices.shape = (4, 1, 2)\n+ # # reshard(x, devices.reshape(4, 1, 2))\n+ # sharded_args = [jax.device_put_sharded(list(x), devices) for x in args]\n+ # with core.new_sublevel(), core.extend_axis_env(axis_name, axis_size, main):\n+ # t = main.with_cur_sublevel()\n+ # shard_axes = {axis_name: 0}\n+ # tracers = [MapTracer(t, arg, shard_axes) for arg in sharded_args]\n+ # ans = fun.call_wrapped(*tracers)\n+ # out_tracers = map(t.full_raise, ans)\n+ # outvals = [t.val for t in out_tracers]\n+ # return outvals\n+ # else:\n+ # breakpoint()\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -727,6 +727,39 @@ class PythonPmapTest(jtu.JaxTestCase):\nexpected = grad(lambda x: jnp.sum(baseline_fun(x)))(x)\nself.assertAllClose(ans, expected, atol=1e-3, rtol=1e-3)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": f\"_mesh={device_mesh_shape}\".replace(\" \", \"\"),\n+ \"device_mesh_shape\": device_mesh_shape}\n+ for device_mesh_shape in [(1, 2)])\n+ def testNestedWithClosure2(self, device_mesh_shape):\n+ mesh_shape = self._getMeshShape(device_mesh_shape)\n+\n+ @partial(self.pmap, axis_name='i')\n+ def test_fun(x):\n+ y = jnp.sum(jnp.sin(x))\n+\n+ @partial(self.pmap, axis_name='j')\n+ def g(z):\n+ return jnp.exp(x.sum())\n+ return grad(lambda w: jnp.sum(g(w)))(x)\n+\n+ @vmap\n+ def baseline_fun(x):\n+ y = jnp.sum(jnp.sin(x))\n+\n+ @vmap\n+ def g(z):\n+ return jnp.exp(x.sum())\n+ return grad(lambda w: jnp.sum(g(w)))(x)\n+\n+ shape = mesh_shape\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ print(x.shape)\n+\n+ ans = grad(lambda x: jnp.sum(test_fun(x)))(x)\n+ expected = grad(lambda x: jnp.sum(baseline_fun(x)))(x)\n+ self.assertAllClose(ans, expected, atol=1e-3, rtol=1e-3)\n+\ndef testShardedDeviceArrays(self):\nf = lambda x: 2 * x\nf = self.pmap(f, axis_name='i')\n@@ -1164,9 +1197,16 @@ class PythonPmapTest(jtu.JaxTestCase):\nx = np.ones((device_count + 1, 10))\nself.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\n+ if not config.jax_disable_jit:\n+ # When jit is disabled, this error is not raised given an identity fn. We\n+ # kept this branch so as not to perturb old tests.\nf = self.pmap(lambda x: self.pmap(lambda x: x)(x))\nx = np.ones((device_count, 2, 10))\nself.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\n+ else:\n+ f = self.pmap(lambda x: self.pmap(lambda x: 2 * x)(x))\n+ x = np.ones((device_count, 2, 10))\n+ self.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\ndef testPmapConstant(self):\ndevice_count = jax.device_count()\n@@ -1203,6 +1243,8 @@ class PythonPmapTest(jtu.JaxTestCase):\nbufs = ans._arrays\nelse:\nbufs = ans.device_buffers\n+ # TODO(mattjj,sharadmv): fix physical layout with eager pmap, remove 'if'\n+ if not config.jax_disable_jit:\nself.assertEqual([b.device() for b in bufs], devices)\ndef testPmapConstantError(self):\n@@ -1286,6 +1328,8 @@ class PythonPmapTest(jtu.JaxTestCase):\n[b.device() for b in expected_sharded_bufs])\ndef testNestedPmapConstantError(self):\n+ if config.jax_disable_jit:\n+ raise SkipTest(\"error test doesn't apply with disable_jit\")\nf = self.pmap(self.pmap(lambda x: 3))\nshape = (2, jax.device_count() // 2 + 1, 3)\nx = jnp.arange(prod(shape)).reshape(shape)\n@@ -1702,7 +1746,7 @@ class PythonPmapTest(jtu.JaxTestCase):\ndef testCompositionWithJitTwice(self):\n@jit\ndef f(x):\n- y = 2 * x\n+ y = jnp.float32(2) * x\n@jit\ndef g(z):\n@@ -1710,7 +1754,7 @@ class PythonPmapTest(jtu.JaxTestCase):\nreturn g(x)\n- f(np.arange(1.).reshape((1, 1))) # doesn't crash\n+ f(np.arange(1., dtype='float32').reshape((1, 1))) # doesn't crash\n@ignore_jit_of_pmap_warning()\ndef testIssue1065(self):\n@@ -1904,7 +1948,7 @@ class PythonPmapTest(jtu.JaxTestCase):\ndef testJitOfPmapWarningMessage(self):\ndevice_count = jax.device_count()\n- if device_count == 1:\n+ if device_count == 1 or config.jax_disable_jit:\nraise SkipTest(\"test requires at least two devices\")\ndef foo(x): return x\n@@ -2068,6 +2112,8 @@ class PythonPmapTest(jtu.JaxTestCase):\ndef test_grad_of_pmap_compilation_caching(self, axis_size):\nif len(jax.local_devices()) < axis_size:\nraise SkipTest(\"too few devices for test\")\n+ if config.jax_disable_jit:\n+ raise SkipTest(\"caching doesn't apply with jit disabled\")\n@jax.pmap\ndef f(x):\n@@ -2474,6 +2520,8 @@ class PmapWithDevicesTest(jtu.JaxTestCase):\nf(jnp.ones(jax.device_count() + 1))\ndef testBadAxisSizeErrorNested(self):\n+ if config.jax_disable_jit:\n+ raise SkipTest(\"error doesn't apply when jit is disabled\")\nf = pmap(pmap(lambda x: lax.psum(x, ('i', 'j')),\naxis_name='j'),\naxis_name='i',\n@@ -2487,6 +2535,8 @@ class PmapWithDevicesTest(jtu.JaxTestCase):\ndef testNestedPmaps(self):\nif jax.device_count() % 2 != 0:\nraise SkipTest\n+ if config.jax_disable_jit:\n+ raise SkipTest(\"disable_jit requires num devices to equal axis size\")\n# Devices specified in outer pmap are OK\n@partial(pmap, axis_name='i', devices=jax.devices())\n@@ -2504,6 +2554,8 @@ class PmapWithDevicesTest(jtu.JaxTestCase):\ndef testNestedPmapsBools(self):\nif jax.device_count() % 2 != 0:\nraise SkipTest\n+ if config.jax_disable_jit:\n+ raise SkipTest(\"disable_jit requires num devices to equal axis size\")\n# Devices specified in outer pmap are OK\n@partial(pmap, axis_name='i', devices=jax.devices())\n@@ -3041,6 +3093,8 @@ class ArrayPmapTest(jtu.JaxTestCase):\nself.assertArraysEqual(out2, input_data)\ndef test_pmap_array_in_axes_out_axes(self):\n+ if config.jax_disable_jit:\n+ raise SkipTest(\"test hangs with disable_jit\") # TODO(mattjj,sharadmv,yashkatariya)\ndc = jax.device_count()\ninput_shape = (dc, 2)\na1, input_data = create_input_array_for_pmap(input_shape, in_axes=0)\n@@ -3132,6 +3186,29 @@ class ArrayVmapPmapCollectivesTest(ArrayPmapMixin, VmapPmapCollectivesTest):\nclass ArrayPmapWithDevicesTest(ArrayPmapMixin, PmapWithDevicesTest):\npass\n+class EagerPmapMixin: # i hate mixins\n+\n+ def setUp(self):\n+ super().setUp()\n+ self.jit_disabled = config.jax_disable_jit\n+ config.update('jax_disable_jit', True)\n+\n+ def tearDown(self):\n+ config.update('jax_disable_jit', self.jit_disabled)\n+ super().tearDown()\n+\n+class EagerPythonPmapTest(EagerPmapMixin, PythonPmapTest):\n+ pass\n+\n+class EagerCppPmapTest(EagerPmapMixin, CppPmapTest):\n+ pass\n+\n+class EagerPmapWithDevicesTest(EagerPmapMixin, PmapWithDevicesTest):\n+ pass\n+\n+class EagerVmapOfPmapTest(EagerPmapMixin, VmapOfPmapTest):\n+ pass\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Initial implementation of eager pmap
Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com>
Co-authored-by: Matthew Johnson <mattjj@google.com> |
260,335 | 10.08.2022 18:07:56 | 25,200 | a7f760d9eda2c4f41b0a529b87854fcc689436b0 | Working multihost eager pmap | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -914,10 +914,11 @@ def new_main(trace_type: Type[Trace],\nif leaked_tracers: raise leaked_tracer_error(\"trace\", t(), leaked_tracers)\n@contextmanager\n-def new_base_main(trace_type: Type[Trace]) -> Generator[MainTrace, None, None]:\n+def new_base_main(trace_type: Type[Trace],\n+ **payload) -> Generator[MainTrace, None, None]:\n# See comments in https://github.com/google/jax/pull/3370\nstack = thread_local_state.trace_state.trace_stack\n- main = MainTrace(0, trace_type)\n+ main = MainTrace(0, trace_type, **payload)\nprev_dynamic, stack.dynamic = stack.dynamic, main\nprev_base, stack.stack[0] = stack.stack[0], main\n_update_thread_local_jit_state(stack.dynamic)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -941,29 +941,31 @@ def _emap_impl(fun: lu.WrappedFun, *args,\ndonated_invars: Sequence[bool],\nglobal_arg_shapes: Sequence[Optional[Tuple[int, ...]]]):\nif global_axis_size is not None: raise NotImplementedError\n- del global_axis_size, global_arg_shapes\n- if devices is not None:\n- if len(devices) == 0:\n- raise ValueError(\"'devices' argument to pmap must be non-empty, or None.\")\n- if len(devices) != axis_size:\n- raise ValueError(\n- f\"Leading axis size of input to pmapped function must equal the \"\n- f\"number of local devices passed to pmap. Got axis_size=\"\n- f\"{axis_size}, num_local_devices={len(devices)}.\")\n- else:\n- devices = xb.devices(backend=backend)[:axis_size]\n- if len(devices) != axis_size:\n- msg = (\"compiling computation that requires {} logical devices, but only {} XLA \"\n- \"devices are available (num_replicas={}, num_partitions={})\")\n- raise ValueError(msg.format(axis_size,\n- xb.device_count(backend),\n- None,\n- None))\n+ pci = ParallelCallableInfo(\n+ name, backend, axis_name, axis_size,\n+ global_axis_size, devices, None, None, ())\n+ # if devices is not None:\n+ # if len(devices) == 0:\n+ # raise ValueError(\"'devices' argument to pmap must be non-empty, or None.\")\n+ # if len(devices) != axis_size:\n+ # raise ValueError(\n+ # f\"Leading axis size of input to pmapped function must equal the \"\n+ # f\"number of local devices passed to pmap. Got axis_size=\"\n+ # f\"{axis_size}, num_local_devices={len(devices)}.\")\n+ # else:\n+ # devices = xb.devices(backend=backend)[:axis_size]\n+ # if len(devices) != axis_size:\n+ # msg = (\"compiling computation that requires {} logical devices, but only {} XLA \"\n+ # \"devices are available (num_replicas={}, num_partitions={})\")\n+ # raise ValueError(msg.format(axis_size,\n+ # xb.device_count(backend),\n+ # None,\n+ # None))\nsharded_args = []\nshard_axes = []\nfor arg, in_axis in zip(args, in_axes):\nif in_axis == 0:\n- sharded_args.append(jax.device_put_sharded(list(arg), devices))\n+ sharded_args.append(arg)\nshard_axes.append({axis_name: 0})\nelif in_axis is None:\nsharded_args.append(arg)\n@@ -972,10 +974,9 @@ def _emap_impl(fun: lu.WrappedFun, *args,\nperm = list(range(arg.ndim))\na = perm.pop(in_axis)\nperm.insert(0, a)\n- new_arg = arg.transpose(perm)\n- sharded_args.append(jax.device_put_sharded(list(new_arg), devices))\n+ sharded_args.append(arg.transpose(perm))\nshard_axes.append({axis_name: 0})\n- with core.new_base_main(MapTrace) as main:\n+ with core.new_base_main(MapTrace, pci=pci) as main:\nwith core.new_sublevel(), core.extend_axis_env(axis_name, axis_size, main):\nt = main.with_cur_sublevel()\ntracers = [\n@@ -989,21 +990,10 @@ def _emap_impl(fun: lu.WrappedFun, *args,\n# This next bit is like matchaxis in batching.py (for the end of a vmap)\nnew_outvals = []\nfor out_axis_src, out_axis, outval in zip(out_axes_src, out_axes, outvals):\n- if out_axis is None:\n- if src := out_axis_src.get(axis_name) is None:\n- new_outvals.append(outval)\n- else:\n- idx = [slice(None)] * len(outval.shape)\n- idx[src] = 0\n- new_outvals.append(outval[tuple(idx)])\n- elif out_axis == 0 == out_axis_src.get(axis_name):\n- new_outvals.append(outval)\n- else:\n- # TODO maybe just a transpose/broadcast here?\nwith jax._src.config.disable_jit(False):\n- new_outvals.append(\n- jax.pmap(lambda _, x: x, in_axes=(0, out_axis_src.get(axis_name)),\n- out_axes=out_axis)(np.arange(axis_size), outval))\n+ out = jax.pmap(lambda _, x: x, in_axes=(0, out_axis_src.get(axis_name)),\n+ out_axes=out_axis)(np.arange(axis_size), outval)\n+ new_outvals.append(out)\nreturn new_outvals\n@@ -1012,6 +1002,10 @@ def _map_indices_to_map_schedule(idx: Tuple[Optional[int], ...]):\nclass MapTrace(core.Trace):\n+ def __init__(self, *args, pci):\n+ super().__init__(*args)\n+ self.pci = pci\n+\ndef _get_frames(self):\nframes = [f for f in core.thread_local_state.trace_state.axis_env\nif f.main_trace is self.main]\n@@ -1036,7 +1030,8 @@ class MapTrace(core.Trace):\nfor i, name in reversed(list(enumerate(names))):\nin_axes = tuple(arg_axis[i] for arg_axis in all_axes)\nif any(in_axis is not None for in_axis in in_axes):\n- f = jax.pmap(f, in_axes=in_axes, axis_name=name)\n+ f = jax.pmap(f, in_axes=in_axes, axis_name=name,\n+ devices=self.main.payload['pci'].devices)\nused_names.append(name)\nwith core.eval_context(), jax._src.config.disable_jit(False):\noutvals = f(*vals)\n@@ -1105,10 +1100,12 @@ class MapTrace(core.Trace):\nreturn MapTracer(self, outval, shard_axis_out)\ndef process_axis_index(self, frame):\n- assert frame.size is not None\n+ fake_primitive = types.SimpleNamespace(\n+ multiple_results=False, bind=lambda _: jax.lax.axis_index(frame.name))\nwith core.eval_context():\nrange = jax.lax.iota(np.int32, frame.size)\n- return MapTracer(self, range, {frame.name: 0})\n+ dummy_tracer = MapTracer(self, range, {frame.name: 0})\n+ return self.process_primitive(fake_primitive, (dummy_tracer,), {})\ndef annotation_to_flat(ndim: int, mapped_axes: Sequence[int],\nsrc_flat: Optional[int], dst_annotation: Optional[int]\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -1189,21 +1189,14 @@ class PythonPmapTest(jtu.JaxTestCase):\ndef testDeviceCountError(self):\ndevice_count = jax.device_count()\n- f = self.pmap(lambda x: x)\n+ f = self.pmap(lambda x: 2 * x)\nx = jnp.arange(device_count + 1)\nself.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\n- f = self.pmap(lambda x: x)\n+ f = self.pmap(lambda x: 2 * x)\nx = np.ones((device_count + 1, 10))\nself.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\n- if not config.jax_disable_jit:\n- # When jit is disabled, this error is not raised given an identity fn. We\n- # kept this branch so as not to perturb old tests.\n- f = self.pmap(lambda x: self.pmap(lambda x: x)(x))\n- x = np.ones((device_count, 2, 10))\n- self.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\n- else:\nf = self.pmap(lambda x: self.pmap(lambda x: 2 * x)(x))\nx = np.ones((device_count, 2, 10))\nself.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\n@@ -1218,6 +1211,7 @@ class PythonPmapTest(jtu.JaxTestCase):\nexpected = np.repeat(3, device_count)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ if not config.jax_disable_jit:\nf = self.pmap(lambda x: (x, 3))\nx = np.arange(device_count)\nwith jtu.assert_num_jit_and_pmap_compilations(1):\n"
}
] | Python | Apache License 2.0 | google/jax | Working multihost eager pmap
Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com>
Co-authored-by: Skye Wanderman-Milne <skyewm@google.com> |
260,510 | 12.08.2022 10:59:20 | 25,200 | 72dbe311722e7dfb14fd3894875ad8e57409b92c | Initial transpose implementation | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/for_loop.py",
"new_path": "jax/_src/lax/control_flow/for_loop.py",
"diff": "@@ -34,6 +34,7 @@ from jax._src import state\nfrom jax._src.util import (partition_list, merge_lists, safe_map, safe_zip,\nsplit_list)\nimport jax.numpy as jnp\n+import numpy as np\nfrom jax._src.lax.control_flow import loops\nfrom jax._src.lax.control_flow.common import _abstractify, _initial_style_jaxpr\n@@ -468,6 +469,73 @@ def _convert_inputs_to_reads(\neval_jaxpr, [i_aval, *res_ref_avals, *orig_ref_avals])\nreturn jaxpr\n+def transpose_jaxpr(jaxpr: core.Jaxpr, which_linear: List[bool]) -> core.Jaxpr:\n+ which_linear = map(bool, np.cumsum(which_linear).astype(np.bool_))\n+ def trans(i, *args):\n+ # First we want to run the computation to read all the residual refs. We can\n+ # do that by using partial evaluation with all linear inputs unknown.\n+ res_jaxpr, tangent_jaxpr_, *_ = \\\n+ _partial_eval_jaxpr_custom(jaxpr, [False, *which_linear],\n+ _save_everything)\n+ res_args = [x for x, lin in zip(args, which_linear) if not lin]\n+ res = core.eval_jaxpr(res_jaxpr, (), i, *res_args)\n+\n+ # Now that we have residual values, we run the tangent jaxpr. It takes as\n+ # input the residuals, the loop index, and all the refs (at least, the ones\n+ # that are used in the body). Luckily, `tangent_jaxpr_` has all known and\n+ # unknown inputs!\n+ tangent_jaxpr, used = pe.dce_jaxpr(tangent_jaxpr_, [])\n+ used_res, (used_i,), used_ct = split_list(used, [len(res), 1])\n+ primals_args = [*(r for u, r in zip(used_res, res) if u)]\n+ if used_i:\n+ primals_args = [*primals_args, i]\n+ ct_args = [x for x, u in zip(args, used_ct) if u]\n+ ad.backward_pass(\n+ tangent_jaxpr, (), False, (), (*primals_args, *ct_args), ())\n+ return []\n+ jaxpr_trans, _, _ = pe.trace_to_jaxpr_dynamic(\n+ lu.wrap_init(trans), [v.aval for v in jaxpr.invars])\n+ return jaxpr_trans\n+\n+def _for_transpose(in_cts, *args, jaxpr, nsteps, reverse, which_linear):\n+ # if any in_ct is nonzero, we definitely want it in args_ (and the\n+ # corresponding x in args could be an undefined primal, but doesnt have to be)\n+ # for non-res stuff:\n+ # getting and setting => (nonzero ct, UndefinedPrimal arg)\n+ # just setting => (nonzero ct, not UndefinedPrimal, dummy value)\n+ # just getting => (zero ct , UndefinedPrimal arg)\n+ # for res stuff:\n+ # (zero ct , not UndefinedPrimal)\n+ args_ = []\n+ which_linear_transpose = []\n+ for x, ct in zip(args, in_cts):\n+ if type(ct) is ad_util.Zero and not ad.is_undefined_primal(x):\n+ # this is a residual, take x!\n+ args_.append(x)\n+ which_linear_transpose.append(False)\n+ elif type(ct) is ad_util.Zero and ad.is_undefined_primal(x):\n+ # the loop was 'just getting', plug in a zero\n+ args_.append(ad_util.zeros_like_aval(x.aval))\n+ which_linear_transpose.append(False)\n+ elif type(ct) is not ad_util.Zero and not ad.is_undefined_primal(x):\n+ # the loop was 'just setting', grab that cotangent! x is dummy\n+ args_.append(ct)\n+ which_linear_transpose.append(False)\n+ elif type(ct) is not ad_util.Zero and ad.is_undefined_primal(x):\n+ # the loop was 'getting and setting', grab that cotangent!\n+ args_.append(ct)\n+ which_linear_transpose.append(True)\n+\n+ jaxpr_transpose = transpose_jaxpr(jaxpr, which_linear)\n+ assert len(args_) == len(jaxpr_transpose.invars) - 1\n+ all_outs = for_p.bind(*args_, jaxpr=jaxpr_transpose, nsteps=nsteps,\n+ reverse=not reverse,\n+ which_linear=tuple(which_linear_transpose))\n+ ct_outs = [ct if ad.is_undefined_primal(x) else None\n+ for x, ct in zip(args, all_outs)]\n+ return ct_outs\n+ad.primitive_transposes[for_p] = _for_transpose\n+\n### Testing utility\ndef discharged_for_loop(nsteps, body, init_state, *, reverse: bool = False):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/primitives.py",
"new_path": "jax/_src/state/primitives.py",
"diff": "@@ -252,3 +252,10 @@ def _swap_transpose(g, ref, x, *idx):\nx_bar = ref_swap(ref, idx, ad_util.instantiate(g))\nreturn [None, x_bar] + [None] * len(idx)\nad.primitive_transposes[swap_p] = _swap_transpose\n+\n+def addupdate_transpose(cts_in, ref, x, *idx):\n+ # addupdate transpose is get\n+ del cts_in, x\n+ g = ref_get(ref, idx)\n+ return [None] + [None] * len(idx) + [g]\n+ad.primitive_transposes[addupdate_p] = addupdate_transpose\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -173,7 +173,7 @@ def recast_to_float0(primal, tangent):\n# errors if you will)\ndef backward_pass(jaxpr: core.Jaxpr, reduce_axes, transform_stack,\nconsts, primals_in, cotangents_in):\n- if all(type(ct) is Zero for ct in cotangents_in):\n+ if all(type(ct) is Zero for ct in cotangents_in) and not jaxpr.effects:\nreturn map(lambda v: Zero(v.aval), jaxpr.invars)\ndef write_cotangent(prim, v, ct):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -1607,7 +1607,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)\n@jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\ndef testScanGrad(self, jit_scan, jit_f, scan):\nrng = self.rng()\n@@ -2799,6 +2799,39 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nnp.testing.assert_allclose(actual_tangents[0], expected_tangents[0])\nnp.testing.assert_allclose(actual_tangents[1], expected_tangents[1])\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_grad(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.grad(lambda args: for_( n, f, args)[1].sum())(args)\n+ ans_discharged = jax.grad(\n+ lambda args: for_reference(n, f, args)[1].sum())(args)\n+ expected = jax.grad(lambda args: ref(*args)[1].sum())(args)\n+ self.assertAllClose(ans, ans_discharged, check_dtypes=True, rtol=tol,\n+ atol=tol)\n+ self.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\n+ jtu.check_grads(lambda *args: for_(n, f, args)[1].sum(), args, order=2)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Initial transpose implementation
Co-authored-by: Matthew Johnson <mattjj@google.com> |
260,510 | 11.08.2022 10:49:56 | 25,200 | fe040cc01e76616bf347afd2b2179a4477f29819 | Cleaning up eager pmap implementation | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -113,12 +113,12 @@ zip, unsafe_zip = safe_zip, zip\nFLAGS = flags.FLAGS\nflags.DEFINE_bool(\n- \"experimental_cpp_jit\", bool_env(\"JAX_CPP_JIT\", False),\n+ \"experimental_cpp_jit\", bool_env(\"JAX_CPP_JIT\", True),\n\"A flag enabling the C++ jax.jit fast path.\"\n\"Set this to `False` only if it crashes otherwise and report \"\n\"the error to the jax-team.\")\nflags.DEFINE_bool(\n- \"experimental_cpp_pmap\", bool_env(\"JAX_CPP_PMAP\", False),\n+ \"experimental_cpp_pmap\", bool_env(\"JAX_CPP_PMAP\", True),\n\"A flag enabling the C++ jax.pmap fast path. Until the default \"\n\"is switched to True, the feature is not supported and possibly broken \"\n\"(e.g. it may use unreleased code from jaxlib.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/config.py",
"new_path": "jax/_src/config.py",
"diff": "@@ -897,6 +897,13 @@ config.define_bool_state(\ndefault=False,\nhelp='Enable using a cache for lowering subjaxprs.')\n+# TODO(sharadmv,mattjj): set default to True, then remove\n+config.define_bool_state(\n+ name='jax_eager_pmap',\n+ default=False,\n+ upgrade=True,\n+ help='Enable eager-mode pmap when jax_disable_jit is activated.')\n+\n@contextlib.contextmanager\ndef explicit_device_put_scope() -> Iterator[None]:\n\"\"\"Indicates that the current context is an explicit device_put*() call.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -907,7 +907,9 @@ def xla_pmap_impl(fun: lu.WrappedFun, *args,\nout_axes_thunk: Callable[[], Sequence[Optional[int]]],\ndonated_invars: Sequence[bool],\nglobal_arg_shapes: Sequence[Optional[Tuple[int, ...]]]):\n- if config.jax_disable_jit:\n+ if (config.jax_disable_jit and config.jax_eager_pmap and\n+ global_axis_size is None and not any(d for d in donated_invars) and\n+ not all(g is not None for g in global_arg_shapes)):\nreturn _emap_impl(fun, *args, backend=backend, axis_name=axis_name,\naxis_size=axis_size, global_axis_size=global_axis_size,\ndevices=devices, name=name, in_axes=in_axes,\n@@ -929,6 +931,10 @@ def xla_pmap_impl(fun: lu.WrappedFun, *args,\n(\"fingerprint\", fingerprint))\nreturn compiled_fun(*args)\n+class EmapInfo(NamedTuple):\n+ backend: Optional[str]\n+ devices: Optional[Sequence[Any]]\n+\ndef _emap_impl(fun: lu.WrappedFun, *args,\nbackend: Optional[str],\naxis_name: core.AxisName,\n@@ -940,76 +946,64 @@ def _emap_impl(fun: lu.WrappedFun, *args,\nout_axes_thunk: Callable[[], Sequence[Optional[int]]],\ndonated_invars: Sequence[bool],\nglobal_arg_shapes: Sequence[Optional[Tuple[int, ...]]]):\n- if global_axis_size is not None: raise NotImplementedError\n- pci = ParallelCallableInfo(\n- name, backend, axis_name, axis_size,\n- global_axis_size, devices, None, None, ())\n- # if devices is not None:\n- # if len(devices) == 0:\n- # raise ValueError(\"'devices' argument to pmap must be non-empty, or None.\")\n- # if len(devices) != axis_size:\n- # raise ValueError(\n- # f\"Leading axis size of input to pmapped function must equal the \"\n- # f\"number of local devices passed to pmap. Got axis_size=\"\n- # f\"{axis_size}, num_local_devices={len(devices)}.\")\n- # else:\n- # devices = xb.devices(backend=backend)[:axis_size]\n- # if len(devices) != axis_size:\n- # msg = (\"compiling computation that requires {} logical devices, but only {} XLA \"\n- # \"devices are available (num_replicas={}, num_partitions={})\")\n- # raise ValueError(msg.format(axis_size,\n- # xb.device_count(backend),\n- # None,\n- # None))\n- sharded_args = []\n- shard_axes = []\n- for arg, in_axis in zip(args, in_axes):\n- if in_axis == 0:\n- sharded_args.append(arg)\n- shard_axes.append({axis_name: 0})\n- elif in_axis is None:\n- sharded_args.append(arg)\n- shard_axes.append({})\n- else:\n- perm = list(range(arg.ndim))\n- a = perm.pop(in_axis)\n- perm.insert(0, a)\n- sharded_args.append(arg.transpose(perm))\n- shard_axes.append({axis_name: 0})\n- with core.new_base_main(MapTrace, pci=pci) as main:\n+ # TODO(sharadmv,mattjj): implement these cases\n+ if any(d for d in donated_invars):\n+ raise NotImplementedError(\"Buffer donation not supported in eager pmap.\")\n+ if any(g is not None for g in global_arg_shapes):\n+ raise NotImplementedError(\"Global arg shapes not supported in eager pmap.\")\n+ if global_axis_size is not None:\n+ raise NotImplementedError(\"Non-default global_axis_size not supported in \"\n+ \"eager pmap.\")\n+\n+ emap_info = EmapInfo(backend, devices)\n+ shard_axes = [{} if in_axis is None else {axis_name: in_axis} for in_axis in in_axes]\n+ with core.new_base_main(MapTrace, emap_info=emap_info) as main:\nwith core.new_sublevel(), core.extend_axis_env(axis_name, axis_size, main):\nt = main.with_cur_sublevel()\ntracers = [\n- MapTracer(t, arg, s) for arg, s in zip(sharded_args, shard_axes)]\n+ MapTracer(t, arg, s) for arg, s in zip(args, shard_axes)]\nans = fun.call_wrapped(*tracers)\nout_tracers = map(t.full_raise, ans)\noutvals, out_axes_src = unzip2((t.val, t.shard_axes) for t in out_tracers)\ndel main\nout_axes = out_axes_thunk()\n- # This next bit is like matchaxis in batching.py (for the end of a vmap)\nnew_outvals = []\nfor out_axis_src, out_axis, outval in zip(out_axes_src, out_axes, outvals):\n- with jax._src.config.disable_jit(False):\n+ with jax.disable_jit(False):\nout = jax.pmap(lambda _, x: x, in_axes=(0, out_axis_src.get(axis_name)),\n- out_axes=out_axis)(np.arange(axis_size), outval)\n+ out_axes=out_axis, devices=devices, backend=backend)(\n+ np.arange(axis_size), outval)\nnew_outvals.append(out)\nreturn new_outvals\n-\n-def _map_indices_to_map_schedule(idx: Tuple[Optional[int], ...]):\n- return tuple(None if i is None else i - sum(j is not None and j < i for j in idx[:l]) for l, i in enumerate(idx))\n+def _map_schedule(idx: Tuple[Optional[int], ...]) -> List[Optional[int]]:\n+ # In order to do a multi-map (a simultaneous map over several axes), we will\n+ # nest several maps. Each time we do a map, we \"remove\" an input axis so we\n+ # need to update the remaining map axes. For example, if we are to map over\n+ # the axes 0, 3, and 4, we make three calls to pmap with in_axes as 0, 2, 2.\n+ return [None if i is None else\n+ i - sum(j is not None and j < i for j in idx[:l])\n+ for l, i in enumerate(idx)]\n+\n+def _multi_pmap(f: Callable, info: EmapInfo, names: List[core.AxisName],\n+ all_axes: List[Tuple[Optional[int], ...]]\n+ ) -> Tuple[Callable, Dict[core.AxisName, int]]:\n+ used_names = []\n+ for i, name in reversed(list(enumerate(names))):\n+ in_axes = tuple(arg_axis[i] for arg_axis in all_axes)\n+ if any(in_axis is not None for in_axis in in_axes):\n+ f = jax.pmap(f, in_axes=in_axes, axis_name=name, out_axes=0,\n+ backend=info.backend, devices=info.devices)\n+ used_names.append(name)\n+ out_shard_axes = {name: i for i, name in enumerate(reversed(used_names))}\n+ return f, out_shard_axes\nclass MapTrace(core.Trace):\n- def __init__(self, *args, pci):\n+ def __init__(self, *args, emap_info):\nsuper().__init__(*args)\n- self.pci = pci\n-\n- def _get_frames(self):\n- frames = [f for f in core.thread_local_state.trace_state.axis_env\n- if f.main_trace is self.main]\n- return frames\n+ self.emap_info = emap_info\ndef pure(self, val):\nreturn MapTracer(self, val, {})\n@@ -1018,24 +1012,15 @@ class MapTrace(core.Trace):\nreturn MapTracer(self, tracer.val, tracer.shard_axes)\ndef process_primitive(self, primitive, tracers, params):\n- vals = [t.val for t in tracers]\n- names = [f.name for f in self._get_frames()]\n- f = lambda *args: primitive.bind(*args, **params)\n- used_names = []\n- all_axes = []\n- for t in tracers:\n- arg_axes = tuple(t.shard_axes.get(name, None) for name in names)\n- arg_axes = _map_indices_to_map_schedule(arg_axes)\n- all_axes.append(arg_axes)\n- for i, name in reversed(list(enumerate(names))):\n- in_axes = tuple(arg_axis[i] for arg_axis in all_axes)\n- if any(in_axis is not None for in_axis in in_axes):\n- f = jax.pmap(f, in_axes=in_axes, axis_name=name,\n- devices=self.main.payload['pci'].devices)\n- used_names.append(name)\n- with core.eval_context(), jax._src.config.disable_jit(False):\n- outvals = f(*vals)\n- out_shard_axes = {name: i for i, name in enumerate(reversed(used_names))}\n+ info = self.main.payload[\"emap_info\"]\n+ vals, shard_axes = unzip2([(t.val, t.shard_axes) for t in tracers])\n+ names = [f.name for f in core.thread_local_state.trace_state.axis_env\n+ if f.main_trace is self.main]\n+ all_axes = [_map_schedule(map(s.get, names)) for s in shard_axes]\n+ f_mapped, out_shard_axes = _multi_pmap(partial(primitive.bind, **params),\n+ info, names, all_axes)\n+ with core.eval_context(), jax.disable_jit(False):\n+ outvals = f_mapped(*vals)\nif primitive.multiple_results:\nreturn [MapTracer(self, val, out_shard_axes) for val in outvals]\nreturn MapTracer(self, outvals, out_shard_axes)\n@@ -1049,77 +1034,64 @@ class MapTrace(core.Trace):\ndef process_map(self, call_primitive, fun, tracers, params):\nif params['devices'] is not None:\nraise ValueError(\"Nested pmap with explicit devices argument.\")\n- if config.jax_disable_jit:\n+ if not config.jax_disable_jit:\n+ fake_primitive = types.SimpleNamespace(\n+ multiple_results=True, bind=partial(call_primitive.bind, fun))\n+ return self.process_primitive(fake_primitive, tracers, params)\naxis_name, in_axes, out_axes_thunk, axis_size = (params[\"axis_name\"],\nparams[\"in_axes\"], params[\"out_axes_thunk\"], params[\"axis_size\"])\n- invals = [t.val for t in tracers]\n- shard_axes_src = [t.shard_axes for t in tracers]\n- shard_axes = []\n- for inval, in_axis, shard_axis_src in zip(invals, in_axes, shard_axes_src):\n- new_shard_axis_src = dict(shard_axis_src)\n- if in_axis is not None:\n- idx = [i for i in range(inval.ndim) if i not in shard_axis_src.values()]\n- new_idx = idx[in_axis]\n- new_shard_axis_src = {axis_name: new_idx, **shard_axis_src}\n- shard_axes.append(new_shard_axis_src)\n+ vals, shard_axes = unzip2([(t.val, t.shard_axes) for t in tracers])\n+ shard_axes = [{axis_name: _annot_to_flat(np.ndim(v), s.values(), ax), **s}\n+ if ax is not None else s\n+ for v, ax, s in zip(vals, in_axes, shard_axes)]\nwith core.new_sublevel(), core.extend_axis_env(axis_name, axis_size, self.main):\nt = self.main.with_cur_sublevel()\n- in_tracers = [MapTracer(t, val, shard_axis) for val, shard_axis in\n- zip(invals, shard_axes)]\n+ in_tracers = map(partial(MapTracer, t), vals, shard_axes)\nans = fun.call_wrapped(*in_tracers)\n- out_axes_dest = out_axes_thunk()\nout_tracers = map(t.full_raise, ans)\n- outvals, shard_axes_src = util.unzip2([(t.val, t.shard_axes) for t in\n- out_tracers])\n- new_out_tracers = map(\n- partial(self._make_output_tracer, axis_name, axis_size), outvals,\n- shard_axes_src, out_axes_dest)\n- return new_out_tracers\n- else:\n+ out, outaxes = unzip2((t.val, t.shard_axes) for t in out_tracers)\n+ del t, in_tracers, ans, out_tracers\n+ out, outaxes = unzip2(_match_annot(axis_name, axis_size, v, s, dst)\n+ for v, s, dst in zip(out, outaxes, out_axes_thunk()))\n+ return map(partial(MapTracer, self), out, outaxes)\n+\n+ def process_axis_index(self, frame):\nfake_primitive = types.SimpleNamespace(\n- multiple_results=True, bind=partial(call_primitive.bind, fun))\n- return self.process_primitive(fake_primitive, tracers, params)\n+ multiple_results=False, bind=lambda _: jax.lax.axis_index(frame.name))\n+ with core.eval_context():\n+ range = jax.lax.iota(np.int32, frame.size)\n+ dummy_tracer = MapTracer(self, range, {frame.name: 0})\n+ return self.process_primitive(fake_primitive, (dummy_tracer,), {})\n+\n+def _annot_to_flat(ndim: int, mapped_axes: Iterable[int],\n+ annotation: Optional[int]) -> Optional[int]:\n+ if annotation is None: return None\n+ mapped_axes_ = set(mapped_axes)\n+ return [i for i in range(ndim) if i not in mapped_axes_][annotation]\n- def _make_output_tracer(self, axis_name, axis_size, val, shard_axis_src,\n- dst_annotation):\n+def _match_annot(axis_name: core.AxisName, axis_size: int, val: Any,\n+ shard_axis_src: Dict[core.AxisName, int],\n+ dst_annotation: Optional[int]\n+ ) -> Tuple[Any, Dict[core.AxisName, int]]:\nshard_axis_out = dict(shard_axis_src)\nsrc = shard_axis_out.pop(axis_name, None)\n- dst = annotation_to_flat(np.ndim(val), shard_axis_out.values(),\n- src, dst_annotation)\n+ dst = _annot_to_flat(np.ndim(val) + (src is None), shard_axis_out.values(),\n+ dst_annotation)\nwith core.eval_context():\nif src == dst:\noutval = val\nelif type(src) == type(dst) == int:\noutval = batching.moveaxis(val, src, dst)\n- shard_axis_out = moveaxis(np.ndim(val), shard_axis_src, src, dst)\n+ shard_axis_out = _moveaxis(np.ndim(val), shard_axis_src, src, dst)\nelif src is None and dst is not None:\noutval = batching.broadcast(val, axis_size, dst)\nshard_axis_out = {n: d + (dst <= d) for n, d in shard_axis_out.items()}\nelse:\n- assert False\n- return MapTracer(self, outval, shard_axis_out)\n-\n- def process_axis_index(self, frame):\n- fake_primitive = types.SimpleNamespace(\n- multiple_results=False, bind=lambda _: jax.lax.axis_index(frame.name))\n- with core.eval_context():\n- range = jax.lax.iota(np.int32, frame.size)\n- dummy_tracer = MapTracer(self, range, {frame.name: 0})\n- return self.process_primitive(fake_primitive, (dummy_tracer,), {})\n-\n-def annotation_to_flat(ndim: int, mapped_axes: Sequence[int],\n- src_flat: Optional[int], dst_annotation: Optional[int]\n- ) -> Optional[int]:\n- if dst_annotation is None:\n- return None\n- ndim_ = ndim - len(mapped_axes) + (src_flat is None)\n- dst_annotation = batching.canonicalize_axis(dst_annotation, ndim_)\n- idx = [i for i in range(ndim + (src_flat is None)) if i not in mapped_axes]\n- out = idx[dst_annotation]\n- return out\n+ raise NotImplementedError\n+ return outval, shard_axis_out\n-def moveaxis(ndim: int, shard_axes: Dict[core.AxisName, int],\n- src: int, dst: int):\n+def _moveaxis(ndim: int, shard_axes: Dict[core.AxisName, int],\n+ src: int, dst: int) -> Dict[core.AxisName, int]:\nlst: List[Optional[core.AxisName]] = [None] * ndim\nfor k, v in shard_axes.items():\nlst[v] = k\n"
},
{
"change_type": "DELETE",
"old_path": "matt.py",
"new_path": null,
"diff": "-import pdb, sys, traceback\n-def info(type, value, tb):\n- traceback.print_exception(type, value, tb)\n- pdb.pm()\n-sys.excepthook = info\n-\n-import os\n-import functools\n-import re\n-\n-import jax\n-import jax.numpy as jnp\n-from jax.config import config\n-import numpy as np\n-\n-config.update(\"jax_new_checkpoint\", True)\n-config.update(\"jax_traceback_filtering\", \"off\")\n-config.update(\"jax_platform_name\", \"cpu\")\n-\n-def set_host_device_count(n):\n- xla_flags = os.getenv(\"XLA_FLAGS\", \"\")\n- xla_flags = re.sub(\n- r\"--xla_force_host_platform_device_count=\\S+\", \"\", xla_flags\n- ).split()\n- os.environ[\"XLA_FLAGS\"] = \" \".join(\n- [\"--xla_force_host_platform_device_count={}\".format(n)] + xla_flags\n- )\n-\n-set_host_device_count(8)\n-\n-# @functools.partial(jax.pmap, axis_name=\"foo\")\n-# def f(x):\n-# def cond(i):\n-# return i < 10\n-# def body(i):\n-# return i + 1\n-# return jax.lax.while_loop(cond, body, x)\n-\n-# @functools.partial(jax.pmap, axis_name=\"foo\")\n-# def f(x):\n-# def cond(i):\n-# return i < 10\n-# def body(i):\n-# return i + 1\n-# return jax.lax.while_loop(cond, body, x)\n-\n-# print(f(jnp.arange(4.)))\n-\n-# with jax.disable_jit():\n-# print(f(jnp.arange(4.)))\n-\n-\n-# @jax.pmap\n-# def g(x):\n-# with jax._src.config.disable_jit(False):\n-# return jax.jit(jnp.sin)(x)\n-\n-# print(g(jnp.arange(4.)))\n-\n-# with jax.disable_jit():\n-# print(g(jnp.arange(4.)))\n-\n-# @functools.partial(jax.pmap, in_axes=(0, None, 0, None), axis_name='i')\n-# @functools.partial(jax.pmap, in_axes=(None, 0, 0, None), axis_name='j')\n-# def f(x, y, z, w):\n-# return jax.lax.axis_index(['i', 'j']) + x * y + z + w\n-\n-# print(f(jnp.arange(4.), jnp.arange(2.), jnp.arange(8.).reshape((4, 2)), 100.))\n-\n-# with jax.disable_jit():\n-# print(f(jnp.arange(4.), jnp.arange(2.), jnp.arange(8.).reshape((4, 2)), 100.))\n-\n-device_count = jax.device_count()\n-\n-# @functools.partial(jax.pmap, axis_name='i')\n-# def f(x):\n-# @functools.partial(jax.pmap, axis_name='j')\n-# def g(y):\n-# a = jax.lax.psum(1, 'i')\n-# b = jax.lax.psum(1, 'j')\n-# c = jax.lax.psum(1, ('i', 'j'))\n-# return a, b, c\n-# return g(x)\n-\n-# import numpy as np\n-# shape = (device_count, 1, 4)\n-# x = jnp.arange(np.prod(shape)).reshape(shape)\n-# a, b, c = f(x)\n-# print(a)\n-# print(b)\n-# print(c)\n-\n-# with jax.disable_jit():\n-# a, b, c = f(x)\n-# print(a)\n-# print(b)\n-# print(c)\n-\n-# f = lambda axis: jax.pmap(jax.pmap(lambda x: x + jax.lax.axis_index(axis), 'j'), 'i')\n-# x = jnp.ones((2, 2), dtype='int32')\n-# print(f('i')(x))\n-# print(f('j')(x))\n-\n-# with jax.disable_jit():\n-# print(f('i')(x))\n- # print(f('j')(x))\n-\n-\n-# def f(key):\n-# key = jax.random.fold_in(key, jax.lax.axis_index('i'))\n-# return jax.random.bernoulli(key, p=0.5)\n-\n-# keys = jax.random.split(jax.random.PRNGKey(0), len(jax.devices()))\n-\n-# print(jax.pmap(jax.remat(f), axis_name='i')(keys))\n-\n-# with jax.disable_jit():\n-# print(jax.pmap(jax.remat(f), axis_name='i')(keys))\n-\n-\n-# jax.pmap(lambda x: x)(jnp.zeros(jax.device_count() + 1))\n-# with jax.disable_jit():\n-# jax.pmap(lambda x: x)(jnp.zeros(jax.device_count() + 1))\n-\n-# jax.pmap(lambda x: x)(jnp.zeros(jax.device_count() + 1))\n-# with jax.disable_jit():\n-# jax.pmap(jax.pmap(jnp.square))(jnp.arange(16).reshape((4, 4)))\n-\n-# f = jax.pmap(lambda x: jax.pmap(lambda x: x)(x))\n-# x = jnp.ones((jax.device_count(), 2, 10))\n-# f(x)\n-# with jax.disable_jit():\n-# print(f(x))\n-\n-f = jax.pmap(jax.pmap(lambda x: 3))\n-shape = (2, jax.device_count() // 2, 3)\n-x = jnp.arange(np.prod(shape)).reshape(shape)\n-print(f(x))\n-with jax.disable_jit():\n- print(f(x))\n-# TODO:\n-# * [x] process_call\n-# * jit-of-emap = pmap (already, b/c we're only changing the pmap impl)\n-# * emap-of-jit = our processs_call rule should act same as initial style HOPs\n-# * emap-of-core.call = do a subtrace like thing where we turn around and stay\n-# in python\n-# * [ ] collectives\n-# * [ ] testing\n-# * [ ] nesting (process_map, sublift, etc)\n-# * [ ] shadowing of names\n-\n-# * delete process_call and core.call, just have an xla_call rule\n-# * no call updaters!\n-# * blocked on delete old remat\n-# * first just make xla_call have its own rule\n-# * then make it INITIAL STYLE\n-# * make it take closed jaxprs, so we can delete core.closed_call\n-# * delete all updaters\n-\n-\n-\n-\n-\n-\n-# brainstorming process_map\n- # assert map_primitive is xla_pmap_p\n- # backend, axis_size, axis_name = (\n- # params['backend'], params['axis_size'], params['axis_name'])\n- # if config.jax_disable_jit:\n- # shape = [f.size for f in self._get_frames()]\n- # devices = xb.devices(backend=backend)[:prod(shape) * axis_size]\n- # breakpoint()\n- # # def reshard(x: jnp.ndarray, devices: Array[devices]):\n- # # assert x.ndim == devices.ndim\n- # # e.g . x.shape = (4, 3, 2)\n- # # devices.shape = (4, 1, 2)\n- # # reshard(x, devices.reshape(4, 1, 2))\n- # sharded_args = [jax.device_put_sharded(list(x), devices) for x in args]\n- # with core.new_sublevel(), core.extend_axis_env(axis_name, axis_size, main):\n- # t = main.with_cur_sublevel()\n- # shard_axes = {axis_name: 0}\n- # tracers = [MapTracer(t, arg, shard_axes) for arg in sharded_args]\n- # ans = fun.call_wrapped(*tracers)\n- # out_tracers = map(t.full_raise, ans)\n- # outvals = [t.val for t in out_tracers]\n- # return outvals\n- # else:\n- # breakpoint()\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -727,39 +727,6 @@ class PythonPmapTest(jtu.JaxTestCase):\nexpected = grad(lambda x: jnp.sum(baseline_fun(x)))(x)\nself.assertAllClose(ans, expected, atol=1e-3, rtol=1e-3)\n- @parameterized.named_parameters(\n- {\"testcase_name\": f\"_mesh={device_mesh_shape}\".replace(\" \", \"\"),\n- \"device_mesh_shape\": device_mesh_shape}\n- for device_mesh_shape in [(1, 2)])\n- def testNestedWithClosure2(self, device_mesh_shape):\n- mesh_shape = self._getMeshShape(device_mesh_shape)\n-\n- @partial(self.pmap, axis_name='i')\n- def test_fun(x):\n- y = jnp.sum(jnp.sin(x))\n-\n- @partial(self.pmap, axis_name='j')\n- def g(z):\n- return jnp.exp(x.sum())\n- return grad(lambda w: jnp.sum(g(w)))(x)\n-\n- @vmap\n- def baseline_fun(x):\n- y = jnp.sum(jnp.sin(x))\n-\n- @vmap\n- def g(z):\n- return jnp.exp(x.sum())\n- return grad(lambda w: jnp.sum(g(w)))(x)\n-\n- shape = mesh_shape\n- x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n- print(x.shape)\n-\n- ans = grad(lambda x: jnp.sum(test_fun(x)))(x)\n- expected = grad(lambda x: jnp.sum(baseline_fun(x)))(x)\n- self.assertAllClose(ans, expected, atol=1e-3, rtol=1e-3)\n-\ndef testShardedDeviceArrays(self):\nf = lambda x: 2 * x\nf = self.pmap(f, axis_name='i')\n@@ -3087,8 +3054,6 @@ class ArrayPmapTest(jtu.JaxTestCase):\nself.assertArraysEqual(out2, input_data)\ndef test_pmap_array_in_axes_out_axes(self):\n- if config.jax_disable_jit:\n- raise SkipTest(\"test hangs with disable_jit\") # TODO(mattjj,sharadmv,yashkatariya)\ndc = jax.device_count()\ninput_shape = (dc, 2)\na1, input_data = create_input_array_for_pmap(input_shape, in_axes=0)\n@@ -3180,14 +3145,17 @@ class ArrayVmapPmapCollectivesTest(ArrayPmapMixin, VmapPmapCollectivesTest):\nclass ArrayPmapWithDevicesTest(ArrayPmapMixin, PmapWithDevicesTest):\npass\n-class EagerPmapMixin: # i hate mixins\n+class EagerPmapMixin:\ndef setUp(self):\nsuper().setUp()\n+ self.eager_pmap_enabled = config.jax_eager_pmap\nself.jit_disabled = config.jax_disable_jit\nconfig.update('jax_disable_jit', True)\n+ config.update('jax_eager_pmap', True)\ndef tearDown(self):\n+ config.update('jax_eager_pmap', self.eager_pmap_enabled)\nconfig.update('jax_disable_jit', self.jit_disabled)\nsuper().tearDown()\n@@ -3203,6 +3171,9 @@ class EagerPmapWithDevicesTest(EagerPmapMixin, PmapWithDevicesTest):\nclass EagerVmapOfPmapTest(EagerPmapMixin, VmapOfPmapTest):\npass\n+class EagerArrayPmapTest(EagerPmapMixin, ArrayPmapTest):\n+ pass\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Cleaning up eager pmap implementation
Co-authored-by: Matthew Johnson <mattjj@google.com> |
260,335 | 15.08.2022 12:26:55 | 25,200 | 68e3f58041182adb6c9d0f83bacee0f39e2a68f5 | un-skip polar/qdwh decomp tests skipped on gpu in
On an A100 machine, these tests seem to run fine now. See | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_scipy_test.py",
"new_path": "tests/lax_scipy_test.py",
"diff": "@@ -506,7 +506,6 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nfor nonzero_condition_number in nonzero_condition_numbers\nfor dtype in jtu.dtypes.inexact\nfor seed in seeds))\n- @jtu.skip_on_devices(\"gpu\") # Fails on A100.\ndef testPolar(\nself, n_zero_sv, degeneracy, geometric_spectrum, max_sv, shape, method,\nside, nonzero_condition_number, dtype, seed):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/qdwh_test.py",
"new_path": "tests/qdwh_test.py",
"diff": "@@ -93,8 +93,6 @@ class QdwhTest(jtu.JaxTestCase):\n'm': m, 'n': n, 'log_cond': log_cond}\nfor m, n in zip([8, 10, 20], [6, 10, 18])\nfor log_cond in np.linspace(1, _MAX_LOG_CONDITION_NUM, 4)))\n- # TODO(tianjianlu): Fails on A100 GPU.\n- @jtu.skip_on_devices(\"gpu\")\ndef testQdwhWithUpperTriangularInputAllOnes(self, m, n, log_cond):\n\"\"\"Tests qdwh with upper triangular input of all ones.\"\"\"\na = jnp.triu(jnp.ones((m, n))).astype(_QDWH_TEST_DTYPE)\n@@ -181,8 +179,6 @@ class QdwhTest(jtu.JaxTestCase):\n'm': m, 'n': n, 'log_cond': log_cond}\nfor m, n in zip([10, 8], [10, 8])\nfor log_cond in np.linspace(1, 4, 4)))\n- # TODO(tianjianlu): Fails on A100 GPU.\n- @jtu.skip_on_devices(\"gpu\")\ndef testQdwhWithOnRankDeficientInput(self, m, n, log_cond):\n\"\"\"Tests qdwh with rank-deficient input.\"\"\"\na = jnp.triu(jnp.ones((m, n))).astype(_QDWH_TEST_DTYPE)\n"
}
] | Python | Apache License 2.0 | google/jax | un-skip polar/qdwh decomp tests skipped on gpu in ad6ce74
On an A100 machine, these tests seem to run fine now. See https://github.com/google/jax/issues/8628#issuecomment-1215651697. |
260,287 | 16.08.2022 04:53:41 | 25,200 | ffd34d5ad79331030f706046ef16ec9844875f2a | Allow collectives in manually sharded computations
... at least when the manual sharding applies to the whole mesh, because
that's all that XLA can support right now. This is especially important
when computing gradients of xmapped functions (when manual lowering is
enabled), since AD often introduces many `psum`s. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/parallel.py",
"new_path": "jax/_src/lax/parallel.py",
"diff": "@@ -714,10 +714,21 @@ def _allreduce_lowering(prim, pos_fn, ctx, *args, axes, axis_index_groups):\nreplica_groups = _replica_groups_mhlo(\n_replica_groups(ctx.module_context.axis_env, named_axes,\naxis_index_groups))\n- def all_reduce(x_dtype, x):\n+ axis_context = ctx.module_context.axis_context\n+ is_manual = isinstance(axis_context, mlir.SPMDAxisContext)\n+\n+ def all_reduce(aval, x):\n+ if is_manual:\n+ channel = ctx.module_context.new_channel()\n+ other_args = dict(\n+ channel_handle=mhlo.ChannelHandle.get(\n+ channel, mlir.DEVICE_TO_DEVICE_TYPE),\n+ use_global_device_ids=ir.BoolAttr.get(True))\n+ else:\n+ other_args = {}\nop = mhlo.AllReduceOp(\n- x.type, x, replica_groups=replica_groups, channel_handle=None)\n- scalar_aval = core.ShapedArray((), x_dtype)\n+ x.type, x, replica_groups=replica_groups, **other_args)\n+ scalar_aval = core.ShapedArray((), aval.dtype)\nscalar_type = mlir.aval_to_ir_type(scalar_aval)\nreducer_block = op.regions[0].blocks.append(scalar_type, scalar_type)\nwith ir.InsertionPoint(reducer_block):\n@@ -729,7 +740,7 @@ def _allreduce_lowering(prim, pos_fn, ctx, *args, axes, axis_index_groups):\nmhlo.ReturnOp(util.flatten(out_nodes))\nreturn op.result\n- return [all_reduce(aval.dtype, x) for aval, x in zip(ctx.avals_in, args)]\n+ return [all_reduce(aval, x) for aval, x in zip(ctx.avals_in, args)]\ndef _psum_transpose_rule(cts, *args, axes, axis_index_groups):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -357,10 +357,17 @@ class SPMDAxisContext:\n@property\ndef axis_env(self):\n- # TODO: Should we restrict the mesh to manual axes? This depends on the\n- # semantics of ReplicaId in partially manual computations, but I don't\n- # know what they are...\n- return xla.AxisEnv(nreps=1, names=(), sizes=())\n+ # All collectives that touch axis_env should remember to set use_global_device_ids\n+ # when this context is enabled!\n+ if self.manual_axes != frozenset(self.mesh.axis_names):\n+ raise NotImplementedError(\n+ \"Collectives in manually partitioned computations are only supported \"\n+ \"when all mesh axes are partitioned manually (no partial automatic sharding). \"\n+ \"Make sure that you mention all mesh axes in axis_resources!\")\n+ return xla.AxisEnv(\n+ nreps=self.mesh.size,\n+ names=self.mesh.axis_names,\n+ sizes=tuple(self.mesh.shape.values()))\ndef extend_manual(self, axes: FrozenSet[MeshAxisName]) -> SPMDAxisContext:\nreturn SPMDAxisContext(self.mesh, self.manual_axes | axes)\n@@ -1056,7 +1063,6 @@ def lower_fun(fun: Callable, multiple_results: bool = True) -> Callable:\ndef f_lowered(ctx, *args, **params):\nf = fun if multiple_results else lambda *args, **kw: (fun(*args, **kw),)\nwrapped_fun = lu.wrap_init(f, params)\n- axis_env = ctx.module_context.axis_env\nif config.jax_dynamic_shapes:\n# We might be applying this function to arguments with dynamic shapes,\n@@ -1072,10 +1078,8 @@ def lower_fun(fun: Callable, multiple_results: bool = True) -> Callable:\nif type(a) is core.DShapedArray else a, True)\nfor a in ctx.avals_in]\nwrapped_fun = lu.annotate(wrapped_fun, (*implicit_args, *explicit_args))\n- with core.extend_axis_env_nd(zip(axis_env.names, axis_env.sizes)):\njaxpr, _, consts = pe.trace_to_jaxpr_dynamic2(wrapped_fun)\nelse:\n- with core.extend_axis_env_nd(zip(axis_env.names, axis_env.sizes)):\njaxpr, _, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, ctx.avals_in)\nout, tokens = jaxpr_subcomp(\n@@ -1360,6 +1364,7 @@ def xla_fallback_lowering(prim: core.Primitive):\nregister_lowering(ad.custom_lin_p, ad._raise_custom_vjp_error_on_jvp)\n+DEVICE_TO_DEVICE_TYPE = 1\nSEND_TO_HOST_TYPE = 2\nRECV_FROM_HOST_TYPE = 3\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -2743,7 +2743,6 @@ def lower_mesh_computation(\n]\nreplicated_args = [False] * len(in_jaxpr_avals)\naxis_ctx = mlir.SPMDAxisContext(mesh)\n- axis_env = axis_ctx.axis_env\nelse:\nreplicated_args = [not _get_array_mapping(i.spec) for i in in_shardings] # type: ignore\nin_partitions = None\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/xmap_test.py",
"new_path": "tests/xmap_test.py",
"diff": "@@ -819,6 +819,21 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\nx = jnp.arange(20, dtype=jnp.float32).reshape(4, 5)\nself.assertAllClose(h(x), jnp.sin(x * x) + x * x + x)\n+ @parameterized.named_parameters(\n+ {'testcase_name': name, 'mesh': mesh}\n+ for name, mesh in (\n+ ('1d', (('x', 2),)),\n+ ('2d', (('x', 2), ('y', 2))),\n+ ))\n+ @jtu.with_mesh_from_kwargs\n+ def testCollective(self, mesh):\n+ all_axes = tuple(axis[0] for axis in mesh)\n+ f = xmap(lambda x: lax.psum(x, 'i'), in_axes=['i', 'j'], out_axes=['j'],\n+ axis_resources=dict(zip('ij', all_axes)))\n+ h = pjit(lambda x: f(x * x), in_axis_resources=P(*all_axes), out_axis_resources=None)\n+ x = jnp.arange(16, dtype=jnp.float32).reshape(4, 4)\n+ self.assertAllClose(h(x), (x * x).sum(0))\n+\nclass NamedNumPyTest(XMapTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Allow collectives in manually sharded computations
... at least when the manual sharding applies to the whole mesh, because
that's all that XLA can support right now. This is especially important
when computing gradients of xmapped functions (when manual lowering is
enabled), since AD often introduces many `psum`s.
PiperOrigin-RevId: 467895089 |
260,287 | 16.08.2022 09:13:30 | 25,200 | 2aea07827cc6171e9f7e66f21c153b7ec463dedb | Fix XLA fallback to avoid checking the mesh conditions
The warning about not using the full mesh manually is mainly to improve error messages
(otherwise an XLA error is generated). But the MLIR lowering fallback uses axis_env
unconditionally, so we have to go around that check. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -364,6 +364,10 @@ class SPMDAxisContext:\n\"Collectives in manually partitioned computations are only supported \"\n\"when all mesh axes are partitioned manually (no partial automatic sharding). \"\n\"Make sure that you mention all mesh axes in axis_resources!\")\n+ return self.unsafe_axis_env\n+\n+ @property\n+ def unsafe_axis_env(self):\nreturn xla.AxisEnv(\nnreps=self.mesh.size,\nnames=self.mesh.axis_names,\n@@ -1340,8 +1344,13 @@ def xla_fallback_lowering(prim: core.Primitive):\n@cache_lowering\ndef fallback(ctx: LoweringRuleContext, *args, **params):\nmodule_ctx = ctx.module_context\n+ axis_ctx = module_ctx.axis_context\n+ if isinstance(axis_ctx, SPMDAxisContext):\n+ axis_env = axis_ctx.unsafe_axis_env\n+ else:\n+ axis_env = module_ctx.axis_env\nxla_computation = xla.primitive_subcomputation(\n- module_ctx.platform, module_ctx.axis_env, prim, ctx.avals_in,\n+ module_ctx.platform, axis_env, prim, ctx.avals_in,\nctx.avals_out, **params)\nxla_module = xla_computation_to_mhlo_module(xla_computation)\ncallee_name = merge_mhlo_modules(\n"
}
] | Python | Apache License 2.0 | google/jax | Fix XLA fallback to avoid checking the mesh conditions
The warning about not using the full mesh manually is mainly to improve error messages
(otherwise an XLA error is generated). But the MLIR lowering fallback uses axis_env
unconditionally, so we have to go around that check.
PiperOrigin-RevId: 467941551 |
260,557 | 14.08.2022 08:26:27 | -7,200 | 99c5e91874a973b0dc7f39bba040bbcf133d82ce | add dtype arg to jnp.stack and friends
Since the np.stack group is getting a dtype argument in numpy 1.24, they
should also have it in JAX.
Because they are just wrappers of np.concatenate, the changes are small. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -1616,14 +1616,14 @@ def pad(array, pad_width, mode=\"constant\", **kwargs):\n@_wraps(np.stack, skip_params=['out'])\n-def stack(arrays, axis: int = 0, out=None):\n+def stack(arrays, axis: int = 0, out=None, dtype=None):\nif not len(arrays):\nraise ValueError(\"Need at least one array to stack.\")\nif out is not None:\nraise NotImplementedError(\"The 'out' argument to jnp.stack is not supported.\")\nif isinstance(arrays, (np.ndarray, ndarray)):\naxis = _canonicalize_axis(axis, arrays.ndim)\n- return concatenate(expand_dims(arrays, axis + 1), axis=axis)\n+ return concatenate(expand_dims(arrays, axis + 1), axis=axis, dtype=dtype)\nelse:\n_stackable(*arrays) or _check_arraylike(\"stack\", *arrays)\nshape0 = shape(arrays[0])\n@@ -1633,7 +1633,7 @@ def stack(arrays, axis: int = 0, out=None):\nif shape(a) != shape0:\nraise ValueError(\"All input arrays must have the same shape.\")\nnew_arrays.append(expand_dims(a, axis))\n- return concatenate(new_arrays, axis=axis)\n+ return concatenate(new_arrays, axis=axis, dtype=dtype)\n@_wraps(np.tile)\ndef tile(A, reps):\n@@ -1696,33 +1696,33 @@ def concatenate(arrays, axis: int = 0, dtype=None):\n@_wraps(np.vstack)\n-def vstack(tup):\n+def vstack(tup, dtype=None):\nif isinstance(tup, (np.ndarray, ndarray)):\narrs = jax.vmap(atleast_2d)(tup)\nelse:\narrs = [atleast_2d(m) for m in tup]\n- return concatenate(arrs, axis=0)\n+ return concatenate(arrs, axis=0, dtype=dtype)\nrow_stack = vstack\n@_wraps(np.hstack)\n-def hstack(tup):\n+def hstack(tup, dtype=None):\nif isinstance(tup, (np.ndarray, ndarray)):\narrs = jax.vmap(atleast_1d)(tup)\narr0_ndim = arrs.ndim - 1\nelse:\narrs = [atleast_1d(m) for m in tup]\narr0_ndim = arrs[0].ndim\n- return concatenate(arrs, axis=0 if arr0_ndim == 1 else 1)\n+ return concatenate(arrs, axis=0 if arr0_ndim == 1 else 1, dtype=dtype)\n@_wraps(np.dstack)\n-def dstack(tup):\n+def dstack(tup, dtype=None):\nif isinstance(tup, (np.ndarray, ndarray)):\narrs = jax.vmap(atleast_3d)(tup)\nelse:\narrs = [atleast_3d(m) for m in tup]\n- return concatenate(arrs, axis=2)\n+ return concatenate(arrs, axis=2, dtype=dtype)\n@_wraps(np.column_stack)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -3311,9 +3311,11 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CompileAndCheck(jnp_fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"{}_axis={}_array={}\".format(\n- jtu.format_test_name_suffix(\"\", [shape] * len(dtypes), dtypes), axis, array_input),\n- \"shape\": shape, \"axis\": axis, \"dtypes\": dtypes, \"array_input\": array_input}\n+ {\"testcase_name\": \"{}_axis={}_array={}_out={}\".format(\n+ jtu.format_test_name_suffix(\"\", [shape] * len(dtypes), dtypes), axis, array_input,\n+ np.dtype(out_dtype).name),\n+ \"shape\": shape, \"axis\": axis, \"dtypes\": dtypes, \"array_input\": array_input,\n+ \"out_dtype\": out_dtype}\nfor dtypes in [\n[np.float32],\n[np.float32, np.float32],\n@@ -3323,23 +3325,30 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n]\nfor shape in [(), (2,), (3, 4), (1, 100)]\nfor axis in range(-len(shape), len(shape) + 1)\n- for array_input in [True, False]))\n- def testStack(self, shape, axis, dtypes, array_input):\n+ for array_input in [True, False]\n+ for out_dtype in [np.float32, np.int32]))\n+ def testStack(self, shape, axis, dtypes, array_input, out_dtype):\nrng = jtu.rand_default(self.rng())\nif array_input:\nargs_maker = lambda: [np.array([rng(shape, dtype) for dtype in dtypes])]\nelse:\nargs_maker = lambda: [[rng(shape, dtype) for dtype in dtypes]]\n- np_fun = _promote_like_jnp(partial(np.stack, axis=axis))\n- jnp_fun = partial(jnp.stack, axis=axis)\n+\n+ if numpy_version < (1, 24):\n+ np_fun = _promote_like_jnp(lambda *args: np.stack(*args, axis=axis).astype(out_dtype))\n+ else:\n+ np_fun = _promote_like_jnp(partial(np.stack, axis=axis, dtype=out_dtype))\n+\n+ jnp_fun = partial(jnp.stack, axis=axis, dtype=out_dtype)\nwith jtu.strict_promotion_if_dtypes_match(dtypes):\nself._CheckAgainstNumpy(jnp_fun, np_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_op={}_{}_array={}\".format(\n- op, jtu.format_test_name_suffix(\"\", [shape] * len(dtypes), dtypes), array_input),\n- \"shape\": shape, \"op\": op, \"dtypes\": dtypes, \"array_input\": array_input}\n+ {\"testcase_name\": \"_op={}_{}_array={}_out={}\".format(\n+ op, jtu.format_test_name_suffix(\"\", [shape] * len(dtypes), dtypes), array_input,\n+ np.dtype(out_dtype).name),\n+ \"shape\": shape, \"op\": op, \"dtypes\": dtypes, \"array_input\": array_input, \"out_dtype\": out_dtype}\nfor op in [\"hstack\", \"vstack\", \"dstack\"]\nfor dtypes in [\n[np.float32],\n@@ -3349,15 +3358,21 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n[np.float32, np.int32, np.float64],\n]\nfor shape in [(), (2,), (3, 4), (1, 100), (2, 3, 4)]\n- for array_input in [True, False]))\n- def testHVDStack(self, shape, op, dtypes, array_input):\n+ for array_input in [True, False]\n+ for out_dtype in [np.float32, np.int32]))\n+ def testHVDStack(self, shape, op, dtypes, array_input, out_dtype):\nrng = jtu.rand_default(self.rng())\nif array_input:\nargs_maker = lambda: [np.array([rng(shape, dtype) for dtype in dtypes])]\nelse:\nargs_maker = lambda: [[rng(shape, dtype) for dtype in dtypes]]\n- np_fun = _promote_like_jnp(getattr(np, op))\n- jnp_fun = getattr(jnp, op)\n+\n+ if numpy_version < (1, 24) or op == \"dstack\":\n+ np_fun = _promote_like_jnp(lambda *args: getattr(np, op)(*args).astype(out_dtype))\n+ else:\n+ np_fun = partial(_promote_like_jnp(getattr(np, op)), dtype=out_dtype)\n+\n+ jnp_fun = partial(getattr(jnp, op), dtype=out_dtype)\nwith jtu.strict_promotion_if_dtypes_match(dtypes):\nself._CheckAgainstNumpy(jnp_fun, np_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n@@ -6388,7 +6403,7 @@ class NumpySignaturesTest(jtu.JaxTestCase):\n'einsum': ['kwargs'],\n'einsum_path': ['einsum_call'],\n'eye': ['order', 'like'],\n- 'hstack': ['dtype', 'casting'],\n+ 'hstack': ['casting'],\n'identity': ['like'],\n'in1d': ['kind'],\n'isin': ['kind'],\n@@ -6400,11 +6415,11 @@ class NumpySignaturesTest(jtu.JaxTestCase):\n'histogramdd': ['normed'],\n'ones': ['order', 'like'],\n'ones_like': ['subok', 'order'],\n- 'row_stack': ['dtype', 'casting'],\n- 'stack': ['dtype', 'casting'],\n+ 'row_stack': ['casting'],\n+ 'stack': ['casting'],\n'tri': ['like'],\n'unique': ['equal_nan'],\n- 'vstack': ['dtype', 'casting'],\n+ 'vstack': ['casting'],\n'zeros_like': ['subok', 'order']\n}\n"
}
] | Python | Apache License 2.0 | google/jax | add dtype arg to jnp.stack and friends
Since the np.stack group is getting a dtype argument in numpy 1.24, they
should also have it in JAX.
Because they are just wrappers of np.concatenate, the changes are small. |
260,510 | 16.08.2022 10:45:17 | 25,200 | 6ae46c3d696444c840763c78b38788306227a182 | Bump pmap_test size to handle new eager tests | [
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -526,9 +526,9 @@ jax_test(\nname = \"pmap_test\",\nsrcs = [\"pmap_test.py\"],\nshard_count = {\n- \"cpu\": 5,\n+ \"cpu\": 10,\n\"gpu\": 10,\n- \"tpu\": 5,\n+ \"tpu\": 10,\n},\ntags = [\"multiaccelerator\"],\ndeps = [\n"
}
] | Python | Apache License 2.0 | google/jax | Bump pmap_test size to handle new eager tests
PiperOrigin-RevId: 467967021 |
260,419 | 16.08.2022 14:12:20 | 18,000 | 475d4d149755907fd0aa0bbc8d3e93a0dd598a70 | Increase jax.distributed timeout to 5 min | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/distributed.py",
"new_path": "jax/_src/distributed.py",
"diff": "@@ -72,8 +72,10 @@ class State:\nif self.client is not None:\nraise RuntimeError('distributed.initialize should only be called once.')\n+ # Set init_timeout to 5 min to leave time for all the processes to connect\nself.client = xla_extension.get_distributed_runtime_client(\n- coordinator_address, process_id, config.jax_coordination_service)\n+ coordinator_address, process_id, config.jax_coordination_service,\n+ init_timeout=300)\nlogging.info('Connecting to JAX distributed service on %s', coordinator_address)\nself.client.connect()\n"
}
] | Python | Apache License 2.0 | google/jax | Increase jax.distributed timeout to 5 min |
260,631 | 16.08.2022 14:25:10 | 25,200 | 0abbdd064846817e97ca751d1c7ee5f4a933789c | Add a backend field to `mlir.ModuleContext` so that host callback lowering can use the correct backend | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -852,7 +852,7 @@ def xla_computation(fun: Callable,\nfun_name = getattr(fun, \"__name__\", \"unknown\")\n- backend = backend if backend is not None else xb.get_backend().platform\n+ platform = backend if backend is not None else xb.get_backend().platform\ndef make_axis_env(nreps):\nif axis_env is None:\n@@ -905,14 +905,15 @@ def xla_computation(fun: Callable,\ncore.ClosedJaxpr(jaxpr, consts),\nunordered_effects=unordered_effects,\nordered_effects=ordered_effects,\n- platform=backend,\n+ backend_or_name=backend,\n+ platform=platform,\naxis_context=mlir.ReplicaAxisContext(axis_env_),\nname_stack=new_name_stack(wrap_name(fun_name, \"xla_computation\")),\ndonated_args=donated_invars,\n- arg_shardings=(None if in_parts_flat is None else\n- map(xla.sharding_to_proto, in_parts_flat)),\n- result_shardings=(None if out_parts_flat is None else\n- map(xla.sharding_to_proto, out_parts_flat)))\n+ arg_shardings=(None if in_parts_flat is None else map(\n+ xla.sharding_to_proto, in_parts_flat)),\n+ result_shardings=(None if out_parts_flat is None else map(\n+ 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(\nmlir.module_to_string(lowering_result.module),\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -383,8 +383,8 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nordered_effects = [eff for eff in closed_jaxpr.effects\nif eff in core.ordered_effects]\nlowering_result = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr,\n- unordered_effects, ordered_effects, backend.platform,\n+ module_name, closed_jaxpr, unordered_effects,\n+ ordered_effects, backend, backend.platform,\nmlir.ReplicaAxisContext(axis_env), name_stack, donated_invars)\nmodule, keepalive, host_callbacks = (\nlowering_result.module, lowering_result.keepalive,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -1099,7 +1099,7 @@ def _outside_call_translation_rule(ctx, avals_in, avals_out,\nxla.aval_to_xla_shapes(res_aval)[0]\nfor res_aval in callback_flat_results_aval\n]\n- backend = xb.get_backend(ctx.platform)\n+ backend = ctx.module_context.backend\ntoken_and_results_op, keep_alive = backend.emit_python_callback(\nwrapped_callback,\ncomp,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -411,6 +411,7 @@ class ModuleContext:\nmodule: ir.Module\nip: ir.InsertionPoint\nsymbol_table: ir.SymbolTable\n+ backend_or_name: Optional[Union[str, xb.XlaBackend]]\nplatform: str\naxis_context: AxisContext\nname_stack: NameStack\n@@ -428,6 +429,7 @@ class ModuleContext:\ndef __init__(\nself,\n+ backend_or_name: Optional[Union[str, xb.XlaBackend]],\nplatform: str,\naxis_context: AxisContext,\nname_stack: NameStack,\n@@ -447,6 +449,7 @@ class ModuleContext:\nself.module = module or ir.Module.create(loc=ir.Location.unknown(self.context))\nself.ip = ip or ir.InsertionPoint(self.module.body)\nself.symbol_table = symbol_table or ir.SymbolTable(self.module.operation)\n+ self.backend_or_name = backend_or_name\nself.platform = platform\nself.axis_context = axis_context\nself.name_stack = name_stack\n@@ -459,6 +462,12 @@ class ModuleContext:\nif cached_call_jaxpr_lowerings is None\nelse cached_call_jaxpr_lowerings)\n+ @property\n+ def backend(self) -> xb.XlaBackend:\n+ if self.backend_or_name is None or isinstance(self.backend_or_name, str):\n+ return xb.get_backend(self.backend_or_name)\n+ return self.backend_or_name\n+\ndef new_channel(self) -> int:\nreturn next(self.channel_iterator)\n@@ -566,6 +575,7 @@ def lower_jaxpr_to_module(\njaxpr: core.ClosedJaxpr,\nunordered_effects: List[core.Effect],\nordered_effects: List[core.Effect],\n+ backend_or_name: Optional[Union[str, xb.XlaBackend]],\nplatform: str,\naxis_context: AxisContext,\nname_stack: NameStack,\n@@ -615,8 +625,8 @@ def lower_jaxpr_to_module(\n# Create a keepalives list that will be mutated during the lowering.\nkeepalives: List[Any] = []\nhost_callbacks: List[Any] = []\n- ctx = ModuleContext(platform, axis_context, name_stack, keepalives,\n- channel_iter, host_callbacks)\n+ ctx = ModuleContext(backend_or_name, platform, axis_context, name_stack,\n+ keepalives, 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@@ -1441,12 +1451,17 @@ def receive_from_host(channel: int, token: mhlo.TokenType,\nreturn token, result\n-def _emit_tpu_python_callback(backend: xb.XlaBackend, ctx: LoweringRuleContext,\n- callback, token: Optional[Any], operands: List[ir.Value],\n+def _emit_tpu_python_callback(\n+ backend: xb.XlaBackend,\n+ ctx: LoweringRuleContext,\n+ callback,\n+ token: Optional[Any],\n+ operands: List[ir.Value],\noperand_avals: List[core.ShapedArray],\noperand_shapes: List[xc.Shape],\nresult_avals: List[core.ShapedArray],\n- result_shapes: List[xc.Shape], *,\n+ result_shapes: List[xc.Shape],\n+ *,\nsharding: Optional[xc.OpSharding] = None\n) -> Tuple[List[ir.Value], Any, Any]:\ntoken = token or mhlo.CreateTokenOp(mhlo.TokenType.get()).result\n@@ -1533,7 +1548,7 @@ def emit_python_callback(\nif platform not in {\"cpu\", \"cuda\", \"rocm\", \"tpu\"}:\nraise ValueError(\nf\"`EmitPythonCallback` not supported on {platform} backend.\")\n- backend = xb.get_backend(platform)\n+ backend = ctx.module_context.backend\nresult_shapes = util.flatten(\n[xla.aval_to_xla_shapes(result_aval) for result_aval in result_avals])\noperand_shapes = util.flatten(\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1372,9 +1372,15 @@ def lower_parallel_callable(\nunordered_effects = [eff for eff in closed_jaxpr.effects\nif eff not in core.ordered_effects]\nlowering_result = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, unordered_effects, [],\n- backend.platform, mlir.ReplicaAxisContext(axis_env),\n- name_stack, donated_invars, replicated_args=replicated_args,\n+ module_name,\n+ closed_jaxpr,\n+ unordered_effects, [],\n+ backend,\n+ backend.platform,\n+ mlir.ReplicaAxisContext(axis_env),\n+ name_stack,\n+ donated_invars,\n+ replicated_args=replicated_args,\narg_shardings=_shardings_to_mlir_shardings(parts.arg_parts),\nresult_shardings=_shardings_to_mlir_shardings(parts.out_parts))\nmodule, keepalive, host_callbacks = (\n@@ -2624,9 +2630,17 @@ def lower_sharding_computation(\nunordered_effects = [eff for eff in closed_jaxpr.effects\nif eff not in core.ordered_effects]\nlowering_result = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, unordered_effects, [], backend.platform,\n- axis_ctx, name_stack, donated_invars, replicated_args=replicated_args,\n- arg_shardings=in_op_shardings, result_shardings=out_op_shardings)\n+ module_name,\n+ closed_jaxpr,\n+ unordered_effects, [],\n+ backend,\n+ backend.platform,\n+ axis_ctx,\n+ name_stack,\n+ donated_invars,\n+ replicated_args=replicated_args,\n+ arg_shardings=in_op_shardings,\n+ result_shardings=out_op_shardings)\nmodule, keepalive, host_callbacks = (\nlowering_result.module, lowering_result.keepalive,\nlowering_result.host_callbacks)\n@@ -2760,9 +2774,17 @@ def lower_mesh_computation(\nunordered_effects = [eff for eff in closed_jaxpr.effects\nif eff not in core.ordered_effects]\nlowering_result = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, unordered_effects, [], backend.platform,\n- axis_ctx, name_stack, donated_invars, replicated_args=replicated_args,\n- arg_shardings=in_partitions, result_shardings=out_partitions)\n+ module_name,\n+ closed_jaxpr,\n+ unordered_effects, [],\n+ backend,\n+ backend.platform,\n+ axis_ctx,\n+ name_stack,\n+ donated_invars,\n+ replicated_args=replicated_args,\n+ arg_shardings=in_partitions,\n+ result_shardings=out_partitions)\nmodule, keepalive, host_callbacks = (\nlowering_result.module, lowering_result.keepalive,\nlowering_result.host_callbacks)\n"
}
] | Python | Apache License 2.0 | google/jax | Add a backend field to `mlir.ModuleContext` so that host callback lowering can use the correct backend
PiperOrigin-RevId: 468024979 |
260,335 | 16.08.2022 12:07:27 | 25,200 | d19e34fa4a1d89c02a72dc49896013ba6fc99127 | delete old remat implementation
moved lowering rule logic from remat_impl.py (now deleted) to ad_checkpoint.py | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -10,6 +10,10 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n## jax 0.3.17 (Unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jax-v0.3.16...main).\n+* Breaking changes\n+ * {func}`jax.checkpoint`, also known as {func}`jax.remat`, no longer supports\n+ the `concrete` option, following the previous version's deprecation; see\n+ [JEP 11830](https://jax.readthedocs.io/en/latest/jep/11830-new-remat-checkpoint.html).\n## jax 0.3.16\n* [GitHub commits](https://github.com/google/jax/compare/jax-v0.3.15...main).\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jep/11830-new-remat-checkpoint.md",
"new_path": "docs/jep/11830-new-remat-checkpoint.md",
"diff": "@@ -19,9 +19,7 @@ As of [#11830](https://github.com/google/jax/pull/11830) we're switching on a ne\n## How can I disable the change, and go back to the old behavior for now?\n-In case you have a problem with this change, it will **temporarily** be possible to switch off the new implementation by setting the `jax_new_checkpoint` config option to be False, in any one of these ways:\n-\n-\n+In case you have a problem with this change, **through version `jax==0.3.16`** it is possible to switch off the new implementation by setting the `jax_new_checkpoint` config option to be False, in any one of these ways:\n1. set the shell environment variable `JAX_NEW_CHECKPOINT=0`;\n2. execute `jax.config.update('jax_new_checkpoint', False)`;\n@@ -29,6 +27,10 @@ In case you have a problem with this change, it will **temporarily** be possible\nIf you need to revert to the old implementation, **please reach out** on a GitHub issue so that we can make the new implementation work for you.\n+As of `jax==0.3.17` the `jax_new_checkpoint` config option is no longer\n+available. If you have an issue, please reach out on [the issue\n+tracker](https://github.com/google/jax/issues) so we can help fix it!\n+\n## Why are we doing this?\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -18,19 +18,23 @@ from typing import Callable, Optional, List, Tuple, Sequence, Set, Union, Any\nimport types\nfrom absl import logging\n+import numpy as np\nimport jax\nfrom jax import core\nfrom jax import linear_util as lu\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\n-from jax.interpreters import partial_eval as pe\nfrom jax.interpreters import mlir\n+from jax.interpreters import partial_eval as pe\n+from jax.interpreters import xla\nfrom jax.tree_util import tree_flatten, tree_unflatten\nfrom jax._src import ad_util\n+from jax._src import util\nfrom jax._src import source_info_util\nfrom jax._src import traceback_util\nfrom jax._src.api_util import flatten_fun, shaped_abstractify\n+from jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.traceback_util import api_boundary\nfrom jax._src.util import (unzip2, wraps, split_list, partition_list, safe_map,\nsafe_zip, merge_lists, weakref_lru_cache)\n@@ -38,9 +42,6 @@ from jax._src.util import (unzip2, wraps, split_list, partition_list, safe_map,\nsource_info_util.register_exclusion(__file__)\ntraceback_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-\nmap = safe_map\nzip = safe_zip\n@@ -582,6 +583,104 @@ def remat_dce(used_outputs: List[bool], eqn: core.JaxprEqn\npe.dce_rules[remat_p] = remat_dce\n+def remat_lowering(*args, jaxpr: core.Jaxpr, prevent_cse: bool,\n+ differentiated: bool, is_gpu_platform: bool = False,\n+ **_):\n+ assert not jaxpr.constvars\n+\n+ if differentiated and prevent_cse:\n+ if jax.config.jax_remat_opt_barrier:\n+ translation_rule = _remat_translation_using_opt_barrier\n+ elif is_gpu_platform:\n+ translation_rule = _remat_translation_using_while\n+ else:\n+ translation_rule = _remat_translation_using_cond\n+ else:\n+ translation_rule = lambda *args, jaxpr: core.eval_jaxpr(jaxpr, (), *args)\n+\n+ return jax.named_call(translation_rule, name=\"remat\")(*args, jaxpr=jaxpr)\n+\n+def _remat_translation_using_opt_barrier(*args, jaxpr: core.Jaxpr):\n+ args = _optimization_barrier(args)\n+ return core.eval_jaxpr(jaxpr, (), *args)\n+\n+# TODO(mattjj): add core utility for 'create dummy value for this type'?\n+def _dummy_like(aval: core.AbstractValue) -> Any:\n+ if aval is core.abstract_token:\n+ return jax.lax.create_token()\n+ elif isinstance(aval, (core.ShapedArray, core.DShapedArray)):\n+ return jax.lax.broadcast(jax.lax.empty(aval.dtype), aval.shape) # type: ignore\n+ else:\n+ raise ValueError(aval)\n+\n+def _remat_translation_using_while(*args, jaxpr: core.Jaxpr):\n+ # Implements:\n+ # for(counter=0, result=0; counter < rng(1, 2); counter ++) {\n+ # result = eval_jaxpr(*args)\n+ # }\n+ # The loop carry is a tuple: (counter, result, args)\n+ avals_out = tuple(v.aval for v in jaxpr.outvars)\n+ carry_init = (np.int32(0), tuple(map(_dummy_like, avals_out)), args)\n+ def cond(carry):\n+ counter, _, _ = carry\n+ unif = jax.lax.rng_uniform(np.int32(1), np.int32(2), shape=())\n+ return counter < unif\n+\n+ def body(carry):\n+ counter, _, args = carry\n+ results = core.eval_jaxpr(jaxpr, (), *args)\n+ return (counter + 1, tuple(results), args)\n+\n+ carry_res = jax.lax.while_loop(cond, body, carry_init)\n+ return carry_res[1]\n+\n+def _remat_translation_using_cond(*args, jaxpr: core.Jaxpr):\n+ # Implements:\n+ # if(rng(0, 1) < 2)\n+ # return eval_jaxpr(*args)\n+ # else:\n+ # return 0\n+ avals_out = tuple(v.aval for v in jaxpr.outvars)\n+\n+ def remat_comp(*args):\n+ return tuple(core.eval_jaxpr(jaxpr, (), *args))\n+ def dummy_comp(*args):\n+ return tuple(map(_dummy_like, avals_out))\n+\n+ unif = jax.lax.rng_uniform(np.float32(0), np.float32(1), shape=())\n+ return jax.lax.cond(unif < np.float32(2), remat_comp, dummy_comp, *args)\n+\n+mlir.register_lowering(\n+ remat_p, mlir.lower_fun(remat_lowering, multiple_results=True))\n+mlir.register_lowering(\n+ remat_p,\n+ mlir.lower_fun(partial(remat_lowering, is_gpu_platform=True),\n+ multiple_results=True),\n+ platform=\"gpu\")\n+\n+def _optimization_barrier_abstract_eval(*args):\n+ return args\n+\n+def _optimization_barrier_lowering_rule(ctx, *args):\n+ barrier_types = map(mlir.aval_to_ir_types, ctx.avals_in)\n+ flat_barrier_types = util.flatten(barrier_types)\n+ flat_args = mlir.flatten_lowering_ir_args(args)\n+ barrier_op = mhlo.OptimizationBarrierOp(flat_barrier_types, flat_args)\n+ return util.unflatten(barrier_op.results, map(len, barrier_types))\n+\n+def _optimization_barrier(arg):\n+ flat_args, treedef = tree_flatten(arg)\n+ return tree_unflatten(treedef, optimization_barrier_p.bind(*flat_args))\n+\n+optimization_barrier_p = core.Primitive('optimization_barrier')\n+optimization_barrier_p.multiple_results = True\n+optimization_barrier_p.def_impl(\n+ partial(xla.apply_primitive, optimization_barrier_p))\n+optimization_barrier_p.def_abstract_eval(_optimization_barrier_abstract_eval)\n+mlir.register_lowering(optimization_barrier_p,\n+ _optimization_barrier_lowering_rule)\n+\n+\ndef checkpoint_name(x, name):\nreturn name_p.bind(x, name=name)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -3103,27 +3103,11 @@ def checkpoint(fun: Callable, *,\n\" return f(x)\\n\"\n\" else:\\n\"\n\" return g(x)\\n\"\n- \"\\n\")\n- if config.jax_new_checkpoint:\n+ \"\\n\"\n+ \"See https://jax.readthedocs.io/en/latest/jep/11830-new-remat-checkpoint.html\\n\")\nraise NotImplementedError(msg)\n- else:\n- warn(msg, DeprecationWarning)\n-\n- if config.jax_new_checkpoint:\nreturn new_checkpoint(fun, prevent_cse=prevent_cse, policy=policy,\nstatic_argnums=static_argnums)\n-\n- @wraps(fun)\n- @api_boundary\n- def remat_f(*args, **kwargs):\n- f, args = _remat_static_argnums(fun, static_argnums, args)\n- args_flat, in_tree = tree_flatten((args, kwargs))\n- flat_fun, out_tree = flatten_fun(lu.wrap_init(f), in_tree)\n- out_flat = pe.remat_call(flat_fun, *args_flat, name=flat_fun.__name__,\n- concrete=concrete, prevent_cse=prevent_cse,\n- differentiated=False, policy=policy)\n- return tree_unflatten(out_tree(), out_flat)\n- return remat_f\nremat = checkpoint # type: ignore\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/config.py",
"new_path": "jax/_src/config.py",
"diff": "@@ -875,13 +875,6 @@ config.define_bool_state(\ndefault=(lib.version >= (0, 3, 6)),\nhelp=('Enables using optimization-barrier op for lowering remat.'))\n-# TODO(mattjj): set default to True, then remove\n-config.define_bool_state(\n- name='jax_new_checkpoint',\n- default=True,\n- upgrade=True,\n- help='Whether to use the new jax.checkpoint implementation.')\n-\n# TODO(b/205307544): Remove flag once coordination service has rolled out.\nconfig.define_bool_state(\nname='jax_coordination_service',\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/__init__.py",
"new_path": "jax/_src/lax/control_flow/__init__.py",
"diff": "@@ -19,8 +19,6 @@ from jax._src.lax.control_flow.loops import (associative_scan, cummax, cummax_p,\nscan, scan_bind, scan_p,\n_scan_impl, while_loop, while_p)\nfrom jax._src.lax.control_flow.conditionals import cond, cond_p, switch\n-from jax._src.lax.control_flow.remat_impl import (remat_impl,\n- optimization_barrier_p)\nfrom jax._src.lax.control_flow.solves import (custom_linear_solve, custom_root,\n_custom_linear_solve_impl,\nlinear_solve_p)\n@@ -32,3 +30,5 @@ from jax._src.lax.control_flow.common import (_initial_style_open_jaxpr,\n_initial_style_jaxpr,\n_initial_style_jaxprs_with_common_consts,\n_check_tree_and_avals)\n+# TODO(mattjj): fix dependent library which expects optimization_barrier_p here\n+from jax._src.ad_checkpoint import optimization_barrier_p\n"
},
{
"change_type": "DELETE",
"old_path": "jax/_src/lax/control_flow/remat_impl.py",
"new_path": null,
"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 the remat implementation.\"\"\"\n-from functools import partial\n-\n-from typing import Optional\n-\n-import jax\n-from jax import core\n-from jax import lax\n-from jax.config import config\n-from jax.interpreters import mlir\n-from jax.interpreters import partial_eval as pe\n-from jax.interpreters import xla\n-from jax.tree_util import tree_flatten, tree_unflatten\n-from jax._src import ad_checkpoint\n-from jax._src import util\n-from jax._src.util import safe_map, wrap_name\n-from jax._src.lax.control_flow.conditionals import cond\n-from jax._src.lib.mlir.dialects import mhlo\n-from jax._src.lax.control_flow.loops import while_loop\n-import numpy as np\n-\n-_map = safe_map\n-\n-def _dummy_remat_result(aval: core.AbstractValue):\n- \"\"\"A result that will be discarded\"\"\"\n- if aval is core.abstract_token:\n- return lax.create_token()\n- else:\n- return lax.broadcast(np.array(0, dtype=aval.dtype), aval.shape) # type: ignore\n-\n-def _remat_translation_using_cond(*args,\n- jaxpr: core.Jaxpr):\n- # Implements:\n- # if(rng(0, 1) < 2)\n- # return eval_jaxpr(*args)\n- # else:\n- # return 0\n- avals_out = tuple(ov.aval for ov in jaxpr.outvars)\n-\n- def remat_comp(*args):\n- return tuple(core.eval_jaxpr(jaxpr, (), *args))\n- def dummy_comp(*args):\n- return tuple(_map(_dummy_remat_result, avals_out))\n-\n- cond_pred = (lax.rng_uniform(np.float32(0), np.float32(1), shape=()) < np.float32(2))\n- return cond(cond_pred, remat_comp, dummy_comp, *args)\n-\n-def _remat_translation_using_while(*args,\n- jaxpr: core.Jaxpr):\n- # Implements:\n- # for(counter=0, result=0; counter < rng(1, 2); counter ++) {\n- # result = eval_jaxpr(*args)\n- # }\n- # The loop carry is a tuple: (counter, result, args)\n- avals_out = tuple(ov.aval for ov in jaxpr.outvars)\n- dummies_like_result = tuple(_map(_dummy_remat_result, avals_out))\n- carry_init = (np.int32(0), dummies_like_result, args)\n- def cond(carry):\n- counter, _, _ = carry\n- return counter < lax.rng_uniform(np.int32(1), np.int32(2), shape=())\n-\n- def body(carry):\n- counter, _, args = carry\n- results = core.eval_jaxpr(jaxpr, (), *args)\n- return (counter + 1, tuple(results), args)\n-\n- carry_res = while_loop(cond, body, carry_init)\n- return carry_res[1]\n-\n-\n-def _remat_translation_using_opt_barrier(*args, jaxpr: core.Jaxpr):\n- args = _optimization_barrier(args)\n- return core.eval_jaxpr(jaxpr, (), *args)\n-\n-\n-def remat_impl(*args,\n- call_jaxpr: Optional[core.Jaxpr] = None,\n- jaxpr: Optional[core.Jaxpr] = None,\n- prevent_cse: bool, differentiated: bool,\n- policy,\n- is_gpu_platform: bool = False,\n- concrete: bool = False,\n- name: str = \"checkpoint\"):\n- # Support either \"jaxpr\" (for remat2) and \"call_jaxpr\" (for remat)\n- # name is not passed for remat2, defaults to \"checkpoint\"\n- # TODO: remove call_jaxpr once we drop the remat call primitive\n- if jaxpr is None:\n- jaxpr = call_jaxpr\n- assert jaxpr is not None\n- assert not jaxpr.constvars\n-\n- del concrete, policy # Unused.\n- if differentiated and prevent_cse:\n- if config.jax_remat_opt_barrier:\n- translation_rule = _remat_translation_using_opt_barrier\n- elif is_gpu_platform:\n- translation_rule = _remat_translation_using_while\n- else:\n- translation_rule = _remat_translation_using_cond\n- else:\n- translation_rule = lambda *args, jaxpr: core.eval_jaxpr(jaxpr, (), *args)\n-\n- return jax.named_call(translation_rule, name=wrap_name(name, \"remat\"))(*args, jaxpr=jaxpr)\n-\n-for remat_primitive in (pe.remat_call_p, ad_checkpoint.remat_p): # type: ignore\n- mlir.register_lowering(remat_primitive,\n- mlir.lower_fun(remat_impl, multiple_results=True))\n- mlir.register_lowering(remat_primitive,\n- mlir.lower_fun(partial(remat_impl,\n- is_gpu_platform=True),\n- multiple_results=True),\n- platform=\"gpu\")\n-\n-\n-def _optimization_barrier_abstract_eval(*args):\n- return args\n-\n-\n-def _optimization_barrier_lowering_rule(ctx, *args):\n- barrier_types = _map(mlir.aval_to_ir_types, ctx.avals_in)\n- flat_barrier_types = util.flatten(barrier_types)\n-\n- flat_args = mlir.flatten_lowering_ir_args(args)\n- barrier_op = mhlo.OptimizationBarrierOp(flat_barrier_types, flat_args)\n- return util.unflatten(barrier_op.results, _map(len, barrier_types))\n-\n-\n-def _optimization_barrier(arg):\n- flat_args, treedef = tree_flatten(arg)\n- return tree_unflatten(treedef, optimization_barrier_p.bind(*flat_args))\n-\n-\n-optimization_barrier_p = core.Primitive('optimization_barrier')\n-optimization_barrier_p.multiple_results = True\n-optimization_barrier_p.def_impl(\n- partial(xla.apply_primitive, optimization_barrier_p))\n-optimization_barrier_p.def_abstract_eval(_optimization_barrier_abstract_eval)\n-mlir.register_lowering(optimization_barrier_p,\n- _optimization_barrier_lowering_rule)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -1615,16 +1615,6 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\n# cased to just pass-through the token\nin_axes=eqn.params[\"in_axes\"] + (None, None),\nout_axes=eqn.params[\"out_axes\"] + (0, 0))))\n- elif eqn.primitive is pe.remat_call_p:\n- call_jaxpr = cast(core.Jaxpr, eqn.params[\"call_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- call_jaxpr=_rewrite_jaxpr(call_jaxpr, True, True),\n- )))\nelif eqn.primitive is custom_derivatives.custom_jvp_call_jaxpr_p:\nfun_jaxpr = eqn.params[\"fun_jaxpr\"]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1070,9 +1070,9 @@ class TensorFlowTrace(core.Trace):\ndef post_process_call(self, call_primitive: core.Primitive,\nout_tracers: Sequence[TensorFlowTracer], params):\n- # We encountered a call primitive, e.g., remat_call_p, whose result\n- # (out_tracers) include TensorFlowTracer that were not passed through\n- # its arguments (captured from the environment).\n+ # We encountered a call primitive whose result (out_tracers) include\n+ # TensorFlowTracer that were not passed through its arguments (captured from\n+ # the environment).\nvals = tuple(t.val for t in out_tracers)\nmain = self.main\n@@ -1137,8 +1137,7 @@ def _unexpected_primitive(p: core.Primitive, *args, **kwargs):\n# Call primitives are inlined\n-for unexpected in [core.call_p, core.named_call_p, xla.xla_call_p,\n- partial_eval.remat_call_p, maps.xmap_p]:\n+for unexpected in [core.call_p, core.named_call_p, xla.xla_call_p, maps.xmap_p]:\ntf_impl[unexpected] = partial(_unexpected_primitive, unexpected)\n# Primitives that are not yet implemented must be explicitly declared here.\n@@ -2549,7 +2548,7 @@ tf_impl_with_avals[lax.scan_p] = _convert_jax_impl(\nextra_name_stack=\"scan\")\ntf_impl_with_avals[ad_checkpoint.remat_p] = \\\n- _convert_jax_impl(partial(lax_control_flow.remat_impl,\n+ _convert_jax_impl(partial(ad_checkpoint.remat_lowering,\n# TODO: jax2tf cannot discriminate by platform\nis_gpu_platform=False),\nmultiple_results=True,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -42,7 +42,7 @@ import jax._src.lib.xla_bridge\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n# pylint: disable=g-direct-tensorflow-import\n-from tensorflow.compiler.tf2xla.python import xla as tfxla # type: ignore[import]\n+from google3.third_party.tensorflow.compiler.tf2xla.python import xla as tfxla # type: ignore[import]\n# pylint: enable=g-direct-tensorflow-import\nconfig.parse_flags_with_absl()\n@@ -766,16 +766,13 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.TransformConvertAndCompare(f, arg, \"grad\")\nself.TransformConvertAndCompare(f, arg, \"grad_vmap\")\n- @parameterized.named_parameters(jtu.cases_from_list(\n- dict(testcase_name=f\"_{flavor}\", flavor=flavor)\n- for flavor in [\"old\", \"new\"]))\n- def test_remat(self, flavor=\"old\"):\n+ def test_remat(self):\ndef f(x1):\nx2 = jnp.sin(x1)\nx3 = jnp.sin(x2)\nx4 = jnp.sin(x3)\nreturn x4\n- remat_f = jax.remat(f) if flavor == \"old\" else ad_checkpoint.checkpoint(f)\n+ remat_f = ad_checkpoint.checkpoint(f)\n# The computation of grad_f computes \"sin\" 5 times, 3 for the forward pass\n# and then to rematerialize \"x2\" and \"x3\" in the backward pass.\n@@ -783,21 +780,19 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\n# Check that we have a Sin under a conditional\nf_tf = tf.function(jax2tf.convert(jax.grad(remat_f)), autograph=False)\nf_tf_graph = f_tf.get_concrete_function(arg).graph.as_graph_def()\n- if flavor == \"old\":\n- raise unittest.SkipTest(\"TODO: CSE widget not yet implemented for old-style remat\")\nif jax.config.jax_remat_opt_barrier:\nif config.jax2tf_default_experimental_native_lowering:\nself.assertRegex(\nstr(f_tf_graph), r\"mhlo.optimization_barrier\")\nelse:\nself.assertRegex(\n- str(f_tf_graph), r\"remat_checkpoint_/XlaOptimizationBarrier\")\n+ str(f_tf_graph), r\"XlaOptimizationBarrier\")\nelif config.jax_experimental_name_stack:\nself.assertRegex(str(f_tf_graph),\n- r'transpose/jax2tf_f_/jvp/checkpoint/remat_checkpoint_/cond/branch_1_fun/Sin')\n+ r'transpose/jax2tf_f_/jvp/checkpoint/cond/branch_1_fun/Sin')\nelse:\nself.assertRegex(str(f_tf_graph),\n- r'remat_checkpoint_/switch_case/indexed_case/Sin')\n+ r'switch_case/indexed_case/Sin')\ndef test_remat_free_var(self):\ndef f(x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/ad.py",
"new_path": "jax/interpreters/ad.py",
"diff": "@@ -637,39 +637,11 @@ def _closed_call_transpose(params, jaxpr, args, ct, cts_in_avals, reduce_axes):\nprimitive_transposes[core.closed_call_p] = _closed_call_transpose\n-def remat_transpose(params, call_jaxpr, primals_in, cotangents_in,\n- cotangent_in_avals, reduce_axes):\n- unknowns = map(is_undefined_primal, primals_in)\n- primal_jaxpr, tangent_jaxpr, _, _ = \\\n- pe.partial_eval_jaxpr_nounits(pe.close_jaxpr(call_jaxpr),\n- unknowns=unknowns, instantiate=True) # type: ignore\n- args, in_tree = tree_flatten((primals_in, cotangents_in))\n- transpose = lu.hashable_partial(lu.wrap_init(_remat_transpose), primal_jaxpr,\n- tangent_jaxpr, reduce_axes)\n- flat_transpose, out_tree = flatten_fun_nokwargs(transpose, in_tree)\n- flat_cotangents_out = pe.remat_call_p.bind(flat_transpose, *args, **params)\n- return tree_unflatten(out_tree(), flat_cotangents_out)\n-primitive_transposes[pe.remat_call_p] = remat_transpose\n-\n-def _remat_transpose(primal_jaxpr, tangent_jaxpr, reduce_axes,\n- primals_tangents_in, cotangents_in):\n- primals_in = [x for x in primals_tangents_in if not is_undefined_primal(x)]\n- tangents_in = [x for x in primals_tangents_in if is_undefined_primal(x)]\n- res = core.jaxpr_as_fun(primal_jaxpr)(*primals_in)\n- cotangents_out_ = backward_pass(tangent_jaxpr.jaxpr, reduce_axes, False, (),\n- (*res, *tangents_in), cotangents_in)\n- cotangents_out = iter(cotangents_out_[len(res):])\n- outs = [next(cotangents_out) if is_undefined_primal(x) else Zero.from_value(x)\n- for x in primals_tangents_in]\n- assert next(cotangents_out, None) is None\n- return outs\n-\n@lu.transformation_with_aux\ndef nonzero_outputs(*args, **kwargs):\nresults = yield args, kwargs\nyield results, [type(r) is not Zero for r in results]\n-\ndef map_transpose(primitive, params, call_jaxpr, args, ct, _, reduce_axes):\nall_args, in_tree_def = tree_flatten(((), args, ct)) # empty consts\nfun = lu.hashable_partial(lu.wrap_init(backward_pass), call_jaxpr, reduce_axes, False)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1118,127 +1118,6 @@ def _partial_eval_jaxpr_nounits(jaxpr, in_unknowns, instantiate):\nreturn closed_jaxpr_known, closed_jaxpr_unknown, out_unknowns, res_avals\n-remat_call_p: Primitive = core.CallPrimitive('remat_call')\n-remat_call = remat_call_p.bind\n-remat_call_p.def_impl(core.call_impl)\n-\n-def _remat_partial_eval(trace, _, f, tracers, params):\n- concrete = params['concrete']\n-\n- # Unlike JaxprTrace.process_call, we want to form a jaxpr for the entirety of\n- # the function being called, not just for the unknown parts. To do that, we\n- # instantiate all the input tracers as constants in the jaxpr being formed.\n- # Those tracers might have concrete avals, and doing abstract interpretation\n- # on concrete avals engenders a tradeoff: it allows data-dependent Python\n- # control flow to work, but it can in some cases lead to redundant FLOPs (done\n- # both in the `bind` call below and the `core.jaxpr_as_fun` call). We use the\n- # `concrete` parameter to switch this behavior, and if `concrete` is False\n- # then we raise the avals to the Shaped level.\n- if concrete:\n- instantiated_tracers = map(trace.instantiate_const, tracers)\n- else:\n- instantiated_tracers = map(trace.instantiate_const_abstracted, tracers)\n-\n- # Using the instantiated tracers, run call_bind like JaxprTrace.process_call.\n- # This way we record all primitives applied to the inputs (all treated as\n- # unknown/instantiated) to produce the output. In the context of autodiff,\n- # that means we record primal, residual, and tangent computations (e.g. sine,\n- # cosine, and multiply).\n- in_pvals = [t.pval for t in instantiated_tracers]\n- in_knowns, in_avals, () = partition_pvals(in_pvals) # all are unknown\n- assert not any(in_knowns)\n- f = trace_to_subjaxpr_nounits(f, trace.main, True)\n- f, aux = partial_eval_wrapper_nounits(f, tuple(in_knowns), tuple(in_avals))\n- consts = 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`.')\n- env_tracers = map(trace.full_raise, env)\n- jaxpr = convert_constvars_jaxpr(jaxpr)\n- del 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- # optimization.\n-\n- # We're done with `f`, and in the steps to follow we work with `jaxpr`. To\n- # that end, we want a list of which inputs to `jaxpr` are known/unknown.\n- in_unknowns = ([False] * len(consts) +\n- [not t.is_known() for t in it.chain(env_tracers, tracers)])\n-\n- if params['policy']:\n- # unzip into jaxpr_known and jaxpr_unknown\n- jaxpr_known, jaxpr_unknown, out_unknowns, out_inst, _ = \\\n- partial_eval_jaxpr_custom(jaxpr, in_unknowns, [True] * len(in_unknowns),\n- False, False, params['policy'])\n- jaxpr_known, in_used_known = dce_jaxpr(jaxpr_known, [True] * len(jaxpr_known.outvars))\n- _, used_outs_unknown = partition_list(out_inst, out_unknowns)\n- jaxpr_unknown, in_used_unknown = dce_jaxpr(jaxpr_unknown, used_outs_unknown)\n-\n- # compute known outputs and residuals (hoisted out of a remat_call)\n- _, in_consts_ = unzip2(t.pval for t in it.chain(env_tracers, tracers)\n- if t.pval.is_known())\n- _, known_inputs = partition_list(in_used_known, [*consts, *in_consts_])\n- outs = core.eval_jaxpr(jaxpr_known, (), *known_inputs)\n- known_outputs, res = split_list(outs, [len(out_unknowns)-sum(out_unknowns)])\n-\n- # set up unknown outputs with a recipe to call remat\n- res_tracers = map(trace.new_instantiated_const, res)\n- const_tracers = map(trace.new_instantiated_const, consts)\n- in_jaxpr_tracers = [*res_tracers, *const_tracers, *env_tracers,\n- *instantiated_tracers]\n- _, in_jaxpr_tracers = partition_list(in_used_unknown, in_jaxpr_tracers)\n- unknown_outputs = [JaxprTracer(trace, PartialVal.unknown(x.aval), None)\n- for x in jaxpr_unknown.outvars]\n- new_params = dict(params, call_jaxpr=jaxpr_unknown, differentiated=True)\n- recipe = new_eqn_recipe(in_jaxpr_tracers, unknown_outputs, remat_call_p,\n- new_params, jaxpr_unknown.effects, source_info_util.current())\n- for t in unknown_outputs: t.recipe = recipe\n- return merge_lists(out_unknowns, known_outputs, unknown_outputs)\n- else:\n- # TODO(mattjj): this is an old parallel code path, to be deleted once the\n- # new path is fully functional\n-\n- # Now that we have a `jaxpr` which represents as much as `f` as possible, we\n- # want to actually compute known output values. To do that, we first extract\n- # a `jaxpr_known`, and compute which outputs of `jaxpr` are known/unknown.\n- jaxpr_known_, _, out_unknowns, res_avals = partial_eval_jaxpr_nounits(\n- core.ClosedJaxpr(jaxpr, ()), in_unknowns, instantiate=False) # type: ignore\n- jaxpr_known, () = jaxpr_known_.jaxpr, jaxpr_known_.consts\n- num_res = len(res_avals)\n- # Next, we need values for known outputs. To get them, we need to evaluate\n- # jaxpr_known, minus the residual outputs that we don't need. In addition to\n- # eliminating residual outputs, we should perform DCE to eliminate the\n- # computation of those residuals; for example, if the primal program\n- # includes a sine, jaxpr_known includes both the sine and cosine, yet we\n- # don't want to compute the cosine here.\n- known_inputs = consts + [t for t in it.chain(env_tracers, tracers)\n- if t.pval.is_known()]\n- num_known_outputs = len(out_unknowns) - sum(out_unknowns)\n- jaxpr_known, kept_inputs = dce_jaxpr(\n- jaxpr_known, [True] * num_known_outputs + [False] * num_res)\n- known_inputs = [x for x, kept in zip(known_inputs, kept_inputs) if kept]\n- known_outputs = core.eval_jaxpr(jaxpr_known, (), *known_inputs)\n- del jaxpr_known, res_avals, num_res, num_known_outputs, kept_inputs\n-\n- # We compute unknown outputs by using the full `jaxpr`, though we can prune\n- # out of it any known outputs and computations and only keep those\n- # operations we need to compute the unknown outputs.\n- jaxpr, kept_inputs = dce_jaxpr(jaxpr, out_unknowns)\n- const_tracers = map(trace.instantiate_const, map(trace.full_raise, consts))\n- unknown_inputs = [*const_tracers, *env_tracers, *instantiated_tracers]\n- unknown_inputs = [x for x, kept in zip(unknown_inputs, kept_inputs) if kept]\n- unknown_outputs = [JaxprTracer(trace, PartialVal.unknown(x.aval), None)\n- for x in jaxpr.outvars]\n- eqn = new_eqn_recipe(unknown_inputs, unknown_outputs, remat_call_p,\n- dict(params, call_jaxpr=jaxpr,\n- differentiated=True),\n- jaxpr.effects, source_info_util.current())\n- for t in unknown_outputs: t.recipe = eqn\n-\n- return merge_lists(out_unknowns, known_outputs, unknown_outputs)\n-call_partial_eval_rules[remat_call_p] = _remat_partial_eval\n-\ndef partial_eval_jaxpr_custom(\njaxpr: Jaxpr,\nin_unknowns: Sequence[bool],\n@@ -1400,10 +1279,6 @@ partial_eval_jaxpr_custom_rules[core.call_p] = \\\npartial_eval_jaxpr_custom_rules[core.named_call_p] = \\\npartial(call_partial_eval_custom_rule, 'call_jaxpr',\nlambda _, __, ___, ____, _____, x, y: (x, y))\n-partial_eval_jaxpr_custom_rules[remat_call_p] = \\\n- partial(call_partial_eval_custom_rule, 'call_jaxpr',\n- lambda _, __, ___, ____, _____, p1, p2:\n- (p1, dict(p2, differentiated=True)))\ndef _jaxpr_forwarding(jaxpr: Jaxpr) -> List[Optional[int]]:\n@@ -1494,7 +1369,6 @@ def dce_jaxpr_call_rule(used_outputs: List[bool], eqn: JaxprEqn\nreturn used_inputs, new_eqn\ndce_rules[core.call_p] = dce_jaxpr_call_rule\ndce_rules[core.named_call_p] = dce_jaxpr_call_rule\n-dce_rules[remat_call_p] = dce_jaxpr_call_rule\ndef dce_jaxpr_closed_call_rule(used_outputs: List[bool], eqn: JaxprEqn\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -3922,55 +3922,6 @@ class RematTest(jtu.JaxTestCase):\nexpected = f_lin_expected(3.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @unittest.skipIf(config.jax_new_checkpoint, \"test is for old remat only\")\n- def test_remat_grad_python_control_flow(self):\n- # See test `test_remat_grad_python_control_flow_static_argnums` for the\n- # new recommended way to express this computation.\n-\n- def g(x):\n- if x > 0:\n- return lax.sin(x), 3.\n- else:\n- return lax.cos(x), 4.\n-\n- def f(x):\n- x, _ = g(x)\n- return x\n-\n- with self.assertWarnsRegex(DeprecationWarning, \"static_argnums\"):\n- g = api.remat(g, concrete=True)\n-\n- ans = f(2.)\n- expected = np.sin(2.)\n- self.assertAllClose(ans, expected, check_dtypes=False)\n-\n- ans = api.grad(f)(2.)\n- expected = np.cos(2.)\n- self.assertAllClose(ans, expected, check_dtypes=False)\n-\n- @unittest.skipIf(config.jax_new_checkpoint, \"new remat raises error here\")\n- def test_remat_concrete_deprecation_warning(self):\n- def g(x):\n- if x > 0:\n- return lax.sin(x), 3.\n- else:\n- return lax.cos(x), 4.\n-\n- with self.assertWarnsRegex(DeprecationWarning, \"static_argnums\"):\n- _ = api.remat(g, concrete=True)\n-\n- @unittest.skipIf(not config.jax_new_checkpoint, \"old remat warns here\")\n- def test_remat_concrete_deprecation_error(self):\n- def g(x):\n- if x > 0:\n- return lax.sin(x), 3.\n- else:\n- return lax.cos(x), 4.\n-\n- with self.assertRaisesRegex(NotImplementedError, \"static_argnums\"):\n- _ = api.remat(g, concrete=True)\n-\n- @unittest.skipIf(not config.jax_new_checkpoint, \"old remat different error\")\ndef test_remat_concrete_error(self):\n@api.remat # no static_argnums or concrete\ndef g(x):\n@@ -4055,7 +4006,6 @@ class RematTest(jtu.JaxTestCase):\nexpected = np.cos(2.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @unittest.skipIf(not config.jax_new_checkpoint, \"old remat retraces here\")\ndef test_remat_retracing(self):\n# This is *not* a very important behavior; remat doesn't need to provide\n# caching guarantees with the same importance as jit. But even so, in the\n@@ -4079,7 +4029,6 @@ class RematTest(jtu.JaxTestCase):\ny.block_until_ready()\nself.assertEqual(count, 1)\n- @unittest.skipIf(not config.jax_new_checkpoint, \"old remat retraces here\")\ndef test_remat_static_agnums_retracing(self):\n# This is *not* a super important behavior; remat doesn't need to provide\n# caching guarantees with the same importance as jit. But even so, in the\n@@ -4971,7 +4920,6 @@ 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\")\ndef test_fwd_caching(self):\n# see above test also\nidentity = jax.checkpoint(jax.jit(lambda x: 2 * x))\n@@ -4981,7 +4929,6 @@ class RematTest(jtu.JaxTestCase):\ny.block_until_ready()\nself.assertEqual(count[0], 1)\n- @unittest.skipIf(not config.jax_new_checkpoint, \"old remat recompiles here\")\ndef test_fwd_caching_static_argnums(self):\n# see above test also\nidentity = jax.checkpoint(jax.jit(lambda x: 2 * x), static_argnums=(0,))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -1979,7 +1979,7 @@ 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+ if use_remat == \"old\": raise SkipTest()\ndef f(x):\nid_print_result = hcb.id_print(x, output_stream=testing_stream)\n"
}
] | Python | Apache License 2.0 | google/jax | delete old remat implementation
moved lowering rule logic from remat_impl.py (now deleted) to ad_checkpoint.py |
260,287 | 16.08.2022 11:57:48 | 0 | 6ed2d22566df9093994a3a844e2899e7e238a388 | Update WORKSPACE
to include the addition of use_global_device_ids in AllReduceOp. | [
{
"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 = \"5b0ebc0eae9fbc746721dd7559ee4e718c4da348cb3ee1984be55a23d058e0aa\",\n- strip_prefix = \"tensorflow-575daff8f02c7ac1b20faa02e02c287c02e443bc\",\n+ sha256 = \"1d4ccd16e5ac50bd1fcdec4d42d6d50a6295d025d1282da1b166e0bcbfbde9d6\",\n+ strip_prefix = \"tensorflow-8a14428882b6a39aadcb9f62e83dbaee36c44e49\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/575daff8f02c7ac1b20faa02e02c287c02e443bc.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/8a14428882b6a39aadcb9f62e83dbaee36c44e49.tar.gz\",\n],\n)\n"
}
] | Python | Apache License 2.0 | google/jax | Update WORKSPACE
to include the addition of use_global_device_ids in AllReduceOp. |
260,510 | 17.08.2022 10:45:47 | 25,200 | 8068e4638c924cfbe3dafb080b26c9024f9fea96 | Re-bump shard count for `pmap_test` | [
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -526,9 +526,9 @@ jax_test(\nname = \"pmap_test\",\nsrcs = [\"pmap_test.py\"],\nshard_count = {\n- \"cpu\": 10,\n- \"gpu\": 10,\n- \"tpu\": 10,\n+ \"cpu\": 15,\n+ \"gpu\": 30,\n+ \"tpu\": 15,\n},\ntags = [\"multiaccelerator\"],\ndeps = [\n"
}
] | Python | Apache License 2.0 | google/jax | Re-bump shard count for `pmap_test`
PiperOrigin-RevId: 468239588 |
260,510 | 15.08.2022 17:05:27 | 25,200 | 393bca122d1731122803ea33d1105047298d48de | Expose pure callback and enable rank polymorphic callbacks | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -14,6 +14,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* {func}`jax.checkpoint`, also known as {func}`jax.remat`, no longer supports\nthe `concrete` option, following the previous version's deprecation; see\n[JEP 11830](https://jax.readthedocs.io/en/latest/jep/11830-new-remat-checkpoint.html).\n+* Changes\n+ * Added {func}`jax.pure_callback` that enables calling back to pure Python functions from functions compiled with `jax.jit` or `jax.pmap`.\n## jax 0.3.16\n* [GitHub commits](https://github.com/google/jax/compare/jax-v0.3.15...main).\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/__init__.py",
"new_path": "jax/__init__.py",
"diff": "@@ -100,6 +100,7 @@ from jax._src.api import (\npmap as pmap,\nprocess_count as process_count,\nprocess_index as process_index,\n+ pure_callback as pure_callback,\npxla, # TODO(phawkins): update users to avoid this.\nremat as remat,\nShapedArray as ShapedArray,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -44,6 +44,7 @@ from jax.tree_util import (tree_map, tree_flatten, tree_unflatten,\ntreedef_is_leaf, treedef_children,\nPartial, PyTreeDef, all_leaves, treedef_tuple)\n+from jax._src import callback as jcb\nfrom jax._src import device_array\nfrom jax._src import dispatch\nfrom jax._src import dtypes\n@@ -3230,6 +3231,50 @@ def block_until_ready(x):\nreturn x\nreturn jax.tree_util.tree_map(try_to_block, x)\n+def pure_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\n+ *args: Any, **kwargs: Any):\n+ \"\"\"Calls a pure Python callback function from staged out JAX programs.\n+\n+ ``pure_callback`` enables calling a Python function in JIT-ed JAX functions.\n+ The input ``callback`` will be passed NumPy arrays in place of JAX arrays and\n+ should also return NumPy arrays. Execution takes place on the CPU host.\n+\n+ The callback is treated as \"pure\" meaning it can be called multiple times when\n+ transformed (for example in a ``vmap`` or ``pmap``), and it can also\n+ potentially be removed from JAX programs via dead-code elimination. Pure\n+ callbacks can also be reordered if data-dependence allows.\n+\n+ When ``pmap``-ed, the pure callback will be called several times (one on each axis\n+ of the map). When `vmap`-ed the behavior will depend on the value of the\n+ ``rank_polymorphic`` keyword argument. If the callback is indicated as rank\n+ polymorphic, the callback will be called directly on batched inputs (where the\n+ batch axis is the leading dimension). Additionally, the callbacks should\n+ return outputs that also have a leading batch axis. If not rank polymorphic,\n+``callback`` will be mapped sequentially across the batched axis.\n+\n+ Args:\n+ callback: A Python callable. The callable will be passed in NumPy arrays and\n+ should return a PyTree of NumPy arrays that matches\n+ ``result_shape_dtypes``.\n+ result_shape_dtypes: A PyTree of Python objects that have ``shape`` and\n+ ``dtype`` properties that correspond to the shape and dtypes of the\n+ outputs of ``callback``.\n+ *args: The positional arguments to the callback. Must be PyTrees of JAX\n+ types.\n+ rank_polymorphic: A boolean that indicates whether or not ``callback`` is\n+ rank polymorphic, meaning it can handle arrays with additional leading\n+ dimensions. If ``rank_polymorphic`` is `True`, when the callback is mapped\n+ via `jax.vmap`, it will be called directly on inputs with leading batch\n+ dimensions instead of executing ``callback`` on each mapped input\n+ individually. The callback should also return outputs batched across the\n+ leading axis.\n+ **kwargs: The keyword arguments to the callback. Must be PyTrees of JAX\n+ types.\n+\n+ Returns:\n+ The value of ``callback(*args, **kwargs)``.\n+ \"\"\"\n+ return jcb.pure_callback(callback, result_shape_dtypes, *args, **kwargs)\ndef clear_backends():\n\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/callback.py",
"new_path": "jax/_src/callback.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Module for JAX callbacks.\"\"\"\n+from __future__ import annotations\n+\nimport functools\n-from typing import Any, Callable\n+from typing import Any, Callable, Sequence\nfrom jax import core\n-from jax import lax\nfrom jax import tree_util\nfrom jax._src import lib as jaxlib\nfrom jax._src import util\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\n-import jax.numpy as jnp\n# `pure_callback_p` is the main primitive for staging out Python pure callbacks.\n@@ -35,15 +35,16 @@ map, unsafe_map = util.safe_map, map\n@pure_callback_p.def_impl\n-def pure_callback_impl(*args, result_avals, callback: Callable[..., Any]):\n- del result_avals\n+def pure_callback_impl(*args, result_avals, callback: Callable[..., Any],\n+ rank_polymorphic: bool):\n+ del rank_polymorphic, result_avals\nreturn callback(*args)\n@pure_callback_p.def_abstract_eval\ndef pure_callback_abstract_eval(*avals, callback: Callable[..., Any],\n- result_avals):\n- del avals, callback\n+ result_avals, rank_polymorphic: bool):\n+ del avals, callback, rank_polymorphic\nreturn result_avals\n@@ -66,12 +67,25 @@ def pure_callback_transpose_rule(*args, **kwargs):\nad.primitive_transposes[pure_callback_p] = pure_callback_transpose_rule\n-def pure_callback_batching_rule(args, dims, *, callback, **params):\n+def pure_callback_batching_rule(args, dims, *, callback, rank_polymorphic: bool,\n+ result_avals: Sequence[core.ShapedArray]):\n+ axis_size = next(a.shape[0] for a, d in zip(args, dims)\n+ if d is not batching.not_mapped)\nnew_args = []\nfor arg, dim in zip(args, dims):\n- new_args.append(jnp.rollaxis(arg, dim))\n- outvals = lax.map(\n- functools.partial(pure_callback_p.bind, callback=callback, **params),\n+ new_args.append(batching.moveaxis(arg, dim, 0))\n+ if rank_polymorphic:\n+ result_avals = tuple(\n+ core.unmapped_aval(axis_size, core.no_axis_name, 0, aval) # type: ignore\n+ for aval in result_avals)\n+ outvals = pure_callback_p.bind(\n+ *new_args, callback=callback, rank_polymorphic=rank_polymorphic,\n+ result_avals=result_avals)\n+ else:\n+ from jax._src.lax.control_flow import map as lax_map\n+ outvals = lax_map(\n+ functools.partial(pure_callback_p.bind, callback=callback,\n+ rank_polymorphic=rank_polymorphic, result_avals=result_avals),\n*new_args)\nreturn tuple(outvals), (0,) * len(outvals)\n@@ -101,38 +115,7 @@ mlir.register_lowering(pure_callback_p, pure_callback_lowering)\ndef pure_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\n- *args: Any, **kwargs: Any):\n- \"\"\"Calls a pure Python callback function from staged out JAX programs.\n-\n- ``pure_callback`` enables calling a Python function in JIT-ed JAX functions.\n- The input ``callback`` will be passed NumPy arrays in place of JAX arrays and\n- should also return NumPy arrays. Execution takes place on the CPU host.\n-\n- The callback is treated as \"pure\" meaning it can be called multiple times when\n- transformed (for example in a ``vmap`` or ``pmap``), and it can also\n- potentially be removed from JAX programs via dead-code elimination. Pure\n- callbacks can also be reordered if data-dependence allows.\n-\n- When both `pmap` and `vmap`-ed, the pure callback will be called several times\n- (one on each axis of the map). In the `pmap` case, these calls will happen\n- across several threads whereas in the `vmap` case, they will happen serially.\n-\n- Args:\n- callback: A Python callable. The callable will be passed in NumPy arrays and\n- should return a PyTree of NumPy arrays that matches\n- ``result_shape_dtypes``.\n- result_shape_dtypes: A PyTree of Python objects that have ``shape`` and\n- ``dtype`` properties that correspond to the shape and dtypes of the\n- outputs of ``callback``.\n- *args: The positional arguments to the callback. Must be PyTrees of JAX\n- types.\n- **kwargs: The keyword arguments to the callback. Must be PyTrees of JAX\n- types.\n-\n- Returns:\n- The value of ``callback(*args, **kwargs)``.\n- \"\"\"\n-\n+ *args: Any, rank_polymorphic: bool = False, **kwargs: Any):\ndef _flat_callback(*flat_args):\nargs, kwargs = tree_util.tree_unflatten(in_tree, flat_args)\nreturn tree_util.tree_leaves(callback(*args, **kwargs))\n@@ -142,5 +125,6 @@ def pure_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\nlambda x: core.ShapedArray(x.shape, x.dtype), result_shape_dtypes)\nflat_result_avals, out_tree = tree_util.tree_flatten(result_avals)\nout_flat = pure_callback_p.bind(\n- *flat_args, callback=_flat_callback, result_avals=flat_result_avals)\n+ *flat_args, callback=_flat_callback,\n+ result_avals=tuple(flat_result_avals), rank_polymorphic=rank_polymorphic)\nreturn tree_util.tree_unflatten(out_tree, out_flat)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1154,6 +1154,7 @@ tf_not_yet_impl = [\n\"getslice\",\n\"full_to_shard\",\n\"shard_to_full\",\n+ \"pure_callback\",\n# Not high priority?\n\"after_all\",\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/python_callback_test.py",
"new_path": "tests/python_callback_test.py",
"diff": "@@ -24,12 +24,12 @@ import jax\nfrom jax import core\nfrom jax import lax\nfrom jax import tree_util\n-from jax._src import callback as jc\nfrom jax._src import debugging\nfrom jax._src import lib as jaxlib\nfrom jax._src import test_util as jtu\nfrom jax._src import util\nfrom jax.config import config\n+from jax.experimental import maps\nfrom jax.interpreters import mlir\nimport jax.numpy as jnp\nimport numpy as np\n@@ -459,13 +459,15 @@ class PythonCallbackTest(jtu.JaxTestCase):\nclass PurePythonCallbackTest(jtu.JaxTestCase):\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_simple_pure_callback(self):\n@jax.jit\ndef f(x):\n- return jc.pure_callback(lambda x: (x * 2.).astype(x.dtype), x, x)\n+ return jax.pure_callback(lambda x: (x * 2.).astype(x.dtype), x, x)\nself.assertEqual(f(2.), 4.)\n+ @jtu.skip_on_devices(*disabled_backends)\ndef test_can_dce_pure_callback(self):\nif jax.default_backend() == \"tpu\":\n@@ -479,31 +481,134 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\n@jax.jit\ndef f(x):\n- _ = jc.pure_callback(_callback, x, x)\n+ _ = jax.pure_callback(_callback, x, x)\nreturn x * 2.\n_ = f(2.)\nself.assertEmpty(log)\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_wrong_number_of_args(self):\n+\n+ @jax.jit\n+ def f():\n+ # Calling a function that expects `x` with no arguments\n+ return jax.pure_callback(lambda x: np.ones(4, np.float32),\n+ core.ShapedArray((4,), np.float32))\n+\n+ with self.assertRaises(RuntimeError):\n+ f()\n+ jax.effects_barrier()\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_wrong_number_of_returned_values(self):\n+\n+ @jax.jit\n+ def f(x):\n+ # Calling a function with a return value that expects no return values\n+ return jax.pure_callback(lambda x: (x, np.ones(4, np.float32)), x)\n+\n+ with self.assertRaises(RuntimeError):\n+ f(2.)\n+ jax.effects_barrier()\n+\n+ @jax.jit\n+ def g():\n+ # Calling a function with a return value that expects no return values\n+ return jax.pure_callback(lambda: None, (\n+ core.ShapedArray((1,), np.float32), core.ShapedArray((2,), np.float32)))\n+\n+ with self.assertRaises(RuntimeError):\n+ g()\n+ jax.effects_barrier()\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_wrong_shape_outputs(self):\n+\n+ @jax.jit\n+ def f():\n+ # Calling a function expected a (1,) shaped return value but getting ()\n+ return jax.pure_callback(lambda: np.float32(1.),\n+ core.ShapedArray((1,), np.float32))\n+\n+ with self.assertRaises(RuntimeError):\n+ f()\n+ jax.effects_barrier()\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_wrong_dtype_outputs(self):\n+\n+ def _cb():\n+ return np.array([1], np.float64)\n+\n+ @jax.jit\n+ def f():\n+ # Calling a function expected a f32 return value but getting f64\n+ return callback(_cb, core.ShapedArray((1,), np.float32))\n+\n+ with self.assertRaises(RuntimeError):\n+ f()\n+ jax.effects_barrier()\n+\ndef test_can_vmap_pure_callback(self):\n@jax.jit\n@jax.vmap\ndef f(x):\n- return jc.pure_callback(np.sin, x, x)\n+ return jax.pure_callback(np.sin, x, x)\nout = f(jnp.arange(4.))\nnp.testing.assert_allclose(out, np.sin(np.arange(4.)))\n@jax.jit\ndef g(x):\n- return jc.pure_callback(np.sin, x, x)\n+ return jax.pure_callback(np.sin, x, x)\nout = jax.vmap(g, in_axes=1)(jnp.arange(8.).reshape((4, 2)))\nnp.testing.assert_allclose(out, np.sin(np.arange(8.).reshape((4, 2))).T)\n+ def test_vmap_rank_polymorphic_callback(self):\n+\n+ def cb(x):\n+ self.assertTupleEqual(x.shape, ())\n+ return np.sin(x)\n+\n+ @jax.jit\n+ @jax.vmap\n+ def f(x):\n+ return jax.pure_callback(cb, x, x)\n+\n+ _ = f(jnp.arange(4.))\n+\n+ def cb2(x):\n+ self.assertTupleEqual(x.shape, (4,))\n+ return np.sin(x)\n+\n+\n+ @jax.jit\n+ @jax.vmap\n+ def g(x):\n+ return jax.pure_callback(cb2, x, x, rank_polymorphic=True)\n+\n+ _ = g(jnp.arange(4.))\n+\n+ def test_vmap_rank_polymorphic_callback_errors_if_returns_wrong_shape(self):\n+\n+ def cb(x):\n+ # Reduces over all dimension when it shouldn't\n+ return np.sin(x).sum()\n+\n+ @jax.jit\n+ @jax.vmap\n+ def f(x):\n+ return jax.pure_callback(cb, x, x, rank_polymorphic=True)\n+\n+ with self.assertRaises(RuntimeError):\n+ f(jnp.arange(4.))\n+ jax.effects_barrier()\n+\ndef test_can_pmap_pure_callback(self):\n@jax.pmap\ndef f(x):\n- return jc.pure_callback(np.sin, x, x)\n+ return jax.pure_callback(np.sin, x, x)\nout = f(jnp.arange(float(jax.local_device_count())))\nnp.testing.assert_allclose(out, np.sin(np.arange(jax.local_device_count())))\n@@ -515,7 +620,7 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\n@jax.jit\n@jax.grad\ndef f(x):\n- return jc.pure_callback(sin, x, x)\n+ return jax.pure_callback(sin, x, x)\nwith self.assertRaisesRegex(\nValueError, \"Pure callbacks do not support JVP.\"):\nf(2.)\n@@ -524,12 +629,12 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\n@jax.custom_jvp\ndef sin(x):\n- return jc.pure_callback(np.sin, x, x)\n+ return jax.pure_callback(np.sin, x, x)\n@sin.defjvp\ndef sin_jvp(xs, ts):\n(x,), (t,), = xs, ts\n- return sin(x), jc.pure_callback(np.cos, x, x) * t\n+ return sin(x), jax.pure_callback(np.cos, x, x) * t\n@jax.jit\n@jax.grad\n@@ -551,10 +656,10 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\ndef f(pred, x):\ndef true_fun(x):\n- return jc.pure_callback(_callback1, x, x)\n+ return jax.pure_callback(_callback1, x, x)\ndef false_fun(x):\n- return jc.pure_callback(_callback2, x, x)\n+ return jax.pure_callback(_callback2, x, x)\nreturn lax.cond(pred, true_fun, false_fun, x)\n@@ -573,7 +678,7 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\ndef f(x):\ndef body(x, _):\n- x = jc.pure_callback(_callback, x, x)\n+ x = jax.pure_callback(_callback, x, x)\nreturn x, ()\nreturn lax.scan(body, x, jnp.arange(10))[0]\n@@ -594,11 +699,11 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\ndef f(x):\ndef cond(x):\n- return jc.pure_callback(\n+ return jax.pure_callback(\n_cond_callback, jax.ShapeDtypeStruct((), np.bool_), x)\ndef body(x):\n- return jc.pure_callback(_callback, x, x)\n+ return jax.pure_callback(_callback, x, x)\nreturn lax.while_loop(cond, body, x)\n@@ -613,7 +718,7 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\n@jax.pmap\ndef f(x):\n- return jc.pure_callback(_callback, x, x)\n+ return jax.pure_callback(_callback, x, x)\nout = f(\njnp.arange(2 * jax.local_device_count(),\n@@ -622,5 +727,36 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\nout,\nnp.arange(2 * jax.local_device_count()).reshape([-1, 2]) + 1.)\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_inside_xmap(self):\n+\n+ def _callback(x):\n+ return (x + 1.).astype(x.dtype)\n+\n+ def f(x):\n+ return jax.pure_callback(_callback, x, x)\n+\n+ f = maps.xmap(f, in_axes=['a'], out_axes=['a'],\n+ axis_resources={'a': 'dev'})\n+ with maps.Mesh(np.array(jax.devices()), ['dev']):\n+ out = f(jnp.arange(40.))\n+ np.testing.assert_allclose(out, jnp.arange(1., 41.))\n+\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_rank_polymorphic_callback_inside_xmap(self):\n+\n+ def _callback(x):\n+ return (x + 1.).astype(x.dtype)\n+\n+ def f(x):\n+ return jax.pure_callback(_callback, x, x, rank_polymorphic=True)\n+\n+ f = maps.xmap(f, in_axes=['a'], out_axes=['a'],\n+ axis_resources={'a': 'dev'})\n+ with maps.Mesh(np.array(jax.devices()), ['dev']):\n+ out = f(jnp.arange(40.))\n+ np.testing.assert_allclose(out, jnp.arange(1., 41.))\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Expose pure callback and enable rank polymorphic callbacks |
260,510 | 17.08.2022 12:29:14 | 25,200 | 87e3898a9f0e0b949d610112199d5d1949ed3512 | Set `jax_eager_pmap` to True | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/config.py",
"new_path": "jax/_src/config.py",
"diff": "@@ -893,7 +893,7 @@ config.define_bool_state(\n# TODO(sharadmv,mattjj): set default to True, then remove\nconfig.define_bool_state(\nname='jax_eager_pmap',\n- default=False,\n+ default=True,\nupgrade=True,\nhelp='Enable eager-mode pmap when jax_disable_jit is activated.')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -968,11 +968,18 @@ def _emap_impl(fun: lu.WrappedFun, *args,\ndel main\nout_axes = out_axes_thunk()\n+ platform = xb.get_backend(backend).platform\n+ donate_argnums = (1,) if platform in {\"cuda\", \"rocm\", \"tpu\"} else ()\nnew_outvals = []\nfor out_axis_src, out_axis, outval in zip(out_axes_src, out_axes, outvals):\nwith jax.disable_jit(False):\n+ donate_argnums_ = donate_argnums\n+ if isinstance(outval, (ShardedDeviceArray, jax.experimental.array.Array)):\n+ # We don't want to donate if it's already sharded.\n+ donate_argnums_ = ()\nout = jax.pmap(lambda _, x: x, in_axes=(0, out_axis_src.get(axis_name)),\n- out_axes=out_axis, devices=devices, backend=backend)(\n+ out_axes=out_axis, devices=devices, backend=backend,\n+ donate_argnums=donate_argnums_)(\nnp.arange(axis_size), outval)\nnew_outvals.append(out)\nreturn new_outvals\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -2083,9 +2083,6 @@ class PythonPmapTest(jtu.JaxTestCase):\nself.assertEqual(count[0], 0) # cache hits on fwd and bwd\ndef testSizeOverflow(self):\n- if config.jax_disable_jit:\n- # TODO(sharadmv, mattjj): investigate and fix this issue\n- raise SkipTest(\"OOMs in eager mode\")\nx = jnp.arange(1)\nx = self.pmap(lambda _: jnp.ones([8, 267736, 1024], dtype=jnp.int8))(x)\nself.assertEqual(x.size, 8 * 267736 * 1024)\n"
}
] | Python | Apache License 2.0 | google/jax | Set `jax_eager_pmap` to True
PiperOrigin-RevId: 468265661 |
260,631 | 17.08.2022 15:04:18 | 25,200 | ef95e2ecef11fb68529c855f7ec5b30a4935f92a | Replace JAX client side implementation of RoundNearestEven with higher efficiency op RoundNearestEvenOp | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -1689,19 +1689,6 @@ ceil_p = standard_unop(_float, 'ceil')\nad.defjvp_zero(ceil_p)\nmlir.register_lowering(ceil_p, partial(_nary_lower_mhlo, mhlo.CeilOp))\n-def _round_to_nearest_even(x):\n- half = _const(x, 0.5)\n- one = _const(x, 1)\n- round_val = floor(x)\n- fraction = x - round_val\n- nearest_even_int = sub(\n- round_val, mul(_const(x, 2), floor(mul(half, x))))\n- is_odd = eq(nearest_even_int, one)\n- return select(\n- bitwise_or(gt(fraction, half),\n- bitwise_and(eq(fraction, half), is_odd)),\n- add(round_val, one), round_val)\n-\nround_p = standard_unop(_float, 'round')\nad.defjvp_zero(round_p)\n@@ -1710,9 +1697,7 @@ def _round_lower(ctx, x, *, rounding_method):\nreturn mhlo.RoundOp(x).results\nelse:\nassert rounding_method is RoundingMethod.TO_NEAREST_EVEN\n- round_nearest = mlir.cache_lowering(mlir.lower_fun(_round_to_nearest_even,\n- multiple_results=False))\n- return round_nearest(ctx, x)\n+ return mhlo.RoundNearestEvenOp(x).results\nmlir.register_lowering(round_p, _round_lower)\nis_finite_p = unop(_fixed_dtype(np.bool_), _float, 'is_finite')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1235,9 +1235,7 @@ def _round(operand, *, rounding_method,\ntf.where(cond, tf.constant(np.array(1), operand.dtype),\ntf.math.round(operand)) + floor)\nelse: # rounding_method is RoundingMethod.TO_NEAREST_EVEN\n- rounding_fun = _convert_jax_impl(\n- lax_internal._round_to_nearest_even, multiple_results=False)\n- return rounding_fun(operand, _in_avals=_in_avals, _out_aval=_out_aval)\n+ return tf.math.round(operand)\ntf_impl_with_avals[lax.round_p] = _round\ntf_impl[lax.nextafter_p] = tf.math.nextafter\n"
}
] | Python | Apache License 2.0 | google/jax | Replace JAX client side implementation of RoundNearestEven with higher efficiency op RoundNearestEvenOp
PiperOrigin-RevId: 468302607 |
260,335 | 07.01.2022 20:21:30 | 28,800 | 887b7ce2cb3d6d8aedac5cc273e137f1c876e3c7 | remove custom_jvp_call_jaxpr_p and its rules
They were superfluous! Instead use the "new" mechanism for converting from
jaxpr params to bind params (in
This change languished until we could land / and friends. But now
we can! | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/custom_derivatives.py",
"new_path": "jax/_src/custom_derivatives.py",
"diff": "from functools import update_wrapper, reduce, partial\nimport inspect\nimport operator as op\n-from typing import (Any, Callable, Generic, List, Optional, Sequence, Set,\n- Tuple, TypeVar)\n+from typing import (Callable, Generic, Optional, Sequence, Tuple, TypeVar, Set,\n+ Any)\nfrom jax import core\nfrom jax import linear_util as lu\n@@ -276,8 +276,6 @@ def _flatten_jvp(in_tree, *args):\nyield primals_out + tangents_out, out_tree\nclass CustomJVPCallPrimitive(core.CallPrimitive):\n- initial_style: core.Primitive\n-\ndef bind(self, fun, jvp, *args):\nargs = map(core.full_lower, args)\ntop_trace = core.find_top_trace(args)\n@@ -297,6 +295,23 @@ class CustomJVPCallPrimitive(core.CallPrimitive):\ndef post_process(self, trace, out_tracers, jvp_was_run: bool):\nreturn trace.post_process_custom_jvp_call(out_tracers, jvp_was_run)\n+ def get_bind_params(self, params):\n+ new_params = dict(params)\n+ call_jaxpr = new_params.pop('call_jaxpr')\n+ num_consts = new_params.pop('num_consts')\n+ jvp_jaxpr_thunk = new_params.pop('jvp_jaxpr_thunk')\n+ fun = lu.wrap_init(core.jaxpr_as_fun(call_jaxpr))\n+\n+ @lu.wrap_init\n+ def jvp(*xs):\n+ jvp_jaxpr, jvp_consts = jvp_jaxpr_thunk()\n+ n, ragged = divmod(len(xs), 2)\n+ assert not ragged\n+ primals, tangents = xs[num_consts:n], xs[n+num_consts:]\n+ return core.eval_jaxpr(jvp_jaxpr, jvp_consts, *primals, *tangents)\n+\n+ return [fun, jvp], new_params\n+\n@lu.transformation_with_aux\ndef process_env_traces(primitive, level: int, jvp_was_run: bool, *args):\nouts = yield args, {}\n@@ -314,6 +329,23 @@ def process_env_traces(primitive, level: int, jvp_was_run: bool, *args):\ntodo.append(cur_todo)\nyield outs, tuple(todo) # Ensure the aux output is immutable\n+ def get_bind_params(self, params):\n+ new_params = dict(params)\n+ call_jaxpr = new_params.pop('call_jaxpr')\n+ num_consts = new_params.pop('num_consts')\n+ jvp_jaxpr_thunk = new_params.pop('jvp_jaxpr_thunk')\n+ fun = lu.wrap_init(core.jaxpr_as_fun(call_jaxpr))\n+\n+ @lu.wrap_init\n+ def jvp(*xs):\n+ jvp_jaxpr, jvp_consts = jvp_jaxpr_thunk()\n+ n, ragged = divmod(len(xs), 2)\n+ assert not ragged\n+ primals, tangents = xs[num_consts:n], xs[n+num_consts:]\n+ return core.eval_jaxpr(jvp_jaxpr, jvp_consts, *primals, *tangents)\n+\n+ return [fun, jvp], new_params\n+\ndef _apply_todos(todos, outs):\ntodos_list = list(todos)\nwhile todos_list:\n@@ -324,122 +356,35 @@ def _apply_todos(todos, outs):\nallowed_effects: Set[core.Effect] = set()\ncustom_jvp_call_p = CustomJVPCallPrimitive('custom_jvp_call')\n-\n-def _custom_jvp_call_jaxpr_impl(*args, fun_jaxpr: core.ClosedJaxpr, **params):\n- del params # other params ignored because we're just executing the primal fun\n- return core.jaxpr_as_fun(fun_jaxpr)(*args)\n-\n-def _custom_jvp_call_jaxpr_abstract_eval(*args, fun_jaxpr: core.ClosedJaxpr, **params):\n- del args, params\n- disallowed_effects = {eff for eff in fun_jaxpr.effects if eff not in\n+def _custom_jvp_call_typecheck(*in_avals, call_jaxpr, jvp_jaxpr_thunk, num_consts):\n+ # TODO(mattjj): could do more checking here...\n+ del in_avals, jvp_jaxpr_thunk, num_consts\n+ disallowed_effects = {eff for eff in call_jaxpr.effects if eff not in\nallowed_effects}\nif disallowed_effects:\nraise NotImplementedError(\nf'Effects not supported in `custom_jvp`: {disallowed_effects}')\n- return fun_jaxpr.out_avals, fun_jaxpr.effects\n-\n-custom_jvp_call_jaxpr_p = core.AxisPrimitive('custom_jvp_call_jaxpr')\n-custom_jvp_call_jaxpr_p.multiple_results = True\n-custom_jvp_call_jaxpr_p.def_impl(_custom_jvp_call_jaxpr_impl)\n-custom_jvp_call_jaxpr_p.def_effectful_abstract_eval(_custom_jvp_call_jaxpr_abstract_eval)\n-CustomJVPCallPrimitive.initial_style = custom_jvp_call_jaxpr_p\n-\n-mlir.register_lowering(custom_jvp_call_jaxpr_p, mlir.lower_fun(\n- _custom_jvp_call_jaxpr_impl, multiple_results=True))\n+ return call_jaxpr.out_avals, call_jaxpr.effects\n+core.custom_typechecks[custom_jvp_call_p] = _custom_jvp_call_typecheck\n-\n-def _custom_jvp_call_jaxpr_jvp(\n- primals, tangents, *, fun_jaxpr: core.ClosedJaxpr,\n- jvp_jaxpr_thunk: Callable[[], Tuple[core.Jaxpr, Sequence[Any]]],\n- num_consts: int):\n- _, args = split_list(primals, [num_consts])\n- consts_dot, args_dot = split_list(tangents, [num_consts])\n- if any(type(t) is not Zero for t in consts_dot):\n- raise ad.CustomJVPException()\n- jvp_jaxpr, jvp_consts = jvp_jaxpr_thunk() # consts can be tracers!\n- args_dot = map(ad.instantiate_zeros, args_dot)\n- # Cast float0 to zeros with the primal dtype because custom jvp rules don't\n- # currently handle float0s\n- args_dot = map(ad.replace_float0s, args, args_dot)\n- outs = core.eval_jaxpr(jvp_jaxpr, jvp_consts, *args, *args_dot)\n- primals_out, tangents_out = split_list(outs, [len(outs) // 2])\n- tangents_out = map(ad.recast_to_float0, primals_out, tangents_out)\n- if config.jax_enable_checks:\n- assert all(map(core.typecheck, fun_jaxpr.out_avals, primals_out))\n- return primals_out, tangents_out\n-ad.primitive_jvps[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_jvp\n-\n-def _custom_jvp_call_jaxpr_vmap(\n- axis_size, axis_name, main_type, args, in_dims, *, fun_jaxpr: core.ClosedJaxpr,\n- jvp_jaxpr_thunk: Callable[[], Tuple[core.Jaxpr, Sequence[Any]]],\n- num_consts: int):\n- args = [batching.moveaxis(x, d, 0) if d is not not_mapped and d != 0\n- else x for x, d in zip(args, in_dims)]\n- num_out = len(fun_jaxpr.out_avals)\n-\n- in_batched = [d is not not_mapped for d in in_dims]\n- batched_fun_jaxpr, out_batched = batching.batch_jaxpr(\n- fun_jaxpr, axis_size, in_batched, False, axis_name, main_type)\n- out_dims1 = [0 if b else not_mapped for b in out_batched]\n- out_dims2 = [] # mutable cell updated by batched_jvp_jaxpr_thunk\n-\n- @pe._memoize\n- def batched_jvp_jaxpr_thunk():\n- jvp_jaxpr = core.ClosedJaxpr(*jvp_jaxpr_thunk()) # consts can be tracers\n- _, args_batched = split_list(in_batched, [num_consts])\n- _, all_batched = batching.batch_jaxpr(jvp_jaxpr, axis_size, args_batched * 2, False,\n- axis_name, main_type)\n- primals_batched, tangents_batched = split_list(all_batched, [num_out])\n- out_batched = map(op.or_, primals_batched, tangents_batched)\n- out_dims2.append([0 if b else not_mapped for b in out_batched])\n- batched_jvp_jaxpr, _ = batching.batch_jaxpr(\n- jvp_jaxpr, axis_size, args_batched * 2, out_batched * 2,\n- axis_name, main_type)\n- return batched_jvp_jaxpr.jaxpr, batched_jvp_jaxpr.consts\n-\n- batched_outs = custom_jvp_call_jaxpr_p.bind(\n- *args, fun_jaxpr=batched_fun_jaxpr,\n- jvp_jaxpr_thunk=batched_jvp_jaxpr_thunk, num_consts=num_consts)\n- out_dims = out_dims2[0] if out_dims2 else out_dims1\n- return batched_outs, out_dims\n-batching.axis_primitive_batchers[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_vmap\n-\n-xla.register_initial_style_primitive(custom_jvp_call_jaxpr_p)\n+def _custom_jvp_call_mlir_translation(ctx, *args, call_jaxpr, jvp_jaxpr_thunk,\n+ num_consts):\n+ del jvp_jaxpr_thunk, num_consts\n+ args_ = map(mlir.wrap_singleton_ir_values, args)\n+ consts = mlir._ir_consts(call_jaxpr.consts)\n+ out, tokens = mlir.jaxpr_subcomp(ctx.module_context, call_jaxpr.jaxpr,\n+ ctx.tokens_in, consts, *args_)\n+ ctx.set_tokens_out(tokens)\n+ return out\n+mlir.register_lowering(custom_jvp_call_p, _custom_jvp_call_mlir_translation)\n# If a (multi)linear function is defined with a custom jvp, then\n-# custom_jvp_call_jaxpr can appear in jaxprs to be transposed. Since it's\n-# already been linearized, we can drop the jvp rule.\n-def _custom_jvp_call_jaxpr_transpose(reduce_axes, cts, *args, fun_jaxpr,\n- jvp_jaxpr_thunk, num_consts):\n- del jvp_jaxpr_thunk, num_consts\n- return ad.backward_pass(\n- fun_jaxpr.jaxpr, reduce_axes, False, fun_jaxpr.consts, args, cts)\n-ad.reducing_transposes[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_transpose\n-\n-def custom_jvp_jaxpr_custom_partial_eval_rule(\n- saveable: Callable[..., bool], unks_in: List[bool], inst_in: List[bool],\n- eqn: core.JaxprEqn\n- ) -> Tuple[Optional[core.JaxprEqn], core.JaxprEqn, List[bool], List[bool], List[core.Var]]:\n- # It doesn't make sense to unzip (i.e. break up) a custom_jvp function into\n- # constituent parts, so we always perform full remat. An alternative would be\n- # to allow the policy function to decide whether the value of a\n- # custom_jvp-decorated function's application should be saved or not.\n- # TODO(mattjj,jekbradbury): the user writing the custom_jvp-decorated function\n- # probably has a better idea for what to do under remat (e.g. if the function\n- # contains dots or not), so we should allow for more expressive interaction\n- # (e.g. allow the policy to depend on which custom_jvp-decorated function is\n- # being applied, or annotating the behavior where custom_vjp is called.)\n- inst_out = [True] * len(eqn.outvars)\n- new_inst = [x for x, inst in zip(eqn.invars, inst_in)\n- if type(x) is core.Var and not inst]\n- if any(unks_in):\n- unks_out = [True] * len(eqn.outvars)\n- return None, eqn, unks_out, inst_out, new_inst\n- else:\n- unks_out = [False] * len(eqn.outvars)\n- return eqn, eqn, unks_out, inst_out, new_inst\n-pe.partial_eval_jaxpr_custom_rules[custom_jvp_call_jaxpr_p] = \\\n- custom_jvp_jaxpr_custom_partial_eval_rule # type: ignore\n+# custom_jvp_call_ can appear in jaxprs to be transposed. Since it's already\n+# been linearized, we can drop the jvp rule.\n+def _custom_jvp_call_transpose(params, jaxpr, args, ct, _, reduce_axes):\n+ del params\n+ return ad.backward_pass(jaxpr.jaxpr, reduce_axes, None, jaxpr.consts, args, ct)\n+ad.primitive_transposes[custom_jvp_call_p] = _custom_jvp_call_transpose\n### VJPs\n@@ -776,9 +721,6 @@ xla.register_initial_style_primitive(custom_vjp_call_jaxpr_p)\nbatching.primitive_batchers[ad.custom_lin_p] = ad._raise_custom_vjp_error_on_jvp\nmlir.register_lowering(ad.custom_lin_p, ad._raise_custom_vjp_error_on_jvp)\n-pe.partial_eval_jaxpr_custom_rules[custom_vjp_call_jaxpr_p] = \\\n- custom_jvp_jaxpr_custom_partial_eval_rule # type: ignore\n-\ndef custom_gradient(fun):\n\"\"\"Convenience function for defining custom VJP rules (aka custom gradients).\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -500,7 +500,8 @@ def escaped_tracer_error(tracer, detail=None):\nnum_frames = FLAGS.jax_tracer_error_num_traceback_frames\nmsg = ('Encountered an unexpected tracer. A function transformed by JAX '\n'had a side effect, allowing for a reference to an intermediate value '\n- f'with shape {tracer.shape} and dtype {tracer.dtype} to escape.\\n'\n+ f'with type {tracer.aval.str_short()} wrapped in a '\n+ f'{type(tracer).__name__} to escape the scope of the transformation.\\n'\n'JAX transformations require that functions explicitly return their '\n'outputs, and disallow saving intermediate values to global state.')\ndbg = getattr(tracer, '_debug_info', None)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -20,7 +20,6 @@ from jax._src.custom_derivatives import (\ncustom_gradient as custom_gradient,\ncustom_jvp as custom_jvp,\ncustom_jvp_call_p as custom_jvp_call_p,\n- custom_jvp_call_jaxpr_p as custom_jvp_call_jaxpr_p,\ncustom_vjp as custom_vjp,\ncustom_vjp_call_p as custom_vjp_call_p,\ncustom_vjp_call_jaxpr_p as custom_vjp_call_jaxpr_p,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/callback.py",
"new_path": "jax/experimental/callback.py",
"diff": "@@ -264,9 +264,7 @@ def _custom_derivative_call_jaxpr_callback_rule(primitive, trace, *tracers,\nvals = [t.val for t in tracers]\nnew_closed_jaxpr = callback_jaxpr(fun_jaxpr, trace.callback, strip_calls=trace.strip_calls)\n- if primitive == cd.custom_jvp_call_jaxpr_p:\n- thunk_name = 'jvp_jaxpr_thunk'\n- elif primitive == cd.custom_vjp_call_jaxpr_p:\n+ if primitive == cd.custom_vjp_call_jaxpr_p:\nthunk_name = 'fwd_jaxpr_thunk'\nparams['bwd'] = callback_subtrace(params['bwd'], main)\nelse:\n@@ -287,7 +285,5 @@ def _custom_derivative_call_jaxpr_callback_rule(primitive, trace, *tracers,\nnum_consts=new_num_consts, **params)\nreturn safe_map(trace.pure, out)\n-custom_callback_rules[cd.custom_jvp_call_jaxpr_p] = partial(\n- _custom_derivative_call_jaxpr_callback_rule, cd.custom_jvp_call_jaxpr_p)\ncustom_callback_rules[cd.custom_vjp_call_jaxpr_p] = partial(\n_custom_derivative_call_jaxpr_callback_rule, cd.custom_vjp_call_jaxpr_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -1615,8 +1615,8 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\n# cased to just pass-through the token\nin_axes=eqn.params[\"in_axes\"] + (None, None),\nout_axes=eqn.params[\"out_axes\"] + (0, 0))))\n- elif eqn.primitive is custom_derivatives.custom_jvp_call_jaxpr_p:\n- fun_jaxpr = eqn.params[\"fun_jaxpr\"]\n+ elif eqn.primitive is custom_derivatives.custom_jvp_call_p:\n+ fun_jaxpr = eqn.params[\"call_jaxpr\"]\ndef unreachable_thunk():\nassert False, \"Should not be reached\"\n@@ -1627,7 +1627,7 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\noutvars=eqn.outvars + [output_token_var, output_itoken_var],\nparams=dict(\neqn.params,\n- fun_jaxpr=_rewrite_closed_jaxpr(fun_jaxpr, True, True),\n+ call_jaxpr=_rewrite_closed_jaxpr(fun_jaxpr, True, True),\njvp_jaxpr_thunk=unreachable_thunk\n)))\nelif eqn.primitive is custom_derivatives.custom_vjp_call_jaxpr_p:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -2788,14 +2788,15 @@ def _tridiagonal_solve(*args: TfVal, _in_avals, _out_aval, **params):\ntf_impl_with_avals[lax.linalg.tridiagonal_solve_p] = _tridiagonal_solve\n-def _custom_jvp_call_jaxpr(*args: TfVal, fun_jaxpr: core.ClosedJaxpr,\n+def _custom_jvp_call(*args: TfVal, call_jaxpr: core.ClosedJaxpr,\njvp_jaxpr_thunk: Callable,\nnum_consts: int) -> Sequence[TfVal]:\n# TODO(necula): ensure that there is no AD transformation in scope\n- return _interpret_jaxpr(fun_jaxpr, *args, extra_name_stack=\"custom_jvp\")\n+ del jvp_jaxpr_thunk, num_consts\n+ return _interpret_jaxpr(call_jaxpr, *args, extra_name_stack=\"custom_jvp\")\n-tf_impl[custom_derivatives.custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr\n+tf_impl[custom_derivatives.custom_jvp_call_p] = _custom_jvp_call\ndef _custom_vjp_call_jaxpr(*args: TfVal, fun_jaxpr: core.ClosedJaxpr,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -61,7 +61,6 @@ import numpy as np\nimport jax\nfrom jax import core\nfrom jax import lax\n-from jax.custom_derivatives import custom_jvp_call_jaxpr_p\nfrom jax.interpreters import xla\nimport jax.linear_util as lu\nimport jax.numpy as jnp\n@@ -682,13 +681,6 @@ def _lax_min_taylor_rule(primal_in, series_in):\nreturn primal_out, series_out\njet_rules[lax.min_p] = _lax_min_taylor_rule\n-def _custom_jvp_call_jaxpr_rule(primals_in, series_in, *, fun_jaxpr,\n- jvp_jaxpr_thunk):\n- # TODO(mattjj): do something better than ignoring custom jvp rules for jet?\n- del jvp_jaxpr_thunk\n- return jet(core.jaxpr_as_fun(fun_jaxpr), primals_in, series_in)\n-jet_rules[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_rule\n-\ndef _scatter_add_rule(primals_in, series_in, *, update_jaxpr, update_consts,\ndimension_numbers, indices_are_sorted, unique_indices,\nmode):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -463,45 +463,12 @@ class JaxprTrace(Trace):\ndef _current_truncated_name_stack(self):\nreturn source_info_util.current_name_stack()[len(self.name_stack):]\n- def process_custom_jvp_call(self, prim, f, jvp, tracers):\n- # TODO(mattjj): after old remat is deleted, make this method trivial:\n- # https://github.com/google/jax/pull/9137/files#diff-440d9df723b313bb263bc7704103cad1dcc886ff6553aa78c30188b0b323b686R319-R323\n- # Because we instantiate all tracers, in_knowns is all False.\n- tracers = map(self.instantiate_const_abstracted, tracers)\n- in_knowns, in_avals, () = partition_pvals([t.pval for t in tracers])\n- f = trace_to_subjaxpr_nounits(f, self.main, True)\n- f, aux = partial_eval_wrapper_nounits(f, tuple(in_knowns), tuple(in_avals))\n- out_flat = prim.bind(f, jvp)\n- out_knowns, out_avals, jaxpr, env = aux()\n- out_consts, res = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])\n- res_tracers = map(self.new_instantiated_const, res)\n- env_tracers = map(self.full_raise, env)\n- out_tracers = [JaxprTracer(self, PartialVal.unknown(a), None)\n- for a in out_avals]\n- closed_jaxpr = core.ClosedJaxpr(convert_constvars_jaxpr(jaxpr), ())\n-\n- @_memoize\n- def jvp_jaxpr_thunk():\n- jvp_ = trace_to_subjaxpr_nounits(jvp, self.main, True)\n- jvp_, aux = partial_eval_wrapper_nounits(\n- jvp_, tuple(in_knowns) * 2, tuple(in_avals) * 2)\n- with core.new_sublevel():\n- out_flat = jvp_.call_wrapped()\n- out_knowns, out_avals, jaxpr, env = aux()\n- _, res = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])\n- converted_jaxpr = convert_envvars_to_constvars(jaxpr, len(env))\n- return converted_jaxpr, (*res, *env)\n-\n- name_stack = self._current_truncated_name_stack()\n- source = source_info_util.current().replace(name_stack=name_stack)\n- eqn = new_eqn_recipe((*res_tracers, *env_tracers, *tracers),\n- out_tracers, prim.initial_style,\n- dict(fun_jaxpr=closed_jaxpr,\n- jvp_jaxpr_thunk=jvp_jaxpr_thunk,\n- num_consts=len(res)+len(env)),\n- jaxpr.effects, source)\n- for t in out_tracers: t.recipe = eqn\n- return merge_lists(out_knowns, out_tracers, out_consts)\n+ def process_custom_jvp_call(self, prim, fun, jvp, tracers):\n+ # We assume partial evaluation is only performed to build linear functions,\n+ # and hence we don't need to keep the custom JVP rule around anymore.\n+ del jvp\n+ assert not all(t.is_known() for t in tracers)\n+ return fun.call_wrapped(*tracers)\ndef post_process_custom_jvp_call(self, out_tracers, _):\n# This path should only be reachable if we expose a partial eval API\n@@ -1796,8 +1763,8 @@ class DynamicJaxprTrace(core.Trace):\ninvars = map(self.getvar, tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\noutvars = map(self.makevar, out_tracers)\n- eqn = new_jaxpr_eqn([*constvars, *invars], outvars, prim.initial_style,\n- dict(fun_jaxpr=closed_fun_jaxpr,\n+ eqn = new_jaxpr_eqn([*constvars, *invars], outvars, prim,\n+ dict(call_jaxpr=closed_fun_jaxpr,\njvp_jaxpr_thunk=jvp_jaxpr_thunk,\nnum_consts=len(consts)),\nfun_jaxpr.effects,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -3163,8 +3163,7 @@ class APITest(jtu.JaxTestCase):\n_ = self._saved_tracer+1\ndef test_escaped_tracer_shape_dtype(self):\n- with self.assertRaisesRegex(core.UnexpectedTracerError,\n- r\"shape \\(4, 3\\) and dtype int32\"):\n+ with self.assertRaisesRegex(core.UnexpectedTracerError, r\"int32\\[4,3\\]\"):\njax.jit(self.helper_save_tracer)(jnp.ones((4, 3), dtype=jnp.int32))\n_ = self._saved_tracer+1\n@@ -6642,15 +6641,15 @@ class CustomJVPTest(jtu.JaxTestCase):\ndef g(x):\nreturn f(f(x))\n- ans = api.grad(api.grad(api.remat(g)))(2.)\n+ ans = api.grad(api.grad(new_checkpoint(g)))(2.)\nexpected = api.grad(api.grad(g))(2.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- ans = api.grad(api.remat(api.grad(g)))(2.)\n+ ans = api.grad(new_checkpoint(api.grad(g)))(2.)\nexpected = api.grad(api.grad(g))(2.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- ans = api.grad(api.grad(api.grad(api.remat(g))))(2.)\n+ ans = api.grad(api.grad(api.grad(new_checkpoint(g))))(2.)\nexpected = api.grad(api.grad(api.grad(g)))(2.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n"
}
] | Python | Apache License 2.0 | google/jax | remove custom_jvp_call_jaxpr_p and its rules
They were superfluous! Instead use the "new" mechanism for converting from
jaxpr params to bind params (in #9136).
This change languished until we could land #11830 / #11950 and friends. But now
we can! |
260,631 | 17.08.2022 22:40:14 | 25,200 | fe665b3a641e06e5ebd7067f2204a3696235f844 | Copybara import of the project:
by Matthew Johnson
remove custom_jvp_call_jaxpr_p and its rules
They were superfluous! Instead use the "new" mechanism for converting from
jaxpr params to bind params (in
This change languished until we could land / and friends. But now
we can! | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/custom_derivatives.py",
"new_path": "jax/_src/custom_derivatives.py",
"diff": "from functools import update_wrapper, reduce, partial\nimport inspect\nimport operator as op\n-from typing import (Callable, Generic, Optional, Sequence, Tuple, TypeVar, Set,\n- Any)\n+from typing import (Any, Callable, Generic, List, Optional, Sequence, Set,\n+ Tuple, TypeVar)\nfrom jax import core\nfrom jax import linear_util as lu\n@@ -276,6 +276,8 @@ def _flatten_jvp(in_tree, *args):\nyield primals_out + tangents_out, out_tree\nclass CustomJVPCallPrimitive(core.CallPrimitive):\n+ initial_style: core.Primitive\n+\ndef bind(self, fun, jvp, *args):\nargs = map(core.full_lower, args)\ntop_trace = core.find_top_trace(args)\n@@ -295,23 +297,6 @@ class CustomJVPCallPrimitive(core.CallPrimitive):\ndef post_process(self, trace, out_tracers, jvp_was_run: bool):\nreturn trace.post_process_custom_jvp_call(out_tracers, jvp_was_run)\n- def get_bind_params(self, params):\n- new_params = dict(params)\n- call_jaxpr = new_params.pop('call_jaxpr')\n- num_consts = new_params.pop('num_consts')\n- jvp_jaxpr_thunk = new_params.pop('jvp_jaxpr_thunk')\n- fun = lu.wrap_init(core.jaxpr_as_fun(call_jaxpr))\n-\n- @lu.wrap_init\n- def jvp(*xs):\n- jvp_jaxpr, jvp_consts = jvp_jaxpr_thunk()\n- n, ragged = divmod(len(xs), 2)\n- assert not ragged\n- primals, tangents = xs[num_consts:n], xs[n+num_consts:]\n- return core.eval_jaxpr(jvp_jaxpr, jvp_consts, *primals, *tangents)\n-\n- return [fun, jvp], new_params\n-\n@lu.transformation_with_aux\ndef process_env_traces(primitive, level: int, jvp_was_run: bool, *args):\nouts = yield args, {}\n@@ -329,23 +314,6 @@ def process_env_traces(primitive, level: int, jvp_was_run: bool, *args):\ntodo.append(cur_todo)\nyield outs, tuple(todo) # Ensure the aux output is immutable\n- def get_bind_params(self, params):\n- new_params = dict(params)\n- call_jaxpr = new_params.pop('call_jaxpr')\n- num_consts = new_params.pop('num_consts')\n- jvp_jaxpr_thunk = new_params.pop('jvp_jaxpr_thunk')\n- fun = lu.wrap_init(core.jaxpr_as_fun(call_jaxpr))\n-\n- @lu.wrap_init\n- def jvp(*xs):\n- jvp_jaxpr, jvp_consts = jvp_jaxpr_thunk()\n- n, ragged = divmod(len(xs), 2)\n- assert not ragged\n- primals, tangents = xs[num_consts:n], xs[n+num_consts:]\n- return core.eval_jaxpr(jvp_jaxpr, jvp_consts, *primals, *tangents)\n-\n- return [fun, jvp], new_params\n-\ndef _apply_todos(todos, outs):\ntodos_list = list(todos)\nwhile todos_list:\n@@ -356,35 +324,122 @@ def _apply_todos(todos, outs):\nallowed_effects: Set[core.Effect] = set()\ncustom_jvp_call_p = CustomJVPCallPrimitive('custom_jvp_call')\n-def _custom_jvp_call_typecheck(*in_avals, call_jaxpr, jvp_jaxpr_thunk, num_consts):\n- # TODO(mattjj): could do more checking here...\n- del in_avals, jvp_jaxpr_thunk, num_consts\n- disallowed_effects = {eff for eff in call_jaxpr.effects if eff not in\n+\n+def _custom_jvp_call_jaxpr_impl(*args, fun_jaxpr: core.ClosedJaxpr, **params):\n+ del params # other params ignored because we're just executing the primal fun\n+ return core.jaxpr_as_fun(fun_jaxpr)(*args)\n+\n+def _custom_jvp_call_jaxpr_abstract_eval(*args, fun_jaxpr: core.ClosedJaxpr, **params):\n+ del args, params\n+ disallowed_effects = {eff for eff in fun_jaxpr.effects if eff not in\nallowed_effects}\nif disallowed_effects:\nraise NotImplementedError(\nf'Effects not supported in `custom_jvp`: {disallowed_effects}')\n- return call_jaxpr.out_avals, call_jaxpr.effects\n-core.custom_typechecks[custom_jvp_call_p] = _custom_jvp_call_typecheck\n+ return fun_jaxpr.out_avals, fun_jaxpr.effects\n-def _custom_jvp_call_mlir_translation(ctx, *args, call_jaxpr, jvp_jaxpr_thunk,\n- num_consts):\n- del jvp_jaxpr_thunk, num_consts\n- args_ = map(mlir.wrap_singleton_ir_values, args)\n- consts = mlir._ir_consts(call_jaxpr.consts)\n- out, tokens = mlir.jaxpr_subcomp(ctx.module_context, call_jaxpr.jaxpr,\n- ctx.tokens_in, consts, *args_)\n- ctx.set_tokens_out(tokens)\n- return out\n-mlir.register_lowering(custom_jvp_call_p, _custom_jvp_call_mlir_translation)\n+custom_jvp_call_jaxpr_p = core.AxisPrimitive('custom_jvp_call_jaxpr')\n+custom_jvp_call_jaxpr_p.multiple_results = True\n+custom_jvp_call_jaxpr_p.def_impl(_custom_jvp_call_jaxpr_impl)\n+custom_jvp_call_jaxpr_p.def_effectful_abstract_eval(_custom_jvp_call_jaxpr_abstract_eval)\n+CustomJVPCallPrimitive.initial_style = custom_jvp_call_jaxpr_p\n+\n+mlir.register_lowering(custom_jvp_call_jaxpr_p, mlir.lower_fun(\n+ _custom_jvp_call_jaxpr_impl, multiple_results=True))\n+\n+\n+def _custom_jvp_call_jaxpr_jvp(\n+ primals, tangents, *, fun_jaxpr: core.ClosedJaxpr,\n+ jvp_jaxpr_thunk: Callable[[], Tuple[core.Jaxpr, Sequence[Any]]],\n+ num_consts: int):\n+ _, args = split_list(primals, [num_consts])\n+ consts_dot, args_dot = split_list(tangents, [num_consts])\n+ if any(type(t) is not Zero for t in consts_dot):\n+ raise ad.CustomJVPException()\n+ jvp_jaxpr, jvp_consts = jvp_jaxpr_thunk() # consts can be tracers!\n+ args_dot = map(ad.instantiate_zeros, args_dot)\n+ # Cast float0 to zeros with the primal dtype because custom jvp rules don't\n+ # currently handle float0s\n+ args_dot = map(ad.replace_float0s, args, args_dot)\n+ outs = core.eval_jaxpr(jvp_jaxpr, jvp_consts, *args, *args_dot)\n+ primals_out, tangents_out = split_list(outs, [len(outs) // 2])\n+ tangents_out = map(ad.recast_to_float0, primals_out, tangents_out)\n+ if config.jax_enable_checks:\n+ assert all(map(core.typecheck, fun_jaxpr.out_avals, primals_out))\n+ return primals_out, tangents_out\n+ad.primitive_jvps[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_jvp\n+\n+def _custom_jvp_call_jaxpr_vmap(\n+ axis_size, axis_name, main_type, args, in_dims, *, fun_jaxpr: core.ClosedJaxpr,\n+ jvp_jaxpr_thunk: Callable[[], Tuple[core.Jaxpr, Sequence[Any]]],\n+ num_consts: int):\n+ args = [batching.moveaxis(x, d, 0) if d is not not_mapped and d != 0\n+ else x for x, d in zip(args, in_dims)]\n+ num_out = len(fun_jaxpr.out_avals)\n+\n+ in_batched = [d is not not_mapped for d in in_dims]\n+ batched_fun_jaxpr, out_batched = batching.batch_jaxpr(\n+ fun_jaxpr, axis_size, in_batched, False, axis_name, main_type)\n+ out_dims1 = [0 if b else not_mapped for b in out_batched]\n+ out_dims2 = [] # mutable cell updated by batched_jvp_jaxpr_thunk\n+\n+ @pe._memoize\n+ def batched_jvp_jaxpr_thunk():\n+ jvp_jaxpr = core.ClosedJaxpr(*jvp_jaxpr_thunk()) # consts can be tracers\n+ _, args_batched = split_list(in_batched, [num_consts])\n+ _, all_batched = batching.batch_jaxpr(jvp_jaxpr, axis_size, args_batched * 2, False,\n+ axis_name, main_type)\n+ primals_batched, tangents_batched = split_list(all_batched, [num_out])\n+ out_batched = map(op.or_, primals_batched, tangents_batched)\n+ out_dims2.append([0 if b else not_mapped for b in out_batched])\n+ batched_jvp_jaxpr, _ = batching.batch_jaxpr(\n+ jvp_jaxpr, axis_size, args_batched * 2, out_batched * 2,\n+ axis_name, main_type)\n+ return batched_jvp_jaxpr.jaxpr, batched_jvp_jaxpr.consts\n+\n+ batched_outs = custom_jvp_call_jaxpr_p.bind(\n+ *args, fun_jaxpr=batched_fun_jaxpr,\n+ jvp_jaxpr_thunk=batched_jvp_jaxpr_thunk, num_consts=num_consts)\n+ out_dims = out_dims2[0] if out_dims2 else out_dims1\n+ return batched_outs, out_dims\n+batching.axis_primitive_batchers[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_vmap\n+\n+xla.register_initial_style_primitive(custom_jvp_call_jaxpr_p)\n# If a (multi)linear function is defined with a custom jvp, then\n-# custom_jvp_call_ can appear in jaxprs to be transposed. Since it's already\n-# been linearized, we can drop the jvp rule.\n-def _custom_jvp_call_transpose(params, jaxpr, args, ct, _, reduce_axes):\n- del params\n- return ad.backward_pass(jaxpr.jaxpr, reduce_axes, None, jaxpr.consts, args, ct)\n-ad.primitive_transposes[custom_jvp_call_p] = _custom_jvp_call_transpose\n+# custom_jvp_call_jaxpr can appear in jaxprs to be transposed. Since it's\n+# already been linearized, we can drop the jvp rule.\n+def _custom_jvp_call_jaxpr_transpose(reduce_axes, cts, *args, fun_jaxpr,\n+ jvp_jaxpr_thunk, num_consts):\n+ del jvp_jaxpr_thunk, num_consts\n+ return ad.backward_pass(\n+ fun_jaxpr.jaxpr, reduce_axes, False, fun_jaxpr.consts, args, cts)\n+ad.reducing_transposes[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_transpose\n+\n+def custom_jvp_jaxpr_custom_partial_eval_rule(\n+ saveable: Callable[..., bool], unks_in: List[bool], inst_in: List[bool],\n+ eqn: core.JaxprEqn\n+ ) -> Tuple[Optional[core.JaxprEqn], core.JaxprEqn, List[bool], List[bool], List[core.Var]]:\n+ # It doesn't make sense to unzip (i.e. break up) a custom_jvp function into\n+ # constituent parts, so we always perform full remat. An alternative would be\n+ # to allow the policy function to decide whether the value of a\n+ # custom_jvp-decorated function's application should be saved or not.\n+ # TODO(mattjj,jekbradbury): the user writing the custom_jvp-decorated function\n+ # probably has a better idea for what to do under remat (e.g. if the function\n+ # contains dots or not), so we should allow for more expressive interaction\n+ # (e.g. allow the policy to depend on which custom_jvp-decorated function is\n+ # being applied, or annotating the behavior where custom_vjp is called.)\n+ inst_out = [True] * len(eqn.outvars)\n+ new_inst = [x for x, inst in zip(eqn.invars, inst_in)\n+ if type(x) is core.Var and not inst]\n+ if any(unks_in):\n+ unks_out = [True] * len(eqn.outvars)\n+ return None, eqn, unks_out, inst_out, new_inst\n+ else:\n+ unks_out = [False] * len(eqn.outvars)\n+ return eqn, eqn, unks_out, inst_out, new_inst\n+pe.partial_eval_jaxpr_custom_rules[custom_jvp_call_jaxpr_p] = \\\n+ custom_jvp_jaxpr_custom_partial_eval_rule # type: ignore\n### VJPs\n@@ -721,6 +776,9 @@ xla.register_initial_style_primitive(custom_vjp_call_jaxpr_p)\nbatching.primitive_batchers[ad.custom_lin_p] = ad._raise_custom_vjp_error_on_jvp\nmlir.register_lowering(ad.custom_lin_p, ad._raise_custom_vjp_error_on_jvp)\n+pe.partial_eval_jaxpr_custom_rules[custom_vjp_call_jaxpr_p] = \\\n+ custom_jvp_jaxpr_custom_partial_eval_rule # type: ignore\n+\ndef custom_gradient(fun):\n\"\"\"Convenience function for defining custom VJP rules (aka custom gradients).\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -500,8 +500,7 @@ def escaped_tracer_error(tracer, detail=None):\nnum_frames = FLAGS.jax_tracer_error_num_traceback_frames\nmsg = ('Encountered an unexpected tracer. A function transformed by JAX '\n'had a side effect, allowing for a reference to an intermediate value '\n- f'with type {tracer.aval.str_short()} wrapped in a '\n- f'{type(tracer).__name__} to escape the scope of the transformation.\\n'\n+ f'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.')\ndbg = getattr(tracer, '_debug_info', None)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/custom_derivatives.py",
"new_path": "jax/custom_derivatives.py",
"diff": "@@ -20,6 +20,7 @@ from jax._src.custom_derivatives import (\ncustom_gradient as custom_gradient,\ncustom_jvp as custom_jvp,\ncustom_jvp_call_p as custom_jvp_call_p,\n+ custom_jvp_call_jaxpr_p as custom_jvp_call_jaxpr_p,\ncustom_vjp as custom_vjp,\ncustom_vjp_call_p as custom_vjp_call_p,\ncustom_vjp_call_jaxpr_p as custom_vjp_call_jaxpr_p,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/callback.py",
"new_path": "jax/experimental/callback.py",
"diff": "@@ -264,7 +264,9 @@ def _custom_derivative_call_jaxpr_callback_rule(primitive, trace, *tracers,\nvals = [t.val for t in tracers]\nnew_closed_jaxpr = callback_jaxpr(fun_jaxpr, trace.callback, strip_calls=trace.strip_calls)\n- if primitive == cd.custom_vjp_call_jaxpr_p:\n+ if primitive == cd.custom_jvp_call_jaxpr_p:\n+ thunk_name = 'jvp_jaxpr_thunk'\n+ elif primitive == cd.custom_vjp_call_jaxpr_p:\nthunk_name = 'fwd_jaxpr_thunk'\nparams['bwd'] = callback_subtrace(params['bwd'], main)\nelse:\n@@ -285,5 +287,7 @@ def _custom_derivative_call_jaxpr_callback_rule(primitive, trace, *tracers,\nnum_consts=new_num_consts, **params)\nreturn safe_map(trace.pure, out)\n+custom_callback_rules[cd.custom_jvp_call_jaxpr_p] = partial(\n+ _custom_derivative_call_jaxpr_callback_rule, cd.custom_jvp_call_jaxpr_p)\ncustom_callback_rules[cd.custom_vjp_call_jaxpr_p] = partial(\n_custom_derivative_call_jaxpr_callback_rule, cd.custom_vjp_call_jaxpr_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -1615,8 +1615,8 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\n# cased to just pass-through the token\nin_axes=eqn.params[\"in_axes\"] + (None, None),\nout_axes=eqn.params[\"out_axes\"] + (0, 0))))\n- elif eqn.primitive is custom_derivatives.custom_jvp_call_p:\n- fun_jaxpr = eqn.params[\"call_jaxpr\"]\n+ elif eqn.primitive is custom_derivatives.custom_jvp_call_jaxpr_p:\n+ fun_jaxpr = eqn.params[\"fun_jaxpr\"]\ndef unreachable_thunk():\nassert False, \"Should not be reached\"\n@@ -1627,7 +1627,7 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\noutvars=eqn.outvars + [output_token_var, output_itoken_var],\nparams=dict(\neqn.params,\n- call_jaxpr=_rewrite_closed_jaxpr(fun_jaxpr, True, True),\n+ fun_jaxpr=_rewrite_closed_jaxpr(fun_jaxpr, True, True),\njvp_jaxpr_thunk=unreachable_thunk\n)))\nelif eqn.primitive is custom_derivatives.custom_vjp_call_jaxpr_p:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -2786,15 +2786,14 @@ def _tridiagonal_solve(*args: TfVal, _in_avals, _out_aval, **params):\ntf_impl_with_avals[lax.linalg.tridiagonal_solve_p] = _tridiagonal_solve\n-def _custom_jvp_call(*args: TfVal, call_jaxpr: core.ClosedJaxpr,\n+def _custom_jvp_call_jaxpr(*args: TfVal, fun_jaxpr: core.ClosedJaxpr,\njvp_jaxpr_thunk: Callable,\nnum_consts: int) -> Sequence[TfVal]:\n# TODO(necula): ensure that there is no AD transformation in scope\n- del jvp_jaxpr_thunk, num_consts\n- return _interpret_jaxpr(call_jaxpr, *args, extra_name_stack=\"custom_jvp\")\n+ return _interpret_jaxpr(fun_jaxpr, *args, extra_name_stack=\"custom_jvp\")\n-tf_impl[custom_derivatives.custom_jvp_call_p] = _custom_jvp_call\n+tf_impl[custom_derivatives.custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr\ndef _custom_vjp_call_jaxpr(*args: TfVal, fun_jaxpr: core.ClosedJaxpr,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -61,6 +61,7 @@ import numpy as np\nimport jax\nfrom jax import core\nfrom jax import lax\n+from jax.custom_derivatives import custom_jvp_call_jaxpr_p\nfrom jax.interpreters import xla\nimport jax.linear_util as lu\nimport jax.numpy as jnp\n@@ -681,6 +682,13 @@ def _lax_min_taylor_rule(primal_in, series_in):\nreturn primal_out, series_out\njet_rules[lax.min_p] = _lax_min_taylor_rule\n+def _custom_jvp_call_jaxpr_rule(primals_in, series_in, *, fun_jaxpr,\n+ jvp_jaxpr_thunk):\n+ # TODO(mattjj): do something better than ignoring custom jvp rules for jet?\n+ del jvp_jaxpr_thunk\n+ return jet(core.jaxpr_as_fun(fun_jaxpr), primals_in, series_in)\n+jet_rules[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_rule\n+\ndef _scatter_add_rule(primals_in, series_in, *, update_jaxpr, update_consts,\ndimension_numbers, indices_are_sorted, unique_indices,\nmode):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -463,12 +463,45 @@ class JaxprTrace(Trace):\ndef _current_truncated_name_stack(self):\nreturn source_info_util.current_name_stack()[len(self.name_stack):]\n- def process_custom_jvp_call(self, prim, fun, jvp, tracers):\n- # We assume partial evaluation is only performed to build linear functions,\n- # and hence we don't need to keep the custom JVP rule around anymore.\n- del jvp\n- assert not all(t.is_known() for t in tracers)\n- return fun.call_wrapped(*tracers)\n+ def process_custom_jvp_call(self, prim, f, jvp, tracers):\n+ # TODO(mattjj): after old remat is deleted, make this method trivial:\n+ # https://github.com/google/jax/pull/9137/files#diff-440d9df723b313bb263bc7704103cad1dcc886ff6553aa78c30188b0b323b686R319-R323\n+ # Because we instantiate all tracers, in_knowns is all False.\n+ tracers = map(self.instantiate_const_abstracted, tracers)\n+ in_knowns, in_avals, () = partition_pvals([t.pval for t in tracers])\n+ f = trace_to_subjaxpr_nounits(f, self.main, True)\n+ f, aux = partial_eval_wrapper_nounits(f, tuple(in_knowns), tuple(in_avals))\n+ out_flat = prim.bind(f, jvp)\n+ out_knowns, out_avals, jaxpr, env = aux()\n+ out_consts, res = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])\n+ res_tracers = map(self.new_instantiated_const, res)\n+ env_tracers = map(self.full_raise, env)\n+ out_tracers = [JaxprTracer(self, PartialVal.unknown(a), None)\n+ for a in out_avals]\n+ closed_jaxpr = core.ClosedJaxpr(convert_constvars_jaxpr(jaxpr), ())\n+\n+ @_memoize\n+ def jvp_jaxpr_thunk():\n+ jvp_ = trace_to_subjaxpr_nounits(jvp, self.main, True)\n+ jvp_, aux = partial_eval_wrapper_nounits(\n+ jvp_, tuple(in_knowns) * 2, tuple(in_avals) * 2)\n+ with core.new_sublevel():\n+ out_flat = jvp_.call_wrapped()\n+ out_knowns, out_avals, jaxpr, env = aux()\n+ _, res = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])\n+ converted_jaxpr = convert_envvars_to_constvars(jaxpr, len(env))\n+ return converted_jaxpr, (*res, *env)\n+\n+ name_stack = self._current_truncated_name_stack()\n+ source = source_info_util.current().replace(name_stack=name_stack)\n+ eqn = new_eqn_recipe((*res_tracers, *env_tracers, *tracers),\n+ out_tracers, prim.initial_style,\n+ dict(fun_jaxpr=closed_jaxpr,\n+ jvp_jaxpr_thunk=jvp_jaxpr_thunk,\n+ num_consts=len(res)+len(env)),\n+ jaxpr.effects, source)\n+ for t in out_tracers: t.recipe = eqn\n+ return merge_lists(out_knowns, out_tracers, out_consts)\ndef post_process_custom_jvp_call(self, out_tracers, _):\n# This path should only be reachable if we expose a partial eval API\n@@ -1763,8 +1796,8 @@ class DynamicJaxprTrace(core.Trace):\ninvars = map(self.getvar, tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\noutvars = map(self.makevar, out_tracers)\n- eqn = new_jaxpr_eqn([*constvars, *invars], outvars, prim,\n- dict(call_jaxpr=closed_fun_jaxpr,\n+ eqn = new_jaxpr_eqn([*constvars, *invars], outvars, prim.initial_style,\n+ dict(fun_jaxpr=closed_fun_jaxpr,\njvp_jaxpr_thunk=jvp_jaxpr_thunk,\nnum_consts=len(consts)),\nfun_jaxpr.effects,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -3163,7 +3163,8 @@ class APITest(jtu.JaxTestCase):\n_ = self._saved_tracer+1\ndef test_escaped_tracer_shape_dtype(self):\n- with self.assertRaisesRegex(core.UnexpectedTracerError, r\"int32\\[4,3\\]\"):\n+ with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ r\"shape \\(4, 3\\) and dtype int32\"):\njax.jit(self.helper_save_tracer)(jnp.ones((4, 3), dtype=jnp.int32))\n_ = self._saved_tracer+1\n@@ -6641,15 +6642,15 @@ class CustomJVPTest(jtu.JaxTestCase):\ndef g(x):\nreturn f(f(x))\n- ans = api.grad(api.grad(new_checkpoint(g)))(2.)\n+ ans = api.grad(api.grad(api.remat(g)))(2.)\nexpected = api.grad(api.grad(g))(2.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- ans = api.grad(new_checkpoint(api.grad(g)))(2.)\n+ ans = api.grad(api.remat(api.grad(g)))(2.)\nexpected = api.grad(api.grad(g))(2.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- ans = api.grad(api.grad(api.grad(new_checkpoint(g))))(2.)\n+ ans = api.grad(api.grad(api.grad(api.remat(g))))(2.)\nexpected = api.grad(api.grad(api.grad(g)))(2.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n"
}
] | Python | Apache License 2.0 | google/jax | Copybara import of the project:
--
887b7ce2cb3d6d8aedac5cc273e137f1c876e3c7 by Matthew Johnson <mattjj@google.com>:
remove custom_jvp_call_jaxpr_p and its rules
They were superfluous! Instead use the "new" mechanism for converting from
jaxpr params to bind params (in #9136).
This change languished until we could land #11830 / #11950 and friends. But now
we can!
PiperOrigin-RevId: 468373797 |
260,507 | 18.08.2022 08:45:41 | 25,200 | d5de596d1739051b88dffa2c0a310aa832c047b9 | Sparse direct solver via QR factorization CUDA implementation. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/linalg.py",
"new_path": "jax/experimental/sparse/linalg.py",
"diff": "@@ -20,6 +20,12 @@ import functools\nimport jax\nimport jax.numpy as jnp\n+from jax import core\n+from jax.interpreters import mlir\n+from jax.interpreters import xla\n+\n+from jax._src.lib import gpu_solver\n+\nimport numpy as np\ndef lobpcg_standard(\n@@ -501,3 +507,49 @@ def _extend_basis(X, m):\nh = -2 * jnp.linalg.multi_dot(\n[w, w[k:, :].T, other], precision=jax.lax.Precision.HIGHEST)\nreturn h.at[k:].add(other)\n+\n+\n+# Sparse direct solve via QR factorization\n+\n+\n+def _spsolve_abstract_eval(data, indices, indptr, b, tol, reorder):\n+ del data, indices, indptr, tol, reorder\n+ return core.raise_to_shaped(b)\n+\n+\n+def _spsolve_gpu_lowering(ctx, data, indices, indptr, b, tol, reorder):\n+ data_aval, _, _, _, = ctx.avals_in\n+\n+ return gpu_solver.cuda_csrlsvqr(data_aval.dtype, data, indices,\n+ indptr, b, tol, reorder)\n+\n+\n+spsolve_p = core.Primitive('spsolve')\n+spsolve_p.def_impl(functools.partial(xla.apply_primitive, spsolve_p))\n+spsolve_p.def_abstract_eval(_spsolve_abstract_eval)\n+mlir.register_lowering(spsolve_p, _spsolve_gpu_lowering, platform='cuda')\n+\n+\n+def spsolve(data, indices, indptr, b, tol=1e-6, reorder=1):\n+ \"\"\"A sparse direct solver using QR factorization.\n+\n+ Accepts a sparse matrix in CSR format `data, indices, indptr` arrays.\n+ Currently only the CUDA GPU backend is implemented.\n+\n+ Args:\n+ data : An array containing the non-zero entries of the CSR matrix.\n+ indices : The column indices of the CSR matrix.\n+ indptr : The row pointer array of the CSR matrix.\n+ b : The right hand side of the linear system.\n+ tol : Tolerance to decide if singular or not. Defaults to 1e-6.\n+ reorder : The reordering scheme to use to reduce fill-in. No reordering if\n+ `reorder=0'. Otherwise, symrcm, symamd, or csrmetisnd (`reorder=1,2,3'),\n+ respectively. Defaults to symrcm.\n+\n+ Returns:\n+ An array with the same dtype and size as b representing the solution to\n+ the sparse linear system.\n+ \"\"\"\n+ if jax._src.lib.xla_extension_version < 86:\n+ raise ValueError('spsolve requires jaxlib version 86 or above.')\n+ return spsolve_p.bind(data, indices, indptr, b, tol=tol, reorder=reorder)\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cuda_gpu_kernels.cc",
"new_path": "jaxlib/cuda/cuda_gpu_kernels.cc",
"diff": "@@ -37,6 +37,7 @@ XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"cuda_threefry2x32\", CudaThreeFry2x32,\nXLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"cusolver_potrf\", Potrf, \"CUDA\");\nXLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"cusolver_getrf\", Getrf, \"CUDA\");\nXLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"cusolver_geqrf\", Geqrf, \"CUDA\");\n+XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"cusolver_csrlsvqr\", Csrlsvqr, \"CUDA\");\nXLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"cusolver_orgqr\", Orgqr, \"CUDA\");\nXLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"cusolver_syevd\", Syevd, \"CUDA\");\nXLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(\"cusolver_syevj\", Syevj, \"CUDA\");\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusolver.cc",
"new_path": "jaxlib/cuda/cusolver.cc",
"diff": "@@ -182,6 +182,19 @@ std::pair<int, py::bytes> BuildGeqrfDescriptor(const py::dtype& dtype, int b,\nreturn {lwork, PackDescriptor(GeqrfDescriptor{type, b, m, n, lwork})};\n}\n+// csrlsvqr: Linear system solve via Sparse QR\n+\n+// Returns a descriptor for a csrlsvqr operation.\n+py::bytes BuildCsrlsvqrDescriptor(const py::dtype& dtype, int n, int nnzA,\n+ int reorder, double tol) {\n+ CusolverType type = DtypeToCusolverType(dtype);\n+ auto h = SpSolverHandlePool::Borrow();\n+ JAX_THROW_IF_ERROR(h.status());\n+ auto& handle = *h;\n+\n+ return PackDescriptor(CsrlsvqrDescriptor{type, n, nnzA, reorder, tol});\n+}\n+\n// orgqr/ungqr: apply elementary Householder transformations\n// Returns the workspace size and a descriptor for a geqrf operation.\n@@ -463,6 +476,7 @@ py::dict Registrations() {\ndict[\"cusolver_potrf\"] = EncapsulateFunction(Potrf);\ndict[\"cusolver_getrf\"] = EncapsulateFunction(Getrf);\ndict[\"cusolver_geqrf\"] = EncapsulateFunction(Geqrf);\n+ dict[\"cusolver_csrlsvqr\"] = EncapsulateFunction(Csrlsvqr);\ndict[\"cusolver_orgqr\"] = EncapsulateFunction(Orgqr);\ndict[\"cusolver_syevd\"] = EncapsulateFunction(Syevd);\ndict[\"cusolver_syevj\"] = EncapsulateFunction(Syevj);\n@@ -476,6 +490,7 @@ PYBIND11_MODULE(_cusolver, m) {\nm.def(\"build_potrf_descriptor\", &BuildPotrfDescriptor);\nm.def(\"build_getrf_descriptor\", &BuildGetrfDescriptor);\nm.def(\"build_geqrf_descriptor\", &BuildGeqrfDescriptor);\n+ m.def(\"build_csrlsvqr_descriptor\", &BuildCsrlsvqrDescriptor);\nm.def(\"build_orgqr_descriptor\", &BuildOrgqrDescriptor);\nm.def(\"build_syevd_descriptor\", &BuildSyevdDescriptor);\nm.def(\"build_syevj_descriptor\", &BuildSyevjDescriptor);\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusolver_kernels.cc",
"new_path": "jaxlib/cuda/cusolver_kernels.cc",
"diff": "@@ -27,6 +27,7 @@ limitations under the License.\n#include \"third_party/gpus/cuda/include/cuda.h\"\n#include \"third_party/gpus/cuda/include/cuda_runtime_api.h\"\n#include \"third_party/gpus/cuda/include/cusolverDn.h\"\n+#include \"third_party/gpus/cuda/include/cusolverSp.h\"\n#include \"jaxlib/cuda/cuda_gpu_kernel_helpers.h\"\n#include \"jaxlib/handle_pool.h\"\n#include \"jaxlib/kernel_helpers.h\"\n@@ -52,6 +53,24 @@ template <>\nreturn Handle(pool, handle, stream);\n}\n+template <>\n+/*static*/ absl::StatusOr<SpSolverHandlePool::Handle>\n+SpSolverHandlePool::Borrow(cudaStream_t stream) {\n+ SpSolverHandlePool* pool = Instance();\n+ absl::MutexLock lock(&pool->mu_);\n+ cusolverSpHandle_t handle;\n+ if (pool->handles_[stream].empty()) {\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpCreate(&handle)));\n+ } else {\n+ handle = pool->handles_[stream].back();\n+ pool->handles_[stream].pop_back();\n+ }\n+ if (stream) {\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpSetStream(handle, stream)));\n+ }\n+ return Handle(pool, handle, stream);\n+}\n+\nstatic int SizeOfCusolverType(CusolverType type) {\nswitch (type) {\ncase CusolverType::F32:\n@@ -332,6 +351,103 @@ void Geqrf(cudaStream_t stream, void** buffers, const char* opaque,\n}\n}\n+// csrlsvqr: Linear system solve via Sparse QR\n+\n+static absl::Status Csrlsvqr_(cudaStream_t stream, void** buffers,\n+ const char* opaque, size_t opaque_len,\n+ int& singularity) {\n+ auto s = UnpackDescriptor<CsrlsvqrDescriptor>(opaque, opaque_len);\n+ JAX_RETURN_IF_ERROR(s.status());\n+ const CsrlsvqrDescriptor& d = **s;\n+\n+ // This is the handle to the CUDA session. Gets a cusolverSp handle.\n+ auto h = SpSolverHandlePool::Borrow(stream);\n+ JAX_RETURN_IF_ERROR(h.status());\n+ auto& handle = *h;\n+\n+ cusparseMatDescr_t matdesc = nullptr;\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseCreateMatDescr(&matdesc)));\n+ JAX_RETURN_IF_ERROR(\n+ JAX_AS_STATUS(cusparseSetMatType(matdesc, CUSPARSE_MATRIX_TYPE_GENERAL)));\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(\n+ cusparseSetMatIndexBase(matdesc, CUSPARSE_INDEX_BASE_ZERO)));\n+\n+ switch (d.type) {\n+ case CusolverType::F32: {\n+ float* csrValA = static_cast<float*>(buffers[0]);\n+ int* csrRowPtrA = static_cast<int*>(buffers[1]);\n+ int* csrColIndA = static_cast<int*>(buffers[2]);\n+ float* b = static_cast<float*>(buffers[3]);\n+ float* x = static_cast<float*>(buffers[4]);\n+\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpScsrlsvqr(\n+ handle.get(), d.n, d.nnz, matdesc, csrValA, csrRowPtrA, csrColIndA,\n+ b, (float)d.tol, d.reorder, x, &singularity)));\n+\n+ break;\n+ }\n+ case CusolverType::F64: {\n+ double* csrValA = static_cast<double*>(buffers[0]);\n+ int* csrRowPtrA = static_cast<int*>(buffers[1]);\n+ int* csrColIndA = static_cast<int*>(buffers[2]);\n+ double* b = static_cast<double*>(buffers[3]);\n+ double* x = static_cast<double*>(buffers[4]);\n+\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpDcsrlsvqr(\n+ handle.get(), d.n, d.nnz, matdesc, csrValA, csrRowPtrA, csrColIndA,\n+ b, d.tol, d.reorder, x, &singularity)));\n+\n+ break;\n+ }\n+ case CusolverType::C64: {\n+ cuComplex* csrValA = static_cast<cuComplex*>(buffers[0]);\n+ int* csrRowPtrA = static_cast<int*>(buffers[1]);\n+ int* csrColIndA = static_cast<int*>(buffers[2]);\n+ cuComplex* b = static_cast<cuComplex*>(buffers[3]);\n+ cuComplex* x = static_cast<cuComplex*>(buffers[4]);\n+\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpCcsrlsvqr(\n+ handle.get(), d.n, d.nnz, matdesc, csrValA, csrRowPtrA, csrColIndA,\n+ b, (float)d.tol, d.reorder, x, &singularity)));\n+\n+ break;\n+ }\n+ case CusolverType::C128: {\n+ cuDoubleComplex* csrValA = static_cast<cuDoubleComplex*>(buffers[0]);\n+ int* csrRowPtrA = static_cast<int*>(buffers[1]);\n+ int* csrColIndA = static_cast<int*>(buffers[2]);\n+ cuDoubleComplex* b = static_cast<cuDoubleComplex*>(buffers[3]);\n+ cuDoubleComplex* x = static_cast<cuDoubleComplex*>(buffers[4]);\n+\n+ JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpZcsrlsvqr(\n+ handle.get(), d.n, d.nnz, matdesc, csrValA, csrRowPtrA, csrColIndA,\n+ b, (float)d.tol, d.reorder, x, &singularity)));\n+\n+ break;\n+ }\n+ }\n+\n+ cusparseDestroyMatDescr(matdesc);\n+ return absl::OkStatus();\n+}\n+\n+void Csrlsvqr(cudaStream_t stream, void** buffers, const char* opaque,\n+ size_t opaque_len, XlaCustomCallStatus* status) {\n+ // Is >= 0 if A is singular.\n+ int singularity = -1;\n+\n+ auto s = Csrlsvqr_(stream, buffers, opaque, opaque_len, singularity);\n+ if (!s.ok()) {\n+ XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),\n+ s.message().length());\n+ }\n+\n+ if (singularity >= 0) {\n+ auto s = std::string(\"Singular matrix in linear solve.\");\n+ XlaCustomCallStatusSetFailure(status, s.c_str(), s.length());\n+ }\n+}\n+\n// orgqr/ungqr: apply elementary Householder transformations\nstatic absl::Status Orgqr_(cudaStream_t stream, void** buffers,\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusolver_kernels.h",
"new_path": "jaxlib/cuda/cusolver_kernels.h",
"diff": "@@ -20,17 +20,23 @@ limitations under the License.\n#include \"third_party/gpus/cuda/include/cuda.h\"\n#include \"third_party/gpus/cuda/include/cuda_runtime_api.h\"\n#include \"third_party/gpus/cuda/include/cusolverDn.h\"\n+#include \"third_party/gpus/cuda/include/cusolverSp.h\"\n#include \"jaxlib/handle_pool.h\"\n#include \"tensorflow/compiler/xla/service/custom_call_status.h\"\nnamespace jax {\nusing SolverHandlePool = HandlePool<cusolverDnHandle_t, cudaStream_t>;\n+using SpSolverHandlePool = HandlePool<cusolverSpHandle_t, cudaStream_t>;\ntemplate <>\nabsl::StatusOr<SolverHandlePool::Handle> SolverHandlePool::Borrow(\ncudaStream_t stream);\n+template <>\n+absl::StatusOr<SpSolverHandlePool::Handle> SpSolverHandlePool::Borrow(\n+ cudaStream_t stream);\n+\n// Set of types known to Cusolver.\nenum class CusolverType {\nF32,\n@@ -70,6 +76,17 @@ struct GeqrfDescriptor {\nvoid Geqrf(cudaStream_t stream, void** buffers, const char* opaque,\nsize_t opaque_len, XlaCustomCallStatus* status);\n+// csrlsvpr: Linear system solve via Sparse QR\n+\n+struct CsrlsvqrDescriptor {\n+ CusolverType type;\n+ int n, nnz, reorder;\n+ double tol;\n+};\n+\n+void Csrlsvqr(cudaStream_t stream, void** buffers, const char* opaque,\n+ size_t opaque_len, XlaCustomCallStatus* status);\n+\n// orgqr/ungqr: apply elementary Householder transformations\nstruct OrgqrDescriptor {\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/gpu_solver.py",
"new_path": "jaxlib/gpu_solver.py",
"diff": "@@ -260,6 +260,31 @@ cuda_geqrf_batched = partial(_geqrf_batched_mhlo, \"cu\", _cublas)\nrocm_geqrf_batched = partial(_geqrf_batched_mhlo, \"hip\", _hipblas)\n+def _csrlsvqr_mhlo(platform, gpu_solver, dtype, data,\n+ indices, indptr, b, tol, reorder):\n+ \"\"\"Sparse solver via QR decomposition. CUDA only.\"\"\"\n+ b_type = ir.RankedTensorType(b.type)\n+ data_type = ir.RankedTensorType(data.type)\n+\n+ n = b_type.shape[0]\n+ nnz = data_type.shape[0]\n+ opaque = gpu_solver.build_csrlsvqr_descriptor(\n+ np.dtype(dtype), n, nnz, reorder, tol\n+ )\n+\n+ out = custom_call(\n+ f\"{platform}solver_csrlsvqr\", # call_target_name\n+ [b.type], # out_types\n+ [data, indptr, indices, b], # operands\n+ backend_config=opaque, # backend_config\n+ operand_layouts=[(0,), (0,), (0,), (0,)], # operand_layouts\n+ result_layouts=[(0,)] # result_layouts\n+ )\n+ return [out]\n+\n+cuda_csrlsvqr = partial(_csrlsvqr_mhlo, \"cu\", _cusolver)\n+\n+\ndef _orgqr_mhlo(platform, gpu_solver, dtype, a, tau):\n\"\"\"Product of elementary Householder reflections.\"\"\"\na_type = ir.RankedTensorType(a.type)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -2319,5 +2319,38 @@ class SparseRandomTest(jtu.JaxTestCase):\nself.assertAlmostEqual(int(num_nonzero), approx_expected_num_nonzero, delta=2)\n+class SparseSolverTest(jtu.JaxTestCase):\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_re{}_({})\".format(reorder,\n+ jtu.format_shape_dtype_string((size, size), dtype)),\n+ \"size\": size, \"reorder\": reorder, \"dtype\": dtype}\n+ for size in [20, 50, 100]\n+ for reorder in [0, 1, 2, 3]\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.complex))\n+ @unittest.skipIf(not GPU_LOWERING_ENABLED, \"test requires cusparse/cusolver\")\n+ @unittest.skipIf(jtu.device_under_test() != \"gpu\", \"test requires GPU\")\n+ @unittest.skipIf(jax._src.lib.xla_extension_version < 86, \"test requires jaxlib version 86\")\n+ @jtu.skip_on_devices(\"rocm\")\n+ def test_sparse_qr_linear_solver(self, size, reorder, dtype):\n+ rng = rand_sparse(self.rng())\n+ a = rng((size, size), dtype)\n+ nse = (a != 0).sum()\n+ data, indices, indptr = sparse.csr_fromdense(a, nse=nse)\n+\n+ rng_k = jtu.rand_default(self.rng())\n+ b = rng_k([size], dtype)\n+\n+ def args_maker():\n+ return data, indices, indptr, b\n+\n+ tol = 1e-8\n+ def sparse_solve(data, indices, indptr, b):\n+ return sparse.linalg.spsolve(data, indices, indptr, b, tol, reorder)\n+ x = sparse_solve(data, indices, indptr, b)\n+\n+ self.assertAllClose(a @ x, b, rtol=1e-2)\n+ self._CompileAndCheck(sparse_solve, args_maker)\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Sparse direct solver via QR factorization CUDA implementation.
PiperOrigin-RevId: 468467698 |
260,335 | 18.08.2022 12:07:26 | 25,200 | d2647cf0fa0a878e3fa862aa9a6fc923afee5004 | clean up some dead code, from bad merge | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/custom_derivatives.py",
"new_path": "jax/_src/custom_derivatives.py",
"diff": "@@ -331,23 +331,6 @@ def process_env_traces(primitive, level: int, jvp_was_run: bool, *args):\ntodo.append(cur_todo)\nyield outs, tuple(todo) # Ensure the aux output is immutable\n- def get_bind_params(self, params):\n- new_params = dict(params)\n- call_jaxpr = new_params.pop('call_jaxpr')\n- num_consts = new_params.pop('num_consts')\n- jvp_jaxpr_thunk = new_params.pop('jvp_jaxpr_thunk')\n- fun = lu.wrap_init(core.jaxpr_as_fun(call_jaxpr))\n-\n- @lu.wrap_init\n- def jvp(*xs):\n- jvp_jaxpr, jvp_consts = jvp_jaxpr_thunk()\n- n, ragged = divmod(len(xs), 2)\n- assert not ragged\n- primals, tangents = xs[num_consts:n], xs[n+num_consts:]\n- return core.eval_jaxpr(jvp_jaxpr, jvp_consts, *primals, *tangents)\n-\n- return [fun, jvp], new_params\n-\ndef _apply_todos(todos, outs):\ntodos_list = list(todos)\nwhile todos_list:\n"
}
] | Python | Apache License 2.0 | google/jax | clean up some dead code, from bad merge |
260,510 | 12.08.2022 16:52:49 | 25,200 | 49b7729f6b2334d8dbeda8f8d2859ed8471d47d0 | More tests for transpose | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/for_loop.py",
"new_path": "jax/_src/lax/control_flow/for_loop.py",
"diff": "@@ -307,8 +307,9 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\nconstvars=[])\nfor _ in range(num_inputs):\njaxpr_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, _, _, = pe.partial_eval_jaxpr_custom(\n+ discharged_jaxpr, jaxpr_in_unknowns, [True] * len(jaxpr_in_unknowns),\n+ in_unknowns, False, _save_everything)\nout_unknowns = list(out_unknowns)\nif out_unknowns == in_unknowns:\nbreak\n@@ -374,6 +375,8 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\nknown_vals = [t.pval.get_known() for t in known_tracers]\nempty_res = map(ad_util.zeros_like_aval, res_avals)\njaxpr_known_args = [*known_vals, *empty_res]\n+ # We assume the known inputs are nonlinear which is okay to do for AD but not\n+ # necessarily okay for general partial eval.\njaxpr_known_which_linear = (False,) * len(jaxpr_known_args)\nout_flat = for_p.bind(*jaxpr_known_args, jaxpr=jaxpr_known, nsteps=nsteps,\nreverse=reverse, which_linear=jaxpr_known_which_linear)\n@@ -470,7 +473,6 @@ def _convert_inputs_to_reads(\nreturn jaxpr\ndef transpose_jaxpr(jaxpr: core.Jaxpr, which_linear: List[bool]) -> core.Jaxpr:\n- which_linear = map(bool, np.cumsum(which_linear).astype(np.bool_))\ndef trans(i, *args):\n# First we want to run the computation to read all the residual refs. We can\n# do that by using partial evaluation with all linear inputs unknown.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/primitives.py",
"new_path": "jax/_src/state/primitives.py",
"diff": "@@ -21,6 +21,7 @@ from jax._src import ad_util\nfrom jax._src import pretty_printer as pp\nfrom jax._src.util import safe_map, safe_zip\nfrom jax.interpreters import ad\n+from jax.interpreters import partial_eval as pe\nimport jax.numpy as jnp\nfrom jax._src.state.types import ShapedArrayRef, StateEffect\n@@ -257,5 +258,23 @@ def addupdate_transpose(cts_in, ref, x, *idx):\n# addupdate transpose is get\ndel cts_in, x\ng = ref_get(ref, idx)\n- return [None] + [None] * len(idx) + [g]\n+ return [None, g] + [None] * len(idx)\nad.primitive_transposes[addupdate_p] = addupdate_transpose\n+\n+## get/swap/addupdate partial_eval_custom rules\n+\n+def _state_partial_eval_custom(prim, saveable, unks_in, inst_in, eqn):\n+ if any(unks_in):\n+ res = [v for v, inst in zip(eqn.invars, inst_in) if not inst]\n+ return None, eqn, [True] * len(eqn.outvars), [True] * len(eqn.outvars), res\n+ elif saveable(get_p, *[var.aval for var in eqn.invars], **eqn.params):\n+ return eqn, None, [False] * len(eqn.outvars), [False] * len(eqn.outvars), []\n+ res = [v for v, inst in zip(eqn.invars, inst_in) if not inst]\n+ return eqn, eqn, [False] * len(eqn.outvars), [True] * len(eqn.outvars), []\n+\n+pe.partial_eval_jaxpr_custom_rules[get_p] = partial(_state_partial_eval_custom,\n+ get_p)\n+pe.partial_eval_jaxpr_custom_rules[swap_p] = partial(_state_partial_eval_custom,\n+ swap_p)\n+pe.partial_eval_jaxpr_custom_rules[addupdate_p] = partial(\n+ _state_partial_eval_custom, addupdate_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -99,7 +99,7 @@ SCAN_IMPLS_WITH_FOR = [\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+ (scan_with_for, 'for_loop'),\n]\n@@ -1594,6 +1594,8 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nif scan is scan_with_new_checkpoint2:\nrtol = {np.float64: 1e-12, np.float32: 1e-4}\n+ elif scan is scan_with_for:\n+ rtol = {np.float64: 1e-12, np.float32: 1e-4}\nelse:\nrtol = {np.float64: 1e-14, np.float32: 1e-4}\n@@ -1633,13 +1635,19 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nexpected = jax.grad(lambda c, as_: list(scan_reference(f, c, as_))[0].sum())(c, as_)\nif scan is scan_with_new_checkpoint:\nrtol = {np.float32: 5e-5, np.float64: 1e-13}\n+ atol = 1e-5\n+ elif scan is scan_with_for:\n+ rtol = {np.float32: 2e-5, np.float64: 1e-13}\n+ atol = {np.float32: 6e-2, np.float64: 1e-13}\nelse:\nrtol = {np.float32: 2e-5, np.float64: 1e-13}\n- self.assertAllClose(ans, expected, check_dtypes=False, rtol=rtol, atol=1e-5)\n+ atol = 1e-5\n+ self.assertAllClose(ans, expected, check_dtypes=False, rtol=rtol, atol=atol)\nrtol = 5e-3 if scan is not scan_with_new_checkpoint2 else 5e-2\n+ atol = 5e-2 if \"tpu\" in jtu.device_under_test() else 1e-3\njtu.check_grads(partial(scan, f), (c, as_), order=2, modes=[\"rev\"],\n- atol=1e-3, rtol=rtol)\n+ atol=atol, 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@@ -1782,7 +1790,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 testScanHigherOrderDifferentiation(self, scan):\nd = 0.75\ndef f(c, a):\n@@ -2778,6 +2786,19 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nif v.aval.shape == (2, 32)]\nself.assertLen(consts, 2)\n+ def loss(A):\n+ def step(x, i):\n+ return jnp.matmul(A, x), None\n+ init_x = jnp.zeros(A.shape[-1:])\n+ last_x, _ = for_loop.scan(step, init_x, jnp.arange(10))\n+ return jnp.sum(last_x)\n+\n+ A = jnp.zeros((3, 3))\n+ # The second DUS was unnecessarily replicating A across time.\n+ # We check XLA because _scan_impl is \"underneath\" the jaxpr language.\n+ s = str(jax.xla_computation(jax.grad(loss))(A).as_hlo_text())\n+ assert s.count(\"dynamic-update-slice(\") < 2\n+\ndef test_for_loop_fixpoint_correctly_identifies_loop_varying_residuals(self):\ndef body(i, refs):\n@@ -2830,8 +2851,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nself.assertAllClose(ans, ans_discharged, check_dtypes=True, rtol=tol,\natol=tol)\nself.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\n- jtu.check_grads(lambda *args: for_(n, f, args)[1].sum(), args, order=2)\n-\n+ jtu.check_grads(lambda *args: for_(n, f, args)[1].sum(), args, order=3)\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | More tests for transpose |
260,631 | 18.08.2022 22:07:58 | 25,200 | 29482a2ef6b60d319a6a4cee00e20a067fb42d2d | Copybara import of the project:
by Jake VanderPlas
jnp.remainder: match numpy's behavior for integer zero denominator | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/ufuncs.py",
"new_path": "jax/_src/numpy/ufuncs.py",
"diff": "@@ -529,8 +529,6 @@ def frexp(x):\ndef remainder(x1, x2):\nx1, x2 = _promote_args_numeric(\"remainder\", x1, x2)\nzero = _constant_like(x1, 0)\n- if dtypes.issubdtype(x2.dtype, np.integer):\n- x2 = _where(x2 == 0, lax_internal._ones(x2), x2)\ntrunc_mod = lax.rem(x1, x2)\ntrunc_mod_not_zero = lax.ne(trunc_mod, zero)\ndo_plus = lax.bitwise_and(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -287,9 +287,9 @@ JAX_COMPOUND_OP_RECORDS = [\nop_record(\"rad2deg\", 1, float_dtypes, all_shapes, jtu.rand_default, []),\nop_record(\"ravel\", 1, all_dtypes, all_shapes, jtu.rand_default, [\"rev\"]),\nop_record(\"real\", 1, number_dtypes, all_shapes, jtu.rand_some_inf, []),\n- op_record(\"remainder\", 2, default_dtypes, all_shapes, jtu.rand_some_zero, [],\n+ op_record(\"remainder\", 2, default_dtypes, all_shapes, jtu.rand_nonzero, [],\ntolerance={np.float16: 1e-2}),\n- op_record(\"mod\", 2, default_dtypes, all_shapes, jtu.rand_some_zero, []),\n+ op_record(\"mod\", 2, default_dtypes, all_shapes, jtu.rand_nonzero, []),\nop_record(\"modf\", 1, float_dtypes, all_shapes, jtu.rand_default, []),\nop_record(\"modf\", 1, int_dtypes + unsigned_dtypes, all_shapes,\njtu.rand_default, [], check_dtypes=False),\n"
}
] | Python | Apache License 2.0 | google/jax | Copybara import of the project:
--
0cf7b33e9e166f21a05bbddb04f95dad89a5f7a9 by Jake VanderPlas <jakevdp@google.com>:
jnp.remainder: match numpy's behavior for integer zero denominator
PiperOrigin-RevId: 468621345 |
260,631 | 19.08.2022 04:57:07 | 25,200 | 764c268ff6d3d6d69c30f6a2dae91739f0a82730 | Increase the threshold to use tuple_args to 2000 args for TPUs. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -916,7 +916,10 @@ def xla_computation(fun: Callable,\nxla.sharding_to_proto, in_parts_flat)),\nresult_shardings=(None if out_parts_flat is None else map(\nxla.sharding_to_proto, out_parts_flat)))\n- should_tuple = tuple_args if tuple_args is not None else (len(avals) > 100)\n+ if tuple_args is not None:\n+ should_tuple = tuple_args\n+ else:\n+ dispatch.should_tuple_args(len(avals), backend.platform)\nbuilt = xc._xla.mlir.mlir_module_to_xla_computation(\nmlir.module_to_string(lowering_result.module),\nuse_tuple_args=should_tuple,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -329,6 +329,14 @@ def log_elapsed_time(fmt: str):\nlogging.log(log_priority, fmt.format(elapsed_time=elapsed_time))\n+def should_tuple_args(num_args: int, platform: str):\n+ # pass long arg lists as tuple for TPU\n+ if platform == \"tpu\":\n+ return num_args > 2000\n+ else:\n+ return num_args > 100\n+\n+\n@profiler.annotate_function\ndef lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\ndonated_invars, always_lower: bool, keep_unused: bool,\n@@ -430,7 +438,7 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\n\"extra data movement anyway, so maybe you don't want it after all).\")\n# pass long arg lists as tuple for TPU\n- tuple_args = len(abstract_args) > 100\n+ tuple_args = should_tuple_args(len(abstract_args), backend.platform)\naxis_env = xla.AxisEnv(nreps, (), ())\nname_stack = util.new_name_stack(util.wrap_name(name, 'jit'))\nclosed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1199,11 +1199,6 @@ def find_replicas(jaxpr, axis_size, global_axis_size):\nreturn ReplicaInfo(jaxpr_replicas, num_local_replicas, num_global_replicas)\n-def should_tuple_args(shards: ShardInfo):\n- # tuplify long arg lists for TPU\n- return len(shards.global_sharded_avals) > 100\n-\n-\ndef stage_parallel_callable(\npci: ParallelCallableInfo,\nfun: lu.WrappedFun,\n@@ -1371,7 +1366,8 @@ def lower_parallel_callable(\nclosed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\nreplicated_args = [axis is None for axis in in_axes]\nmodule: Union[str, xc.XlaComputation]\n- tuple_args = should_tuple_args(shards)\n+ tuple_args = dispatch.should_tuple_args(len(shards.global_sharded_avals),\n+ backend.platform)\nmodule_name = f\"pmap_{fun.__name__}\"\nwith maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\nif any(eff in core.ordered_effects for eff in closed_jaxpr.effects):\n@@ -2638,7 +2634,8 @@ def lower_sharding_computation(\njaxpr = dispatch.apply_outfeed_rewriter(jaxpr)\n# 2. Build up the HLO\n- tuple_args = len(in_jaxpr_avals) > 100 # pass long arg lists as tuple for TPU\n+ tuple_args = dispatch.should_tuple_args(len(in_jaxpr_avals), backend.platform)\n+\nin_op_shardings: Optional[List[Optional[xc.OpSharding]]]\nout_op_shardings: Optional[List[Optional[xc.OpSharding]]]\naxis_ctx: mlir.ShardingContext\n@@ -2771,7 +2768,8 @@ def lower_mesh_computation(\njaxpr = dispatch.apply_outfeed_rewriter(jaxpr)\n# 2. Build up the HLO\n- tuple_args = len(in_jaxpr_avals) > 100 # pass long arg lists as tuple for TPU\n+ tuple_args = dispatch.should_tuple_args(len(in_jaxpr_avals), backend.platform)\n+\nin_partitions: Optional[List[Optional[xc.OpSharding]]]\nout_partitions: Optional[List[Optional[xc.OpSharding]]]\naxis_ctx: mlir.AxisContext\n"
}
] | Python | Apache License 2.0 | google/jax | Increase the threshold to use tuple_args to 2000 args for TPUs.
PiperOrigin-RevId: 468675921 |
260,335 | 11.08.2022 19:39:50 | 25,200 | b3b4ffbc218a190eb4785c31cdcbf1411659c417 | make slicing compilation a little faster
For the common special case of int or slice-of-int/None indexing, we can
generate a lax.slice rather than a lax.gather. That makes compilation a little
faster, and makes the generated jaxpr a bit more wieldy too, to process in
transformations and to read when pretty-printed. | [
{
"change_type": "MODIFY",
"old_path": "benchmarks/api_benchmark.py",
"new_path": "benchmarks/api_benchmark.py",
"diff": "@@ -546,6 +546,13 @@ def bench_slicing_compilation(state):\nwhile state:\njax.jit(lambda x: (x[0], x[1], x[2])).lower(x).compile()\n+@google_benchmark.register\n+@google_benchmark.option.unit(google_benchmark.kMillisecond)\n+def bench_slicing_compilation2(state):\n+ x = jnp.arange(3)\n+ while state:\n+ jax.jit(lambda x: (x[:1], x[1:2], x[2:3])).lower(x).compile()\n+\nif __name__ == \"__main__\":\ngoogle_benchmark.main()\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3593,6 +3593,25 @@ def _rewriting_take(arr, idx, indices_are_sorted=False, unique_indices=False,\n# All supported cases of indexing can be implemented as an XLA gather,\n# followed by an optional reverse and broadcast_in_dim.\n+ # Handle some special cases, falling back if error messages might differ.\n+ if (arr.ndim > 0 and isinstance(idx, (int, np.integer)) and\n+ not isinstance(idx, (bool, np.bool_)) and isinstance(arr.shape[0], int)):\n+ if 0 <= idx < arr.shape[0]:\n+ return lax.index_in_dim(arr, idx, keepdims=False)\n+ if (arr.ndim > 0 and isinstance(arr.shape[0], int) and\n+ isinstance(idx, slice) and\n+ (type(idx.start) is int or idx.start is None) and\n+ (type(idx.stop) is int or idx.stop is None) and\n+ (type(idx.step) is int or idx.step is None)):\n+ n = arr.shape[0]\n+ start = idx.start if idx.start is not None else 0\n+ stop = idx.stop if idx.stop is not None else n\n+ step = idx.step if idx.step is not None else 1\n+ if (0 <= start < n and 0 <= stop <= n and 0 < step and\n+ (start, stop, step) != (0, n, 1)):\n+ return lax.slice_in_dim(arr, start, stop, step)\n+\n+\n# TODO(mattjj,dougalm): expand dynamic shape indexing support\nif (jax.config.jax_dynamic_shapes and type(idx) is slice and idx.step is None\nand (isinstance(idx.start, core.Tracer) or isinstance(idx.stop, core.Tracer))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -325,6 +325,7 @@ deflinear(lax.broadcast_in_dim_p)\ndeflinear(lax.concatenate_p)\ndeflinear(lax.pad_p)\ndeflinear(lax.reshape_p)\n+deflinear(lax.squeeze_p)\ndeflinear(lax.rev_p)\ndeflinear(lax.transpose_p)\ndeflinear(lax.slice_p)\n"
}
] | Python | Apache License 2.0 | google/jax | make slicing compilation a little faster
For the common special case of int or slice-of-int/None indexing, we can
generate a lax.slice rather than a lax.gather. That makes compilation a little
faster, and makes the generated jaxpr a bit more wieldy too, to process in
transformations and to read when pretty-printed. |
260,332 | 19.08.2022 11:08:11 | 25,200 | c2e521807c0615244a5a1363a58d9ee73bafbce5 | Add support to test gpu jaxlib nightly in CI instead of prebuilt jax/jaxlib | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/slurm_job_scripts/multinode_pytest.sub",
"new_path": ".github/workflows/slurm_job_scripts/multinode_pytest.sub",
"diff": "#!/bin/bash\n-#SBATCH -A arbitrary\n+#SBATCH -A ci-jax-gpu\n#SBATCH -p compute\n#SBATCH -N 2 # number of nodes\n-#SBATCH -t 01:00:00 # wall time\n-#SBATCH -J \"arbitrary\" # job name (<< CHANGE ! >>)\n+#SBATCH -t 00:15:00 # wall time\n+#SBATCH -J \"ci-jax-gpu\" # job name\n#SBATCH --exclusive # exclusive node access\n#SBATCH --mem=0 # all mem avail\n#SBATCH --mail-type=FAIL # only send email on failure\n-#SBATCH --ntasks-per-node=1 # n tasks per machine\n+#SBATCH --ntasks-per-node=1 # 1 tasks per machine for now\n#SBATCH --overcommit # Needed for pytorch\nset -x\n# File system and volume glue code\n#-------------------------------------------------------------------------------\n-CONTAINER=\"nvcr.io/nvidian/jax_t5x:jax_0.3.14\"\n+CONTAINER=\"nvcr.io/nvidian/jax_t5x:cuda11.4-cudnn8.2-ubuntu20.04-manylinux2014-multipython\"\nCONTAINER_NAME=\"multinode_ci_test_container\"\nBASE_WORKSPACE_DIR=$GITHUB_WORKSPACE\nWORKSPACE_DIR=/workspace\nMOUNTS=\"--container-mounts=$BASE_WORKSPACE_DIR:/$WORKSPACE_DIR\"\n+\n+# Since the docker container doesn't contain MLX drivers for IB, following flags\n+# are needed to make NCCL work with an ethernet setup\n+# Note:@sudhakarsingh27 This is very specific, need to abstract this out\n+EXPORTS=\"--export=ALL,NCCL_SOCKET_IFNAME=enp45s0f0,NCCL_SOCKET_NTHREADS=2,NCCL_NSOCKS_PERTHREAD=2\"\n#-------------------------------------------------------------------------------\n# Setup command to be run before the actual pytest command\nread -r -d '' setup_cmd <<EOF\n-pip install pytest \\\n+python3.8 -m pip install --pre jaxlib -f https://storage.googleapis.com/jax-releases/jaxlib_nightly_cuda_releases.html \\\n+&& python3.8 -m pip install git+https://github.com/google/jax \\\n+&& python3.8 -m pip install pytest \\\n&& mkdir -p /workspace/outputs/\nEOF\n# Main pytest command that runs the tests\nread -r -d '' cmd <<EOF\ndate \\\n-&& pytest -v -s --continue-on-collection-errors \\\n+&& python3.8 -m pip list | grep jax \\\n+&& python3.8 -m pytest -v -s --continue-on-collection-errors \\\n--junit-xml=/workspace/outputs/junit_output_\\${SLURM_PROCID}.xml \\\n/workspace/tests/distributed_multinode_test.py\nEOF\n@@ -52,6 +60,7 @@ srun -o $OUTFILE -e $OUTFILE \\\n--container-image=\"$CONTAINER\" \\\n--container-name=$CONTAINER_NAME \\\n$MOUNTS \\\n+ $EXPORTS \\\nbash -c \"${setup_cmd}\"\n# Barrier command\n@@ -60,9 +69,11 @@ wait\n# Run the actual pytest command\necho $cmd\nsrun -o $OUTFILE -e $OUTFILE \\\n+ --open-mode=append \\\n--container-writable \\\n--container-image=\"$CONTAINER\" \\\n--container-name=$CONTAINER_NAME \\\n$MOUNTS \\\n+ $EXPORTS \\\nbash -c \"${cmd}\"\nset +x\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/distributed_multinode_test.py",
"new_path": "tests/distributed_multinode_test.py",
"diff": "import os\nimport unittest\n+from absl.testing import absltest\n+\nimport jax\nimport jax._src.lib\nfrom jax._src import test_util as jtu\n@@ -60,3 +62,6 @@ class MultiNodeGpuTest(jtu.JaxTestCase):\ny = jax.pmap(lambda x: jax.lax.psum(x, \"i\"), axis_name=\"i\")(x)\nself.assertEqual(y[0], jax.device_count())\nprint(y)\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add support to test gpu jaxlib nightly in CI instead of prebuilt jax/jaxlib |
260,447 | 19.08.2022 12:25:37 | 25,200 | d37b711dd46b19baf75d990e14493c80586fcd37 | [sparse] Add batch count and batch stride to matrix descriptors. | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusparse.cc",
"new_path": "jaxlib/cuda/cusparse.cc",
"diff": "@@ -78,17 +78,21 @@ cudaDataType DtypeToCudaDataType(const py::dtype& np_type) {\n// Returns the descriptor for a Sparse matrix.\nSparseMatDescriptor BuildSparseMatDescriptor(const py::dtype& data_dtype,\nconst py::dtype& index_dtype,\n- int rows, int cols, int nnz) {\n+ int rows, int cols, int nnz,\n+ int batch_count,\n+ int batch_stride) {\ncudaDataType value_type = DtypeToCudaDataType(data_dtype);\ncusparseIndexType_t index_type = DtypeToCuSparseIndexType(index_dtype);\n- return SparseMatDescriptor{value_type, index_type, rows, cols, nnz};\n+ return SparseMatDescriptor{\n+ value_type, index_type, rows, cols, nnz, batch_count, batch_stride};\n}\n// Returns the descriptor for a Dense matrix.\nDenseMatDescriptor BuildDenseMatDescriptor(const py::dtype& data_dtype,\n- int rows, int cols) {\n+ int rows, int cols, int batch_count,\n+ int batch_stride) {\ncudaDataType value_type = DtypeToCudaDataType(data_dtype);\n- return DenseMatDescriptor{value_type, rows, cols};\n+ return DenseMatDescriptor{value_type, rows, cols, batch_count, batch_stride};\n}\n// Returns the descriptor for a Dense vector.\n@@ -109,7 +113,8 @@ std::pair<size_t, py::bytes> BuildCsrToDenseDescriptor(\nJAX_THROW_IF_ERROR(h.status());\nauto& handle = *h;\nSparseMatDescriptor d =\n- BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz);\n+ BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz,\n+ /*batch_count*/1, /*batch_stride*/0);\ncusparseSpMatDescr_t mat_a = 0;\ncusparseDnMatDescr_t mat_b = 0;\n@@ -185,7 +190,8 @@ std::pair<size_t, py::bytes> BuildCsrFromDenseDescriptor(\nJAX_THROW_IF_ERROR(h.status());\nauto& handle = *h;\nSparseMatDescriptor d =\n- BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz);\n+ BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz,\n+ /*batch_count=*/1, /*batch_stride=*/0);\ncusparseDnMatDescr_t mat_a = 0;\ncusparseSpMatDescr_t mat_b = 0;\n@@ -261,7 +267,8 @@ std::pair<size_t, py::bytes> BuildCsrMatvecDescriptor(\nJAX_THROW_IF_ERROR(h.status());\nauto& handle = *h;\nSparseMatDescriptor A =\n- BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz);\n+ BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz,\n+ /*batch_count=*/1, /*batch_stride=*/0);\nDenseVecDescriptor x =\nBuildDenseVecDescriptor(x_dtype, transpose ? rows : cols);\nDenseVecDescriptor y =\n@@ -308,11 +315,14 @@ std::pair<size_t, py::bytes> BuildCsrMatmatDescriptor(\nJAX_THROW_IF_ERROR(h.status());\nauto& handle = *h;\nSparseMatDescriptor A =\n- BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz);\n+ BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz,\n+ /*batch_count=*/1, /*batch_stride=*/0);\nDenseMatDescriptor B =\n- BuildDenseMatDescriptor(b_dtype, transpose ? rows : cols, BCcols);\n+ BuildDenseMatDescriptor(b_dtype, transpose ? rows : cols, BCcols,\n+ /*batch_count=*/1, /*batch_stride=*/0);\nDenseMatDescriptor C =\n- BuildDenseMatDescriptor(compute_dtype, transpose ? cols : rows, BCcols);\n+ BuildDenseMatDescriptor(compute_dtype, transpose ? cols : rows, BCcols,\n+ /*batch_count=*/1, /*batch_stride=*/0);\ncusparseOperation_t op_A = transpose ? CUSPARSE_OPERATION_TRANSPOSE\n: CUSPARSE_OPERATION_NON_TRANSPOSE;\n@@ -356,7 +366,8 @@ std::pair<size_t, py::bytes> BuildCooToDenseDescriptor(\nJAX_THROW_IF_ERROR(h.status());\nauto& handle = *h;\nSparseMatDescriptor d =\n- BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz);\n+ BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz,\n+ /*batch_count=*/1, /*batch_stride=*/0);\ncusparseSpMatDescr_t mat_a = 0;\ncusparseDnMatDescr_t mat_b = 0;\n@@ -392,7 +403,8 @@ std::pair<size_t, py::bytes> BuildCooFromDenseDescriptor(\nJAX_THROW_IF_ERROR(h.status());\nauto& handle = *h;\nSparseMatDescriptor d =\n- BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz);\n+ BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz,\n+ /*batch_count=*/1, /*batch_stride=*/0);\ncusparseDnMatDescr_t mat_a = 0;\ncusparseSpMatDescr_t mat_b = 0;\n@@ -428,7 +440,8 @@ std::pair<size_t, py::bytes> BuildCooMatvecDescriptor(\nJAX_THROW_IF_ERROR(h.status());\nauto& handle = *h;\nSparseMatDescriptor A =\n- BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz);\n+ BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz,\n+ /*batch_count=*/1, /*batch_stride=*/0);\nDenseVecDescriptor x =\nBuildDenseVecDescriptor(x_dtype, transpose ? rows : cols);\nDenseVecDescriptor y =\n@@ -470,16 +483,32 @@ std::pair<size_t, py::bytes> BuildCooMatvecDescriptor(\nstd::pair<size_t, py::bytes> BuildCooMatmatDescriptor(\nconst py::dtype& data_dtype, const py::dtype& b_dtype,\nconst py::dtype& compute_dtype, const py::dtype& index_dtype, int rows,\n- int cols, int BCcols, int nnz, bool transpose) {\n+ int cols, int BCcols, int nnz, bool transpose, int batch_count,\n+ int lhs_batch_stride, int rhs_batch_stride) {\n+ // Three batch modes are supported, C_i = A_i B, C_i = A B_i, and\n+ // Ci = A_i B_i, where `i` denotes the batch dimension.\n+ // All three matrices A, B, and C must have the same batch count.\n+ // Use batch stride to trigger individual mode, e.g.,\n+ // `rhs_batch_stride = 0` for C_i = A_i B.\nauto h = SparseHandlePool::Borrow();\nJAX_THROW_IF_ERROR(h.status());\nauto& handle = *h;\n+\nSparseMatDescriptor A =\n- BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz);\n+ BuildSparseMatDescriptor(data_dtype, index_dtype, rows, cols, nnz,\n+ batch_count, lhs_batch_stride);\nDenseMatDescriptor B =\n- BuildDenseMatDescriptor(b_dtype, transpose ? rows : cols, BCcols);\n+ BuildDenseMatDescriptor(b_dtype, transpose ? rows : cols, BCcols,\n+ batch_count, rhs_batch_stride);\n+ int C_rows = (transpose == true) ? cols : rows;\n+ // TODO(tianjianlu): enable the selection of batch stride.\n+ // The issue (https://github.com/NVIDIA/CUDALibrarySamples/issues/81#issuecomment-1205562643)\n+ // in cusparse library does not allow batch_stride = 0.\n+ // int C_batch_stride = (batch_count > 1)? C_rows * BCcols : 0;\n+ int C_batch_stride = C_rows * BCcols;\nDenseMatDescriptor C =\n- BuildDenseMatDescriptor(compute_dtype, transpose ? cols : rows, BCcols);\n+ BuildDenseMatDescriptor(compute_dtype, /*rows=*/C_rows, /*cols=*/BCcols,\n+ batch_count, C_batch_stride);\ncusparseOperation_t op_A = transpose ? CUSPARSE_OPERATION_TRANSPOSE\n: CUSPARSE_OPERATION_NON_TRANSPOSE;\n@@ -487,16 +516,6 @@ std::pair<size_t, py::bytes> BuildCooMatmatDescriptor(\ncusparseDnMatDescr_t mat_b = 0;\ncusparseDnMatDescr_t mat_c = 0;\n- // All three matrices A, B, and C must have the same batch_count.\n- // TODO(tianjianlu): use batch_count from matrix descriptor.\n- int batch_count = 1;\n-\n- // Three batch modes are supported, C_i = A_i B, C_i = A B_i, and\n- // Ci = A_i B_i, where `i` denotes the batch dimension. Use `batch_stride` to\n- // trigger individual mode, e.g., using `batch_stride_B = 0` in C_i = A_i B.\n- int batch_stride_A = A.rows * A.cols;\n- int batch_stride_B = B.rows * B.cols;\n- int batch_stride_C = C.rows * C.cols;\n// bufferSize does not reference these pointers, but does error on NULL.\nint val = 0;\n@@ -506,19 +525,19 @@ std::pair<size_t, py::bytes> BuildCooMatmatDescriptor(\nA.index_type, CUSPARSE_INDEX_BASE_ZERO, A.value_type)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(\ncusparseCooSetStridedBatch(\n- mat_a, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_A)));\n+ mat_a, /*batchCount=*/batch_count, /*batchStride=*/A.batch_stride)));\nJAX_THROW_IF_ERROR(\nJAX_AS_STATUS(cusparseCreateDnMat(&mat_b, B.rows, B.cols, /*ld=*/B.cols,\nempty, B.type, CUSPARSE_ORDER_ROW)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(\ncusparseDnMatSetStridedBatch(\n- mat_b, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_B)));\n+ mat_b, /*batchCount=*/batch_count, /*batchStride=*/B.batch_stride)));\nJAX_THROW_IF_ERROR(\nJAX_AS_STATUS(cusparseCreateDnMat(&mat_c, C.rows, C.cols, /*ld=*/C.cols,\nempty, C.type, CUSPARSE_ORDER_ROW)));\nJAX_THROW_IF_ERROR(JAX_AS_STATUS(\ncusparseDnMatSetStridedBatch(\n- mat_c, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_C)));\n+ mat_c, /*batchCount=*/batch_count, /*batchStride=*/C.batch_stride)));\nsize_t buffer_size;\nCudaConst alpha = CudaOne(C.type);\nCudaConst beta = CudaZero(C.type);\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusparse_kernels.cc",
"new_path": "jaxlib/cuda/cusparse_kernels.cc",
"diff": "@@ -509,35 +509,25 @@ static absl::Status CooMatmat_(cudaStream_t stream, void** buffers,\ncusparseDnMatDescr_t mat_b = 0;\ncusparseDnMatDescr_t mat_c = 0;\n- // All three matrices A, B, and C must have the same batch_count.\n- // TODO(tianjianlu): use batch_count from matrix descriptor.\n- int batch_count = 1;\n-\n- // Three batch modes are supported, C_i = A_i B, C_i = A B_i, and\n- // Ci = A_i B_i, where `i` denotes the batch dimension. Use `batch_stride` to\n- // trigger individual mode, e.g., using `batch_stride_B = 0` in C_i = A_i B.\n- int batch_stride_A = d.A.rows * d.A.cols;\n- int batch_stride_B = d.B.rows * d.B.cols;\n- int batch_stride_C = d.C.rows * d.C.cols;\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseCreateCoo(\n&mat_a, d.A.rows, d.A.cols, d.A.nnz, coo_row_ind, coo_col_ind, coo_values,\nd.A.index_type, CUSPARSE_INDEX_BASE_ZERO, d.A.value_type)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(\n- cusparseCooSetStridedBatch(\n- mat_a, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_A)));\n+ cusparseCooSetStridedBatch(mat_a, /*batchCount=*/d.A.batch_count,\n+ /*batchStride=*/d.A.batch_stride)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseCreateDnMat(\n&mat_b, d.B.rows, d.B.cols,\n/*ld=*/d.B.cols, Bbuf, d.B.type, CUSPARSE_ORDER_ROW)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(\n- cusparseDnMatSetStridedBatch(\n- mat_b, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_B)));\n+ cusparseDnMatSetStridedBatch(mat_b, /*batchCount=*/d.B.batch_count,\n+ /*batchStride=*/d.B.batch_stride)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseCreateDnMat(\n&mat_c, d.C.rows, d.C.cols,\n/*ld=*/d.C.cols, Cbuf, d.C.type, CUSPARSE_ORDER_ROW)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(\n- cusparseDnMatSetStridedBatch(\n- mat_c, /*batchCount=*/batch_count, /*batchStride=*/batch_stride_C)));\n+ cusparseDnMatSetStridedBatch(mat_c, /*batchCount=*/d.C.batch_count,\n+ /*batchStride=*/d.C.batch_stride)));\nJAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseSpMM(\nhandle.get(), d.op_A, /*opB=*/CUSPARSE_OPERATION_NON_TRANSPOSE, &alpha,\nmat_a, mat_b, &beta, mat_c, d.C.type, CUSPARSE_SPMM_ALG_DEFAULT, buf)));\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/cuda/cusparse_kernels.h",
"new_path": "jaxlib/cuda/cusparse_kernels.h",
"diff": "@@ -61,11 +61,15 @@ struct SparseMatDescriptor {\ncudaDataType value_type;\ncusparseIndexType_t index_type;\nint rows, cols, nnz;\n+ int batch_count = 1;\n+ int batch_stride = 0;\n};\nstruct DenseMatDescriptor {\ncudaDataType type;\nint rows, cols;\n+ int batch_count = 1;\n+ int batch_stride = 0;\n};\nstruct DenseVecDescriptor {\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/gpu_sparse.py",
"new_path": "jaxlib/gpu_sparse.py",
"diff": "@@ -291,9 +291,21 @@ def _coo_matmat_mhlo(platform, gpu_sparse, data, row, col, B, *, shape,\ncompute_dtype = data_dtype\ncompute_type = data_type\n+ # TODO(tianjianlu): use user-defined batch count after enabling batch mode.\n+ batch_count = 1\n+\n+ # TODO(tianjianlu): use batch stride to trigger different mode of batch\n+ # computation. Currently batch_stride = 0 is not allowed because of the issue\n+ # in cusparse https://github.com/NVIDIA/CUDALibrarySamples/issues/81#issuecomment-1205562643\n+ # Set batch stride to be the matrix size for now.\n+ lhs_batch_stride = rows * cols\n+ B_rows = rows if transpose else cols\n+ rhs_batch_stride = B_rows * Ccols\n+\nbuffer_size, opaque = gpu_sparse.build_coo_matmat_descriptor(\ndata_dtype, x_dtype, compute_dtype, index_dtype,\n- rows, cols, Ccols, nnz, transpose)\n+ rows, cols, Ccols, nnz, transpose, batch_count, lhs_batch_stride,\n+ rhs_batch_stride)\nout_size = cols if transpose else rows\nout = custom_call(\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Add batch count and batch stride to matrix descriptors.
PiperOrigin-RevId: 468760351 |
260,558 | 22.08.2022 15:46:38 | -7,200 | 88f605123302903e3b0c081b9de688959d57cc21 | target_total_secs has type `int` but used as type `None`
"filename": "benchmarks/benchmark.py"
"warning_type": "Incompatible variable type [9]",
"warning_message": " target_total_secs is declared to have type `int` but is used as type `None`."
"warning_line": 86
"fix": int to Optional[int] | [
{
"change_type": "MODIFY",
"old_path": "benchmarks/benchmark.py",
"new_path": "benchmarks/benchmark.py",
"diff": "@@ -83,7 +83,7 @@ def benchmark(f: Callable[[], Any], iters: Optional[int] = None,\ndef benchmark_suite(prepare: Callable[..., Callable], params_list: List[Dict],\n- name: str, target_total_secs: int = None):\n+ name: str, target_total_secs: Optional[int] = None):\n\"\"\"Benchmarks a function for several combinations of parameters.\nPrints the summarized results in a table..\n"
}
] | Python | Apache License 2.0 | google/jax | target_total_secs has type `int` but used as type `None`
"filename": "benchmarks/benchmark.py"
"warning_type": "Incompatible variable type [9]",
"warning_message": " target_total_secs is declared to have type `int` but is used as type `None`."
"warning_line": 86
"fix": int to Optional[int] |
260,631 | 23.08.2022 10:37:34 | 25,200 | a73a6a8de082c58667ab732d12762b8c5c9f1dbd | Shut down preemption sync manager if enabled. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/distributed.py",
"new_path": "jax/_src/distributed.py",
"diff": "@@ -87,6 +87,8 @@ class State:\nif self.service:\nself.service.shutdown()\nself.service = None\n+ if self.preemption_sync_manager:\n+ self.preemption_sync_manager = None\ndef initialize_preemption_sync_manager(self):\nif self.preemption_sync_manager is not None:\n"
}
] | Python | Apache License 2.0 | google/jax | Shut down preemption sync manager if enabled.
PiperOrigin-RevId: 469497215 |
260,335 | 23.08.2022 19:06:57 | 25,200 | 88a212e3bbdaabde113f448667095f4554201705 | in ad_checkpoint WrapHashably.__eq__, check _both_ are hashable
fixes | [
{
"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, Sequence, Set, Union, Any\n+from typing import (Callable, Optional, List, Tuple, Sequence, Set, Union, Any,\n+ FrozenSet)\nimport types\nfrom absl import logging\n@@ -302,7 +303,7 @@ def _remat_static_argnums(fun, static_argnums, args):\nclass WrapHashably:\nval: Any\n- hash: Optional[int] = None\n+ hash: int\nhashable: bool\ndef __init__(self, val):\n@@ -317,8 +318,10 @@ class WrapHashably:\nreturn self.hash\ndef __eq__(self, other):\nif isinstance(other, WrapHashably):\n- try: return self.val == other.val\n- except: return self.val is other.val\n+ if self.hashable and other.hashable:\n+ return self.val == other.val\n+ else:\n+ return self.val is other.val\nreturn False\n# This caching is useful to avoid retracing even when static_argnums is used.\n@@ -326,7 +329,7 @@ class WrapHashably:\n# On that benchmark, including this caching makes a ~10x difference (which can\n# be made arbitrary large by involving larger functions to be traced).\n@weakref_lru_cache\n-def _dyn_args_fun(fun: Callable, static_argnums: Tuple[int, ...],\n+def _dyn_args_fun(fun: Callable, static_argnums: FrozenSet[int],\nstatic_args: Tuple[WrapHashably, ...], nargs: int):\ndef new_fun(*dyn_args, **kwargs):\nstatic_args_, dyn_args_ = iter(static_args), iter(dyn_args)\n"
}
] | Python | Apache License 2.0 | google/jax | in ad_checkpoint WrapHashably.__eq__, check _both_ are hashable
fixes #12063 |
260,510 | 24.08.2022 11:46:51 | 25,200 | 91b1e01f60c9a11421eec9ca60d2533310e7328b | Update to pxla dispatch path to handle ordered effects with a single device | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/mlir.py",
"new_path": "jax/interpreters/mlir.py",
"diff": "@@ -813,19 +813,19 @@ def lower_jaxpr_to_fun(\ntoken_types = [token_type() for _ in effects]\ninput_types = [*token_types, *input_types]\noutput_types = [*output_token_types, *token_types, *output_types]\n- if input_output_aliases:\n+ if input_output_aliases is not None:\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\ninput_output_aliases = [None if a is None else a + num_output_tokens +\nnum_tokens for a in input_output_aliases]\n- if arg_shardings:\n+ if arg_shardings is not None:\ntoken_shardings = [None] * num_tokens\narg_shardings = [*token_shardings, *arg_shardings]\n- if result_shardings:\n+ if result_shardings is not None:\ntoken_shardings = [None] * (num_tokens + num_output_tokens)\nresult_shardings = [*token_shardings, *result_shardings]\n- if replicated_args:\n+ if replicated_args is not None:\ntoken_replicated_args = [False] * num_tokens\nreplicated_args = [*token_replicated_args, *replicated_args]\nflat_input_types = util.flatten(input_types)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1393,10 +1393,13 @@ 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+ ordered_effects = [eff for eff in closed_jaxpr.effects\n+ if eff in core.ordered_effects]\nlowering_result = mlir.lower_jaxpr_to_module(\nmodule_name,\nclosed_jaxpr,\n- unordered_effects, [],\n+ unordered_effects,\n+ ordered_effects,\nbackend,\nbackend.platform,\nmlir.ReplicaAxisContext(axis_env),\n@@ -1411,6 +1414,7 @@ def lower_parallel_callable(\nreturn PmapComputation(module, pci=pci, replicas=replicas, parts=parts,\nshards=shards, tuple_args=tuple_args,\nunordered_effects=unordered_effects,\n+ ordered_effects=ordered_effects,\nkeepalive=keepalive, host_callbacks=host_callbacks)\n@@ -1465,6 +1469,7 @@ class PmapExecutable(stages.XlaExecutable):\nshards: ShardInfo,\ntuple_args: bool,\nunordered_effects: List[core.Effect],\n+ ordered_effects: List[core.Effect],\nhost_callbacks: List[Any],\nkeepalive: Any):\ndevices = pci.devices\n@@ -1581,7 +1586,8 @@ class PmapExecutable(stages.XlaExecutable):\nhandle_args = InputsHandler(\ncompiled.local_devices(), in_shardings, input_indices, InputsHandlerMode.pmap)\nexecute_fun = ExecuteReplicated(compiled, pci.backend, handle_args,\n- handle_outs, unordered_effects, keepalive,\n+ handle_outs, unordered_effects,\n+ ordered_effects, keepalive,\nbool(host_callbacks))\nfingerprint = getattr(compiled, \"fingerprint\", None)\n@@ -1939,41 +1945,65 @@ def partitioned_sharding_spec(num_partitions: int,\nclass ExecuteReplicated:\n\"\"\"The logic to shard inputs, execute a replicated model, returning outputs.\"\"\"\n__slots__ = ['xla_executable', 'backend', 'in_handler', 'out_handler',\n- 'has_unordered_effects', 'keepalive', 'has_host_callbacks',\n- '__weakref__']\n+ 'has_unordered_effects', 'ordered_effects', 'keepalive',\n+ 'has_host_callbacks', '_local_devices', '__weakref__']\ndef __init__(self, xla_executable, backend, in_handler: InputsHandler,\nout_handler: ResultsHandler,\n- unordered_effects: List[core.Effect], keepalive: Any,\n+ unordered_effects: List[core.Effect],\n+ ordered_effects: List[core.Effect], keepalive: Any,\nhas_host_callbacks: bool):\nself.xla_executable = xla_executable\nself.backend = backend\nself.in_handler = in_handler\nself.out_handler = out_handler\nself.has_unordered_effects = bool(unordered_effects)\n+ self.ordered_effects = ordered_effects\n+ self._local_devices = self.xla_executable.local_devices()\n+ if ordered_effects:\n+ assert len(self._local_devices) == 1\nself.keepalive = keepalive\nself.has_host_callbacks = has_host_callbacks\n- @profiler.annotate_function\n- def __call__(self, *args):\n- input_bufs = self.in_handler(args)\n- if self.has_unordered_effects or self.has_host_callbacks:\n+ def _call_with_tokens(self, input_bufs):\n# TODO(sharadmv): simplify this logic when minimum jaxlib version is\n# bumped\n+ if self.ordered_effects:\n+ device, = self._local_devices\n+ tokens = [list(dispatch.runtime_tokens.get_token(eff, device))\n+ for eff in self.ordered_effects]\n+ input_bufs = [*tokens, *input_bufs]\n+ num_output_tokens = len(self.ordered_effects) + (\n+ not can_execute_with_token and self.has_unordered_effects)\nif can_execute_with_token:\nout_bufs, sharded_token = (\nself.xla_executable.execute_sharded_on_local_devices_with_tokens(\ninput_bufs))\n- for i, device in enumerate(self.xla_executable.local_devices()):\n+ token_bufs, out_bufs = util.split_list(out_bufs, [num_output_tokens])\n+ for i, device in enumerate(self._local_devices):\ndispatch.runtime_tokens.set_output_runtime_token(\ndevice, sharded_token.get_token(i))\n+ for eff, token_buf in zip(self.ordered_effects, token_bufs):\n+ dispatch.runtime_tokens.update_token(eff, token_buf)\nelse:\nout_bufs = self.xla_executable.execute_sharded_on_local_devices(\ninput_bufs)\n- token_bufs, *out_bufs = out_bufs\n- for i, device in enumerate(self.xla_executable.local_devices()):\n- token = (token_bufs[i],)\n+ token_bufs, out_bufs = util.split_list(out_bufs, [num_output_tokens])\n+ if self.has_unordered_effects:\n+ unordered_token_buf, *token_bufs = token_bufs\n+ for i, device in enumerate(self._local_devices):\n+ token = (unordered_token_buf[i],)\ndispatch.runtime_tokens.set_output_token(device, token)\n+ for eff, token_buf in zip(self.ordered_effects, token_bufs):\n+ dispatch.runtime_tokens.update_token(eff, token_buf)\n+ return out_bufs\n+\n+ @profiler.annotate_function\n+ def __call__(self, *args):\n+ input_bufs = self.in_handler(args)\n+ if (self.ordered_effects or self.has_unordered_effects or\n+ self.has_host_callbacks):\n+ out_bufs = self._call_with_tokens(input_bufs)\nelse:\nout_bufs = self.xla_executable.execute_sharded_on_local_devices(\ninput_bufs)\n@@ -2676,10 +2706,12 @@ def lower_sharding_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+ ordered_effects = [eff for eff in closed_jaxpr.effects\n+ if eff in core.ordered_effects]\nlowering_result = mlir.lower_jaxpr_to_module(\nmodule_name,\nclosed_jaxpr,\n- unordered_effects, [],\n+ unordered_effects, ordered_effects,\nbackend,\nbackend.platform,\naxis_ctx,\n@@ -2706,6 +2738,7 @@ def lower_sharding_computation(\nin_is_global=in_is_global,\nauto_spmd_lowering=False,\nunordered_effects=unordered_effects,\n+ ordered_effects=ordered_effects,\nhost_callbacks=host_callbacks,\nkeepalive=keepalive)\n@@ -2821,10 +2854,13 @@ 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+ ordered_effects = [eff for eff in closed_jaxpr.effects\n+ if eff in core.ordered_effects]\nlowering_result = mlir.lower_jaxpr_to_module(\nmodule_name,\nclosed_jaxpr,\n- unordered_effects, [],\n+ unordered_effects,\n+ ordered_effects,\nbackend,\nbackend.platform,\naxis_ctx,\n@@ -2850,6 +2886,7 @@ def lower_mesh_computation(\nin_is_global=in_is_global,\nauto_spmd_lowering=auto_spmd_lowering,\nunordered_effects=unordered_effects,\n+ ordered_effects=ordered_effects,\nhost_callbacks=host_callbacks,\nkeepalive=keepalive)\n@@ -2990,6 +3027,7 @@ class MeshExecutable(stages.XlaExecutable):\n_allow_propagation_to_outputs: bool,\n_allow_compile_replicated: bool,\nunordered_effects: List[core.Effect],\n+ ordered_effects: List[core.Effect],\nhost_callbacks: List[Any],\nkeepalive: Any) -> MeshExecutable:\nif auto_spmd_lowering:\n@@ -3067,7 +3105,8 @@ class MeshExecutable(stages.XlaExecutable):\nhandle_args = InputsHandler(xla_executable.local_devices(), in_shardings,\ninput_indices, InputsHandlerMode.pjit_or_xmap)\nunsafe_call = ExecuteReplicated(xla_executable, backend, handle_args,\n- handle_outs, unordered_effects, keepalive,\n+ handle_outs, unordered_effects,\n+ ordered_effects, keepalive,\nbool(host_callbacks))\nreturn MeshExecutable(xla_executable, unsafe_call, input_avals,\n"
}
] | Python | Apache License 2.0 | google/jax | Update to pxla dispatch path to handle ordered effects with a single device
PiperOrigin-RevId: 469785153 |
260,310 | 25.08.2022 11:15:03 | 25,200 | 28b14b1242d0e5cc31172ebdd5b8ee87ea2d49c1 | Fix jax2tf GDA bug. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -55,9 +55,11 @@ from jax._src.lax import windowed_reductions as lax_windowed_reductions\nfrom jax._src import lib as jaxlib\nfrom jax._src.lib import xla_client\n+from jax.experimental.global_device_array import GlobalDeviceArray\nfrom jax.experimental.jax2tf import shape_poly\nfrom jax.experimental.jax2tf import impl_no_xla\n+\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n@@ -816,6 +818,16 @@ def _to_jax_dtype(tf_dtype):\nreturn dtypes.canonicalize_dtype(tf_dtype.as_numpy_dtype)\n+def _maybe_decode_gda(gda_or_py_object: Any):\n+ \"\"\"Convert GlobalDeviceArray into numpy object.\"\"\"\n+ if jax.process_count() != 1:\n+ raise RuntimeError(\"GlobalDeviceArray does not support multi-process\"\n+ f\" currently. Process num = {jax.process_count()}\")\n+ if isinstance(gda_or_py_object, GlobalDeviceArray):\n+ return gda_or_py_object._value\n+ return gda_or_py_object\n+\n+\ndef _tfval_to_tensor_jax_dtype(val: TfVal,\njax_dtype: Optional[DType] = None,\nmemoize_constants=False) -> Tuple[TfVal, DType]:\n@@ -862,7 +874,8 @@ def _tfval_to_tensor_jax_dtype(val: TfVal,\n# The float0 type is not known to TF.\nif jax_dtype == dtypes.float0:\nval = np.zeros(np.shape(val), conversion_dtype.as_numpy_dtype)\n- tf_val = tf.convert_to_tensor(val, dtype=conversion_dtype)\n+ tf_val = tf.convert_to_tensor(\n+ _maybe_decode_gda(val), dtype=conversion_dtype)\nif do_memoize:\n_thread_local_state.constant_cache[const_key] = (val, tf_val)\nreturn tf_val, jax_dtype\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "\"\"\"Tests for JAX2TF converted.\nSpecific JAX primitive conversion tests are in primitives_test.\"\"\"\n-\n-import unittest\n+import collections\n+import os\nfrom typing import Callable, Dict, Optional, Tuple\n+import unittest\nfrom absl import logging\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n-from collections import OrderedDict\n-import os\n-\nimport jax\nfrom jax import ad_checkpoint\nfrom jax import dtypes\nfrom jax import lax\nfrom jax import numpy as jnp\n+from jax._src import lib as jaxlib\n+from jax._src import source_info_util\nfrom jax._src import test_util as jtu\n+import jax._src.lib.xla_bridge\nfrom jax.config import config\nfrom jax.experimental import jax2tf\n+from jax.experimental.global_device_array import GlobalDeviceArray\nfrom jax.experimental.jax2tf.tests import tf_test_util\n-import jax.interpreters.mlir as mlir\n-from jax._src import source_info_util\n-from jax._src import lib as jaxlib\n-import jax._src.lib.xla_bridge\n-\n+from jax.experimental.pjit import FROM_GDA\n+from jax.experimental.pjit import pjit\n+from jax.interpreters import mlir\n+from jax.interpreters.pxla import PartitionSpec as P\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n# pylint: disable=g-direct-tensorflow-import\n@@ -370,7 +371,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ndefault_float_type = jax2tf.dtype_of_val(4.)\nx = tf.Variable([4.], dtype=default_float_type)\ny = tf.Variable([4., 5.], dtype=default_float_type)\n- inputs = OrderedDict()\n+ inputs = collections.OrderedDict()\ninputs['r'] = x\ninputs['d'] = y\nwith tf.GradientTape(persistent=True) as tape:\n@@ -1323,12 +1324,44 @@ class XlaCallModuleTest(tf_test_util.JaxToTfTestCase):\ndim_args_spec=('0.0',))\nres = tf.function(f_tf, jit_compile=True, autograph=False)(x1)\n- self.assertAllClose(tf.nest.map_structure(lambda t: t.numpy(), res),\n- jax_res)\n+ self.assertAllClose(\n+ tf.nest.map_structure(lambda t: t.numpy(), res), jax_res)\n+\n+ def test_global_device_array(self):\n+\n+ def create_gda(global_shape, global_mesh, mesh_axes, global_data=None):\n+ if global_data is None:\n+ global_data = np.arange(np.prod(global_shape)).reshape(global_shape)\n+ return GlobalDeviceArray.from_callback(\n+ global_shape, global_mesh, mesh_axes,\n+ lambda idx: global_data[idx]), global_data\n+\n+ # Create GDA\n+ global_mesh = jtu.create_global_mesh((4, 2), (\"x\", \"y\"))\n+ mesh_axes = P((\"x\", \"y\"))\n+ params, _ = create_gda((8, 2), global_mesh, mesh_axes)\n+\n+ def jax_func(input_data):\n+ handle = pjit(\n+ jnp.matmul,\n+ in_axis_resources=(P(\"y\", \"x\"), FROM_GDA),\n+ out_axis_resources=None)\n+ return handle(input_data, params)\n+\n+ with global_mesh:\n+ tf_func = tf.function(\n+ jax2tf.convert(jax_func, enable_xla=True),\n+ jit_compile=True,\n+ )\n+ input_data = np.arange(16).reshape(2, 8)\n+ jax_out = jax_func(input_data=input_data)\n+ tf_out = tf_func(input_data=input_data)\n+ # TODO(b/243146552) We can switch to ConvertAndCompare after this bug fix.\n+ np.array_equal(jax_out._value, np.array(tf_out))\nif __name__ == \"__main__\":\n# TODO: Remove once tensorflow is 2.10.0 everywhere.\n- if not hasattr(tfxla, 'optimization_barrier'):\n- jax.config.update('jax_remat_opt_barrier', False)\n+ if not hasattr(tfxla, \"optimization_barrier\"):\n+ jax.config.update(\"jax_remat_opt_barrier\", False)\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Fix jax2tf GDA bug.
PiperOrigin-RevId: 470036308 |
260,510 | 25.08.2022 10:25:05 | 25,200 | 260f1d8b843483df46cf397ae5a1afc0abc9c64f | Add option to generate perfetto trace without generating link | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/profiler.py",
"new_path": "jax/_src/profiler.py",
"diff": "@@ -72,12 +72,14 @@ class _ProfileState:\nself.profile_session = None\nself.log_dir = None\nself.create_perfetto_link = False\n+ self.create_perfetto_trace = False\nself.lock = threading.Lock()\n_profile_state = _ProfileState()\n-def start_trace(log_dir, create_perfetto_link: bool = False):\n+def start_trace(log_dir, create_perfetto_link: bool = False,\n+ create_perfetto_trace: bool = False):\n\"\"\"Starts a profiler trace.\nThe trace will capture CPU, GPU, and/or TPU activity, including Python\n@@ -96,6 +98,12 @@ def start_trace(log_dir, create_perfetto_link: bool = False):\ncreate_perfetto_link: A boolean which, if true, creates and prints link to\nthe Perfetto trace viewer UI (https://ui.perfetto.dev). The program will\nblock until the link is opened and Perfetto loads the trace.\n+ create_perfetto_trace: A boolean which, if true, additionally dumps a\n+ ``perfetto_trace.json.gz`` file that is compatible for upload with the\n+ Perfetto trace viewer UI (https://ui.perfetto.dev). The file will also be\n+ generated if ``create_perfetto_link`` is true. This could be useful if you\n+ want to generate a Perfetto-compatible trace without blocking the\n+ processs.\n\"\"\"\nwith _profile_state.lock:\nif _profile_state.profile_session is not None:\n@@ -109,8 +117,11 @@ def start_trace(log_dir, create_perfetto_link: bool = False):\n_profile_state.profile_session = xla_client.profiler.ProfilerSession()\n_profile_state.create_perfetto_link = create_perfetto_link\n+ _profile_state.create_perfetto_trace = (\n+ create_perfetto_trace or create_perfetto_link)\n_profile_state.log_dir = log_dir\n+\ndef _write_perfetto_trace_file(log_dir):\n# Navigate to folder with the latest trace dump to find `trace.json.jz`\ncurr_path = os.path.abspath(log_dir)\n@@ -152,13 +163,12 @@ class _PerfettoServer(http.server.SimpleHTTPRequestHandler):\ndef do_POST(self):\nself.send_error(404, \"File not found\")\n-def _host_perfetto_trace_file(log_dir):\n+def _host_perfetto_trace_file(path):\n# ui.perfetto.dev looks for files hosted on `127.0.0.1:9001`. We set up a\n# TCP server that is hosting the `perfetto_trace.json.gz` file.\nport = 9001\n- abs_filename = _write_perfetto_trace_file(log_dir)\norig_directory = os.path.abspath(os.getcwd())\n- directory, filename = os.path.split(abs_filename)\n+ directory, filename = os.path.split(path)\ntry:\nos.chdir(directory)\nsocketserver.TCPServer.allow_reuse_address = True\n@@ -183,15 +193,18 @@ def stop_trace():\nif _profile_state.profile_session is None:\nraise RuntimeError(\"No profile started\")\n_profile_state.profile_session.stop_and_export(_profile_state.log_dir)\n+ if _profile_state.create_perfetto_trace:\n+ abs_filename = _write_perfetto_trace_file(_profile_state.log_dir)\nif _profile_state.create_perfetto_link:\n- _host_perfetto_trace_file(_profile_state.log_dir)\n+ _host_perfetto_trace_file(abs_filename)\n_profile_state.profile_session = None\n_profile_state.create_perfetto_link = False\n+ _profile_state.create_perfetto_trace = False\n_profile_state.log_dir = None\n@contextmanager\n-def trace(log_dir, create_perfetto_link=False):\n+def trace(log_dir, create_perfetto_link=False, create_perfetto_trace=False):\n\"\"\"Context manager to take a profiler trace.\nThe trace will capture CPU, GPU, and/or TPU activity, including Python\n@@ -209,8 +222,14 @@ def trace(log_dir, create_perfetto_link=False):\ncreate_perfetto_link: A boolean which, if true, creates and prints link to\nthe Perfetto trace viewer UI (https://ui.perfetto.dev). The program will\nblock until the link is opened and Perfetto loads the trace.\n+ create_perfetto_trace: A boolean which, if true, additionally dumps a\n+ ``perfetto_trace.json.gz`` file that is compatible for upload with the\n+ Perfetto trace viewer UI (https://ui.perfetto.dev). The file will also be\n+ generated if ``create_perfetto_link`` is true. This could be useful if you\n+ want to generate a Perfetto-compatible trace without blocking the\n+ processs.\n\"\"\"\n- start_trace(log_dir, create_perfetto_link)\n+ start_trace(log_dir, create_perfetto_link, create_perfetto_trace)\ntry:\nyield\nfinally:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/collect_profile.py",
"new_path": "jax/collect_profile.py",
"diff": "@@ -90,13 +90,14 @@ def collect_profile(port: int, duration_in_ms: int, host: str,\nin root_trace_folder.iterdir()]\nlatest_folder = max(trace_folders, key=os.path.getmtime)\nxplane = next(latest_folder.glob(\"*.xplane.pb\"))\n- result = convert.xspace_to_tool_data([xplane], \"trace_viewer^\", None)\n+ result, _ = convert.xspace_to_tool_data([xplane], \"trace_viewer^\", {})\nwith gzip.open(str(latest_folder / \"remote.trace.json.gz\"), \"wb\") as fp:\nfp.write(result.encode(\"utf-8\"))\nif not no_perfetto_link:\n- jax._src.profiler._host_perfetto_trace_file(str(log_dir_))\n+ path = jax._src.profiler._write_perfetto_trace_file(str(log_dir_))\n+ jax._src.profiler._host_perfetto_trace_file(path)\ndef main(args):\ncollect_profile(args.port, args.duration_in_ms, args.host, args.log_dir,\n"
}
] | Python | Apache License 2.0 | google/jax | Add option to generate perfetto trace without generating link |
260,631 | 25.08.2022 15:14:01 | 25,200 | cc8d406bdbf4dc782a2d9e05ea08e56360887be8 | Copybara import of the project:
by Jake VanderPlas
generate lax.slice instead of lax.gather for more indexing cases | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -77,8 +77,8 @@ from jax._src.numpy.util import ( # noqa: F401\n_register_stackable, _stackable, _where, _wraps)\nfrom jax._src.numpy.vectorize import vectorize\nfrom jax._src.ops import scatter\n-from jax._src.util import (unzip2, unzip3, prod as _prod, subvals, safe_zip,\n- ceil_of_ratio, canonicalize_axis as _canonicalize_axis)\n+from jax._src.util import (unzip2, prod as _prod, subvals, safe_zip, ceil_of_ratio,\n+ canonicalize_axis as _canonicalize_axis)\nfrom jax.experimental.array import Array\nnewaxis = None\n@@ -3587,50 +3587,30 @@ def take_along_axis(arr, indices, axis: Optional[int],\n### Indexing\n-def _is_integer_index(idx: Any) -> bool:\n- return isinstance(idx, (int, np.integer)) and not isinstance(idx, (bool, np.bool_))\n-\n-def _is_inbound_integer_index(idx: Any, size: int) -> bool:\n- return _is_integer_index(idx) and -size <= idx < size\n-\n-def _is_nonreversing_static_slice(idx: Any) -> bool:\n- return (isinstance(idx, slice) and\n- _all(i is None or _is_integer_index(i)\n- for i in [idx.start, idx.stop, idx.step]) and\n- (idx.step is None or idx.step > 0))\n-\n-def _attempt_rewriting_take_via_slice(arr, idx):\n- # attempt to compute _rewriting_take via lax.slice(); return None if not possible.\n- idx = idx if isinstance(idx, tuple) else (idx,)\n- if not _all(isinstance(i, int) for i in arr.shape):\n- return None\n- if len(idx) > arr.ndim:\n- return None\n- if not _all(_is_inbound_integer_index(i, size) or _is_nonreversing_static_slice(i)\n- for i, size in zip(idx, arr.shape)):\n- return None\n- sqeeze_dimensions = [i for i, ind in enumerate(idx) if not isinstance(ind, slice)]\n- idx += (arr.ndim - len(idx)) * (slice(None),)\n- slices = []\n- for ind, size in safe_zip(idx, arr.shape):\n- if isinstance(ind, slice):\n- slices.append(ind.indices(size))\n- else:\n- ind = ind + size if ind < 0 else ind\n- slices.append((ind, ind + 1, 1))\n- return lax.squeeze(lax.slice(arr, *unzip3(slices)), sqeeze_dimensions)\n-\ndef _rewriting_take(arr, idx, indices_are_sorted=False, unique_indices=False,\nmode=None, fill_value=None):\n# Computes arr[idx].\n# All supported cases of indexing can be implemented as an XLA gather,\n# followed by an optional reverse and broadcast_in_dim.\n- # For simplicity of generated primitives, we call lax.slice in the simplest\n- # cases: i.e. non-dynamic arrays indexed with only integers and slices.\n- result = _attempt_rewriting_take_via_slice(arr, idx)\n- if result is not None:\n- return result\n+ # Handle some special cases, falling back if error messages might differ.\n+ if (arr.ndim > 0 and isinstance(idx, (int, np.integer)) and\n+ not isinstance(idx, (bool, np.bool_)) and isinstance(arr.shape[0], int)):\n+ if 0 <= idx < arr.shape[0]:\n+ return lax.index_in_dim(arr, idx, keepdims=False)\n+ if (arr.ndim > 0 and isinstance(arr.shape[0], int) and\n+ isinstance(idx, slice) and\n+ (type(idx.start) is int or idx.start is None) and\n+ (type(idx.stop) is int or idx.stop is None) and\n+ (type(idx.step) is int or idx.step is None)):\n+ n = arr.shape[0]\n+ start = idx.start if idx.start is not None else 0\n+ stop = idx.stop if idx.stop is not None else n\n+ step = idx.step if idx.step is not None else 1\n+ if (0 <= start < n and 0 <= stop <= n and 0 < step and\n+ (start, stop, step) != (0, n, 1)):\n+ return lax.slice_in_dim(arr, start, stop, step)\n+\n# TODO(mattjj,dougalm): expand dynamic shape indexing support\nif (jax.config.jax_dynamic_shapes and type(idx) is slice and idx.step is None\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_indexing_test.py",
"new_path": "tests/lax_numpy_indexing_test.py",
"diff": "@@ -860,30 +860,6 @@ class IndexingTest(jtu.JaxTestCase):\nself.assertAllClose(expected, primals)\nself.assertAllClose(np.zeros_like(x), tangents)\n- def testSimpleIndexingUsesSlice(self):\n- jaxpr = jax.make_jaxpr(lambda x: x[:2, :2])(jnp.ones((3, 4)))\n- self.assertEqual(len(jaxpr.jaxpr.eqns), 1)\n- self.assertEqual(jaxpr.jaxpr.eqns[0].primitive, lax.slice_p)\n-\n- jaxpr = jax.make_jaxpr(lambda x: x[:, 1::2])(jnp.ones((3, 4)))\n- self.assertEqual(len(jaxpr.jaxpr.eqns), 1)\n- self.assertEqual(jaxpr.jaxpr.eqns[0].primitive, lax.slice_p)\n-\n- jaxpr = jax.make_jaxpr(lambda x: x[0, :2, 1])(jnp.ones((3, 4, 5)))\n- self.assertEqual(len(jaxpr.jaxpr.eqns), 2)\n- self.assertEqual(jaxpr.jaxpr.eqns[0].primitive, lax.slice_p)\n- self.assertEqual(jaxpr.jaxpr.eqns[1].primitive, lax.squeeze_p)\n-\n- jaxpr = jax.make_jaxpr(lambda x: x[0, 0])(jnp.ones((3, 4, 5)))\n- self.assertEqual(len(jaxpr.jaxpr.eqns), 2)\n- self.assertEqual(jaxpr.jaxpr.eqns[0].primitive, lax.slice_p)\n- self.assertEqual(jaxpr.jaxpr.eqns[1].primitive, lax.squeeze_p)\n-\n- jaxpr = jax.make_jaxpr(lambda x: x[:, 1])(jnp.ones((3, 4, 5)))\n- self.assertEqual(len(jaxpr.jaxpr.eqns), 2)\n- self.assertEqual(jaxpr.jaxpr.eqns[0].primitive, lax.slice_p)\n- self.assertEqual(jaxpr.jaxpr.eqns[1].primitive, lax.squeeze_p)\n-\ndef testTrivialGatherIsntGenerated(self):\n# https://github.com/google/jax/issues/1621\njaxpr = jax.make_jaxpr(lambda x: x[:, None])(np.arange(4))\n@@ -891,12 +867,9 @@ class IndexingTest(jtu.JaxTestCase):\nself.assertNotIn('gather', str(jaxpr))\njaxpr = jax.make_jaxpr(lambda x: x[0:6:1])(np.arange(4))\n- self.assertEqual(len(jaxpr.jaxpr.eqns), 1)\n- self.assertEqual(jaxpr.jaxpr.eqns[0].primitive, lax.slice_p)\n-\n+ self.assertEqual(len(jaxpr.jaxpr.eqns), 0)\njaxpr = jax.make_jaxpr(lambda x: x[:4])(np.arange(4))\n- self.assertEqual(len(jaxpr.jaxpr.eqns), 1)\n- self.assertEqual(jaxpr.jaxpr.eqns[0].primitive, lax.slice_p)\n+ self.assertEqual(len(jaxpr.jaxpr.eqns), 0)\njaxpr = jax.make_jaxpr(lambda x: x[::-1])(np.arange(4))\nself.assertEqual(len(jaxpr.jaxpr.eqns), 1)\n"
}
] | Python | Apache License 2.0 | google/jax | Copybara import of the project:
--
d5ee729a7f5d583c8e212c6a9f1b98221b13cbdc by Jake VanderPlas <jakevdp@google.com>:
generate lax.slice instead of lax.gather for more indexing cases
PiperOrigin-RevId: 470094833 |
260,332 | 25.08.2022 15:27:07 | 25,200 | 4b1a2eaaec5a48846b3ba50c140bf721b5d180e6 | combine gpu tests | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/slurm_job_scripts/multinode_pytest.sub",
"new_path": ".github/workflows/slurm_job_scripts/multinode_pytest.sub",
"diff": "@@ -33,6 +33,7 @@ read -r -d '' setup_cmd <<EOF\npython3.8 -m pip install --pre jaxlib -f https://storage.googleapis.com/jax-releases/jaxlib_nightly_cuda_releases.html \\\n&& python3.8 -m pip install git+https://github.com/google/jax \\\n&& python3.8 -m pip install pytest \\\n+&& python3.8 -m pip install pytest-forked \\\n&& mkdir -p /workspace/outputs/\nEOF\n@@ -40,9 +41,9 @@ EOF\nread -r -d '' cmd <<EOF\ndate \\\n&& python3.8 -m pip list | grep jax \\\n-&& python3.8 -m pytest -v -s --continue-on-collection-errors \\\n+&& python3.8 -m pytest --forked -v -s --continue-on-collection-errors \\\n--junit-xml=/workspace/outputs/junit_output_\\${SLURM_PROCID}.xml \\\n- /workspace/tests/distributed_multinode_test.py\n+ /workspace/tests/multiprocess_gpu_test.py\nEOF\n# create run specific output directory for ease of analysis\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -90,17 +90,8 @@ py_test(\n)\npy_test(\n- name = \"distributed_multinode_test\",\n- srcs = [\"distributed_multinode_test.py\"],\n- deps = [\n- \"//jax\",\n- \"//jax:test_util\",\n- ],\n-)\n-\n-py_test(\n- name = \"distributed_test\",\n- srcs = [\"distributed_test.py\"],\n+ name = \"multiprocess_gpu_test\",\n+ srcs = [\"multiprocess_gpu_test.py\"],\nargs = [\n\"--exclude_test_targets=MultiProcessGpuTest\",\n],\n"
},
{
"change_type": "DELETE",
"old_path": "tests/distributed_multinode_test.py",
"new_path": null,
"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-\n-import os\n-import unittest\n-\n-from absl.testing import absltest\n-\n-import jax\n-import jax._src.lib\n-from jax._src import test_util as jtu\n-import jax.numpy as jnp\n-\n-@unittest.skipIf(\n- os.environ.get(\"SLURM_JOB_NUM_NODES\", None) != \"2\",\n- \"Slurm environment with at least two nodes needed!\")\n-class MultiNodeGpuTest(jtu.JaxTestCase):\n-\n- def test_gpu_multi_node_initialize_and_psum(self):\n-\n- # Hookup the ENV vars expected to be set already in the SLURM environment\n- nodelist = os.environ.get(\"SLURM_STEP_NODELIST\", None)\n- if nodelist is not None:\n- coordinator_address = nodelist.split('[')[0] + \\\n- nodelist.split('[')[1].split(',')[0]\n- num_tasks = os.environ.get(\"SLURM_NPROCS\", None)\n- taskid = os.environ.get(\"SLURM_PROCID\", None)\n- localid = os.environ.get(\"SLURM_LOCALID\", None)\n-\n- # fixing port since it needs to be the same for all the processes\n- port = \"54321\"\n-\n- print(f\"coord addr:port : {coordinator_address}:{port}\\nTotal tasks: \"\n- f\"{num_tasks}\\ntask id: {taskid}\\nlocal id: {localid}\")\n-\n- self.assertEqual(\n- coordinator_address is None or num_tasks is None or taskid is None,\n- False)\n-\n- jax.distributed.initialize(coordinator_address=f'{coordinator_address}:{port}',\n- num_processes=int(num_tasks),\n- process_id=int(taskid))\n-\n- print(f\"Total devices: {jax.device_count()}, Total tasks: {int(num_tasks)}, \"\n- f\"Devices per task: {jax.local_device_count()}\")\n-\n- self.assertEqual(jax.device_count(),\n- int(num_tasks) * jax.local_device_count())\n-\n- x = jnp.ones(jax.local_device_count())\n- y = jax.pmap(lambda x: jax.lax.psum(x, \"i\"), axis_name=\"i\")(x)\n- self.assertEqual(y[0], jax.device_count())\n- print(y)\n-\n-if __name__ == \"__main__\":\n- absltest.main(testLoader=jtu.JaxTestLoader())\n"
},
{
"change_type": "RENAME",
"old_path": "tests/distributed_test.py",
"new_path": "tests/multiprocess_gpu_test.py",
"diff": "@@ -24,6 +24,7 @@ from absl.testing import parameterized\nimport jax\nfrom jax.config import config\nfrom jax._src import distributed\n+import jax.numpy as jnp\nfrom jax._src.lib import xla_extension_version\nfrom jax._src import test_util as jtu\n@@ -146,5 +147,46 @@ class MultiProcessGpuTest(jtu.JaxTestCase):\nself.assertEqual(proc.returncode, 0)\nself.assertEqual(out, f'{num_gpus_per_task},{num_gpus}')\n+@unittest.skipIf(\n+ os.environ.get(\"SLURM_JOB_NUM_NODES\", None) != \"2\",\n+ \"Slurm environment with at least two nodes needed!\")\n+class MultiNodeGpuTest(jtu.JaxTestCase):\n+\n+ def test_gpu_multi_node_initialize_and_psum(self):\n+\n+ # Hookup the ENV vars expected to be set already in the SLURM environment\n+ nodelist = os.environ.get(\"SLURM_STEP_NODELIST\", None)\n+ if nodelist is not None:\n+ coordinator_address = nodelist.split('[')[0] + \\\n+ nodelist.split('[')[1].split(',')[0]\n+ num_tasks = os.environ.get(\"SLURM_NPROCS\", None)\n+ taskid = os.environ.get(\"SLURM_PROCID\", None)\n+ localid = os.environ.get(\"SLURM_LOCALID\", None)\n+\n+ # fixing port since it needs to be the same for all the processes\n+ port = \"54321\"\n+\n+ print(f\"coord addr:port : {coordinator_address}:{port}\\nTotal tasks: \"\n+ f\"{num_tasks}\\ntask id: {taskid}\\nlocal id: {localid}\")\n+\n+ self.assertEqual(\n+ coordinator_address is None or num_tasks is None or taskid is None,\n+ False)\n+\n+ jax.distributed.initialize(coordinator_address=f'{coordinator_address}:{port}',\n+ num_processes=int(num_tasks),\n+ process_id=int(taskid))\n+\n+ print(f\"Total devices: {jax.device_count()}, Total tasks: {int(num_tasks)}, \"\n+ f\"Devices per task: {jax.local_device_count()}\")\n+\n+ self.assertEqual(jax.device_count(),\n+ int(num_tasks) * jax.local_device_count())\n+\n+ x = jnp.ones(jax.local_device_count())\n+ y = jax.pmap(lambda x: jax.lax.psum(x, \"i\"), axis_name=\"i\")(x)\n+ self.assertEqual(y[0], jax.device_count())\n+ print(y)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | combine gpu tests |
260,403 | 26.08.2022 00:24:55 | 25,200 | 3c9178745ba0300f66626603bb2e4e0eab8b914a | Add runtime type check in named_scope to ensure that name is a string. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -3180,6 +3180,8 @@ def named_scope(\n... logits = w.dot(x)\n... return jax.nn.relu(logits)\n\"\"\"\n+ if not isinstance(name, str):\n+ raise ValueError(\"named_scope name argument must be a string.\")\nwith source_info_util.extend_name_stack(name):\nyield\n"
}
] | Python | Apache License 2.0 | google/jax | Add runtime type check in named_scope to ensure that name is a string.
PiperOrigin-RevId: 470177071 |
260,689 | 26.08.2022 11:37:04 | -7,200 | 024ae47e79cd7855cd02e573d5569c9d951411cd | Switch from pocketfft to ducc
All credit goes to Martin Reinecke | [
{
"change_type": "MODIFY",
"old_path": "build/LICENSE.txt",
"new_path": "build/LICENSE.txt",
"diff": "@@ -4332,8 +4332,8 @@ Copyright 2019 The TensorFlow Authors. All rights reserved.\nlimitations under the License.\n--------------------------------------------------------------------------------\n-License for pocketfft:\n-Copyright (C) 2010-2018 Max-Planck-Society\n+License for the FFT components of ducc0:\n+Copyright (C) 2010-2022 Max-Planck-Society\nAll rights reserved.\nRedistribution and use in source and binary forms, with or without modification,\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/pocketfft_kernels.cc",
"new_path": "jaxlib/pocketfft_kernels.cc",
"diff": "@@ -16,72 +16,104 @@ limitations under the License.\n#include <complex>\n#include \"flatbuffers/flatbuffers.h\"\n-#include \"pocketfft/pocketfft_hdronly.h\"\n#include \"jaxlib/pocketfft_generated.h\"\n+#include \"pocketfft/src/ducc0/fft/fft.h\"\n#include \"tensorflow/compiler/xla/service/custom_call_status.h\"\nnamespace jax {\n+using shape_t = ducc0::fmav_info::shape_t;\n+using stride_t = ducc0::fmav_info::stride_t;\n+\n+void fixstrides(stride_t &str, size_t size) {\n+ ptrdiff_t ssize = ptrdiff_t(size);\n+ for (auto &s : str) {\n+ auto tmp = s / ssize;\n+ if (tmp * ssize != s)\n+ throw \"Bad stride\";\n+ s = tmp;\n+ }\n+}\n+\nvoid PocketFft(void *out, void **in, XlaCustomCallStatus *) {\nconst PocketFftDescriptor *descriptor = GetPocketFftDescriptor(in[0]);\n- pocketfft::shape_t shape(descriptor->shape()->begin(),\n- descriptor->shape()->end());\n- pocketfft::stride_t stride_in(descriptor->strides_in()->begin(),\n+ shape_t shape(descriptor->shape()->begin(), descriptor->shape()->end());\n+ stride_t stride_in(descriptor->strides_in()->begin(),\ndescriptor->strides_in()->end());\n- pocketfft::stride_t stride_out(descriptor->strides_out()->begin(),\n+ stride_t stride_out(descriptor->strides_out()->begin(),\ndescriptor->strides_out()->end());\n- pocketfft::shape_t axes(descriptor->axes()->begin(),\n- descriptor->axes()->end());\n+ shape_t axes(descriptor->axes()->begin(), descriptor->axes()->end());\nswitch (descriptor->fft_type()) {\ncase PocketFftType_C2C:\nif (descriptor->dtype() == PocketFftDtype_COMPLEX64) {\n- std::complex<float>* a_in =\n- reinterpret_cast<std::complex<float>*>(in[1]);\n- std::complex<float>* a_out =\n- reinterpret_cast<std::complex<float>*>(out);\n- pocketfft::c2c(shape, stride_in, stride_out, axes,\n- descriptor->forward(), a_in, a_out,\n+ fixstrides(stride_in, sizeof(std::complex<float>));\n+ fixstrides(stride_out, sizeof(std::complex<float>));\n+ ducc0::cfmav<std::complex<float>> m_in(\n+ reinterpret_cast<std::complex<float> *>(in[1]), shape, stride_in);\n+ ducc0::vfmav<std::complex<float>> m_out(\n+ reinterpret_cast<std::complex<float> *>(out), shape, stride_out);\n+ ducc0::c2c(m_in, m_out, axes, descriptor->forward(),\nstatic_cast<float>(descriptor->scale()));\n} else {\n- std::complex<double>* a_in =\n- reinterpret_cast<std::complex<double>*>(in[1]);\n- std::complex<double>* a_out =\n- reinterpret_cast<std::complex<double>*>(out);\n- pocketfft::c2c(shape, stride_in, stride_out, axes,\n- descriptor->forward(), a_in, a_out, descriptor->scale());\n+ fixstrides(stride_in, sizeof(std::complex<double>));\n+ fixstrides(stride_out, sizeof(std::complex<double>));\n+ ducc0::cfmav<std::complex<double>> m_in(\n+ reinterpret_cast<std::complex<double> *>(in[1]), shape, stride_in);\n+ ducc0::vfmav<std::complex<double>> m_out(\n+ reinterpret_cast<std::complex<double> *>(out), shape, stride_out);\n+ ducc0::c2c(m_in, m_out, axes, descriptor->forward(),\n+ static_cast<double>(descriptor->scale()));\n}\nbreak;\ncase PocketFftType_C2R:\nif (descriptor->dtype() == PocketFftDtype_COMPLEX64) {\n- std::complex<float>* a_in =\n- reinterpret_cast<std::complex<float>*>(in[1]);\n- float* a_out = reinterpret_cast<float*>(out);\n- pocketfft::c2r(shape, stride_in, stride_out, axes,\n- descriptor->forward(), a_in, a_out,\n+ fixstrides(stride_in, sizeof(std::complex<float>));\n+ fixstrides(stride_out, sizeof(float));\n+ auto shape_in = shape;\n+ shape_in[axes.back()] = shape_in[axes.back()] / 2 + 1;\n+ ducc0::cfmav<std::complex<float>> m_in(\n+ reinterpret_cast<std::complex<float> *>(in[1]), shape_in, stride_in);\n+ ducc0::vfmav<float> m_out(reinterpret_cast<float *>(out), shape,\n+ stride_out);\n+ ducc0::c2r(m_in, m_out, axes, descriptor->forward(),\nstatic_cast<float>(descriptor->scale()));\n} else {\n- std::complex<double>* a_in =\n- reinterpret_cast<std::complex<double>*>(in[1]);\n- double* a_out = reinterpret_cast<double*>(out);\n- pocketfft::c2r(shape, stride_in, stride_out, axes,\n- descriptor->forward(), a_in, a_out, descriptor->scale());\n+ fixstrides(stride_in, sizeof(std::complex<double>));\n+ fixstrides(stride_out, sizeof(double));\n+ auto shape_in = shape;\n+ shape_in[axes.back()] = shape_in[axes.back()] / 2 + 1;\n+ ducc0::cfmav<std::complex<double>> m_in(\n+ reinterpret_cast<std::complex<double> *>(in[1]), shape_in, stride_in);\n+ ducc0::vfmav<double> m_out(reinterpret_cast<double *>(out), shape,\n+ stride_out);\n+ ducc0::c2r(m_in, m_out, axes, descriptor->forward(),\n+ static_cast<double>(descriptor->scale()));\n}\nbreak;\ncase PocketFftType_R2C:\nif (descriptor->dtype() == PocketFftDtype_COMPLEX64) {\n- float* a_in = reinterpret_cast<float*>(in[1]);\n- std::complex<float>* a_out =\n- reinterpret_cast<std::complex<float>*>(out);\n- pocketfft::r2c(shape, stride_in, stride_out, axes,\n- descriptor->forward(), a_in, a_out,\n+ fixstrides(stride_in, sizeof(float));\n+ fixstrides(stride_out, sizeof(std::complex<float>));\n+ auto shape_out = shape;\n+ shape_out[axes.back()] = shape_out[axes.back()] / 2 + 1;\n+ ducc0::cfmav<float> m_in(reinterpret_cast<float *>(in[1]), shape,\n+ stride_in);\n+ ducc0::vfmav<std::complex<float>> m_out(\n+ reinterpret_cast<std::complex<float> *>(out), shape_out, stride_out);\n+ ducc0::r2c(m_in, m_out, axes, descriptor->forward(),\nstatic_cast<float>(descriptor->scale()));\n} else {\n- double* a_in = reinterpret_cast<double*>(in[1]);\n- std::complex<double>* a_out =\n- reinterpret_cast<std::complex<double>*>(out);\n- pocketfft::r2c(shape, stride_in, stride_out, axes,\n- descriptor->forward(), a_in, a_out, descriptor->scale());\n+ fixstrides(stride_in, sizeof(double));\n+ fixstrides(stride_out, sizeof(std::complex<double>));\n+ auto shape_out = shape;\n+ shape_out[axes.back()] = shape_out[axes.back()] / 2 + 1;\n+ ducc0::cfmav<double> m_in(reinterpret_cast<double *>(in[1]), shape,\n+ stride_in);\n+ ducc0::vfmav<std::complex<double>> m_out(\n+ reinterpret_cast<std::complex<double> *>(out), shape_out, stride_out);\n+ ducc0::r2c(m_in, m_out, axes, descriptor->forward(),\n+ static_cast<double>(descriptor->scale()));\n}\nbreak;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "third_party/pocketfft/BUILD.bazel",
"new_path": "third_party/pocketfft/BUILD.bazel",
"diff": "@@ -4,8 +4,20 @@ package(default_visibility = [\"//visibility:public\"])\ncc_library(\nname = \"pocketfft\",\n- hdrs = [\"pocketfft_hdronly.h\"],\n- copts = [\"-fexceptions\"],\n+ hdrs = [\"src/ducc0/fft/fft.h\"],\n+ srcs = [\"src/ducc0/fft/fft1d.h\",\n+ \"src/ducc0/infra/aligned_array.h\",\n+ \"src/ducc0/infra/error_handling.h\",\n+ \"src/ducc0/infra/mav.h\",\n+ \"src/ducc0/infra/simd.h\",\n+ \"src/ducc0/infra/threading.h\",\n+ \"src/ducc0/infra/threading.cc\",\n+ \"src/ducc0/infra/useful_macros.h\",\n+ \"src/ducc0/math/cmplx.h\",\n+ \"src/ducc0/math/unity_roots.h\",\n+],\n+ copts = [\"-fexceptions\", \"-ffast-math\"],\nfeatures = [\"-use_header_modules\"],\ninclude_prefix = \"pocketfft\",\n+ includes = [\"pocketfft\", \"src\"],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "third_party/pocketfft/workspace.bzl",
"new_path": "third_party/pocketfft/workspace.bzl",
"diff": "@@ -19,11 +19,11 @@ load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\ndef repo():\nhttp_archive(\nname = \"pocketfft\",\n- sha256 = \"66eda977b195965d27aeb9d74f46e0029a6a02e75fbbc47bb554aad68615a260\",\n- strip_prefix = \"pocketfft-f800d91ba695b6e19ae2687dd60366900b928002\",\n+ strip_prefix = \"ducc-356d619a4b5f6f8940d15913c14a043355ef23be\",\n+ sha256 = \"d23eb2d06f03604867ad40af4fe92dec7cccc2c59f5119e9f01b35b973885c61,\nurls = [\n- \"https://github.com/mreineck/pocketfft/archive/f800d91ba695b6e19ae2687dd60366900b928002.tar.gz\",\n- \"https://storage.googleapis.com/jax-releases/mirror/pocketfft/pocketfft-f800d91ba695b6e19ae2687dd60366900b928002.tar.gz\",\n+ \"https://github.com/mreineck/ducc/archive/356d619a4b5f6f8940d15913c14a043355ef23be.tar.gz\",\n+ \"https://storage.googleapis.com/jax-releases/mirror/ducc/ducc-356d619a4b5f6f8940d15913c14a043355ef23be.tar.gz\",\n],\nbuild_file = \"@//third_party/pocketfft:BUILD.bazel\",\n)\n"
}
] | Python | Apache License 2.0 | google/jax | Switch from pocketfft to ducc
All credit goes to Martin Reinecke <martin@mpa-garching.mpg.de>. |
260,332 | 29.08.2022 09:00:19 | 25,200 | a571db18db953ee2af78066fea1111150032f4c1 | Enable one gpu per process in multinode GPU CI | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/slurm_job_scripts/multinode_pytest.sub",
"new_path": ".github/workflows/slurm_job_scripts/multinode_pytest.sub",
"diff": "#SBATCH -J \"ci-jax-gpu\" # job name\n#SBATCH --exclusive # exclusive node access\n#SBATCH --mem=0 # all mem avail\n-#SBATCH --mail-type=FAIL # only send email on failure\n-#SBATCH --ntasks-per-node=1 # 1 tasks per machine for now\n+#SBATCH --mail-type=FAIL # only send email on failures\n#SBATCH --overcommit # Needed for pytorch\nset -x\n@@ -57,6 +56,7 @@ OUTFILE=\"${OUTPUT_DIR}/output-%j-%n.txt\"\n# that the processes are launched together\necho $setup_cmd\nsrun -o $OUTFILE -e $OUTFILE \\\n+ --ntasks-per-node=1 \\\n--container-writable \\\n--container-image=\"$CONTAINER\" \\\n--container-name=$CONTAINER_NAME \\\n@@ -70,6 +70,7 @@ wait\n# Run the actual pytest command\necho $cmd\nsrun -o $OUTFILE -e $OUTFILE \\\n+ --ntasks-per-node=8 \\\n--open-mode=append \\\n--container-writable \\\n--container-image=\"$CONTAINER\" \\\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/multiprocess_gpu_test.py",
"new_path": "tests/multiprocess_gpu_test.py",
"diff": "@@ -151,15 +151,15 @@ class MultiProcessGpuTest(jtu.JaxTestCase):\n@unittest.skipIf(\nos.environ.get(\"SLURM_JOB_NUM_NODES\", None) != \"2\",\n\"Slurm environment with at least two nodes needed!\")\n-class MultiNodeGpuTest(jtu.JaxTestCase):\n+class SlurmMultiNodeGpuTest(jtu.JaxTestCase):\ndef test_gpu_multi_node_initialize_and_psum(self):\n# Hookup the ENV vars expected to be set already in the SLURM environment\n- nodelist = os.environ.get(\"SLURM_STEP_NODELIST\", None)\n- if nodelist is not None:\n- coordinator_address = nodelist.split('[')[0] + \\\n- nodelist.split('[')[1].split(',')[0]\n+ coordinator_address = os.environ.get(\"SLURM_STEP_NODELIST\", None)\n+ if coordinator_address is not None and '[' in coordinator_address:\n+ coordinator_address = coordinator_address.split('[')[0] + \\\n+ coordinator_address.split('[')[1].split(',')[0]\nnum_tasks = os.environ.get(\"SLURM_NPROCS\", None)\ntaskid = os.environ.get(\"SLURM_PROCID\", None)\nlocalid = os.environ.get(\"SLURM_LOCALID\", None)\n@@ -174,6 +174,9 @@ class MultiNodeGpuTest(jtu.JaxTestCase):\ncoordinator_address is None or num_tasks is None or taskid is None,\nFalse)\n+ # os.environ[\"CUDA_VISIBLE_DEVICES\"] = localid #WAR for Bug:12119\n+ jax.config.update(\"jax_cuda_visible_devices\", localid)\n+\njax.distributed.initialize(coordinator_address=f'{coordinator_address}:{port}',\nnum_processes=int(num_tasks),\nprocess_id=int(taskid))\n"
}
] | Python | Apache License 2.0 | google/jax | Enable one gpu per process in multinode GPU CI |
260,510 | 29.08.2022 14:52:14 | 25,200 | 4936713c88a678990a4a3f1f03cac0aed2c301b1 | Use cases_from_list to limit number of tests | [
{
"change_type": "MODIFY",
"old_path": "tests/state_test.py",
"new_path": "tests/state_test.py",
"diff": "@@ -373,13 +373,13 @@ class StatePrimitivesTest(jtu.JaxTestCase):\nself.assertEqual(jaxpr.eqns[2].primitive, state.get_p)\nself.assertEqual(jaxpr.eqns[3].primitive, state.get_p)\n- @parameterized.parameters(\n+ @parameterized.parameters(jtu.cases_from_list([\ndict(ref_shape=ref_shape, ref_bdim=ref_bdim, idx_shape=idx_shape,\nindexed_dims=indexed_dims, idx_bdims=idx_bdims, out_bdim=out_bdim,\nop=op)\n- for ref_shape in [(1,), (2, 3), ()]\n+ for ref_shape in [(1,), (2, 3), (4, 5, 6)]\nfor ref_bdim in range(1 + len(ref_shape))\n- for idx_shape in [(), (2,),(5, 6)]\n+ for idx_shape in [(), (1,), (2,), (5, 6)]\nfor indexed_dims in it.product([True, False], repeat=len(ref_shape))\nfor idx_bdims in it.product([None, *range(1 + len(idx_shape))],\nrepeat=sum(indexed_dims))\n@@ -397,7 +397,7 @@ class StatePrimitivesTest(jtu.JaxTestCase):\n*indexer)])\nor [jnp.ones(x_ref.shape, x_ref.dtype)[None][(0, *indexer)]])\n]\n- )\n+ ]))\ndef test_vmap(self, ref_shape, ref_bdim, idx_shape, indexed_dims,\nidx_bdims, out_bdim, op):\n"
}
] | Python | Apache License 2.0 | google/jax | Use cases_from_list to limit number of tests |
260,510 | 29.08.2022 17:23:56 | 25,200 | 10b2e210ed5049595bbc00cf2a8cf9fd873382ba | Enable custom_jvp/vjp in eager pmap | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1082,6 +1082,18 @@ class MapTrace(core.Trace):\nfor v, s, dst in zip(out, outaxes, out_axes_thunk()))\nreturn map(partial(MapTracer, self), out, outaxes)\n+ def process_custom_jvp_call(self, primitive, fun, jvp, tracers):\n+ fake_primitive = types.SimpleNamespace(\n+ multiple_results=True, bind=partial(primitive.bind, fun, jvp))\n+ return self.process_primitive(fake_primitive, tracers, {})\n+\n+ def process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers,\n+ out_trees):\n+ fake_primitive = types.SimpleNamespace(\n+ multiple_results=True, bind=partial(primitive.bind, fun, fwd, bwd,\n+ out_trees=out_trees))\n+ return self.process_primitive(fake_primitive, tracers, {})\n+\ndef process_axis_index(self, frame):\nfake_primitive = types.SimpleNamespace(\nmultiple_results=False, bind=lambda _: jax.lax.axis_index(frame.name))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -3123,7 +3123,39 @@ class EagerPmapMixin:\nsuper().tearDown()\nclass EagerPythonPmapTest(EagerPmapMixin, PythonPmapTest):\n- pass\n+\n+ def test_custom_jvp(self):\n+\n+ @jax.custom_jvp\n+ def foo(x):\n+ return jnp.exp(x)\n+ @foo.defjvp\n+ def foo_jvp(xs, ts):\n+ (x,), (t,) = xs, ts\n+ return foo(x), t * 4.\n+\n+ f = lambda x, t: jax.jvp(foo, (x,), (t,))\n+ x = jnp.arange(\n+ jax.local_device_count() * 5, dtype=jnp.dtype('float32')).reshape((\n+ jax.local_device_count(), 5))\n+ self.assertAllClose(self.pmap(f)(x, x), jax.vmap(f)(x, x))\n+\n+ def test_custom_vjp(self):\n+\n+ @jax.custom_vjp\n+ def foo(x):\n+ return jnp.exp(x)\n+\n+ def foo_fwd(x):\n+ return foo(x), x\n+ def foo_bwd(_, g):\n+ return (g * 5.,)\n+ foo.defvjp(foo_fwd, foo_bwd)\n+\n+ f = jax.grad(foo)\n+ x = jnp.arange(jax.local_device_count(), dtype=jnp.dtype('float32'))\n+ self.assertAllClose(self.pmap(f)(x), jax.vmap(f)(x))\n+\nclass EagerCppPmapTest(EagerPmapMixin, CppPmapTest):\npass\n"
}
] | Python | Apache License 2.0 | google/jax | Enable custom_jvp/vjp in eager pmap
PiperOrigin-RevId: 470855724 |
260,287 | 18.08.2022 13:33:34 | 0 | cbcc77b37653a4b92910a33b47215250a037d3f5 | Add a correct jaxpr substitution for the cond primitive
The default rule only searches for jaxprs stashed immediately in params,
but cond keeps a tuple of jaxprs, so we missed them. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/conditionals.py",
"new_path": "jax/_src/lax/control_flow/conditionals.py",
"diff": "@@ -671,6 +671,12 @@ def _cond_transpose(reduce_axes, cts, *args, branches, linear):\nassert next(out_iter, None) is None\nreturn [None] + out\n+def _cond_axis_substitution(params, subst, traverse):\n+ if not traverse:\n+ return params\n+ branches = tuple(core.subst_axis_names_jaxpr(jaxpr, subst) for jaxpr in params['branches'])\n+ return dict(params, branches=branches)\n+\ndef _cond_typecheck(*in_atoms, branches, linear):\navals = [x.aval for x in in_atoms]\ntc = partial(_typecheck_param, 'cond')\n@@ -753,6 +759,7 @@ pe.custom_partial_eval_rules[cond_p] = _cond_partial_eval\nbatching.axis_primitive_batchers[cond_p] = _cond_batching_rule\nxla.register_initial_style_primitive(cond_p)\ncore.custom_typechecks[cond_p] = _cond_typecheck\n+core.axis_substitution_rules[cond_p] = _cond_axis_substitution\npe.partial_eval_jaxpr_custom_rules[cond_p] = _cond_partial_eval_custom\npe.dce_rules[cond_p] = _cond_dce_rule\n"
}
] | Python | Apache License 2.0 | google/jax | Add a correct jaxpr substitution for the cond primitive
The default rule only searches for jaxprs stashed immediately in params,
but cond keeps a tuple of jaxprs, so we missed them. |
260,631 | 30.08.2022 14:03:54 | 25,200 | 4847c0929e168423e98eaa9bbdded6838db657f0 | Init local variables
It's UB to use uninitialized values as arguments. | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/lapack_kernels.cc",
"new_path": "jaxlib/lapack_kernels.cc",
"diff": "@@ -661,7 +661,7 @@ void RealGees<T>::Kernel(void* out_tuple, void** data, XlaCustomCallStatus*) {\nconst T* a_in = reinterpret_cast<T*>(data[4]);\n// bool* select (T, T) = reinterpret_cast<bool* (T, T)>(data[5]);\n- bool (*select)(T, T);\n+ bool (*select)(T, T) = nullptr;\nvoid** out = reinterpret_cast<void**>(out_tuple);\nT* a_work = reinterpret_cast<T*>(out[0]);\n@@ -672,8 +672,7 @@ void RealGees<T>::Kernel(void* out_tuple, void** data, XlaCustomCallStatus*) {\nint* sdim_out = reinterpret_cast<int*>(out[4]);\nint* info_out = reinterpret_cast<int*>(out[5]);\n- bool* b_work;\n- if (sort == 'N') b_work = new bool[n];\n+ bool* b_work = (sort != 'N') ? (new bool[n]) : nullptr;\nT work_query;\nint lwork = -1;\n@@ -722,7 +721,7 @@ void ComplexGees<T>::Kernel(void* out_tuple, void** data,\nconst T* a_in = reinterpret_cast<T*>(data[4]);\n// bool* select (T, T) = reinterpret_cast<bool* (T, T)>(data[5]);\n- bool (*select)(T);\n+ bool (*select)(T) = nullptr;\nvoid** out = reinterpret_cast<void**>(out_tuple);\nT* a_work = reinterpret_cast<T*>(out[0]);\n@@ -733,8 +732,7 @@ void ComplexGees<T>::Kernel(void* out_tuple, void** data,\nint* sdim_out = reinterpret_cast<int*>(out[4]);\nint* info_out = reinterpret_cast<int*>(out[5]);\n- bool* b_work = nullptr;\n- if (sort != 'N') b_work = new bool[n];\n+ bool* b_work = (sort != 'N') ? (new bool[n]) : nullptr;\nT work_query;\nint lwork = -1;\n"
}
] | Python | Apache License 2.0 | google/jax | Init local variables
It's UB to use uninitialized values as arguments.
PiperOrigin-RevId: 471084634 |
260,631 | 30.08.2022 15:29:59 | 25,200 | 9c16c832341ebbd959cef8718fa63ae14ca381c1 | Rollback of upgrade logistic (sigmoid) function into a lax primitive. | [
{
"change_type": "MODIFY",
"old_path": "docs/jax.lax.rst",
"new_path": "docs/jax.lax.rst",
"diff": "@@ -103,7 +103,6 @@ Operators\nlgamma\nlog\nlog1p\n- logistic\nmax\nmin\nmul\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -300,10 +300,6 @@ def tanh(x: Array) -> Array:\nr\"\"\"Elementwise hyperbolic tangent: :math:`\\mathrm{tanh}(x)`.\"\"\"\nreturn tanh_p.bind(x)\n-def logistic(x: Array) -> Array:\n- r\"\"\"Elementwise logistic (sigmoid) function: :math:`\\frac{1}{1 + e^{-x}}`.\"\"\"\n- return logistic_p.bind(x)\n-\ndef sin(x: Array) -> Array:\nr\"\"\"Elementwise sine: :math:`\\mathrm{sin}(x)`.\"\"\"\nreturn sin_p.bind(x)\n@@ -1740,10 +1736,6 @@ ad.defjvp2(tanh_p, lambda g, ans, x: mul(add(g, mul(g, ans)),\nsub(_one(x), ans)))\nmlir.register_lowering(tanh_p, partial(_nary_lower_mhlo, mhlo.TanhOp))\n-logistic_p = standard_unop(_float | _complex, 'logistic')\n-ad.defjvp2(logistic_p, lambda g, ans, x: mul(g, mul(ans, sub(_one(ans), ans))))\n-mlir.register_lowering(logistic_p, partial(_nary_lower_mhlo, mhlo.LogisticOp))\n-\nsin_p = standard_unop(_float | _complex, 'sin')\nad.defjvp(sin_p, lambda g, x: mul(g, cos(x)))\nif mlir_api_version < 27:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax_reference.py",
"new_path": "jax/_src/lax_reference.py",
"diff": "@@ -69,7 +69,6 @@ asinh = np.arcsinh\nacosh = np.arccosh\natanh = np.arctanh\n-def logistic(x): return 1 / (1 + np.exp(-x))\ndef betainc(a, b, x): return scipy.special.betainc(a, b, x).astype(x.dtype)\ndef lgamma(x): return scipy.special.gammaln(x).astype(x.dtype)\ndef digamma(x): return scipy.special.digamma(x).astype(x.dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/nn/functions.py",
"new_path": "jax/_src/nn/functions.py",
"diff": "@@ -91,7 +91,7 @@ def sigmoid(x: Array) -> Array:\nArgs:\nx : input array\n\"\"\"\n- return lax.logistic(x)\n+ return expit(x)\n@jax.jit\ndef silu(x: Array) -> Array:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/scipy/special.py",
"new_path": "jax/_src/scipy/special.py",
"diff": "@@ -96,10 +96,13 @@ logit.defjvps(\nlambda g, ans, x: lax.div(g, lax.mul(x, lax.sub(_lax_const(x, 1), x))))\n+@api.custom_jvp\n@_wraps(osp_special.expit, module='scipy.special', update_doc=False)\ndef expit(x):\nx, = _promote_args_inexact(\"expit\", x)\n- return lax.logistic(x)\n+ one = _lax_const(x, 1)\n+ return lax.div(one, lax.add(one, lax.exp(lax.neg(x))))\n+expit.defjvps(lambda g, ans, x: g * ans * (_lax_const(ans, 1) - ans))\n@_wraps(osp_special.logsumexp, module='scipy.special')\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1352,8 +1352,6 @@ tf_impl_with_avals[lax.asin_p] = _convert_jax_impl(\ntf_impl_with_avals[lax.atan_p] = _convert_jax_impl(\nlax_internal.atan_impl, multiple_results=False)\n-tf_impl[lax.logistic_p] = tf.math.sigmoid\n-\ndef _atan2(y, x, **kwargs):\nif x.dtype.is_complex or y.dtype.is_complex:\ncomplex_component_dtype = {\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"diff": "@@ -130,15 +130,14 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n\"cos\", \"cosh\", \"complex\", \"conj\", \"convert_element_type\", \"cummax\",\n\"cummin\", \"device_put\", \"dynamic_slice\", \"dynamic_update_slice\", \"exp\",\n\"eq\", \"floor\", \"gather\", \"ge\", \"gt\", \"imag\", \"iota\", \"is_finite\", \"le\",\n- \"logistic\", \"lt\", \"log\", \"mul\", \"ne\", \"neg\", \"not\", \"or\", \"pad\",\n- \"population_count\", \"random_categorical\", \"random_uniform\",\n- \"random_randint\", \"reduce\", \"reduce_and\", \"reduce_prod\", \"reduce_or\",\n- \"reduce_sum\", \"reduce_window_mul\", \"reduce_window_min\",\n- \"reduce_window_max\", \"real\", \"reshape\", \"rev\", \"rsqrt\", \"select_n\",\n- \"select_and_scatter_add\", \"shift_left\", \"shift_right_logical\",\n- \"shift_right_arithmetic\", \"sign\", \"sin\", \"sinh\", \"slice\", \"sqrt\",\n- \"squeeze\", \"stop_gradient\", \"sub\", \"tie_in\", \"transpose\", \"xor\",\n- \"zeros_like\"\n+ \"lt\", \"log\", \"mul\", \"ne\", \"neg\", \"not\", \"or\", \"pad\", \"population_count\",\n+ \"random_categorical\", \"random_uniform\", \"random_randint\",\n+ \"reduce\", \"reduce_and\", \"reduce_prod\", \"reduce_or\", \"reduce_sum\",\n+ \"reduce_window_mul\", \"reduce_window_min\", \"reduce_window_max\", \"real\",\n+ \"reshape\", \"rev\", \"rsqrt\", \"select_n\", \"select_and_scatter_add\",\n+ \"shift_left\", \"shift_right_logical\", \"shift_right_arithmetic\", \"sign\",\n+ \"sin\", \"sinh\", \"slice\", \"sqrt\", \"squeeze\", \"stop_gradient\", \"sub\",\n+ \"tie_in\", \"transpose\", \"xor\", \"zeros_like\"\n}\n@classmethod\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -432,7 +432,6 @@ for dtype in jtu.dtypes.all_floating + jtu.dtypes.complex:\n_make_unary_elementwise_harness(prim=lax.sqrt_p, dtype=dtype)\n_make_unary_elementwise_harness(prim=lax.tan_p, dtype=dtype)\n_make_unary_elementwise_harness(prim=lax.tanh_p, dtype=dtype)\n- _make_unary_elementwise_harness(prim=lax.logistic_p, dtype=dtype)\nfor dtype in jtu.dtypes.all_floating:\n_make_unary_elementwise_harness(prim=lax.bessel_i0e_p, dtype=dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jet.py",
"new_path": "jax/experimental/jet.py",
"diff": "@@ -498,11 +498,11 @@ def _integer_pow_taylor(primals_in, series_in, *, y):\njet_rules[lax.integer_pow_p] = _integer_pow_taylor\n-def _logistic_taylor(primals_in, series_in):\n+def _expit_taylor(primals_in, series_in):\nx, = primals_in\nseries, = series_in\nu = [x] + series\n- v = [lax.logistic(x)] + [None] * len(series)\n+ v = [jax.scipy.special.expit(x)] + [None] * len(series)\ne = [v[0] * (1 - v[0])] + [None] * len(series) # terms for sigmoid' = sigmoid * (1 - sigmoid)\nfor k in range(1, len(v)):\nv[k] = fact(k-1) * sum(_scale(k, j) * e[k-j] * u[j] for j in range(1, k+1))\n@@ -511,15 +511,12 @@ def _logistic_taylor(primals_in, series_in):\nprimal_out, *series_out = v\nreturn primal_out, series_out\n-jet_rules[lax.logistic_p] = _logistic_taylor\n-\n-\ndef _tanh_taylor(primals_in, series_in):\nx, = primals_in\nseries, = series_in\nu = [2*x] + [2 * series_ for series_ in series]\nprimals_in, *series_in = u\n- primal_out, series_out = _logistic_taylor((primals_in, ), (series_in, ))\n+ primal_out, series_out = _expit_taylor((primals_in, ), (series_in, ))\nseries_out = [2 * series_ for series_ in series_out]\nreturn 2 * primal_out - 1, series_out\njet_rules[lax.tanh_p] = _tanh_taylor\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/__init__.py",
"new_path": "jax/lax/__init__.py",
"diff": "@@ -139,8 +139,6 @@ from jax._src.lax.lax import (\nlog1p as log1p,\nlog1p_p as log1p_p,\nlog_p as log_p,\n- logistic as logistic,\n- logistic_p as logistic_p,\nlt as lt,\nlt_p as lt_p,\nmake_bint as make_bint,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/jet_test.py",
"new_path": "tests/jet_test.py",
"diff": "@@ -188,7 +188,7 @@ class JetTest(jtu.JaxTestCase):\nprimals = (primal_in, )\nseries = (terms_in, )\n- y, terms = jax.experimental.jet._logistic_taylor(primals, series)\n+ y, terms = jax.experimental.jet._expit_taylor(primals, series)\nexpected_y, expected_terms = jvp_taylor(jax.scipy.special.expit, primals, series)\natol = 1e-4\n@@ -283,7 +283,7 @@ class JetTest(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_tanh(self): self.unary_check(jnp.tanh, lims=[-500, 500], order=5)\n@jtu.skip_on_devices(\"tpu\")\n- def test_logistic(self): self.unary_check(lax.logistic, lims=[-100, 100], order=5)\n+ def test_expit(self): self.unary_check(jax.scipy.special.expit, lims=[-100, 100], order=5)\n@jtu.skip_on_devices(\"tpu\")\ndef test_expit2(self): self.expit_check(lims=[-500, 500], order=5)\n@jtu.skip_on_devices(\"tpu\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_autodiff_test.py",
"new_path": "tests/lax_autodiff_test.py",
"diff": "@@ -134,9 +134,6 @@ LAX_GRAD_OPS = [\ndtypes=grad_complex_dtypes),\ngrad_test_spec(lax.cbrt, nargs=1, order=2, rng_factory=jtu.rand_default,\ndtypes=grad_float_dtypes, tol={np.float64: 3e-5}),\n- grad_test_spec(lax.logistic, nargs=1, order=2,\n- rng_factory=jtu.rand_default,\n- dtypes=grad_inexact_dtypes),\ngrad_test_spec(lax.add, nargs=2, order=2, rng_factory=jtu.rand_default,\ndtypes=grad_inexact_dtypes),\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -115,7 +115,6 @@ LAX_OPS = [\n# TODO(b/143135720): on GPU, tanh has only ~float32 precision.\nop_record(\"tanh\", 1, float_dtypes + complex_dtypes, jtu.rand_small,\n{np.float64: 1e-9, np.complex128: 1e-7}),\n- op_record(\"logistic\", 1, float_dtypes + complex_dtypes, jtu.rand_default),\nop_record(\"sin\", 1, float_dtypes + complex_dtypes, jtu.rand_default),\nop_record(\"cos\", 1, float_dtypes + complex_dtypes, jtu.rand_default),\nop_record(\"atan2\", 2, float_dtypes, jtu.rand_default),\n@@ -2960,8 +2959,6 @@ class LazyConstantTest(jtu.JaxTestCase):\nfor op, dtypes in unary_op_types.items())\ndef testUnaryWeakTypes(self, op_name, rec_dtypes):\n\"\"\"Test that all lax unary ops propagate weak_type information appropriately.\"\"\"\n- if op_name == \"bitwise_not\":\n- raise unittest.SkipTest(\"https://github.com/google/jax/issues/12066\")\n# Find a valid dtype for the function.\nfor dtype in [np.float_, np.int_, np.complex_, np.bool_]:\ndtype = dtypes.canonicalize_dtype(dtype)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_stats_test.py",
"new_path": "tests/scipy_stats_test.py",
"diff": "@@ -351,7 +351,7 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nwith jtu.strict_promotion_if_dtypes_match(dtypes):\nself._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n- tol=3e-5)\n+ tol=1e-6)\nself._CompileAndCheck(lax_fun, args_maker)\n@genNamedParametersNArgs(1)\n@@ -397,7 +397,7 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\nreturn list(map(rng, shapes, dtypes))\nself._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n- tol=2e-5)\n+ tol=1e-6)\nself._CompileAndCheck(lax_fun, args_maker)\n@genNamedParametersNArgs(3)\n"
}
] | Python | Apache License 2.0 | google/jax | Rollback of upgrade logistic (sigmoid) function into a lax primitive.
PiperOrigin-RevId: 471105650 |
260,510 | 31.08.2022 12:18:40 | 25,200 | 311a9cb5d9da004e9dffc781ce2bd785a7a60560 | Throw error when 64-bit dtypes used incorrectly in `jax.pure_callback` | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/callback.py",
"new_path": "jax/_src/callback.py",
"diff": "\"\"\"Module for JAX callbacks.\"\"\"\nfrom __future__ import annotations\n-import functools\n-\nfrom typing import Any, Callable, Sequence\nfrom jax import core\nfrom jax import tree_util\n+from jax._src import dtypes\nfrom jax._src import lib as jaxlib\nfrom jax._src import util\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\n-\n+import numpy as np\n# `pure_callback_p` is the main primitive for staging out Python pure callbacks.\npure_callback_p = core.Primitive(\"pure_callback\")\n@@ -113,6 +112,11 @@ def pure_callback_lowering(ctx, *args, callback, **params):\nmlir.register_lowering(pure_callback_p, pure_callback_lowering)\n+def _check_shape_dtype(shape_dtype):\n+ dt = np.dtype(shape_dtype.dtype)\n+ if dtypes.canonicalize_dtype(dt) != dt:\n+ raise ValueError(\n+ \"Cannot return 64-bit values when `jax_enable_x64` is disabled\")\ndef pure_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\n*args: Any, vectorized: bool = False, **kwargs: Any):\n@@ -121,6 +125,7 @@ def pure_callback(callback: Callable[..., Any], result_shape_dtypes: Any,\nreturn tree_util.tree_leaves(callback(*args, **kwargs))\nflat_args, in_tree = tree_util.tree_flatten((args, kwargs))\n+ tree_util.tree_map(_check_shape_dtype, result_shape_dtypes)\nresult_avals = tree_util.tree_map(\nlambda x: core.ShapedArray(x.shape, x.dtype), result_shape_dtypes)\nflat_result_avals, out_tree = tree_util.tree_flatten(result_avals)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/python_callback_test.py",
"new_path": "tests/python_callback_test.py",
"diff": "@@ -558,6 +558,20 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\nf()\njax.effects_barrier()\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_callback_with_wrongly_specified_64_bit_dtype(self):\n+ if config.jax_enable_x64:\n+ raise unittest.SkipTest(\"Test only needed when 64-bit mode disabled.\")\n+\n+ @jax.jit\n+ def f():\n+ return jax.pure_callback(lambda: np.float64(1.),\n+ core.ShapedArray((), np.float64))\n+\n+ with self.assertRaises(ValueError):\n+ f()\n+ jax.effects_barrier()\n+\ndef test_can_vmap_pure_callback(self):\n@jax.jit\n"
}
] | Python | Apache License 2.0 | google/jax | Throw error when 64-bit dtypes used incorrectly in `jax.pure_callback` |
260,310 | 31.08.2022 15:05:05 | 25,200 | 59c2fc9ea9c2c289501d1af6751e2b473eddf482 | [jax2tf] add a new test for jax2tf gda test.
Now it cover the test using gda as jax function input. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -1336,11 +1336,12 @@ class XlaCallModuleTest(tf_test_util.JaxToTfTestCase):\nglobal_shape, global_mesh, mesh_axes,\nlambda idx: global_data[idx]), global_data\n- # Create GDA\nglobal_mesh = jtu.create_global_mesh((4, 2), (\"x\", \"y\"))\nmesh_axes = P((\"x\", \"y\"))\nparams, _ = create_gda((8, 2), global_mesh, mesh_axes)\n+ input_data = np.arange(16).reshape(2, 8)\n+ # Test 1: use GDA as constants\ndef jax_func(input_data):\nhandle = pjit(\njnp.matmul,\n@@ -1353,12 +1354,29 @@ class XlaCallModuleTest(tf_test_util.JaxToTfTestCase):\njax2tf.convert(jax_func, enable_xla=True),\njit_compile=True,\n)\n- input_data = np.arange(16).reshape(2, 8)\njax_out = jax_func(input_data=input_data)\ntf_out = tf_func(input_data=input_data)\n# TODO(b/243146552) We can switch to ConvertAndCompare after this bug fix.\nnp.array_equal(jax_out._value, np.array(tf_out))\n+ # Test 2: use GDA as JAX function input\n+ def jax_func_2(input_data, params):\n+ handle = pjit(\n+ jnp.matmul,\n+ in_axis_resources=(P(\"y\", \"x\"), P((\"x\", \"y\"),)),\n+ out_axis_resources=None)\n+ return handle(input_data, params)\n+\n+ with global_mesh:\n+ tf_func_2 = tf.function(\n+ jax2tf.convert(jax_func_2, enable_xla=True),\n+ jit_compile=True,\n+ )\n+ jax_out_2 = jax_func_2(input_data=input_data, params=params)\n+ tf_out_2 = tf_func_2(input_data=input_data, params=params)\n+ # TODO(b/243146552) We can switch to ConvertAndCompare after this bug fix.\n+ np.array_equal(jax_out_2._value, np.array(tf_out_2))\n+\nif __name__ == \"__main__\":\n# TODO: Remove once tensorflow is 2.10.0 everywhere.\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] add a new test for jax2tf gda test.
Now it cover the test using gda as jax function input.
PiperOrigin-RevId: 471365834 |
260,411 | 30.08.2022 23:04:31 | 25,200 | 906a212b8050ad5d6c91d6819176c0c00b64c427 | [shape_poly] Add limited support for jnp.repeat with shape polymorphism
Supports only the case when the `repeats` parameter is a dimension polynomials
and the total_repeat_length is None. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -2351,7 +2351,7 @@ def indices(dimensions, dtype=int32, sparse=False):\n_TOTAL_REPEAT_LENGTH_DOC = \"\"\"\\\n-Jax adds the optional `total_repeat_length` parameter which specifies the total\n+JAX adds the optional `total_repeat_length` parameter which specifies the total\nnumber of repeat, and defaults to sum(repeats). It must be specified for repeat\nto be compilable. If `sum(repeats)` is larger than the specified\n`total_repeat_length` the remaining values will be discarded. In the case of\n@@ -2362,7 +2362,8 @@ will be repeated.\n@_wraps(np.repeat, lax_description=_TOTAL_REPEAT_LENGTH_DOC)\ndef repeat(a, repeats, axis: Optional[int] = None, *, total_repeat_length=None):\n- _check_arraylike(\"repeat\", a, repeats)\n+ _check_arraylike(\"repeat\", a)\n+ core.is_special_dim_size(repeats) or _check_arraylike(\"repeat\", repeats)\nif axis is None:\na = ravel(a)\n@@ -2371,9 +2372,14 @@ def repeat(a, repeats, axis: Optional[int] = None, *, total_repeat_length=None):\naxis = core.concrete_or_error(operator.index, axis, \"'axis' argument of jnp.repeat()\")\nassert isinstance(axis, int) # to appease mypy\n- # If total_repeat_length is not given, can't compile, use a default.\n+ if core.is_special_dim_size(repeats):\n+ if total_repeat_length is not None:\n+ raise ValueError(\"jnp.repeat with a DimPolynomial `repeats` is supported only \"\n+ \"when `total_repeat_length` is None\")\n+\n+ # If total_repeat_length is not given, use a default.\nif total_repeat_length is None:\n- repeats = core.concrete_or_error(np.array, repeats,\n+ repeats = core.concrete_or_error(None, repeats,\n\"When jit-compiling jnp.repeat, the total number of repeats must be static. \"\n\"To fix this, either specify a static value for `repeats`, or pass a static \"\n\"value to `total_repeat_length`.\")\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": "@@ -1672,6 +1672,31 @@ _POLY_SHAPE_TEST_HARNESSES = [\npoly_axes=[0])\nfor reduce_op in [jnp.all, jnp.any, jnp.max, jnp.min, jnp.prod, jnp.sum]\n],\n+ # Repeat f32[b, 2] * 3\n+ _make_harness(\"repeat\", \"repeats=int_axis=0\",\n+ lambda x: jnp.repeat(x, repeats=3, axis=0),\n+ [RandArg((3, 2), _f32)],\n+ poly_axes=[0]),\n+ # Repeat f32[b, 2] * b\n+ _make_harness(\"repeat\", \"repeats=poly_axis=0\",\n+ lambda x: jnp.repeat(x, repeats=x.shape[0], axis=0),\n+ [RandArg((3, 2), _f32)],\n+ poly_axes=[0]),\n+ # Repeat f32[b, 2] * b\n+ _make_harness(\"repeat\", \"repeats=poly_axis=None\",\n+ lambda x: jnp.repeat(x, repeats=x.shape[0], axis=None),\n+ [RandArg((3, 2), _f32)],\n+ poly_axes=[0]),\n+ # Repeat f32 * b\n+ _make_harness(\"repeat\", \"repeats=poly_axis=None_scalar\",\n+ lambda x, y: jnp.repeat(x, repeats=y.shape[0], axis=None),\n+ [RandArg((), _f32), RandArg((3, 2), _f32)],\n+ poly_axes=[None, 0]),\n+ _make_harness(\"repeat\", \"repeats=poly_axis=None_total_repeat_length1\",\n+ lambda x: jnp.repeat(x, repeats=x.shape[0], axis=None, total_repeat_length=8),\n+ [RandArg((3, 2), _f32)],\n+ poly_axes=[0],\n+ expect_error=(ValueError, \"jnp.repeat with a DimPolynomial `repeats` is supported only .*\")),\n_make_harness(\"reshape\", \"0\",\nlambda x: x.reshape([x.shape[0], -1]),\n[RandArg((3, 2, 3), _f32)],\n@@ -1912,7 +1937,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=\"reduce_window_add_noxla_poly_axes=[1]\",\n+ #one_containing=\"repeat_repeats=poly_axis=None_scalar_poly_axes=[None, 0]\",\n)\ndef test_prim(self, harness: Harness):\n_test_one_harness(self, harness)\n"
}
] | Python | Apache License 2.0 | google/jax | [shape_poly] Add limited support for jnp.repeat with shape polymorphism
Supports only the case when the `repeats` parameter is a dimension polynomials
and the total_repeat_length is None. |
260,305 | 01.09.2022 13:27:23 | 0 | 1c69f594fba78062cd43cf3ca70821204619d1bf | testSphHarmOrderZeroDegreeOne and test_custom_linear_solve_cholesky have been fixed in ROCm, no need to skip | [
{
"change_type": "MODIFY",
"old_path": "tests/custom_linear_solve_test.py",
"new_path": "tests/custom_linear_solve_test.py",
"diff": "@@ -227,7 +227,6 @@ class CustomLinearSolveTest(jtu.JaxTestCase):\norder=2,\nrtol={jnp.float32: 6e-2, jnp.float64: 2e-3})\n- @jtu.skip_on_devices(\"rocm\") # rtol and atol needs to be adjusted for ROCm\ndef test_custom_linear_solve_cholesky(self):\ndef positive_definite_solve(a, b):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_scipy_test.py",
"new_path": "tests/lax_scipy_test.py",
"diff": "@@ -409,7 +409,6 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nself.assertAllClose(actual, expected, rtol=1.1e-7, atol=3e-8)\n- @jtu.skip_on_devices(\"rocm\") # rtol and atol needs to be adjusted for ROCm\n@jax.numpy_dtype_promotion('standard') # This test explicitly exercises dtype promotion\ndef testSphHarmOrderZeroDegreeOne(self):\n\"\"\"Tests the spherical harmonics of order one and degree zero.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | testSphHarmOrderZeroDegreeOne and test_custom_linear_solve_cholesky have been fixed in ROCm, no need to skip |
260,510 | 01.09.2022 15:27:27 | 25,200 | e1410bd16bc6e9d31900c0a588e7b9d4454beb05 | Use lowering as impl rule for `pure_callback` | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/callback.py",
"new_path": "jax/_src/callback.py",
"diff": "\"\"\"Module for JAX callbacks.\"\"\"\nfrom __future__ import annotations\n+import functools\n+\nfrom typing import Any, Callable, Sequence\nfrom jax import core\n@@ -21,6 +23,7 @@ from jax import tree_util\nfrom jax._src import dtypes\nfrom jax._src import lib as jaxlib\nfrom jax._src import util\n+from jax._src import dispatch\nfrom jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\n@@ -33,11 +36,12 @@ pure_callback_p.multiple_results = True\nmap, unsafe_map = util.safe_map, map\n-@pure_callback_p.def_impl\ndef pure_callback_impl(*args, result_avals, callback: Callable[..., Any],\nvectorized: bool):\ndel vectorized, result_avals\nreturn callback(*args)\n+pure_callback_p.def_impl(functools.partial(dispatch.apply_primitive,\n+ pure_callback_p))\n@pure_callback_p.def_abstract_eval\n@@ -102,7 +106,7 @@ def pure_callback_lowering(ctx, *args, callback, **params):\n\"Please upgrade to a jaxlib >= 0.3.15.\")\ndef _callback(*flat_args):\n- return tuple(pure_callback_p.impl(*flat_args, callback=callback, **params))\n+ return tuple(pure_callback_impl(*flat_args, callback=callback, **params))\nresult, _, keepalive = mlir.emit_python_callback(\nctx, _callback, None, list(args), ctx.avals_in, ctx.avals_out, False,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/python_callback_test.py",
"new_path": "tests/python_callback_test.py",
"diff": "@@ -469,6 +469,17 @@ class PurePythonCallbackTest(jtu.JaxTestCase):\nsuper().tearDown()\ndispatch.runtime_tokens.clear()\n+ @jtu.skip_on_devices(*disabled_backends)\n+ def test_pure_callback_passes_ndarrays_without_jit(self):\n+\n+ def cb(x):\n+ self.assertIs(type(x), np.ndarray)\n+ return x\n+\n+ def f(x):\n+ return jax.pure_callback(cb, x, x)\n+ f(jnp.array(2.))\n+\n@jtu.skip_on_devices(*disabled_backends)\ndef test_simple_pure_callback(self):\n"
}
] | Python | Apache License 2.0 | google/jax | Use lowering as impl rule for `pure_callback` |
260,496 | 01.09.2022 14:13:48 | -7,200 | 7cc7da8576a679c81fc4429bd4f81a25e0201cb9 | Improves quickdraw example in jax2tf | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples/tf_js/README.md",
"new_path": "jax/experimental/jax2tf/examples/tf_js/README.md",
"diff": "-This directory contains examples of using the jax2tf converter to produce\n-models that can be used with TensorFlow.js. Note that this is still highly\n-experimental.\n+This directory contains a simple example of using the jax2tf converter to\n+produce models that can be used with TensorFlow.js. This example uses\n+[tfjs.converters.jax_conversion.convert_jax() API](https://github.com/tensorflow/tfjs/tree/master/tfjs-converter#calling-a-converter-function-in-python-flaxjax),\n+which is part of TensorFlow.JS, and uses jax2tf under the hood.\n+\n+See the following blog post for more details:\n+[JAX on the Web with TensorFlow.js](https://blog.tensorflow.org/2022/08/jax-on-web-with-tensorflowjs.html).\n"
},
{
"change_type": "RENAME",
"old_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/utils.py",
"new_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/input_pipeline.py",
"diff": "@@ -46,7 +46,7 @@ def download_dataset(dir_path, nb_classes):\nprint(f'Failed to fetch {cls_filename}')\nreturn classes\n-def load_classes(dir_path, classes, batch_size=256, test_ratio=0.1,\n+def get_datasets(dir_path, classes, batch_size=256, test_ratio=0.1,\nmax_items_per_class=4096):\nx, y = np.empty([0, 784]), np.empty([0])\nfor idx, cls in enumerate(classes):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.py",
"new_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.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 absl import app # type: ignore\n+from absl import app\nfrom absl import flags\n-import os # type: ignore\n+import os\nimport time\n-from typing import Callable\n-import flax # type: ignore\nfrom flax import linen as nn\n-from flax.training import common_utils # type: ignore\n+from flax.training import train_state\n-import jax # type: ignore\n+import jax\nfrom jax import lax\nfrom jax import numpy as jnp\n-from jax.experimental.jax2tf.examples import saved_model_lib # type: ignore\n+import optax\n-import numpy as np # type: ignore\n-import tensorflow as tf # type: ignore\n-from tensorflowjs.converters import convert_tf_saved_model # type: ignore\n+import numpy as np\n+import tensorflow as tf\n+import tensorflowjs as tfjs\n-from jax.config import config # type: ignore\n-config.config_with_absl()\n+import input_pipeline\n-import utils\n-flags.DEFINE_boolean(\"run_eval_on_train\", False,\n- (\"Also run eval on the train set after each epoch. This \"\n- \"slows down training considerably.\"))\nflags.DEFINE_integer(\"num_epochs\", 5,\n(\"Number of epochs to train for.\"))\nflags.DEFINE_integer(\"num_classes\", 100, \"Number of classification classes.\")\n@@ -53,7 +46,7 @@ FLAGS = flags.FLAGS\n# The code below is an adaptation for Flax from the work published here:\n# https://blog.tensorflow.org/2018/07/train-model-in-tfkeras-with-colab-and-run-in-browser-tensorflowjs.html\n-class QuickDrawModule(nn.Module):\n+class QuickDraw(nn.Module):\n@nn.compact\ndef __call__(self, x):\nx = nn.Conv(features=16, kernel_size=(3, 3), padding='SAME')(x)\n@@ -73,92 +66,91 @@ class QuickDrawModule(nn.Module):\nx = nn.relu(x)\nx = nn.Dense(features=FLAGS.num_classes)(x)\n- x = nn.softmax(x)\nreturn x\n-def predict(params, inputs):\n- \"\"\"A functional interface to the trained Module.\"\"\"\n- return QuickDrawModule().apply({'params': params}, inputs)\n-def categorical_cross_entropy_loss(logits, labels):\n- onehot_labels = common_utils.onehot(labels, logits.shape[-1])\n- return jnp.mean(-jnp.sum(onehot_labels * jnp.log(logits), axis=1))\n-\n-def update(optimizer, inputs, labels):\n+@jax.jit\n+def apply_model(state, inputs, labels):\n+ \"\"\"Computes gradients, loss and accuracy for a single batch.\"\"\"\ndef loss_fn(params):\n- logits = predict(params, inputs)\n- return categorical_cross_entropy_loss(logits, labels)\n- grad = jax.grad(loss_fn)(optimizer.target)\n- optimizer = optimizer.apply_gradient(grad)\n- return optimizer\n-\n-def accuracy(predict: Callable, params, dataset):\n- def top_k_classes(x, k):\n- bcast_idxs = jnp.broadcast_to(np.arange(x.shape[-1]), x.shape)\n- sorted_vals, sorted_idxs = lax.sort_key_val(x, bcast_idxs)\n- topk_idxs = (\n- lax.slice_in_dim(sorted_idxs, -k, sorted_idxs.shape[-1], axis=-1))\n- return topk_idxs\n- def _per_batch(inputs, labels):\n- logits = predict(params, inputs)\n- predicted_classes = top_k_classes(logits, 1)\n- predicted_classes = predicted_classes.reshape((predicted_classes.shape[0],))\n- return jnp.mean(predicted_classes == labels)\n- batched = [_per_batch(inputs, labels) for inputs, labels in dataset]\n- return jnp.mean(jnp.stack(batched))\n-\n-def train_one_epoch(optimizer, train_ds):\n- for inputs, labels in train_ds:\n- optimizer = jax.jit(update)(optimizer, inputs, labels)\n- return optimizer\n-\n-def init_model():\n- rng = jax.random.PRNGKey(0)\n- init_shape = jnp.ones((1, 28, 28, 1), jnp.float32)\n- initial_params = QuickDrawModule().init(rng, init_shape)[\"params\"]\n- optimizer = flax.optim.Adam(\n- learning_rate=0.001, beta1=0.9, beta2=0.999).create(initial_params)\n- return optimizer, initial_params\n-\n-def train(train_ds, test_ds, classes):\n- optimizer, params = init_model()\n+ logits = state.apply_fn({'params': params}, inputs)\n+ one_hot = jax.nn.one_hot(labels, FLAGS.num_classes)\n+ loss = jnp.mean(optax.softmax_cross_entropy(logits=logits, labels=one_hot))\n+ return loss, logits\n+ grad_fn = jax.value_and_grad(loss_fn, has_aux=True)\n+ (loss, logits), grads = grad_fn(state.params)\n+ accuracy = jnp.mean(jnp.argmax(logits, -1) == labels)\n+ return grads, loss, accuracy\n+\n+\n+@jax.jit\n+def update_model(state, grads):\n+ return state.apply_gradients(grads=grads)\n+\n+\n+def run_epoch(state, dataset, train=True):\n+ epoch_loss = []\n+ epoch_accuracy = []\n+\n+ for inputs, labels in dataset:\n+ grads, loss, accuracy = apply_model(state, inputs, labels)\n+ if train:\n+ state = update_model(state, grads)\n+ epoch_loss.append(loss)\n+ epoch_accuracy.append(accuracy)\n+ loss = np.mean(epoch_loss)\n+ accuracy = np.mean(epoch_accuracy)\n+ return state, loss, accuracy\n+\n+\n+def create_train_state(rng):\n+ quick_draw = QuickDraw()\n+ params = quick_draw.init(rng, jnp.ones((1, 28, 28, 1)))['params']\n+ tx = optax.adam(learning_rate=0.001, b1=0.9, b2=0.999)\n+ return train_state.TrainState.create(\n+ apply_fn=quick_draw.apply, params=params, tx=tx)\n+\n+\n+def train(state, train_ds, test_ds):\nfor epoch in range(1, FLAGS.num_epochs+1):\nstart_time = time.time()\n- optimizer = train_one_epoch(optimizer, train_ds)\n- if FLAGS.run_eval_on_train:\n- train_acc = accuracy(predict, optimizer.target, train_ds)\n- print(f\"Training set accuracy {train_acc}\")\n+ state, train_loss, train_accuracy = run_epoch(state, train_ds)\n+ _, test_loss, test_accuracy = run_epoch(state, test_ds, train=False)\n+\n+ print(f\"Training set accuracy {train_accuracy}\")\n+ print(f\"Training set loss {train_loss}\")\n+ print(f\"Test set accuracy {test_accuracy}\")\n+ print(f\"Test set loss {test_loss}\")\n- test_acc = accuracy(predict, optimizer.target, test_ds)\n- print(f\"Test set accuracy {test_acc}\")\nepoch_time = time.time() - start_time\nprint(f\"Epoch {epoch} in {epoch_time:0.2f} sec\")\n- return optimizer.target\n+ return state\n+\n+\n+def main(argv):\n+ if len(argv) > 1:\n+ raise app.UsageError('Too many command-line arguments.')\n-def main(*args):\nbase_model_path = \"/tmp/jax2tf/tf_js_quickdraw\"\ndataset_path = os.path.join(base_model_path, \"data\")\n- num_classes = FLAGS.num_classes\n- classes = utils.download_dataset(dataset_path, num_classes)\n- assert len(classes) == num_classes, classes\n+ classes = input_pipeline.download_dataset(dataset_path, FLAGS.num_classes)\n+ assert len(classes) == FLAGS.num_classes, \"Incorrect number of classes\"\nprint(f\"Classes are: {classes}\")\nprint(\"Loading dataset into memory...\")\n- train_ds, test_ds = utils.load_classes(dataset_path, classes)\n+ train_ds, test_ds = input_pipeline.get_datasets(dataset_path, classes)\nprint(f\"Starting training for {FLAGS.num_epochs} epochs...\")\n- flax_params = train(train_ds, test_ds, classes)\n- model_dir = os.path.join(base_model_path, \"saved_models\")\n- # the model must be converted with with_gradient set to True to be able to\n- # convert the saved model to TF.js, as \"PreventGradient\" is not supported\n- saved_model_lib.convert_and_save_model(predict, flax_params, model_dir,\n+ state = create_train_state(jax.random.PRNGKey(0))\n+ state = train(state, train_ds, test_ds)\n+\n+ tfjs.converters.convert_jax(\n+ apply_fn=state.apply_fn,\n+ params={'params': state.params},\ninput_signatures=[tf.TensorSpec([1, 28, 28, 1])],\n- with_gradient=True, compile_model=False,\n- enable_xla=False)\n- conversion_dir = os.path.join(base_model_path, 'tfjs_models')\n- convert_tf_saved_model(model_dir, conversion_dir)\n+ model_dir=os.path.join(base_model_path, 'tfjs_models'))\nif __name__ == \"__main__\":\napp.run(main)\n"
}
] | Python | Apache License 2.0 | google/jax | Improves quickdraw example in jax2tf |
260,411 | 03.09.2022 08:17:38 | -10,800 | fe055d06ba9517cc2a68ba2ef6270ddd06950cf0 | Allow get_aval to work on ShapeDtypeStruct
This is necessary to be able to call jit(f).lower(ShapeDtypeStruct(...) when
jax_dynamic_shapes is on. The code in partial_eval.infer_lambda_input_type
calls get_aval. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -2958,6 +2958,10 @@ class ShapeDtypeStruct:\nnamed = frozenset(self.named_shape.items())\nreturn hash((self.shape, self.dtype, named))\n+core.pytype_aval_mappings[ShapeDtypeStruct] = (\n+ lambda x: ShapedArray(x.shape, dtypes.canonicalize_dtype(x.dtype),\n+ weak_type=False, named_shape=x.named_shape))\n+\ndef eval_shape(fun: Callable, *args, **kwargs):\n\"\"\"Compute the shape/dtype of ``fun`` without any FLOPs.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/dynamic_api_test.py",
"new_path": "tests/dynamic_api_test.py",
"diff": "@@ -1273,6 +1273,15 @@ class DynamicShapeTest(jtu.JaxTestCase):\nmhlo = f_lowered.compiler_ir('mhlo')\nself.assertIn('tensor<?xi32>', str(mhlo))\n+ def test_lower_abstracted_axes_shapedtypestruct(self):\n+ @partial(jax.jit, abstracted_axes=('n',))\n+ def f(x):\n+ return x.sum()\n+\n+ f_lowered = f.lower(jax.ShapeDtypeStruct((3,), np.int32))\n+ mhlo = f_lowered.compiler_ir('mhlo')\n+ self.assertIn('tensor<?xi32>', str(mhlo))\n+\ndef test_vmap_abstracted_axis(self):\ndef foo(x, y):\nz = jax.vmap(jnp.sin)(x) * y\n"
}
] | Python | Apache License 2.0 | google/jax | Allow get_aval to work on ShapeDtypeStruct
This is necessary to be able to call jit(f).lower(ShapeDtypeStruct(...) when
--jax_dynamic_shapes is on. The code in partial_eval.infer_lambda_input_type
calls get_aval. |
260,411 | 03.09.2022 08:31:07 | -10,800 | 33d1c08a31625c56c59f4a90a52c2b1fd367c7e8 | Update jax/experimental/jax2tf/jax2tf.py | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -270,7 +270,7 @@ def convert(fun_jax: Callable,\nReturns:\nA version of `fun_jax` that expects TfVals as arguments (or\n- tuple/lists/dicts) thereof, and returns TfVals as outputs, and uses\n+ tuple/lists/dicts thereof), and returns TfVals as outputs, and uses\nonly TensorFlow ops.\n\"\"\"\nif experimental_native_lowering == \"default\":\n"
}
] | Python | Apache License 2.0 | google/jax | Update jax/experimental/jax2tf/jax2tf.py
Co-authored-by: Marc van Zee <marcvanzee@gmail.com> |
260,546 | 05.09.2022 16:16:18 | 25,200 | 892dea5d8777a8d1cf008409b2dd90fcb0df788a | Fix NaNs in the gradient of jnp.interp when the spline being interpolated into contains the same knot coordinate twice. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -988,7 +988,9 @@ def interp(x, xp, fp, left=None, right=None, period=None):\ndf = fp[i] - fp[i - 1]\ndx = xp[i] - xp[i - 1]\ndelta = x - xp[i - 1]\n- f = where((dx == 0), fp[i], fp[i - 1] + (delta / dx) * df)\n+\n+ dx0 = dx == 0 # Protect against NaNs in `f` when `dx` is zero.\n+ f = where(dx0, fp[i], fp[i - 1] + (delta / where(dx0, 1, dx)) * df)\nif period is None:\nf = where(x < xp[0], fp[0] if left is None else left, f)\n"
}
] | Python | Apache License 2.0 | google/jax | Fix NaNs in the gradient of jnp.interp when the spline being interpolated into contains the same knot coordinate twice.
PiperOrigin-RevId: 472333594 |
260,424 | 06.09.2022 14:59:59 | -3,600 | 82f74d18984c8b8a137b763f4bbcbeef8134b5d5 | Checkify: Remove some `err` <-not-> `pred` flipping.
Now all internal APIs deal in terms of errs (error thrown if True), and
only the check API takes a pred (error thrown if False). | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -125,11 +125,11 @@ init_error = Error(False, 0, {})\nnext_code = it.count(1).__next__ # globally unique ids, could be uuid4\n-def assert_func(error: Error, pred: Bool, msg: str,\n+def assert_func(error: Error, err: Bool, msg: str,\npayload: Optional[Payload]) -> Error:\ncode = next_code()\npayload = init_payload() if payload is None else payload\n- out_err = error.err | jnp.logical_not(pred)\n+ out_err = error.err | err\nout_code = lax.select(error.err, error.code, code)\nout_payload = lax.select(error.err, error.payload, payload)\nreturn Error(out_err, out_code, {code: msg, **error.msgs}, out_payload)\n@@ -462,20 +462,20 @@ def check_error(error: Error) -> None:\nerr, code, payload = error.err, error.code, error.payload\nerr = core.raise_as_much_as_possible(err)\n- return assert_p.bind(~err, code, payload, msgs=error.msgs)\n+ return assert_p.bind(err, code, payload, msgs=error.msgs)\nassert_p = core.Primitive('assert') # TODO: rename to check?\nassert_p.multiple_results = True # zero results\n@assert_p.def_impl\n-def assert_impl(pred, code, payload, *, msgs):\n- Error(~pred, code, msgs, payload).throw()\n+def assert_impl(err, code, payload, *, msgs):\n+ Error(err, code, msgs, payload).throw()\nreturn []\nCheckEffect = object()\n@assert_p.def_effectful_abstract_eval\n-def assert_abstract_eval(pred, code, payload, *, msgs):\n+def assert_abstract_eval(err, code, payload, *, msgs):\nreturn [], {CheckEffect}\ndef assert_lowering_rule(*a, **k):\n@@ -494,9 +494,9 @@ cf.allowed_effects.add(CheckEffect)\ndef assert_batching_rule(batched_args, batch_dims, *, msgs):\nsize = next(x.shape[dim] for x, dim in zip(batched_args, batch_dims)\nif dim is not batching.not_mapped)\n- pred, code, payload = (batching.bdim_at_front(a, d, size)\n+ err, code, payload = (batching.bdim_at_front(a, d, size)\nfor a, d in zip(batched_args, batch_dims))\n- err = Error(jnp.logical_not(pred), code, msgs, payload)\n+ err = Error(err, code, msgs, payload)\ncheck_error(err)\nreturn [], []\n@@ -511,9 +511,9 @@ def nan_error_check(prim, error, enabled_errors, *in_vals, **params):\nout = prim.bind(*in_vals, **params)\nif ErrorCategory.NAN not in enabled_errors:\nreturn out, error\n- no_nans = jnp.logical_not(jnp.any(jnp.isnan(out)))\n- msg = f\"nan generated by primitive {prim.name} at {summary()}\"\n- return out, assert_func(error, no_nans, msg, None)\n+ any_nans = jnp.any(jnp.isnan(out))\n+ msg = f'nan generated by primitive {prim.name} at {summary()}'\n+ return out, assert_func(error, any_nans, msg, None)\ndef gather_error_check(error, enabled_errors, operand, start_indices, *,\ndimension_numbers, slice_sizes, unique_indices,\n@@ -534,10 +534,10 @@ def gather_error_check(error, enabled_errors, operand, start_indices, *,\nupper_bound = operand_dims[np.array(dnums.start_index_map)]\nupper_bound -= np.array(slice_sizes)[np.array(dnums.start_index_map)]\nupper_bound = jnp.expand_dims(upper_bound, axis=tuple(range(num_batch_dims)))\n- in_bounds = (start_indices >= 0) & (start_indices <= upper_bound.astype(start_indices.dtype))\n+ out_of_bounds = (start_indices < 0) | (start_indices > upper_bound.astype(start_indices.dtype))\n# Get first OOB index, axis and axis size so it can be added to the error msg.\n- flat_idx = jnp.argmin(in_bounds)\n+ flat_idx = jnp.argmin(jnp.logical_not(out_of_bounds))\nmulti_idx = jnp.unravel_index(flat_idx, start_indices.shape)\noob_axis = jnp.array(dnums.start_index_map)[multi_idx[-1]]\noob_axis_size = jnp.array(operand.shape)[oob_axis]\n@@ -549,19 +549,19 @@ def gather_error_check(error, enabled_errors, operand, start_indices, *,\n'index {payload0} is out of bounds for axis {payload1} '\n'with size {payload2}.')\n- return out, assert_func(error, jnp.all(in_bounds), msg, payload)\n+ return out, assert_func(error, jnp.any(out_of_bounds), msg, payload)\nerror_checks[lax.gather_p] = gather_error_check\ndef div_error_check(error, enabled_errors, x, y):\n\"\"\"Checks for division by zero and NaN.\"\"\"\nif ErrorCategory.DIV in enabled_errors:\n- all_nonzero = jnp.logical_not(jnp.any(jnp.equal(y, 0)))\n+ any_zero = jnp.any(jnp.equal(y, 0))\nmsg = f'divided by zero at {summary()}'\n- error = assert_func(error, all_nonzero, msg, None)\n+ error = assert_func(error, any_zero, msg, None)\nreturn nan_error_check(lax.div_p, error, enabled_errors, x, y)\nerror_checks[lax.div_p] = div_error_check\n-def scatter_in_bounds(operand, indices, updates, dnums):\n+def scatter_oob(operand, indices, updates, dnums):\n# Ref: see clamping code used in scatter_translation_rule\nslice_sizes = []\npos = 0\n@@ -579,9 +579,9 @@ def scatter_in_bounds(operand, indices, updates, dnums):\nupper_bound = lax.broadcast_in_dim(upper_bound, indices.shape,\n(len(indices.shape) - 1,))\n- lower_in_bounds = jnp.all(jnp.greater_equal(indices, 0))\n- upper_in_bounds = jnp.all(jnp.less_equal(indices, upper_bound.astype(indices.dtype)))\n- return jnp.logical_and(lower_in_bounds, upper_in_bounds)\n+ lower_oob = jnp.any(jnp.less(indices, 0))\n+ upper_oob = jnp.any(jnp.greater(indices, upper_bound.astype(indices.dtype)))\n+ return jnp.logical_or(lower_oob, upper_oob)\ndef scatter_error_check(prim, error, enabled_errors, operand, indices, updates,\n*, update_jaxpr, update_consts, dimension_numbers,\n@@ -596,13 +596,13 @@ def scatter_error_check(prim, error, enabled_errors, operand, indices, updates,\nif ErrorCategory.OOB not in enabled_errors:\nreturn out, error\n- in_bounds = scatter_in_bounds(operand, indices, updates, dimension_numbers)\n+ out_of_bounds = scatter_oob(operand, indices, updates, dimension_numbers)\noob_msg = f'out-of-bounds indexing while updating at {summary()}'\n- oob_error = assert_func(error, in_bounds, oob_msg, None)\n+ oob_error = assert_func(error, out_of_bounds, oob_msg, None)\n- no_nans = jnp.logical_not(jnp.any(jnp.isnan(out)))\n+ any_nans = jnp.any(jnp.isnan(out))\nnan_msg = f'nan generated by primitive {prim.name} at {summary()}'\n- return out, assert_func(oob_error, no_nans, nan_msg, None)\n+ return out, assert_func(oob_error, any_nans, nan_msg, None)\nerror_checks[lax.scatter_p] = partial(scatter_error_check, lax.scatter_p)\nerror_checks[lax.scatter_add_p] = partial(scatter_error_check, lax.scatter_add_p)\nerror_checks[lax.scatter_mul_p] = partial(scatter_error_check, lax.scatter_mul_p)\n@@ -786,11 +786,11 @@ add_nan_check(lax.max_p)\nadd_nan_check(lax.min_p)\n-def assert_discharge_rule(error, enabled_errors, pred, code, payload, *, msgs):\n+def assert_discharge_rule(error, enabled_errors, err, code, payload, *, msgs):\nif ErrorCategory.USER_CHECK not in enabled_errors:\nreturn [], error\n- out_err = error.err | jnp.logical_not(pred)\n+ out_err = error.err | err\nout_code = lax.select(error.err, error.code, code)\nreturn [], Error(out_err, out_code, {**error.msgs, **msgs}, payload)\nerror_checks[assert_p] = assert_discharge_rule\n"
}
] | Python | Apache License 2.0 | google/jax | Checkify: Remove some `err` <-not-> `pred` flipping.
Now all internal APIs deal in terms of errs (error thrown if True), and
only the check API takes a pred (error thrown if False). |
260,510 | 02.09.2022 10:11:58 | 25,200 | b2a5d2c3bbd39210a0a5ff03002449f51d115e17 | Add partial_eval_custom 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": "@@ -33,7 +33,7 @@ from jax._src import dtypes\nfrom jax._src import source_info_util\nfrom jax._src import state\nfrom jax._src.util import (partition_list, merge_lists, safe_map, safe_zip,\n- split_list)\n+ split_list, split_dict)\nimport jax.numpy as jnp\nimport numpy as np\n@@ -319,6 +319,7 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\njaxpr: core.Jaxpr, nsteps: int, reverse: bool,\nwhich_linear: Tuple[bool, ...]) -> List[pe.JaxprTracer]:\nnum_inputs = len(tracers)\n+ assert num_inputs == len(jaxpr.invars) - 1\nin_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@@ -446,6 +447,135 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\nreturn merge_lists(in_unknowns, known_outputs, unknown_outputs)\npe.custom_partial_eval_rules[for_p] = _for_partial_eval\n+def _for_partial_eval_custom(saveable, in_unknowns, in_inst, eqn):\n+ jaxpr, nsteps, reverse, which_linear = split_dict(\n+ eqn.params, [\"jaxpr\", \"nsteps\", \"reverse\", \"which_linear\"])\n+ num_inputs = len(eqn.invars)\n+ # We first need to run a fixpoint to determine which of the `Ref`s are unknown\n+ # after running the for loop. However, the jaxpr has no outputs. Instead, we\n+ # discharge the body and run the fixpoint with the discharged jaxpr. We can do\n+ # this because the outputs of the discharged jaxpr are one-to-one with the\n+ # 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+ in_unknowns, in_inst = list(in_unknowns), list(in_inst)\n+ for _ in range(num_inputs):\n+ jaxpr_in_unknowns = [False] * len(discharged_consts) + [False, *in_unknowns]\n+ _, _, out_unknowns, inst_out, _, = pe.partial_eval_jaxpr_custom(\n+ discharged_jaxpr, jaxpr_in_unknowns, True,\n+ ensure_out_unknowns=in_unknowns, ensure_out_inst=True,\n+ saveable=saveable)\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+ new_inst = [x for x, inst in zip(eqn.invars, in_inst)\n+ if type(x) is core.Var and not inst]\n+ in_inst = [True] * len(eqn.invars)\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_staged_resin_, _, _, num_res = \\\n+ pe.partial_eval_jaxpr_custom(jaxpr, [False, *in_unknowns],\n+ [True, *in_inst], [], [], saveable)\n+\n+ # `partial_eval_jaxpr_custom` will give us jaxprs that have hybrid `Ref` and\n+ # non-Ref 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+\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+\n+ jaxpr_known, res_avals = _convert_outputs_to_writes(nsteps,\n+ jaxpr_known_resout,\n+ loop_invar_res)\n+\n+ known_invars, _ = partition_list(in_unknowns, eqn.invars)\n+ known_outvars, _ = partition_list(in_unknowns, eqn.outvars)\n+ newvar = core.gensym()\n+ resvars = map(newvar, res_avals)\n+\n+ @lu.wrap_init\n+ def known(*known_vals):\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+ return for_p.bind(*jaxpr_known_args, jaxpr=jaxpr_known, nsteps=nsteps,\n+ reverse=reverse, which_linear=jaxpr_known_which_linear)\n+ call_jaxpr_, _, call_jaxpr_consts = pe.trace_to_jaxpr_dynamic(\n+ known, [v.aval for v in known_invars])\n+ call_jaxpr = core.ClosedJaxpr(call_jaxpr_, call_jaxpr_consts)\n+ eqn_known = pe.new_jaxpr_eqn(known_invars, [*known_outvars, *resvars],\n+ core.closed_call_p, dict(call_jaxpr=call_jaxpr),\n+ call_jaxpr.effects, eqn.source_info)\n+\n+ jaxpr_staged = _convert_inputs_to_reads(nsteps, len(res_avals),\n+ jaxpr_staged_resin_,\n+ loop_invar_res)\n+ which_linear_unknown = (False,) * num_res + tuple(which_linear)\n+ params_staged = dict(eqn.params, jaxpr=jaxpr_staged, reverse=reverse,\n+ nsteps=nsteps,\n+ which_linear=which_linear_unknown)\n+\n+ @lu.wrap_init\n+ def staged(*res_and_refs):\n+ out_flat = for_p.bind(*res_and_refs, **params_staged)\n+ _, ans = split_list(out_flat, [num_res])\n+ _, ans = partition_list(inst_out, ans)\n+ return ans\n+ call_jaxpr_, _, call_jaxpr_consts = pe.trace_to_jaxpr_dynamic(\n+ staged, [v.aval for v in [*resvars, *eqn.invars]])\n+ assert len(jaxpr_staged.invars) - 1 == len(call_jaxpr_.invars)\n+ call_jaxpr = core.ClosedJaxpr(call_jaxpr_, call_jaxpr_consts)\n+ _, outvars = partition_list(inst_out, eqn.outvars)\n+ eqn_staged = pe.new_jaxpr_eqn([*resvars, *eqn.invars], outvars,\n+ core.closed_call_p, dict(call_jaxpr=call_jaxpr),\n+ call_jaxpr.effects, eqn.source_info)\n+ new_vars = [*new_inst, *resvars]\n+ return eqn_known, eqn_staged, in_unknowns, inst_out, new_vars\n+\n+pe.partial_eval_jaxpr_custom_rules[for_p] = _for_partial_eval_custom\n+\ndef _convert_outputs_to_writes(\nnsteps: int, jaxpr: core.Jaxpr, loop_invar_res: Sequence[bool]\n) -> Tuple[core.Jaxpr, List[core.ShapedArray]]:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/primitives.py",
"new_path": "jax/_src/state/primitives.py",
"diff": "@@ -328,10 +328,10 @@ def _state_partial_eval_custom(prim, saveable, unks_in, inst_in, eqn):\nif any(unks_in):\nres = [v for v, inst in zip(eqn.invars, inst_in) if not inst]\nreturn None, eqn, [True] * len(eqn.outvars), [True] * len(eqn.outvars), res\n- elif saveable(get_p, *[var.aval for var in eqn.invars], **eqn.params):\n+ elif saveable(prim, *[var.aval for var in eqn.invars], **eqn.params):\nreturn eqn, None, [False] * len(eqn.outvars), [False] * len(eqn.outvars), []\nres = [v for v, inst in zip(eqn.invars, inst_in) if not inst]\n- return eqn, eqn, [False] * len(eqn.outvars), [True] * len(eqn.outvars), []\n+ return eqn, eqn, [False] * len(eqn.outvars), [True] * len(eqn.outvars), res\npe.partial_eval_jaxpr_custom_rules[get_p] = partial(_state_partial_eval_custom,\nget_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -1240,9 +1240,45 @@ def call_partial_eval_custom_rule(\nnew_inst = [x for x, inst in zip(eqn.invars, inst_in)\nif type(x) is Var and not inst]\nreturn eqn_known, eqn_staged, unks_out, inst_out, new_inst + residuals\n+\n+def closed_call_partial_eval_custom_rule(\n+ jaxpr_param_name: str,\n+ saveable: Callable[..., bool], unks_in: List[bool], inst_in: List[bool],\n+ eqn: JaxprEqn, *, res_aval: ResAvalUpdater = _default_res_aval_updater,\n+ ) -> Tuple[JaxprEqn, JaxprEqn, Sequence[bool], Sequence[bool], List[Var]]:\n+ # TODO(sharadmv,mattjj): dedup this rule with call_partial_eval_custom_rule.\n+ closed_jaxpr = eqn.params[jaxpr_param_name]\n+ jaxpr = convert_constvars_jaxpr(closed_jaxpr.jaxpr)\n+ unks_in = [False] * len(closed_jaxpr.consts) + list(unks_in)\n+ inst_in = [False] * len(closed_jaxpr.consts) + list(inst_in)\n+ jaxpr_known, jaxpr_staged, unks_out, inst_out, num_res = \\\n+ partial_eval_jaxpr_custom(jaxpr, unks_in, inst_in, False, False, saveable)\n+ ins_known, _ = partition_list(unks_in, eqn.invars)\n+ out_binders_known, _ = partition_list(unks_out, eqn.outvars)\n+ _, ins_staged = partition_list(inst_in, eqn.invars)\n+ _, out_binders_staged = partition_list(inst_out, eqn.outvars)\n+ newvar = core.gensym([jaxpr_known, jaxpr_staged])\n+ params_known = {**eqn.params, jaxpr_param_name: core.ClosedJaxpr(jaxpr_known,\n+ ())}\n+ params_staged = {**eqn.params, jaxpr_param_name:\n+ core.ClosedJaxpr(jaxpr_staged, ())}\n+ residuals = [newvar(res_aval(params_known, var.aval))\n+ for var in jaxpr_staged.invars[:num_res]]\n+ eqn_known = new_jaxpr_eqn(ins_known, [*out_binders_known, *residuals],\n+ eqn.primitive, params_known, jaxpr_known.effects, eqn.source_info)\n+ eqn_staged = new_jaxpr_eqn([*residuals, *ins_staged], out_binders_staged,\n+ eqn.primitive, params_staged,\n+ jaxpr_staged.effects, eqn.source_info)\n+ assert len(eqn_staged.invars) == len(jaxpr_staged.invars)\n+ new_inst = [x for x, inst in zip(eqn.invars, inst_in)\n+ if type(x) is Var and not inst]\n+ return eqn_known, eqn_staged, unks_out, inst_out, new_inst + residuals\n+\npartial_eval_jaxpr_custom_rules[core.call_p] = \\\npartial(call_partial_eval_custom_rule, 'call_jaxpr',\nlambda _, __, ___, ____, _____, x, y: (x, y))\n+partial_eval_jaxpr_custom_rules[core.closed_call_p] = \\\n+ partial(closed_call_partial_eval_custom_rule, 'call_jaxpr')\npartial_eval_jaxpr_custom_rules[core.named_call_p] = \\\npartial(call_partial_eval_custom_rule, 'call_jaxpr',\nlambda _, __, ___, ____, _____, x, y: (x, y))\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -89,6 +89,9 @@ def scan_with_new_checkpoint2(f, *args, **kwargs):\ndef scan_with_for(f, *args, **kwargs):\nreturn for_loop.scan(f, *args, **kwargs)\n+def scan_with_remat_for(f, *args, **kwargs):\n+ return jax.remat(lambda *args: for_loop.scan(f, *args, **kwargs))(*args)\n+\nSCAN_IMPLS = [\n(lax.scan, 'unroll1'),\n(partial(lax.scan, unroll=2), 'unroll2'),\n@@ -102,9 +105,27 @@ SCAN_IMPLS_WITH_FOR = [\n(scan_with_new_checkpoint , 'new_checkpoint'),\n(scan_with_new_checkpoint2, 'new_checkpoint2'),\n(scan_with_for, 'for_loop'),\n+ (scan_with_remat_for, 'for_loop_remat'),\n+]\n+\n+def remat_of_for_loop(nsteps, body, state, **kwargs):\n+ return jax.remat(lambda state: for_loop.for_loop(nsteps, body, state,\n+ **kwargs))(state)\n+\n+FOR_LOOP_IMPLS = [\n+ (for_loop.for_loop, 'for_loop'),\n+ (jax.jit(for_loop.for_loop, static_argnums=(0, 1)), 'jit_for_loop'),\n+ (remat_of_for_loop, 'remat_for_loop'),\n]\n+def _for_loop_impls(f):\n+ return parameterized.named_parameters(\n+ dict(testcase_name=impl_name, for_impl=for_impl)\n+ for for_impl, impl_name in FOR_LOOP_IMPLS\n+ )(f)\n+\n+\ndef while_loop_new_checkpoint(cond_fun, body_fun, init_val):\nreturn new_checkpoint(partial(lax.while_loop, cond_fun, body_fun))(init_val)\n@@ -2571,82 +2592,89 @@ class LaxControlFlowTest(jtu.JaxTestCase):\njax.grad(f)(1.) # doesn't crash\n-\nclass ForLoopTest(jtu.JaxTestCase):\n- def test_for_loop_impl_trivial(self):\n- out = for_loop.for_loop(5, lambda i, _: None, None)\n+ @_for_loop_impls\n+ def test_for_loop_impl_trivial(self, for_impl):\n+ out = for_impl(5, lambda i, _: None, None)\nself.assertEqual(out, None)\n- def test_for_loop_can_write_to_ref(self):\n+ @_for_loop_impls\n+ def test_for_loop_can_write_to_ref(self, for_impl):\ndef body(_, x_ref):\nx_ref[()] = jnp.float32(1.)\n- out = for_loop.for_loop(1, body, jnp.float32(0.))\n+ out = for_impl(1, body, jnp.float32(0.))\nself.assertEqual(out, 1.)\ndef body2(i, x_ref):\nx_ref[()] = jnp.float32(i)\n- out = for_loop.for_loop(2, body2, jnp.float32(0.))\n+ out = for_impl(2, body2, jnp.float32(0.))\nself.assertEqual(out, 1.)\ndef body3(i, x_ref):\nx_ref[()] = jnp.float32(i) * 2.\n- out = for_loop.for_loop(2, body3, jnp.float32(0.))\n+ out = for_impl(2, body3, jnp.float32(0.))\nself.assertEqual(out, 2.)\n- def test_for_loop_can_write_to_multiple_refs(self):\n+ @_for_loop_impls\n+ def test_for_loop_can_write_to_multiple_refs(self, for_impl):\ndef body(_, refs):\nx_ref, y_ref = refs\nx_ref[()] = jnp.float32(1.)\ny_ref[()] = jnp.float32(2.)\n- x, y = for_loop.for_loop(1, body, (jnp.float32(0.), jnp.float32(0.)))\n+ x, y = for_impl(1, body, (jnp.float32(0.), jnp.float32(0.)))\nself.assertEqual(x, 1.)\nself.assertEqual(y, 2.)\n- def test_for_loop_can_read_from_ref(self):\n+ @_for_loop_impls\n+ def test_for_loop_can_read_from_ref(self, for_impl):\ndef body(_, x_ref):\nx_ref[()]\n- x = for_loop.for_loop(1, body, jnp.float32(0.))\n+ x = for_impl(1, body, jnp.float32(0.))\nself.assertEqual(x, 0.)\n- def test_for_loop_can_read_from_and_write_to_ref(self):\n+ @_for_loop_impls\n+ def test_for_loop_can_read_from_and_write_to_ref(self, for_impl):\ndef body(_, x_ref):\nx = x_ref[()]\nx_ref[()] = x + jnp.float32(1.)\n- x = for_loop.for_loop(5, body, jnp.float32(0.))\n+ x = for_impl(5, body, jnp.float32(0.))\nself.assertEqual(x, 5.)\n- def test_for_loop_can_read_from_and_write_to_refs(self):\n+ @_for_loop_impls\n+ def test_for_loop_can_read_from_and_write_to_refs(self, for_impl):\ndef body2(_, refs):\nx_ref, y_ref = refs\nx = x_ref[()]\ny_ref[()] = x + 1.\nx_ref[()] = x + 1.\n- x, y = for_loop.for_loop(5, body2, (0., 0.))\n+ x, y = for_impl(5, body2, (0., 0.))\nself.assertEqual(x, 5.)\nself.assertEqual(y, 5.)\n- def test_for_loop_can_read_from_and_write_to_ref_slice(self):\n+ @_for_loop_impls\n+ def test_for_loop_can_read_from_and_write_to_ref_slice(self, for_impl):\ndef body(i, x_ref):\nx = x_ref[i]\nx_ref[i] = x + jnp.float32(1.)\n- x = for_loop.for_loop(4, body, jnp.ones(4, jnp.float32))\n+ x = for_impl(4, body, jnp.ones(4, jnp.float32))\nnp.testing.assert_allclose(x, 2 * jnp.ones(4, jnp.float32))\ndef body2(i, x_ref):\nx = x_ref[i, 0]\nx_ref[i, 1] = x + x_ref[i, 1]\n- x = for_loop.for_loop(4, body2, jnp.arange(8.).reshape((4, 2)))\n+ x = for_impl(4, body2, jnp.arange(8.).reshape((4, 2)))\nnp.testing.assert_allclose(\nx, jnp.array([[0., 1.], [2., 5.], [4., 9.], [6., 13.]]))\n- def test_for_loop_can_implement_cumsum(self):\n+ @_for_loop_impls\n+ def test_for_loop_can_implement_cumsum(self, for_impl):\ndef cumsum(x):\ndef body(i, refs):\nx_ref, accum_ref = refs\naccum_ref[i + 1] = accum_ref[i] + x_ref[i]\naccum = jnp.zeros(x.shape[0] + 1, x.dtype)\n- _, accum_out = for_loop.for_loop(x.shape[0], body, (x, accum))\n+ _, accum_out = for_impl(x.shape[0], body, (x, accum))\nreturn accum_out[1:]\nkey = jax.random.PRNGKey(0)\n@@ -2708,18 +2736,20 @@ def for_body_reverse(i, refs):\nreverse_ref = lambda x, y: (x, x[::-1])\n-identity = lambda x, y: (x, y)\n+def for_body_noop(i, refs):\n+ pass\n+noop_ref = lambda x, y: (x, y)\nfor_reference = for_loop.discharged_for_loop\nclass ForLoopTransformationTest(jtu.JaxTestCase):\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+ {\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\n+ for_body_name, nsteps, impl_name),\n+ \"f\": for_body, \"body_shapes\": body_shapes,\n+ \"ref\": ref, \"n\": nsteps, \"for_impl\": for_impl}\n+ for for_impl, impl_name in FOR_LOOP_IMPLS\nfor 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@@ -2729,14 +2759,12 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\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+ def test_for_jvp(self, f, ref, body_shapes, n, for_impl):\n+ for_ = for_impl\nrng = self.rng()\nargs = [rng.randn(*s) for s in body_shapes]\n- if jit_for:\n- for_ = jax.jit(for_, static_argnums=(0, 1))\ntol = {np.float64: 1e-12, np.float32: 1e-4}\nans = jax.jvp( lambda *args: for_( n, f, args), args, args)\nans_discharged = jax.jvp(lambda *args: for_reference(n, f, args), args, args)\n@@ -2746,11 +2774,11 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\njtu.check_grads(partial(for_, n, f), (args,), order=3, modes=[\"fwd\"])\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+ {\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\n+ for_body_name, nsteps, impl_name),\n+ \"f\": for_body, \"body_shapes\": body_shapes,\n+ \"ref\": ref, \"n\": nsteps, \"for_impl\": for_impl}\n+ for for_impl, impl_name in FOR_LOOP_IMPLS\nfor 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@@ -2760,14 +2788,12 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\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+ def test_for_linearize(self, f, ref, body_shapes, n, for_impl):\n+ for_ = for_impl\nrng = self.rng()\nargs = [rng.randn(*s) for s in body_shapes]\n- if jit_for:\n- for_ = jax.jit(for_, static_argnums=(0, 1))\ntol = {np.float64: 1e-12, np.float32: 1e-4}\nans = jax.linearize(lambda *args: for_( n, f, args), *args)[1](*args)\nans_discharged = jax.linearize(lambda *args: for_reference(n, f, args),\n@@ -2804,7 +2830,9 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\ns = str(jax.xla_computation(jax.grad(loss))(A).as_hlo_text())\nassert s.count(\"dynamic-update-slice(\") < 2\n- def test_for_loop_fixpoint_correctly_identifies_loop_varying_residuals(self):\n+ @_for_loop_impls\n+ def test_for_loop_fixpoint_correctly_identifies_loop_varying_residuals(\n+ self, for_impl):\ndef body(i, refs):\na_ref, b_ref, c_ref = refs\n@@ -2815,7 +2843,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nc_ref[i] = x * b\ndef f(a, b):\nc = jnp.zeros_like(a)\n- _, b, c = for_loop.for_loop(5, body, (a, b, c))\n+ _, b, c = for_impl(5, body, (a, b, c))\nreturn b, c\na = jnp.arange(5.) + 1.\nb = 1.\n@@ -2826,12 +2854,13 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nnp.testing.assert_allclose(actual_tangents[1], expected_tangents[1])\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+ {\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\n+ for_body_name, nsteps, impl_name),\n+ \"f\": for_body, \"body_shapes\": body_shapes,\n+ \"ref\": ref, \"n\": nsteps, \"for_impl\": for_impl}\n+ for for_impl, impl_name in FOR_LOOP_IMPLS\nfor for_body_name, for_body, ref, body_shapes, nsteps in [\n+ (\"noop\", for_body_noop, noop_ref, [(4,), (4,)], 4),\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@@ -2840,14 +2869,12 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\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_grad(self, jit_for, f, ref, body_shapes, n):\n- for_ = for_loop.for_loop\n+ def test_for_grad(self, f, ref, body_shapes, n, for_impl):\n+ for_ = for_impl\nrng = self.rng()\nargs = [rng.randn(*s) for s in body_shapes]\n- if jit_for:\n- for_ = jax.jit(for_, static_argnums=(0, 1))\ntol = {np.float64: 1e-12, np.float32: 1e-4}\nans = jax.grad(lambda args: for_( n, f, args)[1].sum())(args)\nans_discharged = jax.grad(\n@@ -2857,7 +2884,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\natol=tol)\nself.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\njtu.check_grads(lambda *args: for_(n, f, args)[1].sum(), args, order=3,\n- rtol=5e-3)\n+ rtol=7e-3, atol=1e-2)\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add partial_eval_custom rule for `for_loop` |
260,546 | 06.09.2022 11:21:57 | 25,200 | dc4591dd6cd126b2a942fc89322ef65a8a0d867f | Fix NaNs in the gradient of jnp.interp when the spline being interpolated into contains knots that are small and nearby. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -989,8 +989,9 @@ def interp(x, xp, fp, left=None, right=None, period=None):\ndx = xp[i] - xp[i - 1]\ndelta = x - xp[i - 1]\n- dx0 = dx == 0 # Protect against NaNs in `f` when `dx` is zero.\n- f = where(dx0, fp[i], fp[i - 1] + (delta / where(dx0, 1, dx)) * df)\n+ epsilon = np.spacing(np.finfo(xp.dtype).eps)\n+ dx0 = lax.abs(dx) <= epsilon # Prevent NaN gradients when `dx` is small.\n+ f = where(dx0, fp[i - 1], fp[i - 1] + (delta / where(dx0, 1, dx)) * df)\nif period is None:\nf = where(x < xp[0], fp[0] if left is None else left, f)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -3135,6 +3135,23 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nrtol=1E-3)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_dtype={}_period={}_left={}_right={}\".format(\n+ dtype, period, left, right),\n+ \"dtype\": dtype, \"period\": period, \"left\": left, \"right\": right}\n+ for period in [None, 0.59]\n+ for left in [None, 0]\n+ for right in [None, 1]\n+ for dtype in jtu.dtypes.floating\n+ ))\n+ def testInterpGradNan(self, dtype, period, left, right):\n+ kwds = dict(period=period, left=left, right=right)\n+ jnp_fun = partial(jnp.interp, **kwds)\n+ # Probe values of x and xp that are close to zero and close together.\n+ x = dtype(np.exp(np.linspace(-90, -20, 1000)))\n+ g = jax.grad(lambda z: jnp.sum(jnp_fun(z, z, jnp.ones_like(z))))(x)\n+ np.testing.assert_equal(np.all(np.isfinite(g)), True)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_x1={}_x2={}_x1_rng={}\".format(\njtu.format_shape_dtype_string(x1_shape, x1_dtype),\n"
}
] | Python | Apache License 2.0 | google/jax | Fix NaNs in the gradient of jnp.interp when the spline being interpolated into contains knots that are small and nearby.
PiperOrigin-RevId: 472511203 |
260,332 | 06.09.2022 11:45:59 | 25,200 | 5f1858f533281bf5193601d94145bb4f5fece5ba | Add pytest marker inside the test only if pytest is present in the env | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/slurm_job_scripts/multinode_pytest.sub",
"new_path": ".github/workflows/slurm_job_scripts/multinode_pytest.sub",
"diff": "@@ -40,7 +40,7 @@ EOF\nread -r -d '' cmd <<EOF\ndate \\\n&& python3.8 -m pip list | grep jax \\\n-&& python3.8 -m pytest --forked -v -s --continue-on-collection-errors \\\n+&& python3.8 -m pytest -m SlurmMultiNodeGpuTest --forked -v -s --continue-on-collection-errors \\\n--junit-xml=/workspace/outputs/junit_output_\\${SLURM_PROCID}.xml \\\n/workspace/tests/multiprocess_gpu_test.py\nEOF\n"
},
{
"change_type": "MODIFY",
"old_path": "pytest.ini",
"new_path": "pytest.ini",
"diff": "[pytest]\n+markers =\n+ SlurmMultiNodeGpuTest: mark a test for Slurm multinode GPU nightly CI\nfilterwarnings =\nerror\nignore:No GPU/TPU found, falling back to CPU.:UserWarning\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/multiprocess_gpu_test.py",
"new_path": "tests/multiprocess_gpu_test.py",
"diff": "@@ -33,6 +33,11 @@ try:\nexcept ImportError:\nportpicker = None\n+try:\n+ import pytest\n+except ImportError:\n+ pytest = None\n+\nconfig.parse_flags_with_absl()\n@@ -151,8 +156,12 @@ class MultiProcessGpuTest(jtu.JaxTestCase):\n@unittest.skipIf(\nos.environ.get(\"SLURM_JOB_NUM_NODES\", None) != \"2\",\n\"Slurm environment with at least two nodes needed!\")\n+@unittest.skipIf(not pytest, \"Test requires pytest markers\")\nclass SlurmMultiNodeGpuTest(jtu.JaxTestCase):\n+ if pytest is not None:\n+ pytestmark = pytest.mark.SlurmMultiNodeGpuTest\n+\ndef test_gpu_multi_node_initialize_and_psum(self):\n# Hookup the ENV vars expected to be set already in the SLURM environment\n"
}
] | Python | Apache License 2.0 | google/jax | Add pytest marker inside the test only if pytest is present in the env |
260,335 | 06.09.2022 15:05:41 | 25,200 | 3c811b1520dbbea0f4eb929536444a21a8ae0a53 | fix bugs, infeed/outfeed must be considered effectful | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -439,6 +439,8 @@ def remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\nad.primitive_jvps[remat_p] = remat_jvp\nremat_allowed_effects: Set[core.Effect] = set()\n+remat_allowed_effects.add(lax.lax.InOutFeedEffect.Infeed)\n+remat_allowed_effects.add(lax.lax.InOutFeedEffect.Outfeed)\ndef remat_partial_eval(trace, *tracers, jaxpr, **params):\nassert not jaxpr.constvars\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/custom_derivatives.py",
"new_path": "jax/_src/custom_derivatives.py",
"diff": "@@ -26,6 +26,7 @@ from jax.tree_util import (tree_flatten, tree_unflatten, tree_map,\nregister_pytree_node_class, tree_leaves)\nfrom jax._src import custom_api_util\nfrom jax._src import dtypes\n+from jax._src.lax import lax\nfrom jax._src.util import cache, safe_zip, safe_map, split_list, Unhashable\nfrom jax._src.api_util import flatten_fun_nokwargs, argnums_partial\nfrom jax.core import raise_to_shaped\n@@ -339,6 +340,10 @@ def _apply_todos(todos, outs):\nallowed_effects: Set[core.Effect] = set()\n+allowed_effects.add(lax.InOutFeedEffect.Infeed)\n+allowed_effects.add(lax.InOutFeedEffect.Outfeed)\n+\n+\ncustom_jvp_call_p = CustomJVPCallPrimitive('custom_jvp_call')\ndef _custom_jvp_call_typecheck(*in_avals, call_jaxpr, jvp_jaxpr_thunk, num_consts):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/common.py",
"new_path": "jax/_src/lax/control_flow/common.py",
"diff": "@@ -21,6 +21,7 @@ from jax import core\nfrom jax import linear_util as lu\nfrom jax.api_util import flatten_fun_nokwargs\nfrom jax.interpreters import partial_eval as pe\n+from jax._src.lax import lax\nfrom jax._src import ad_util\nfrom jax._src import util\nfrom jax._src.util import cache, weakref_lru_cache, safe_map, unzip3\n@@ -29,6 +30,8 @@ from jax.tree_util import tree_map, tree_unflatten, tree_structure\nmap, unsafe_map = safe_map, map\nallowed_effects: Set[core.Effect] = set()\n+allowed_effects.add(lax.InOutFeedEffect.Infeed)\n+allowed_effects.add(lax.InOutFeedEffect.Outfeed)\ndef _abstractify(x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -4093,6 +4093,9 @@ def _after_all_lowering(ctx, *operands):\nmlir.register_lowering(after_all_p, _after_all_lowering)\n+InOutFeedEffect = enum.Enum('InOutFeedEffect', ['Infeed', 'Outfeed'])\n+\n+\ndef infeed(token, shape=None, partitions=None):\n\"\"\"Consumes an infeed value of `shape` from the host. Experimental.\n@@ -4118,13 +4121,14 @@ def infeed(token, shape=None, partitions=None):\ndef _infeed_abstract_eval(token, *, shapes, partitions):\nif token is not abstract_token:\nraise TypeError(\"First argument to infeed must be a token\")\n- return shapes + (abstract_token,)\n+ return (*shapes, abstract_token), {InOutFeedEffect.Infeed}\ninfeed_p = Primitive(\"infeed\")\ninfeed_p.multiple_results = True\ninfeed_p.def_impl(partial(xla.apply_primitive, infeed_p))\n-infeed_p.def_abstract_eval(_infeed_abstract_eval)\n+infeed_p.def_effectful_abstract_eval(_infeed_abstract_eval)\n+mlir.lowerable_effects.add(InOutFeedEffect.Infeed)\ndef _infeed_lowering(ctx, token, *, shapes, partitions):\n@@ -4170,11 +4174,12 @@ def outfeed(token, xs, partitions = None):\ndef _outfeed_abstract_eval(token, *xs, partitions):\nif token is not abstract_token:\nraise TypeError(\"First argument to outfeed must be a token\")\n- return abstract_token\n+ return abstract_token, {InOutFeedEffect.Outfeed}\noutfeed_p = Primitive(\"outfeed\")\noutfeed_p.def_impl(partial(xla.apply_primitive, outfeed_p))\n-outfeed_p.def_abstract_eval(_outfeed_abstract_eval)\n+outfeed_p.def_effectful_abstract_eval(_outfeed_abstract_eval)\n+mlir.lowerable_effects.add(InOutFeedEffect.Outfeed)\ndef _outfeed_lowering(ctx, token, *xs, partitions):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -208,6 +208,7 @@ class JaxprEqn(NamedTuple):\ndef replace(self, *args, **kwargs):\nreturn self._replace(*args, **kwargs)\n+# TODO(mattjj): call typecheck rules here, so we dont form bad eqns\ndef new_jaxpr_eqn(invars, outvars, primitive, params, effects, source_info=None):\nsource_info = source_info or source_info_util.new_source_info()\nif config.jax_enable_checks:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -2079,10 +2079,14 @@ def _pmap_partial_eval_custom_res_maker(params_known, aval):\ndef _pmap_dce_rule(used_outputs, eqn):\n# just like pe.dce_jaxpr_call_rule, except handles in_axes / out_axes\nnew_jaxpr, used_inputs = pe.dce_jaxpr(eqn.params['call_jaxpr'], used_outputs)\n+ _, donated_invars = partition_list(used_inputs, eqn.params['donated_invars'])\n+ _, glb_arg_shps = partition_list(used_inputs, eqn.params['global_arg_shapes'])\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+ new_params = dict(eqn.params, call_jaxpr=new_jaxpr,\n+ donated_invars=donated_invars,\n+ global_arg_shapes=glb_arg_shps,\n+ in_axes=tuple(in_axes), out_axes=tuple(out_axes))\nif not any(used_inputs) and not any(used_outputs) and not new_jaxpr.effects:\nreturn used_inputs, None\nelse:\n@@ -2682,6 +2686,7 @@ def lower_sharding_computation(\n# Device assignment across all inputs and outputs should be the same. This\n# is checked in pjit.\nif inp_device_assignment is not None:\n+ assert not in_shardings, \"if device_assignment given, no in_shardings\"\ndevice_assignment = inp_device_assignment\nbackend = xb.get_device_backend(device_assignment[0])\nfirst_sharding = None\n@@ -2743,7 +2748,7 @@ def lower_sharding_computation(\nif (not (jaxpr.effects or has_outfeed) and\n(not jaxpr.eqns and all(kept_outputs) or not jaxpr.outvars) and\nall(_is_unspecified(o) for o in out_shardings) and # type: ignore\n- not hasattr(backend, \"compile_replicated\")):\n+ not hasattr(backend, \"compile_replicated\")): # this means 'not pathways'\nreturn MeshComputation(\nstr(name_stack), None, True, donated_invars, jaxpr=jaxpr, consts=consts,\nglobal_in_avals=global_in_avals, global_out_avals=global_out_avals,\n"
}
] | Python | Apache License 2.0 | google/jax | fix bugs, infeed/outfeed must be considered effectful
Co-authored-by: Yash Katariya <yashkatariya@google.com>
Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com> |
260,411 | 03.09.2022 08:08:50 | -10,800 | f1fc7fe302148dad29c602031892970cab252714 | [jax2tf] Refactor the experimental_native_lowering path in jax2tf
This is part of a suite of refactorings aimed towards supporting
pjit by jax2tf experimental_native_lowering. The goal here is
to remove many references to internal JAX core APIs, and instead
use the AOT APIs: jax.jit(func_jax).lower(*args).
Only the experimental_native_lowering behavior should be affected. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -17,7 +17,7 @@ import contextlib\nimport os\nimport re\nimport threading\n-from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union, cast\n+from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union, cast\nfrom absl import logging\n@@ -180,10 +180,6 @@ class _ThreadLocalState(threading.local):\nself.constant_cache = None # None means that we don't use a cache. We\n# may be outside a conversion scope.\n- # Experimental flag to use the JAX native lowering.\n- self.experimental_native_lowering = False\n-\n-\n_thread_local_state = _ThreadLocalState()\ndef _get_current_name_stack() -> Union[NameStack, str]:\n@@ -323,9 +319,6 @@ def convert(fun_jax: Callable,\nprev_enable_xla = _thread_local_state.enable_xla\n_thread_local_state.enable_xla = enable_xla\n- prev_experimental_native_lowering = _thread_local_state.experimental_native_lowering\n- _thread_local_state.experimental_native_lowering = experimental_native_lowering\n-\nprev_include_xla_op_metadata = _thread_local_state.include_xla_op_metadata\n# TODO(b/189306134): implement support for XLA metadata\n_thread_local_state.include_xla_op_metadata = False\n@@ -343,7 +336,8 @@ def convert(fun_jax: Callable,\nouts_tf, out_avals = _interpret_fun_jax(fun_flat_jax,\nargs_flat_tf, args_avals_flat,\nname_stack,\n- fresh_constant_cache=True)\n+ fresh_constant_cache=True,\n+ experimental_native_lowering=experimental_native_lowering)\nreturn (tuple(outs_tf),\nmake_custom_gradient_fn_tf(\nfun_flat_jax=fun_flat_jax,\n@@ -356,7 +350,9 @@ def convert(fun_jax: Callable,\nelse:\nouts_tf, out_avals = _interpret_fun_jax(fun_flat_jax,\nargs_flat_tf, args_avals_flat,\n- name_stack, fresh_constant_cache=True)\n+ name_stack,\n+ fresh_constant_cache=True,\n+ experimental_native_lowering=experimental_native_lowering)\nmessage = (\"The jax2tf-converted function does not support gradients. \"\n\"Use `with_gradient` parameter to enable gradients\")\n# We use PreventGradient, which is propagated through a SavedModel.\n@@ -367,7 +363,6 @@ def convert(fun_jax: Callable,\nfinally:\n_thread_local_state.shape_env = ()\n_thread_local_state.enable_xla = prev_enable_xla\n- _thread_local_state.experimental_native_lowering = prev_experimental_native_lowering\n_thread_local_state.include_xla_op_metadata = prev_include_xla_op_metadata\nout_flat_tf = [tf.identity(x, \"jax2tf_out\") for x in out_flat_tf]\n@@ -538,30 +533,33 @@ def _extended_name_stack(extra_name_stack: Optional[str]):\ndef _interpret_fun_jax(\nfun_jax: Callable,\n- in_vals_tf: Sequence[TfVal],\n- in_avals: Sequence[core.ShapedArray],\n+ args_tf: Sequence[TfVal],\n+ args_avals: Sequence[core.ShapedArray],\nextra_name_stack: Optional[str],\n- fresh_constant_cache: bool = False\n+ fresh_constant_cache: bool = False,\n+ experimental_native_lowering: bool = False\n) -> Tuple[Sequence[TfVal], Tuple[core.ShapedArray]]:\n- if _thread_local_state.experimental_native_lowering:\n- return util.unzip2(_lower_native(fun_jax, in_vals_tf, in_avals, extra_name_stack))\n+ if experimental_native_lowering:\n+ del extra_name_stack\n+ return _lower_native_and_run(fun_jax, args_avals, args_tf)\nelse:\nwith core.new_base_main(TensorFlowTrace) as main: # type: ignore\n- subtrace_fun = _interpret_subtrace(lu.wrap_init(fun_jax), main, in_avals)\n+ subtrace_fun = _interpret_subtrace(lu.wrap_init(fun_jax), main, args_avals)\nwith _extended_name_stack(extra_name_stack):\nwith core.new_sublevel():\nout_vals: Sequence[Tuple[TfVal, core.ShapedArray]] = \\\n- _call_wrapped_with_new_constant_cache(subtrace_fun, in_vals_tf,\n+ _call_wrapped_with_new_constant_cache(subtrace_fun, args_tf,\nfresh_constant_cache=fresh_constant_cache)\ndel main\nreturn util.unzip2(out_vals)\n-def _lower_native(fun_jax: Callable, in_vals_tf: Sequence[TfVal],\n- in_avals: Sequence[core.ShapedArray],\n- extra_name_stack: Optional[str]):\n- \"\"\"Lowers the function using native lowering.\n+def _lower_native_and_run(fun_jax: Callable,\n+ args_avals: Sequence[core.ShapedArray],\n+ args_tf: Sequence[TfVal],\n+ ) -> Tuple[Sequence[TfVal], Tuple[core.ShapedArray]]:\n+ \"\"\"Lowers the function using native lowering and then invokes it.\nWork-in-progress.\n@@ -570,63 +568,46 @@ def _lower_native(fun_jax: Callable, in_vals_tf: Sequence[TfVal],\nSpecial care must be taken in presence of shape polymorphism.\n\"\"\"\n- lu_fun = lu.wrap_init(fun_jax)\n# Look for shape polymorphism\n- abstract_axes: Sequence[Dict[int, str]] = [] # one for each argument\n- for aval in in_avals:\n+ # For each arg, map axis idx to dimension variable name\n+ abstracted_axes: Sequence[Dict[int, str]] = []\n+ # For each dimension variable, encode how to compute its value from the\n+ # shape of the explicit arguments. E.g., \"2.1\" denotes args_tf[2].shape[1].\n+ # Note: We assume that lowering will introduce dim args in the order in which\n+ # dim variables are first seen when scanning the explicit arguments\n+ # in order and then scanning their shapes for dim variables.\n+ dim_args_spec: List[str] = []\n+ dim_vars_seen: Set[str] = set()\n+ for arg_idx, aval in enumerate(args_avals):\none_abstract_axes = {}\n- for i, d in enumerate(aval.shape):\n+ for axis_idx, d in enumerate(aval.shape):\nif not core.is_constant_dim(d):\nd_var = d.to_var()\nif d_var is None:\n- raise ValueError(f\"Only simple variables supported: {aval.shape}\")\n- one_abstract_axes[i] = d_var\n- abstract_axes.append(one_abstract_axes)\n- if any(abstract_axes):\n+ raise ValueError(f\"Only simple dimension variables supported: {aval.shape}\")\n+ if not d_var in dim_vars_seen:\n+ dim_args_spec.append(f\"{arg_idx}.{axis_idx}\")\n+ dim_vars_seen.add(d_var)\n+ one_abstract_axes[axis_idx] = d_var\n+ abstracted_axes.append(one_abstract_axes)\n+\n+ if any(abstracted_axes):\nif not config.jax_dynamic_shapes:\nraise ValueError(\n- \"Found shape polymorphism but --jax_dynamic_shapes is not on\")\n- # In order to use infer_input_type, we must manufacture some JAX arguments.\n- # Actually the only thing that matters is that get_aval(x) and x.shape work for them.\n- # This is a hack, should find a way to refactor infer_lambda_input_type so that we\n- # can reuse it here more cleanly.\n- top_trace = core.find_top_trace(())\n- fake_vals_jax = [\n- TensorFlowTracer(top_trace, val, aval) # type: ignore\n- for val, aval in zip(in_vals_tf, in_avals)\n- ]\n- in_type = partial_eval.infer_lambda_input_type(abstract_axes, fake_vals_jax) # type: ignore\n- lu_fun = lu.annotate(lu_fun, in_type)\n- arg_specs = [(None, None) for _ in in_avals]\n-\n- nr_dim_vars = 0\n- # For each dimension variable, encode how to compute its value from the\n- # shape of the explicit arguments. E.g., \"2.1\" denotes args[2].shape[1]\n- dim_args_spec_dict: Dict[int, str] = {}\n- for arg_idx, (arg_aval, is_explicit) in enumerate(in_type):\n- if not is_explicit:\n- nr_dim_vars += 1\n- else:\n- for i, d in enumerate(arg_aval.shape):\n- if isinstance(d, core.DBIdx) and d.val not in dim_args_spec_dict:\n- dim_args_spec_dict[d.val] = f\"{arg_idx - nr_dim_vars}.{i}\"\n- dim_args_spec = [dim_args_spec_dict[i] for i in range(nr_dim_vars)]\n+ \"Found shape polymorphism but --jax_dynamic_shapes is not set\")\n+ abstracted_axes = tuple(abstracted_axes)\nelse:\n- arg_specs = [(aval, None) for aval in in_avals] # type: ignore\n- dim_args_spec = []\n+ abstracted_axes = None # type: ignore\n+ arg_specs_jax = [\n+ jax.ShapeDtypeStruct(aval.shape, aval.dtype)\n+ for aval in args_avals\n+ ]\n# TODO: specify the backend for experimental_native_lowering\n- device = None\nbackend = jax.default_backend()\n- lowered = dispatch.lower_xla_callable(\n- lu_fun,\n- device,\n- backend,\n- extra_name_stack,\n- (False,) * len(in_avals), # donated\n- True, # always_lower,\n- True, # keep_unused\n- *arg_specs)\n+ lowered = jax.jit(fun_jax, backend=backend,\n+ keep_unused=True, # TODO: allow dropping unused\n+ abstracted_axes=abstracted_axes).lower(*arg_specs_jax)._lowering\nmhlo_module = lowered.mhlo()\nmhlo_module_text = mlir.module_to_string(mhlo_module)\n@@ -652,7 +633,7 @@ def _lower_native(fun_jax: Callable, in_vals_tf: Sequence[TfVal],\n# Figure out the result types and shapes\nout_avals = lowered.compile_args[\"out_avals\"]\n- # TODO: handle d being InDBIdx\n+ # TODO(necula): handle d being InDBIdx\nout_shapes = tuple(\ntuple(d if type(d) is int else None\nfor d in out_aval.shape)\n@@ -665,7 +646,7 @@ def _lower_native(fun_jax: Callable, in_vals_tf: Sequence[TfVal],\nout_types = tuple(_out_type(out_aval.dtype) for out_aval in out_avals)\nres = tfxla.call_module(\n- in_vals_tf,\n+ args_tf,\nmodule=mhlo_module_text,\nTout=out_types,\nSout=out_shapes,\n@@ -682,7 +663,7 @@ def _lower_native(fun_jax: Callable, in_vals_tf: Sequence[TfVal],\nres = tuple(\n_convert_res(res_val, out_aval.dtype)\nfor res_val, out_aval in zip(res, out_avals))\n- return zip(res, out_avals)\n+ return res, out_avals\ndef _fixup_mhlo_module_text(mhlo_module_text: str) -> str:\n# A workaround for MHLO not (yet) having backwards compatibility. With\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -488,8 +488,8 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ndict(testcase_name=f\"function={with_function}\",\nwith_function=with_function)\nfor with_function in [False, True]))\n- def test_gradients_unused_argument_readme(self, with_function=True):\n- # x2 and x3 are not used. x3 has integer type.\n+ def test_gradients_unused_argument_readme(self, with_function=False):\n+ # x1 and x3 are not used. x3 has integer type.\ndef fn(x0, x1, x2, x3):\nreturn x0 * 0. + x2 * 2.\n@@ -536,7 +536,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ndict(testcase_name=f\"function={with_function}\",\nwith_function=with_function)\nfor with_function in [False, True]))\n- def test_gradients_int_argument(self, with_function=True):\n+ def test_gradients_int_argument(self, with_function=False):\n# https://github.com/google/jax/issues/6975\n# Also issue #6975.\n# An expanded version of test_gradients_unused_argument\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Refactor the experimental_native_lowering path in jax2tf
This is part of a suite of refactorings aimed towards supporting
pjit by jax2tf experimental_native_lowering. The goal here is
to remove many references to internal JAX core APIs, and instead
use the AOT APIs: jax.jit(func_jax).lower(*args).
Only the experimental_native_lowering behavior should be affected. |
260,424 | 07.09.2022 06:34:52 | 25,200 | 79a74f37fad6def73788f3febec8480dda4f085f | Rollback of Breaks internal target with `NotImplementedError: Differentiation rule for 'assert' not implemented` | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -125,11 +125,11 @@ init_error = Error(False, 0, {})\nnext_code = it.count(1).__next__ # globally unique ids, could be uuid4\n-def assert_func(error: Error, err: Bool, msg: str,\n+def assert_func(error: Error, pred: Bool, msg: str,\npayload: Optional[Payload]) -> Error:\ncode = next_code()\npayload = init_payload() if payload is None else payload\n- out_err = error.err | err\n+ out_err = error.err | jnp.logical_not(pred)\nout_code = lax.select(error.err, error.code, code)\nout_payload = lax.select(error.err, error.payload, payload)\nreturn Error(out_err, out_code, {code: msg, **error.msgs}, out_payload)\n@@ -462,20 +462,20 @@ def check_error(error: Error) -> None:\nerr, code, payload = error.err, error.code, error.payload\nerr = core.raise_as_much_as_possible(err)\n- return assert_p.bind(err, code, payload, msgs=error.msgs)\n+ return assert_p.bind(~err, code, payload, msgs=error.msgs)\nassert_p = core.Primitive('assert') # TODO: rename to check?\nassert_p.multiple_results = True # zero results\n@assert_p.def_impl\n-def assert_impl(err, code, payload, *, msgs):\n- Error(err, code, msgs, payload).throw()\n+def assert_impl(pred, code, payload, *, msgs):\n+ Error(~pred, code, msgs, payload).throw()\nreturn []\nCheckEffect = object()\n@assert_p.def_effectful_abstract_eval\n-def assert_abstract_eval(err, code, payload, *, msgs):\n+def assert_abstract_eval(pred, code, payload, *, msgs):\nreturn [], {CheckEffect}\ndef assert_lowering_rule(*a, **k):\n@@ -494,9 +494,9 @@ cf.allowed_effects.add(CheckEffect)\ndef assert_batching_rule(batched_args, batch_dims, *, msgs):\nsize = next(x.shape[dim] for x, dim in zip(batched_args, batch_dims)\nif dim is not batching.not_mapped)\n- err, code, payload = (batching.bdim_at_front(a, d, size)\n+ pred, code, payload = (batching.bdim_at_front(a, d, size)\nfor a, d in zip(batched_args, batch_dims))\n- err = Error(err, code, msgs, payload)\n+ err = Error(jnp.logical_not(pred), code, msgs, payload)\ncheck_error(err)\nreturn [], []\n@@ -511,9 +511,9 @@ def nan_error_check(prim, error, enabled_errors, *in_vals, **params):\nout = prim.bind(*in_vals, **params)\nif ErrorCategory.NAN not in enabled_errors:\nreturn out, error\n- any_nans = jnp.any(jnp.isnan(out))\n- msg = f'nan generated by primitive {prim.name} at {summary()}'\n- return out, assert_func(error, any_nans, msg, None)\n+ no_nans = jnp.logical_not(jnp.any(jnp.isnan(out)))\n+ msg = f\"nan generated by primitive {prim.name} at {summary()}\"\n+ return out, assert_func(error, no_nans, msg, None)\ndef gather_error_check(error, enabled_errors, operand, start_indices, *,\ndimension_numbers, slice_sizes, unique_indices,\n@@ -534,10 +534,10 @@ def gather_error_check(error, enabled_errors, operand, start_indices, *,\nupper_bound = operand_dims[np.array(dnums.start_index_map)]\nupper_bound -= np.array(slice_sizes)[np.array(dnums.start_index_map)]\nupper_bound = jnp.expand_dims(upper_bound, axis=tuple(range(num_batch_dims)))\n- out_of_bounds = (start_indices < 0) | (start_indices > upper_bound.astype(start_indices.dtype))\n+ in_bounds = (start_indices >= 0) & (start_indices <= upper_bound.astype(start_indices.dtype))\n# Get first OOB index, axis and axis size so it can be added to the error msg.\n- flat_idx = jnp.argmin(jnp.logical_not(out_of_bounds))\n+ flat_idx = jnp.argmin(in_bounds)\nmulti_idx = jnp.unravel_index(flat_idx, start_indices.shape)\noob_axis = jnp.array(dnums.start_index_map)[multi_idx[-1]]\noob_axis_size = jnp.array(operand.shape)[oob_axis]\n@@ -549,19 +549,19 @@ def gather_error_check(error, enabled_errors, operand, start_indices, *,\n'index {payload0} is out of bounds for axis {payload1} '\n'with size {payload2}.')\n- return out, assert_func(error, jnp.any(out_of_bounds), msg, payload)\n+ return out, assert_func(error, jnp.all(in_bounds), msg, payload)\nerror_checks[lax.gather_p] = gather_error_check\ndef div_error_check(error, enabled_errors, x, y):\n\"\"\"Checks for division by zero and NaN.\"\"\"\nif ErrorCategory.DIV in enabled_errors:\n- any_zero = jnp.any(jnp.equal(y, 0))\n+ all_nonzero = jnp.logical_not(jnp.any(jnp.equal(y, 0)))\nmsg = f'divided by zero at {summary()}'\n- error = assert_func(error, any_zero, msg, None)\n+ error = assert_func(error, all_nonzero, msg, None)\nreturn nan_error_check(lax.div_p, error, enabled_errors, x, y)\nerror_checks[lax.div_p] = div_error_check\n-def scatter_oob(operand, indices, updates, dnums):\n+def scatter_in_bounds(operand, indices, updates, dnums):\n# Ref: see clamping code used in scatter_translation_rule\nslice_sizes = []\npos = 0\n@@ -579,9 +579,9 @@ def scatter_oob(operand, indices, updates, dnums):\nupper_bound = lax.broadcast_in_dim(upper_bound, indices.shape,\n(len(indices.shape) - 1,))\n- lower_oob = jnp.any(jnp.less(indices, 0))\n- upper_oob = jnp.any(jnp.greater(indices, upper_bound.astype(indices.dtype)))\n- return jnp.logical_or(lower_oob, upper_oob)\n+ lower_in_bounds = jnp.all(jnp.greater_equal(indices, 0))\n+ upper_in_bounds = jnp.all(jnp.less_equal(indices, upper_bound.astype(indices.dtype)))\n+ return jnp.logical_and(lower_in_bounds, upper_in_bounds)\ndef scatter_error_check(prim, error, enabled_errors, operand, indices, updates,\n*, update_jaxpr, update_consts, dimension_numbers,\n@@ -596,13 +596,13 @@ def scatter_error_check(prim, error, enabled_errors, operand, indices, updates,\nif ErrorCategory.OOB not in enabled_errors:\nreturn out, error\n- out_of_bounds = scatter_oob(operand, indices, updates, dimension_numbers)\n+ in_bounds = scatter_in_bounds(operand, indices, updates, dimension_numbers)\noob_msg = f'out-of-bounds indexing while updating at {summary()}'\n- oob_error = assert_func(error, out_of_bounds, oob_msg, None)\n+ oob_error = assert_func(error, in_bounds, oob_msg, None)\n- any_nans = jnp.any(jnp.isnan(out))\n+ no_nans = jnp.logical_not(jnp.any(jnp.isnan(out)))\nnan_msg = f'nan generated by primitive {prim.name} at {summary()}'\n- return out, assert_func(oob_error, any_nans, nan_msg, None)\n+ return out, assert_func(oob_error, no_nans, nan_msg, None)\nerror_checks[lax.scatter_p] = partial(scatter_error_check, lax.scatter_p)\nerror_checks[lax.scatter_add_p] = partial(scatter_error_check, lax.scatter_add_p)\nerror_checks[lax.scatter_mul_p] = partial(scatter_error_check, lax.scatter_mul_p)\n@@ -786,11 +786,11 @@ add_nan_check(lax.max_p)\nadd_nan_check(lax.min_p)\n-def assert_discharge_rule(error, enabled_errors, err, code, payload, *, msgs):\n+def assert_discharge_rule(error, enabled_errors, pred, code, payload, *, msgs):\nif ErrorCategory.USER_CHECK not in enabled_errors:\nreturn [], error\n- out_err = error.err | err\n+ out_err = error.err | jnp.logical_not(pred)\nout_code = lax.select(error.err, error.code, code)\nreturn [], Error(out_err, out_code, {**error.msgs, **msgs}, payload)\nerror_checks[assert_p] = assert_discharge_rule\n"
}
] | Python | Apache License 2.0 | google/jax | Rollback of #12232: Breaks internal target with `NotImplementedError: Differentiation rule for 'assert' not implemented`
PiperOrigin-RevId: 472709946 |
260,631 | 08.09.2022 03:59:30 | 25,200 | 14f1a345a147da244db46f2165709736eed27ad0 | roll back breakage | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/ad_checkpoint.py",
"new_path": "jax/_src/ad_checkpoint.py",
"diff": "@@ -439,8 +439,6 @@ def remat_jvp(primals, tangents, jaxpr, prevent_cse, differentiated, policy):\nad.primitive_jvps[remat_p] = remat_jvp\nremat_allowed_effects: Set[core.Effect] = set()\n-remat_allowed_effects.add(lax.lax.InOutFeedEffect.Infeed)\n-remat_allowed_effects.add(lax.lax.InOutFeedEffect.Outfeed)\ndef remat_partial_eval(trace, *tracers, jaxpr, **params):\nassert not jaxpr.constvars\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/custom_derivatives.py",
"new_path": "jax/_src/custom_derivatives.py",
"diff": "@@ -26,7 +26,6 @@ from jax.tree_util import (tree_flatten, tree_unflatten, tree_map,\nregister_pytree_node_class, tree_leaves)\nfrom jax._src import custom_api_util\nfrom jax._src import dtypes\n-from jax._src.lax import lax\nfrom jax._src.util import cache, safe_zip, safe_map, split_list, Unhashable\nfrom jax._src.api_util import flatten_fun_nokwargs, argnums_partial\nfrom jax.core import raise_to_shaped\n@@ -340,10 +339,6 @@ def _apply_todos(todos, outs):\nallowed_effects: Set[core.Effect] = set()\n-allowed_effects.add(lax.InOutFeedEffect.Infeed)\n-allowed_effects.add(lax.InOutFeedEffect.Outfeed)\n-\n-\ncustom_jvp_call_p = CustomJVPCallPrimitive('custom_jvp_call')\ndef _custom_jvp_call_typecheck(*in_avals, call_jaxpr, jvp_jaxpr_thunk, num_consts):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/dispatch.py",
"new_path": "jax/_src/dispatch.py",
"diff": "@@ -316,11 +316,6 @@ def sharded_lowering(fun, device, backend, name, donated_invars, keep_unused,\n\"programming model, please read \"\n\"https://jax.readthedocs.io/en/latest/multi_process.html.\")\n- if not in_shardings:\n- inp_device_assignment = da\n- else:\n- inp_device_assignment = None\n-\n# Pass in a singleton `_UNSPECIFIED` for out_shardings because we don't know\n# the number of output avals at this stage. lower_sharding_computation will\n# apply it to all out_avals.\n@@ -328,13 +323,15 @@ def sharded_lowering(fun, device, backend, name, donated_invars, keep_unused,\nfun, 'jit', name, in_shardings, pjit._UNSPECIFIED,\ndonated_invars, in_avals,\nin_is_global=(True,) * len(arg_specs), keep_unused=keep_unused,\n- committed=committed, inp_device_assignment=inp_device_assignment).compile(\n+ committed=committed).compile(\n_allow_propagation_to_outputs=True).unsafe_call\ndef _xla_callable_uncached(fun: lu.WrappedFun, device, backend, name,\ndonated_invars, keep_unused, *arg_specs):\n- if config.jax_array:\n+ # TODO(yashkatariya): Remove the `and arg_specs` from here once\n+ # lower_sharding_computation supports no avals as input.\n+ if config.jax_array and arg_specs:\nreturn sharded_lowering(fun, device, backend, name,\ndonated_invars, keep_unused, *arg_specs)\nelse:\n@@ -344,13 +341,6 @@ def _xla_callable_uncached(fun: lu.WrappedFun, device, backend, name,\nxla_callable = lu.cache(_xla_callable_uncached)\n-def is_single_device_sharding(sharding) -> bool:\n- from jax.experimental.sharding import PmapSharding\n- # Special case PmapSharding here because PmapSharding maps away an axis\n- # and needs to be handled separately.\n- return len(sharding.device_set) == 1 and not isinstance(sharding, PmapSharding)\n-\n-\n@contextlib.contextmanager\ndef log_elapsed_time(fmt: str):\nif _on_exit:\n@@ -541,11 +531,19 @@ def jaxpr_has_bints(jaxpr: core.Jaxpr) -> bool:\ndef _prune_unused_inputs(\njaxpr: core.Jaxpr) -> Tuple[core.Jaxpr, Set[int], Set[int]]:\n- used_outputs = [True] * len(jaxpr.outvars)\n- new_jaxpr, used_consts, used_inputs = pe.dce_jaxpr_consts(jaxpr, used_outputs)\n- kept_const_idx = {i for i, b in enumerate(used_consts) if b}\n- kept_var_idx = {i for i, b in enumerate(used_inputs) if b}\n- return new_jaxpr, kept_const_idx, kept_var_idx\n+ used = {v for v in jaxpr.outvars if isinstance(v, core.Var)}\n+ # TODO(zhangqiaorjc): Improve the DCE algorithm by also pruning primitive\n+ # applications that do not produce used outputs. Must handle side-effecting\n+ # primitives and nested jaxpr.\n+ used.update(\n+ v for eqn in jaxpr.eqns for v in eqn.invars if isinstance(v, core.Var))\n+ kept_const_idx, new_constvars = util.unzip2(\n+ (i, v) for i, v in enumerate(jaxpr.constvars) if v in used)\n+ kept_var_idx, new_invars = util.unzip2(\n+ (i, v) for i, v in enumerate(jaxpr.invars) if v in used)\n+ new_jaxpr = core.Jaxpr(new_constvars, new_invars, jaxpr.outvars, jaxpr.eqns,\n+ jaxpr.effects)\n+ return new_jaxpr, set(kept_const_idx), set(kept_var_idx)\n# We can optionally set a Jaxpr rewriter that can be applied just before\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/common.py",
"new_path": "jax/_src/lax/control_flow/common.py",
"diff": "@@ -21,7 +21,6 @@ from jax import core\nfrom jax import linear_util as lu\nfrom jax.api_util import flatten_fun_nokwargs\nfrom jax.interpreters import partial_eval as pe\n-from jax._src.lax import lax\nfrom jax._src import ad_util\nfrom jax._src import util\nfrom jax._src.util import cache, weakref_lru_cache, safe_map, unzip3\n@@ -30,8 +29,6 @@ from jax.tree_util import tree_map, tree_unflatten, tree_structure\nmap, unsafe_map = safe_map, map\nallowed_effects: Set[core.Effect] = set()\n-allowed_effects.add(lax.InOutFeedEffect.Infeed)\n-allowed_effects.add(lax.InOutFeedEffect.Outfeed)\ndef _abstractify(x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -30,7 +30,6 @@ from jax._src import ad_util\nfrom jax._src import api\nfrom jax._src import api_util\nfrom jax._src import device_array\n-from jax._src import dispatch\nfrom jax import linear_util as lu\nfrom jax._src import dtypes\nfrom jax import tree_util\n@@ -1327,7 +1326,7 @@ def full_like(x: Array, fill_value: Array, dtype: Optional[DType] = None,\n# (so it works in staged-out code as well as 'eager' code). Related to\n# equi-sharding.\nif (config.jax_array and hasattr(x, 'sharding') and\n- not dispatch.is_single_device_sharding(x.sharding)):\n+ not isinstance(x.sharding, sharding.SingleDeviceSharding)):\nreturn array.make_array_from_callback(\nfill_shape, x.sharding, lambda idx: val[idx]) # type: ignore[arg-type]\nreturn val\n@@ -4109,9 +4108,6 @@ def _after_all_lowering(ctx, *operands):\nmlir.register_lowering(after_all_p, _after_all_lowering)\n-InOutFeedEffect = enum.Enum('InOutFeedEffect', ['Infeed', 'Outfeed'])\n-\n-\ndef infeed(token, shape=None, partitions=None):\n\"\"\"Consumes an infeed value of `shape` from the host. Experimental.\n@@ -4137,14 +4133,13 @@ def infeed(token, shape=None, partitions=None):\ndef _infeed_abstract_eval(token, *, shapes, partitions):\nif token is not abstract_token:\nraise TypeError(\"First argument to infeed must be a token\")\n- return (*shapes, abstract_token), {InOutFeedEffect.Infeed}\n+ return shapes + (abstract_token,)\ninfeed_p = Primitive(\"infeed\")\ninfeed_p.multiple_results = True\ninfeed_p.def_impl(partial(xla.apply_primitive, infeed_p))\n-infeed_p.def_effectful_abstract_eval(_infeed_abstract_eval)\n-mlir.lowerable_effects.add(InOutFeedEffect.Infeed)\n+infeed_p.def_abstract_eval(_infeed_abstract_eval)\ndef _infeed_lowering(ctx, token, *, shapes, partitions):\n@@ -4190,12 +4185,11 @@ def outfeed(token, xs, partitions = None):\ndef _outfeed_abstract_eval(token, *xs, partitions):\nif token is not abstract_token:\nraise TypeError(\"First argument to outfeed must be a token\")\n- return abstract_token, {InOutFeedEffect.Outfeed}\n+ return abstract_token\noutfeed_p = Primitive(\"outfeed\")\noutfeed_p.def_impl(partial(xla.apply_primitive, outfeed_p))\n-outfeed_p.def_effectful_abstract_eval(_outfeed_abstract_eval)\n-mlir.lowerable_effects.add(InOutFeedEffect.Outfeed)\n+outfeed_p.def_abstract_eval(_outfeed_abstract_eval)\ndef _outfeed_lowering(ctx, token, *xs, partitions):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/prng.py",
"new_path": "jax/_src/prng.py",
"diff": "@@ -31,7 +31,7 @@ from jax.interpreters import mlir\nfrom jax.interpreters import pxla\nfrom jax.interpreters import xla\nfrom jax.experimental.sharding import (\n- MeshPspecSharding, PmapSharding, OpShardingSharding)\n+ MeshPspecSharding, SingleDeviceSharding, PmapSharding, OpShardingSharding)\nfrom jax._src import dispatch\nfrom jax._src import dtypes\n@@ -364,7 +364,7 @@ class KeyTyRules:\nphys_handler_maker = pxla.global_result_handlers[\n(core.ShapedArray, output_type)]\n- if dispatch.is_single_device_sharding(out_sharding):\n+ if isinstance(out_sharding, SingleDeviceSharding):\nphys_sharding = out_sharding\nelif isinstance(out_sharding, MeshPspecSharding):\ntrailing_spec = [None] * len(key_shape)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -208,7 +208,6 @@ class JaxprEqn(NamedTuple):\ndef replace(self, *args, **kwargs):\nreturn self._replace(*args, **kwargs)\n-# TODO(mattjj): call typecheck rules here, so we don't form bad eqns\ndef new_jaxpr_eqn(invars, outvars, primitive, params, effects, source_info=None):\nsource_info = source_info or source_info_util.new_source_info()\nif config.jax_enable_checks:\n@@ -2163,7 +2162,6 @@ aval_mapping_handlers: Dict[Type, AvalMapHandlerPair] = {\nDShapedArray: (_map_dshaped_array, _unmap_dshaped_array),\nShapedArray: (_map_shaped_array, _unmap_shaped_array),\nConcreteArray: (_map_shaped_array, _unmap_shaped_array),\n- AbstractToken: (lambda _, __, a: a, lambda _, __, ___, a: a)\n}\n@contextmanager\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/array.py",
"new_path": "jax/experimental/array.py",
"diff": "@@ -451,7 +451,7 @@ def _device_put_array(x, device: Optional[Device]):\n# TODO(yashkatariya): Remove this restriction and the round trip via host\n# once lowering to XLA goes through `lower_mesh_computation`.\nassert x.is_fully_addressable()\n- if dispatch.is_single_device_sharding(x.sharding):\n+ if isinstance(x.sharding, SingleDeviceSharding):\nx = dispatch._copy_device_array_to_device(pxla._set_aval(x._arrays[0]), device)\nreturn (x,)\nelse:\n@@ -462,7 +462,7 @@ dispatch.device_put_handlers[Array] = _device_put_array\ndef _array_pmap_shard_arg(x, devices, indices, mode):\n- if dispatch.is_single_device_sharding(x.sharding):\n+ if isinstance(x.sharding, SingleDeviceSharding):\nreturn pxla._shard_device_array(x, devices, indices, mode)\nif x._fast_path_args is None:\n@@ -484,7 +484,7 @@ def _array_shard_arg(x, devices, indices, mode):\nif mode == pxla.InputsHandlerMode.pmap:\nreturn _array_pmap_shard_arg(x, devices, indices, mode)\nelse:\n- if dispatch.is_single_device_sharding(x.sharding):\n+ if isinstance(x.sharding, SingleDeviceSharding):\nreturn [buf if buf.device() == d else buf.copy_to_device(d)\nfor buf, d in safe_zip(x._arrays, devices)]\n# If PmapSharding exists, then do a round trip via host. This will happen\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -961,17 +961,6 @@ def convert_constvars_jaxpr(jaxpr: Jaxpr) -> Jaxpr:\nconfig.jax_enable_checks and core.check_jaxpr(lifted_jaxpr)\nreturn lifted_jaxpr\n-@weakref_lru_cache\n-def convert_invars_to_constvars(jaxpr: Jaxpr, n: int) -> Jaxpr:\n- \"\"\"Move n invars to constvars. Like an inverse of convert_constvars_Jaxpr.\"\"\"\n- config.jax_enable_checks and core.check_jaxpr(jaxpr)\n- constvars, invars = split_list(jaxpr.invars, [n])\n- lifted_jaxpr = Jaxpr(constvars=tuple(constvars), invars=invars,\n- outvars=jaxpr.outvars, eqns=jaxpr.eqns,\n- effects=jaxpr.effects)\n- config.jax_enable_checks and core.check_jaxpr(lifted_jaxpr)\n- return lifted_jaxpr\n-\ndef convert_envvars_to_constvars(jaxpr: Jaxpr, num_env_vars: int) -> Jaxpr:\nconfig.jax_enable_checks and core.check_jaxpr(jaxpr)\nenv_vars, invars = split_list(jaxpr.invars, [num_env_vars])\n@@ -1317,17 +1306,6 @@ def dce_jaxpr(jaxpr: Jaxpr, used_outputs: Sequence[bool],\ninstantiate = (instantiate,) * len(jaxpr.invars)\nreturn _dce_jaxpr(jaxpr, tuple(used_outputs), tuple(instantiate))\n-\n-def dce_jaxpr_consts(jaxpr: Jaxpr, used_outputs: Sequence[bool],\n- instantiate: Union[bool, Sequence[bool]] = False,\n- ) -> Tuple[Jaxpr, List[bool], List[bool]]:\n- jaxpr_ = convert_constvars_jaxpr(jaxpr)\n- new_jaxpr_, used_inputs_ = dce_jaxpr(jaxpr_, used_outputs)\n- used_consts, used_inputs = split_list(used_inputs_, [len(jaxpr.constvars)])\n- new_jaxpr = convert_invars_to_constvars(new_jaxpr_, sum(used_consts))\n- return new_jaxpr, used_consts, used_inputs\n-\n-\n@weakref_lru_cache\ndef _dce_jaxpr(jaxpr: Jaxpr, used_outputs: Tuple[bool, ...],\ninstantiate: Tuple[bool, ...]\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -2081,13 +2081,10 @@ def _pmap_partial_eval_custom_res_maker(params_known, aval):\ndef _pmap_dce_rule(used_outputs, eqn):\n# just like pe.dce_jaxpr_call_rule, except handles in_axes / out_axes\nnew_jaxpr, used_inputs = pe.dce_jaxpr(eqn.params['call_jaxpr'], used_outputs)\n- _, donated_invars = partition_list(used_inputs, eqn.params['donated_invars'])\n- # TODO(yashkatariya,mattjj): Handle global_arg_shapes here too.\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,\n- donated_invars=tuple(donated_invars),\n- in_axes=tuple(in_axes), out_axes=tuple(out_axes))\n+ new_params = dict(eqn.params, call_jaxpr=new_jaxpr, in_axes=tuple(in_axes),\n+ out_axes=tuple(out_axes))\nif not any(used_inputs) and not any(used_outputs) and not new_jaxpr.effects:\nreturn used_inputs, None\nelse:\n@@ -2675,8 +2672,7 @@ def lower_sharding_computation(\nglobal_in_avals: Sequence[core.ShapedArray],\nin_is_global: Sequence[bool],\nkeep_unused: bool,\n- committed: bool,\n- inp_device_assignment: Optional[Sequence[xc.Device]] = None):\n+ committed: bool):\n\"\"\"Lowers a computation to XLA. It can take arbitrary shardings as input.\nThe caller of this code can pass in a singleton _UNSPECIFIED because the\n@@ -2686,21 +2682,12 @@ def lower_sharding_computation(\n\"\"\"\n# Device assignment across all inputs and outputs should be the same. This\n# is checked in pjit.\n- if inp_device_assignment is not None:\n- from jax.experimental.sharding import SingleDeviceSharding\n- assert not in_shardings, \"if device_assignment given, no in_shardings\"\n- # TODO(yashkatariya): Look into allowing more than 1 device here.\n- assert len(inp_device_assignment) == 1\n- device_assignment = inp_device_assignment\n- backend = xb.get_device_backend(device_assignment[0])\n- first_sharding = SingleDeviceSharding(device_assignment[0])\n- else:\nif _is_unspecified(out_shardings):\n- backend, first_sharding = _get_backend_from_shardings(in_shardings) # type: ignore\n+ backend, first_sharding = _get_backend_from_shardings(in_shardings)\nelse:\n# type ignore because mypy can't understand that out_shardings that are\n# UNSPECIFIED singleton are filtered above.\n- backend, first_sharding = _get_backend_from_shardings( # type: ignore\n+ backend, first_sharding = _get_backend_from_shardings(\nit.chain(in_shardings, out_shardings)) # type: ignore\ndevice_assignment = first_sharding._device_assignment\n@@ -2711,7 +2698,6 @@ def lower_sharding_computation(\n\"in {elapsed_time} sec\"):\njaxpr, global_out_avals, consts = pe.trace_to_jaxpr_final(\nfun, global_in_avals, debug_info=pe.debug_info_final(fun, api_name))\n- kept_outputs = [True] * len(global_out_avals)\nlog_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG\nlogging.log(log_priority,\n@@ -2737,29 +2723,10 @@ def lower_sharding_computation(\ndonated_invars = tuple(x for i, x in enumerate(donated_invars) if i in kept_var_idx)\ndel kept_const_idx\n- process_index = xb.process_index()\n- local_device_assignment = [d for d in device_assignment\n- if d.process_index == process_index]\n- if len(device_assignment) != len(local_device_assignment):\n+ if not first_sharding.is_fully_addressable():\ncheck_multihost_collective_allowlist(jaxpr)\n-\n- has_outfeed = core.jaxpr_uses_outfeed(jaxpr)\njaxpr = dispatch.apply_outfeed_rewriter(jaxpr)\n- # Computations that only produce constants and/or only rearrange their inputs,\n- # which are often produced from partial evaluation, don't need compilation,\n- # and don't need to evaluate their arguments.\n- if (not (jaxpr.effects or has_outfeed) and\n- (not jaxpr.eqns and all(kept_outputs) or not jaxpr.outvars) and\n- all(_is_unspecified(o) for o in out_shardings) and # type: ignore\n- not hasattr(backend, \"compile_replicated\")): # this means 'not pathways'\n- return MeshComputation(\n- str(name_stack), None, True, donated_invars, jaxpr=jaxpr, consts=consts,\n- global_in_avals=global_in_avals, global_out_avals=global_out_avals,\n- in_shardings=in_shardings,\n- device_assignment=device_assignment, committed=committed,\n- kept_var_idx=kept_var_idx, keepalive=None)\n-\n# Look at the number of replcas present in the jaxpr. In\n# lower_sharding_computation, nreps > 1 during `jit(pmap)` cases. This is\n# handled here so as to deprecate the lower_xla_callable codepath when\n@@ -2842,7 +2809,6 @@ def lower_sharding_computation(\nreturn MeshComputation(\nstr(name_stack),\nmodule,\n- False,\ndonated_invars,\nmesh=None,\nglobal_in_avals=global_in_avals,\n@@ -3005,7 +2971,6 @@ def lower_mesh_computation(\nreturn MeshComputation(\nstr(name_stack),\nmodule,\n- False,\ndonated_invars,\nmesh=mesh,\nglobal_in_avals=global_in_avals,\n@@ -3031,10 +2996,9 @@ class MeshComputation(stages.XlaLowering):\n_executable: Optional[MeshExecutable]\ndef __init__(self, name: str, hlo: Union[ir.Module, xc.XlaComputation],\n- is_trivial: bool, donated_invars: Sequence[bool], **compile_args):\n+ donated_invars: Sequence[bool], **compile_args):\nself._name = name\nself._hlo = hlo\n- self.is_trivial = is_trivial\nself._donated_invars = donated_invars\nself.compile_args = compile_args\nself._executable = None\n@@ -3042,8 +3006,6 @@ class MeshComputation(stages.XlaLowering):\n# -- stages.XlaLowering overrides\ndef hlo(self) -> xc.XlaComputation:\n- if self.is_trivial:\n- raise ValueError(\"A trivial computation has no HLO\")\n# this is a method for api consistency with dispatch.XlaComputation\nif isinstance(self._hlo, xc.XlaComputation):\nreturn self._hlo\n@@ -3052,8 +3014,6 @@ class MeshComputation(stages.XlaLowering):\nuse_tuple_args=self.compile_args[\"tuple_args\"])\ndef mhlo(self) -> ir.Module:\n- if self.is_trivial:\n- raise ValueError(\"A trivial computation has no MHLO\")\nif isinstance(self._hlo, xc.XlaComputation):\nmodule_str = xe.mlir.xla_computation_to_mlir_module(self._hlo)\nwith mlir.make_ir_context():\n@@ -3064,9 +3024,6 @@ class MeshComputation(stages.XlaLowering):\n_allow_propagation_to_outputs : bool = False,\n_allow_compile_replicated : bool = True) -> MeshExecutable:\nif self._executable is None:\n- if self.is_trivial:\n- self._executable = MeshExecutable.from_trivial_jaxpr(**self.compile_args)\n- else:\nself._executable = MeshExecutable.from_hlo(\nself._name, self._hlo, **self.compile_args,\n_allow_propagation_to_outputs=_allow_propagation_to_outputs,\n@@ -3290,32 +3247,6 @@ class MeshExecutable(stages.XlaExecutable):\nreturn MeshExecutable(xla_executable, unsafe_call, input_avals,\nin_shardings, out_shardings, auto_spmd_lowering)\n- @staticmethod\n- def from_trivial_jaxpr(jaxpr, consts, global_in_avals, global_out_avals,\n- in_shardings, device_assignment,\n- committed, kept_var_idx, keepalive) -> MeshExecutable:\n- assert keepalive is None\n- out_shardings = _out_shardings_for_trivial(\n- jaxpr, consts, in_shardings, device_assignment)\n- if config.jax_array or config.jax_parallel_functions_output_gda:\n- are_global = [True] * len(global_out_avals)\n- else:\n- are_global = [False] * len(global_out_avals)\n- _, indices, _ = _get_input_metadata(global_out_avals, out_shardings,\n- are_global)\n- process_index = xb.process_index()\n- local_device_assignment = [d for d in device_assignment\n- if d.process_index == process_index]\n- handle_ins = InputsHandler(local_device_assignment, out_shardings, indices,\n- InputsHandlerMode.pjit_or_xmap)\n- handle_outs = global_avals_to_results_handler(\n- global_out_avals, out_shardings, committed,\n- [False] * len(global_out_avals))\n- unsafe_call = partial(_execute_trivial, jaxpr, consts, handle_ins,\n- handle_outs, kept_var_idx)\n- return MeshExecutable(None, unsafe_call, global_in_avals, in_shardings,\n- out_shardings, False)\n-\n# -- stages.XlaExecutable overrides\ndef xla_extension_executable(self):\n@@ -3330,39 +3261,6 @@ class MeshExecutable(stages.XlaExecutable):\nreturn self.unsafe_call(*args)\n-def _out_shardings_for_trivial(\n- jaxpr: core.Jaxpr, consts: Sequence[Any],\n- in_shardings: Sequence[XLACompatibleSharding],\n- device_assignment: Sequence[xc.Device],\n- ) -> List[XLACompatibleSharding]:\n- # For each jaxpr output, compute a Sharding by:\n- # * if the output is a forwarded input, get the corresponding in_sharding;\n- # * if the output is a constant Array, get its .sharding attribute;\n- # * otherwise, the output is a literal or numpy.ndarray constant, so give it\n- # a replicated sharding\n- from jax.experimental import array\n- from jax.experimental import sharding\n- rep = sharding.OpShardingSharding(\n- device_assignment, sharding._get_replicated_op_sharding())\n- shardings: Dict[core.Var, sharding.XLACompatibleSharding] = {}\n- for constvar, constval in zip(jaxpr.constvars, consts):\n- if isinstance(constval, array.Array):\n- shardings[constvar] = constval.sharding\n- map(shardings.setdefault, jaxpr.invars, in_shardings)\n- return [rep if isinstance(x, core.Literal) else shardings.get(x, rep)\n- for x in jaxpr.outvars]\n-\n-\n-def _execute_trivial(jaxpr, consts, in_handler, out_handler, kept_var_idx, *args):\n- env: Dict[core.Var, Any] = {}\n- pruned_args = (x for i, x in enumerate(args) if i in kept_var_idx)\n- map(env.setdefault, jaxpr.invars, pruned_args)\n- map(env.setdefault, jaxpr.constvars, consts)\n- outs = [xla.canonicalize_dtype(v.val) if type(v) is core.Literal else env[v]\n- for v in jaxpr.outvars]\n- return out_handler(in_handler(outs))\n-\n-\n@lru_cache()\ndef _create_mesh_pspec_sharding(mesh, pspec, parsed_pspec=None):\nfrom jax.experimental.sharding import MeshPspecSharding\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1070,6 +1070,9 @@ class CPPJitTest(jtu.BufferDonationTestCase):\njitted_f = self.jit(lambda x, y: x, keep_unused=True)\nwith jtu.count_device_put() as count:\n_ = jitted_f(1, 2)\n+ if config.jax_array:\n+ self.assertEqual(count[0], 2)\n+ else:\nself.assertEqual(count[0], 1)\n@jtu.ignore_warning(category=DeprecationWarning)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/array_test.py",
"new_path": "tests/array_test.py",
"diff": "@@ -20,7 +20,6 @@ import numpy as np\nimport jax\nimport jax.numpy as jnp\n-from jax._src import dispatch\nfrom jax._src import config as jax_config\nfrom jax._src import test_util as jtu\nfrom jax._src.lib import xla_client as xc\n@@ -190,7 +189,7 @@ class JaxArrayTest(jtu.JaxTestCase):\nwith jax_config.jax_array(True):\narr = jnp.array([1, 2, 3])\nself.assertIsInstance(arr, array.Array)\n- self.assertTrue(dispatch.is_single_device_sharding(arr.sharding))\n+ self.assertIsInstance(arr.sharding, sharding.SingleDeviceSharding)\nself.assertEqual(arr._committed, False)\ndef test_jnp_array_jit_add(self):\n@@ -272,7 +271,7 @@ class JaxArrayTest(jtu.JaxTestCase):\nout = jnp.zeros_like(a)\nexpected = np.zeros(a.shape, dtype=np.int32)\nself.assertArraysEqual(out, expected)\n- self.assertTrue(dispatch.is_single_device_sharding(out.sharding))\n+ self.assertIsInstance(out.sharding, sharding.SingleDeviceSharding)\n@jax_config.jax_array(True)\ndef test_wrong_num_arrays(self):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/debug_nans_test.py",
"new_path": "tests/debug_nans_test.py",
"diff": "@@ -225,8 +225,8 @@ class DebugInfsTest(jtu.JaxTestCase):\ndef testDebugNansDoesntReturnDeoptimizedResult(self):\n@jax.jit\ndef f(x):\n- y = x + 2 # avoid trivial dispatch path by adding some eqn\n- return jnp.nan, y\n+ x + 2 # avoid trivial dispatch path by adding some eqn\n+ return jnp.nan\nwith self.assertRaisesRegex(FloatingPointError, \"de-optimized\"):\nwith jax.debug_nans(True):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/multi_device_test.py",
"new_path": "tests/multi_device_test.py",
"diff": "@@ -202,9 +202,6 @@ class MultiDeviceTest(jtu.JaxTestCase):\nself.assertIsInstance(f(), jnp.DeviceArray)\nself.assert_uncommitted_to_device(f(), devices[0])\nself.assert_uncommitted_to_device(jax.jit(f)(), devices[0])\n- # Skip for jax.Array because it doesn't work with the device argument of\n- # jit as it is deprecated.\n- if not config.jax_array:\nself.assert_committed_to_device(jax.jit(f, device=devices[1])(),\ndevices[1])\n"
}
] | Python | Apache License 2.0 | google/jax | roll back breakage
PiperOrigin-RevId: 472949225 |
260,424 | 08.09.2022 05:25:19 | 25,200 | b3393e3b60e76c30dfd9820ab5ef2aafb06c9607 | Checkify: add jvp rule for assert_p. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/checkify.py",
"new_path": "jax/_src/checkify.py",
"diff": "@@ -27,6 +27,7 @@ from jax import linear_util as lu\nfrom jax.api_util import flatten_fun\nfrom jax.experimental import pjit\nfrom jax.experimental import maps\n+from jax.interpreters import ad\nfrom jax.interpreters import batching\nfrom jax.interpreters import mlir\nfrom jax.interpreters import partial_eval as pe\n@@ -502,6 +503,13 @@ def assert_batching_rule(batched_args, batch_dims, *, msgs):\nbatching.primitive_batchers[assert_p] = assert_batching_rule\n+def assert_jvp_rule(primals, _, *, msgs):\n+ # Check primals, discard tangents.\n+ assert_p.bind(*primals, msgs=msgs)\n+ return [], []\n+\n+ad.primitive_jvps[assert_p] = assert_jvp_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": "@@ -861,6 +861,19 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\ncheckify.checkify(g)(0.) # does not crash\n+ def test_grad(self):\n+ @checkify.checkify\n+ @jax.grad\n+ def f(x):\n+ checkify.check(jnp.all(x > 0), \"should be positive!\")\n+ return x\n+\n+ err, _ = f(1.)\n+ self.assertIsNone(err.get())\n+\n+ err, _ = f(0.)\n+ self.assertIsNotNone(err.get())\n+ self.assertIn(\"should be positive\", err.get())\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Checkify: add jvp rule for assert_p.
PiperOrigin-RevId: 472961963 |
260,510 | 06.09.2022 13:26:41 | 25,200 | b6c3b9df190b536396a55eaf4fef1d577025136b | Split State effect into Read/Write/Accum effects and tie them to Ref avals | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow/for_loop.py",
"new_path": "jax/_src/lax/control_flow/for_loop.py",
"diff": "@@ -51,7 +51,9 @@ T = TypeVar('T')\nclass Ref(Generic[T]): pass\nArray = Any\n-StateEffect = state.StateEffect\n+ReadEffect = state.ReadEffect\n+WriteEffect = state.WriteEffect\n+AccumEffect = state.AccumEffect\nShapedArrayRef = state.ShapedArrayRef\nref_set = state.ref_set\nref_get = state.ref_get\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/__init__.py",
"new_path": "jax/_src/state/__init__.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Module for state.\"\"\"\n-from jax._src.state.types import ShapedArrayRef, StateEffect\n+from jax._src.state.types import (ShapedArrayRef, ReadEffect, WriteEffect,\n+ AccumEffect)\nfrom jax._src.state.primitives import (ref_get, ref_set, ref_swap,\nref_addupdate, get_p, swap_p,\naddupdate_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/primitives.py",
"new_path": "jax/_src/state/primitives.py",
"diff": "@@ -27,7 +27,8 @@ from jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nimport jax.numpy as jnp\n-from jax._src.state.types import ShapedArrayRef, StateEffect\n+from jax._src.state.types import (ShapedArrayRef, ReadEffect, WriteEffect,\n+ AccumEffect)\n## General utilities\n@@ -155,7 +156,7 @@ def _get_abstract_eval(ref_aval: ShapedArrayRef, *idx, indexed_dims):\nraise ValueError(f\"Invalid `idx` and `indexed_dims`: {idx}, {indexed_dims}\")\nidx_shapes = tuple(i.shape for i in idx)\nshape = _get_slice_output_shape(ref_aval.shape, idx_shapes, indexed_dims)\n- return (core.ShapedArray(shape, ref_aval.dtype), {StateEffect})\n+ return (core.ShapedArray(shape, ref_aval.dtype), {ReadEffect(ref_aval)})\nget_p.def_effectful_abstract_eval(_get_abstract_eval)\n@@ -182,7 +183,7 @@ def _swap_abstract_eval(ref_aval: ShapedArrayRef, val_aval: core.AbstractValue,\nf\"Ref dtype: {ref_aval.dtype}. \"\nf\"Value shape: {val_aval.dtype}. \")\nreturn (core.ShapedArray(expected_output_shape, ref_aval.dtype),\n- {StateEffect})\n+ {WriteEffect(ref_aval)})\nswap_p.def_effectful_abstract_eval(_swap_abstract_eval)\n@@ -209,7 +210,7 @@ def _addupdate_abstract_eval(ref_aval: ShapedArrayRef,\nraise ValueError(\"Invalid dtype for `addupdate`. \"\nf\"Ref dtype: {ref_aval.dtype}. \"\nf\"Value shape: {val_aval.dtype}. \")\n- return [], {StateEffect}\n+ return [], {AccumEffect(ref_aval)}\naddupdate_p.def_effectful_abstract_eval(_addupdate_abstract_eval)\n## Pretty printing for `get` and `swap` in jaxprs\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/types.py",
"new_path": "jax/_src/state/types.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Module for state types.\"\"\"\n+from __future__ import annotations\nfrom functools import partial\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union\n@@ -44,11 +45,29 @@ zip, unsafe_zip = safe_zip, zip\nArray = Any\n-class _StateEffect:\n- def __repr__(self):\n- return \"State\"\n- __str__ = __repr__\n-StateEffect = _StateEffect()\n+class RefEffect:\n+ def __init__(self, ref_aval: ShapedArrayRef):\n+ self.ref_aval = ref_aval\n+\n+ def __eq__(self, other):\n+ if not isinstance(other, self.__class__):\n+ return False\n+ return self.ref_aval is other.ref_aval\n+\n+ def __hash__(self):\n+ return hash((self.__class__, self.ref_aval))\n+\n+class ReadEffect(RefEffect):\n+ def __str__(self):\n+ return f\"Read<{self.ref_aval}>\"\n+\n+class WriteEffect(RefEffect):\n+ def __str__(self):\n+ return f\"Write<{self.ref_aval}>\"\n+\n+class AccumEffect(RefEffect):\n+ def __str__(self):\n+ return f\"Accum<{self.ref_aval}>\"\n# ## `Ref`s\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -317,9 +317,9 @@ jax_test(\nname = \"lax_control_flow_test\",\nsrcs = [\"lax_control_flow_test.py\"],\nshard_count = {\n- \"cpu\": 20,\n- \"gpu\": 20,\n- \"tpu\": 20,\n+ \"cpu\": 30,\n+ \"gpu\": 30,\n+ \"tpu\": 30,\n\"iree\": 10,\n},\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/state_test.py",
"new_path": "tests/state_test.py",
"diff": "@@ -97,7 +97,7 @@ class StatePrimitivesTest(jtu.JaxTestCase):\nelse:\njaxpr, out_avals, _ = pe.trace_to_jaxpr_dynamic(\nlu.wrap_init(f), [ref_aval])\n- self.assertSetEqual(jaxpr.effects, {state.StateEffect})\n+ self.assertSetEqual(jaxpr.effects, {state.ReadEffect(ref_aval)})\nself.assertLen(out_avals, 1)\nout_aval, = out_avals\nself.assertIsInstance(out_aval, core.ShapedArray)\n@@ -163,7 +163,7 @@ class StatePrimitivesTest(jtu.JaxTestCase):\nelse:\njaxpr, out_avals, _ = pe.trace_to_jaxpr_dynamic(\nlu.wrap_init(f), [ref_aval, val_aval])\n- self.assertSetEqual(jaxpr.effects, {state.StateEffect})\n+ self.assertSetEqual(jaxpr.effects, {state.WriteEffect(ref_aval)})\nself.assertLen(out_avals, 1)\nout_aval, = out_avals\nself.assertIsInstance(out_aval, core.ShapedArray)\n@@ -218,7 +218,7 @@ class StatePrimitivesTest(jtu.JaxTestCase):\nelse:\njaxpr, out_avals, _ = pe.trace_to_jaxpr_dynamic(\nlu.wrap_init(f), [ref_aval, val_aval])\n- self.assertSetEqual(jaxpr.effects, {state.StateEffect})\n+ self.assertSetEqual(jaxpr.effects, {state.AccumEffect(ref_aval)})\nself.assertLen(out_avals, 0)\ndef test_addupdate_abstract_eval_must_take_in_refs(self):\n"
}
] | Python | Apache License 2.0 | google/jax | Split State effect into Read/Write/Accum effects and tie them to Ref avals |
260,510 | 06.09.2022 14:29:40 | 25,200 | 6967c7ef51c4831d06e9ce8b66cedbfcf61ba390 | Add sound loop invariance detection | [
{
"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, Generic, List, Optional, Sequence, Tuple, TypeVar\n+from typing import Any, Callable, Generic, List, Optional, Sequence, Set, Tuple, TypeVar\nfrom jax import core\nfrom jax import lax\n@@ -54,6 +54,7 @@ Array = Any\nReadEffect = state.ReadEffect\nWriteEffect = state.WriteEffect\nAccumEffect = state.AccumEffect\n+StateEffect = state.StateEffect\nShapedArrayRef = state.ShapedArrayRef\nref_set = state.ref_set\nref_get = state.ref_get\n@@ -222,6 +223,11 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\ninit, _, ys = for_loop(length, for_body, (init, xs, ys), reverse=reverse)\nreturn init, ys\n+def _get_ref_state_effects(jaxpr: core.Jaxpr) -> List[Set[StateEffect]]:\n+ all_effects = jaxpr.effects\n+ return [{eff for eff in all_effects\n+ if isinstance(eff, (ReadEffect, WriteEffect, AccumEffect))\n+ and eff.ref_aval is v.aval} for v in jaxpr.invars]\n@for_p.def_abstract_eval\ndef _for_abstract_eval(*avals, jaxpr, **__):\n@@ -317,6 +323,38 @@ def _partial_eval_jaxpr_custom(jaxpr, in_unknowns, policy):\n_save_everything = lambda *_, **__: True\n+def _is_read_only(ref_effects: Set[StateEffect]) -> bool:\n+ assert len(ref_effects) > 0\n+ if len(ref_effects) > 1:\n+ # Means we must have a write or accum effect so not read-only\n+ return False\n+ eff, = ref_effects\n+ return isinstance(eff, ReadEffect)\n+\n+def _loop_invariant_outputs(jaxpr: core.Jaxpr) -> List[bool]:\n+ # Get effects for each of the jaxpr inputs and remove the loop index.\n+ ref_effects = _get_ref_state_effects(jaxpr)[1:]\n+ # We first assume that *read-only `Ref`s* are loop-invariant. We can safely do\n+ # this because the only way something can be loop-varying is if we write to it\n+ # at some point. It's *possible* that read-write `Ref`s are loop-invariant but\n+ # we conservatively assume they aren't.\n+ loop_invar_refs = [_is_read_only(effs) if effs else True\n+ for effs in ref_effects]\n+ loop_var_refs = map(operator.not_, loop_invar_refs)\n+\n+ # We'd like to detect if the outputs of the jaxpr are loop-invariant. An\n+ # output is loop-invariant if it is downstream of only loop-invariant values\n+ # (seeded by the read-only `Ref`s). If at any point, a loop-varying value\n+ # interacts with a loop-invariant value, we produce a loop-varying value. We\n+ # can use `partial_eval` to perform this analysis by treating loop-varying\n+ # values as \"unknown\" and loop-invariant values as \"known\", since when a known\n+ # and unknown value interact, they produce an unknown value.\n+ loop_var_inputs = [True, *loop_var_refs]\n+ _, _, loop_var_outputs, _, _, = _partial_eval_jaxpr_custom(\n+ jaxpr, loop_var_inputs, _save_everything)\n+ return map(operator.not_, loop_var_outputs)\n+\n+\ndef _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\njaxpr: core.Jaxpr, nsteps: int, reverse: bool,\nwhich_linear: Tuple[bool, ...]) -> List[pe.JaxprTracer]:\n@@ -371,29 +409,7 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\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+ loop_invar_res = _loop_invariant_outputs(jaxpr_known_resout)\njaxpr_known, res_avals = _convert_outputs_to_writes(nsteps,\njaxpr_known_resout,\n@@ -504,29 +520,7 @@ def _for_partial_eval_custom(saveable, in_unknowns, in_inst, eqn):\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+ loop_invar_res = _loop_invariant_outputs(jaxpr_known_resout)\njaxpr_known, res_avals = _convert_outputs_to_writes(nsteps,\njaxpr_known_resout,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/__init__.py",
"new_path": "jax/_src/state/__init__.py",
"diff": "# limitations under the License.\n\"\"\"Module for state.\"\"\"\nfrom jax._src.state.types import (ShapedArrayRef, ReadEffect, WriteEffect,\n- AccumEffect)\n+ AccumEffect, StateEffect)\nfrom jax._src.state.primitives import (ref_get, ref_set, ref_swap,\nref_addupdate, get_p, swap_p,\naddupdate_p)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/types.py",
"new_path": "jax/_src/state/types.py",
"diff": "@@ -69,6 +69,8 @@ class AccumEffect(RefEffect):\ndef __str__(self):\nreturn f\"Accum<{self.ref_aval}>\"\n+StateEffect = Union[ReadEffect, WriteEffect, AccumEffect]\n+\n# ## `Ref`s\n# We need an aval for `Ref`s so we can represent `get` and `swap` in Jaxprs.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -2853,6 +2853,29 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nnp.testing.assert_allclose(actual_tangents[0], expected_tangents[0])\nnp.testing.assert_allclose(actual_tangents[1], expected_tangents[1])\n+ def body2(_, refs):\n+ # Here we use `i_ref` as a loop counter\n+ a_ref, b_ref, c_ref, i_ref = refs\n+ i = i_ref[()]\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+ i_ref[()] = i + 1\n+\n+ def g(a, b):\n+ c = jnp.zeros_like(a)\n+ _, b, c, _ = for_impl(5, body2, (a, b, c, 0))\n+ return b, c\n+ a = jnp.arange(5.) + 1.\n+ b = 1.\n+ _, g_lin = jax.linearize(f, a, b)\n+ expected_tangents = g_lin(a, b)\n+ _, actual_tangents = jax.jvp(g, (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@parameterized.named_parameters(\n{\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\nfor_body_name, nsteps, impl_name),\n"
}
] | Python | Apache License 2.0 | google/jax | Add sound loop invariance detection |
260,335 | 08.09.2022 13:45:06 | 25,200 | 47b2dfe92fe2590ed00958b2abc0e9c6ccb7d2cb | add _device attribute to PRNGKeyArray so that computation follows key placement
unrelated: remove some redundant hasattr + try / except AttributeError | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/ndarray.py",
"new_path": "jax/_src/numpy/ndarray.py",
"diff": "@@ -31,8 +31,7 @@ class ArrayMeta(abc.ABCMeta):\n# that isinstance(x, ndarray) might return true but\n# issubclass(type(x), ndarray) might return false for an array tracer.\ntry:\n- return (hasattr(instance, \"aval\") and\n- isinstance(instance.aval, core.UnshapedArray))\n+ return isinstance(instance.aval, core.UnshapedArray)\nexcept AttributeError:\nsuper().__instancecheck__(instance)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/prng.py",
"new_path": "jax/_src/prng.py",
"diff": "import abc\nfrom functools import partial\n+import operator as op\nfrom typing import Any, Callable, Hashable, Iterator, NamedTuple, Sequence\nimport numpy as np\n@@ -114,8 +115,7 @@ class PRNGKeyArrayMeta(abc.ABCMeta):\ndef __instancecheck__(self, instance):\ntry:\n- return (hasattr(instance, 'aval') and\n- isinstance(instance.aval, core.ShapedArray) and\n+ return (isinstance(instance.aval, core.ShapedArray) and\ntype(instance.aval.dtype) is KeyTy)\nexcept AttributeError:\nsuper().__instancecheck__(instance)\n@@ -169,6 +169,10 @@ class PRNGKeyArray(metaclass=PRNGKeyArrayMeta):\ndef dtype(self):\nreturn KeyTy(self.impl)\n+ _device = property(op.attrgetter('_base_array._device'))\n+ _committed = property(op.attrgetter('_base_array._committed'))\n+ sharding = property(op.attrgetter('_base_array.sharding'))\n+\ndef _is_scalar(self):\nbase_ndim = len(self.impl.key_shape)\nreturn self._base_array.ndim == base_ndim\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/multi_device_test.py",
"new_path": "tests/multi_device_test.py",
"diff": "@@ -150,6 +150,12 @@ class MultiDeviceTest(jtu.JaxTestCase):\njax.device_put(x_uncommitted, devices[3])),\ndevices[4])\n+ def test_computation_follows_data_prng(self):\n+ _, device, *_ = self.get_devices()\n+ rng = jax.device_put(jax.random.PRNGKey(0), device)\n+ val = jax.random.normal(rng, ())\n+ self.assert_committed_to_device(val, device)\n+\ndef test_primitive_compilation_cache(self):\ndevices = self.get_devices()\n"
}
] | Python | Apache License 2.0 | google/jax | add _device attribute to PRNGKeyArray so that computation follows key placement
unrelated: remove some redundant hasattr + try / except AttributeError |
260,447 | 12.09.2022 10:08:50 | 25,200 | 3243e23aa528db390fdece3fa32517c28a50318b | [sparse] Lower batch-mode bcoo_dot_genernal to cusparseSpMM. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/sparse/bcoo.py",
"new_path": "jax/experimental/sparse/bcoo.py",
"diff": "@@ -42,6 +42,8 @@ from jax._src.lax.lax import (\n_const, ranges_like, remaining, _dot_general_batch_dim_nums, _dot_general_shape_rule,\nDotDimensionNumbers)\nfrom jax._src.lib.mlir import ir\n+from jax._src.lib import xla_bridge\n+from jax._src.lib import version as jaxlib_version\nfrom jax._src.lib.mlir.dialects import mhlo\nfrom jax._src.numpy.setops import _unique\n@@ -736,9 +738,8 @@ def _bcoo_dot_general_cuda_lowering(\n# Checks the shapes of lhs and rhs.\nassert props.n_dense == 0\n- assert props.n_batch == 0\n- assert props.n_sparse in [1, 2]\n- assert rhs_ndim in [1, 2]\n+ assert (props.n_batch, props.n_sparse, rhs_ndim) in [\n+ (0, 1, 1), (0, 1, 2), (0, 2, 1), (0, 2, 2), (1, 2, 2)]\n# Checks the operation dimensions.\nassert len(lhs_batch) == 0\n@@ -761,6 +762,8 @@ def _bcoo_dot_general_cuda_lowering(\nelse:\nraise ValueError(f\"rhs has to be 1d or 2d; get {rhs_ndim}d.\")\n+ if props.n_batch == 0:\n+ # non-batch mode.\nlhs_transpose = False\nif props.n_sparse == 1:\n# Converts lhs to a row vector.\n@@ -809,6 +812,73 @@ def _bcoo_dot_general_cuda_lowering(\nx_dtype=rhs_aval.dtype)]\nelse:\nraise ValueError(f\"lhs has to be 1d or 2d; get {props.n_sparse}d.\")\n+ elif props.n_batch == 1:\n+ # batch mode.\n+ lhs_indices_shape = ir.RankedTensorType(lhs_indices.type).shape\n+ lhs_data_shape = ir.RankedTensorType(lhs_data.type).shape\n+ batch_count, _, _ = lhs_indices_shape\n+ rhs_shape = ir.RankedTensorType(rhs.type).shape\n+\n+ # Squeeze the batch dimension for both indices and data.\n+ lhs_indices_2d_shape = (np.prod(np.array(lhs_indices_shape)[:-1]),\n+ lhs_indices_shape[-1])\n+ lhs_data_1d_shape = (np.prod(np.array(lhs_data_shape)), )\n+\n+ lhs_indices_2d = mhlo.ReshapeOp(\n+ ir.RankedTensorType.get(\n+ lhs_indices_2d_shape,\n+ ir.RankedTensorType(lhs_indices.type).element_type),\n+ lhs_indices).result\n+\n+ lhs_data_1d = mhlo.ReshapeOp(\n+ ir.RankedTensorType.get(\n+ lhs_data_1d_shape,\n+ ir.RankedTensorType(lhs_data.type).element_type),\n+ lhs_data).result\n+\n+ row = _collapse_mhlo(\n+ mhlo.SliceOp(\n+ lhs_indices_2d,\n+ start_indices=mlir.dense_int_elements([0, 0]),\n+ limit_indices=mlir.dense_int_elements([lhs_indices_2d_shape[0], 1]),\n+ strides=mlir.dense_int_elements([1, 1])).result,\n+ start=0, end=1)\n+\n+ col = _collapse_mhlo(\n+ mhlo.SliceOp(\n+ lhs_indices_2d,\n+ start_indices=mlir.dense_int_elements([0, 1]),\n+ limit_indices=mlir.dense_int_elements([lhs_indices_2d_shape[0], 2]),\n+ strides=mlir.dense_int_elements([1, 1])).result,\n+ start=0, end=1)\n+\n+ # Broadcast rhs to have the same batch size as lhs.\n+ # TODO(tianjianlu): remove broadcasting.\n+ # Use batch_stride = 0 for non-batch.\n+ # The issue (https://github.com/NVIDIA/CUDALibrarySamples/issues/81#issuecomment-1205562643)\n+ # in cusparse library does not allow batch_stride = 0 for a non-batched rhs.\n+ batched_rhs_shape = (batch_count,) + tuple(rhs_shape)\n+ batched_rhs = mhlo.BroadcastInDimOp(\n+ ir.RankedTensorType.get(batched_rhs_shape,\n+ ir.RankedTensorType(rhs.type).element_type),\n+ rhs,\n+ broadcast_dimensions=mlir.dense_int_elements([1, 2])).result\n+ batched_rhs_2d_shape = (np.prod(np.array(batched_rhs_shape)[:-1]), batched_rhs_shape[-1])\n+ batched_rhs_2d = mhlo.ReshapeOp(\n+ ir.RankedTensorType.get(\n+ batched_rhs_2d_shape,\n+ ir.RankedTensorType(batched_rhs.type).element_type),\n+ batched_rhs).result\n+\n+ lhs_transpose = True if lhs_contract[0] == props.n_batch else False\n+\n+ return [bcoo_dot_general_fn(\n+ lhs_data_1d, row, col, batched_rhs_2d, shape=lhs_spinfo.shape,\n+ transpose=lhs_transpose, data_dtype=lhs_data_aval.dtype,\n+ index_dtype=lhs_indices_aval.dtype,\n+ x_dtype=rhs_aval.dtype)]\n+ else:\n+ raise ValueError(f\"n_batch has to be 0 or 1; get {props.n_batch}.\")\ndef _bcoo_dot_general_gpu_lowering(\ncoo_matvec_lowering, coo_matmat_lowering,\n@@ -820,7 +890,7 @@ def _bcoo_dot_general_gpu_lowering(\nctx, lhs_data, lhs_indices, rhs,\ndimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n- (lhs_contract, _), (lhs_batch, rhs_batch) = dimension_numbers\n+ (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\nlhs_data_aval, lhs_indices_aval, rhs_aval, = ctx.avals_in\nn_batch, n_sparse, n_dense, _ = _validate_bcoo(\nlhs_data_aval, lhs_indices_aval, lhs_spinfo.shape)\n@@ -834,7 +904,7 @@ def _bcoo_dot_general_gpu_lowering(\nctx, lhs_data, lhs_indices, rhs,\ndimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n- if (n_batch or n_dense or\n+ if (n_batch > 1 or n_dense or\nn_sparse not in [1, 2] or rhs_aval.ndim not in [1, 2] or\nlhs_batch or rhs_batch or len(lhs_contract) != 1):\nreturn _bcoo_dot_general_default_lowering(\n@@ -850,6 +920,25 @@ def _bcoo_dot_general_gpu_lowering(\nctx, lhs_data, lhs_indices, rhs,\ndimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n+ if n_batch == 1:\n+ # The support for batched computation in cusparseSpMM COO was added in\n+ # 11.6.1: https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#cusparse-11.6.1\n+ cuda_version = int(xla_bridge.get_backend().platform_version.split()[-1])\n+\n+ # TODO(tianjianlu): enable the batch mode of cusparseSpMv.\n+ cuda_supported_batch_mode = (\n+ n_sparse == 2 and rhs_aval.ndim == 2 and\n+ len(lhs_contract) == 1 and lhs_contract[0] in [1, 2] and\n+ len(rhs_contract) == 1 and rhs_contract[0] in [0, 1] and\n+ cuda_version >= 11061 and jaxlib_version >= (0, 3, 18))\n+ if not cuda_supported_batch_mode:\n+ warnings.warn(\"bcoo_dot_general GPU lowering currently does not \"\n+ \"support this batch-mode computation. Falling back to \"\n+ \"the default implementation.\", CuSparseEfficiencyWarning)\n+ return _bcoo_dot_general_default_lowering(\n+ ctx, lhs_data, lhs_indices, rhs,\n+ dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n+\nreturn _bcoo_dot_general_cuda_lowering(\ncoo_matvec_lowering, coo_matmat_lowering, ctx, lhs_data, lhs_indices, rhs,\ndimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n"
},
{
"change_type": "MODIFY",
"old_path": "jaxlib/gpu_sparse.py",
"new_path": "jaxlib/gpu_sparse.py",
"diff": "@@ -283,7 +283,16 @@ def _coo_matmat_mhlo(platform, gpu_sparse, data, row, col, B, *, shape,\nx_dtype, data_dtype, index_dtype):\n\"\"\"COO from dense matrix.\"\"\"\ndata_type, _, nnz = _validate_coo_mhlo(data, row, col)\n+ is_batched_matmat = False\n+ batch_count = 1\n+ if len(shape) == 2:\nrows, cols = shape\n+ elif len(shape) == 3:\n+ is_batched_matmat = True\n+ batch_count, rows, cols = shape\n+ # Redefine nnz as nnz per batch.\n+ nnz = nnz // batch_count\n+\nB_shape = ir.RankedTensorType(B.type).shape\n_, Ccols = B_shape\n@@ -291,14 +300,11 @@ def _coo_matmat_mhlo(platform, gpu_sparse, data, row, col, B, *, shape,\ncompute_dtype = data_dtype\ncompute_type = data_type\n- # TODO(tianjianlu): use user-defined batch count after enabling batch mode.\n- batch_count = 1\n-\n# TODO(tianjianlu): use batch stride to trigger different mode of batch\n# computation. Currently batch_stride = 0 is not allowed because of the issue\n# in cusparse https://github.com/NVIDIA/CUDALibrarySamples/issues/81#issuecomment-1205562643\n# Set batch stride to be the matrix size for now.\n- lhs_batch_stride = rows * cols\n+ lhs_batch_stride = nnz\nB_rows = rows if transpose else cols\nrhs_batch_stride = B_rows * Ccols\n@@ -308,17 +314,24 @@ def _coo_matmat_mhlo(platform, gpu_sparse, data, row, col, B, *, shape,\nrhs_batch_stride)\nout_size = cols if transpose else rows\n+ if is_batched_matmat:\n+ out_shape = [batch_count, out_size, Ccols]\n+ out_layout = [2, 1, 0]\n+ else:\n+ out_shape = [out_size, Ccols]\n+ out_layout = [1, 0]\n+\nout = custom_call(\nf\"{platform}sparse_coo_matmat\",\n[\n- ir.RankedTensorType.get([out_size, Ccols], compute_type),\n+ ir.RankedTensorType.get(out_shape, compute_type),\nir.RankedTensorType.get([buffer_size],\nir.IntegerType.get_signless(8)),\n],\n[data, row, col, B],\nbackend_config=opaque,\noperand_layouts=[[0], [0], [0], [1, 0]],\n- result_layouts=[[1, 0], [0]])\n+ result_layouts=[out_layout, [0]])\nreturn out[0]\ncuda_coo_matmat = partial(_coo_matmat_mhlo, \"cu\", _cusparse)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/sparse_test.py",
"new_path": "tests/sparse_test.py",
"diff": "@@ -36,6 +36,7 @@ from jax import lax\nfrom jax._src.lib import xla_extension_version\nfrom jax._src.lib import gpu_sparse\nfrom jax._src.lib import xla_bridge\n+from jax._src.lib import version as jaxlib_version\nfrom jax._src.util import unzip2\nfrom jax import jit\nfrom jax import tree_util\n@@ -123,6 +124,13 @@ def rand_sparse(rng, nse=0.5, post=lambda x: x, rand_method=jtu.rand_default):\nreturn post(M)\nreturn _rand_sparse\n+def _is_required_cuda_version_satisfied(cuda_version):\n+ version = xla_bridge.get_backend().platform_version\n+ if version == \"<unknown>\" or version.split()[0] == \"rocm\":\n+ return False\n+ else:\n+ return int(version.split()[-1]) >= cuda_version\n+\nclass cuSparseTest(jtu.JaxTestCase):\ndef gpu_dense_conversion_warning_context(self, dtype):\n@@ -1149,6 +1157,110 @@ class BCOOTest(jtu.JaxTestCase):\nself._CompileAndCheck(f_sparse, args_maker)\nself._CheckAgainstNumpy(f_dense, f_sparse, args_maker)\n+ @unittest.skipIf(not GPU_LOWERING_ENABLED, \"test requires cusparse/hipsparse\")\n+ @unittest.skipIf(jtu.device_under_test() != \"gpu\", \"test requires GPU\")\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_n_batch={}_lhs_shape={}_rhs_shape={}_lhs_contracting={}_rhs_contracting={}\"\n+ .format(n_batch, jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype),\n+ lhs_contracting, rhs_contracting),\n+ \"n_batch\": n_batch, \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape,\n+ \"dtype\": dtype, \"lhs_contracting\": lhs_contracting,\n+ \"rhs_contracting\": rhs_contracting}\n+ for n_batch, lhs_shape, rhs_shape, lhs_contracting, rhs_contracting in [\n+ [1, (1, 2, 3), (3, 2), [2], [0]],\n+ [1, (1, 3, 2), (3, 2), [1], [0]],\n+ [1, (1, 3, 2), (4, 3), [1], [1]],\n+ [1, (4, 2, 3), (3, 5), [2], [0]],\n+ [1, (4, 2, 3), (2, 5), [1], [0]],\n+ [1, (4, 2, 3), (5, 3), [2], [1]],\n+ ]\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.complex))\n+ @jtu.skip_on_devices(\"rocm\")\n+ def test_bcoo_batched_matmat_cusparse(\n+ self, n_batch, lhs_shape, rhs_shape, dtype, lhs_contracting,\n+ rhs_contracting):\n+ rng = jtu.rand_small(self.rng())\n+ rng_sparse = rand_sparse(self.rng())\n+ def args_maker():\n+ lhs = rng_sparse(lhs_shape, dtype)\n+ rhs = rng(rhs_shape, dtype)\n+ nse = int(sparse_bcoo._bcoo_nse(lhs, n_batch=n_batch, n_dense=0))\n+ lhs_bcoo = sparse_bcoo.bcoo_fromdense(lhs, n_batch=n_batch, nse=nse,\n+ index_dtype=jnp.int32)\n+ return lhs_bcoo, lhs, rhs\n+\n+ dimension_numbers = ((lhs_contracting, rhs_contracting), ([], []))\n+\n+ def f_dense(lhs_bcoo, lhs, rhs):\n+ return lax.dot_general(lhs, rhs, dimension_numbers=dimension_numbers)\n+\n+ def f_sparse(lhs_bcoo, lhs, rhs):\n+ return sparse_bcoo.bcoo_dot_general(lhs_bcoo, rhs,\n+ dimension_numbers=dimension_numbers)\n+\n+ cuda_version_11061_and_beyond = _is_required_cuda_version_satisfied(\n+ cuda_version=11061)\n+ jaxlib_version_0318_and_beyond = jaxlib_version >= (0, 3, 18)\n+ if cuda_version_11061_and_beyond and jaxlib_version_0318_and_beyond:\n+ # TODO(tianjianlu): In some cases, this fails python_should_be_executing.\n+ # self._CompileAndCheck(f_sparse, args_maker)\n+ self._CheckAgainstNumpy(f_dense, f_sparse, args_maker)\n+ self._CheckAgainstNumpy(f_dense, jit(f_sparse), args_maker)\n+ else:\n+ lhs_bcoo, lhs, rhs = args_maker()\n+ matmat_expected = f_dense(lhs_bcoo, lhs, rhs)\n+ with self.assertWarnsRegex(\n+ sparse.CuSparseEfficiencyWarning,\n+ \"bcoo_dot_general GPU lowering currently does not support this \"\n+ \"batch-mode computation.*\"):\n+ matmat_default_lowering_fallback = jit(f_sparse)(lhs_bcoo, lhs, rhs)\n+ self.assertAllClose(matmat_expected, matmat_default_lowering_fallback,\n+ atol=1E-6, rtol=1E-6)\n+\n+ @unittest.skipIf(not GPU_LOWERING_ENABLED, \"test requires cusparse/hipsparse\")\n+ @unittest.skipIf(jtu.device_under_test() != \"gpu\", \"test requires GPU\")\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_n_batch={}_lhs_shape={}_rhs_shape={}_lhs_contracting={}_rhs_contracting={}\"\n+ .format(n_batch, jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype),\n+ lhs_contracting, rhs_contracting),\n+ \"n_batch\": n_batch, \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape,\n+ \"dtype\": dtype, \"lhs_contracting\": lhs_contracting,\n+ \"rhs_contracting\": rhs_contracting}\n+ for n_batch, lhs_shape, rhs_shape, lhs_contracting, rhs_contracting in [\n+ [1, (1, 2, 3), (3), [2], [0]],\n+ [1, (1, 2), (3, 2), [1], [1]],\n+ ]\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.complex))\n+ @jtu.skip_on_devices(\"rocm\")\n+ def test_bcoo_batched_matmat_default_lowering(\n+ self, n_batch, lhs_shape, rhs_shape, dtype, lhs_contracting,\n+ rhs_contracting):\n+ rng = jtu.rand_small(self.rng())\n+ rng_sparse = rand_sparse(self.rng())\n+ lhs = rng_sparse(lhs_shape, dtype)\n+ rhs = rng(rhs_shape, dtype)\n+ nse = int(sparse_bcoo._bcoo_nse(lhs, n_batch=n_batch, n_dense=0))\n+ lhs_bcoo = sparse_bcoo.bcoo_fromdense(lhs, n_batch=n_batch, nse=nse,\n+ index_dtype=jnp.int32)\n+ dimension_numbers = ((lhs_contracting, rhs_contracting), ([], []))\n+ matmat_expected = lax.dot_general(lhs, rhs,\n+ dimension_numbers=dimension_numbers)\n+ sp_matmat = jit(partial(sparse_bcoo.bcoo_dot_general,\n+ dimension_numbers=dimension_numbers))\n+\n+ if config.jax_bcoo_cusparse_lowering:\n+ with self.assertWarnsRegex(\n+ sparse.CuSparseEfficiencyWarning,\n+ \"bcoo_dot_general GPU lowering currently does not support this \"\n+ \"batch-mode computation.*\"):\n+ matmat_default_lowering_fallback = sp_matmat(lhs_bcoo, rhs)\n+\n+ self.assertArraysEqual(matmat_expected, matmat_default_lowering_fallback)\n+\n@unittest.skipIf(not GPU_LOWERING_ENABLED, \"test requires cusparse/hipsparse\")\n@unittest.skipIf(jtu.device_under_test() != \"gpu\", \"test requires GPU\")\n@jtu.skip_on_devices(\"rocm\") # TODO(rocm): see SWDEV-328107\n"
}
] | Python | Apache License 2.0 | google/jax | [sparse] Lower batch-mode bcoo_dot_genernal to cusparseSpMM.
PiperOrigin-RevId: 473777597 |
260,510 | 12.09.2022 14:40:11 | 25,200 | e5725f1df1831b745efece57f10a017fafaf6951 | Split for_loop_test out of lax_control_flow_test | [
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -910,6 +910,16 @@ jax_test(\n],\n)\n+jax_test(\n+ name = \"for_loop_test\",\n+ srcs = [\"for_loop_test.py\"],\n+ shard_count = {\n+ \"cpu\": 10,\n+ \"gpu\": 10,\n+ \"tpu\": 10,\n+ },\n+)\n+\njax_test(\nname = \"clear_backends_test\",\nsrcs = [\"clear_backends_test.py\"],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/for_loop_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+from functools import partial\n+\n+from absl.testing import absltest\n+from absl.testing import parameterized\n+\n+import numpy as np\n+\n+import jax\n+from jax._src import test_util as jtu\n+import jax.numpy as jnp\n+from jax._src.lax.control_flow import for_loop\n+\n+from jax.config import config\n+config.parse_flags_with_absl()\n+\n+def remat_of_for_loop(nsteps, body, state, **kwargs):\n+ return jax.remat(lambda state: for_loop.for_loop(nsteps, body, state,\n+ **kwargs))(state)\n+\n+FOR_LOOP_IMPLS = [\n+ (for_loop.for_loop, 'for_loop'),\n+ (jax.jit(for_loop.for_loop, static_argnums=(0, 1)), 'jit_for_loop'),\n+ (remat_of_for_loop, 'remat_for_loop'),\n+]\n+\n+\n+def _for_loop_impls(f):\n+ return parameterized.named_parameters(\n+ dict(testcase_name=impl_name, for_impl=for_impl)\n+ for for_impl, impl_name in FOR_LOOP_IMPLS\n+ )(f)\n+\n+\n+class ForLoopTest(jtu.JaxTestCase):\n+\n+ @_for_loop_impls\n+ def test_for_loop_impl_trivial(self, for_impl):\n+ out = for_impl(5, lambda i, _: None, None)\n+ self.assertIsNone(out)\n+\n+ @_for_loop_impls\n+ def test_for_loop_can_write_to_ref(self, for_impl):\n+ def body(_, x_ref):\n+ x_ref[()] = jnp.float32(1.)\n+ out = for_impl(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_impl(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_impl(2, body3, jnp.float32(0.))\n+ self.assertEqual(out, 2.)\n+\n+ @_for_loop_impls\n+ def test_for_loop_can_write_to_multiple_refs(self, for_impl):\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_impl(1, body, (jnp.float32(0.), jnp.float32(0.)))\n+ self.assertEqual(x, 1.)\n+ self.assertEqual(y, 2.)\n+\n+ @_for_loop_impls\n+ def test_for_loop_can_read_from_ref(self, for_impl):\n+ def body(_, x_ref):\n+ x_ref[()] # pylint: disable=pointless-statement\n+ x = for_impl(1, body, jnp.float32(0.))\n+ self.assertEqual(x, 0.)\n+\n+ @_for_loop_impls\n+ def test_for_loop_can_read_from_and_write_to_ref(self, for_impl):\n+ def body(_, x_ref):\n+ x = x_ref[()]\n+ x_ref[()] = x + jnp.float32(1.)\n+ x = for_impl(5, body, jnp.float32(0.))\n+ self.assertEqual(x, 5.)\n+\n+ @_for_loop_impls\n+ def test_for_loop_can_read_from_and_write_to_refs(self, for_impl):\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_impl(5, body2, (0., 0.))\n+ self.assertEqual(x, 5.)\n+ self.assertEqual(y, 5.)\n+\n+ @_for_loop_impls\n+ def test_for_loop_can_read_from_and_write_to_ref_slice(self, for_impl):\n+ def body(i, x_ref):\n+ x = x_ref[i]\n+ x_ref[i] = x + jnp.float32(1.)\n+ x = for_impl(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_impl(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+ @_for_loop_impls\n+ def test_for_loop_can_implement_cumsum(self, for_impl):\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_impl(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+\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+def for_body_noop(i, refs):\n+ pass\n+noop_ref = 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\": \"_f={}_nsteps={}_impl={}\".format(\n+ for_body_name, nsteps, impl_name),\n+ \"f\": for_body, \"body_shapes\": body_shapes,\n+ \"ref\": ref, \"n\": nsteps, \"for_impl\": for_impl}\n+ for for_impl, impl_name in FOR_LOOP_IMPLS\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, f, ref, body_shapes, n, for_impl):\n+ for_ = for_impl\n+ rng = self.rng()\n+\n+ args = [rng.randn(*s) for s in body_shapes]\n+\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+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\n+ for_body_name, nsteps, impl_name),\n+ \"f\": for_body, \"body_shapes\": body_shapes,\n+ \"ref\": ref, \"n\": nsteps, \"for_impl\": for_impl}\n+ for for_impl, impl_name in FOR_LOOP_IMPLS\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, f, ref, body_shapes, n, for_impl):\n+ for_ = for_impl\n+ rng = self.rng()\n+\n+ args = [rng.randn(*s) for s in body_shapes]\n+\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)\n+\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+\n+ def loss(A):\n+ def step(x, _):\n+ return jnp.matmul(A, x), None\n+ init_x = jnp.zeros(A.shape[-1:])\n+ last_x, _ = for_loop.scan(step, init_x, jnp.arange(10))\n+ return jnp.sum(last_x)\n+\n+ A = jnp.zeros((3, 3))\n+ # The second DUS was unnecessarily replicating A across time.\n+ # We check XLA because _scan_impl is \"underneath\" the jaxpr language.\n+ s = str(jax.xla_computation(jax.grad(loss))(A).as_hlo_text())\n+ assert s.count(\"dynamic-update-slice(\") < 2\n+\n+ @_for_loop_impls\n+ def test_for_loop_fixpoint_correctly_identifies_loop_varying_residuals(\n+ self, for_impl):\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_impl(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+ def body2(_, refs):\n+ # Here we use `i_ref` as a loop counter\n+ a_ref, b_ref, c_ref, i_ref = refs\n+ i = i_ref[()]\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+ i_ref[()] = i + 1\n+\n+ def g(a, b):\n+ c = jnp.zeros_like(a)\n+ _, b, c, _ = for_impl(5, body2, (a, b, c, 0))\n+ return b, c\n+ a = jnp.arange(5.) + 1.\n+ b = 1.\n+ _, g_lin = jax.linearize(f, a, b)\n+ expected_tangents = g_lin(a, b)\n+ _, actual_tangents = jax.jvp(g, (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+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\n+ for_body_name, nsteps, impl_name),\n+ \"f\": for_body, \"body_shapes\": body_shapes,\n+ \"ref\": ref, \"n\": nsteps, \"for_impl\": for_impl}\n+ for for_impl, impl_name in FOR_LOOP_IMPLS\n+ for for_body_name, for_body, ref, body_shapes, nsteps in [\n+ (\"noop\", for_body_noop, noop_ref, [(4,), (4,)], 4),\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_grad(self, f, ref, body_shapes, n, for_impl):\n+ for_ = for_impl\n+ rng = self.rng()\n+\n+ args = [rng.randn(*s) for s in body_shapes]\n+\n+ tol = {np.float64: 1e-12, np.float32: 1e-4}\n+ ans = jax.grad(lambda args: for_( n, f, args)[1].sum())(args)\n+ ans_discharged = jax.grad(\n+ lambda args: for_reference(n, f, args)[1].sum())(args)\n+ expected = jax.grad(lambda args: ref(*args)[1].sum())(args)\n+ self.assertAllClose(ans, ans_discharged, check_dtypes=True, rtol=tol,\n+ atol=tol)\n+ self.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\n+ jtu.check_grads(lambda *args: for_(n, f, args)[1].sum(), args, order=3,\n+ rtol=7e-3, atol=1e-2)\n+\n+if __name__ == '__main__':\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -108,24 +108,6 @@ SCAN_IMPLS_WITH_FOR = [\n(scan_with_remat_for, 'for_loop_remat'),\n]\n-def remat_of_for_loop(nsteps, body, state, **kwargs):\n- return jax.remat(lambda state: for_loop.for_loop(nsteps, body, state,\n- **kwargs))(state)\n-\n-FOR_LOOP_IMPLS = [\n- (for_loop.for_loop, 'for_loop'),\n- (jax.jit(for_loop.for_loop, static_argnums=(0, 1)), 'jit_for_loop'),\n- (remat_of_for_loop, 'remat_for_loop'),\n-]\n-\n-\n-def _for_loop_impls(f):\n- return parameterized.named_parameters(\n- dict(testcase_name=impl_name, for_impl=for_impl)\n- for for_impl, impl_name in FOR_LOOP_IMPLS\n- )(f)\n-\n-\ndef while_loop_new_checkpoint(cond_fun, body_fun, init_val):\nreturn new_checkpoint(partial(lax.while_loop, cond_fun, body_fun))(init_val)\n@@ -2592,322 +2574,5 @@ class LaxControlFlowTest(jtu.JaxTestCase):\njax.grad(f)(1.) # doesn't crash\n-class ForLoopTest(jtu.JaxTestCase):\n-\n- @_for_loop_impls\n- def test_for_loop_impl_trivial(self, for_impl):\n- out = for_impl(5, lambda i, _: None, None)\n- self.assertEqual(out, None)\n-\n- @_for_loop_impls\n- def test_for_loop_can_write_to_ref(self, for_impl):\n- def body(_, x_ref):\n- x_ref[()] = jnp.float32(1.)\n- out = for_impl(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_impl(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_impl(2, body3, jnp.float32(0.))\n- self.assertEqual(out, 2.)\n-\n- @_for_loop_impls\n- def test_for_loop_can_write_to_multiple_refs(self, for_impl):\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_impl(1, body, (jnp.float32(0.), jnp.float32(0.)))\n- self.assertEqual(x, 1.)\n- self.assertEqual(y, 2.)\n-\n- @_for_loop_impls\n- def test_for_loop_can_read_from_ref(self, for_impl):\n- def body(_, x_ref):\n- x_ref[()]\n- x = for_impl(1, body, jnp.float32(0.))\n- self.assertEqual(x, 0.)\n-\n- @_for_loop_impls\n- def test_for_loop_can_read_from_and_write_to_ref(self, for_impl):\n- def body(_, x_ref):\n- x = x_ref[()]\n- x_ref[()] = x + jnp.float32(1.)\n- x = for_impl(5, body, jnp.float32(0.))\n- self.assertEqual(x, 5.)\n-\n- @_for_loop_impls\n- def test_for_loop_can_read_from_and_write_to_refs(self, for_impl):\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_impl(5, body2, (0., 0.))\n- self.assertEqual(x, 5.)\n- self.assertEqual(y, 5.)\n-\n- @_for_loop_impls\n- def test_for_loop_can_read_from_and_write_to_ref_slice(self, for_impl):\n- def body(i, x_ref):\n- x = x_ref[i]\n- x_ref[i] = x + jnp.float32(1.)\n- x = for_impl(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_impl(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- @_for_loop_impls\n- def test_for_loop_can_implement_cumsum(self, for_impl):\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_impl(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-\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-def for_body_noop(i, refs):\n- pass\n-noop_ref = 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\": \"_f={}_nsteps={}_impl={}\".format(\n- for_body_name, nsteps, impl_name),\n- \"f\": for_body, \"body_shapes\": body_shapes,\n- \"ref\": ref, \"n\": nsteps, \"for_impl\": for_impl}\n- for for_impl, impl_name in FOR_LOOP_IMPLS\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, f, ref, body_shapes, n, for_impl):\n- for_ = for_impl\n- rng = self.rng()\n-\n- args = [rng.randn(*s) for s in body_shapes]\n-\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- @parameterized.named_parameters(\n- {\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\n- for_body_name, nsteps, impl_name),\n- \"f\": for_body, \"body_shapes\": body_shapes,\n- \"ref\": ref, \"n\": nsteps, \"for_impl\": for_impl}\n- for for_impl, impl_name in FOR_LOOP_IMPLS\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, f, ref, body_shapes, n, for_impl):\n- for_ = for_impl\n- rng = self.rng()\n-\n- args = [rng.randn(*s) for s in body_shapes]\n-\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)\n-\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-\n- def loss(A):\n- def step(x, i):\n- return jnp.matmul(A, x), None\n- init_x = jnp.zeros(A.shape[-1:])\n- last_x, _ = for_loop.scan(step, init_x, jnp.arange(10))\n- return jnp.sum(last_x)\n-\n- A = jnp.zeros((3, 3))\n- # The second DUS was unnecessarily replicating A across time.\n- # We check XLA because _scan_impl is \"underneath\" the jaxpr language.\n- s = str(jax.xla_computation(jax.grad(loss))(A).as_hlo_text())\n- assert s.count(\"dynamic-update-slice(\") < 2\n-\n- @_for_loop_impls\n- def test_for_loop_fixpoint_correctly_identifies_loop_varying_residuals(\n- self, for_impl):\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_impl(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- def body2(_, refs):\n- # Here we use `i_ref` as a loop counter\n- a_ref, b_ref, c_ref, i_ref = refs\n- i = i_ref[()]\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- i_ref[()] = i + 1\n-\n- def g(a, b):\n- c = jnp.zeros_like(a)\n- _, b, c, _ = for_impl(5, body2, (a, b, c, 0))\n- return b, c\n- a = jnp.arange(5.) + 1.\n- b = 1.\n- _, g_lin = jax.linearize(f, a, b)\n- expected_tangents = g_lin(a, b)\n- _, actual_tangents = jax.jvp(g, (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- @parameterized.named_parameters(\n- {\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\n- for_body_name, nsteps, impl_name),\n- \"f\": for_body, \"body_shapes\": body_shapes,\n- \"ref\": ref, \"n\": nsteps, \"for_impl\": for_impl}\n- for for_impl, impl_name in FOR_LOOP_IMPLS\n- for for_body_name, for_body, ref, body_shapes, nsteps in [\n- (\"noop\", for_body_noop, noop_ref, [(4,), (4,)], 4),\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_grad(self, f, ref, body_shapes, n, for_impl):\n- for_ = for_impl\n- rng = self.rng()\n-\n- args = [rng.randn(*s) for s in body_shapes]\n-\n- tol = {np.float64: 1e-12, np.float32: 1e-4}\n- ans = jax.grad(lambda args: for_( n, f, args)[1].sum())(args)\n- ans_discharged = jax.grad(\n- lambda args: for_reference(n, f, args)[1].sum())(args)\n- expected = jax.grad(lambda args: ref(*args)[1].sum())(args)\n- self.assertAllClose(ans, ans_discharged, check_dtypes=True, rtol=tol,\n- atol=tol)\n- self.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\n- jtu.check_grads(lambda *args: for_(n, f, args)[1].sum(), args, order=3,\n- rtol=7e-3, atol=1e-2)\n-\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Split for_loop_test out of lax_control_flow_test
PiperOrigin-RevId: 473848277 |
260,510 | 13.09.2022 09:26:32 | 25,200 | dc4922fd0827ba0f27c7c04ab3ff50b8fa8c4fab | Bump shards on for_loop_test | [
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -914,9 +914,9 @@ jax_test(\nname = \"for_loop_test\",\nsrcs = [\"for_loop_test.py\"],\nshard_count = {\n- \"cpu\": 10,\n- \"gpu\": 10,\n- \"tpu\": 10,\n+ \"cpu\": 20,\n+ \"gpu\": 20,\n+ \"tpu\": 20,\n},\n)\n"
}
] | Python | Apache License 2.0 | google/jax | Bump shards on for_loop_test
PiperOrigin-RevId: 474038276 |
260,510 | 13.09.2022 12:33:40 | 25,200 | ad326b99daa5ddcab314818095da380f5afaca02 | Use cases_from_list to subsample enumerated cases in for_loop_test | [
{
"change_type": "MODIFY",
"old_path": "tests/BUILD",
"new_path": "tests/BUILD",
"diff": "@@ -914,9 +914,9 @@ jax_test(\nname = \"for_loop_test\",\nsrcs = [\"for_loop_test.py\"],\nshard_count = {\n- \"cpu\": 20,\n- \"gpu\": 20,\n- \"tpu\": 20,\n+ \"cpu\": 10,\n+ \"gpu\": 10,\n+ \"tpu\": 10,\n},\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/for_loop_test.py",
"new_path": "tests/for_loop_test.py",
"diff": "@@ -196,7 +196,7 @@ for_reference = for_loop.discharged_for_loop\nclass ForLoopTransformationTest(jtu.JaxTestCase):\n- @parameterized.named_parameters(\n+ @parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\nfor_body_name, nsteps, impl_name),\n\"f\": for_body, \"body_shapes\": body_shapes,\n@@ -210,7 +210,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\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+ ]))\ndef test_for_jvp(self, f, ref, body_shapes, n, for_impl):\nfor_ = for_impl\nrng = self.rng()\n@@ -225,7 +225,7 @@ 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- @parameterized.named_parameters(\n+ @parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\nfor_body_name, nsteps, impl_name),\n\"f\": for_body, \"body_shapes\": body_shapes,\n@@ -239,7 +239,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\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+ ]))\ndef test_for_linearize(self, f, ref, body_shapes, n, for_impl):\nfor_ = for_impl\nrng = self.rng()\n@@ -328,7 +328,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nnp.testing.assert_allclose(actual_tangents[0], expected_tangents[0])\nnp.testing.assert_allclose(actual_tangents[1], expected_tangents[1])\n- @parameterized.named_parameters(\n+ @parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\nfor_body_name, nsteps, impl_name),\n\"f\": for_body, \"body_shapes\": body_shapes,\n@@ -343,7 +343,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\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+ ]))\ndef test_for_grad(self, f, ref, body_shapes, n, for_impl):\nfor_ = for_impl\nrng = self.rng()\n"
}
] | Python | Apache License 2.0 | google/jax | Use cases_from_list to subsample enumerated cases in for_loop_test
PiperOrigin-RevId: 474093596 |
260,510 | 02.09.2022 10:11:58 | 25,200 | f26f1e8afcdebc4ded7932fa5928c10a216344ac | Add support for closing over `Ref`s in nested for loops | [
{
"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, Generic, List, Optional, Sequence, Set, Tuple, TypeVar\n+from typing import Any, Callable, Generic, List, Optional, Sequence, Set, Tuple, TypeVar, Union\nfrom jax import core\nfrom jax import lax\n@@ -70,21 +70,23 @@ for_p.multiple_results = True\n### Tracing utilities\ndef _hoist_consts_to_refs(jaxpr: core.Jaxpr) -> core.Jaxpr:\n- num_consts = len(jaxpr.constvars)\n+ all_const_avals = [var.aval for var in jaxpr.constvars]\n+ is_const_ref = [isinstance(var.aval, ShapedArrayRef) for var in\n+ jaxpr.constvars]\n+ const_avals, const_ref_avals = partition_list(is_const_ref, all_const_avals)\n+ const_avals = [ShapedArrayRef(aval.shape, aval.dtype) for aval in const_avals] # pytype: disable=attribute-error\n+ merged_const_avals = merge_lists(is_const_ref, const_avals, const_ref_avals)\n+ i_aval, *arg_avals = [var.aval for var in jaxpr.invars]\n+ in_avals = [i_aval, *merged_const_avals, *arg_avals]\n+ num_consts = len(merged_const_avals)\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.\ndef _hoist(i, *consts_args):\n- const_refs, args = split_list(consts_args, [num_consts])\n+ all_consts, args = split_list(consts_args, [num_consts])\n+ consts, const_refs = partition_list(is_const_ref, all_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+ consts = map(lambda x: ref_get(x, ()), consts)\n+ all_consts = merge_lists(is_const_ref, consts, const_refs)\n+ return core.eval_jaxpr(jaxpr, all_consts, i, *args)\nhoisted_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(\nlu.wrap_init(_hoist), in_avals)\nassert not consts, \"All consts should have been converted to refs\"\n@@ -105,7 +107,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,\n+def for_loop(nsteps: Union[int, Sequence[int]],\n+ 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@@ -138,6 +141,16 @@ def for_loop(nsteps: int, body: Callable[[Array, Ref[S]], None], init_state: S,\nReturns:\nA Pytree of values representing the output of the for loop.\n\"\"\"\n+ if isinstance(nsteps, int):\n+ nsteps = [nsteps]\n+ if len(nsteps) > 1:\n+ outer_step, *rest_steps = nsteps\n+ def wrapped_body(i, refs):\n+ vals = tree_map(lambda ref: state.ref_get(ref, ()), refs)\n+ vals = for_loop(rest_steps, partial(body, i), vals)\n+ tree_map(lambda ref, val: state.ref_set(ref, (), val), refs, vals)\n+ return for_loop(outer_step, wrapped_body, init_state)\n+ nsteps, = nsteps\nflat_state, state_tree = tree_flatten(init_state)\nstate_avals = map(val_to_ref_aval, flat_state)\nidx_aval = core.ShapedArray((), jnp.dtype(\"int32\"))\n@@ -229,9 +242,27 @@ def _get_ref_state_effects(jaxpr: core.Jaxpr) -> List[Set[StateEffect]]:\nif isinstance(eff, (ReadEffect, WriteEffect, AccumEffect))\nand eff.ref_aval is v.aval} for v in jaxpr.invars]\n-@for_p.def_abstract_eval\n+@for_p.def_effectful_abstract_eval\ndef _for_abstract_eval(*avals, jaxpr, **__):\n- return list(avals)\n+ # Find out for each of the `Ref`s in our jaxpr what effects they have.\n+ jaxpr_aval_effects = _get_ref_state_effects(jaxpr)[1:]\n+ aval_effects = [set(eff.replace(ref_aval=aval) for eff in effs) for aval, effs\n+ in zip(avals, jaxpr_aval_effects)\n+ if isinstance(aval, ShapedArrayRef)]\n+ nonlocal_state_effects = core.join_effects(*aval_effects)\n+ return list(avals), nonlocal_state_effects\n+\n+@state.register_discharge_rule(for_p)\n+def _for_discharge_rule(in_avals, *args: Any, jaxpr: core.Jaxpr,\n+ reverse: bool, which_linear: Sequence[bool],\n+ nsteps: int\n+ ) -> Tuple[Sequence[Optional[Any]], Sequence[Any]]:\n+ out_vals = for_p.bind(*args, jaxpr=jaxpr, reverse=reverse,\n+ which_linear=which_linear, nsteps=nsteps)\n+ new_invals = []\n+ for aval, out_val in zip(in_avals, out_vals):\n+ new_invals.append(out_val if isinstance(aval, ShapedArrayRef) else None)\n+ return new_invals, out_vals\ndef _for_impl(*args, jaxpr, nsteps, reverse, which_linear):\ndel which_linear\n@@ -388,10 +419,10 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\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+ jaxpr_known_resout, jaxpr_unknown_resin_, uk_out, inst_out, 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+ # # `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@@ -443,6 +474,10 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\nloop_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_and_known = map(operator.and_, used_refs, map(operator.not_, in_unknowns))\n+ tracers = [trace.instantiate_const(t) if u_and_k else t for t, u_and_k # type: ignore\n+ in zip(tracers, used_and_known)]\n+ _, known_used = partition_list(used_refs, used_and_known)\n_, used_tracers = partition_list(used_refs, tracers)\n_, used_which_linear = partition_list(used_refs, which_linear)\nwhich_linear_unknown = (False,) * num_res + tuple(used_which_linear)\n@@ -455,13 +490,16 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\nname_stack = source_info_util.current_name_stack()[len(trace.name_stack):]\nsource = source_info_util.current().replace(name_stack=name_stack)\n+ assert len(unknown_inputs) == len(res_ref_unknown_outputs)\n+ assert len(unknown_inputs) == len(jaxpr_unknown.invars) - 1\neqn = pe.new_eqn_recipe(unknown_inputs, res_ref_unknown_outputs,\nfor_p, dict(jaxpr=jaxpr_unknown, nsteps=nsteps,\nreverse=reverse,\nwhich_linear=which_linear_unknown),\ncore.no_effects, source)\n+ for t in res_ref_unknown_outputs: t.recipe = eqn\n_, unknown_outputs = split_list(res_ref_unknown_outputs, [num_res])\n- for t in unknown_outputs: t.recipe = eqn\n+ unknown_outputs, _ = partition_list(known_used, unknown_outputs)\nreturn merge_lists(in_unknowns, known_outputs, unknown_outputs)\npe.custom_partial_eval_rules[for_p] = _for_partial_eval\n@@ -479,9 +517,10 @@ def _for_partial_eval_custom(saveable, in_unknowns, in_inst, eqn):\ninvars=discharged_jaxpr.constvars + discharged_jaxpr.invars,\nconstvars=[])\nin_unknowns, in_inst = list(in_unknowns), list(in_inst)\n+ out_unknowns, out_inst = in_unknowns, in_inst\nfor _ in range(num_inputs):\njaxpr_in_unknowns = [False] * len(discharged_consts) + [False, *in_unknowns]\n- _, _, out_unknowns, inst_out, _, = pe.partial_eval_jaxpr_custom(\n+ _, _, out_unknowns, out_inst, _, = pe.partial_eval_jaxpr_custom(\ndischarged_jaxpr, jaxpr_in_unknowns, True,\nensure_out_unknowns=in_unknowns, ensure_out_inst=True,\nsaveable=saveable)\n@@ -490,7 +529,7 @@ def _for_partial_eval_custom(saveable, in_unknowns, in_inst, eqn):\nbreak\nin_unknowns = map(operator.or_, in_unknowns, out_unknowns)\nelse:\n- raise Exception(\"Invalid fixpoint\")\n+ if num_inputs > 0: raise Exception(\"Invalid fixpoint\")\ndel out_unknowns # Redundant since it's the same as `in_unknowns`\nnew_inst = [x for x, inst in zip(eqn.invars, in_inst)\nif type(x) is core.Var and not inst]\n@@ -557,18 +596,18 @@ def _for_partial_eval_custom(saveable, in_unknowns, in_inst, eqn):\ndef staged(*res_and_refs):\nout_flat = for_p.bind(*res_and_refs, **params_staged)\n_, ans = split_list(out_flat, [num_res])\n- _, ans = partition_list(inst_out, ans)\n+ _, ans = partition_list(out_inst, ans)\nreturn ans\ncall_jaxpr_, _, call_jaxpr_consts = pe.trace_to_jaxpr_dynamic(\nstaged, [v.aval for v in [*resvars, *eqn.invars]])\nassert len(jaxpr_staged.invars) - 1 == len(call_jaxpr_.invars)\ncall_jaxpr = core.ClosedJaxpr(call_jaxpr_, call_jaxpr_consts)\n- _, outvars = partition_list(inst_out, eqn.outvars)\n+ _, outvars = partition_list(out_inst, eqn.outvars)\neqn_staged = pe.new_jaxpr_eqn([*resvars, *eqn.invars], outvars,\ncore.closed_call_p, dict(call_jaxpr=call_jaxpr),\ncall_jaxpr.effects, eqn.source_info)\nnew_vars = [*new_inst, *resvars]\n- return eqn_known, eqn_staged, in_unknowns, inst_out, new_vars\n+ return eqn_known, eqn_staged, in_unknowns, out_inst, new_vars\npe.partial_eval_jaxpr_custom_rules[for_p] = _for_partial_eval_custom\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/__init__.py",
"new_path": "jax/_src/state/__init__.py",
"diff": "@@ -17,4 +17,4 @@ from jax._src.state.types import (ShapedArrayRef, ReadEffect, WriteEffect,\nfrom jax._src.state.primitives import (ref_get, ref_set, ref_swap,\nref_addupdate, get_p, swap_p,\naddupdate_p)\n-from jax._src.state.discharge import discharge_state\n+from jax._src.state.discharge import discharge_state, register_discharge_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/discharge.py",
"new_path": "jax/_src/state/discharge.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Module for discharging state primitives.\"\"\"\n+from __future__ import annotations\n+import dataclasses\nfrom functools import partial\n-from typing import Any, Dict, List, Sequence, Tuple\n+\n+from typing import Any, Dict, List, Optional, Sequence, Tuple\n+from typing_extensions import Protocol\nimport numpy as np\n@@ -21,9 +25,10 @@ from jax import core\nfrom jax import lax\nfrom jax import linear_util as lu\nfrom jax.interpreters import partial_eval as pe\n-from jax._src.util import safe_map, safe_zip\n+from jax._src.util import safe_map, safe_zip, split_list\n-from jax._src.state.types import ShapedArrayRef\n+from jax._src.state.types import (ShapedArrayRef, ReadEffect, WriteEffect,\n+ AccumEffect)\nfrom jax._src.state.primitives import get_p, swap_p, addupdate_p\n## JAX utilities\n@@ -36,7 +41,7 @@ zip, unsafe_zip = safe_zip, zip\n# Let's say we have a jaxpr that takes in `Ref`s and outputs regular JAX values\n# (`Ref`s should never be outputs from jaxprs). We'd like to convert that jaxpr\n# into a \"pure\" jaxpr that takes in and outputs values and no longer has the\n-# `StateEffect` effect.\n+# `Read/Write/Accum` effects.\ndef discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any]\n) -> Tuple[core.Jaxpr, List[Any]]:\n@@ -48,6 +53,81 @@ def discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any]\nnew_jaxpr, _ , new_consts = pe.trace_to_jaxpr_dynamic(eval_jaxpr, in_avals)\nreturn new_jaxpr, new_consts\n+@dataclasses.dataclass\n+class Environment:\n+ env: Dict[core.Var, Any]\n+\n+ def read(self, v: core.Atom) -> Any:\n+ if type(v) is core.Literal:\n+ return v.val\n+ assert isinstance(v, core.Var)\n+ return self.env[v]\n+\n+ def write(self, v: core.Var, val: Any) -> None:\n+ self.env[v] = val\n+\n+class DischargeRule(Protocol):\n+\n+ def __call__(self, in_avals: Sequence[core.AbstractValue], *args: Any,\n+ **params: Any) -> Tuple[Sequence[Optional[Any]], Sequence[Any]]:\n+ ...\n+\n+_discharge_rules: dict[core.Primitive, DischargeRule] = {}\n+\n+def register_discharge_rule(prim: core.Primitive):\n+ def register(f: DischargeRule):\n+ _discharge_rules[prim] = f\n+ return register\n+\n+def _has_refs(eqn: core.JaxprEqn):\n+ return any(isinstance(v.aval, ShapedArrayRef) for v in eqn.invars)\n+\n+def _eval_jaxpr_discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any],\n+ *args: Any):\n+ env = Environment({})\n+\n+ map(env.write, jaxpr.constvars, consts)\n+ # Here some args may correspond to `Ref` avals but they'll be treated like\n+ # regular values in this interpreter.\n+ map(env.write, jaxpr.invars, args)\n+\n+ for eqn in jaxpr.eqns:\n+ if _has_refs(eqn):\n+ if eqn.primitive not in _discharge_rules:\n+ raise NotImplementedError(\"No state discharge rule implemented for \"\n+ f\"primitive: {eqn.primitive}\")\n+ invals = map(env.read, eqn.invars)\n+ in_avals = [v.aval for v in eqn.invars]\n+ new_invals, ans = _discharge_rules[eqn.primitive](in_avals, *invals,\n+ **eqn.params)\n+ for new_inval, invar in zip(new_invals, eqn.invars):\n+ if new_inval is not None:\n+ env.write(invar, new_inval)\n+ else:\n+ # Default primitive rule, similar to `core.eval_jaxpr`. Note that here\n+ # we assume any higher-order primitives inside of the jaxpr are *not*\n+ # stateful.\n+ subfuns, bind_params = eqn.primitive.get_bind_params(eqn.params)\n+ ans = eqn.primitive.bind(*subfuns, *map(env.read, eqn.invars),\n+ **bind_params)\n+ if eqn.primitive.multiple_results:\n+ map(env.write, eqn.outvars, ans)\n+ else:\n+ env.write(eqn.outvars[0], ans)\n+ # By convention, we return the outputs of the jaxpr first and then the final\n+ # values of the `Ref`s. Callers to this function should be able to split\n+ # them up by looking at `len(jaxpr.outvars)`.\n+ out_vals = map(env.read, jaxpr.outvars)\n+ ref_vals = map(\n+ env.read, [v for v in jaxpr.invars if type(v.aval) is ShapedArrayRef])\n+ return out_vals + ref_vals\n+\n+@register_discharge_rule(get_p)\n+def _get_discharge_rule(_: Sequence[core.AbstractValue], x, *non_slice_idx,\n+ indexed_dims: Sequence[bool]):\n+ y = _get_discharge(x, non_slice_idx, indexed_dims)\n+ return (None,) * (len(non_slice_idx) + 1), y\n+\ndef _get_discharge(x, idx, indexed_dims):\nif not any(indexed_dims):\nreturn x\n@@ -73,6 +153,14 @@ def _indexer(idx, indexed_dims):\nassert next(idx_, None) is None\nreturn indexer\n+@register_discharge_rule(swap_p)\n+def _swap_discharge_rule(_: Sequence[core.AbstractValue], x, val, *non_slice_idx,\n+ indexed_dims: Sequence[bool]):\n+ if not any(indexed_dims):\n+ z, x_new = x, val\n+ z, x_new = _swap_discharge(x, val, non_slice_idx, indexed_dims)\n+ return (x_new, None) + (None,) * len(non_slice_idx), z\n+\ndef _swap_discharge(x, val, idx, indexed_dims):\nif not any(indexed_dims):\nz, x_new = x, val\n@@ -84,6 +172,12 @@ def _swap_discharge(x, val, idx, indexed_dims):\nx_new = _prepend_scatter(x, idx, indexed_dims, val)\nreturn z, x_new\n+@register_discharge_rule(addupdate_p)\n+def _addupdate_discharge_rule(_: Sequence[core.AbstractValue], x, val,\n+ *non_slice_idx, indexed_dims: Sequence[bool]):\n+ ans = _addupdate_discharge(x, val, non_slice_idx, indexed_dims)\n+ return (ans, None) + (None,) * len(non_slice_idx), []\n+\ndef _addupdate_discharge(x, val, idx, indexed_dims):\nif not any(indexed_dims):\nreturn x + val\n@@ -110,63 +204,20 @@ def _dynamic_update_index(x, idx, val, indexed_dims):\nsizes = [1 if b else size for b, size in zip(indexed_dims, x.shape)]\nreturn lax.dynamic_update_slice(x, val.reshape(sizes), starts)\n-def _eval_jaxpr_discharge_state(jaxpr: core.Jaxpr, consts: Sequence[Any],\n- *args: Any):\n- env: Dict[core.Var, Any] = {}\n-\n- def read(v: core.Atom) -> Any:\n- if type(v) is core.Literal:\n- return v.val\n- assert isinstance(v, core.Var)\n- return env[v]\n-\n- def write(v: core.Var, val: Any) -> None:\n- env[v] = val\n-\n- map(write, jaxpr.constvars, consts)\n- # Here some args may correspond to `Ref` avals but they'll be treated like\n- # regular values in this interpreter.\n- map(write, jaxpr.invars, args)\n-\n- for eqn in jaxpr.eqns:\n- in_vals = map(read, eqn.invars)\n- if eqn.primitive is get_p:\n- # `y <- x[i]` becomes `y = ds x i`\n- x, *idx = in_vals\n- y = _get_discharge(x, idx, eqn.params['indexed_dims'])\n- write(eqn.outvars[0], y)\n- elif eqn.primitive is swap_p:\n- # `z, x[i] <- x[i], val` becomes:\n- # z = ds x i\n- # x = dus x i val\n- assert isinstance(eqn.invars[0], core.Var)\n- x, val, *idx = in_vals\n- z, x_new = _swap_discharge(x, val, idx, eqn.params['indexed_dims'])\n- write(eqn.outvars[0], z)\n- write(eqn.invars[0] , x_new)\n- elif eqn.primitive is addupdate_p:\n- # `x[i] += val` becomes:\n- # y = ds x i\n- # z = y + val\n- # x = dus x i z\n- assert isinstance(eqn.invars[0], core.Var)\n- x, val, *idx = in_vals\n- ans = _addupdate_discharge(x, val, idx, eqn.params['indexed_dims'])\n- write(eqn.invars[0], ans)\n- else:\n- # Default primitive rule, similar to `core.eval_jaxpr`. Note that here\n- # we assume any higher-order primitives inside of the jaxpr are *not*\n- # stateful.\n- subfuns, bind_params = eqn.primitive.get_bind_params(eqn.params)\n- ans = eqn.primitive.bind(*subfuns, *map(read, eqn.invars), **bind_params)\n- if eqn.primitive.multiple_results:\n- map(write, eqn.outvars, ans)\n- else:\n- write(eqn.outvars[0], ans)\n- # By convention, we return the outputs of the jaxpr first and then the final\n- # values of the `Ref`s. Callers to this function should be able to split\n- # them up by looking at `len(jaxpr.outvars)`.\n- out_vals = map(read, jaxpr.outvars)\n- ref_vals = map(\n- read, [v for v in jaxpr.invars if type(v.aval) is ShapedArrayRef])\n- return out_vals + ref_vals\n+@register_discharge_rule(core.closed_call_p)\n+def _closed_call_discharge_rule(in_avals: Sequence[core.AbstractValue], *args,\n+ call_jaxpr: core.ClosedJaxpr):\n+ jaxpr, consts = call_jaxpr.jaxpr, call_jaxpr.consts\n+ num_outs = len(jaxpr.outvars)\n+ discharged_jaxpr, discharged_consts = discharge_state(jaxpr, consts)\n+ discharged_closed_jaxpr = core.ClosedJaxpr(discharged_jaxpr,\n+ discharged_consts)\n+ fun = lu.wrap_init(core.jaxpr_as_fun(discharged_closed_jaxpr))\n+ out_and_ref_vals = core.closed_call_p.bind(fun, *args,\n+ call_jaxpr=discharged_closed_jaxpr)\n+ out_vals, ref_vals = split_list(out_and_ref_vals, [num_outs])\n+ ref_vals_iter = iter(ref_vals)\n+ new_invals = tuple(next(ref_vals_iter) if isinstance(aval, ShapedArrayRef)\n+ else None for aval in in_avals)\n+ assert next(ref_vals_iter, None) is None\n+ return new_invals, out_vals\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/state/types.py",
"new_path": "jax/_src/state/types.py",
"diff": "@@ -57,6 +57,11 @@ class RefEffect:\ndef __hash__(self):\nreturn hash((self.__class__, self.ref_aval))\n+ def replace(self, *, ref_aval: Optional[ShapedArrayRef] = None):\n+ if ref_aval is None:\n+ ref_aval = self.ref_aval\n+ return self.__class__(ref_aval)\n+\nclass ReadEffect(RefEffect):\ndef __str__(self):\nreturn f\"Read<{self.ref_aval}>\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/for_loop_test.py",
"new_path": "tests/for_loop_test.py",
"diff": "@@ -19,9 +19,10 @@ from absl.testing import parameterized\nimport numpy as np\nimport jax\n+from jax import random\nfrom jax._src import test_util as jtu\n-import jax.numpy as jnp\nfrom jax._src.lax.control_flow import for_loop\n+import jax.numpy as jnp\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -30,10 +31,19 @@ def remat_of_for_loop(nsteps, body, state, **kwargs):\nreturn jax.remat(lambda state: for_loop.for_loop(nsteps, body, state,\n**kwargs))(state)\n+def nested_for_loop(nsteps, body, state, **kwargs):\n+ def outer_body(_, refs):\n+ def inner_body(i, _):\n+ body(i, refs)\n+ return\n+ for_loop.for_loop(nsteps, inner_body, ())\n+ return for_loop.for_loop(1, outer_body, state)\n+\nFOR_LOOP_IMPLS = [\n(for_loop.for_loop, 'for_loop'),\n(jax.jit(for_loop.for_loop, static_argnums=(0, 1)), 'jit_for_loop'),\n(remat_of_for_loop, 'remat_for_loop'),\n+ (nested_for_loop, 'nested_for_loop'),\n]\n@@ -361,5 +371,23 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\njtu.check_grads(lambda *args: for_(n, f, args)[1].sum(), args, order=3,\nrtol=7e-3, atol=1e-2)\n+ def test_grad_of_triple_nested_for_loop(self):\n+\n+ func = lambda x: jnp.sin(x) + 1.\n+\n+ @jax.jit\n+ def f(x):\n+ out = jnp.zeros_like(x)\n+ def body(i, j, k, refs):\n+ x_ref, out_ref = refs\n+ y = func(x_ref[i, j, k])\n+ out_ref[i, j, k] += y\n+ return for_loop.for_loop(x.shape, body, (x, out))[1].sum()\n+\n+ x = random.normal(random.PRNGKey(0), (5, 4, 3))\n+ ref = lambda x: jax.vmap(jax.vmap(jax.vmap(func)))(x).sum()\n+ self.assertAllClose(f(x), ref(x))\n+ jtu.check_grads(f, (x,), order=2, atol=0.1, rtol=0.1)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -1723,7 +1723,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\n@parameterized.named_parameters(\n{\"testcase_name\": \"_impl={}\".format(scan_name), \"scan\": scan_impl}\n- for scan_impl, scan_name in SCAN_IMPLS)\n+ for scan_impl, scan_name in SCAN_IMPLS_WITH_FOR)\ndef testIssue711(self, scan):\n# Tests reverse-mode differentiation through a scan for which the scanned\n# function also involves reverse-mode differentiation.\n"
}
] | Python | Apache License 2.0 | google/jax | Add support for closing over `Ref`s in nested for loops |
260,335 | 13.09.2022 16:06:33 | 25,200 | 49a6034fa38fd213860e92b468551fd51dd6e6e0 | [dynamic-shapes] enable basic einsum support, following jax2tf shape polys | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -2908,10 +2908,11 @@ def einsum(*operands, out=None, optimize='optimal', precision=None,\nfor d in np.shape(op) if not core.is_constant_dim(d)\n}\nif not non_constant_dim_types:\n- einsum_contract_path_fn = opt_einsum.contract_path\n+ contract_path = opt_einsum.contract_path\nelse:\n- einsum_contract_path_fn = _polymorphic_einsum_contract_path_handlers[next(iter(non_constant_dim_types))]\n- operands, contractions = einsum_contract_path_fn(\n+ ty = next(iter(non_constant_dim_types))\n+ contract_path = _poly_einsum_handlers.get(ty, _default_poly_einsum_handler)\n+ operands, contractions = contract_path(\n*operands, einsum_call=True, use_blas=True, optimize=optimize)\ncontractions = tuple((a, frozenset(b), c) for a, b, c, *_ in contractions)\n@@ -2919,7 +2920,16 @@ def einsum(*operands, out=None, optimize='optimal', precision=None,\n# Enable other modules to override einsum_contact_path.\n# Indexed by the type of the non constant dimension\n-_polymorphic_einsum_contract_path_handlers = {} # type: ignore\n+_poly_einsum_handlers = {} # type: ignore\n+\n+def _default_poly_einsum_handler(*operands, **kwargs):\n+ dummy = collections.namedtuple('dummy', ['shape', 'dtype'])\n+ dummies = [dummy(tuple(d if type(d) is int else 8 for d in x.shape), x.dtype)\n+ if hasattr(x, 'dtype') else x for x in operands]\n+ mapping = {id(d): i for i, d in enumerate(dummies)}\n+ out_dummies, contractions = opt_einsum.contract_path(*dummies, **kwargs)\n+ contract_operands = [operands[mapping[id(d)]] for d in out_dummies]\n+ return contract_operands, contractions\n@_wraps(np.einsum_path)\ndef einsum_path(subscripts, *operands, optimize='greedy'):\n@@ -3027,7 +3037,7 @@ def _einsum(operands: Sequence,\n# NOTE(mattjj): this can fail non-deterministically in python3, maybe\n# due to opt_einsum\n- assert _all(\n+ assert jax.config.jax_dynamic_shapes or _all(\nname in lhs_names and name in rhs_names and\nlhs.shape[lhs_names.index(name)] == rhs.shape[rhs_names.index(name)]\nfor name in contracted_names)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -518,7 +518,7 @@ def _einsum_contract_path(*operands, **kwargs):\ncontract_operands.append(operands[idx[0]])\nreturn contract_operands, contractions\n-lax_numpy._polymorphic_einsum_contract_path_handlers[_DimPolynomial] = _einsum_contract_path\n+lax_numpy._poly_einsum_handlers[_DimPolynomial] = _einsum_contract_path\n# A JAX primitive with no array arguments but with a dimension parameter\n# that is a DimPoly. The value of the primitive is the value of the dimension.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/dynamic_api_test.py",
"new_path": "tests/dynamic_api_test.py",
"diff": "@@ -1327,6 +1327,33 @@ class DynamicShapeTest(jtu.JaxTestCase):\nh, = e.outvars\nself.assertEqual(h.aval.shape, (b, 1))\n+ def test_einsum_basic(self):\n+ x = jnp.arange(20.).reshape(4, 5)\n+\n+ def f(x):\n+ return jnp.einsum('ij,kj->ik', x, x)\n+\n+ jaxpr = jax.make_jaxpr(f, abstracted_axes=('n', 'm'))(x).jaxpr\n+ # { lambda ; a:i32[] b:i32[] c:f32[a,b]. let\n+ # d:f32[a,a] = xla_call[\n+ # call_jaxpr={ lambda ; e:i32[] f:i32[] g:f32[e,f] h:f32[e,f]. let\n+ # i:f32[e,e] = dot_general[\n+ # dimension_numbers=(((1,), (1,)), ((), ()))\n+ # precision=None\n+ # preferred_element_type=None\n+ # ] g h\n+ # in (i,) }\n+ # name=_einsum\n+ # ] a b c c\n+ # in (d,) }\n+ self.assertLen(jaxpr.invars, 3)\n+ a, b, c = jaxpr.invars\n+ self.assertEqual(c.aval.shape[0], a)\n+ self.assertLen(jaxpr.eqns, 1)\n+ self.assertLen(jaxpr.eqns[0].outvars, 1)\n+ d, = jaxpr.eqns[0].outvars\n+ self.assertEqual(d.aval.shape, (a, a))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [dynamic-shapes] enable basic einsum support, following jax2tf shape polys |
260,335 | 13.09.2022 17:51:16 | 25,200 | 71b0968f703a6fa873b3abdfe6f9b2f01f0507b0 | skip some for_loop test cases on gpu due to flakey timeouts | [
{
"change_type": "MODIFY",
"old_path": "tests/for_loop_test.py",
"new_path": "tests/for_loop_test.py",
"diff": "@@ -221,6 +221,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\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+ @jtu.skip_on_devices(\"gpu\") # TODO(mattjj,sharadmv): timeouts?\ndef test_for_jvp(self, f, ref, body_shapes, n, for_impl):\nfor_ = for_impl\nrng = self.rng()\n@@ -233,7 +234,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nexpected = jax.jvp(ref, args, args)\nself.assertAllClose(ans, ans_discharged, check_dtypes=True, rtol=tol, atol=tol)\nself.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\n- jtu.check_grads(partial(for_, n, f), (args,), order=3, modes=[\"fwd\"])\n+ jtu.check_grads(partial(for_, n, f), (args,), order=2, modes=[\"fwd\"])\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_f={}_nsteps={}_impl={}\".format(\n@@ -250,6 +251,7 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\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+ @jtu.skip_on_devices(\"gpu\") # TODO(mattjj,sharadmv): timeouts?\ndef test_for_linearize(self, f, ref, body_shapes, n, for_impl):\nfor_ = for_impl\nrng = self.rng()\n@@ -354,6 +356,8 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\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+ @jtu.skip_on_devices(\"gpu\") # TODO(mattjj,sharadmv): timeouts?\n+ @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\ndef test_for_grad(self, f, ref, body_shapes, n, for_impl):\nfor_ = for_impl\nrng = self.rng()\n@@ -368,9 +372,10 @@ class ForLoopTransformationTest(jtu.JaxTestCase):\nself.assertAllClose(ans, ans_discharged, check_dtypes=True, rtol=tol,\natol=tol)\nself.assertAllClose(ans, expected, check_dtypes=True, rtol=tol, atol=tol)\n- jtu.check_grads(lambda *args: for_(n, f, args)[1].sum(), args, order=3,\n+ jtu.check_grads(lambda *args: for_(n, f, args)[1].sum(), args, order=2,\nrtol=7e-3, atol=1e-2)\n+ @jtu.skip_on_devices(\"gpu\") # TODO(mattjj,sharadmv): timeouts?\ndef test_grad_of_triple_nested_for_loop(self):\nfunc = lambda x: jnp.sin(x) + 1.\n"
}
] | Python | Apache License 2.0 | google/jax | skip some for_loop test cases on gpu due to flakey timeouts
PiperOrigin-RevId: 474168747 |
260,510 | 14.09.2022 08:51:37 | 25,200 | 08c5753ee2a37ba2ea46a09564c99386c2dc639d | Implement unrolling 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": "@@ -109,7 +109,7 @@ def val_to_ref_aval(x) -> ShapedArrayRef:\ndef for_loop(nsteps: Union[int, Sequence[int]],\nbody: Callable[[Array, Ref[S]], None], init_state: S,\n- *, reverse: bool = False) -> S:\n+ *, reverse: bool = False, unroll: int = 1) -> 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@@ -138,18 +138,24 @@ def for_loop(nsteps: Union[int, Sequence[int]],\nnot return anything.\ninit_state: A Pytree of JAX-compatible values used to initialize the `Ref`s\nthat will be passed into the for loop body.\n+ unroll: A positive int specifying, in the underlying operation of the\n+ `for` primitive, how many iterations to unroll within a single iteration\n+ of a loop. Higher values may speed up execution time at the cost of longer\n+ compilation time.\nReturns:\nA Pytree of values representing the output of the for loop.\n\"\"\"\n+ if unroll < 1:\n+ raise ValueError(\"`unroll` must be a positive integer.\")\nif isinstance(nsteps, int):\nnsteps = [nsteps]\nif len(nsteps) > 1:\nouter_step, *rest_steps = nsteps\ndef wrapped_body(i, refs):\nvals = tree_map(lambda ref: state.ref_get(ref, ()), refs)\n- vals = for_loop(rest_steps, partial(body, i), vals)\n+ vals = for_loop(rest_steps, partial(body, i), vals, unroll=unroll)\ntree_map(lambda ref, val: state.ref_set(ref, (), val), refs, vals)\n- return for_loop(outer_step, wrapped_body, init_state)\n+ return for_loop(outer_step, wrapped_body, init_state, unroll=unroll)\nnsteps, = nsteps\nflat_state, state_tree = tree_flatten(init_state)\nstate_avals = map(val_to_ref_aval, flat_state)\n@@ -162,7 +168,8 @@ def for_loop(nsteps: Union[int, Sequence[int]],\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=reverse, which_linear=which_linear)\n+ reverse=reverse, which_linear=which_linear,\n+ unroll=unroll)\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):]\n@@ -178,10 +185,10 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\nlength: Optional[int] = None,\nreverse: bool = False,\nunroll: int = 1) -> Tuple[Carry, Y]:\n- if unroll != 1:\n- raise NotImplementedError(\"Unroll not implemented\")\nif not callable(f):\nraise TypeError(\"scan: f argument should be a callable.\")\n+ if unroll < 1:\n+ raise ValueError(\"`unroll` must be a positive integer.\")\nxs_flat, xs_tree = tree_flatten(xs)\ntry:\n@@ -233,7 +240,8 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\ntree_map(lambda c_ref, c: ref_set(c_ref, (), c), carry_refs, carry)\ntree_map(lambda y_ref, y: ref_set(y_ref, (i,), y), ys_refs, y)\nassert isinstance(length, int)\n- init, _, ys = for_loop(length, for_body, (init, xs, ys), reverse=reverse)\n+ init, _, ys = for_loop(length, for_body, (init, xs, ys), reverse=reverse,\n+ unroll=unroll)\nreturn init, ys\ndef _get_ref_state_effects(jaxpr: core.Jaxpr) -> List[Set[StateEffect]]:\n@@ -255,33 +263,50 @@ def _for_abstract_eval(*avals, jaxpr, **__):\n@state.register_discharge_rule(for_p)\ndef _for_discharge_rule(in_avals, *args: Any, jaxpr: core.Jaxpr,\nreverse: bool, which_linear: Sequence[bool],\n- nsteps: int\n+ nsteps: int, unroll: int\n) -> Tuple[Sequence[Optional[Any]], Sequence[Any]]:\nout_vals = for_p.bind(*args, jaxpr=jaxpr, reverse=reverse,\n- which_linear=which_linear, nsteps=nsteps)\n+ which_linear=which_linear, nsteps=nsteps,\n+ unroll=unroll)\nnew_invals = []\nfor aval, out_val in zip(in_avals, out_vals):\nnew_invals.append(out_val if isinstance(aval, ShapedArrayRef) else None)\nreturn new_invals, out_vals\n-def _for_impl(*args, jaxpr, nsteps, reverse, which_linear):\n+def _for_impl(*args, jaxpr, nsteps, reverse, which_linear, unroll):\ndel which_linear\ndischarged_jaxpr, consts = discharge_state(jaxpr, ())\n+ def body(i, state):\n+ i_ = nsteps - i - 1 if reverse else i\n+ return core.eval_jaxpr(discharged_jaxpr, consts, i_, *state)\n+ return _for_impl_unrolled(body, nsteps, unroll, *args)\n+\n+def _for_impl_unrolled(body, nsteps, unroll, *args):\n+ remainder = nsteps % unroll\n+ i = jnp.int32(0)\n+ state = list(args)\n+\n+ for _ in range(remainder):\n+ state = body(i, state)\n+ i = i + 1\n+\ndef cond(carry):\ni, _ = carry\nreturn i < nsteps\n- def body(carry):\n+ def while_body(carry):\ni, 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+ for _ in range(unroll):\n+ state = body(i, state)\n+ i = i + 1\n+ return i, state\n+ _, state = lax.while_loop(cond, while_body, (i, state))\nreturn state\n+\nmlir.register_lowering(for_p, mlir.lower_fun(_for_impl, multiple_results=True))\nfor_p.def_impl(partial(xla.apply_primitive, for_p))\ndef _for_vmap(axis_size, axis_name, main_type, args, dims, *,\n- jaxpr, nsteps, reverse, which_linear):\n+ jaxpr, nsteps, reverse, which_linear, unroll):\ninit_batched = [d is not batching.not_mapped for d in dims]\ndischarged_jaxpr, body_consts = discharge_state(jaxpr, ())\nbatched = init_batched\n@@ -303,11 +328,13 @@ def _for_vmap(axis_size, axis_name, main_type, args, dims, *,\naxis_name=axis_name, main_type=main_type)\nbatched_jaxpr, () = batched_jaxpr_.jaxpr, batched_jaxpr_.consts # TODO consts\nout_flat = for_p.bind(*args, jaxpr=batched_jaxpr, nsteps=nsteps,\n- reverse=reverse, which_linear=which_linear)\n+ reverse=reverse, which_linear=which_linear,\n+ unroll=unroll)\nreturn out_flat, [0 if b else batching.not_mapped for b in batched]\nbatching.axis_primitive_batchers[for_p] = _for_vmap\n-def _for_jvp(primals, tangents, *, jaxpr, nsteps, reverse, which_linear):\n+def _for_jvp(primals, tangents, *, jaxpr, nsteps, reverse, which_linear,\n+ unroll):\nnonzero_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@@ -334,7 +361,7 @@ def _for_jvp(primals, tangents, *, jaxpr, nsteps, reverse, which_linear):\njvp_which_linear = which_linear + (True,) * len(tangents)\nout_flat = for_p.bind(*primals, *tangents, jaxpr=jvp_jaxpr,\nnsteps=nsteps, reverse=reverse,\n- which_linear=jvp_which_linear)\n+ which_linear=jvp_which_linear, unroll=unroll)\n# `out_flat` includes constant inputs into the `for_loop` which are converted\n# into outputs as well. We don't care about these in AD so we throw them out.\nout_primals, out_tangents = split_list(out_flat, [len(primals)])\n@@ -388,7 +415,8 @@ def _loop_invariant_outputs(jaxpr: core.Jaxpr) -> List[bool]:\ndef _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\njaxpr: core.Jaxpr, nsteps: int, reverse: bool,\n- which_linear: Tuple[bool, ...]) -> List[pe.JaxprTracer]:\n+ which_linear: Tuple[bool, ...],\n+ unroll: int) -> List[pe.JaxprTracer]:\nnum_inputs = len(tracers)\nassert num_inputs == len(jaxpr.invars) - 1\nin_unknowns = [not t.pval.is_known() for t in tracers]\n@@ -454,7 +482,8 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\n# necessarily okay for general partial eval.\njaxpr_known_which_linear = (False,) * len(jaxpr_known_args)\nout_flat = for_p.bind(*jaxpr_known_args, jaxpr=jaxpr_known, nsteps=nsteps,\n- reverse=reverse, which_linear=jaxpr_known_which_linear)\n+ reverse=reverse, which_linear=jaxpr_known_which_linear,\n+ unroll=unroll)\nknown_outputs, residuals = split_list(out_flat, [len(known_tracers)])\nresiduals = map(trace.new_instantiated_const, residuals)\n@@ -495,7 +524,8 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\neqn = pe.new_eqn_recipe(unknown_inputs, res_ref_unknown_outputs,\nfor_p, dict(jaxpr=jaxpr_unknown, nsteps=nsteps,\nreverse=reverse,\n- which_linear=which_linear_unknown),\n+ which_linear=which_linear_unknown,\n+ unroll=unroll),\ncore.no_effects, source)\nfor t in res_ref_unknown_outputs: t.recipe = eqn\n_, unknown_outputs = split_list(res_ref_unknown_outputs, [num_res])\n@@ -504,8 +534,8 @@ def _for_partial_eval(trace: pe.JaxprTrace, *tracers: pe.JaxprTracer,\npe.custom_partial_eval_rules[for_p] = _for_partial_eval\ndef _for_partial_eval_custom(saveable, in_unknowns, in_inst, eqn):\n- jaxpr, nsteps, reverse, which_linear = split_dict(\n- eqn.params, [\"jaxpr\", \"nsteps\", \"reverse\", \"which_linear\"])\n+ jaxpr, nsteps, reverse, which_linear, unroll = split_dict(\n+ eqn.params, [\"jaxpr\", \"nsteps\", \"reverse\", \"which_linear\", \"unroll\"])\nnum_inputs = len(eqn.invars)\n# We first need to run a fixpoint to determine which of the `Ref`s are unknown\n# after running the for loop. However, the jaxpr has no outputs. Instead, we\n@@ -576,7 +606,8 @@ def _for_partial_eval_custom(saveable, in_unknowns, in_inst, eqn):\njaxpr_known_args = [*known_vals, *empty_res]\njaxpr_known_which_linear = (False,) * len(jaxpr_known_args)\nreturn for_p.bind(*jaxpr_known_args, jaxpr=jaxpr_known, nsteps=nsteps,\n- reverse=reverse, which_linear=jaxpr_known_which_linear)\n+ reverse=reverse, which_linear=jaxpr_known_which_linear,\n+ unroll=unroll)\ncall_jaxpr_, _, call_jaxpr_consts = pe.trace_to_jaxpr_dynamic(\nknown, [v.aval for v in known_invars])\ncall_jaxpr = core.ClosedJaxpr(call_jaxpr_, call_jaxpr_consts)\n@@ -590,7 +621,8 @@ def _for_partial_eval_custom(saveable, in_unknowns, in_inst, eqn):\nwhich_linear_unknown = (False,) * num_res + tuple(which_linear)\nparams_staged = dict(eqn.params, jaxpr=jaxpr_staged, reverse=reverse,\nnsteps=nsteps,\n- which_linear=which_linear_unknown)\n+ which_linear=which_linear_unknown,\n+ unroll=unroll)\n@lu.wrap_init\ndef staged(*res_and_refs):\n@@ -689,7 +721,7 @@ def transpose_jaxpr(jaxpr: core.Jaxpr, which_linear: List[bool]) -> core.Jaxpr:\nlu.wrap_init(trans), [v.aval for v in jaxpr.invars])\nreturn jaxpr_trans\n-def _for_transpose(in_cts, *args, jaxpr, nsteps, reverse, which_linear):\n+def _for_transpose(in_cts, *args, jaxpr, nsteps, reverse, which_linear, unroll):\n# if any in_ct is nonzero, we definitely want it in args_ (and the\n# corresponding x in args could be an undefined primal, but doesnt have to be)\n# for non-res stuff:\n@@ -722,7 +754,8 @@ def _for_transpose(in_cts, *args, jaxpr, nsteps, reverse, which_linear):\nassert len(args_) == len(jaxpr_transpose.invars) - 1\nall_outs = for_p.bind(*args_, jaxpr=jaxpr_transpose, nsteps=nsteps,\nreverse=not reverse,\n- which_linear=tuple(which_linear_transpose))\n+ which_linear=tuple(which_linear_transpose),\n+ unroll=unroll)\nct_outs = [ct if ad.is_undefined_primal(x) else None\nfor x, ct in zip(args, all_outs)]\nreturn ct_outs\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/for_loop_test.py",
"new_path": "tests/for_loop_test.py",
"diff": "@@ -44,6 +44,7 @@ FOR_LOOP_IMPLS = [\n(jax.jit(for_loop.for_loop, static_argnums=(0, 1)), 'jit_for_loop'),\n(remat_of_for_loop, 'remat_for_loop'),\n(nested_for_loop, 'nested_for_loop'),\n+ (partial(for_loop.for_loop, unroll=3), 'unrolled_for_loop'),\n]\n"
}
] | Python | Apache License 2.0 | google/jax | Implement unrolling for for_loop |
260,674 | 15.09.2022 11:45:33 | 25,200 | 311f85e8b0ab2b7aedf5f8686423594e4c8a5ee8 | Adjust tolerance for lu test in preparation for XLA switch from cublas to cublasLt | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"diff": "@@ -827,7 +827,12 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ncustom_numeric(\ndtypes=[np.float32, np.complex64], devices=(\"cpu\", \"gpu\"),\ntol=1e-5),\n- custom_numeric(dtypes=[np.float64, np.complex128], tol=1e-13),\n+ custom_numeric(\n+ dtypes=[np.float64, np.complex128],\n+ modes=(\"eager\", \"graph\"),\n+ tol=1e-13),\n+ custom_numeric(\n+ dtypes=[np.float64, np.complex128], modes=(\"compiled\"), tol=1e-14),\ncustom_numeric(\ncustom_assert=custom_assert,\ndescription=(\"May return different, but also correct, results when \"\n"
}
] | Python | Apache License 2.0 | google/jax | Adjust tolerance for lu test in preparation for XLA switch from cublas to cublasLt
PiperOrigin-RevId: 474618770 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.